Merge origin/main into smlib
Conflicts, both sides kept:
- Cargo.lock, crates/engine/Cargo.toml: smlib's solidcraft-profile/solidcraft-step beside
main's solidcraft-testkit and the image comment.
- crates/doc/src/{eval,eval_more,name_lookup,project}.rs: smlib's "a stored name finds its
face or edge or asks to reselect" logic kept; main's long-name quoting (#8673) applied to
its messages. Main's split-name hole re-lookup (#10699) dropped: names here never report
split.
- crates/doc/src/lib.rs: both exports, with main's revolve_extent_for_handle.
- crates/engine/src/cmd/silhouette.rs: main's outline()/Silhouette split, on the fallible
world_state().
- crates/engine/src/cmd/sketch_project_tests.rs: both tests.
- crates/ui-egui/src/{canvas,hole_refs}.rs: main's anchor_item/model_text on
open_meshing::session_world.
- crates/ui-egui/src/preview.rs: main's cut_tint switch around smlib's kept-surface ghost
filter; both helpers and both tests.
Seam fixes: FeatureKind::Repair in main's kind_key/type_name_to_kind_key (#10748); main's
new world_state() callers in ui-egui use session_world or unwrap in tests; a sketch test's
Spline gets nurbs: None.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SdcgEu4Lr3moCCisdZShKz
This commit is contained in:
commit
7f2af7f729
322 files changed
+19209
-1225
No files matched your search
@@ -1,6 +1,7 @@
|
||||
# While a new geometry kernel is evaluated, new issues, pull requests and discussions about kernel
|
||||
# work are labelled `kernel-paused` for a maintainer to answer (CONTRIBUTING.md, "Kernel work is
|
||||
# paused"). The logic is in scripts/kernel-paused/ (tested in ci.yml).
|
||||
# While a new geometry kernel is evaluated, new issues and discussions about kernel work, and new
|
||||
# pull requests that change the kernel directories, are labelled `kernel-paused` for a maintainer to
|
||||
# answer (CONTRIBUTING.md, "Kernel work is paused"). The logic is in scripts/kernel-paused/ (tested
|
||||
# in ci.yml).
|
||||
name: Kernel paused
|
||||
|
||||
on:
|
||||
|
||||
+123
@@ -647,6 +647,129 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments.
|
||||
| assets/icons/ui/design/svg/model/print_face.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
|
||||
| assets/locales/fi.json | SolidCraft contributors | Original Finnish translation of SolidCraft's English catalog, AI-assisted (Claude Code) clean-room from the English and not yet reviewed line by line by a native speaker; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/icons/ui/design/svg/model/plane_axis_point.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 |
|
||||
| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 |
|
||||
|
||||
## Code adapted from sibling projects
|
||||
|
||||
|
||||
+7
-6
@@ -19,12 +19,13 @@ Questions, ideas or want to say what you're working on? Join the [Discord](https
|
||||
|
||||
## Kernel work is paused
|
||||
|
||||
We're evaluating a new geometry kernel. Until that's decided, please don't open issues, pull
|
||||
requests or discussions about kernel work: booleans, fillets, chamfers, shell, offsets, sweeps and
|
||||
lofts, threads and holes, STEP/IGES import and export, tessellation, or anything else that changes
|
||||
`crates/kernel/`. The pinned issue on the tracker explains it. New ones get the `kernel-paused`
|
||||
label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes and data loss
|
||||
are still taken as issues, and everything outside the kernel carries on as normal.
|
||||
We're moving to a new geometry kernel. Until that's done, please don't open pull requests that
|
||||
change `crates/kernel/`, `crates/geom/` or `vendor/truck*`, or issues and discussions about kernel
|
||||
work: booleans, fillets, chamfers, shell, offsets, sweeps and lofts, threads and holes, STEP/IGES
|
||||
import and export, or tessellation. The pinned issue on the tracker explains it. New ones get the
|
||||
`kernel-paused` label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes
|
||||
and data loss are still taken as issues. Pull requests outside those directories carry on as normal,
|
||||
including the dialogs and tools for these features.
|
||||
|
||||
## Get it running (about 10 minutes on a fast machine)
|
||||
|
||||
|
||||
Generated
+7
@@ -4204,6 +4204,7 @@ dependencies = [
|
||||
"solidcraft-geom",
|
||||
"solidcraft-kernel",
|
||||
"solidcraft-profile",
|
||||
"solidcraft-testkit",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
]
|
||||
@@ -4230,6 +4231,7 @@ dependencies = [
|
||||
name = "solidcraft-mcp"
|
||||
version = "0.29.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"serde_json",
|
||||
"solidcraft-engine",
|
||||
"solidcraft-gpu",
|
||||
@@ -4254,6 +4256,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"solidcraft-geom",
|
||||
"web-time",
|
||||
"weezl",
|
||||
]
|
||||
|
||||
@@ -4298,6 +4301,10 @@ dependencies = [
|
||||
"solidcraft-profile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-testkit"
|
||||
version = "0.29.0"
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-ui-egui"
|
||||
version = "0.29.0"
|
||||
|
||||
@@ -31,6 +31,8 @@ solidcraft-space-mouse = { path = "crates/space-mouse" }
|
||||
solidcraft-mcp = { path = "crates/mcp" }
|
||||
solidcraft-derive = { path = "crates/derive" }
|
||||
solidcraft-3dx-client = { path = "crates/threedx-client" }
|
||||
# test tooling: a dev-dependency only (xtask/src/layers.rs)
|
||||
solidcraft-testkit = { path = "crates/testkit" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "مقطع",
|
||||
"Section (optional)": "المقطع (اختياري)",
|
||||
"Section position": "موضع المقطع",
|
||||
"Sections": "المقاطع",
|
||||
"Sections (one sketch each)": "المقاطع (رسم واحد لكل منها)",
|
||||
"Select Other": "تحديد آخر",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "تحديد آخر: أبقِ الزر الأيسر ثابتًا على النموذج (أو انقر بالزر الأيمن › تحديد آخر…) لعرض كل ما تحت المؤشر؛ وانقر مرة أخرى في الموضع نفسه لتحديد العنصر التالي هناك. انقر نقرًا مزدوجًا بالزر الأوسط للانتقال إلى العرض الرئيسي (التفضيلات › التنقل).",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "إظهار العرض المفكك",
|
||||
"cmd.expr_evaluate": "تقييم تعبير",
|
||||
"cmd.face_delete": "حذف وجه",
|
||||
"cmd.file.export_3mf": "تصدير 3MF",
|
||||
"cmd.file.export_obj": "تصدير OBJ",
|
||||
"cmd.file.export_step": "تصدير STEP",
|
||||
"cmd.file.export_stl": "تصدير STL",
|
||||
"cmd.file.export_urdf": "تصدير URDF",
|
||||
"cmd.file_export": "تصدير",
|
||||
"cmd.file_insert_mesh": "إدراج شبكة",
|
||||
"cmd.file_insert_step": "إدراج STEP",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "تفعيل ألوان المكوّنات",
|
||||
"cmd.inspect_colored_components_disable": "تعطيل ألوان المكوّنات",
|
||||
"cmd.inspect_compare": "مقارنة الأجسام",
|
||||
"cmd.inspect_compare_picture": "مقارنة بصورة مرجعية",
|
||||
"cmd.inspect_continuity": "تحليل الاستمرارية",
|
||||
"cmd.inspect_curvature_comb": "تحليل مشط الانحناء",
|
||||
"cmd.inspect_curvature_map": "تحليل خريطة الانحناء",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "تحرير سحابة النقاط",
|
||||
"cmd.pointcloud_insert": "إدراج سحابة نقاط",
|
||||
"cmd.pointcloud_list": "سحب النقاط",
|
||||
"cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير",
|
||||
"cmd.render.result.discard": "تجاهل نتيجة التصيير",
|
||||
"cmd.render.result.select": "تحديد نتيجة التصيير",
|
||||
"cmd.render_aging_describe": "تقادم السطح بالطبقات",
|
||||
"cmd.render_backends": "محركات التصيير",
|
||||
"cmd.render_batch": "تصيير كل اللقطات",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "أداة التنقل",
|
||||
"cmd.view_top": "العرض العلوي",
|
||||
"cmd.view_visual_style": "نمط العرض",
|
||||
"color.blue": "أزرق",
|
||||
"color.copy": "انقر لنسخ قيم اللون",
|
||||
"color.edit": "انقر لتعديل اللون",
|
||||
"color.gamma": "عرض قيم اللون في نطاق جاما 0-255",
|
||||
"color.green": "أخضر",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "أدخل #rrggbb أو #rrggbbaa؛ مع الخانات الست تبقى العتامة كما هي",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "عرض قيم اللون في النطاق الخطي 0-1",
|
||||
"color.recent": "الألوان الأخيرة",
|
||||
"color.recent_help": "تظهر هنا الألوان التي تختارها في أي حقل لون",
|
||||
"color.red": "أحمر",
|
||||
"color.saturation": "التشبع (بالمئة)",
|
||||
"color.saturation_value": "التشبع والقيمة",
|
||||
"color.selected": "اللون المحدد",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "اختر أجسامًا أو ميزات: الرسم ليس أيًّا منهما. كرّر منحنياته بأداة النمط أو المرآة داخل الرسم، أو ابثقه أولًا.",
|
||||
"dialog.select": "↖ تحديد",
|
||||
"dialog.selected_count": "↖ {count} محدد",
|
||||
"dialog.selection_constraint": "قيد {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · منحنى {id}",
|
||||
"dialog.selection_guidance": "حدد مُدخلًا لتغييره. انقر على العناصر المحددة لإزالتها؛ Ctrl/Cmd مع النقر يبدّل تحديدها أيضًا. راجع المعاينة ثم اضغط موافق.",
|
||||
"dialog.selection_midpoint": "نقطة المنتصف · {id}",
|
||||
"dialog.selection_profile": "{sketch} · المقطع {number}",
|
||||
"dialog.selection_step": "{step} من {total}: حدد {input}",
|
||||
"dialog.step": "الخطوة",
|
||||
"document.changed_on_disk": "تغيّر {name} على القرص",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "سحب بالزر الأيسر",
|
||||
"prefs.button_middle": "سحب بالزر الأوسط",
|
||||
"prefs.button_right": "سحب بالزر الأيمن",
|
||||
"prefs.carousel_next": "التالي",
|
||||
"prefs.carousel_previous": "السابق",
|
||||
"prefs.choose_font": "اختيار ملف خط…",
|
||||
"prefs.click": "نقر",
|
||||
"prefs.contact_shading": "تظليل التلامس الناعم",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "الأسطح المنحنية",
|
||||
"prefs.curves": "الأسطح المنحنية",
|
||||
"prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر",
|
||||
"prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا يُرسم سوى محيطها.",
|
||||
"prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة",
|
||||
"prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء",
|
||||
"prefs.dead_zone_note": "الشريط المخطط هو المنطقة الميتة: تُتجاهل الحركة داخلها.",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "الموضع",
|
||||
"prefs.prefer_free_sketch_points": "تفضيل نقاط الرسم القابلة للتحريك عند تداخل النقاط",
|
||||
"prefs.preview_choices": "معاينة اختياراتك",
|
||||
"prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة",
|
||||
"prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي.",
|
||||
"prefs.print_face_highlight": "إبراز وجه الطباعة",
|
||||
"prefs.print_face_highlight_tip": "مدى قوة تلوين وجه الطباعة للجسم ورسم حدوده في العرض. القيمة 0 % لا تُظهر أي إبراز.",
|
||||
"prefs.profile_active": "ملف التعريف النشط",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "اللون الأساسي · sRGB",
|
||||
"render.base_metallic": "النسبة المعدنية",
|
||||
"render.base_opaque_only": "يحافظ هذا المحرر على دلالات الجسم المعتم. استخدم عناصر التحكم الصريحة للزجاج من أجل النفاذ البصري.",
|
||||
"render.batch_all_shots": "كل اللقطات ({count})",
|
||||
"render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.",
|
||||
"render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.",
|
||||
"render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار",
|
||||
"render.bloom_enable": "توهج العرض",
|
||||
"render.bloom_help": "توهج إبداعي للإخراج فقط من الإضاءات الخطية الموجبة، يُنشر بثلاث تمريرات صندوقية مُطبّعة. نصف القطر ببكسلات الإخراج. يُضاف في ضوء العرض الخطي قبل sRGB؛ وليس عدسة ولا تأثيرًا حجميًا ولا تحسينًا للتقارب. يبقى EXR الخام دون تغيير.",
|
||||
"render.bloom_opaque": "يتطلب التوهج إخراجًا معتمًا. يُرفض PNG الشفاف بدل تسطيحه بصمت.",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "اختر مظهرًا من المظاهر أولًا",
|
||||
"render.chromatic_offset": "إزاحة لونية عند الحواف",
|
||||
"render.clear_stage": "إزالة المنصة المحفوظة",
|
||||
"render.compare_divider": "فاصل المقارنة",
|
||||
"render.compare_live": "حي",
|
||||
"render.compare_live_preview": "معاينة حية",
|
||||
"render.compare_render": "التصيير {number}",
|
||||
"render.compare_side": "التصيير {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}",
|
||||
"render.compare_swap": "تبديل",
|
||||
"render.copy_request": "نسخ JSON",
|
||||
"render.cpu_aa_help": "العيّنات المكانية: المزيد منها يحسّن الحواف ويزيد زمن التصيير.",
|
||||
"render.cpu_area_add": "إضافة ضوء مستطيل على CPU",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "تُعرض آخر صورة مكتملة؛ ولم يستبدلها تصيير أحدث.",
|
||||
"render.result_sequence": "نقطة التحقق",
|
||||
"render.result_title": "نتيجة التصيير",
|
||||
"render.results_choose": "النتائج المحتفظ بها",
|
||||
"render.results_label": "التصيير {number} · {shot} · {seconds} ث",
|
||||
"render.results_stale_label": "{result} [قديم]",
|
||||
"render.results_unnamed": "صورة",
|
||||
"render.return_design": "العودة إلى التصميم",
|
||||
"render.review_stale": "هذه المراجعة قديمة. حُلّها أو افحص مرة أخرى قبل التطبيق.",
|
||||
"render.ribbon_aging": "التقادم",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "الميزات",
|
||||
"ui.agent_chat_ctx_more": "+{n} أخرى",
|
||||
"ui.agent_chat_ctx_other": "أخرى",
|
||||
"ui.agent_chat_custom_heading": "نموذج مخصص",
|
||||
"ui.agent_chat_custom_hint": "أي برنامج يتحدث بروتوكول Agent Client Protocol عبر stdin وstdout. لا تشغّله أي صدفة أوامر.",
|
||||
"ui.agent_chat_denied": "مرفوض",
|
||||
"ui.agent_chat_deny": "رفض",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "الكل",
|
||||
"ui.agent_chat_mode_ask": "السؤال",
|
||||
"ui.agent_chat_mode_edits": "التعديلات",
|
||||
"ui.agent_chat_model_custom": "استخدام المخصص: {model}",
|
||||
"ui.agent_chat_model_no_tools": "لا يستطيع {model} استخدام أدوات SolidCraft، لذا يمكنه المحادثة فقط. اختر نموذجًا يدعم الأدوات.",
|
||||
"ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}",
|
||||
"ui.agent_chat_model_search": "البحث عن النماذج…",
|
||||
"ui.agent_chat_model_tip": "النموذج الذي يستخدمه الوكيل. يُحفظ اختيارك لهذا الوكيل.",
|
||||
"ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}",
|
||||
"ui.agent_chat_models_heading": "النماذج المتاحة",
|
||||
"ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…",
|
||||
"ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج",
|
||||
"ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج",
|
||||
"ui.agent_chat_new": "محادثة جديدة",
|
||||
"ui.agent_chat_new_confirm": "بدء محادثة جديدة؟ ستُمسح المحادثة الحالية.",
|
||||
"ui.agent_chat_next_picture": "الصورة التالية",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "في {name} تغييرات غير محفوظة، لذا أُدرج ملفه المحفوظ. احفظه، ثم استخدم تحديث الروابط لإدخال التغييرات.",
|
||||
"ui.insert_design.unsaved": "تغييرات غير محفوظة",
|
||||
"ui.inspect": "فحص",
|
||||
"ui.instances": "النسخ",
|
||||
"ui.intersect": "تقاطع",
|
||||
"ui.isolate": "عزل",
|
||||
"ui.join": "ضم",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "فتح التصميم المرتبط؟",
|
||||
"web.open_link_confirm": "توجد تغييرات غير محفوظة. هل تريد فتح التصميم المرتبط في تبويب جديد؟",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ اختيار · Enter / Tab إكمال · Esc إغلاق",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ اختيار · Enter يطبّق ما كتبته · Esc إغلاق",
|
||||
"⌘Enter continues on GitHub.": "⌘Enter يتابع في GitHub."
|
||||
}
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} ima nesačuvane promjene, pa je umetnuta njegova sačuvana datoteka. Sačuvajte ga, a zatim pokrenite Ažuriraj veze da unesete promjene.",
|
||||
"ui.insert_design.unsaved": "Nesačuvane promjene",
|
||||
"ui.inspect": "Pregledaj",
|
||||
"ui.instances": "Instance",
|
||||
"ui.intersect": "Presjek",
|
||||
"ui.isolate": "Izoluj",
|
||||
"ui.join": "Spoji",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} obsahuje neuložené změny, proto byl vložen jeho uložený soubor. Uložte jej a pak použijte Aktualizovat odkazy, aby se změny převzaly.",
|
||||
"ui.insert_design.unsaved": "Neuložené změny",
|
||||
"ui.inspect": "Analýza",
|
||||
"ui.instances": "Instance",
|
||||
"ui.intersect": "Průnik",
|
||||
"ui.isolate": "Izolovat",
|
||||
"ui.join": "Sjednotit",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} har ændringer, der ikke er gemt, så dens gemte fil blev indsat. Gem den, og kør derefter Opdatér forbindelser for at hente ændringerne.",
|
||||
"ui.insert_design.unsaved": "Ikke-gemte ændringer",
|
||||
"ui.inspect": "Inspicér",
|
||||
"ui.instances": "Forekomster",
|
||||
"ui.intersect": "Fællesvolumen",
|
||||
"ui.isolate": "Isolér",
|
||||
"ui.join": "Foren",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "Schnitt",
|
||||
"Section (optional)": "Abschnitt (optional)",
|
||||
"Section position": "Lage des Querschnitts",
|
||||
"Sections": "Querschnitte",
|
||||
"Sections (one sketch each)": "Querschnitte (je eine Skizze)",
|
||||
"Select Other": "Andere auswählen",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Anderes auswählen: Halten Sie die linke Taste ruhig auf dem Modell gedrückt (oder Rechtsklick › Anderes auswählen…), um alles unter dem Cursor aufzulisten; klicken Sie erneut an dieselbe Stelle, um das nächste Element dort auszuwählen. Doppelklick mit der mittleren Taste wechselt zur Startansicht (Einstellungen › Navigation).",
|
||||
@@ -934,6 +935,11 @@
|
||||
"cmd.explode_show": "Explosionsdarstellung anzeigen",
|
||||
"cmd.expr_evaluate": "Ausdruck auswerten",
|
||||
"cmd.face_delete": "Fläche löschen",
|
||||
"cmd.file.export_3mf": "Als 3MF exportieren",
|
||||
"cmd.file.export_obj": "Als OBJ exportieren",
|
||||
"cmd.file.export_step": "Als STEP exportieren",
|
||||
"cmd.file.export_stl": "Als STL exportieren",
|
||||
"cmd.file.export_urdf": "Als URDF exportieren",
|
||||
"cmd.file_export": "Exportieren",
|
||||
"cmd.file_insert_mesh": "Netz einfügen",
|
||||
"cmd.file_insert_step": "STEP einfügen",
|
||||
@@ -1041,6 +1047,9 @@
|
||||
"cmd.pointcloud_edit": "Punktwolke bearbeiten",
|
||||
"cmd.pointcloud_insert": "Punktwolke einfügen",
|
||||
"cmd.pointcloud_list": "Punktwolken",
|
||||
"cmd.render.compare.divider": "Render-Vergleichstrenner verschieben",
|
||||
"cmd.render.result.discard": "Renderergebnis verwerfen",
|
||||
"cmd.render.result.select": "Renderergebnis auswählen",
|
||||
"cmd.render_aging_describe": "Mehrschichtige Oberflächenalterung",
|
||||
"cmd.render_backends": "Render-Backends",
|
||||
"cmd.render_batch": "Alle Aufnahmen rendern",
|
||||
@@ -1288,9 +1297,11 @@
|
||||
"cmd.view_tool": "Navigationswerkzeug",
|
||||
"cmd.view_top": "Draufsicht",
|
||||
"cmd.view_visual_style": "Darstellungsstil",
|
||||
"color.blue": "Blau",
|
||||
"color.copy": "Klicken, um Farbwerte zu kopieren",
|
||||
"color.edit": "Klicken, um Farbe zu bearbeiten",
|
||||
"color.gamma": "Farbwerte im Gammaraum 0-255 anzeigen",
|
||||
"color.green": "Grün",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "#rrggbb oder #rrggbbaa eingeben; sechs Ziffern behalten die Deckkraft bei",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1298,6 +1309,7 @@
|
||||
"color.linear": "Farbwerte im linearen Raum 0-1 anzeigen",
|
||||
"color.recent": "Zuletzt verwendete Farben",
|
||||
"color.recent_help": "Farben, die Sie in einem beliebigen Farbfeld wählen, erscheinen hier",
|
||||
"color.red": "Rot",
|
||||
"color.saturation": "Sättigung (Prozent)",
|
||||
"color.saturation_value": "Sättigung und Wert",
|
||||
"color.selected": "Ausgewählte Farbe",
|
||||
@@ -1355,7 +1367,11 @@
|
||||
"dialog.pattern_sketch_not_object": "Körper oder Funktionen wählen: Eine Skizze ist keines von beiden. Ihre Kurven mit Muster oder Spiegeln in der Skizze wiederholen oder sie zuerst extrudieren.",
|
||||
"dialog.select": "↖ Auswählen",
|
||||
"dialog.selected_count": "↖ {count} ausgewählt",
|
||||
"dialog.selection_constraint": "Bedingung {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · Kurve {id}",
|
||||
"dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.",
|
||||
"dialog.selection_midpoint": "Mittelpunkt · {id}",
|
||||
"dialog.selection_profile": "{sketch} · Profil {number}",
|
||||
"dialog.selection_step": "{step} von {total}: {input} auswählen",
|
||||
"dialog.step": "Schritt",
|
||||
"document.changed_on_disk": "{name} wurde auf dem Datenträger geändert",
|
||||
@@ -2137,6 +2153,8 @@
|
||||
"prefs.button_left": "Ziehen mit der linken Maustaste",
|
||||
"prefs.button_middle": "Ziehen mit der mittleren Maustaste",
|
||||
"prefs.button_right": "Ziehen mit der rechten Maustaste",
|
||||
"prefs.carousel_next": "Weiter",
|
||||
"prefs.carousel_previous": "Zurück",
|
||||
"prefs.choose_font": "Schriftdatei auswählen…",
|
||||
"prefs.click": "Klicken",
|
||||
"prefs.contact_shading": "Weiche Kontaktschattierung",
|
||||
@@ -2149,6 +2167,8 @@
|
||||
"prefs.ctrl_cmd": "Strg / Cmd",
|
||||
"prefs.curved_surfaces": "Gekrümmte Flächen",
|
||||
"prefs.curves": "Gekrümmte Flächen",
|
||||
"prefs.cut_preview_tint": "Entferntes Material rot anzeigen",
|
||||
"prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.",
|
||||
"prefs.dark_parts_shading": "Form dunkler Teile erhalten",
|
||||
"prefs.dark_parts_shading_help": "Die Ansicht in linearem Licht mit sanftem Himmelslicht schattieren, damit dunkle Flächen einen Verlauf behalten statt schwarz zu werden",
|
||||
"prefs.dead_zone_note": "Der schraffierte Bereich kennzeichnet die Totzone. Bewegungen innerhalb dieses Bereichs werden ignoriert.",
|
||||
@@ -2266,6 +2286,8 @@
|
||||
"prefs.placement": "Platzierung",
|
||||
"prefs.prefer_free_sketch_points": "Bei überlappenden Punkten bewegliche Skizzenpunkte bevorzugen",
|
||||
"prefs.preview_choices": "Vorschau Ihrer Einstellungen",
|
||||
"prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben",
|
||||
"prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet.",
|
||||
"prefs.print_face_highlight": "Hervorhebung der Auflagefläche",
|
||||
"prefs.print_face_highlight_tip": "Wie stark die Auflagefläche eines Körpers in der Ansicht eingefärbt und umrandet wird. 0 % zeigt keine Hervorhebung.",
|
||||
"prefs.profile_active": "Aktives Profil",
|
||||
@@ -2563,6 +2585,10 @@
|
||||
"render.base_color": "Grundfarbe · sRGB",
|
||||
"render.base_metallic": "Metallanteil",
|
||||
"render.base_opaque_only": "Dieser Editor lässt Körper undurchsichtig. Für optische Transmission verwenden Sie die gesonderten Glaseinstellungen.",
|
||||
"render.batch_all_shots": "Alle Ansichten ({count})",
|
||||
"render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.",
|
||||
"render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.",
|
||||
"render.batch_status": "{running} läuft · {waiting} warten",
|
||||
"render.bloom_enable": "Darstellungs-Bloom",
|
||||
"render.bloom_help": "Kreativer Ausgabeglanz aus linearen Glanzlichtern mit drei normierten Durchläufen. Radius in Ausgabepixeln; Addition vor sRGB. Keine Linsen-, Volumen- oder Konvergenzsimulation. Das rohe EXR bleibt unverändert.",
|
||||
"render.bloom_opaque": "Bloom benötigt eine deckende Ausgabe. Transparentes PNG wird abgelehnt, nicht still abgeflacht.",
|
||||
@@ -2673,6 +2699,13 @@
|
||||
"render.choose_look": "Zuerst einen Look in der Bibliothek wählen",
|
||||
"render.chromatic_offset": "Chromatischer Kantenversatz",
|
||||
"render.clear_stage": "Remove saved stage",
|
||||
"render.compare_divider": "Vergleichstrenner",
|
||||
"render.compare_live": "Live",
|
||||
"render.compare_live_preview": "Live-Vorschau",
|
||||
"render.compare_render": "Render {number}",
|
||||
"render.compare_side": "Render {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}",
|
||||
"render.compare_swap": "Tauschen",
|
||||
"render.copy_request": "JSON kopieren",
|
||||
"render.cpu_aa_help": "Räumliche Samples: Mehr Samples verbessern die Kantenglättung, verlängern jedoch die Renderzeit.",
|
||||
"render.cpu_area_add": "Rechteckiges CPU-Flächenlicht hinzufügen",
|
||||
@@ -3422,6 +3455,10 @@
|
||||
"render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.",
|
||||
"render.result_sequence": "Prüfpunkt",
|
||||
"render.result_title": "Render-Ergebnis",
|
||||
"render.results_choose": "Behaltene Ergebnisse",
|
||||
"render.results_label": "Render {number} · {shot} · {seconds} s",
|
||||
"render.results_stale_label": "{result} [veraltet]",
|
||||
"render.results_unnamed": "Bild",
|
||||
"render.return_design": "Zurück zu Design",
|
||||
"render.review_stale": "Diese Prüfung ist veraltet. Lösen Sie sie auf oder prüfen Sie erneut, bevor Sie sie anwenden.",
|
||||
"render.ribbon_aging": "Alterung",
|
||||
@@ -4093,6 +4130,7 @@
|
||||
"ui.agent_chat_ctx_features": "Funktionen",
|
||||
"ui.agent_chat_ctx_more": "+{n} weitere",
|
||||
"ui.agent_chat_ctx_other": "Sonstiges",
|
||||
"ui.agent_chat_custom_heading": "Eigenes Modell",
|
||||
"ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.",
|
||||
"ui.agent_chat_denied": "Abgelehnt",
|
||||
"ui.agent_chat_deny": "Ablehnen",
|
||||
@@ -4136,8 +4174,16 @@
|
||||
"ui.agent_chat_mode_all": "Alles",
|
||||
"ui.agent_chat_mode_ask": "Fragen",
|
||||
"ui.agent_chat_mode_edits": "Ändern",
|
||||
"ui.agent_chat_model_custom": "Eigenes verwenden: {model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} kann die Werkzeuge von SolidCraft nicht verwenden und daher nur chatten. Wählen Sie ein Modell mit Werkzeugunterstützung.",
|
||||
"ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}",
|
||||
"ui.agent_chat_model_search": "Modelle suchen…",
|
||||
"ui.agent_chat_model_tip": "Das vom Agenten verwendete Modell. Ihre Auswahl wird für diesen Agenten gespeichert.",
|
||||
"ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}",
|
||||
"ui.agent_chat_models_heading": "Verfügbare Modelle",
|
||||
"ui.agent_chat_models_listing": "Modelle werden abgerufen…",
|
||||
"ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle",
|
||||
"ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste",
|
||||
"ui.agent_chat_new": "Neuer Chat",
|
||||
"ui.agent_chat_new_confirm": "Neuen Chat starten? Der aktuelle wird geleert.",
|
||||
"ui.agent_chat_next_picture": "Nächstes Bild",
|
||||
@@ -4716,6 +4762,7 @@
|
||||
"ui.insert_design.saved_file": "{name} hat ungespeicherte Änderungen, daher wurde die gespeicherte Datei eingefügt. Speichern Sie sie und wählen Sie dann Verknüpfungen aktualisieren, um die Änderungen zu übernehmen.",
|
||||
"ui.insert_design.unsaved": "Ungespeicherte Änderungen",
|
||||
"ui.inspect": "Prüfen",
|
||||
"ui.instances": "Instanzen",
|
||||
"ui.intersect": "Schnitt",
|
||||
"ui.isolate": "Isolieren",
|
||||
"ui.join": "Verbinden",
|
||||
@@ -5206,6 +5253,7 @@
|
||||
"web.open_link": "Verknüpftes Design öffnen?",
|
||||
"web.open_link_confirm": "Es gibt nicht gespeicherte Änderungen. Das verknüpfte Design in einem neuen Tab öffnen?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ auswählen · Eingabe / Tab vervollständigen · Esc schließen",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ wählen · Enter wendet das Getippte an · Esc schließt",
|
||||
"⌘Enter continues on GitHub.": "⌘Enter geht weiter zu GitHub."
|
||||
}
|
||||
@@ -249,6 +249,7 @@
|
||||
"ui.details_curvature_caption": "Faces are coloured by their local radius of curvature.",
|
||||
"ui.details_draft_caption": "Faces are coloured by their angle to the pull direction.",
|
||||
"ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file",
|
||||
"ui.instances": "Instances",
|
||||
"ui.layout_compact": "Compact",
|
||||
"ui.layout_floating": "Floating",
|
||||
"ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "Section",
|
||||
"Section (optional)": "Section (optional)",
|
||||
"Section position": "Section position",
|
||||
"Sections": "Sections",
|
||||
"Sections (one sketch each)": "Sections (one sketch each)",
|
||||
"Select Other": "Select Other",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "Show Exploded View",
|
||||
"cmd.expr_evaluate": "Evaluate Expression",
|
||||
"cmd.face_delete": "Delete Face",
|
||||
"cmd.file.export_3mf": "Export 3MF",
|
||||
"cmd.file.export_obj": "Export OBJ",
|
||||
"cmd.file.export_step": "Export STEP",
|
||||
"cmd.file.export_stl": "Export STL",
|
||||
"cmd.file.export_urdf": "Export URDF",
|
||||
"cmd.file_export": "Export",
|
||||
"cmd.file_insert_mesh": "Insert Mesh",
|
||||
"cmd.file_insert_step": "Insert STEP",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "Enable Component Colors",
|
||||
"cmd.inspect_colored_components_disable": "Disable Component Colors",
|
||||
"cmd.inspect_compare": "Compare Bodies",
|
||||
"cmd.inspect_compare_picture": "Compare Picture",
|
||||
"cmd.inspect_continuity": "Continuity Analysis",
|
||||
"cmd.inspect_curvature_comb": "Curvature Comb Analysis",
|
||||
"cmd.inspect_curvature_map": "Curvature Map Analysis",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "Edit Point Cloud",
|
||||
"cmd.pointcloud_insert": "Insert Point Cloud",
|
||||
"cmd.pointcloud_list": "Point Clouds",
|
||||
"cmd.render.compare.divider": "Move Render Comparison Divider",
|
||||
"cmd.render.result.discard": "Discard Render Result",
|
||||
"cmd.render.result.select": "Select Render Result",
|
||||
"cmd.render_aging_describe": "Layered Surface Aging",
|
||||
"cmd.render_backends": "Render Backends",
|
||||
"cmd.render_batch": "Render All Shots",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "Navigation tool",
|
||||
"cmd.view_top": "Top View",
|
||||
"cmd.view_visual_style": "Visual style",
|
||||
"color.blue": "Blue",
|
||||
"color.copy": "Click to copy color values",
|
||||
"color.edit": "Click to edit color",
|
||||
"color.gamma": "Showing color values in 0-255 gamma space",
|
||||
"color.green": "Green",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "Showing color values in 0-1 linear space",
|
||||
"color.recent": "Recent colors",
|
||||
"color.recent_help": "Colors you pick in any color field appear here",
|
||||
"color.red": "Red",
|
||||
"color.saturation": "Saturation (percent)",
|
||||
"color.saturation_value": "Saturation and value",
|
||||
"color.selected": "Selected color",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "Pick bodies or features: a sketch is neither. Repeat its curves with the sketch's own Pattern or Mirror, or extrude it first.",
|
||||
"dialog.select": "↖ Select",
|
||||
"dialog.selected_count": "↖ {count} selected",
|
||||
"dialog.selection_constraint": "Constraint {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · curve {id}",
|
||||
"dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.",
|
||||
"dialog.selection_midpoint": "Midpoint · {id}",
|
||||
"dialog.selection_profile": "{sketch} · profile {number}",
|
||||
"dialog.selection_step": "{step} of {total}: Select {input}",
|
||||
"dialog.step": "Step",
|
||||
"document.changed_on_disk": "{name} changed on disk",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "Left drag",
|
||||
"prefs.button_middle": "Middle drag",
|
||||
"prefs.button_right": "Right drag",
|
||||
"prefs.carousel_next": "Next",
|
||||
"prefs.carousel_previous": "Previous",
|
||||
"prefs.choose_font": "Choose font file…",
|
||||
"prefs.click": "Click",
|
||||
"prefs.contact_shading": "Soft contact shading",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "Curved surfaces",
|
||||
"prefs.curves": "Curved surfaces",
|
||||
"prefs.cut_preview_tint": "Show removed material in red",
|
||||
"prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.",
|
||||
"prefs.dark_parts_shading": "Keep the shape of dark parts",
|
||||
"prefs.dark_parts_shading_help": "Shade the view in linear light with a soft sky fill, so dark faces keep a gradient instead of turning black",
|
||||
"prefs.dead_zone_note": "The hatched band is the dead zone: motion inside it is ignored.",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "Placement",
|
||||
"prefs.prefer_free_sketch_points": "Prefer movable sketch points when points overlap",
|
||||
"prefs.preview_choices": "Preview of your choices",
|
||||
"prefs.preview_tint_new_faces": "Tint new surface in a preview",
|
||||
"prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself.",
|
||||
"prefs.print_face_highlight": "Print face highlight",
|
||||
"prefs.print_face_highlight_tip": "How strongly the print face of a body is tinted and outlined in the view. 0 % shows no highlight.",
|
||||
"prefs.profile_active": "Active profile",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "Base color · sRGB",
|
||||
"render.base_metallic": "Metallic fraction",
|
||||
"render.base_opaque_only": "This editor preserves opaque body semantics. Use the explicit glass controls for optical transmission.",
|
||||
"render.batch_all_shots": "All shots ({count})",
|
||||
"render.batch_empty": "Save a shot before rendering all shots.",
|
||||
"render.batch_limit": "Render all shots is limited to 32 shots.",
|
||||
"render.batch_status": "{running} running · {waiting} waiting",
|
||||
"render.bloom_enable": "Display bloom",
|
||||
"render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalized box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.",
|
||||
"render.bloom_opaque": "Bloom requires opaque output. Transparent PNG is refused, not silently flattened.",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "Choose a look in Appearances first",
|
||||
"render.chromatic_offset": "Chromatic edge offset",
|
||||
"render.clear_stage": "Remove saved stage",
|
||||
"render.compare_divider": "Comparison divider",
|
||||
"render.compare_live": "Live",
|
||||
"render.compare_live_preview": "Live preview",
|
||||
"render.compare_render": "Render {number}",
|
||||
"render.compare_side": "Render {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}",
|
||||
"render.compare_swap": "Swap",
|
||||
"render.copy_request": "Copy JSON",
|
||||
"render.cpu_aa_help": "Spatial samples: more samples improve edges and increase render time.",
|
||||
"render.cpu_area_add": "Add rectangular CPU light",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "Showing the last completed image; a newer render has not replaced it.",
|
||||
"render.result_sequence": "Checkpoint",
|
||||
"render.result_title": "Render Result",
|
||||
"render.results_choose": "Retained results",
|
||||
"render.results_label": "Render {number} · {shot} · {seconds} s",
|
||||
"render.results_stale_label": "{result} [stale]",
|
||||
"render.results_unnamed": "Image",
|
||||
"render.return_design": "Return to Design",
|
||||
"render.review_stale": "This review is stale. Resolve or check again before applying.",
|
||||
"render.ribbon_aging": "Aging",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "Features",
|
||||
"ui.agent_chat_ctx_more": "+{n} more",
|
||||
"ui.agent_chat_ctx_other": "Other",
|
||||
"ui.agent_chat_custom_heading": "Custom model",
|
||||
"ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.",
|
||||
"ui.agent_chat_denied": "Denied",
|
||||
"ui.agent_chat_deny": "Deny",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "All",
|
||||
"ui.agent_chat_mode_ask": "Ask",
|
||||
"ui.agent_chat_mode_edits": "Edits",
|
||||
"ui.agent_chat_model_custom": "Use custom: {model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.",
|
||||
"ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}",
|
||||
"ui.agent_chat_model_search": "Search models…",
|
||||
"ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.",
|
||||
"ui.agent_chat_models_failed": "Couldn't list models: {error}",
|
||||
"ui.agent_chat_models_heading": "Available models",
|
||||
"ui.agent_chat_models_listing": "Listing models…",
|
||||
"ui.agent_chat_models_none": "The endpoint lists no models",
|
||||
"ui.agent_chat_models_not_a_list": "The answer was no model list",
|
||||
"ui.agent_chat_new": "New chat",
|
||||
"ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.",
|
||||
"ui.agent_chat_next_picture": "Next picture",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "{name} has unsaved changes, so its saved file was inserted. Save it, then Update Links to bring the changes in.",
|
||||
"ui.insert_design.unsaved": "Unsaved changes",
|
||||
"ui.inspect": "Inspect",
|
||||
"ui.instances": "Instances",
|
||||
"ui.intersect": "Intersect",
|
||||
"ui.isolate": "Isolate",
|
||||
"ui.join": "Join",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "Open linked design?",
|
||||
"web.open_link_confirm": "There are unsaved changes. Open the linked design in a new tab?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss",
|
||||
"⌘Enter continues on GitHub.": "⌘Enter continues on GitHub."
|
||||
}
|
||||
@@ -4354,6 +4354,7 @@
|
||||
"ui.insert_design.saved_file": "{name} tiene cambios sin guardar, así que se insertó su archivo guardado. Guárdalo y luego Actualizar vínculos para traer los cambios.",
|
||||
"ui.insert_design.unsaved": "Cambios sin guardar",
|
||||
"ui.inspect": "Inspeccionar",
|
||||
"ui.instances": "Instancias",
|
||||
"ui.intersect": "Intersecar",
|
||||
"ui.isolate": "Aislar",
|
||||
"ui.join": "Unir",
|
||||
|
||||
@@ -4318,6 +4318,7 @@
|
||||
"ui.insert_design.saved_file": "Mallissa {name} on tallentamattomia muutoksia, joten sen tallennettu tiedosto lisättiin. Tallenna se ja tuo muutokset valitsemalla Päivitä linkit.",
|
||||
"ui.insert_design.unsaved": "Tallentamattomia muutoksia",
|
||||
"ui.inspect": "Tarkastele",
|
||||
"ui.instances": "Esiintymät",
|
||||
"ui.intersect": "Leikkaus",
|
||||
"ui.isolate": "Eristä",
|
||||
"ui.join": "Yhdistä",
|
||||
|
||||
@@ -4654,6 +4654,7 @@
|
||||
"ui.insert_design.saved_file": "{name} contient des modifications non enregistrées ; c'est donc son fichier enregistré qui a été inséré. Enregistrez-le, puis utilisez Mettre à jour les liens pour intégrer les modifications.",
|
||||
"ui.insert_design.unsaved": "Modifications non enregistrées",
|
||||
"ui.inspect": "Inspecter",
|
||||
"ui.instances": "Instances",
|
||||
"ui.intersect": "Intersection",
|
||||
"ui.isolate": "Isoler",
|
||||
"ui.join": "Joindre",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "חתך",
|
||||
"Section (optional)": "חתך (אופציונלי)",
|
||||
"Section position": "מיקום החתך",
|
||||
"Sections": "חתכים",
|
||||
"Sections (one sketch each)": "חתכים (סקיצה אחת לכל אחד)",
|
||||
"Select Other": "בחירת אחר",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "בחירת אחר: החזקת הכפתור השמאלי ללא תזוזה על המודל (או לחיצה ימנית › בחירת אחר…) מציגה את כל מה שמתחת לסמן; לחיצה נוספת באותה נקודה בוחרת את הפריט הבא שם. לחיצה כפולה על הכפתור האמצעי חוזרת לתצוגת הבית (העדפות › ניווט).",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "הצגת תצוגה מפוצצת",
|
||||
"cmd.expr_evaluate": "חישוב ביטוי",
|
||||
"cmd.face_delete": "מחיקת פאה",
|
||||
"cmd.file.export_3mf": "ייצוא 3MF",
|
||||
"cmd.file.export_obj": "ייצוא OBJ",
|
||||
"cmd.file.export_step": "ייצוא STEP",
|
||||
"cmd.file.export_stl": "ייצוא STL",
|
||||
"cmd.file.export_urdf": "ייצוא URDF",
|
||||
"cmd.file_export": "ייצוא",
|
||||
"cmd.file_insert_mesh": "הוספת רשת משולשים",
|
||||
"cmd.file_insert_step": "הוספת STEP",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "הפעלת צבעי רכיבים",
|
||||
"cmd.inspect_colored_components_disable": "ביטול צבעי רכיבים",
|
||||
"cmd.inspect_compare": "השוואת גופים",
|
||||
"cmd.inspect_compare_picture": "השוואה לתמונת ייחוס",
|
||||
"cmd.inspect_continuity": "ניתוח רציפות",
|
||||
"cmd.inspect_curvature_comb": "ניתוח מסרק עקמומיות",
|
||||
"cmd.inspect_curvature_map": "ניתוח מפת עקמומיות",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "עריכת ענן נקודות",
|
||||
"cmd.pointcloud_insert": "הוספת ענן נקודות",
|
||||
"cmd.pointcloud_list": "ענני נקודות",
|
||||
"cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור",
|
||||
"cmd.render.result.discard": "השלך תוצאת רינדור",
|
||||
"cmd.render.result.select": "בחר תוצאת רינדור",
|
||||
"cmd.render_aging_describe": "הזדקנות משטח בשכבות",
|
||||
"cmd.render_backends": "מנועי הדמיה",
|
||||
"cmd.render_batch": "רינדור כל הצילומים",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "כלי ניווט",
|
||||
"cmd.view_top": "תצוגה עליונה",
|
||||
"cmd.view_visual_style": "סגנון תצוגה",
|
||||
"color.blue": "כחול",
|
||||
"color.copy": "לחיצה מעתיקה את ערכי הצבע",
|
||||
"color.edit": "לחיצה לעריכת הצבע",
|
||||
"color.gamma": "ערכי הצבע מוצגים במרחב גמא 0-255",
|
||||
"color.green": "ירוק",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "ערכי הצבע מוצגים במרחב לינארי 0-1",
|
||||
"color.recent": "צבעים אחרונים",
|
||||
"color.recent_help": "צבעים שבוחרים בכל שדה צבע מופיעים כאן",
|
||||
"color.red": "אדום",
|
||||
"color.saturation": "רוויה (אחוזים)",
|
||||
"color.saturation_value": "רוויה ובהירות",
|
||||
"color.selected": "הצבע שנבחר",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "בחרו גופים או פיצ'רים: סקיצה אינה אף אחד מהם. חזרו על העקומות שלה בעזרת המערך או השיקוף של הסקיצה עצמה, או בצעו לה שליפה קודם.",
|
||||
"dialog.select": "↖ בחירה",
|
||||
"dialog.selected_count": "↖ {count} נבחרו",
|
||||
"dialog.selection_constraint": "אילוץ {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · עקומה {id}",
|
||||
"dialog.selection_guidance": "יש לבחור קלט כדי לשנות אותו. לחיצה על אובייקט שנבחר מסירה אותו; גם Ctrl/Cmd+לחיצה מחליפה את מצבו. לאחר בדיקת התצוגה המקדימה יש ללחוץ על אישור.",
|
||||
"dialog.selection_midpoint": "נקודת אמצע · {id}",
|
||||
"dialog.selection_profile": "{sketch} · פרופיל {number}",
|
||||
"dialog.selection_step": "{step} מתוך {total}: בחירת {input}",
|
||||
"dialog.step": "שלב",
|
||||
"document.changed_on_disk": "{name} השתנה בדיסק",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "גרירה שמאלית",
|
||||
"prefs.button_middle": "גרירה אמצעית",
|
||||
"prefs.button_right": "גרירה ימנית",
|
||||
"prefs.carousel_next": "הבא",
|
||||
"prefs.carousel_previous": "הקודם",
|
||||
"prefs.choose_font": "בחירת קובץ גופן…",
|
||||
"prefs.click": "לחיצה",
|
||||
"prefs.contact_shading": "הצללת מגע רכה",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "משטחים מעוקלים",
|
||||
"prefs.curves": "משטחים מעוקלים",
|
||||
"prefs.cut_preview_tint": "הצגת חומר שהוסר באדום",
|
||||
"prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.",
|
||||
"prefs.dark_parts_shading": "שמירה על צורת חלקים כהים",
|
||||
"prefs.dark_parts_shading_help": "הצללת התצוגה באור ליניארי עם תאורת שמיים רכה, כך שפאות כהות שומרות על מעבר גוונים במקום להפוך לשחורות",
|
||||
"prefs.dead_zone_note": "הפס המקווקו הוא האזור המת: תנועה בתוכו לא נלקחת בחשבון.",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "מיקום",
|
||||
"prefs.prefer_free_sketch_points": "העדפת נקודות סקיצה ניתנות להזזה כשנקודות חופפות",
|
||||
"prefs.preview_choices": "תצוגה מקדימה של הבחירות שלך",
|
||||
"prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה",
|
||||
"prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו.",
|
||||
"prefs.print_face_highlight": "הדגשת פאת ההדפסה",
|
||||
"prefs.print_face_highlight_tip": "עד כמה חזק צובעים ומקיפים את פאת ההדפסה של גוף בתצוגה. 0 % אינו מציג הדגשה.",
|
||||
"prefs.profile_active": "פרופיל פעיל",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "צבע בסיס · sRGB",
|
||||
"render.base_metallic": "שיעור מתכתיות",
|
||||
"render.base_opaque_only": "עורך זה שומר על משמעות של גוף אטום. להעברה אופטית יש להשתמש בפקדי הזכוכית המפורשים.",
|
||||
"render.batch_all_shots": "כל הצילומים ({count})",
|
||||
"render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.",
|
||||
"render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.",
|
||||
"render.batch_status": "{running} רצים · {waiting} ממתינים",
|
||||
"render.bloom_enable": "זוהר בתצוגה",
|
||||
"render.bloom_help": "זוהר יצירתי לפלט בלבד מהבהרות ליניאריות חיוביות, המתפשט בשלושה מעברי תיבה מנורמלים. הרדיוס בפיקסלים של הפלט. נוסף באור תצוגה ליניארי לפני sRGB; אינו עדשה, אינו אפקט נפחי ואינו שיפור התכנסות. ה־EXR הגולמי אינו משתנה.",
|
||||
"render.bloom_opaque": "זוהר דורש פלט אטום. PNG שקוף נדחה, ואינו משוטח בשקט.",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "בחר קודם מראה במראות",
|
||||
"render.chromatic_offset": "היסט כרומטי בקצוות",
|
||||
"render.clear_stage": "הסרת הבמה השמורה",
|
||||
"render.compare_divider": "מחיצת השוואה",
|
||||
"render.compare_live": "חי",
|
||||
"render.compare_live_preview": "תצוגה חיה",
|
||||
"render.compare_render": "רינדור {number}",
|
||||
"render.compare_side": "רינדור {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}",
|
||||
"render.compare_swap": "החלף",
|
||||
"render.copy_request": "העתקת JSON",
|
||||
"render.cpu_aa_help": "דגימות מרחביות: יותר דגימות משפרות קצוות ומאריכות את זמן ההדמיה.",
|
||||
"render.cpu_area_add": "הוספת אור מלבני ב־CPU",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "מוצגת התמונה הגמורה האחרונה; הדמיה חדשה יותר לא החליפה אותה.",
|
||||
"render.result_sequence": "נקודת ביקורת",
|
||||
"render.result_title": "תוצאת הדמיה",
|
||||
"render.results_choose": "תוצאות שנשמרו",
|
||||
"render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳",
|
||||
"render.results_stale_label": "{result} [ישן]",
|
||||
"render.results_unnamed": "תמונה",
|
||||
"render.return_design": "חזרה לתכן",
|
||||
"render.review_stale": "סקירה זו אינה עדכנית. יש לפתור או לבדוק שוב לפני ההחלה.",
|
||||
"render.ribbon_aging": "הזדקנות",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "פיצ'רים",
|
||||
"ui.agent_chat_ctx_more": "+{n} נוספים",
|
||||
"ui.agent_chat_ctx_other": "אחר",
|
||||
"ui.agent_chat_custom_heading": "מודל מותאם אישית",
|
||||
"ui.agent_chat_custom_hint": "כל תוכנה שמדברת Agent Client Protocol דרך stdin ו־stdout. היא לא מורצת דרך מעטפת (shell).",
|
||||
"ui.agent_chat_denied": "נדחה",
|
||||
"ui.agent_chat_deny": "דחייה",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "הכול",
|
||||
"ui.agent_chat_mode_ask": "שאלה",
|
||||
"ui.agent_chat_mode_edits": "עריכות",
|
||||
"ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} לא יכול להשתמש בכלים של SolidCraft, ולכן הוא יכול רק לשוחח. יש לבחור מודל שתומך בכלים.",
|
||||
"ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}",
|
||||
"ui.agent_chat_model_search": "חיפוש מודלים…",
|
||||
"ui.agent_chat_model_tip": "המודל שבו הסוכן משתמש. הבחירה נשמרת עבור הסוכן הזה.",
|
||||
"ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}",
|
||||
"ui.agent_chat_models_heading": "מודלים זמינים",
|
||||
"ui.agent_chat_models_listing": "טוען רשימת מודלים…",
|
||||
"ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים",
|
||||
"ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים",
|
||||
"ui.agent_chat_new": "צ'אט חדש",
|
||||
"ui.agent_chat_new_confirm": "להתחיל צ'אט חדש? הצ'אט הנוכחי יימחק.",
|
||||
"ui.agent_chat_next_picture": "התמונה הבאה",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "ב-{name} יש שינויים שלא נשמרו, ולכן נוסף הקובץ השמור שלו. שמרו אותו ואז בחרו עדכון קישורים כדי להכניס את השינויים.",
|
||||
"ui.insert_design.unsaved": "שינויים שלא נשמרו",
|
||||
"ui.inspect": "בדיקה",
|
||||
"ui.instances": "מופעים",
|
||||
"ui.intersect": "חיתוך משותף",
|
||||
"ui.isolate": "בידוד",
|
||||
"ui.join": "איחוד",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "לפתוח את התכן המקושר?",
|
||||
"web.open_link_confirm": "יש שינויים שלא נשמרו. לפתוח את התכן המקושר בלשונית חדשה?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ בחירה · Enter / Tab השלמה · Esc סגירה",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ בחירה · Enter מחיל את מה שהוקלד · Esc סגירה",
|
||||
"⌘Enter continues on GitHub.": "⌘Enter ממשיך ב־GitHub."
|
||||
}
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} ima nespremljene promjene, pa je umetnuta njegova spremljena datoteka. Spremite ga, a zatim pokrenite Ažuriraj veze kako biste unijeli promjene.",
|
||||
"ui.insert_design.unsaved": "Nespremljene promjene",
|
||||
"ui.inspect": "Pregledaj",
|
||||
"ui.instances": "Instance",
|
||||
"ui.intersect": "Presjek",
|
||||
"ui.isolate": "Izoliraj",
|
||||
"ui.join": "Spoji",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} contiene modifiche non salvate, quindi è stato inserito il file salvato. Salvalo, poi usa Aggiorna collegamenti per includere le modifiche.",
|
||||
"ui.insert_design.unsaved": "Modifiche non salvate",
|
||||
"ui.inspect": "Esamina",
|
||||
"ui.instances": "Istanze",
|
||||
"ui.intersect": "Interseca",
|
||||
"ui.isolate": "Isola",
|
||||
"ui.join": "Unisci",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "断面",
|
||||
"Section (optional)": "断面(任意)",
|
||||
"Section position": "断面の位置",
|
||||
"Sections": "セクション",
|
||||
"Sections (one sketch each)": "セクション (各1スケッチ)",
|
||||
"Select Other": "その他を選択",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "分解図を表示",
|
||||
"cmd.expr_evaluate": "式を評価",
|
||||
"cmd.face_delete": "面を削除",
|
||||
"cmd.file.export_3mf": "3MF をエクスポート",
|
||||
"cmd.file.export_obj": "OBJ をエクスポート",
|
||||
"cmd.file.export_step": "STEP をエクスポート",
|
||||
"cmd.file.export_stl": "STL をエクスポート",
|
||||
"cmd.file.export_urdf": "URDF をエクスポート",
|
||||
"cmd.file_export": "エクスポート",
|
||||
"cmd.file_insert_mesh": "メッシュを挿入",
|
||||
"cmd.file_insert_step": "STEP を挿入",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "コンポーネントの色分けを有効化",
|
||||
"cmd.inspect_colored_components_disable": "コンポーネントの色分けを無効化",
|
||||
"cmd.inspect_compare": "ボディを比較",
|
||||
"cmd.inspect_compare_picture": "参考画像と比較",
|
||||
"cmd.inspect_continuity": "連続性解析",
|
||||
"cmd.inspect_curvature_comb": "曲率コーム解析",
|
||||
"cmd.inspect_curvature_map": "曲率マップ解析",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "点群を編集",
|
||||
"cmd.pointcloud_insert": "点群を挿入",
|
||||
"cmd.pointcloud_list": "点群",
|
||||
"cmd.render.compare.divider": "レンダー比較の境界を移動",
|
||||
"cmd.render.result.discard": "レンダリング結果を破棄",
|
||||
"cmd.render.result.select": "レンダリング結果を選択",
|
||||
"cmd.render_aging_describe": "レイヤー式表面エイジング",
|
||||
"cmd.render_backends": "レンダリング バックエンド",
|
||||
"cmd.render_batch": "すべてのショットをレンダリング",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "ナビゲーションツール",
|
||||
"cmd.view_top": "上面ビュー",
|
||||
"cmd.view_visual_style": "表示スタイル",
|
||||
"color.blue": "青",
|
||||
"color.copy": "クリックして色の値をコピー",
|
||||
"color.edit": "クリックして色を編集",
|
||||
"color.gamma": "0〜255のガンマ空間で色の値を表示",
|
||||
"color.green": "緑",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "#rrggbb または #rrggbbaa を入力。6 桁の場合は不透明度を維持",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "0〜1の線形空間で色の値を表示",
|
||||
"color.recent": "最近使った色",
|
||||
"color.recent_help": "どの色フィールドで選んだ色もここに表示されます",
|
||||
"color.red": "赤",
|
||||
"color.saturation": "彩度(パーセント)",
|
||||
"color.saturation_value": "彩度と明度",
|
||||
"color.selected": "選択した色",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "ボディかフィーチャーを選んでください。スケッチはどちらでもありません。曲線はスケッチ内のパターンかミラーで繰り返すか、先に押し出してください。",
|
||||
"dialog.select": "↖ 選択",
|
||||
"dialog.selected_count": "↖ {count} 個選択中",
|
||||
"dialog.selection_constraint": "拘束 {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · 曲線 {id}",
|
||||
"dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。",
|
||||
"dialog.selection_midpoint": "中点 · {id}",
|
||||
"dialog.selection_profile": "{sketch} · プロファイル {number}",
|
||||
"dialog.selection_step": "{total} ステップ中 {step}: {input} を選択",
|
||||
"dialog.step": "ステップ",
|
||||
"document.changed_on_disk": "{name} がディスク上で変更されました",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "左ドラッグ",
|
||||
"prefs.button_middle": "中央ドラッグ",
|
||||
"prefs.button_right": "右ドラッグ",
|
||||
"prefs.carousel_next": "次へ",
|
||||
"prefs.carousel_previous": "前へ",
|
||||
"prefs.choose_font": "フォントファイルを選択…",
|
||||
"prefs.click": "クリック",
|
||||
"prefs.contact_shading": "柔らかな接触陰影",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "曲面",
|
||||
"prefs.curves": "曲面",
|
||||
"prefs.cut_preview_tint": "除去される材料を赤で表示",
|
||||
"prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。",
|
||||
"prefs.dark_parts_shading": "暗い部品の形状を保つ",
|
||||
"prefs.dark_parts_shading_help": "リニア光と柔らかいスカイライトでビューをシェーディングし、暗い面が黒くつぶれずにグラデーションを保つようにします",
|
||||
"prefs.dead_zone_note": "斜線の帯はデッドゾーンです。この範囲内の動きは無視されます。",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "配置",
|
||||
"prefs.prefer_free_sketch_points": "スケッチ点が重なったときは移動可能な点を優先する",
|
||||
"prefs.preview_choices": "選択した設定のプレビュー",
|
||||
"prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける",
|
||||
"prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。",
|
||||
"prefs.print_face_highlight": "造形面の強調",
|
||||
"prefs.print_face_highlight_tip": "ビューでボディの造形面を色付けし輪郭を描く強さ。0 % で強調しません。",
|
||||
"prefs.profile_active": "使用中のプロファイル",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "ベースカラー・sRGB",
|
||||
"render.base_metallic": "金属成分の割合",
|
||||
"render.base_opaque_only": "この編集では不透明ボディの意味を保持します。透過には明示的なガラス設定を使用してください。",
|
||||
"render.batch_all_shots": "すべてのショット ({count})",
|
||||
"render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。",
|
||||
"render.batch_limit": "一度にレンダリングできるショットは32個までです。",
|
||||
"render.batch_status": "{running} 実行中 · {waiting} 待機中",
|
||||
"render.bloom_enable": "表示ブルーム",
|
||||
"render.bloom_help": "正の線形ハイライトを3回の正規化フィルターで広げる表示専用の効果です。半径は出力ピクセル単位。sRGB変換前に加算され、レンズ・体積・収束の改善ではありません。生EXRは変わりません。",
|
||||
"render.bloom_opaque": "ブルームには不透明な出力が必要です。透明PNGを暗黙に統合せず拒否します。",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "まず外観ライブラリで外観を選択",
|
||||
"render.chromatic_offset": "色収差のずれ",
|
||||
"render.clear_stage": "保存済みステージを削除",
|
||||
"render.compare_divider": "比較の境界",
|
||||
"render.compare_live": "ライブ",
|
||||
"render.compare_live_preview": "ライブプレビュー",
|
||||
"render.compare_render": "レンダー {number}",
|
||||
"render.compare_side": "レンダー {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得",
|
||||
"render.compare_swap": "入れ替え",
|
||||
"render.copy_request": "JSONをコピー",
|
||||
"render.cpu_aa_help": "空間サンプル数を増やすと輪郭が滑らかになりますが、描画時間も増えます。",
|
||||
"render.cpu_area_add": "CPU矩形ライトを追加",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "最後に完成した画像を表示しています。新しいレンダリングにはまだ置き換わっていません。",
|
||||
"render.result_sequence": "中間結果",
|
||||
"render.result_title": "レンダリング結果",
|
||||
"render.results_choose": "保持した結果",
|
||||
"render.results_label": "レンダー {number} · {shot} · {seconds} 秒",
|
||||
"render.results_stale_label": "{result} [更新前]",
|
||||
"render.results_unnamed": "画像",
|
||||
"render.return_design": "設計に戻る",
|
||||
"render.review_stale": "この確認結果は古くなっています。適用前に再解決または再確認してください。",
|
||||
"render.ribbon_aging": "エイジング",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "フィーチャ",
|
||||
"ui.agent_chat_ctx_more": "ほか{n}件",
|
||||
"ui.agent_chat_ctx_other": "その他",
|
||||
"ui.agent_chat_custom_heading": "カスタムモデル",
|
||||
"ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。",
|
||||
"ui.agent_chat_denied": "拒否しました",
|
||||
"ui.agent_chat_deny": "拒否",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "すべて",
|
||||
"ui.agent_chat_mode_ask": "確認",
|
||||
"ui.agent_chat_mode_edits": "編集",
|
||||
"ui.agent_chat_model_custom": "カスタムを使用: {model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} は SolidCraft のツールを使えず、チャットのみ可能です。ツール対応のモデルを選んでください。",
|
||||
"ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}",
|
||||
"ui.agent_chat_model_search": "モデルを検索…",
|
||||
"ui.agent_chat_model_tip": "エージェントが使うモデル。選択はこのエージェントに対して記憶されます。",
|
||||
"ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}",
|
||||
"ui.agent_chat_models_heading": "利用可能なモデル",
|
||||
"ui.agent_chat_models_listing": "モデルを一覧表示中…",
|
||||
"ui.agent_chat_models_none": "エンドポイントにモデルがありません",
|
||||
"ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした",
|
||||
"ui.agent_chat_new": "新しいチャット",
|
||||
"ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。",
|
||||
"ui.agent_chat_next_picture": "次の画像",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "{name} に保存されていない変更があるため、保存済みのファイルを挿入しました。保存してから、リンクを更新で変更を取り込んでください。",
|
||||
"ui.insert_design.unsaved": "未保存の変更",
|
||||
"ui.inspect": "検査",
|
||||
"ui.instances": "インスタンス",
|
||||
"ui.intersect": "交差",
|
||||
"ui.isolate": "分離表示",
|
||||
"ui.join": "結合",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "リンク先のデザインを開きますか?",
|
||||
"web.open_link_confirm": "保存していない変更があります。リンク先のデザインを新しいタブで開きますか?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選択 · Enter 入力どおりに適用 · Esc 閉じる",
|
||||
"⌘Enter continues on GitHub.": "⌘EnterでGitHubに進みます。"
|
||||
}
|
||||
@@ -476,6 +476,7 @@
|
||||
"Second point": "두 번째 점",
|
||||
"Section": "단면",
|
||||
"Section position": "단면 위치",
|
||||
"Sections": "단면",
|
||||
"Sections (one sketch each)": "단면 (각각 스케치 하나)",
|
||||
"Select Other": "다른 항목 선택",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "다른 항목 선택: 모델 위에서 왼쪽 버튼을 가만히 누르고 있거나(또는 오른쪽 클릭 › 다른 항목 선택…) 커서 아래의 모든 항목을 나열합니다. 같은 위치를 다시 클릭하면 다음 항목이 선택됩니다. 가운데 버튼을 더블 클릭하면 홈으로 이동합니다(환경설정 › 탐색).",
|
||||
@@ -905,6 +906,9 @@
|
||||
"cmd.pointcloud_edit": "포인트 클라우드 편집",
|
||||
"cmd.pointcloud_insert": "포인트 클라우드 삽입",
|
||||
"cmd.pointcloud_list": "포인트 클라우드",
|
||||
"cmd.render.compare.divider": "렌더 비교 구분선 이동",
|
||||
"cmd.render.result.discard": "렌더 결과 버리기",
|
||||
"cmd.render.result.select": "렌더 결과 선택",
|
||||
"cmd.render_backends": "렌더링 백엔드",
|
||||
"cmd.render_batch": "모든 샷 렌더링",
|
||||
"cmd.render_camera_fit": "렌더 대상 화면 맞춤",
|
||||
@@ -1110,14 +1114,17 @@
|
||||
"cmd.view_render_frame": "렌더 프레임 가이드",
|
||||
"cmd.view_save": "새 이름 있는 보기",
|
||||
"cmd.view_shots_strip": "샷 스트립",
|
||||
"color.blue": "파랑",
|
||||
"color.copy": "클릭하여 색상 값 복사",
|
||||
"color.edit": "클릭하여 색상 편집",
|
||||
"color.gamma": "색상 값을 0-255 감마 공간으로 표시 중",
|
||||
"color.green": "초록",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "#rrggbb 또는 #rrggbbaa 입력. 6자리 값은 불투명도 유지",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
"color.hue": "색조",
|
||||
"color.linear": "색상 값을 0-1 선형 공간으로 표시 중",
|
||||
"color.red": "빨강",
|
||||
"color.saturation_value": "채도 및 명도",
|
||||
"color.selected": "선택한 색상",
|
||||
"config.column_filter_empty": "일치하는 열이 없습니다",
|
||||
@@ -1167,7 +1174,11 @@
|
||||
"dialog.pattern_sketch_not_object": "바디나 피처를 선택하세요. 스케치는 둘 다 아닙니다. 곡선은 스케치 안의 패턴이나 대칭 복사로 반복하거나, 먼저 돌출하세요.",
|
||||
"dialog.select": "↖ 선택",
|
||||
"dialog.selected_count": "↖ {count}개 선택됨",
|
||||
"dialog.selection_constraint": "구속 조건 {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · 곡선 {id}",
|
||||
"dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.",
|
||||
"dialog.selection_midpoint": "중점 · {id}",
|
||||
"dialog.selection_profile": "{sketch} · 프로파일 {number}",
|
||||
"dialog.selection_step": "{step}/{total} 단계: {input} 선택",
|
||||
"dialog.step": "단계",
|
||||
"document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?",
|
||||
@@ -1541,6 +1552,8 @@
|
||||
"prefs.button_left": "왼쪽 드래그",
|
||||
"prefs.button_middle": "가운데 드래그",
|
||||
"prefs.button_right": "오른쪽 드래그",
|
||||
"prefs.carousel_next": "다음",
|
||||
"prefs.carousel_previous": "이전",
|
||||
"prefs.choose_font": "글꼴 파일 선택…",
|
||||
"prefs.click": "클릭",
|
||||
"prefs.contact_shading": "부드러운 접촉 음영",
|
||||
@@ -1553,6 +1566,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "곡면",
|
||||
"prefs.curves": "곡면",
|
||||
"prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시",
|
||||
"prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.",
|
||||
"prefs.dark_parts_shading": "어두운 부품의 형태 유지",
|
||||
"prefs.dark_parts_shading_help": "선형 조명과 부드러운 하늘광으로 뷰를 음영 처리하여 어두운 면이 검게 뭉개지지 않고 그라데이션을 유지합니다",
|
||||
"prefs.dead_zone_note": "빗금 친 영역이 데드존입니다. 그 안의 움직임은 무시됩니다.",
|
||||
@@ -1639,6 +1654,8 @@
|
||||
"prefs.persistent_ribbon_pressed_help": "효과가 켜져 있는 동안 리본 명령을 강조 표시합니다. 끄면 이전의 중립적인 모양과 명령 도움말을 유지합니다.",
|
||||
"prefs.perspective_fov": "시야각",
|
||||
"prefs.preview_choices": "선택 항목 미리보기",
|
||||
"prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기",
|
||||
"prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다.",
|
||||
"prefs.print_face_highlight": "출력 바닥면 강조",
|
||||
"prefs.print_face_highlight_tip": "뷰에서 바디의 출력 바닥면을 색칠하고 윤곽을 그리는 강도입니다. 0 %이면 강조하지 않습니다.",
|
||||
"prefs.project_options_dialog": "Project 옵션 대화상자",
|
||||
@@ -1829,6 +1846,10 @@
|
||||
"render.appearances": "외관",
|
||||
"render.assign_help": "클릭하여 선택 항목에 적용하거나 드래그하여 미리 보고 놓으세요. 선택이 없으면 칠하기를 시작합니다.",
|
||||
"render.background": "장면 배경",
|
||||
"render.batch_all_shots": "모든 샷 ({count})",
|
||||
"render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.",
|
||||
"render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.",
|
||||
"render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중",
|
||||
"render.bloom_enable": "표시 블룸",
|
||||
"render.bloom_help": "양의 선형 하이라이트를 세 번의 정규화 필터로 확산하는 출력 전용 효과입니다. 반경은 출력 픽셀 단위이며 sRGB 전에 더합니다. 렌즈·볼륨·수렴 개선이 아니며 원본 EXR은 변하지 않습니다.",
|
||||
"render.bloom_opaque": "블룸에는 불투명 출력이 필요합니다. 투명 PNG를 몰래 합성하지 않고 거부합니다.",
|
||||
@@ -1920,6 +1941,13 @@
|
||||
"render.children.workstation": "워크스테이션",
|
||||
"render.choose_look": "먼저 외관 라이브러리에서 외관을 선택하세요",
|
||||
"render.clear_stage": "Remove saved stage",
|
||||
"render.compare_divider": "비교 구분선",
|
||||
"render.compare_live": "라이브",
|
||||
"render.compare_live_preview": "라이브 미리보기",
|
||||
"render.compare_render": "렌더 {number}",
|
||||
"render.compare_side": "렌더 {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처",
|
||||
"render.compare_swap": "맞바꾸기",
|
||||
"render.cpu_budget": "CPU 리소스 프로필",
|
||||
"render.cpu_budget_bodies": "바디 수 상한",
|
||||
"render.cpu_budget_compact": "컴팩트 (기존 제한)",
|
||||
@@ -2388,6 +2416,10 @@
|
||||
"render.result_actual": "100%",
|
||||
"render.result_actual_size": "100%",
|
||||
"render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.",
|
||||
"render.results_choose": "보관된 결과",
|
||||
"render.results_label": "렌더 {number} · {shot} · {seconds}초",
|
||||
"render.results_stale_label": "{result} [이전 버전]",
|
||||
"render.results_unnamed": "이미지",
|
||||
"render.return_design": "설계로 돌아가기",
|
||||
"render.ribbon_backgrounds": "배경",
|
||||
"render.ribbon_check": "검사",
|
||||
@@ -2935,6 +2967,7 @@
|
||||
"ui.agent_chat_command": "에이전트 명령",
|
||||
"ui.agent_chat_connect": "연결",
|
||||
"ui.agent_chat_copy": "복사",
|
||||
"ui.agent_chat_custom_heading": "사용자 지정 모델",
|
||||
"ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.",
|
||||
"ui.agent_chat_denied": "거부함",
|
||||
"ui.agent_chat_deny": "거부",
|
||||
@@ -2976,7 +3009,15 @@
|
||||
"ui.agent_chat_mode_all": "모두",
|
||||
"ui.agent_chat_mode_ask": "확인",
|
||||
"ui.agent_chat_mode_edits": "편집",
|
||||
"ui.agent_chat_model_custom": "직접 입력 사용: {model}",
|
||||
"ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}",
|
||||
"ui.agent_chat_model_search": "모델 검색…",
|
||||
"ui.agent_chat_model_tip": "에이전트가 사용하는 모델입니다. 선택은 이 에이전트에 기억됩니다.",
|
||||
"ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}",
|
||||
"ui.agent_chat_models_heading": "사용 가능한 모델",
|
||||
"ui.agent_chat_models_listing": "모델 목록을 가져오는 중…",
|
||||
"ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다",
|
||||
"ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다",
|
||||
"ui.agent_chat_new": "새 채팅",
|
||||
"ui.agent_chat_new_confirm": "새 채팅을 시작할까요? 현재 채팅은 지워집니다.",
|
||||
"ui.agent_chat_next_picture": "다음 이미지",
|
||||
@@ -3497,6 +3538,7 @@
|
||||
"ui.insert_design.saved_file": "{name}에 저장되지 않은 변경 사항이 있어 저장된 파일을 삽입했습니다. 저장한 다음 링크 업데이트로 변경 사항을 가져오세요.",
|
||||
"ui.insert_design.unsaved": "저장되지 않은 변경 사항",
|
||||
"ui.inspect": "검사",
|
||||
"ui.instances": "인스턴스",
|
||||
"ui.intersect": "교차",
|
||||
"ui.isolate": "분리 표시",
|
||||
"ui.join": "접합",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} heeft niet-opgeslagen wijzigingen, dus is het opgeslagen bestand ingevoegd. Sla het op en gebruik daarna Koppelingen bijwerken om de wijzigingen over te nemen.",
|
||||
"ui.insert_design.unsaved": "Niet-opgeslagen wijzigingen",
|
||||
"ui.inspect": "Inspecteren",
|
||||
"ui.instances": "Instanties",
|
||||
"ui.intersect": "Snijden",
|
||||
"ui.isolate": "Isoleren",
|
||||
"ui.join": "Samenvoegen",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"en": { "ui.agent_chat_copy_message": "Copy message" },
|
||||
"de": { "ui.agent_chat_copy_message": "Nachricht kopieren" },
|
||||
"ar": { "ui.agent_chat_copy_message": "نسخ الرسالة" },
|
||||
"he": { "ui.agent_chat_copy_message": "העתק הודעה" },
|
||||
"ja": { "ui.agent_chat_copy_message": "メッセージをコピー" },
|
||||
"vi": { "ui.agent_chat_copy_message": "Sao chép tin nhắn" },
|
||||
"zh": { "ui.agent_chat_copy_message": "复制消息" }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"ar": {
|
||||
"cmd.ui.assistant": "إظهار المساعد أو إخفاؤه"
|
||||
},
|
||||
"de": {
|
||||
"cmd.ui.assistant": "Assistenten ein-/ausblenden"
|
||||
},
|
||||
"en": {
|
||||
"cmd.ui.assistant": "Toggle Assistant"
|
||||
},
|
||||
"he": {
|
||||
"cmd.ui.assistant": "הצגה או הסתרה של העוזר"
|
||||
},
|
||||
"ja": {
|
||||
"cmd.ui.assistant": "アシスタントの表示切り替え"
|
||||
},
|
||||
"ko": {
|
||||
"cmd.ui.assistant": "도우미 표시 전환"
|
||||
},
|
||||
"vi": {
|
||||
"cmd.ui.assistant": "Bật/tắt trợ lý"
|
||||
},
|
||||
"zh": {
|
||||
"cmd.ui.assistant": "切换助手显示"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"en": { "cmd.sketch_spline_remove_point": "Remove Spline Point" },
|
||||
"ar": { "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي" },
|
||||
"bs": { "cmd.sketch_spline_remove_point": "Ukloni tačku splajna" },
|
||||
"cs": { "cmd.sketch_spline_remove_point": "Odebrat bod splajnu" },
|
||||
"da": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" },
|
||||
"de": { "cmd.sketch_spline_remove_point": "Splinepunkt entfernen" },
|
||||
"es": { "cmd.sketch_spline_remove_point": "Eliminar punto de spline" },
|
||||
"fi": { "cmd.sketch_spline_remove_point": "Poista splinipiste" },
|
||||
"fr": { "cmd.sketch_spline_remove_point": "Supprimer un point de spline" },
|
||||
"gl": { "cmd.sketch_spline_remove_point": "Eliminar punto do spline" },
|
||||
"he": { "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין" },
|
||||
"hr": { "cmd.sketch_spline_remove_point": "Ukloni točku splinea" },
|
||||
"hu": { "cmd.sketch_spline_remove_point": "Splinepont eltávolítása" },
|
||||
"id": { "cmd.sketch_spline_remove_point": "Hapus Titik Spline" },
|
||||
"it": { "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline" },
|
||||
"ja": { "cmd.sketch_spline_remove_point": "スプライン点を削除" },
|
||||
"ms": { "cmd.sketch_spline_remove_point": "Buang Titik Splin" },
|
||||
"nb": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" },
|
||||
"nl": { "cmd.sketch_spline_remove_point": "Splinepunt verwijderen" },
|
||||
"pl": { "cmd.sketch_spline_remove_point": "Usuń punkt splajnu" },
|
||||
"ro": { "cmd.sketch_spline_remove_point": "Elimină punct din spline" },
|
||||
"ru": { "cmd.sketch_spline_remove_point": "Удалить точку сплайна" },
|
||||
"sr": { "cmd.sketch_spline_remove_point": "Уклони тачку сплајна" },
|
||||
"sv": { "cmd.sketch_spline_remove_point": "Ta bort splinepunkt" },
|
||||
"tr": { "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır" },
|
||||
"uk": { "cmd.sketch_spline_remove_point": "Видалити точку сплайна" },
|
||||
"vi": { "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline" },
|
||||
"zh": { "cmd.sketch_spline_remove_point": "删除样条曲线点" },
|
||||
"zh-TW": { "cmd.sketch_spline_remove_point": "刪除雲形線點" }
|
||||
}
|
||||
@@ -2995,6 +2995,7 @@
|
||||
"ui.insert_design.saved_file": "{name} ma niezapisane zmiany, więc wstawiono jego zapisany plik. Zapisz go, a potem użyj Aktualizuj łącza, aby wprowadzić zmiany.",
|
||||
"ui.insert_design.unsaved": "Niezapisane zmiany",
|
||||
"ui.inspect": "Sprawdź",
|
||||
"ui.instances": "Wystąpienia",
|
||||
"ui.intersect": "Przytnij",
|
||||
"ui.isolate": "Izoluj",
|
||||
"ui.join": "Połącz",
|
||||
|
||||
@@ -2092,6 +2092,7 @@
|
||||
"ui.infinite": "Infinita",
|
||||
"ui.insert": "Inserir",
|
||||
"ui.inspect": "Inspecionar",
|
||||
"ui.instances": "Instâncias",
|
||||
"ui.intersect": "Interseção",
|
||||
"ui.isolate": "Isolar",
|
||||
"ui.join": "Unir",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "Дизајн {name} има несачуване промене, па је уметнута његова сачувана датотека. Сачувајте га, а затим покрените Ажурирај везе да бисте унели промене.",
|
||||
"ui.insert_design.unsaved": "Несачуване промене",
|
||||
"ui.inspect": "Прегледај",
|
||||
"ui.instances": "Инстанце",
|
||||
"ui.intersect": "Пресек",
|
||||
"ui.isolate": "Изолуј",
|
||||
"ui.join": "Споји",
|
||||
|
||||
@@ -4706,6 +4706,7 @@
|
||||
"ui.insert_design.saved_file": "{name} має незбережені зміни, тому вставлено його збережений файл. Збережіть його, потім оновіть зв'язки, щоб перенести зміни.",
|
||||
"ui.insert_design.unsaved": "Незбережені зміни",
|
||||
"ui.inspect": "Перевірити",
|
||||
"ui.instances": "Екземпляри",
|
||||
"ui.intersect": "Перетин",
|
||||
"ui.isolate": "Ізолювати",
|
||||
"ui.join": "З'єднати",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "Mặt cắt",
|
||||
"Section (optional)": "Mặt cắt (tùy chọn)",
|
||||
"Section position": "Vị trí mặt cắt",
|
||||
"Sections": "Các mặt cắt",
|
||||
"Sections (one sketch each)": "Các mặt cắt (mỗi mặt cắt một phác thảo)",
|
||||
"Select Other": "Chọn đối tượng khác",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp. Nhấp đúp chuột giữa để về Góc nhìn chuẩn (Tùy chọn cài đặt › Điều hướng).",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "Hiển thị chế độ xem phân rã",
|
||||
"cmd.expr_evaluate": "Tính giá trị biểu thức",
|
||||
"cmd.face_delete": "Xóa mặt",
|
||||
"cmd.file.export_3mf": "Xuất tệp 3MF",
|
||||
"cmd.file.export_obj": "Xuất tệp OBJ",
|
||||
"cmd.file.export_step": "Xuất tệp STEP",
|
||||
"cmd.file.export_stl": "Xuất tệp STL",
|
||||
"cmd.file.export_urdf": "Xuất tệp URDF",
|
||||
"cmd.file_export": "Xuất tệp",
|
||||
"cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)",
|
||||
"cmd.file_insert_step": "Chèn tệp STEP",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "Bật màu cụm chi tiết",
|
||||
"cmd.inspect_colored_components_disable": "Tắt màu cụm chi tiết",
|
||||
"cmd.inspect_compare": "So sánh các thân khối",
|
||||
"cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu",
|
||||
"cmd.inspect_continuity": "Phân tích độ liên tục mặt",
|
||||
"cmd.inspect_curvature_comb": "Phân tích lược độ cong (Curvature Comb)",
|
||||
"cmd.inspect_curvature_map": "Phân tích bản đồ độ cong (Curvature Map)",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "Chỉnh sửa đám mây điểm",
|
||||
"cmd.pointcloud_insert": "Chèn đám mây điểm",
|
||||
"cmd.pointcloud_list": "Đám mây điểm",
|
||||
"cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất",
|
||||
"cmd.render.result.discard": "Bỏ kết quả kết xuất",
|
||||
"cmd.render.result.select": "Chọn kết quả kết xuất",
|
||||
"cmd.render_aging_describe": "Lão hóa bề mặt phân lớp",
|
||||
"cmd.render_backends": "Kết xuất hình ảnh Sauends",
|
||||
"cmd.render_batch": "Kết xuất mọi cảnh chụp",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "Công cụ điều hướng",
|
||||
"cmd.view_top": "Góc nhìn từ trên",
|
||||
"cmd.view_visual_style": "Kiểu hiển thị trực quan",
|
||||
"color.blue": "Xanh dương",
|
||||
"color.copy": "Nhấp để sao chép giá trị màu",
|
||||
"color.edit": "Nhấp để sửa màu",
|
||||
"color.gamma": "Đang hiển thị giá trị màu trong không gian gamma 0-255",
|
||||
"color.green": "Xanh lá",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "Đang hiển thị giá trị màu trong không gian tuyến tính 0-1",
|
||||
"color.recent": "Màu gần đây",
|
||||
"color.recent_help": "Các màu bạn chọn ở bất kỳ ô màu nào sẽ hiện ở đây",
|
||||
"color.red": "Đỏ",
|
||||
"color.saturation": "Độ bão hòa (phần trăm)",
|
||||
"color.saturation_value": "Độ bão hòa và giá trị",
|
||||
"color.selected": "Màu đã chọn",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "Hãy chọn thân khối hoặc tính năng: bản phác thảo không phải là cả hai. Lặp lại các đường cong của nó bằng Mảng hoặc Lấy đối xứng trong chính bản phác thảo, hoặc đùn khối nó trước.",
|
||||
"dialog.select": "↖ Chọn",
|
||||
"dialog.selected_count": "↖ {count} đã chọn",
|
||||
"dialog.selection_constraint": "Ràng buộc {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · đường cong {id}",
|
||||
"dialog.selection_guidance": "Chọn một mục đầu vào để thay đổi. Nhấp vào đối tượng đã chọn để bỏ chọn; Ctrl/Cmd-nhấp để bật/tắt chọn. Xem trước kết quả, sau đó nhấn OK.",
|
||||
"dialog.selection_midpoint": "Trung điểm · {id}",
|
||||
"dialog.selection_profile": "{sketch} · biên dạng {number}",
|
||||
"dialog.selection_step": "{step} / {total}: Chọn {input}",
|
||||
"dialog.step": "Bước",
|
||||
"document.changed_on_disk": "{name} đã thay đổi trên đĩa",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "Kéo chuột trái",
|
||||
"prefs.button_middle": "Kéo chuột giữa",
|
||||
"prefs.button_right": "Kéo chuột phải",
|
||||
"prefs.carousel_next": "Tiếp",
|
||||
"prefs.carousel_previous": "Trước",
|
||||
"prefs.choose_font": "Chọn tệp phông chữ…",
|
||||
"prefs.click": "Nhấp chuột",
|
||||
"prefs.contact_shading": "Đổ bóng tiếp xúc mềm",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "Các mặt cong",
|
||||
"prefs.curves": "Các đường cong",
|
||||
"prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ",
|
||||
"prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.",
|
||||
"prefs.dark_parts_shading": "Giữ hình dạng của chi tiết tối",
|
||||
"prefs.dark_parts_shading_help": "Tô bóng khung nhìn bằng ánh sáng tuyến tính với ánh sáng bầu trời dịu, để các mặt tối giữ được dải chuyển màu thay vì thành màu đen",
|
||||
"prefs.dead_zone_note": "Dải sọc chéo là vùng chết: các chuyển động bên trong vùng này sẽ bị bỏ qua.",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "Vị trí đặt",
|
||||
"prefs.prefer_free_sketch_points": "Ưu tiên điểm phác thảo có thể di chuyển khi các điểm chồng lên nhau",
|
||||
"prefs.preview_choices": "Xem trước các lựa chọn của bạn",
|
||||
"prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước",
|
||||
"prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó.",
|
||||
"prefs.print_face_highlight": "Tô sáng mặt in",
|
||||
"prefs.print_face_highlight_tip": "Mức tô màu và viền mặt in của thân trong khung nhìn. 0 % không tô sáng.",
|
||||
"prefs.profile_active": "Hồ sơ đang dùng",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "Màu cơ sở · sRGB",
|
||||
"render.base_metallic": "Tỷ lệ kim loại",
|
||||
"render.base_opaque_only": "Trình chỉnh sửa này giữ nguyên ngữ nghĩa khối đục. Dùng các điều khiển thủy tinh riêng biệt để chỉnh độ truyền quang học.",
|
||||
"render.batch_all_shots": "Mọi cảnh chụp ({count})",
|
||||
"render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.",
|
||||
"render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.",
|
||||
"render.batch_status": "{running} đang chạy · {waiting} đang chờ",
|
||||
"render.bloom_enable": "Hiển thị lóe sáng (Bloom)",
|
||||
"render.bloom_help": "Hiệu ứng phát sáng sáng tạo cho đầu ra từ các điểm nhấn tuyến tính dương, được khuếch tán qua ba lượt lọc chuẩn hóa. Bán kính tính theo pixel đầu ra. Được cộng vào ánh sáng tuyến tính hiển thị trước sRGB; không phải ống kính thực tế, hiệu ứng thể tích hay cải thiện hội tụ. Tệp EXR thô không đổi.",
|
||||
"render.bloom_opaque": "Hiệu ứng lóe sáng yêu cầu đầu ra đục. PNG trong suốt sẽ bị từ chối chứ không âm thầm làm phẳng nền.",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "Hãy chọn một diện mạo trong Diện mạo trước",
|
||||
"render.chromatic_offset": "Độ lệch sắc sai viền",
|
||||
"render.clear_stage": "Xóa sân khấu đã lưu",
|
||||
"render.compare_divider": "Vạch so sánh",
|
||||
"render.compare_live": "Trực tiếp",
|
||||
"render.compare_live_preview": "Xem trước trực tiếp",
|
||||
"render.compare_render": "Kết xuất {number}",
|
||||
"render.compare_side": "Kết xuất {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}",
|
||||
"render.compare_swap": "Hoán đổi",
|
||||
"render.copy_request": "Sao chép JSON",
|
||||
"render.cpu_aa_help": "Số mẫu không gian: tăng số mẫu giúp cạnh mượt hơn nhưng tăng thời gian kết xuất.",
|
||||
"render.cpu_area_add": "Thêm nguồn sáng vùng chữ nhật CPU",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "Đang hiển thị hình ảnh hoàn thành gần nhất; kết xuất mới hơn chưa thay thế nó.",
|
||||
"render.result_sequence": "Điểm kiểm tra trung gian",
|
||||
"render.result_title": "Kết quả kết xuất",
|
||||
"render.results_choose": "Kết quả được giữ lại",
|
||||
"render.results_label": "Kết xuất {number} · {shot} · {seconds} giây",
|
||||
"render.results_stale_label": "{result} [cũ]",
|
||||
"render.results_unnamed": "Ảnh",
|
||||
"render.return_design": "Quay lại thiết kế",
|
||||
"render.review_stale": "Kết quả xem xét này đã cũ. Hãy xử lý hoặc kiểm tra lại trước khi áp dụng.",
|
||||
"render.ribbon_aging": "Lão hóa",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "Tính năng",
|
||||
"ui.agent_chat_ctx_more": "+{n} mục khác",
|
||||
"ui.agent_chat_ctx_other": "Khác",
|
||||
"ui.agent_chat_custom_heading": "Mô hình tùy chỉnh",
|
||||
"ui.agent_chat_custom_hint": "Bất kỳ chương trình nào hỗ trợ giao thức Agent Client Protocol qua stdin và stdout. Không chạy qua shell hệ thống.",
|
||||
"ui.agent_chat_denied": "Đã từ chối",
|
||||
"ui.agent_chat_deny": "Từ chối",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "Tất cả",
|
||||
"ui.agent_chat_mode_ask": "Hỏi",
|
||||
"ui.agent_chat_mode_edits": "Chỉnh sửa",
|
||||
"ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} không thể sử dụng các công cụ của SolidCraft nên chỉ có thể trò chuyện. Hãy chọn mô hình có hỗ trợ công cụ.",
|
||||
"ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}",
|
||||
"ui.agent_chat_model_search": "Tìm mô hình…",
|
||||
"ui.agent_chat_model_tip": "Mô hình AI đang sử dụng. Lựa chọn của bạn sẽ được ghi nhớ cho Agent này.",
|
||||
"ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}",
|
||||
"ui.agent_chat_models_heading": "Các mô hình có sẵn",
|
||||
"ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…",
|
||||
"ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào",
|
||||
"ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình",
|
||||
"ui.agent_chat_new": "Cuộc trò chuyện mới",
|
||||
"ui.agent_chat_new_confirm": "Bắt đầu cuộc trò chuyện mới? Cuộc trò chuyện hiện tại sẽ bị xóa.",
|
||||
"ui.agent_chat_next_picture": "Ảnh kế tiếp",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "{name} có thay đổi chưa lưu, nên tệp đã lưu của nó đã được chèn. Hãy lưu nó, rồi dùng Cập nhật liên kết để đưa các thay đổi vào.",
|
||||
"ui.insert_design.unsaved": "Thay đổi chưa lưu",
|
||||
"ui.inspect": "Kiểm tra",
|
||||
"ui.instances": "Số bản",
|
||||
"ui.intersect": "Giao nhau",
|
||||
"ui.isolate": "Cô lập đối tượng",
|
||||
"ui.join": "Nối liền",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "Mở thiết kế liên kết?",
|
||||
"web.open_link_confirm": "Có những thay đổi chưa lưu. Mở thiết kế liên kết trong tab mới?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ chọn · Enter / Tab hoàn tất · Esc bỏ qua",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ để chọn · Enter để áp dụng nội dung đã nhập · Esc để đóng",
|
||||
"⌘Enter continues on GitHub.": "Nhấn ⌘Enter để tiếp tục trên GitHub."
|
||||
}
|
||||
@@ -4708,6 +4708,7 @@
|
||||
"ui.insert_design.saved_file": "{name} 有未儲存的變更,因此插入的是其已儲存的檔案。請儲存後執行「更新連結」以帶入變更。",
|
||||
"ui.insert_design.unsaved": "未儲存的變更",
|
||||
"ui.inspect": "檢查",
|
||||
"ui.instances": "實例數",
|
||||
"ui.intersect": "相交",
|
||||
"ui.isolate": "隔離",
|
||||
"ui.join": "接合",
|
||||
|
||||
@@ -556,6 +556,7 @@
|
||||
"Section": "剖面",
|
||||
"Section (optional)": "截面(可选)",
|
||||
"Section position": "截面位置",
|
||||
"Sections": "截面",
|
||||
"Sections (one sketch each)": "截面(每个一个草图)",
|
||||
"Select Other": "选择其他",
|
||||
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。",
|
||||
@@ -936,6 +937,11 @@
|
||||
"cmd.explode_show": "显示爆炸图",
|
||||
"cmd.expr_evaluate": "计算表达式",
|
||||
"cmd.face_delete": "删除面",
|
||||
"cmd.file.export_3mf": "导出 3MF",
|
||||
"cmd.file.export_obj": "导出 OBJ",
|
||||
"cmd.file.export_step": "导出 STEP",
|
||||
"cmd.file.export_stl": "导出 STL",
|
||||
"cmd.file.export_urdf": "导出 URDF",
|
||||
"cmd.file_export": "导出",
|
||||
"cmd.file_insert_mesh": "插入网格",
|
||||
"cmd.file_insert_step": "插入 STEP",
|
||||
@@ -953,6 +959,7 @@
|
||||
"cmd.inspect_colored_components": "启用组件颜色",
|
||||
"cmd.inspect_colored_components_disable": "禁用组件颜色",
|
||||
"cmd.inspect_compare": "比较实体",
|
||||
"cmd.inspect_compare_picture": "比较参考图",
|
||||
"cmd.inspect_continuity": "连续性分析",
|
||||
"cmd.inspect_curvature_comb": "曲率梳分析",
|
||||
"cmd.inspect_curvature_map": "曲率图分析",
|
||||
@@ -1043,6 +1050,9 @@
|
||||
"cmd.pointcloud_edit": "编辑点云",
|
||||
"cmd.pointcloud_insert": "插入点云",
|
||||
"cmd.pointcloud_list": "点云",
|
||||
"cmd.render.compare.divider": "移动渲染比较分隔线",
|
||||
"cmd.render.result.discard": "丢弃渲染结果",
|
||||
"cmd.render.result.select": "选择渲染结果",
|
||||
"cmd.render_aging_describe": "分层表面老化",
|
||||
"cmd.render_backends": "渲染后端",
|
||||
"cmd.render_batch": "渲染所有镜头",
|
||||
@@ -1290,9 +1300,11 @@
|
||||
"cmd.view_tool": "导航工具",
|
||||
"cmd.view_top": "俯视图",
|
||||
"cmd.view_visual_style": "视觉样式",
|
||||
"color.blue": "蓝色",
|
||||
"color.copy": "单击复制颜色值",
|
||||
"color.edit": "单击编辑颜色",
|
||||
"color.gamma": "以 0–255 伽马空间显示颜色值",
|
||||
"color.green": "绿色",
|
||||
"color.hex": "Hex",
|
||||
"color.hex_help": "输入 #rrggbb 或 #rrggbbaa;六位数保留不透明度",
|
||||
"color.hex_hint": "#rrggbb",
|
||||
@@ -1300,6 +1312,7 @@
|
||||
"color.linear": "以 0–1 线性空间显示颜色值",
|
||||
"color.recent": "最近使用的颜色",
|
||||
"color.recent_help": "在任意颜色字段中选择的颜色会显示在这里",
|
||||
"color.red": "红色",
|
||||
"color.saturation": "饱和度(百分比)",
|
||||
"color.saturation_value": "饱和度和明度",
|
||||
"color.selected": "所选颜色",
|
||||
@@ -1357,7 +1370,11 @@
|
||||
"dialog.pattern_sketch_not_object": "请选择实体或特征:草图两者都不是。请用草图自身的阵列或镜像重复其曲线,或先将其拉伸。",
|
||||
"dialog.select": "↖ 选择",
|
||||
"dialog.selected_count": "↖ 已选择 {count} 个",
|
||||
"dialog.selection_constraint": "约束 {id}",
|
||||
"dialog.selection_external_curve": "{sketch} · 曲线 {id}",
|
||||
"dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。",
|
||||
"dialog.selection_midpoint": "中点 · {id}",
|
||||
"dialog.selection_profile": "{sketch} · 轮廓 {number}",
|
||||
"dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}",
|
||||
"dialog.step": "步骤",
|
||||
"document.changed_on_disk": "{name} 已在磁盘上更改",
|
||||
@@ -2139,6 +2156,8 @@
|
||||
"prefs.button_left": "左键拖动",
|
||||
"prefs.button_middle": "中键拖动",
|
||||
"prefs.button_right": "右键拖动",
|
||||
"prefs.carousel_next": "下一个",
|
||||
"prefs.carousel_previous": "上一个",
|
||||
"prefs.choose_font": "选择字体文件…",
|
||||
"prefs.click": "单击",
|
||||
"prefs.contact_shading": "柔和接触阴影",
|
||||
@@ -2151,6 +2170,8 @@
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "曲面",
|
||||
"prefs.curves": "曲面",
|
||||
"prefs.cut_preview_tint": "以红色显示被移除的材料",
|
||||
"prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。",
|
||||
"prefs.dark_parts_shading": "保持深色零件的形状",
|
||||
"prefs.dark_parts_shading_help": "以线性光照和柔和的天空补光着色视图,使深色面保留渐变而不变成一片黑色",
|
||||
"prefs.dead_zone_note": "斜线区域为死区:此范围内的移动将被忽略。",
|
||||
@@ -2270,6 +2291,8 @@
|
||||
"prefs.placement": "放置",
|
||||
"prefs.prefer_free_sketch_points": "草图点重合时优先选择可移动的点",
|
||||
"prefs.preview_choices": "所选设置预览",
|
||||
"prefs.preview_tint_new_faces": "在预览中为新表面着色",
|
||||
"prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。",
|
||||
"prefs.print_face_highlight": "打印底面高亮",
|
||||
"prefs.print_face_highlight_tip": "视图中实体打印底面的着色和轮廓强度。0 % 不显示高亮。",
|
||||
"prefs.profile_active": "当前配置文件",
|
||||
@@ -2567,6 +2590,10 @@
|
||||
"render.base_color": "基础颜色 · sRGB",
|
||||
"render.base_metallic": "金属比例",
|
||||
"render.base_opaque_only": "此编辑器保留不透明实体语义;光学透射请使用明确的玻璃控件。",
|
||||
"render.batch_all_shots": "所有镜头 ({count})",
|
||||
"render.batch_empty": "渲染所有镜头前请先保存镜头。",
|
||||
"render.batch_limit": "一次最多渲染32个镜头。",
|
||||
"render.batch_status": "{running} 个运行中 · {waiting} 个等待中",
|
||||
"render.bloom_enable": "显示泛光",
|
||||
"render.bloom_help": "仅用于输出的创意辉光,将正线性高光经过三次归一化滤波扩散。半径以输出像素计,在 sRGB 前叠加;不模拟镜头或体积,也不改善收敛。原始 EXR 不变。",
|
||||
"render.bloom_opaque": "泛光需要不透明输出;会拒绝透明 PNG,而非暗中合成背景。",
|
||||
@@ -2677,6 +2704,13 @@
|
||||
"render.choose_look": "请先在外观库中选择外观",
|
||||
"render.chromatic_offset": "边缘色差偏移",
|
||||
"render.clear_stage": "移除已保存的舞台",
|
||||
"render.compare_divider": "比较分隔线",
|
||||
"render.compare_live": "实时",
|
||||
"render.compare_live_preview": "实时预览",
|
||||
"render.compare_render": "渲染 {number}",
|
||||
"render.compare_side": "渲染 {number} · {shot}",
|
||||
"render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}",
|
||||
"render.compare_swap": "交换",
|
||||
"render.copy_request": "复制 JSON",
|
||||
"render.cpu_aa_help": "增加空间采样可改善边缘,但会增加渲染时间。",
|
||||
"render.cpu_area_add": "添加 CPU 矩形光源",
|
||||
@@ -3426,6 +3460,10 @@
|
||||
"render.result_retained": "正在显示最后完成的图像;较新的渲染尚未替换它。",
|
||||
"render.result_sequence": "中间结果",
|
||||
"render.result_title": "渲染结果",
|
||||
"render.results_choose": "保留的结果",
|
||||
"render.results_label": "渲染 {number} · {shot} · {seconds} 秒",
|
||||
"render.results_stale_label": "{result} [已过期]",
|
||||
"render.results_unnamed": "图像",
|
||||
"render.return_design": "返回设计",
|
||||
"render.review_stale": "此审阅结果已过期;应用前请重新解析或检查。",
|
||||
"render.ribbon_aging": "老化",
|
||||
@@ -4097,6 +4135,7 @@
|
||||
"ui.agent_chat_ctx_features": "特征",
|
||||
"ui.agent_chat_ctx_more": "另有 {n} 项",
|
||||
"ui.agent_chat_ctx_other": "其他",
|
||||
"ui.agent_chat_custom_heading": "自定义模型",
|
||||
"ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。",
|
||||
"ui.agent_chat_denied": "已拒绝",
|
||||
"ui.agent_chat_deny": "拒绝",
|
||||
@@ -4140,8 +4179,16 @@
|
||||
"ui.agent_chat_mode_all": "全部",
|
||||
"ui.agent_chat_mode_ask": "询问",
|
||||
"ui.agent_chat_mode_edits": "编辑",
|
||||
"ui.agent_chat_model_custom": "使用自定义:{model}",
|
||||
"ui.agent_chat_model_no_tools": "{model} 无法使用 SolidCraft 的工具,只能聊天。请选择支持工具的模型。",
|
||||
"ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}",
|
||||
"ui.agent_chat_model_search": "搜索模型…",
|
||||
"ui.agent_chat_model_tip": "智能体使用的模型。你的选择会为此智能体记住。",
|
||||
"ui.agent_chat_models_failed": "无法列出模型:{error}",
|
||||
"ui.agent_chat_models_heading": "可用模型",
|
||||
"ui.agent_chat_models_listing": "正在列出模型…",
|
||||
"ui.agent_chat_models_none": "该端点未列出任何模型",
|
||||
"ui.agent_chat_models_not_a_list": "响应不是模型列表",
|
||||
"ui.agent_chat_new": "新对话",
|
||||
"ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。",
|
||||
"ui.agent_chat_next_picture": "下一张图片",
|
||||
@@ -4723,6 +4770,7 @@
|
||||
"ui.insert_design.saved_file": "{name} 有未保存的更改,因此插入的是其已保存的文件。请先保存,再使用“更新链接”导入这些更改。",
|
||||
"ui.insert_design.unsaved": "未保存的更改",
|
||||
"ui.inspect": "检查",
|
||||
"ui.instances": "实例数",
|
||||
"ui.intersect": "相交",
|
||||
"ui.isolate": "隔离",
|
||||
"ui.join": "连接",
|
||||
@@ -5214,6 +5262,7 @@
|
||||
"web.open_link": "打开链接的设计?",
|
||||
"web.open_link_confirm": "有未保存的更改。要在新标签页中打开链接的设计吗?",
|
||||
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭",
|
||||
"↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值",
|
||||
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 选择 · Enter 按原样应用 · Esc 关闭",
|
||||
"⌘Enter continues on GitHub.": "按⌘Enter在GitHub中继续。"
|
||||
}
|
||||
@@ -231,6 +231,28 @@ impl Tokens {
|
||||
dialog_label: Color32::from_rgb(58, 70, 86),
|
||||
selected_ink: Color32::from_rgb(26, 80, 127),
|
||||
selected_bg: Color32::from_rgb(232, 241, 250),
|
||||
figure_ground: Color32::from_rgb(247, 248, 250),
|
||||
figure_line: Color32::from_rgb(111, 124, 143),
|
||||
figure_face_top: Color32::from_rgb(255, 255, 255),
|
||||
figure_face_left: Color32::from_rgb(228, 233, 240),
|
||||
figure_face_right: Color32::from_rgb(201, 210, 222),
|
||||
figure_card: Color32::from_rgb(255, 255, 255),
|
||||
figure_white: Color32::WHITE,
|
||||
figure_black: Color32::BLACK,
|
||||
figure_accent: Color32::from_rgb(35, 110, 173),
|
||||
figure_reference: Color32::from_rgb(138, 83, 0),
|
||||
figure_axis_x: Color32::from_rgb(214, 69, 69),
|
||||
figure_axis_y: Color32::from_rgb(46, 158, 91),
|
||||
figure_axis_z: Color32::from_rgb(47, 111, 208),
|
||||
figure_ok: Color32::from_rgb(47, 125, 91),
|
||||
figure_warn: Color32::from_rgb(201, 138, 0),
|
||||
pref_well: Color32::from_rgb(238, 241, 245),
|
||||
pref_note: Color32::from_rgb(184, 74, 0),
|
||||
pref_note_fill: Color32::from_rgb(251, 235, 221),
|
||||
pref_on_accent: Color32::from_rgb(255, 255, 255),
|
||||
pref_ok: Color32::from_rgb(39, 107, 44),
|
||||
pref_ok_fill: Color32::from_rgb(229, 242, 230),
|
||||
pref_disabled: Color32::from_rgb(138, 148, 163),
|
||||
timeline_item: Color32::WHITE,
|
||||
timeline_item_error: Color32::from_rgb(250, 220, 220),
|
||||
timeline_marker: Color32::from_rgb(70, 76, 88),
|
||||
@@ -352,6 +374,26 @@ impl Tokens {
|
||||
t.dialog_label = t.text;
|
||||
t.selected_ink = Color32::from_rgb(156, 199, 245);
|
||||
t.selected_bg = Color32::from_rgb(42, 70, 110);
|
||||
t.figure_ground = Color32::from_rgb(28, 31, 38);
|
||||
t.figure_line = Color32::from_rgb(163, 174, 194);
|
||||
t.figure_face_top = Color32::from_rgb(107, 119, 144);
|
||||
t.figure_face_left = Color32::from_rgb(81, 91, 114);
|
||||
t.figure_face_right = Color32::from_rgb(57, 66, 86);
|
||||
t.figure_card = Color32::from_rgb(47, 52, 62);
|
||||
t.figure_accent = Color32::from_rgb(140, 190, 245);
|
||||
t.figure_reference = Color32::from_rgb(232, 194, 74);
|
||||
t.figure_axis_x = Color32::from_rgb(242, 122, 122);
|
||||
t.figure_axis_y = Color32::from_rgb(98, 212, 142);
|
||||
t.figure_axis_z = Color32::from_rgb(108, 168, 247);
|
||||
t.figure_ok = Color32::from_rgb(127, 209, 174);
|
||||
t.figure_warn = Color32::from_rgb(232, 194, 74);
|
||||
t.pref_well = Color32::from_rgb(47, 52, 62);
|
||||
t.pref_note = Color32::from_rgb(240, 162, 122);
|
||||
t.pref_note_fill = Color32::from_rgb(74, 51, 38);
|
||||
t.pref_on_accent = Color32::from_rgb(15, 22, 32);
|
||||
t.pref_ok = Color32::from_rgb(127, 209, 174);
|
||||
t.pref_ok_fill = Color32::from_rgb(31, 58, 49);
|
||||
t.pref_disabled = Color32::from_rgb(138, 148, 163);
|
||||
t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_PRIMARY[1]);
|
||||
t.error = Color32::from_rgb(240, 100, 96);
|
||||
t.sketch_conflict = t.error;
|
||||
|
||||
+171
-2
@@ -2550,6 +2550,169 @@ impl FeatureKind {
|
||||
FeatureKind::Repair { .. } => "RepairFeature",
|
||||
}
|
||||
}
|
||||
|
||||
/// Design-file variant key (e.g. `"extrude"`, `"box"`, `"sheet_flange"`).
|
||||
pub fn kind_key(&self) -> &'static str {
|
||||
match self {
|
||||
FeatureKind::BodyTransfer { .. } => "body_transfer",
|
||||
FeatureKind::Sketch { .. } => "sketch",
|
||||
FeatureKind::Extrude { .. } => "extrude",
|
||||
FeatureKind::Revolve { .. } => "revolve",
|
||||
FeatureKind::Fillet { .. } => "fillet",
|
||||
FeatureKind::Chamfer { .. } => "chamfer",
|
||||
FeatureKind::Box { .. } => "box",
|
||||
FeatureKind::Cylinder { .. } => "cylinder",
|
||||
FeatureKind::Sphere { .. } => "sphere",
|
||||
FeatureKind::Torus { .. } => "torus",
|
||||
FeatureKind::Cone { .. } => "cone",
|
||||
FeatureKind::Combine { .. } => "combine",
|
||||
FeatureKind::Pattern { .. } => "pattern",
|
||||
FeatureKind::Mirror { .. } => "mirror",
|
||||
FeatureKind::Hole { .. } => "hole",
|
||||
FeatureKind::Thread { .. } => "thread",
|
||||
FeatureKind::Loft { .. } => "loft",
|
||||
FeatureKind::Sweep { .. } => "sweep",
|
||||
FeatureKind::Shell { .. } => "shell",
|
||||
FeatureKind::Draft { .. } => "draft",
|
||||
FeatureKind::ConstructionPlane { .. } => "construction_plane",
|
||||
FeatureKind::Split { .. } => "split",
|
||||
FeatureKind::ConstructionAxis { .. } => "construction_axis",
|
||||
FeatureKind::ConstructionPoint { .. } => "construction_point",
|
||||
FeatureKind::SplitFace { .. } => "split_face",
|
||||
FeatureKind::Scale { .. } => "scale",
|
||||
FeatureKind::OffsetFace { .. } => "offset_face",
|
||||
FeatureKind::DeleteFace { .. } => "delete_face",
|
||||
FeatureKind::BoundingSolid { .. } => "bounding_solid",
|
||||
FeatureKind::Pipe { .. } => "pipe",
|
||||
FeatureKind::FrameMember { .. } => "frame_member",
|
||||
FeatureKind::Emboss { .. } => "emboss",
|
||||
FeatureKind::Rib { .. } => "rib",
|
||||
FeatureKind::ReplaceFace { .. } => "replace_face",
|
||||
FeatureKind::Align { .. } => "align",
|
||||
FeatureKind::Coil { .. } => "coil",
|
||||
FeatureKind::SheetBase { .. } => "sheet_base",
|
||||
FeatureKind::SheetContour { .. } => "sheet_contour",
|
||||
FeatureKind::SheetFlange { .. } => "sheet_flange",
|
||||
FeatureKind::SheetHem { .. } => "sheet_hem",
|
||||
FeatureKind::SheetPerforate { .. } => "sheet_perforate",
|
||||
FeatureKind::SheetFold { .. } => "sheet_fold",
|
||||
FeatureKind::SheetPath { .. } => "sheet_path",
|
||||
FeatureKind::SheetUnfold { .. } => "sheet_unfold",
|
||||
FeatureKind::SheetConvert { .. } => "sheet_convert",
|
||||
FeatureKind::Boss { .. } => "boss",
|
||||
FeatureKind::Lip { .. } => "lip",
|
||||
FeatureKind::SnapFit { .. } => "snap_fit",
|
||||
FeatureKind::Rest { .. } => "rest",
|
||||
FeatureKind::BoundaryFill { .. } => "boundary_fill",
|
||||
FeatureKind::Remove { .. } => "remove",
|
||||
FeatureKind::Patch { .. } => "patch",
|
||||
FeatureKind::Stitch { .. } => "stitch",
|
||||
FeatureKind::Thicken { .. } => "thicken",
|
||||
FeatureKind::SurfaceExtrude { .. } => "surface_extrude",
|
||||
FeatureKind::Unstitch { .. } => "unstitch",
|
||||
FeatureKind::ReverseNormal { .. } => "reverse_normal",
|
||||
FeatureKind::SurfaceUntrim { .. } => "surface_untrim",
|
||||
FeatureKind::SurfaceRevolve { .. } => "surface_revolve",
|
||||
FeatureKind::SurfaceSweep { .. } => "surface_sweep",
|
||||
FeatureKind::SurfaceLoft { .. } => "surface_loft",
|
||||
FeatureKind::SurfaceOffset { .. } => "surface_offset",
|
||||
FeatureKind::SurfaceRuled { .. } => "surface_ruled",
|
||||
FeatureKind::SurfaceExtend { .. } => "surface_extend",
|
||||
FeatureKind::SurfaceBlend { .. } => "surface_blend",
|
||||
FeatureKind::SurfaceBoundary { .. } => "surface_boundary",
|
||||
FeatureKind::SurfaceNetwork { .. } => "surface_network",
|
||||
FeatureKind::SurfaceMatch { .. } => "surface_match",
|
||||
FeatureKind::SurfaceFair { .. } => "surface_fair",
|
||||
FeatureKind::SurfaceTrim { .. } => "surface_trim",
|
||||
FeatureKind::Move { .. } => "move",
|
||||
FeatureKind::Import { .. } => "import",
|
||||
FeatureKind::MeshConvert { .. } => "mesh_convert",
|
||||
FeatureKind::MeshImport { .. } => "mesh_import",
|
||||
FeatureKind::Repair { .. } => "repair",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a display or Rust type name (e.g. `"HoleFeature"`, `"EdgeFlangeFeature"`)
|
||||
/// to the canonical design-file variant key (`"hole"`, `"sheet_flange"`).
|
||||
pub fn type_name_to_kind_key(name: &str) -> Option<&'static str> {
|
||||
Some(match name {
|
||||
"BodyTransferFeature" => "body_transfer",
|
||||
"Sketch" => "sketch",
|
||||
"ExtrudeFeature" => "extrude",
|
||||
"RevolveFeature" => "revolve",
|
||||
"FilletFeature" => "fillet",
|
||||
"ChamferFeature" => "chamfer",
|
||||
"BoxFeature" => "box",
|
||||
"CylinderFeature" => "cylinder",
|
||||
"SphereFeature" => "sphere",
|
||||
"TorusFeature" => "torus",
|
||||
"ConeFeature" => "cone",
|
||||
"CombineFeature" => "combine",
|
||||
"RectangularPatternFeature" | "PathPatternFeature" | "CircularPatternFeature" => "pattern",
|
||||
"MirrorFeature" => "mirror",
|
||||
"ConstructionPlane" => "construction_plane",
|
||||
"HoleFeature" => "hole",
|
||||
"ThreadFeature" => "thread",
|
||||
"LoftFeature" => "loft",
|
||||
"SweepFeature" => "sweep",
|
||||
"ShellFeature" => "shell",
|
||||
"DraftFeature" => "draft",
|
||||
"SplitBodyFeature" => "split",
|
||||
"SplitFaceFeature" => "split_face",
|
||||
"ConstructionAxis" => "construction_axis",
|
||||
"ConstructionPoint" => "construction_point",
|
||||
"MoveFeature" => "move",
|
||||
"ScaleFeature" => "scale",
|
||||
"OffsetFacesFeature" => "offset_face",
|
||||
"DeleteFaceFeature" => "delete_face",
|
||||
"OffsetSurfaceFeature" => "surface_offset",
|
||||
"BoundingSolidFeature" => "bounding_solid",
|
||||
"PipeFeature" => "pipe",
|
||||
"FrameMemberFeature" => "frame_member",
|
||||
"EmbossFeature" => "emboss",
|
||||
"BossFeature" => "boss",
|
||||
"LipFeature" | "GrooveFeature" => "lip",
|
||||
"SnapFitFeature" => "snap_fit",
|
||||
"RestFeature" => "rest",
|
||||
"BoundaryFillFeature" => "boundary_fill",
|
||||
"BaseFlangeFeature" => "sheet_base",
|
||||
"ContourFlangeFeature" => "sheet_contour",
|
||||
"EdgeFlangeFeature" => "sheet_flange",
|
||||
"HemFeature" => "sheet_hem",
|
||||
"PerforateFeature" => "sheet_perforate",
|
||||
"FoldFeature" => "sheet_fold",
|
||||
"PathFlangeFeature" => "sheet_path",
|
||||
"UnfoldFeature" | "RefoldFeature" => "sheet_unfold",
|
||||
"ConvertToSheetMetalFeature" => "sheet_convert",
|
||||
"CoilFeature" => "coil",
|
||||
"RibFeature" | "WebFeature" => "rib",
|
||||
"ReplaceFaceFeature" => "replace_face",
|
||||
"AlignFeature" => "align",
|
||||
"RemoveFeature" => "remove",
|
||||
"PatchFeature" => "patch",
|
||||
"SurfaceExtrudeFeature" => "surface_extrude",
|
||||
"SurfaceRevolveFeature" => "surface_revolve",
|
||||
"SurfaceSweepFeature" => "surface_sweep",
|
||||
"SurfaceLoftFeature" => "surface_loft",
|
||||
"BlendFeature" => "surface_blend",
|
||||
"BoundaryFeature" => "surface_boundary",
|
||||
"MatchFeature" => "surface_match",
|
||||
"FairFeature" => "surface_fair",
|
||||
"StitchFeature" => "stitch",
|
||||
"ThickenFeature" => "thicken",
|
||||
"TrimFeature" => "surface_trim",
|
||||
"ExtendFeature" => "surface_extend",
|
||||
"RuledSurfaceFeature" => "surface_ruled",
|
||||
"UnstitchFeature" => "unstitch",
|
||||
"ReverseNormalFeature" => "reverse_normal",
|
||||
"UntrimFeature" => "surface_untrim",
|
||||
"BaseFeature" => "import",
|
||||
"MeshFeature" => "mesh_import",
|
||||
"MeshConvertFeature" => "mesh_convert",
|
||||
"RepairFeature" => "repair",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// Default name prefix (`Extrude` → `Extrude1`).
|
||||
pub fn base_name(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -3727,12 +3890,18 @@ impl Document {
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let id = self.next_id.max(1);
|
||||
self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?;
|
||||
let name = match name {
|
||||
Some(n) if !n.trim().is_empty() => n.trim().to_string(),
|
||||
_ => self.unique_name(kind.base_name()),
|
||||
};
|
||||
// Plane references share the feature namespace. A duplicate would silently select
|
||||
// the first feature. Other shared names (a sketch and its extrude) remain supported.
|
||||
let is_plane = matches!(kind, FeatureKind::ConstructionPlane { .. });
|
||||
if self.features.iter().any(|f| f.name == name && (is_plane || matches!(f.kind, FeatureKind::ConstructionPlane { .. }))) {
|
||||
return Err(DocError::Invalid(format!("another feature is called `{name}`")));
|
||||
}
|
||||
let id = self.next_id.max(1);
|
||||
self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?;
|
||||
let f = Feature {
|
||||
id,
|
||||
name,
|
||||
|
||||
+25
-2
@@ -4595,6 +4595,29 @@ pub fn revolve_extent_with_convention(
|
||||
symmetric: bool,
|
||||
to: Option<Vec3>,
|
||||
convention: crate::RevolveConvention,
|
||||
) -> Result<RevolveExtent> {
|
||||
let extent = revolve_extent_for_handle(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, convention)?;
|
||||
// A solid needs an open sweep inside one full turn. Zero and a turn past 360° keep a
|
||||
// handle frame (`revolve_extent_for_handle`) and still fail here, with the same message.
|
||||
if !(extent.sweep.abs() > 1e-9 && extent.sweep.abs() <= std::f64::consts::TAU + 1e-9) {
|
||||
return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into()));
|
||||
}
|
||||
Ok(extent)
|
||||
}
|
||||
|
||||
/// Where the angle handle sits. A sweep of zero, or past a full turn, builds no solid and
|
||||
/// [`revolve_extent_with_convention`] refuses it. The boundary is still a point on the circle,
|
||||
/// and the grab point stays there so the angle can be dragged back into range.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn revolve_extent_for_handle(
|
||||
st: &ModelState,
|
||||
plane: &Plane,
|
||||
regions: &[Region2],
|
||||
(origin, axis): (Vec3, Vec3),
|
||||
(angle, angle2): (f64, Option<f64>),
|
||||
symmetric: bool,
|
||||
to: Option<Vec3>,
|
||||
convention: crate::RevolveConvention,
|
||||
) -> Result<RevolveExtent> {
|
||||
let (start, sweep) = match (to, angle2, symmetric) {
|
||||
(Some(point), _, _) => {
|
||||
@@ -4634,7 +4657,7 @@ pub fn revolve_extent_with_convention(
|
||||
(None, None, true) => (-angle / 2.0, angle),
|
||||
(None, None, false) => (0.0, angle),
|
||||
};
|
||||
if !(sweep.is_finite() && start.is_finite() && sweep.abs() > 1e-9 && sweep.abs() <= std::f64::consts::TAU + 1e-9) {
|
||||
if !(sweep.is_finite() && start.is_finite()) {
|
||||
return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into()));
|
||||
}
|
||||
let points: Vec<Vec2> = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect();
|
||||
@@ -6563,7 +6586,7 @@ fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) ->
|
||||
}
|
||||
let note = if !crate::naming::face_name_exact(b, hit.face) && (face.centroid - at).dot(n).abs() > tol {
|
||||
// Named from geometry and moved off the picked plane: geometry alone decided.
|
||||
Some(format!("face `{name}` was found by geometry, not exact history; check it"))
|
||||
Some(format!("face `{}` was found by geometry, not exact history; check it", crate::name_lookup::quoted(name)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -174,6 +174,25 @@ fn joint_face_measurements_never_follow_a_replaced_body_or_stale_offset() {
|
||||
assert_eq!(work.joint_faces, 0, "offsets are applied after the shared face measurements");
|
||||
}
|
||||
|
||||
/// Every solve of a drag resolves its edge origins again: they share the joint faces' one
|
||||
/// measurement, as a face origin does, instead of tessellating the whole body each time.
|
||||
#[test]
|
||||
fn an_edge_origin_measures_its_faces_once() {
|
||||
use crate::joints::{JointOrigin, Snap};
|
||||
let doc = Document::new("edge origin");
|
||||
let mut state = ModelState::default();
|
||||
state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(), 0));
|
||||
let pick = Vec3::new(5.0, 0.0, 10.0);
|
||||
let origin = JointOrigin { occurrence: 0, snap: Snap::Edge { pick, edge: None, face: None, corner: None, axis: None } };
|
||||
let work = counted(|| {
|
||||
for _ in 0..8 {
|
||||
let frame = joints::resolve_origin(&doc, &state.clone(), &origin).unwrap();
|
||||
assert!(apply_point(&frame, Vec3::ZERO).dist(pick) < 1e-9);
|
||||
}
|
||||
});
|
||||
assert_eq!(work.joint_faces, 1, "a solve must not measure the faces again: {work:?}");
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
|
||||
@@ -50,7 +50,7 @@ fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option<usize> {
|
||||
fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> {
|
||||
let m = b.mesh();
|
||||
let beside: Vec<usize> = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default();
|
||||
let infos = b.body.faces(tol(b))?;
|
||||
let infos = b.joint_faces()?;
|
||||
let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area)));
|
||||
let chosen = match name {
|
||||
Some(n) => {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub use document::*;
|
||||
pub use eval::{
|
||||
EdgeRef, FeatureResult, KeptSeparate, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo,
|
||||
blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at,
|
||||
import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent,
|
||||
import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_for_handle,
|
||||
revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread,
|
||||
suggested_thread_in, tangent_face_chain, through_all_distance, world_state, world_state_reusing,
|
||||
};
|
||||
|
||||
@@ -184,7 +184,7 @@ enum Miss {
|
||||
impl FaceHit {
|
||||
/// What a feature says about how it found a face by its stored name `name` (`None`: exactly).
|
||||
pub fn note(&self, name: &str) -> Option<String> {
|
||||
if !self.verified && !self.on_point { Some(format!("face `{name}` was found by geometry, not exact history; check it")) } else { None }
|
||||
if !self.verified && !self.on_point { Some(format!("face `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,10 +287,26 @@ fn inside_nearest(m: &Mesh, face: usize, p: Vec3, margin: f64) -> Option<Vec3> {
|
||||
best.map(|(_, q)| q)
|
||||
}
|
||||
|
||||
/// A stored name as a message quotes it: whole up to about 80 characters, else its start and
|
||||
/// end around an ellipsis. Generated names grow with the history (a split edge's name holds both
|
||||
/// its faces' names), and a chamfer's warning that quoted fourteen of them in full ran to 122,701
|
||||
/// characters (#8541).
|
||||
pub(crate) fn quoted(name: &str) -> String {
|
||||
const HEAD: usize = 48;
|
||||
const TAIL: usize = 24;
|
||||
let n = name.chars().count();
|
||||
if n <= HEAD + TAIL + 8 {
|
||||
return name.to_string();
|
||||
}
|
||||
let head: String = name.chars().take(HEAD).collect();
|
||||
let tail: String = name.chars().skip(n - TAIL).collect();
|
||||
format!("{head}…{tail}")
|
||||
}
|
||||
|
||||
impl EdgeHit {
|
||||
/// What a feature says about how it found an edge by its stored name `name` (`None`: exactly).
|
||||
pub fn note(&self, name: &str) -> Option<String> {
|
||||
if !self.verified && !self.on_point { Some(format!("edge `{name}` was found by geometry, not exact history; check it")) } else { None }
|
||||
if !self.verified && !self.on_point { Some(format!("edge `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+33
-10
@@ -1846,8 +1846,9 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) {
|
||||
for i in 0..out.len() {
|
||||
let Some(LinkGeom::Arc { c, a, b }) = out.get(i).cloned() else { continue };
|
||||
let r = (c.dist(a) + c.dist(b)) / 2.0;
|
||||
// (arc end, line index, line end index, tangent point, unit normal towards the centre, centre distance)
|
||||
let mut hits: Vec<(usize, usize, usize, Vec2, Vec2, f64)> = Vec::new();
|
||||
// Per arc end: (gap to the line's end, line index, line end index, tangent point, unit
|
||||
// normal towards the centre, centre distance)
|
||||
let mut hits: [Vec<(f64, usize, usize, Vec2, Vec2, f64)>; 2] = [Vec::new(), Vec::new()];
|
||||
for (end, e) in [a, b].into_iter().enumerate() {
|
||||
for (j, g) in out.iter().enumerate() {
|
||||
let LinkGeom::Line(p, q) = g else { continue };
|
||||
@@ -1865,17 +1866,39 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) {
|
||||
if (foot - far).dot(near_pt - far) <= 0.0 || near_pt.dist(foot) > 0.25 * r {
|
||||
continue;
|
||||
}
|
||||
hits.push((end, j, near, foot, n, d));
|
||||
// When this end of the arc already meets another piece of the outline and the line
|
||||
// doesn't end there, the line lies further along (past that piece, as along a
|
||||
// conic fitted with several arcs): moving the end onto it would leave a gap.
|
||||
let gap = near_pt.dist(e);
|
||||
let meets = |g: &LinkGeom| match *g {
|
||||
LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => s.dist(e) <= tol || t.dist(e) <= tol,
|
||||
_ => false,
|
||||
};
|
||||
if gap > tol && out.iter().enumerate().any(|(k, g)| k != i && k != j && meets(g)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = hits.get_mut(end) {
|
||||
h.push((gap, j, near, foot, n, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [None, None];
|
||||
for (end, j, near, foot, n, d) in hits {
|
||||
if let Some(slot) = hits_by_end.get_mut(end)
|
||||
&& slot.is_none()
|
||||
{
|
||||
*slot = Some((j, near, foot, n, d));
|
||||
}
|
||||
for h in &mut hits {
|
||||
h.sort_by(|x, y| x.0.total_cmp(&y.0));
|
||||
}
|
||||
// Each end takes the line ending nearest it. Both ends on one line would pull the arc down
|
||||
// to a point: the end nearer that line's end keeps it, the other takes its next line.
|
||||
let [ha, hb] = &hits;
|
||||
let (ta, tb) = match (ha.first(), hb.first()) {
|
||||
(Some(x), Some(y)) if x.1 == y.1 => {
|
||||
if x.0 <= y.0 {
|
||||
(Some(x), hb.iter().find(|h| h.1 != x.1))
|
||||
} else {
|
||||
(ha.iter().find(|h| h.1 != y.1), Some(y))
|
||||
}
|
||||
}
|
||||
pair => pair,
|
||||
};
|
||||
let hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [ta, tb].map(|h| h.map(|&(_, j, near, foot, n, d)| (j, near, foot, n, d)));
|
||||
let (mut c, mut r) = (c, r);
|
||||
if let [Some((_, _, _, n1, d1)), Some((_, _, _, n2, d2))] = hits_by_end {
|
||||
// One circle tangent to both lines: equal distance to each.
|
||||
|
||||
@@ -255,6 +255,117 @@ mod tests {
|
||||
let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.get(1), out.get(2)) else { panic!("{out:?}") };
|
||||
assert!(a.dist(*p) < 1e-9, "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_snapping_leaves_a_line_further_along_alone() {
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::LinkGeom;
|
||||
let v = Vec2::new;
|
||||
let y = |x: f64| 2.0 - (4.0 - x * x).sqrt();
|
||||
// The arc's end at x = 0.5 already meets the next piece; the line along y = 0 ends at
|
||||
// x = 0.3, further along the outline the other way. Snapping onto it would pull the end
|
||||
// off the piece it meets.
|
||||
let mut out = vec![
|
||||
LinkGeom::Arc { c: v(0., 2.), a: v(0.5, y(0.5)), b: v(-1.5, y(-1.5)) },
|
||||
LinkGeom::Line(v(0.3, 0.), v(10., 0.)),
|
||||
LinkGeom::Line(v(0.5, y(0.5)), v(3., 3.)),
|
||||
];
|
||||
let before = out.clone();
|
||||
super::super::snap_tangent_arcs(&mut out, 0.05);
|
||||
assert_eq!(out.get(1), before.get(1), "{out:?}");
|
||||
let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.first(), out.get(2)) else { panic!("{out:?}") };
|
||||
assert!(a.dist(*p) < 1e-9, "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_snapping_gives_one_line_to_one_end_of_an_arc() {
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::LinkGeom;
|
||||
let v = Vec2::new;
|
||||
let y = |x: f64| 2.0 - (4.0 - x * x).sqrt();
|
||||
// A short arc whose two ends both lie near the end of one line: both snapping onto it
|
||||
// would shrink the arc to the tangent point.
|
||||
let mut out = vec![LinkGeom::Arc { c: v(0., 2.), a: v(-0.2, y(-0.2)), b: v(0.2, y(0.2)) }, LinkGeom::Line(v(-10., 0.), v(0., 0.))];
|
||||
super::super::snap_tangent_arcs(&mut out, 0.05);
|
||||
let Some(LinkGeom::Arc { a, b, .. }) = out.first() else { panic!("{out:?}") };
|
||||
assert!(a.dist(*b) > 0.1, "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_snapping_moves_the_other_end_of_an_arc_to_its_next_line() {
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::LinkGeom;
|
||||
let v = Vec2::new;
|
||||
let y = |x: f64| 2.0 - (4.0 - x * x).sqrt();
|
||||
let (a, b) = (v(-0.2, y(-0.2)), v(0.2, y(0.2)));
|
||||
// The line along y = 0 ends nearest both ends of the arc but nearer b, which keeps it; a
|
||||
// takes the next line, tangent to the circle at a and ending a little past it.
|
||||
let back = (v(0., 2.) - a).normalized().map(|n| v(-n.y, n.x)).unwrap_or(Vec2::X);
|
||||
let mut out =
|
||||
vec![LinkGeom::Arc { c: v(0., 2.), a, b }, LinkGeom::Line(v(0.1, 0.), v(10., 0.)), LinkGeom::Line(a + back * 10., a + back * 0.35)];
|
||||
super::super::snap_tangent_arcs(&mut out, 0.05);
|
||||
let (Some(LinkGeom::Arc { a, b, .. }), Some(LinkGeom::Line(p, _)), Some(LinkGeom::Line(_, q))) = (out.first(), out.get(1), out.get(2)) else {
|
||||
panic!("{out:?}")
|
||||
};
|
||||
assert!(b.dist(*p) < 1e-9 && a.dist(*q) < 1e-9 && a.dist(*b) > 0.1, "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_snapping_closes_a_conic_corner_in_any_order() {
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::LinkGeom;
|
||||
// A square of side 150 with a conic round of 10 mm legs at each corner, fitted with lines
|
||||
// and arcs the way a silhouette is, then snapped with the pieces in each order.
|
||||
for rho in [0.1, 0.15, 0.5, 0.8, 0.9] {
|
||||
let w = rho / (1. - rho);
|
||||
let conic = |s: Vec2, apex: Vec2, e: Vec2, t: f64| {
|
||||
let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t);
|
||||
(s * b0 + apex * b1 + e * b2) * (1. / (b0 + b1 + b2))
|
||||
};
|
||||
let v = Vec2::new;
|
||||
let corners = [
|
||||
(v(-75., 65.), v(-75., 75.), v(-65., 75.)),
|
||||
(v(65., 75.), v(75., 75.), v(75., 65.)),
|
||||
(v(75., -65.), v(75., -75.), v(65., -75.)),
|
||||
(v(-65., -75.), v(-75., -75.), v(-75., -65.)),
|
||||
];
|
||||
let mut chain = Vec::new();
|
||||
for (s, apex, e) in corners {
|
||||
chain.extend((0..=40).map(|k| conic(s, apex, e, f64::from(k) / 40.)));
|
||||
}
|
||||
if let Some(&first) = chain.first() {
|
||||
chain.push(first);
|
||||
}
|
||||
let mut fitted = Vec::new();
|
||||
super::super::fit_chain_with_arcs(&chain, Some(212. * 1e-5), &mut fitted, true);
|
||||
assert!(fitted.iter().any(|g| matches!(g, LinkGeom::Arc { .. })), "{fitted:?}");
|
||||
let ends = |g: &LinkGeom| match *g {
|
||||
LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => vec![s, t],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for k in 0..fitted.len() {
|
||||
let mut out = fitted.clone();
|
||||
out.rotate_left(k);
|
||||
super::super::snap_tangent_arcs(&mut out, 212. * 1e-3);
|
||||
// Every end still meets another piece's end. An end left without a line moves a little
|
||||
// when the arc's radius is set from the lines (well under 0.01 mm here); before, ends
|
||||
// pulled onto lines further along left gaps of 0.25 to 0.55 mm.
|
||||
for (i, g) in out.iter().enumerate() {
|
||||
for e in ends(g) {
|
||||
let gap = out
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| *j != i)
|
||||
.flat_map(|(_, h)| ends(h))
|
||||
.map(|x| x.dist(e))
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(gap < 212. * 1e-3 * 0.02, "rho {rho}, rotation {k}: gap {gap} at {e:?}: {out:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundaries_touching_at_a_vertex_project() {
|
||||
// Two squares of one face family meet only at the corner (1, 1): four boundary edges meet
|
||||
|
||||
@@ -160,6 +160,21 @@ fn results_kept_ahead_outlive_the_cache() {
|
||||
assert!(rel(measure(&m.state().bodies[0].body).unwrap().volume, 30000.0) < 1e-9);
|
||||
}
|
||||
|
||||
/// A warning quotes a long generated name by its start and end (#8541: fourteen split edges'
|
||||
/// full names made one chamfer warning 122,701 characters long); a short name stays whole.
|
||||
#[test]
|
||||
fn warnings_quote_long_names_by_their_ends() {
|
||||
let face = |i: usize| format!("Extrude{i}.side(Sketch{i}.l{i})·Fillet{i}.blend(Chamfer{i}.cap)");
|
||||
let long = (0..40).map(face).collect::<Vec<_>>().join("|");
|
||||
let q = crate::name_lookup::quoted(&long);
|
||||
assert!(q.chars().count() <= 80, "{q}");
|
||||
assert!(q.starts_with("Extrude0.side") && q.ends_with(&long[long.len() - 10..]) && q.contains('…'), "{q}");
|
||||
assert_eq!(crate::name_lookup::quoted("Extrude1.side|Box1.top"), "Extrude1.side|Box1.top");
|
||||
// Characters, not bytes: a name of non-ASCII characters is cut between characters.
|
||||
let wide = "Ü".repeat(200);
|
||||
assert_eq!(crate::name_lookup::quoted(&wide).chars().count(), 73);
|
||||
}
|
||||
|
||||
/// A saved model whose feature warning is longer than 65,536 characters is still taken on open
|
||||
/// (#8541): Save writes it, so Open reads it.
|
||||
#[test]
|
||||
@@ -659,6 +674,28 @@ fn new_names_take_the_first_free_number() {
|
||||
assert_eq!(name(&doc, next), names[0], "the first freed number is taken again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_plane_name_collisions_leave_the_document_unchanged() {
|
||||
let plane = || FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XY".into() } };
|
||||
let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() };
|
||||
for (first, second) in [(plane(), plane()), (plane(), sketch()), (sketch(), plane())] {
|
||||
let mut doc = Document::new("names");
|
||||
let id = doc.add_feature(first, Some("Mid")).unwrap();
|
||||
// A suppressed feature beyond the marker still owns its name.
|
||||
doc.feature_mut(id).unwrap().suppressed = true;
|
||||
doc.marker = Some(0);
|
||||
let before = doc.clone();
|
||||
for name in ["Mid", " Mid "] {
|
||||
let error = doc.add_feature(second.clone(), Some(name)).unwrap_err().to_string();
|
||||
assert!(error.contains("another feature is called `Mid`"), "{error}");
|
||||
assert_eq!(doc, before, "a refused name must not consume an id or change the timeline");
|
||||
}
|
||||
let other = doc.add_feature(second, Some("Upper")).unwrap();
|
||||
assert_eq!(doc.feature(other).unwrap().name, "Upper");
|
||||
assert_eq!(other, before.next_id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_boolean_targets_name_overlapping_component() {
|
||||
for (operation, offset) in [(Operation::Cut, 0.0), (Operation::Intersect, 0.0), (Operation::Cut, 40.0)] {
|
||||
@@ -974,3 +1011,19 @@ fn browser_data_survives_a_save_and_old_designs_read_unchanged() {
|
||||
assert_eq!(resaved["browser_groups"], groups, "{order}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #10748: verify that type names map to their canonical design-file kind keys.
|
||||
#[test]
|
||||
fn feature_kind_key_and_type_name_mappings() {
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("HoleFeature"), Some("hole"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("BoxFeature"), Some("box"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("EdgeFlangeFeature"), Some("sheet_flange"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("RectangularPatternFeature"), Some("pattern"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("PathPatternFeature"), Some("pattern"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("CircularPatternFeature"), Some("pattern"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("ExtrudeFeature"), Some("extrude"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("SplitBodyFeature"), Some("split"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("BaseFeature"), Some("import"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("MeshFeature"), Some("mesh_import"));
|
||||
assert_eq!(FeatureKind::type_name_to_kind_key("NonExistent"), None);
|
||||
}
|
||||
@@ -44,6 +44,7 @@ solidcraft-doc = { workspace = true }
|
||||
solidcraft-io = { workspace = true }
|
||||
solidcraft-render = { workspace = true }
|
||||
solidcraft-profile = { workspace = true }
|
||||
# reference pictures for inspect.compare_picture (PNG and JPEG decode, PNG encode)
|
||||
image = { workspace = true, features = ["jpeg"] }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,692 @@
|
||||
//! Compare the model with a reference picture (#1486): agents model to a picture, and an
|
||||
//! overlap score plus per-edge mm offsets tell the agent which edge to move and by how much.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::io::Cursor;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::canvas::base64_encode;
|
||||
|
||||
use super::CommandSpec;
|
||||
use super::silhouette::{self, Silhouette};
|
||||
use crate::params::bad;
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CMD: &str = "inspect.compare_picture";
|
||||
/// A reference picture is read through the vfs with a byte cap, like `screenshot` output.
|
||||
const MAX_REFERENCE_BYTES: usize = 32 << 20;
|
||||
/// Decoded pixels are capped as well, so a small file cannot unfold into a huge raster.
|
||||
const MAX_DECODED_PIXELS: u64 = 16 << 20;
|
||||
/// The comparison grid each mask is fitted into at most — the picture's and the fitted
|
||||
/// model's alike; keeps the slide search and the memory it needs bounded.
|
||||
const MAX_GRID: usize = 1024;
|
||||
/// Background grows from the border only through steps of at most this per channel, so a
|
||||
/// backdrop's gradual shading belongs to it and the step at the part's outline stops it.
|
||||
const BG_STEP: u16 = 12;
|
||||
/// When the first pass finds no part, the flood retries at this stricter step: a white part
|
||||
/// on a (245, 245, 245) studio backdrop is a step of 10, which BG_STEP lets through.
|
||||
const BG_STEP_STRICT: u16 = 4;
|
||||
/// A picture whose border is mostly transparent: a pixel below this alpha is see-through.
|
||||
const ALPHA_BG: u8 = 128;
|
||||
/// The global retry's backdrop: a pixel within this of the border's main colour is
|
||||
/// background. A light JPEG (white on (245, 245, 245) at quality 75) blurs the step at the
|
||||
/// part's outline below any local limit, so that pass compares to the backdrop's colour.
|
||||
const BG_NEAR: u16 = 8;
|
||||
/// Stations per side for the edge offsets.
|
||||
const STATIONS: usize = 9;
|
||||
|
||||
// For agents modelling to a picture; nothing to show a person, so no toolbar button.
|
||||
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Compare Picture", run).noundo().icon("compare").params(
|
||||
"reference: path to a PNG or JPEG the model should match; view?/camera?/bodies?/rows? as inspect.silhouette; \
|
||||
crop_px?: [x, y, w, h] in pixels, or crop_fraction?: [x, y, w, h] as fractions 0..1 of the picture \
|
||||
(to take one view off a board); part_fills_crop?: false — with true the crop box is the part itself \
|
||||
and no background search runs, for a crop that tightly frames the part; \
|
||||
fit?: \"width\" | \"height\" | \"both\" (default \"width\"): one uniform scale, taken from the named \
|
||||
dimension (\"both\" claims both and scales by width, reporting aspect_mismatch when the shapes differ); \
|
||||
overlay?: false leaves the overlay PNG out → overlap (0..1), edges: top|bottom|left|right in mm at nine stations \
|
||||
(positive where the model reaches past the picture, null where a station misses one of the two), the grid and its \
|
||||
mm_per_px, and overlay_png (red model, blue picture) as base64 PNG. The compare is outline only: \
|
||||
holes are not compared — both the picture's and the model's holes are filled",
|
||||
)];
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reference = p
|
||||
.get("reference")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.ok_or_else(|| bad(CMD, "`reference` is required: a path to a PNG or JPEG"))?;
|
||||
let fit = match p.get("fit") {
|
||||
None => Fit::Width,
|
||||
Some(Value::String(v)) => match v.as_str() {
|
||||
"width" => Fit::Width,
|
||||
"height" => Fit::Height,
|
||||
"both" => Fit::Both,
|
||||
other => return Err(bad(CMD, format!("`fit` must be \"width\", \"height\" or \"both\", not `{other}`"))),
|
||||
},
|
||||
Some(_) => return Err(bad(CMD, "`fit` must be a string")),
|
||||
};
|
||||
let overlay = p.get("overlay").map(|v| v.as_bool().unwrap_or(false)).unwrap_or(true);
|
||||
let part_fills_crop = p.get("part_fills_crop").and_then(Value::as_bool).unwrap_or(false);
|
||||
|
||||
// The model side: the same outline inspect.silhouette returns, as filled rows.
|
||||
let camera = silhouette::camera(p)?;
|
||||
let rows = silhouette::rows(p)?;
|
||||
let wanted = silhouette::body_names(p)?;
|
||||
let model = silhouette::outline(s, &camera, wanted.as_deref(), rows)?;
|
||||
|
||||
// The picture side: decode, crop, and find the part.
|
||||
let bytes = solidcraft_io::vfs::read(reference, MAX_REFERENCE_BYTES).map_err(|e| bad(CMD, format!("{reference}: {e}")))?;
|
||||
let img = decode(&bytes)?;
|
||||
let img = apply_crop(img, p.get("crop_px"), p.get("crop_fraction"))?;
|
||||
let picture = if part_fills_crop {
|
||||
part_from_box(&img).map_err(|reason| bad(CMD, format!("the crop cannot be the part: {reason}")))?
|
||||
} else {
|
||||
find_part(&img).map_err(|reason| bad(CMD, format!("no part found in the picture: {reason}")))?
|
||||
};
|
||||
|
||||
// Fit the model outline to the picture's scale, then slide it to the best overlap.
|
||||
let (mw, mh, mmpp_x, mmpp_y) = fit_model(&model, picture.width, picture.height, fit);
|
||||
let mut model_scaled = resample(&model.mask, model.width, model.height, mw, mh);
|
||||
// The same hole rule the picture side has: a through-hole in the model counts as its
|
||||
// outline, not as a hole the picture has to match.
|
||||
fill_holes(&mut model_scaled);
|
||||
let best = best_overlap(&model_scaled, &picture);
|
||||
let placed = Placed { dx: best.dx, dy: best.dy, mask: &model_scaled };
|
||||
let aspect_mismatch = (picture.width as f64 * mh as f64) / (picture.height as f64 * mw as f64);
|
||||
|
||||
let mut out = json!({
|
||||
"overlap": round4(best.overlap),
|
||||
"stations": STATIONS,
|
||||
"edges": {
|
||||
"top": edge_offsets(&placed, &picture, Edge::Top, mmpp_y),
|
||||
"bottom": edge_offsets(&placed, &picture, Edge::Bottom, mmpp_y),
|
||||
"left": edge_offsets(&placed, &picture, Edge::Left, mmpp_x),
|
||||
"right": edge_offsets(&placed, &picture, Edge::Right, mmpp_x),
|
||||
},
|
||||
"fit": match fit { Fit::Width => "width", Fit::Height => "height", Fit::Both => "both" },
|
||||
"aspect_mismatch": round4(aspect_mismatch),
|
||||
"mm_per_px": {"x": round4(mmpp_x), "y": round4(mmpp_y)},
|
||||
"model": {"width": model.width, "height": model.height, "box_mm": [[round4(model.lo[0]), round4(model.lo[1])], [round4(model.hi[0]), round4(model.hi[1])]], "bodies": model.bodies},
|
||||
"picture": {"width": picture.width, "height": picture.height, "source": reference},
|
||||
});
|
||||
if overlay {
|
||||
out["overlay_png"] = json!(base64_encode(&overlay_png(&picture, &placed)));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Fit {
|
||||
Width,
|
||||
Height,
|
||||
Both,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Edge {
|
||||
Top,
|
||||
Bottom,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// A picture mask, tightly framed to the found part.
|
||||
struct Part {
|
||||
width: usize,
|
||||
height: usize,
|
||||
mask: Vec<Vec<bool>>,
|
||||
}
|
||||
|
||||
/// A model mask placed relative to the picture: its top-left sits at (dx, dy) in the
|
||||
/// picture's own pixel coordinates, which may be negative.
|
||||
struct Placed<'a> {
|
||||
dx: i64,
|
||||
dy: i64,
|
||||
mask: &'a [Vec<bool>],
|
||||
}
|
||||
|
||||
/// Decode PNG or JPEG to RGBA8, refusing anything else and anything that unfolds too large.
|
||||
fn decode(bytes: &[u8]) -> Result<image::RgbaImage> {
|
||||
let guess = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?;
|
||||
if !matches!(guess.format(), Some(image::ImageFormat::Png) | Some(image::ImageFormat::Jpeg)) {
|
||||
return Err(bad(CMD, "the reference must be a PNG or a JPEG"));
|
||||
}
|
||||
let (w, h) = guess.into_dimensions().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?;
|
||||
if w as u64 * h as u64 > MAX_DECODED_PIXELS {
|
||||
return Err(bad(CMD, format!("the picture is {w}x{h}: over the {} megapixel limit", MAX_DECODED_PIXELS >> 20)));
|
||||
}
|
||||
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?;
|
||||
let img = reader.decode().map_err(|e| bad(CMD, format!("cannot decode the picture: {e}")))?;
|
||||
Ok(img.to_rgba8())
|
||||
}
|
||||
|
||||
/// Apply `crop_px: [x, y, w, h]` (pixels) or `crop_fraction: [x, y, w, h]` (fractions 0..1
|
||||
/// of the picture). Explicit units: a crop of `[0, 0, 1, 1]` means one pixel, not the whole.
|
||||
fn apply_crop(img: image::RgbaImage, crop_px: Option<&Value>, crop_fraction: Option<&Value>) -> Result<image::RgbaImage> {
|
||||
match (crop_px, crop_fraction) {
|
||||
(Some(_), Some(_)) => Err(bad(CMD, "give `crop_px` or `crop_fraction`, not both")),
|
||||
(None, None) => Ok(img),
|
||||
(Some(v), None) => {
|
||||
let nums = crop_nums(v, "crop_px")?;
|
||||
let (w, h) = img.dimensions();
|
||||
crop_to(img, nums[0].round() as usize, nums[1].round() as usize, nums[2].round() as usize, nums[3].round() as usize, w, h)
|
||||
}
|
||||
(None, Some(v)) => {
|
||||
let nums = crop_nums(v, "crop_fraction")?;
|
||||
if nums.iter().any(|f| *f > 1.0) {
|
||||
return Err(bad(CMD, "`crop_fraction` values must be 0..1"));
|
||||
}
|
||||
let (w, h) = img.dimensions();
|
||||
crop_to(
|
||||
img,
|
||||
(nums[0] * w as f64).round() as usize,
|
||||
(nums[1] * h as f64).round() as usize,
|
||||
(nums[2] * w as f64).round() as usize,
|
||||
(nums[3] * h as f64).round() as usize,
|
||||
w,
|
||||
h,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn crop_nums(v: &Value, name: &str) -> Result<Vec<f64>> {
|
||||
let nums: Vec<f64> = v
|
||||
.as_array()
|
||||
.filter(|a| a.len() == 4)
|
||||
.and_then(|a| a.iter().map(|v| v.as_f64()).collect())
|
||||
.ok_or_else(|| bad(CMD, format!("`{name}` must be [x, y, w, h]")))?;
|
||||
if nums.iter().any(|v| !v.is_finite() || *v < 0.0) {
|
||||
return Err(bad(CMD, format!("`{name}` values must be non-negative")));
|
||||
}
|
||||
Ok(nums)
|
||||
}
|
||||
|
||||
fn crop_to(img: image::RgbaImage, x: usize, y: usize, cw: usize, ch: usize, w: u32, h: u32) -> Result<image::RgbaImage> {
|
||||
if x >= w as usize || y >= h as usize {
|
||||
return Err(bad(CMD, "the crop starts outside the picture"));
|
||||
}
|
||||
let cw = cw.max(1).min(w as usize - x);
|
||||
let ch = ch.max(1).min(h as usize - y);
|
||||
Ok(image::imageops::crop_imm(&img, x as u32, y as u32, cw as u32, ch as u32).to_image())
|
||||
}
|
||||
|
||||
/// Find the part. Alpha decides only when the backdrop really is transparent — most border
|
||||
/// pixels see-through — so one stray translucent pixel cannot switch the read; then any ink
|
||||
/// is part, so a part drawn at a faint alpha survives. Otherwise grow the background in from
|
||||
/// the border through small colour steps only — seeded from the border pixels close to the
|
||||
/// border's main colour, so a part touching the border is not eaten by its own edge — keep
|
||||
/// what the background did not reach, and keep the largest 4-connected piece. On a retry the
|
||||
/// step is stricter, so a white part on a (245, 245, 245) backdrop (a step of 10) still
|
||||
/// separates; on a second retry the backdrop is taken globally — within BG_NEAR of the
|
||||
/// border's main colour — because a light JPEG blurs the step at the part's outline below
|
||||
/// any local limit. Says which happened when no part is found.
|
||||
fn find_part(img: &image::RgbaImage) -> std::result::Result<Part, String> {
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
if w < 2 || h < 2 {
|
||||
return Err("the picture is smaller than 2 x 2 pixels".to_string());
|
||||
}
|
||||
let px = |x: usize, y: usize| -> [u16; 3] {
|
||||
let p = img.get_pixel(x as u32, y as u32).0;
|
||||
[p[0] as u16, p[1] as u16, p[2] as u16]
|
||||
};
|
||||
let step = |a: [u16; 3], b: [u16; 3]| (a[0].abs_diff(b[0])).max(a[1].abs_diff(b[1])).max(a[2].abs_diff(b[2]));
|
||||
|
||||
// Alpha decides only when the border is mostly see-through: a single backdrop pixel at
|
||||
// alpha 254 in an otherwise opaque picture must not turn the whole read into alpha.
|
||||
let mut border = 0usize;
|
||||
let mut see_through = 0usize;
|
||||
for x in 0..w {
|
||||
for y in [0, h - 1] {
|
||||
border += 1;
|
||||
if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG {
|
||||
see_through += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in [0, w - 1] {
|
||||
border += 1;
|
||||
if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG {
|
||||
see_through += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let uses_alpha = see_through * 2 > border;
|
||||
|
||||
let (part, too_small): (Vec<bool>, String) = if uses_alpha {
|
||||
let mask: Vec<bool> = img.pixels().map(|p| p[3] > 0).collect();
|
||||
(mask, "the picture is transparent: no pixel holds any ink".to_string())
|
||||
} else {
|
||||
let bg = flood_background(&px, w, h, BG_STEP, &step);
|
||||
let mask: Vec<bool> = (0..w * h).map(|i| !bg[i]).collect();
|
||||
if largest_piece(&mask, w, h).len() >= 16 {
|
||||
(mask, "the picture holds no piece big enough to be a part".to_string())
|
||||
} else {
|
||||
let bg = flood_background(&px, w, h, BG_STEP_STRICT, &step);
|
||||
let mask: Vec<bool> = (0..w * h).map(|i| !bg[i]).collect();
|
||||
if largest_piece(&mask, w, h).len() >= 16 {
|
||||
(mask, "the picture holds no piece big enough to be a part".to_string())
|
||||
} else {
|
||||
// The local step fails on a light JPEG: the codec blurs the 10-level step
|
||||
// at the part's outline into steps of a few levels each, under any limit.
|
||||
// Take the backdrop globally instead: near the border's main colour.
|
||||
let main = border_main_colour(&px, w, h);
|
||||
let mask: Vec<bool> = (0..w * h).map(|i| step(main, px(i % w, i / w)) > BG_NEAR).collect();
|
||||
(mask, "the background grew from the border over the whole picture, even with a stricter colour step: the part's colour is too close to the backdrop's".to_string())
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let best = largest_piece(&part, w, h);
|
||||
if best.len() < 16 {
|
||||
return Err(too_small);
|
||||
}
|
||||
// Tight frame, then downscale to the comparison grid at need.
|
||||
let (x0, y0, x1, y1) = frame(&best, w);
|
||||
let (pw, ph) = (x1 - x0 + 1, y1 - y0 + 1);
|
||||
let mut mask = vec![vec![false; pw]; ph];
|
||||
for &i in &best {
|
||||
let (x, y) = (i % w, i / w);
|
||||
mask[y - y0][x - x0] = true;
|
||||
}
|
||||
let (dw, dh) = fit_grid(pw, ph);
|
||||
let mut mask = if (dw, dh) == (pw, ph) { mask } else { resample(&mask, pw, ph, dw, dh) };
|
||||
fill_holes(&mut mask);
|
||||
Ok(Part { width: dw, height: dh, mask })
|
||||
}
|
||||
|
||||
/// The crop box is the part itself (`part_fills_crop`): no background search. This is how
|
||||
/// one view cropped tight off a board says so — a part touching three sides leaves the
|
||||
/// border's main colour the part's own, and the flood would keep the backdrop strip instead.
|
||||
fn part_from_box(img: &image::RgbaImage) -> std::result::Result<Part, String> {
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
if w < 2 || h < 2 {
|
||||
return Err("the crop is smaller than 2 x 2 pixels".to_string());
|
||||
}
|
||||
let (dw, dh) = fit_grid(w, h);
|
||||
Ok(Part { width: dw, height: dh, mask: vec![vec![true; dw]; dh] })
|
||||
}
|
||||
|
||||
/// The border's main colour: the border colour it has most of. A part crossing the border
|
||||
/// is in the border too, but the backdrop is what most of the border shows.
|
||||
fn border_main_colour(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize) -> [u16; 3] {
|
||||
let mut counts: HashMap<[u16; 3], usize> = HashMap::new();
|
||||
for x in 0..w {
|
||||
for y in [0, h - 1] {
|
||||
*counts.entry(px(x, y)).or_default() += 1;
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in [0, w - 1] {
|
||||
*counts.entry(px(x, y)).or_default() += 1;
|
||||
}
|
||||
}
|
||||
counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 3])
|
||||
}
|
||||
|
||||
/// The background mask: grown from every border pixel whose colour is close to the border's
|
||||
/// main colour, crossing only steps of at most `limit` per channel.
|
||||
fn flood_background(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize, limit: u16, step: &impl Fn([u16; 3], [u16; 3]) -> u16) -> Vec<bool> {
|
||||
let main = border_main_colour(px, w, h);
|
||||
|
||||
let mut bg = vec![false; w * h];
|
||||
let mut queue: VecDeque<(usize, usize)> = VecDeque::new();
|
||||
let mut seed = |x: usize, y: usize| {
|
||||
if step(main, px(x, y)) <= limit && !bg[y * w + x] {
|
||||
bg[y * w + x] = true;
|
||||
queue.push_back((x, y));
|
||||
}
|
||||
};
|
||||
for x in 0..w {
|
||||
seed(x, 0);
|
||||
seed(x, h - 1);
|
||||
}
|
||||
for y in 0..h {
|
||||
seed(0, y);
|
||||
seed(w - 1, y);
|
||||
}
|
||||
while let Some((x, y)) = queue.pop_front() {
|
||||
let here = px(x, y);
|
||||
for (nx, ny) in neighbours(x, y, w, h) {
|
||||
if !bg[ny * w + nx] && step(here, px(nx, ny)) <= limit {
|
||||
bg[ny * w + nx] = true;
|
||||
queue.push_back((nx, ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
bg
|
||||
}
|
||||
|
||||
/// The largest 4-connected piece of a mask, as indices into `w`-wide rows.
|
||||
fn largest_piece(mask: &[bool], w: usize, h: usize) -> Vec<usize> {
|
||||
let mut best: Vec<usize> = Vec::new();
|
||||
let mut seen = vec![false; w * h];
|
||||
for start in 0..w * h {
|
||||
if !mask[start] || seen[start] {
|
||||
continue;
|
||||
}
|
||||
let mut piece: Vec<usize> = Vec::new();
|
||||
let mut queue: VecDeque<usize> = VecDeque::new();
|
||||
seen[start] = true;
|
||||
queue.push_back(start);
|
||||
while let Some(i) = queue.pop_front() {
|
||||
piece.push(i);
|
||||
let (x, y) = (i % w, i / w);
|
||||
for (nx, ny) in neighbours(x, y, w, h) {
|
||||
let j = ny * w + nx;
|
||||
if mask[j] && !seen[j] {
|
||||
seen[j] = true;
|
||||
queue.push_back(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
if piece.len() > best.len() {
|
||||
best = piece;
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Fill the holes: pixels the outside never reaches become part — the rule the picture's
|
||||
/// border flood gives the picture side for free, given to the model's mask as well.
|
||||
fn fill_holes(mask: &mut [Vec<bool>]) {
|
||||
let (h, w) = (mask.len(), mask.first().map_or(0, Vec::len));
|
||||
if w < 2 || h < 2 {
|
||||
return;
|
||||
}
|
||||
let mut outside = vec![false; w * h];
|
||||
let mut queue: VecDeque<usize> = VecDeque::new();
|
||||
for x in 0..w {
|
||||
for y in [0, h - 1] {
|
||||
if !mask[y][x] && !outside[y * w + x] {
|
||||
outside[y * w + x] = true;
|
||||
queue.push_back(y * w + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in [0, w - 1] {
|
||||
if !mask[y][x] && !outside[y * w + x] {
|
||||
outside[y * w + x] = true;
|
||||
queue.push_back(y * w + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some(i) = queue.pop_front() {
|
||||
let (x, y) = (i % w, i / w);
|
||||
for (nx, ny) in neighbours(x, y, w, h) {
|
||||
let j = ny * w + nx;
|
||||
if !mask[ny][nx] && !outside[j] {
|
||||
outside[j] = true;
|
||||
queue.push_back(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if !mask[y][x] && !outside[y * w + x] {
|
||||
mask[y][x] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn neighbours(x: usize, y: usize, w: usize, h: usize) -> impl Iterator<Item = (usize, usize)> {
|
||||
[(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)].into_iter().filter(move |(nx, ny)| *nx < w && *ny < h)
|
||||
}
|
||||
|
||||
fn frame(pixels: &[usize], w: usize) -> (usize, usize, usize, usize) {
|
||||
let mut x0 = usize::MAX;
|
||||
let mut y0 = usize::MAX;
|
||||
let mut x1 = 0;
|
||||
let mut y1 = 0;
|
||||
for &i in pixels {
|
||||
let (x, y) = (i % w, i / w);
|
||||
x0 = x0.min(x);
|
||||
y0 = y0.min(y);
|
||||
x1 = x1.max(x);
|
||||
y1 = y1.max(y);
|
||||
}
|
||||
(x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
fn fit_grid(w: usize, h: usize) -> (usize, usize) {
|
||||
let scale = (MAX_GRID as f64 / w.max(h) as f64).min(1.0);
|
||||
(((w as f64 * scale).round() as usize).max(2), ((h as f64 * scale).round() as usize).max(2))
|
||||
}
|
||||
|
||||
/// Nearest-neighbour resample of a mask to (w1, h1).
|
||||
fn resample(mask: &[Vec<bool>], w0: usize, h0: usize, w1: usize, h1: usize) -> Vec<Vec<bool>> {
|
||||
(0..h1)
|
||||
.map(|y| {
|
||||
let row = &mask[((y * h0) / h1.max(1)).min(h0 - 1)];
|
||||
(0..w1).map(|x| row[((x * w0) / w1.max(1)).min(w0 - 1)]).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The model outline's size in picture pixels and the mm per pixel that follows. One
|
||||
/// uniform scale, taken from the dimension the two share — the axes are never stretched
|
||||
/// apart, which would hide the very mismatch the tool is for. `both` claims both dimensions
|
||||
/// and scales by width; the result's `aspect_mismatch` says how far the shapes are apart.
|
||||
/// The fitted size takes the same MAX_GRID cap as the picture's: a narrow model fitted by
|
||||
/// width against a wide picture would otherwise ask for hundreds of megabytes of mask.
|
||||
fn fit_model(model: &Silhouette, pw: usize, ph: usize, fit: Fit) -> (usize, usize, f64, f64) {
|
||||
let s = match fit {
|
||||
Fit::Width | Fit::Both => pw as f64 / model.width as f64,
|
||||
Fit::Height => ph as f64 / model.height as f64,
|
||||
};
|
||||
let mw = ((model.width as f64 * s).round() as usize).max(2);
|
||||
let mh = ((model.height as f64 * s).round() as usize).max(2);
|
||||
let (mw, mh) = fit_grid(mw, mh);
|
||||
(mw, mh, model.width as f64 * model.mm_per_px / mw as f64, model.height as f64 * model.mm_per_px / mh as f64)
|
||||
}
|
||||
|
||||
struct Best {
|
||||
overlap: f64,
|
||||
dx: i64,
|
||||
dy: i64,
|
||||
}
|
||||
|
||||
/// Slide the model mask over the picture mask to the best intersection-over-union. The
|
||||
/// coarse pass covers the whole range of placements where the two frames can share a
|
||||
/// pixel — a tenth of the picture around the centre is not enough when the heights differ —
|
||||
/// and the fine pass walks every offset around its winner.
|
||||
fn best_overlap(model: &[Vec<bool>], picture: &Part) -> Best {
|
||||
let pic = spans_of(&picture.mask);
|
||||
let mdl = spans_of(model);
|
||||
let model_area: i64 = mdl.iter().flatten().map(|[a, b]| (b - a) as i64).sum();
|
||||
let pic_area: i64 = pic.iter().flatten().map(|[a, b]| (b - a) as i64).sum();
|
||||
|
||||
let (mw, mh) = (model[0].len() as i64, model.len() as i64);
|
||||
let (lo_x, hi_x) = (1 - mw, picture.width as i64);
|
||||
let (lo_y, hi_y) = (1 - mh, picture.height as i64);
|
||||
// About 64 coarse samples per axis, never finer than 4 px, never coarser than 32.
|
||||
let step_x = ((hi_x - lo_x) / 64).clamp(4, 32);
|
||||
let step_y = ((hi_y - lo_y) / 64).clamp(4, 32);
|
||||
|
||||
// The frames' aligned corners: both masks are tightly framed, so the best placement of a
|
||||
// matching picture is at or near here.
|
||||
let (mut bx, mut by) = (0i64, 0i64);
|
||||
for round in 0..2 {
|
||||
// Coarse: the whole range at the step; fine: every offset within one coarse step
|
||||
// of the coarse winner.
|
||||
let (sx, sy, x0, x1, y0, y1) = if round == 0 {
|
||||
(step_x, step_y, lo_x, hi_x, lo_y, hi_y)
|
||||
} else {
|
||||
(1, 1, (bx - step_x).max(lo_x), (bx + step_x).min(hi_x), (by - step_y).max(lo_y), (by + step_y).min(hi_y))
|
||||
};
|
||||
let (mut best_score, mut best_x, mut best_y) = (i64::MIN, bx, by);
|
||||
let mut dy = y0;
|
||||
while dy <= y1 {
|
||||
let mut dx = x0;
|
||||
while dx <= x1 {
|
||||
let hits = intersection(&mdl, &pic, dx, dy);
|
||||
let union = model_area + pic_area - hits;
|
||||
let score = if union <= 0 { i64::MIN } else { hits * 1_000_000 / union };
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best_x = dx;
|
||||
best_y = dy;
|
||||
}
|
||||
dx += sx;
|
||||
}
|
||||
dy += sy;
|
||||
}
|
||||
bx = best_x;
|
||||
by = best_y;
|
||||
}
|
||||
|
||||
let hits = intersection(&mdl, &pic, bx, by);
|
||||
let union = model_area + pic_area - hits;
|
||||
Best { overlap: if union <= 0 { 0.0 } else { hits as f64 / union as f64 }, dx: bx, dy: by }
|
||||
}
|
||||
|
||||
fn spans_of(mask: &[Vec<bool>]) -> Vec<Vec<[usize; 2]>> {
|
||||
mask.iter().map(|row| silhouette::spans(row)).collect()
|
||||
}
|
||||
|
||||
/// Pixels the model shares with the picture at model offset (dx, dy), from run-length rows.
|
||||
fn intersection(mdl: &[Vec<[usize; 2]>], pic: &[Vec<[usize; 2]>], dx: i64, dy: i64) -> i64 {
|
||||
let mut hits = 0i64;
|
||||
for (r, spans) in mdl.iter().enumerate() {
|
||||
if spans.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(y) = (dy + r as i64).try_into().ok().and_then(|y: usize| pic.get(y)) else { continue };
|
||||
if y.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for &[a, b] in spans {
|
||||
let (mut lo, hi) = ((a as i64 + dx).max(0), b as i64 + dx);
|
||||
if hi <= lo {
|
||||
continue;
|
||||
}
|
||||
for &[pa, pb] in y {
|
||||
let (s, e) = (lo.max(pa as i64), hi.min(pb as i64));
|
||||
if e > s {
|
||||
hits += e - s;
|
||||
}
|
||||
lo = lo.max(pb as i64);
|
||||
if lo >= hi || pb as i64 >= hi {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// The model's edge against the picture's, in mm, at nine stations along one side; positive
|
||||
/// where the model reaches past the picture, null where a station misses one of the two.
|
||||
fn edge_offsets(model: &Placed, picture: &Part, side: Edge, mmpp: f64) -> Vec<Value> {
|
||||
(1..=STATIONS)
|
||||
.map(|i| {
|
||||
let station = match side {
|
||||
Edge::Top | Edge::Bottom => (picture.width as u64 * i as u64 / (STATIONS as u64 + 1)) as usize,
|
||||
Edge::Left | Edge::Right => (picture.height as u64 * i as u64 / (STATIONS as u64 + 1)) as usize,
|
||||
};
|
||||
let offset = match side {
|
||||
Edge::Top | Edge::Bottom => {
|
||||
let pic = column_edge(&picture.mask, station, matches!(side, Edge::Top));
|
||||
let mdl = (station as i64 - model.dx)
|
||||
.try_into()
|
||||
.ok()
|
||||
.and_then(|mx: usize| column_edge(model.mask, mx, matches!(side, Edge::Top)))
|
||||
.map(|e| e as i64 + model.dy);
|
||||
match (mdl, pic) {
|
||||
(Some(m), Some(p)) => Some(match side {
|
||||
Edge::Top => (p as f64 - m as f64) * mmpp,
|
||||
_ => (m as f64 - p as f64) * mmpp,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Edge::Left | Edge::Right => {
|
||||
let pic = row_edge(&picture.mask, station, matches!(side, Edge::Left));
|
||||
let mdl = (station as i64 - model.dy)
|
||||
.try_into()
|
||||
.ok()
|
||||
.and_then(|my: usize| row_edge(model.mask, my, matches!(side, Edge::Left)))
|
||||
.map(|e| e as i64 + model.dx);
|
||||
match (mdl, pic) {
|
||||
(Some(m), Some(p)) => Some(match side {
|
||||
Edge::Left => (p as f64 - m as f64) * mmpp,
|
||||
_ => (m as f64 - p as f64) * mmpp,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
offset.map(|mm| json!(round3(mm))).unwrap_or(Value::Null)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first (or last, when `first` is false) row holding column `x`; None if none does.
|
||||
fn column_edge(mask: &[Vec<bool>], x: usize, first: bool) -> Option<usize> {
|
||||
let mut found = None;
|
||||
for (y, row) in mask.iter().enumerate() {
|
||||
if row.get(x).copied().unwrap_or(false) {
|
||||
if first {
|
||||
return Some(y);
|
||||
}
|
||||
found = Some(y);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The first (or last) column set in row `y`; None if the row is empty or missing.
|
||||
fn row_edge(mask: &[Vec<bool>], y: usize, first: bool) -> Option<usize> {
|
||||
let row = mask.get(y)?;
|
||||
if first { row.iter().position(|&on| on) } else { row.iter().rposition(|&on| on) }
|
||||
}
|
||||
|
||||
/// The overlay PNG: the picture in blue, the model in red, on a canvas that holds both.
|
||||
fn overlay_png(picture: &Part, model: &Placed) -> Vec<u8> {
|
||||
// A margin so a model that hangs off the picture still fits the canvas.
|
||||
let m = 8i64;
|
||||
let (x0, y0) = (0.min(model.dx) - m, 0.min(model.dy) - m);
|
||||
let (x1, y1) = (
|
||||
(picture.width as i64).max(model.dx + model.mask.first().map_or(0, |r| r.len()) as i64) + m,
|
||||
(picture.height as i64).max(model.dy + model.mask.len() as i64) + m,
|
||||
);
|
||||
let (w, h) = ((x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32);
|
||||
let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([250, 250, 250, 255]));
|
||||
for (y, row) in picture.mask.iter().enumerate() {
|
||||
for (x, &on) in row.iter().enumerate() {
|
||||
if on {
|
||||
img.put_pixel((x as i64 - x0) as u32, (y as i64 - y0) as u32, image::Rgba([70, 110, 230, 255]));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (r, row) in model.mask.iter().enumerate() {
|
||||
for (c, &on) in row.iter().enumerate() {
|
||||
if !on {
|
||||
continue;
|
||||
}
|
||||
let (x, y) = (model.dx + c as i64 - x0, model.dy + r as i64 - y0);
|
||||
if (0..w as i64).contains(&x) && (0..h as i64).contains(&y) {
|
||||
img.put_pixel(x as u32, y as u32, image::Rgba([235, 60, 60, 255]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
// Encoding a mask-sized PNG cannot realistically fail; if it ever does, no overlay.
|
||||
let enc = image::codecs::png::PngEncoder::new(&mut out);
|
||||
use image::ImageEncoder as _;
|
||||
if enc.write_image(img.as_raw(), img.width(), img.height(), image::ExtendedColorType::Rgba8).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
fn round4(v: f64) -> f64 {
|
||||
if v.abs() < 1e12 { (v * 10_000.0).round() / 10_000.0 } else { v }
|
||||
}
|
||||
|
||||
fn round3(v: f64) -> f64 {
|
||||
if v.abs() < 1e12 { (v * 1_000.0).round() / 1_000.0 } else { v }
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
//! Tests for `inspect.compare_picture` (#1486): synthetic reference pictures drawn in code,
|
||||
//! written to the temp dir and read back through the vfs like any other reference.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::Session;
|
||||
use image::ImageEncoder as _;
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, params: Value) -> Value {
|
||||
s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn box_body(s: &mut Session, name: &str, x1: f64, y1: f64, z: f64) {
|
||||
let sketch = format!("{name}Sketch");
|
||||
run(s, "sketch.create", json!({"plane": "XY", "name": sketch}));
|
||||
run(s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [x1, y1]}));
|
||||
run(s, "sketch.finish", json!({}));
|
||||
run(s, "solid.extrude", json!({"sketch": sketch, "distance": z, "operation": "new_body", "body_name": name}));
|
||||
}
|
||||
|
||||
/// A PNG whose pixels come from `paint`.
|
||||
fn png(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
png_rgba(w, h, |x, y| {
|
||||
let [r, g, b] = paint(x, y);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
}
|
||||
|
||||
/// A PNG with alpha, whose pixels come from `paint`.
|
||||
fn png_rgba(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
|
||||
let mut img = image::RgbaImage::new(w as u32, h as u32);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
img.put_pixel(x as u32, y as u32, image::Rgba(paint(x, y)));
|
||||
}
|
||||
}
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
image::codecs::png::PngEncoder::new(&mut out).write_image(img.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgba8).unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
fn jpeg(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
jpeg_q(w, h, 90, paint)
|
||||
}
|
||||
|
||||
fn jpeg_q(w: usize, h: usize, q: u8, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
let mut img = image::RgbaImage::new(w as u32, h as u32);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let [r, g, b] = paint(x, y);
|
||||
img.put_pixel(x as u32, y as u32, image::Rgba([r, g, b, 255]));
|
||||
}
|
||||
}
|
||||
let rgb = image::DynamicImage::ImageRgba8(img).to_rgb8();
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, q)
|
||||
.write_image(rgb.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgb8)
|
||||
.unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
/// Write a reference into the temp dir and return its path.
|
||||
fn reference(name: &str, bytes: &[u8]) -> String {
|
||||
let path = std::env::temp_dir().join(format!("solidcraft-compare-picture-{}-{name}", std::process::id()));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A white rectangle on a grey backdrop: `x0..x1, y0..y1` in pixels.
|
||||
fn rect_picture(w: usize, h: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Vec<u8> {
|
||||
png(w, h, |x, y| if (x0..x1).contains(&x) && (y0..y1).contains(&y) { [255, 255, 255] } else { [200, 200, 200] })
|
||||
}
|
||||
|
||||
fn edges(v: &Value) -> Vec<Vec<Option<f64>>> {
|
||||
["top", "bottom", "left", "right"]
|
||||
.iter()
|
||||
.map(|side| v["edges"][side].as_array().unwrap().iter().map(|e| e.as_f64()).collect::<Vec<Option<f64>>>())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(v: Option<f64>, want: f64, tol: f64) -> bool {
|
||||
v.is_some_and(|e| (e - want).abs() <= tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_picture_scores_high_with_flat_edges() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall
|
||||
let path = reference("match.png", &rect_picture(200, 280, 20, 20, 180, 260));
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]);
|
||||
for side in edges(&out) {
|
||||
for e in side {
|
||||
assert!(near(e, 0.0, 0.6), "edge {e:?}");
|
||||
}
|
||||
}
|
||||
assert!(!out["overlay_png"].as_str().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_step_in_the_bottom_edge_shows_up_in_mm() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
// The aligned picture: a plain part 160 x 240 px — the model's own shape at 8 px per mm.
|
||||
let aligned_path = reference("aligned.png", &rect_picture(200, 280, 20, 20, 180, 260));
|
||||
let aligned = run(&mut s, "inspect.compare_picture", json!({"reference": aligned_path, "view": "front"}));
|
||||
// The stepped picture: over its right half the part's bottom edge sits 35 px higher.
|
||||
// The width fit gives 8 px per mm, so 35 px is 4.375 mm of the model reaching past
|
||||
// the picture.
|
||||
let stepped_path = reference(
|
||||
"stepped.png",
|
||||
&png(200, 280, |x, y| {
|
||||
let bottom = if x >= 100 { 225 } else { 260 };
|
||||
if (20..180).contains(&x) && (20..bottom).contains(&y) { [255, 255, 255] } else { [200, 200, 200] }
|
||||
}),
|
||||
);
|
||||
let stepped = run(&mut s, "inspect.compare_picture", json!({"reference": stepped_path, "view": "front"}));
|
||||
let flat = edges(&aligned)[1].clone();
|
||||
let step = edges(&stepped)[1].clone();
|
||||
for e in flat.iter() {
|
||||
assert!(near(*e, 0.0, 0.6), "flat bottom {e:?}");
|
||||
}
|
||||
// Stations sit at local x = 16..144 px; the notch starts at local x = 80 (global 100),
|
||||
// so stations 5..9 are over it.
|
||||
for e in step.iter().take(4) {
|
||||
assert!(near(*e, 0.0, 0.6), "step bottom left {e:?}");
|
||||
}
|
||||
for e in step.iter().skip(4) {
|
||||
assert!(near(*e, 4.375, 0.6), "step bottom right {e:?}");
|
||||
}
|
||||
assert!(stepped["overlap"].as_f64().unwrap() < aligned["overlap"].as_f64().unwrap());
|
||||
}
|
||||
|
||||
/// #1486's example, pinned: `examples/bracket.json` as it is (upright 30 mm) against the
|
||||
/// same bracket at 40 mm, both from the front, scaled by the 40 mm arm they share.
|
||||
/// The issue's prototype numbers: overlap 0.865, bottom −9.9 mm at the upright (6 % across),
|
||||
/// 0.0 mm everywhere else.
|
||||
#[test]
|
||||
fn the_issue_bracket_pins_overlap_and_the_short_upright() {
|
||||
let mut s = Session::default();
|
||||
// The bracket profile of examples/bracket.json: a 40 x 6 arm with a 6-wide upright to
|
||||
// 30 mm, on XZ so the front view shows the upright hanging below the arm.
|
||||
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Profile"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 6], [6, 6], [6, 30], [0, 30]], "closed": true}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 20.0, "direction": "negative", "body_name": "Bracket"}));
|
||||
// The same bracket with the upright at 40 mm, at 20 px per mm: an 800 x 800 part, the
|
||||
// 800 x 120 arm on top and the 120-wide upright down to 800, on a grey margin.
|
||||
let path = reference(
|
||||
"bracket.png",
|
||||
&png(840, 840, |x, y| {
|
||||
let part = ((20..820).contains(&x) && (20..140).contains(&y)) || ((20..140).contains(&x) && (20..820).contains(&y));
|
||||
if part { [255, 255, 255] } else { [200, 200, 200] }
|
||||
}),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "rows": 480, "overlay": false}));
|
||||
let overlap = out["overlap"].as_f64().unwrap();
|
||||
assert!((overlap - 0.865).abs() <= 0.01, "overlap {overlap}");
|
||||
let e = edges(&out);
|
||||
// The upright is the first station (x = 80 of 800): the model is 10 mm short there.
|
||||
assert!(near(e[1][0], -10.0, 0.2), "bottom at the upright {:?}", e[1][0]);
|
||||
for side in 1..9 {
|
||||
assert!(near(e[1][side], 0.0, 0.1), "bottom elsewhere {:?}", e[1]);
|
||||
}
|
||||
for i in 0..9 {
|
||||
assert!(near(e[0][i], 0.0, 0.1), "top {:?}", e[0]);
|
||||
// Below the model's 30 mm upright the model has no row to answer with: those
|
||||
// side stations are null, as documented.
|
||||
for side in [e[2].clone(), e[3].clone()] {
|
||||
match side[i] {
|
||||
None => {}
|
||||
Some(v) => assert!(v.abs() <= 0.1, "side {side:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_backdrop_still_separates_from_the_part() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
// A backdrop that shifts one step per row: the border flood follows it; the step at the
|
||||
// part's outline (to white) stops it.
|
||||
let path = reference(
|
||||
"gradient.png",
|
||||
&png(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [200 + (y / 30) as u8, 200, 200] }),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jpeg_reference_works_too() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
let path =
|
||||
reference("match.jpg", &jpeg(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [40, 40, 40] }));
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_takes_one_part_off_the_board() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
// Two parts side by side; the crop keeps the left one, a plain rectangle that matches
|
||||
// the model. The right part is bigger overall but L-shaped, so without the crop the
|
||||
// largest piece wins and the score drops.
|
||||
let path = reference(
|
||||
"two.png",
|
||||
&png(400, 300, |x, y| {
|
||||
let left = (20..180).contains(&x) && (20..260).contains(&y);
|
||||
let right = (210..390).contains(&x) && (5..295).contains(&y) && !((300..390).contains(&x) && (100..200).contains(&y));
|
||||
if left || right { [255, 255, 255] } else { [200, 200, 200] }
|
||||
}),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_fraction": [0.0, 0.0, 0.5, 1.0]}));
|
||||
// The picture size is the found part's tight frame: the left rectangle is 160 x 240 px.
|
||||
assert_eq!(out["picture"]["width"], 160);
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]);
|
||||
let whole = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"}));
|
||||
assert!(whole["overlap"].as_f64().unwrap() < out["overlap"].as_f64().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_px_has_explicit_units() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
let path = reference("px.png", &rect_picture(200, 280, 20, 20, 180, 260));
|
||||
// Pixels mean pixels: [10, 10, 180, 260] keeps the part with a margin, and a crop of
|
||||
// one pixel is one pixel, not the whole picture.
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_px": [10, 10, 180, 260]}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]);
|
||||
let dot = reference("dot.png", &rect_picture(200, 280, 100, 100, 101, 101));
|
||||
assert!(
|
||||
s.execute("inspect.compare_picture", &json!({"reference": dot, "crop_px": [0, 0, 1, 1]})).unwrap_err().to_string().contains("no part found")
|
||||
);
|
||||
// Giving both spellings is refused, and so is a fraction above 1.
|
||||
assert!(
|
||||
s.execute("inspect.compare_picture", &json!({"reference": path, "crop_px": [0, 0, 10, 10], "crop_fraction": [0.0, 0.0, 0.1, 0.1]}))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("not both")
|
||||
);
|
||||
assert!(
|
||||
s.execute("inspect.compare_picture", &json!({"reference": path, "crop_fraction": [0.0, 0.0, 1.5, 1.0]}))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("0..1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_both_never_stretches_the_axes_apart() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall
|
||||
// A 20 x 20 mm square picture of a 20 x 30 mm model: `both` used to stretch the model
|
||||
// to the square and report a perfect 1.000 with every edge at 0.0 mm. One uniform
|
||||
// scale (from the width they share) leaves the 10 mm of overhang visible instead.
|
||||
let path = reference("square.png", &rect_picture(220, 220, 10, 10, 210, 210));
|
||||
let both = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "fit": "both", "overlay": false}));
|
||||
assert!((both["overlap"].as_f64().unwrap() - 200.0 / 300.0).abs() < 0.02, "overlap {}", both["overlap"]);
|
||||
assert!((both["aspect_mismatch"].as_f64().unwrap() - 1.5).abs() < 0.01, "aspect_mismatch {}", both["aspect_mismatch"]);
|
||||
// And `width` is the default: leaving `fit` out answers the same as naming it.
|
||||
let plain = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
assert_eq!(plain["overlap"], both["overlap"]);
|
||||
assert_eq!(plain["edges"], both["edges"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_width_keeps_the_models_aspect() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
// The picture part is 160 x 160 px: fit=width scales the model uniformly to 160 x 240,
|
||||
// so it hangs 80 px (10 mm) over the picture's height in total, wherever the slide puts
|
||||
// it. The overlap of a contained model is 160/240 wherever it sits.
|
||||
let path = reference("short.png", &rect_picture(200, 220, 20, 20, 180, 180));
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "fit": "width"}));
|
||||
assert!((out["overlap"].as_f64().unwrap() - 160.0 / 240.0).abs() < 0.05, "overlap {}", out["overlap"]);
|
||||
let bottom: Vec<Option<f64>> = out["edges"]["bottom"].as_array().unwrap().iter().map(|e| e.as_f64()).collect();
|
||||
let top: Vec<Option<f64>> = out["edges"]["top"].as_array().unwrap().iter().map(|e| e.as_f64()).collect();
|
||||
for i in 0..9 {
|
||||
// The overhang splits between top and bottom but always totals the extra 10 mm.
|
||||
assert!(bottom[i].unwrap() >= 0.0 && top[i].unwrap() >= 0.0, "bottom {:?} top {:?}", bottom[i], top[i]);
|
||||
assert!((bottom[i].unwrap() + top[i].unwrap() - 10.0).abs() < 0.6, "bottom {:?} top {:?}", bottom[i], top[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_model_fits_the_grid_not_the_memory() {
|
||||
let mut s = Session::default();
|
||||
// A 2 mm x 1000 mm sliver seen from the front: fitted by width against a 1024-wide
|
||||
// picture it used to become 1024 x 524 288 booleans. The fitted model now takes the
|
||||
// same MAX_GRID cap as the picture, so the comparison just runs.
|
||||
box_body(&mut s, "Sliver", 2.0, 1.0, 1000.0);
|
||||
let path = reference("sliver.png", &rect_picture(1030, 1010, 3, 5, 1027, 1005));
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
// The shapes are nothing alike (the sliver is 1:500, the picture 1024:1000), and the
|
||||
// capped model grid keeps the overlap small — what matters is that it ran at all.
|
||||
assert!(out["overlap"].as_f64().unwrap() < 0.1, "overlap {}", out["overlap"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_pictures_keep_their_part() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
// A part touching the picture's border: only border pixels close to the border's main
|
||||
// colour seed the background, so the part's own border pixels do not flood it.
|
||||
let border = reference("border.png", &rect_picture(200, 280, 0, 20, 160, 260));
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": border, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "border overlap {}", out["overlap"]);
|
||||
// A white part on a (245, 245, 245) studio backdrop: the step of 10 is below BG_STEP,
|
||||
// but the stricter retry separates it.
|
||||
let studio = reference(
|
||||
"studio.png",
|
||||
&png(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": studio, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "studio overlap {}", out["overlap"]);
|
||||
// A part on a transparent background: alpha below 128 is background.
|
||||
let alpha = reference(
|
||||
"alpha.png",
|
||||
&png_rgba(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [90, 90, 90, 255] } else { [0, 0, 0, 0] }),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": alpha, "view": "front"}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "alpha overlap {}", out["overlap"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_through_hole_counts_the_same_on_both_sides() {
|
||||
let mut s = Session::default();
|
||||
// A 200 x 200 mm plate with a 100 x 100 mm through-hole, against a picture of itself
|
||||
// at 1 px per mm, seen from the top (the hole goes through the plate's faces). The
|
||||
// picture's hole is filled by the border flood; the model's hole now gets the same
|
||||
// rule, so the plate scores ~1.0 instead of 0.75.
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Plate"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [200.0, 200.0]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "Plate", "distance": 10.0, "operation": "new_body", "body_name": "Plate"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [50.0, 50.0], "p1": [150.0, 150.0]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20.0, "operation": "cut"}));
|
||||
let path = reference(
|
||||
"plate.png",
|
||||
&png(220, 220, |x, y| {
|
||||
let plate = (10..210).contains(&x) && (10..210).contains(&y);
|
||||
let hole = (60..160).contains(&x) && (60..160).contains(&y);
|
||||
if plate && !hole { [255, 255, 255] } else { [200, 200, 200] }
|
||||
}),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "top", "overlay": false}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]);
|
||||
for side in edges(&out) {
|
||||
for e in side {
|
||||
assert!(near(e, 0.0, 0.6), "edge {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_and_empty_references_fail_cleanly() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
assert!(s.execute("inspect.compare_picture", &json!({})).is_err());
|
||||
// Not an image at all.
|
||||
let text = reference("not.png", b"just text, not a picture");
|
||||
assert!(s.execute("inspect.compare_picture", &json!({"reference": text})).unwrap_err().to_string().contains("PNG or a JPEG"));
|
||||
// A uniform picture: the background eats everything, and says so.
|
||||
let flat = reference("flat.png", &png(64, 64, |_, _| [200, 200, 200]));
|
||||
assert!(s.execute("inspect.compare_picture", &json!({"reference": flat})).unwrap_err().to_string().contains("no part found"));
|
||||
// A fully transparent picture: alpha says there is nothing there.
|
||||
let clear = reference("clear.png", &png_rgba(64, 64, |_, _| [0, 0, 0, 0]));
|
||||
assert!(s.execute("inspect.compare_picture", &json!({"reference": clear})).unwrap_err().to_string().contains("transparent"));
|
||||
// A missing file.
|
||||
assert!(s.execute("inspect.compare_picture", &json!({"reference": "no-such-file.png"})).is_err());
|
||||
// A bad fit name.
|
||||
let path = reference("match2.png", &rect_picture(200, 280, 20, 20, 180, 260));
|
||||
assert!(s.execute("inspect.compare_picture", &json!({"reference": path, "fit": "diagonal"})).is_err());
|
||||
// overlay: false leaves the PNG out.
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
assert!(out.get("overlay_png").is_none());
|
||||
}
|
||||
|
||||
/// Reviewer re-test case: a 60 x 60 opaque PNG with a white 40 x 40 square and a single
|
||||
/// backdrop pixel at alpha 254 used to be read as all part — 1.000 against the 40 x 40
|
||||
/// square at 0.067 mm/px instead of 0.1. Alpha now decides only when the border is mostly
|
||||
/// see-through, and a part drawn at alpha 100 on a transparent backdrop is still the part.
|
||||
#[test]
|
||||
fn one_translucent_pixel_does_not_switch_to_alpha() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Square", 4.0, 1.0, 4.0); // front view: 4 x 4 mm
|
||||
let path = reference(
|
||||
"speck.png",
|
||||
&png_rgba(60, 60, |x, y| {
|
||||
let alpha = if x == 5 && y == 55 { 254 } else { 255 };
|
||||
let c = if (10..50).contains(&x) && (10..50).contains(&y) { 255u8 } else { 128 };
|
||||
[c, c, c, alpha]
|
||||
}),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
// The part is the 40 x 40 square: 4 mm over 40 px is 0.1 mm/px, not 4/60 = 0.067.
|
||||
let mmpp = out["mm_per_px"]["x"].as_f64().unwrap();
|
||||
assert!((mmpp - 0.1).abs() < 0.01, "mm_per_px {mmpp}");
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]);
|
||||
// A part drawn at alpha 100 on a transparent backdrop is the part, not the background.
|
||||
let faint = reference(
|
||||
"faint.png",
|
||||
&png_rgba(60, 60, |x, y| if (10..50).contains(&x) && (10..50).contains(&y) { [255, 255, 255, 100] } else { [0, 0, 0, 0] }),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": faint, "view": "front", "overlay": false}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.9, "faint overlap {}", out["overlap"]);
|
||||
let mmpp = out["mm_per_px"]["x"].as_f64().unwrap();
|
||||
assert!((mmpp - 0.1).abs() < 0.01, "faint mm_per_px {mmpp}");
|
||||
}
|
||||
|
||||
/// Reviewer re-test case: one view cropped off a board — the part touches three sides and
|
||||
/// takes 270 of the 400 border samples, so the border's main colour is the part's own and
|
||||
/// the flood eats it: the 15 px backdrop strip becomes "the part" and an exact model scores
|
||||
/// 0.18. `part_fills_crop: true` says the crop box is the part: no flood, exact model ~1.0.
|
||||
#[test]
|
||||
fn a_tight_crop_can_declare_the_box_is_the_part() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 17.0, 10.0, 20.0); // front view: 17 wide, 20 tall
|
||||
// The tight crop: the white part fills x 0..85 of a 100 x 100 box, touching three
|
||||
// sides — 270 of the border samples — with a 15 px backdrop strip down the right.
|
||||
let path = reference("tight.png", &png(100, 100, |x, _| if x < 85 { [255, 255, 255] } else { [200, 200, 200] }));
|
||||
let flood = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "overlay": false}));
|
||||
assert!(flood["overlap"].as_f64().unwrap() < 0.5, "the flood keeps the strip: overlap {}", flood["overlap"]);
|
||||
let out = run(
|
||||
&mut s,
|
||||
"inspect.compare_picture",
|
||||
json!({"reference": path, "view": "front", "crop_px": [0, 0, 85, 100], "part_fills_crop": true, "overlay": false}),
|
||||
);
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]);
|
||||
// 17 mm over the 85 px the part fills: 0.2 mm/px.
|
||||
assert!((out["mm_per_px"]["x"].as_f64().unwrap() - 0.2).abs() < 0.01, "mm_per_px {}", out["mm_per_px"]);
|
||||
// A crop of a 2 x 2 box is the part; a 1 px box is refused.
|
||||
let dot = reference("tight-dot.png", &png(4, 4, |_, _| [255, 255, 255]));
|
||||
assert!(
|
||||
s.execute("inspect.compare_picture", &json!({"reference": dot, "part_fills_crop": true, "crop_px": [0, 0, 1, 1]}))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("2 x 2")
|
||||
);
|
||||
}
|
||||
|
||||
/// Reviewer re-test case: holes are filled on both sides, so a model missing a 100 x 100
|
||||
/// through-hole scores ~1.000 against a picture that shows the hole. That is the contract —
|
||||
/// outline only — and the command description must say so, so an agent does not read 1.000
|
||||
/// as "matches".
|
||||
#[test]
|
||||
fn the_compare_is_outline_only_holes_are_not_compared() {
|
||||
assert!(
|
||||
crate::cmd::compare_picture::COMMANDS[0].params.contains("holes are not compared"),
|
||||
"the command description must say the compare is outline only"
|
||||
);
|
||||
let mut s = Session::default();
|
||||
// A solid 200 x 200 mm plate against a picture of a plate with a 100 x 100 through-hole.
|
||||
box_body(&mut s, "Plate", 200.0, 10.0, 200.0);
|
||||
let path = reference(
|
||||
"hole-only.png",
|
||||
&png(220, 220, |x, y| {
|
||||
let plate = (10..210).contains(&x) && (10..210).contains(&y);
|
||||
let hole = (60..160).contains(&x) && (60..160).contains(&y);
|
||||
if plate && !hole { [255, 255, 255] } else { [200, 200, 200] }
|
||||
}),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
// The outlines match: the hole is not compared, as the description says.
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]);
|
||||
}
|
||||
|
||||
/// Reviewer re-test case: a white part on (245, 245, 245) saved as JPEG at quality 75 gave
|
||||
/// "no part" even on the stricter retry — the codec blurs the 10-level step at the part's
|
||||
/// outline into steps of a few levels each, under any local limit. The third pass takes the
|
||||
/// backdrop globally: near the border's main colour.
|
||||
#[test]
|
||||
fn a_light_jpeg_keeps_its_part() {
|
||||
let mut s = Session::default();
|
||||
box_body(&mut s, "Box", 20.0, 10.0, 30.0);
|
||||
let path = reference(
|
||||
"light.jpg",
|
||||
&jpeg_q(200, 300, 75, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }),
|
||||
);
|
||||
let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false}));
|
||||
assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]);
|
||||
}
|
||||
@@ -31,7 +31,8 @@ mod relink_tests;
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params(
|
||||
"path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \
|
||||
name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]; \
|
||||
name? (default: the design's name); parent?: component id or name (default: the active one); \
|
||||
translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \
|
||||
reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available",
|
||||
),
|
||||
CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params(
|
||||
@@ -507,8 +508,13 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("reuse").and_then(Value::as_bool).unwrap_or(false) {
|
||||
let existing = s.doc.links.iter().find(|(_, link)| absolute(&resolve(s.path.as_deref(), &link.path)) == file).map(|(id, _)| *id);
|
||||
if let Some(component) = existing {
|
||||
let parent = p.get("parent").cloned().unwrap_or_else(|| json!(s.active_component));
|
||||
return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate}));
|
||||
let parent = if p.get("parent").is_some() { component_key(s, p, "parent", cmd)? } else { s.active_component };
|
||||
// Reuse the definition, not another placement's captured or pending move.
|
||||
// Insert Design places from the parent origin whether the link is new or reused.
|
||||
let mut transform = solidcraft_doc::IDENTITY;
|
||||
transform[3] = [translate.x, translate.y, translate.z, 1.0];
|
||||
let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?;
|
||||
return Ok(json!({"occurrence": occurrence, "component": component}));
|
||||
}
|
||||
}
|
||||
let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation())?;
|
||||
|
||||
@@ -161,6 +161,90 @@ fn reused_design_insertion_is_free_even_before_a_link_exists() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_design_insertion_uses_the_requested_position_and_survives_undo_and_reopen() {
|
||||
let dir = folder("reuse-position");
|
||||
let file = dir.join("part.sc");
|
||||
part(&file, 30);
|
||||
for first_reuses in [false, true] {
|
||||
let mut s = Session::default();
|
||||
let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0], "reuse": first_reuses}));
|
||||
let before = s.doc.to_json();
|
||||
let undo = s.undo.len();
|
||||
let second = run(&mut s, "component.insert_design", json!({"path": file, "translate": [40, 5, 7], "reuse": true}));
|
||||
assert_eq!(first["component"], second["component"]);
|
||||
assert_eq!(s.doc.links.len(), 1);
|
||||
assert_eq!(s.doc.features.len(), 1);
|
||||
assert_eq!(s.undo.len(), undo + 1);
|
||||
let occurrence = second["occurrence"].as_u64().unwrap();
|
||||
assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]);
|
||||
assert_linked_bounds(&mut s, first["occurrence"].as_u64().unwrap(), [20.0, 0.0, 0.0], [30.0, 20.0, 30.0]);
|
||||
assert!(!s.doc.occurrences.iter().find(|o| o.id == occurrence).unwrap().grounded);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.to_json(), before);
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]);
|
||||
let assembly = dir.join("assembly.sc");
|
||||
run(&mut s, "file.save", json!({"path": assembly}));
|
||||
let mut cold = Session::default();
|
||||
run(&mut cold, "doc.open", json!({"path": assembly}));
|
||||
assert_linked_bounds(&mut cold, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]);
|
||||
let at_origin = run(&mut cold, "component.insert_design", json!({"path": file, "reuse": true}))["occurrence"].as_u64().unwrap();
|
||||
assert_linked_bounds(&mut cold, at_origin, [0.0, 0.0, 0.0], [10.0, 20.0, 30.0]);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
fn assert_linked_bounds(s: &mut Session, occurrence: u64, min: [f64; 3], max: [f64; 3]) {
|
||||
let p = run(s, "occurrence.properties", json!({"occurrence": occurrence}));
|
||||
assert_eq!(p["body_count"], 1);
|
||||
assert!((p["total"]["volume_mm3"].as_f64().unwrap() - 6000.0).abs() < 1e-6, "{p}");
|
||||
for (key, expected) in [("min", min), ("max", max)] {
|
||||
for (axis, expected) in expected.into_iter().enumerate() {
|
||||
assert!((p["total"]["bbox"][key][axis].as_f64().unwrap() - expected).abs() < 1e-6, "{key}[{axis}] != {expected}: {p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_design_insertion_ignores_existing_moves_and_uses_the_destination_parent() {
|
||||
let dir = folder("reuse-parent");
|
||||
let file = dir.join("part.sc");
|
||||
part(&file, 30);
|
||||
for capture in [false, true] {
|
||||
let mut s = Session::default();
|
||||
let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0]}));
|
||||
run(
|
||||
&mut s,
|
||||
"occurrence.move",
|
||||
json!({"occurrence": first["occurrence"], "translate": [0, 10, 0], "axis": [0, 0, 1], "angle": "90 deg", "capture": capture, "move_grounded": true}),
|
||||
);
|
||||
let original = s.doc.occurrences.clone();
|
||||
let pending = s.pending_moves.clone();
|
||||
let parent = run(&mut s, "component.create", json!({"name": "Parent", "activate": false}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": parent["occurrence"], "translate": [100, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"}));
|
||||
for explicit_parent in [true, false] {
|
||||
let mut params = json!({"path": file, "translate": [40, 5, 7], "reuse": true});
|
||||
if explicit_parent {
|
||||
params["parent"] = json!("Parent");
|
||||
} else {
|
||||
run(&mut s, "component.activate", json!({"component": parent["component"]}));
|
||||
}
|
||||
let inserted = run(&mut s, "component.insert_design", params);
|
||||
assert_eq!(inserted["component"], first["component"]);
|
||||
assert_linked_bounds(&mut s, inserted["occurrence"].as_u64().unwrap(), [75.0, 40.0, 7.0], [95.0, 50.0, 37.0]);
|
||||
assert_eq!(s.doc.occurrences.first(), original.first());
|
||||
assert_eq!(s.pending_moves, pending);
|
||||
}
|
||||
let before = s.doc.to_json();
|
||||
for parent in [json!("missing"), first["component"].clone()] {
|
||||
assert!(s.execute("component.insert_design", &json!({"path": file, "parent": parent, "reuse": true})).is_err());
|
||||
assert_eq!(s.doc.to_json(), before);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_design_properties_update_density_without_geometry_and_keep_edited_cards() {
|
||||
let dir = folder("properties-density");
|
||||
|
||||
@@ -10,6 +10,14 @@ use crate::params::{bad, bool_, name_or_id_values, num, str_};
|
||||
use crate::{EngineError, Result, Sel, Session, Snapshot};
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("ui.assistant", "Toggle Assistant", crate::checked!("ui.assistant", assistant))
|
||||
.icon("assistant")
|
||||
.key("Ctrl+Shift+A")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&ASSISTANT_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::edit::AssistantResult>)
|
||||
.params("Show or hide Assistant in the app. Headless calls are refused without changing the design"),
|
||||
CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(),
|
||||
CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(),
|
||||
CommandSpec::new("edit.repeat", "Repeat Last Command", crate::checked!("edit.repeat", repeat))
|
||||
@@ -119,6 +127,12 @@ fn redo(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"redone": label}))
|
||||
}
|
||||
|
||||
const ASSISTANT_CONTRACT: crate::schema::TypedContract<crate::schema::edit::AssistantParams> = crate::schema::TypedContract::new();
|
||||
|
||||
fn assistant(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("ui.assistant shows or hides Assistant in the app; no assistant panel exists in a headless session".into()))
|
||||
}
|
||||
|
||||
const REPEAT_CONTRACT: crate::schema::TypedContract<crate::schema::edit::RepeatParams> = crate::schema::TypedContract::new();
|
||||
|
||||
/// Repeat Last Command (#7077) starts a tool, which only the app has: it starts the last one in
|
||||
@@ -1125,7 +1139,7 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rolled_back = s.doc.features.iter().position(|x| x.id == id).is_some_and(|i| i >= marker);
|
||||
let r = s.model.result(id);
|
||||
Ok(json!({
|
||||
"id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back,
|
||||
"id": f.id, "name": f.name, "type": f.kind.kind_key(), "type_name": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back,
|
||||
"definition": def, "omitted": omitted, "inputs": inputs,
|
||||
"error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()),
|
||||
}))
|
||||
@@ -1741,6 +1755,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
trial.doc_mut().marker = Some(idx + 1);
|
||||
trial.refresh();
|
||||
// The edited feature keeps its name. Its temporary replacement needs a fresh one while
|
||||
// the original remains in the trial as a placeholder (including construction planes).
|
||||
if let Some(parameters) = params.as_object_mut() {
|
||||
parameters.remove("name");
|
||||
}
|
||||
let r = spec.run_nested(&mut trial, ¶ms)?;
|
||||
let made = r.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?;
|
||||
let mut new = trial.doc.feature(made).cloned().ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?;
|
||||
|
||||
@@ -1652,3 +1652,14 @@ fn edits_after_a_canvas_share_its_image_with_every_undo_state() {
|
||||
assert_eq!(s.doc.canvases[0].data.as_ptr(), image, "undo brings back the same image");
|
||||
assert_eq!(s.doc.canvases[0].bytes().as_deref(), Some(png.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assistant_toggle_is_refused_headlessly_without_changing_the_document() {
|
||||
let mut s = Session::default();
|
||||
let before = (s.doc.to_json(), s.undo.len());
|
||||
let error = s.execute("ui.assistant", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("headless session"), "{error}");
|
||||
assert_eq!((s.doc.to_json(), s.undo.len()), before);
|
||||
let spec = crate::find_command("ui.assistant").unwrap();
|
||||
assert_eq!((spec.shortcut, spec.tab, spec.undoable), (Some("Ctrl+Shift+A"), "", false));
|
||||
}
|
||||
@@ -1644,8 +1644,8 @@ pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result<EdgeRefForm<'_>, &
|
||||
Ok(EdgeRefForm::Index { body, index })
|
||||
}
|
||||
|
||||
/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); an
|
||||
/// edge is rounded (a fillet).
|
||||
/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); a
|
||||
/// fillet's or chamfer's face changes that feature's size; an edge is rounded (a fillet).
|
||||
fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "solid.press_pull";
|
||||
let distance = req_expr(cmd, p, "distance")?;
|
||||
@@ -1657,10 +1657,9 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.abs() < 1e-9 {
|
||||
return Err(bad(cmd, "the distance must not be zero"));
|
||||
}
|
||||
// A fillet's or chamfer's face: its size changes by the distance (the feature is edited).
|
||||
if let Some(fp) = vec3(face)
|
||||
&& super::face::face_is_planar(s, fp) == Some(false)
|
||||
{
|
||||
// A fillet's or chamfer's face: its size changes by the distance (the feature is edited). A
|
||||
// chamfer's face is flat, so this is asked before whether the face is planar (#4986).
|
||||
if let Some(fp) = vec3(face) {
|
||||
let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default();
|
||||
let fid = solidcraft_doc::persistent_name::made_by(&name);
|
||||
if solidcraft_doc::persistent_name::is_blend(&name) {
|
||||
@@ -1678,8 +1677,10 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({"feature": f.id, "edited": f.name, key: new, "recomputed": out.get("recomputed"), "restored": out.get("restored")}));
|
||||
}
|
||||
// Another curved face moves along its normal.
|
||||
let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?;
|
||||
return (r.run)(s, &json!({"faces": [face], "distance": distance}));
|
||||
if super::face::face_is_planar(s, fp) == Some(false) {
|
||||
let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?;
|
||||
return (r.run)(s, &json!({"faces": [face], "distance": distance}));
|
||||
}
|
||||
}
|
||||
// Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps
|
||||
// being read as a bare number typed into the extrude).
|
||||
|
||||
@@ -61,6 +61,39 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"),
|
||||
// One command per format, so each File › Export item can have a key of its own; started
|
||||
// from a key or command search, the app opens the save picker (the mesh dialog for STL and
|
||||
// 3MF). Each takes `file.export`'s parameters for its format, without `format`.
|
||||
CommandSpec::new("file.export_step", "Export STEP", crate::checked!("file.export_step", export_step))
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_STEP_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
|
||||
.params("path; bodies?: [names] (default: every body; a design with components then exports as a STEP assembly) → {path, bytes, format}: STEP, whatever the path's extension"),
|
||||
CommandSpec::new("file.export_stl", "Export STL", crate::checked!("file.export_stl", export_stl))
|
||||
.icon("mesh_export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_STL_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
|
||||
.params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format}: binary STL, whatever the path's extension"),
|
||||
CommandSpec::new("file.export_3mf", "Export 3MF", crate::checked!("file.export_3mf", export_3mf))
|
||||
.icon("mesh_export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_3MF_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
|
||||
.params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard); objects?: body|component (as file.export) → {path, bytes, format}: 3MF, whatever the path's extension"),
|
||||
CommandSpec::new("file.export_obj", "Export OBJ", crate::checked!("file.export_obj", export_obj_cmd))
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_OBJ_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
|
||||
.params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format, files}: OBJ, with the colours of the bodies in a material library (`.mtl`) next to it"),
|
||||
CommandSpec::new("file.export_urdf", "Export URDF", crate::checked!("file.export_urdf", export_urdf_cmd))
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_URDF_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::file::UrdfExportResult>)
|
||||
.params("path; mesh_prefix?; effort? (default 1000); velocity? (default 10) → {path, format, files, links, joints, warnings}: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md"),
|
||||
CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh)
|
||||
.at("INSERT", "FILES")
|
||||
.icon("mesh_export")
|
||||
@@ -89,6 +122,12 @@ fn new_doc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
const EXPORT_STEP_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportStepParams> = crate::schema::TypedContract::new();
|
||||
const EXPORT_STL_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportMeshParams> = crate::schema::TypedContract::new();
|
||||
const EXPORT_3MF_CONTRACT: crate::schema::TypedContract<crate::schema::file::Export3mfParams> = crate::schema::TypedContract::new();
|
||||
const EXPORT_OBJ_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportMeshParams> = crate::schema::TypedContract::new();
|
||||
const EXPORT_URDF_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportUrdfParams> = crate::schema::TypedContract::new();
|
||||
|
||||
fn path_arg<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
|
||||
str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))
|
||||
}
|
||||
@@ -726,6 +765,7 @@ fn component_parts(s: &Session) -> Vec<(String, Vec<String>)> {
|
||||
|
||||
fn export_to(
|
||||
s: &Session,
|
||||
cmd: &str,
|
||||
path: &str,
|
||||
format: Format,
|
||||
bodies: &[String],
|
||||
@@ -740,7 +780,7 @@ fn export_to(
|
||||
// A design with components exports as a STEP assembly; otherwise bodies as placed.
|
||||
let bytes = if format == Format::Design {
|
||||
if !bodies.is_empty() {
|
||||
return Err(bad("file.export", "design JSON exports the complete document; omit bodies"));
|
||||
return Err(bad(cmd, "design JSON exports the complete document; omit bodies"));
|
||||
}
|
||||
solidcraft_io::write_design(&s.design())
|
||||
} else if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() {
|
||||
@@ -779,11 +819,44 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = path_arg(p, cmd)?;
|
||||
let format = Format::from_name(str_(p, "format").unwrap_or(path))?;
|
||||
if format == Format::Urdf {
|
||||
return export_urdf(s, path, p);
|
||||
if !string_list(cmd, p, "bodies")?.is_empty() {
|
||||
return Err(bad(cmd, "urdf exports the whole assembly; omit bodies"));
|
||||
}
|
||||
return export_urdf(s, cmd, path, p);
|
||||
}
|
||||
let quality = mesh_quality(p, cmd)?;
|
||||
let parts = mesh_parts(s, p, cmd, format)?;
|
||||
export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
|
||||
export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
|
||||
}
|
||||
|
||||
fn export_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export_step";
|
||||
let path = path_arg(p, cmd)?;
|
||||
export_to(s, cmd, path, Format::Step, &string_list(cmd, p, "bodies")?, &[], solidcraft_io::MeshQuality::default())
|
||||
}
|
||||
|
||||
fn export_stl(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export_stl";
|
||||
let path = path_arg(p, cmd)?;
|
||||
export_to(s, cmd, path, Format::StlBinary, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?)
|
||||
}
|
||||
|
||||
fn export_3mf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export_3mf";
|
||||
let path = path_arg(p, cmd)?;
|
||||
let parts = mesh_parts(s, p, cmd, Format::ThreeMf)?;
|
||||
export_to(s, cmd, path, Format::ThreeMf, &string_list(cmd, p, "bodies")?, &parts, mesh_quality(p, cmd)?)
|
||||
}
|
||||
|
||||
fn export_obj_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export_obj";
|
||||
let path = path_arg(p, cmd)?;
|
||||
export_to(s, cmd, path, Format::Obj, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?)
|
||||
}
|
||||
|
||||
fn export_urdf_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export_urdf";
|
||||
export_urdf(s, cmd, path_arg(p, cmd)?, p)
|
||||
}
|
||||
|
||||
/// The OBJ export: the mesh file and the material library beside it, with the colours of the
|
||||
@@ -814,11 +887,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io
|
||||
|
||||
/// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before
|
||||
/// anything is written; the meshes go first and the `.urdf` last.
|
||||
fn export_urdf(s: &Session, path: &str, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.export";
|
||||
if !string_list(cmd, p, "bodies")?.is_empty() {
|
||||
return Err(bad(cmd, "urdf exports the whole assembly; omit bodies"));
|
||||
}
|
||||
fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result<Value> {
|
||||
let positive = |k: &str| match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(_) => num(p, k).filter(|x| *x > 0.0).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a positive number"))),
|
||||
@@ -915,7 +984,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
},
|
||||
);
|
||||
}
|
||||
export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
|
||||
export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
|
||||
}
|
||||
|
||||
/// The browser build can't start a program.
|
||||
@@ -1103,6 +1172,43 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Each format's own export command (one key each in Keyboard Shortcuts) writes that format
|
||||
/// whatever the path's extension, as `file.export` does with `format`, and says so.
|
||||
#[test]
|
||||
fn each_format_has_an_export_command_of_its_own() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-export-per-format-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().to_string();
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap();
|
||||
for (cmd, format, signature) in [
|
||||
("file.export_step", "Step", &b"ISO-10303-21;"[..]),
|
||||
("file.export_3mf", "ThreeMf", &b"PK"[..]),
|
||||
("file.export_obj", "Obj", &b""[..]),
|
||||
("file.export_stl", "StlBinary", &b""[..]),
|
||||
] {
|
||||
// A name with another format's extension: the command, not the name, picks the format.
|
||||
let path = at(&format!("{format}.txt"));
|
||||
let r = s.execute(cmd, &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(path.as_str()), Some(format)), "{cmd}: {r}");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}");
|
||||
assert!(bytes.starts_with(signature), "{cmd}");
|
||||
}
|
||||
// The triangles `file.export` writes (the 80-byte header holds the file's name): a box is
|
||||
// 12 triangles, 84 + 50 bytes each.
|
||||
s.execute("file.export", &json!({"path": at("box.stl")})).unwrap();
|
||||
assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]);
|
||||
assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12);
|
||||
let obj = std::fs::read_to_string(at("Obj.txt")).unwrap();
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}");
|
||||
let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap();
|
||||
assert_eq!(r["format"], "Urdf");
|
||||
assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains("<robot"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #4747: a mesh export's `quality` follows curved faces more closely. A 3 mm hole in a
|
||||
/// 200 mm plate gets more triangles at fine and more again at finest, in STL and 3MF alike
|
||||
/// (Save As Mesh too); standard is what the export always gave; anything else is refused.
|
||||
|
||||
@@ -353,7 +353,8 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option<I
|
||||
let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6));
|
||||
let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()});
|
||||
let verts: Vec<Vec3> = tris.iter().flat_map(|t| t.iter().copied()).collect();
|
||||
let shape = match solidcraft_kernel::face_surface(&b.body, *index) {
|
||||
let surface = solidcraft_kernel::face_surface(&b.body, *index);
|
||||
let shape = match surface {
|
||||
Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => {
|
||||
super::measure_shape::cylinder(origin, axis, radius, &verts).unwrap_or(Shape::Other)
|
||||
}
|
||||
@@ -365,6 +366,7 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option<I
|
||||
_ => Shape::Other,
|
||||
};
|
||||
add_round(&mut json, &shape);
|
||||
super::measure_shape::add_curved(&mut json, surface);
|
||||
let slot = if matches!(shape, Shape::Round { .. }) && !shape.full() { face_slot(b, &m, &shape, &verts) } else { None };
|
||||
if let Some(sl) = &slot {
|
||||
json["slot"] = sl.json();
|
||||
|
||||
@@ -68,6 +68,27 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The radius of a toroidal or spherical face, added to its description: a fillet round a
|
||||
/// circular edge is a torus whose tube radius is the fillet's (`major_radius` is the ring
|
||||
/// through the middle of the rolling ball), a ball or a spherical corner patch a sphere. These
|
||||
/// faces have no axis to measure from, so they stay out of [`Shape`].
|
||||
pub(crate) fn add_curved(v: &mut Value, surface: Option<solidcraft_kernel::FaceSurface>) {
|
||||
use solidcraft_kernel::FaceSurface;
|
||||
let (radius, kind) = match surface {
|
||||
Some(FaceSurface::Torus { minor, major, .. }) if minor.is_finite() && minor > 0.0 => {
|
||||
if major.is_finite() {
|
||||
v["major_radius"] = json!(major.abs());
|
||||
}
|
||||
(minor, "torus")
|
||||
}
|
||||
Some(FaceSurface::Sphere { radius, .. }) if radius.is_finite() && radius > 0.0 => (radius, "sphere"),
|
||||
_ => return,
|
||||
};
|
||||
v["diameter"] = json!(2.0 * radius);
|
||||
v["radius"] = json!(radius);
|
||||
v["surface"] = json!(kind);
|
||||
}
|
||||
|
||||
/// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the
|
||||
/// round shape, centred level with the middle of the face, with its extent and coverage.
|
||||
pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option<Shape> {
|
||||
|
||||
@@ -26,6 +26,9 @@ pub(crate) mod clearance;
|
||||
mod clipboard;
|
||||
mod clipboard_foreign;
|
||||
mod compare;
|
||||
mod compare_picture;
|
||||
#[cfg(test)]
|
||||
mod compare_picture_tests;
|
||||
mod component;
|
||||
mod component_clone;
|
||||
mod component_clone_assembly;
|
||||
@@ -346,6 +349,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
|
||||
v.extend(metadata::COMMANDS.iter());
|
||||
v.extend(inspect::COMMANDS.iter());
|
||||
v.extend(compare::COMMANDS.iter());
|
||||
v.extend(compare_picture::COMMANDS.iter());
|
||||
v.extend(silhouette::COMMANDS.iter());
|
||||
v.extend(materials::COMMANDS.iter());
|
||||
v.extend(material_properties::COMMANDS.iter());
|
||||
|
||||
@@ -68,7 +68,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only()
|
||||
.params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."),
|
||||
CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only()
|
||||
.params("job: exact completed JobId; presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."),
|
||||
.params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."),
|
||||
CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only()
|
||||
.params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."),
|
||||
CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo()
|
||||
@@ -102,7 +102,7 @@ CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_
|
||||
CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only()
|
||||
.params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."),
|
||||
CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only()
|
||||
.params("job: completed JobId, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
|
||||
.params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."),
|
||||
CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo()
|
||||
.params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."),
|
||||
CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only()
|
||||
@@ -128,13 +128,13 @@ CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).ic
|
||||
CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image")
|
||||
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
|
||||
CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only()
|
||||
.params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."),
|
||||
.params("job?: {session, serial, generation}. Non-blocking progress, errors and captured frame metadata with queue:{running,waiting,job,shot,error}. Without job returns queue only. Advances an explicitly started render.batch through render.start as jobs finish; never pumps render work. Preview is separate from the exportable final image."),
|
||||
CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only()
|
||||
.params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."),
|
||||
.params("job?: {session, serial, generation}, default the active render.batch job. Requests cooperative cancellation and drops its waiting shots; completed jobs remain completed. Late cancelled frames cannot be published."),
|
||||
CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only()
|
||||
.params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."),
|
||||
.params("job?: completed JobId (default selected result). Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."),
|
||||
CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only()
|
||||
.params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"),
|
||||
.params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"),
|
||||
CommandSpec::new("render.backends", "Render Backends", backends).icon("list")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
|
||||
@@ -1052,6 +1052,14 @@ fn completed_png_content_identity_matches_status_and_exact_retained_export() {
|
||||
finish(&host);
|
||||
let newer = s.execute("render.status", &json!({"job":replacement})).unwrap();
|
||||
assert_ne!(newer["frame"]["png_sha256"], metadata["png_sha256"]);
|
||||
let still_retained = dir.join("still-retained.png");
|
||||
s.execute("render.export", &json!({"job":id,"path":still_retained})).unwrap();
|
||||
assert_eq!(std::fs::read(still_retained).unwrap(), bytes);
|
||||
for _ in 0..7 {
|
||||
let next = start(&mut s);
|
||||
finish(&host);
|
||||
s.execute("render.status", &json!({"job":next})).unwrap();
|
||||
}
|
||||
let evicted = dir.join("evicted.png");
|
||||
assert!(s.execute("render.export", &json!({"job":id,"path":evicted})).is_err());
|
||||
assert!(!evicted.exists());
|
||||
@@ -1281,7 +1289,12 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads
|
||||
assert_eq!(copied["frame"]["job"], json!(job));
|
||||
assert_eq!(copied["frame"]["width"], 16);
|
||||
assert!(copied.get("png").is_none());
|
||||
for params in [json!({}), json!(null), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] {
|
||||
for params in [json!({}), json!(null)] {
|
||||
assert_eq!(s.execute("render.result.copy", ¶ms).unwrap(), copied, "an omitted job uses the selected result");
|
||||
}
|
||||
for params in
|
||||
[json!({"job":1e300}), json!({"job":"selected"}), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})]
|
||||
{
|
||||
assert!(s.execute("render.result.copy", ¶ms).is_err());
|
||||
}
|
||||
assert!(Arc::ptr_eq(&document, &s.doc));
|
||||
|
||||
@@ -675,7 +675,12 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
p.scene,
|
||||
p.request,
|
||||
p.replace,
|
||||
crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment },
|
||||
crate::render_jobs::Execution {
|
||||
executor: p.executor,
|
||||
options: p.options,
|
||||
environment: p.environment,
|
||||
shot: params.get("setup").and_then(Value::as_str).map(str::to_owned),
|
||||
},
|
||||
)
|
||||
.map_err(job_error)?;
|
||||
let mut status = json!(status);
|
||||
@@ -688,24 +693,32 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Regrade {
|
||||
job: JobId,
|
||||
job: Option<JobId>,
|
||||
presentation: solidcraft_render::job::presentation::Presentation,
|
||||
}
|
||||
pub(super) fn regrade(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: Regrade = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.regrade", e.to_string()))?;
|
||||
input.presentation.validate().map_err(job_error)?;
|
||||
Ok(json!(s.render_jobs.regrade(input.job, input.presentation).map_err(job_error)?))
|
||||
let job = result_source(s, input.job, "render.result.regrade")?;
|
||||
Ok(json!(s.render_jobs.regrade(job, input.presentation).map_err(job_error)?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Job {
|
||||
job: JobId,
|
||||
fn result_source(s: &mut Session, job: Option<JobId>, command: &str) -> Result<JobId> {
|
||||
s.render_jobs.collect().map_err(job_error)?;
|
||||
job.or_else(|| s.render_selected_result()).ok_or_else(|| bad(command, "no completed result is selected"))
|
||||
}
|
||||
|
||||
pub(super) fn status(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?;
|
||||
Ok(json!(s.render_jobs.status(input.job).map_err(job_error)?))
|
||||
let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?;
|
||||
s.advance_render_batch()?;
|
||||
let Some(job) = input.job else {
|
||||
return Ok(json!({"queue":s.render_queue_state()}));
|
||||
};
|
||||
let mut reply = json!(s.render_jobs.status(job).map_err(job_error)?);
|
||||
if let Some(object) = reply.as_object_mut() {
|
||||
object.insert("queue".into(), json!(s.render_queue_state()));
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -714,18 +727,23 @@ struct Pin {
|
||||
job: Option<JobId>,
|
||||
}
|
||||
pub(super) fn pin(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
if params.get("job").is_none() {
|
||||
return Err(bad("render.result.pin", "job or explicit null is required"));
|
||||
}
|
||||
let input: Pin = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.pin", e.to_string()))?;
|
||||
Ok(json!({"frame":s.render_jobs.pin(input.job).map_err(job_error)?}))
|
||||
let job = if params.get("job").is_some_and(Value::is_null) { None } else { Some(result_source(s, input.job, "render.result.pin")?) };
|
||||
Ok(json!({"frame":s.render_jobs.pin(job).map_err(job_error)?}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ResultJob {
|
||||
job: Option<JobId>,
|
||||
}
|
||||
|
||||
pub(super) fn copy(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?;
|
||||
let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?;
|
||||
let job = result_source(s, input.job, "render.result.copy")?;
|
||||
let frame = s
|
||||
.render_jobs
|
||||
.handle(input.job)
|
||||
.handle(job)
|
||||
.map_err(job_error)?
|
||||
.frame()
|
||||
.map_err(job_error)?
|
||||
@@ -738,12 +756,14 @@ pub(super) fn copy(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn cancel(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?;
|
||||
let status = s.render_jobs.status(input.job).map_err(job_error)?;
|
||||
let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?;
|
||||
let job = input.job.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?;
|
||||
let status = s.render_jobs.status(job).map_err(job_error)?;
|
||||
s.cancel_render_batch(job);
|
||||
if status.progress.phase.terminal() {
|
||||
return Ok(json!(status));
|
||||
}
|
||||
Ok(json!(s.render_jobs.handle(input.job).map_err(job_error)?.cancel().map_err(job_error)?))
|
||||
Ok(json!(s.render_jobs.handle(job).map_err(job_error)?.cancel().map_err(job_error)?))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)]
|
||||
@@ -766,7 +786,7 @@ impl ExportFormat {
|
||||
struct Export {
|
||||
#[serde(default)]
|
||||
format: ExportFormat,
|
||||
job: JobId,
|
||||
job: Option<JobId>,
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
overwrite: bool,
|
||||
@@ -784,7 +804,8 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
// Atomic native writers are also used for the app's own files and do not
|
||||
// apply a request's path scope. Check the caller's destination explicitly.
|
||||
solidcraft_io::vfs::check(&input.path).map_err(|e| bad("render.export", e.to_string()))?;
|
||||
let frame = s.render_jobs.frame(input.job).map_err(job_error)?;
|
||||
let job = result_source(s, input.job, "render.export")?;
|
||||
let frame = s.render_jobs.frame(job).map_err(job_error)?;
|
||||
let bytes = match input.format {
|
||||
ExportFormat::Png => frame.png(),
|
||||
ExportFormat::Exr => frame
|
||||
@@ -797,7 +818,7 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
if input.overwrite { solidcraft_io::write_atomic(path, bytes, false) } else { solidcraft_io::safe_write::create_atomic(path, bytes) };
|
||||
result.map_err(|e| bad("render.export", format!("could not export completed {}: {e}", input.format.extension())))?;
|
||||
Ok(
|
||||
json!({"job":input.job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}),
|
||||
json!({"job":job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Planned Render interactions, with explicit non-mutating refusals.
|
||||
//! Transient Render view requests and explicit refusals for planned interactions.
|
||||
use super::CommandSpec;
|
||||
use crate::schema::render_lights::{MuteParams, SoloParams};
|
||||
use crate::schema::{TypedContract, output_schema_for, render_ui::CheckReport};
|
||||
use crate::schema::{
|
||||
TypedContract, output_schema_for,
|
||||
render_ui::{BatchParams, BatchResult, CheckReport, CompareDivider, CompareParams, CompareSide, ResultIndex},
|
||||
};
|
||||
use crate::{Result, Session, params::bad};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -33,19 +36,10 @@ fn mute(_: &mut crate::Session, params: &serde_json::Value) -> crate::Result<ser
|
||||
crate::render_lights::parse_id(&input.id).map_err(|e| crate::params::bad(command, e))?;
|
||||
serde_json::to_value(input).map_err(|e| crate::params::bad(command, e.to_string()))
|
||||
}
|
||||
|
||||
macro_rules! waiting {
|
||||
($id:literal, $label:literal, $tab:literal, $panel:literal, $icon:literal, $reason:literal) => {
|
||||
CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $reason).into())))
|
||||
.enabled(|_| Err(concat!("not supported yet: ", $reason).into()))
|
||||
.planned("5493")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.at($tab, $panel)
|
||||
.icon($icon)
|
||||
.params("No supported parameters. Always refuses without changing the design or history.")
|
||||
};
|
||||
}
|
||||
const RESULT_INDEX: TypedContract<ResultIndex> = TypedContract::new();
|
||||
const COMPARE: TypedContract<CompareParams> = TypedContract::new();
|
||||
const DIVIDER: TypedContract<CompareDivider> = TypedContract::new();
|
||||
const BATCH: TypedContract<BatchParams> = TypedContract::new();
|
||||
|
||||
const CHECK_REPORT: TypedContract<CheckReport> = TypedContract::new();
|
||||
|
||||
@@ -57,6 +51,16 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.params("text: nonempty report, at most 65536 bytes. Validated clipboard request; headless echo only, never renders or edits a design."),
|
||||
CommandSpec::new("render.result.select", "Select Render Result", crate::checked!("render.result.select", select_result))
|
||||
.icon("render_image").noundo().doc_only()
|
||||
.enabled(results_ready)
|
||||
.contract(&RESULT_INDEX).output(output_schema_for::<ResultIndex>)
|
||||
.params("index: integer 0..7, oldest first; must be retained. Selects a completed result as transient per-document view state; echoes index."),
|
||||
CommandSpec::new("render.result.discard", "Discard Render Result", crate::checked!("render.result.discard", discard_result))
|
||||
.icon("delete").noundo().doc_only()
|
||||
.enabled(results_ready)
|
||||
.contract(&RESULT_INDEX).output(output_schema_for::<ResultIndex>)
|
||||
.params("index: integer 0..7, oldest first; must be retained. Drops only that transient result, selecting the newest remaining result if necessary; echoes index."),
|
||||
CommandSpec::new("render.output.size", "Set Render Output Size", output_size)
|
||||
.icon("settings")
|
||||
.noundo()
|
||||
@@ -88,8 +92,20 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.noundo().doc_only().icon("render_scene").at("RENDER SCENE","LIGHTS")
|
||||
.contract(&MUTE).output(crate::schema::output_schema_for::<MuteParams>)
|
||||
.params("id: kind:slot light address; mute:bool. Validates and echoes per-document UI view state, applied to live preview and captured render copies only. Never changes saved settings or history."),
|
||||
waiting!("render.compare", "Compare Images", "RENDER", "RESULT", "compare", "retained image comparison"),
|
||||
waiting!("render.batch", "Render All Shots", "RENDER", "BATCH", "render_image", "the saved-shot render queue"),
|
||||
CommandSpec::new("render.compare", "Compare Images", crate::checked!("render.compare", compare))
|
||||
.icon("compare").noundo().doc_only().at("RENDER", "RESULT")
|
||||
.enabled(results_ready)
|
||||
.contract(&COMPARE).output(output_schema_for::<CompareParams>)
|
||||
.params("left, right: live or retained result index 0..7 (oldest first), distinct and retained; OR off:true. Validated per-document comparison view request; headless echo, no rendering or design/history change."),
|
||||
CommandSpec::new("render.compare.divider", "Move Render Comparison Divider", crate::checked!("render.compare.divider", divider))
|
||||
.icon("compare").noundo().doc_only()
|
||||
.contract(&DIVIDER).output(output_schema_for::<CompareDivider>)
|
||||
.params("position: finite number, clamped to 0.05..0.95. Transient comparison divider request; headless echo only."),
|
||||
CommandSpec::new("render.batch", "Render All Shots", crate::checked!("render.batch", batch))
|
||||
.icon("render_image").noundo().doc_only().at("RENDER", "BATCH")
|
||||
.enabled(|s| s.render_batch_ready())
|
||||
.contract(&BATCH).output(output_schema_for::<BatchResult>)
|
||||
.params("request?: render.start parameters, shared across all saved shots except camera. Default: first saved setup in name order. Captures up to 32 shot cameras and queues sequentially through render.start; returns {queued:n}. Refuses active renders, no shots or stale geometry. render.status (also with {}) and the UI tick advance the queue; Cancel on the active job drops waiting shots. No design/history/revision change."),
|
||||
];
|
||||
|
||||
fn copy_check(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
@@ -100,6 +116,110 @@ fn copy_check(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
Ok(json!({"text":report.text}))
|
||||
}
|
||||
|
||||
fn compare(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: CompareParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare", e.to_string()))?;
|
||||
match input {
|
||||
CompareParams::Off(off) if off.off => {
|
||||
s.render_jobs.set_comparison(None);
|
||||
Ok(json!({"off":true}))
|
||||
}
|
||||
CompareParams::Pair(pair) => {
|
||||
if pair.left == pair.right {
|
||||
return Err(bad("render.compare", "comparison sides must differ"));
|
||||
}
|
||||
let results = s.render_retained_results()?;
|
||||
for side in [pair.left, pair.right] {
|
||||
if let CompareSide::Result(index) = side
|
||||
&& (index > 7 || results.get(index as usize).is_none())
|
||||
{
|
||||
return Err(bad("render.compare", "retained result index is out of bounds"));
|
||||
}
|
||||
}
|
||||
let resolve = |side| match side {
|
||||
CompareSide::Live(_) => None,
|
||||
CompareSide::Result(index) => results.get(index as usize).map(|result| result.frame.job),
|
||||
};
|
||||
s.render_jobs.set_comparison(Some([resolve(pair.left), resolve(pair.right)]));
|
||||
Ok(json!({"left":pair.left,"right":pair.right}))
|
||||
}
|
||||
_ => Err(bad("render.compare", "off must be true")),
|
||||
}
|
||||
}
|
||||
|
||||
fn divider(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: CompareDivider = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare.divider", e.to_string()))?;
|
||||
if !input.position.is_finite() {
|
||||
return Err(bad("render.compare.divider", "position must be finite"));
|
||||
}
|
||||
Ok(json!({"position":input.position.clamp(0.05,0.95)}))
|
||||
}
|
||||
|
||||
fn batch(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: BatchParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.batch", e.to_string()))?;
|
||||
s.render_batch_ready().map_err(|reason| bad("render.batch", reason))?;
|
||||
if s.model.is_stale() {
|
||||
return Err(bad("render.batch", "finish the modelling gesture before rendering shots"));
|
||||
}
|
||||
for name in s.doc.render.setups.keys() {
|
||||
solidcraft_doc::render_settings::RenderSettings::validate_name(name).map_err(|error| bad("render.batch", error.to_string()))?;
|
||||
}
|
||||
let common = if let Some(request) = input.request {
|
||||
Value::Object(request.into_iter().collect())
|
||||
} else {
|
||||
let setup = s.doc.render.setups.values().next().ok_or_else(|| bad("render.batch", "no saved shots"))?;
|
||||
json!({"settings":setup})
|
||||
};
|
||||
let mut request = common.as_object().cloned().ok_or_else(|| bad("render.batch", "request must be an object"))?;
|
||||
let settings = if let Some(name) = request.get("setup") {
|
||||
let name = name.as_str().ok_or_else(|| bad("render.batch", "setup must be a saved name"))?;
|
||||
if request.contains_key("settings") {
|
||||
return Err(bad("render.batch", "choose either setup or settings"));
|
||||
}
|
||||
s.doc.render.setups.get(name).cloned().ok_or_else(|| bad("render.batch", "unknown saved setup"))?
|
||||
} else if let Some(settings) = request.get("settings") {
|
||||
serde_json::from_value(settings.clone()).map_err(|e| bad("render.batch", e.to_string()))?
|
||||
} else {
|
||||
s.doc.render.setups.values().next().cloned().ok_or_else(|| bad("render.batch", "no saved shots"))?
|
||||
};
|
||||
request.remove("setup");
|
||||
// A batch never replaces an active job; malformed replace values must still refuse.
|
||||
if request.get("replace").is_some_and(|value| value != &json!(false)) {
|
||||
return Err(bad("render.batch", "replace must be false or omitted"));
|
||||
}
|
||||
request.insert("settings".into(), json!(settings));
|
||||
let request = std::sync::Arc::new(Value::Object(request));
|
||||
let shots = s
|
||||
.doc
|
||||
.render
|
||||
.setups
|
||||
.iter()
|
||||
.map(|(name, shot)| crate::render_jobs::BatchShot { name: name.clone(), camera: shot.camera, request: request.clone() })
|
||||
.collect();
|
||||
let queued = s.start_render_batch(shots)?;
|
||||
Ok(json!({"queued":queued}))
|
||||
}
|
||||
|
||||
fn results_ready(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.render_jobs.has_results() { Ok(()) } else { Err("no completed render results are retained".into()) }
|
||||
}
|
||||
|
||||
fn indexed_result(s: &mut Session, params: &Value, command: &str, discard: bool) -> Result<Value> {
|
||||
let input: ResultIndex = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
|
||||
if input.index > 7 {
|
||||
return Err(bad(command, "index must be in 0..7"));
|
||||
}
|
||||
s.render_jobs.result_index(input.index as usize, discard).map_err(crate::render_jobs::job_error)?;
|
||||
Ok(json!({"index":input.index}))
|
||||
}
|
||||
|
||||
fn select_result(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
indexed_result(s, params, "render.result.select", false)
|
||||
}
|
||||
|
||||
fn discard_result(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
indexed_result(s, params, "render.result.discard", true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_lights_remaining_planned_commands_refuse_without_mutation() {
|
||||
@@ -149,17 +269,21 @@ fn output_size(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
struct ResultView {
|
||||
view: String,
|
||||
}
|
||||
fn result_view(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
fn result_view(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let input: ResultView = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.view", e.to_string()))?;
|
||||
if !matches!(input.view.as_str(), "model" | "image" | "fit" | "actual") {
|
||||
return Err(bad("render.result.view", "view must be model, image, fit or actual"));
|
||||
}
|
||||
if input.view == "model" {
|
||||
s.render_jobs.set_comparison(None);
|
||||
}
|
||||
Ok(json!({"view":input.view}))
|
||||
}
|
||||
fn close_result(_: &mut Session, params: &Value) -> Result<Value> {
|
||||
fn close_result(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
if !params.as_object().is_some_and(|p| p.is_empty()) {
|
||||
return Err(bad("render.result.close", "expected no parameters"));
|
||||
}
|
||||
s.render_jobs.set_comparison(None);
|
||||
Ok(json!({"view":"model"}))
|
||||
}
|
||||
|
||||
@@ -210,3 +334,344 @@ fn output_sections_copy_report_validates_without_design_history_or_job_changes()
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn complete_result(s: &mut Session, shot: &str) -> solidcraft_render::job::JobId {
|
||||
let reply = s.execute("render.start", &json!({"setup":shot})).unwrap();
|
||||
let job = serde_json::from_value(reply["job"].clone()).unwrap();
|
||||
let host = s.render_job_host().unwrap().clone();
|
||||
for _ in 0..1000 {
|
||||
host.pump(4096).unwrap();
|
||||
if s.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" {
|
||||
return job;
|
||||
}
|
||||
}
|
||||
panic!("bounded result fixture did not complete");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn retained_results_cap_order_metadata_and_selection_never_edit_a_design() {
|
||||
let mut s = Session::default();
|
||||
s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16,"height":8}})).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":32}})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.redo.len(), 1, "view commands must preserve an available redo step");
|
||||
let document = s.doc.clone();
|
||||
let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty());
|
||||
let jobs: Vec<_> = (0..10).map(|_| complete_result(&mut s, "Hero")).collect();
|
||||
let results = s.render_retained_results().unwrap();
|
||||
assert_eq!(results.len(), 8);
|
||||
assert_eq!(results.iter().map(|result| result.frame.job).collect::<Vec<_>>(), jobs[2..]);
|
||||
for result in &results {
|
||||
assert_eq!(result.shot.as_deref(), Some("Hero"));
|
||||
assert_eq!((result.frame.width, result.frame.height), (16, 8));
|
||||
assert!(result.seconds.is_finite() && result.seconds >= 0.0);
|
||||
assert_eq!(result.frame.scene_generation, s.revision);
|
||||
assert!(!result.stale);
|
||||
}
|
||||
assert!(s.render_job_handle(jobs[0]).is_err());
|
||||
assert!(s.render_job_handle(jobs[1]).is_err());
|
||||
assert_eq!(s.render_selected_result(), Some(jobs[9]));
|
||||
assert_eq!(s.execute("render.result.select", &json!({"index":0})).unwrap(), json!({"index":0}));
|
||||
assert_eq!(s.render_selected_result(), Some(jobs[2]));
|
||||
assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(jobs[2]));
|
||||
assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(jobs[2]));
|
||||
s.execute("render.result.discard", &json!({"index":0})).unwrap();
|
||||
assert_eq!(s.render_selected_result(), Some(jobs[9]));
|
||||
assert!(s.render_job_handle(jobs[2]).is_err());
|
||||
s.execute("render.result.select", &json!({"index":2})).unwrap();
|
||||
s.execute("render.result.discard", &json!({"index":0})).unwrap();
|
||||
assert_eq!(s.render_selected_result(), Some(jobs[5]), "discarding an earlier row preserves the selected identity");
|
||||
while !s.render_retained_results().unwrap().is_empty() {
|
||||
s.execute("render.result.discard", &json!({"index":0})).unwrap();
|
||||
}
|
||||
assert!(s.render_selected_result().is_none());
|
||||
assert!(s.execute("render.result.copy", &json!({})).is_err());
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn retained_result_requests_refuse_hostile_and_missing_indices_atomically() {
|
||||
let mut s = Session::default();
|
||||
s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Front","set":{"width":8,"height":8}})).unwrap();
|
||||
let job = complete_result(&mut s, "Front");
|
||||
let document = s.doc.clone();
|
||||
let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty());
|
||||
let retained = s.render_job_host().unwrap().admitted_bytes();
|
||||
for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] {
|
||||
s.param_check = mode;
|
||||
for command in ["render.result.select", "render.result.discard"] {
|
||||
let spec = super::find_command(command).unwrap();
|
||||
assert!(spec.contract.is_some() && spec.output.is_some());
|
||||
for request in [
|
||||
json!(null),
|
||||
json!([]),
|
||||
json!({}),
|
||||
json!({"index":-1}),
|
||||
json!({"index":0.5}),
|
||||
json!({"index":1e300}),
|
||||
json!({"index":u64::MAX}),
|
||||
json!({"index":"0"}),
|
||||
json!({"index":null}),
|
||||
json!({"index":true}),
|
||||
json!({"index":1}),
|
||||
json!({"index":8}),
|
||||
json!({"index":0,"extra":true}),
|
||||
] {
|
||||
assert!(s.execute(command, &request).is_err(), "{command}: {request}");
|
||||
assert_eq!(s.render_retained_results().unwrap().len(), 1);
|
||||
assert_eq!(s.render_selected_result(), Some(job));
|
||||
assert_eq!(s.render_job_host().unwrap().admitted_bytes(), retained);
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()));
|
||||
}
|
||||
}
|
||||
}
|
||||
s.execute("render.settings.set", &json!({"name":"Front","set":{"width":16}})).unwrap();
|
||||
assert!(s.render_retained_results().unwrap()[0].stale);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.render_retained_results().unwrap()[0].stale, "undo does not recapture pixels");
|
||||
assert_eq!(s.render_retained_results().unwrap()[0].frame.scene_generation, before.2);
|
||||
let mut other = Session::default();
|
||||
assert!(other.render_retained_results().unwrap().is_empty());
|
||||
assert!(other.execute("render.result.select", &json!({"index":0})).is_err());
|
||||
assert!(other.render_job_handle(job).is_err());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_compare_validates_both_sides_and_clamps_only_finite_dividers_without_mutation() {
|
||||
let mut s = Session::default();
|
||||
s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":8,"height":8}})).unwrap();
|
||||
complete_result(&mut s, "Hero");
|
||||
complete_result(&mut s, "Hero");
|
||||
s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16}})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
|
||||
let selected = s.selection.clone();
|
||||
for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] {
|
||||
s.param_check = mode;
|
||||
for request in [json!({"left":"live","right":0}), json!({"left":1,"right":0}), json!({"left":0,"right":"live"}), json!({"off":true})] {
|
||||
assert_eq!(s.execute("render.compare", &request).unwrap(), request);
|
||||
}
|
||||
for request in [
|
||||
json!({}),
|
||||
json!([]),
|
||||
json!({"off":false}),
|
||||
json!({"off":true,"left":0}),
|
||||
json!({"left":"live","right":"live"}),
|
||||
json!({"left":0,"right":0}),
|
||||
json!({"left":"unknown","right":0}),
|
||||
json!({"left":"live","right":2}),
|
||||
json!({"left":8,"right":0}),
|
||||
json!({"left":-1,"right":0}),
|
||||
json!({"left":0.5,"right":0}),
|
||||
json!({"left":1e300,"right":"live"}),
|
||||
json!({"left":null,"right":0}),
|
||||
json!({"left":"0","right":1}),
|
||||
json!({"left":true,"right":0}),
|
||||
json!({"left":"live","right":0,"extra":true}),
|
||||
] {
|
||||
assert!(s.execute("render.compare", &request).is_err(), "{request}");
|
||||
}
|
||||
for (position, expected) in [(-1e300, 0.05), (0.0, 0.05), (0.25, 0.25), (1.0, 0.95), (1e300, 0.95)] {
|
||||
assert_eq!(s.execute("render.compare.divider", &json!({"position":position})).unwrap(), json!({"position":expected}));
|
||||
}
|
||||
for request in [json!({}), json!({"position":null}), json!({"position":"NaN"}), json!({"position":true}), json!({"position":0.5,"extra":1})] {
|
||||
assert!(s.execute("render.compare.divider", &request).is_err());
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
assert_eq!(s.selection, selected);
|
||||
assert_eq!(s.render_retained_results().unwrap().len(), 2);
|
||||
}
|
||||
let mut empty = Session::default();
|
||||
assert!(empty.execute("render.compare", &json!({"left":"live","right":0})).is_err());
|
||||
assert!(empty.execute("render.compare", &json!({"off":true})).is_err());
|
||||
for id in ["render.compare", "render.compare.divider", "render.batch"] {
|
||||
let command = super::find_command(id).unwrap();
|
||||
assert!(command.contract.is_some() && command.output.is_some() && command.planned.is_none());
|
||||
assert!(!command.undoable && !command.reads_model);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn batch_fixture(count: usize) -> Session {
|
||||
let mut s = Session::default();
|
||||
s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap();
|
||||
for index in 0..count {
|
||||
let camera = solidcraft_render::Camera { yaw: index as f64 * 0.2, roll: index as f64 * 0.01, ..Default::default() };
|
||||
s.execute("render.settings.set", &json!({"name":format!("Shot {index:02}"),"set":{"camera":camera,"width":8+index,"height":8}})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_batch_is_sequential_uses_snapshot_cameras_and_one_setup_without_design_or_history_changes() {
|
||||
let mut s = batch_fixture(3);
|
||||
s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
|
||||
let cameras: Vec<_> = s.doc.render.setups.values().map(|setup| setup.camera).collect();
|
||||
s.param_check = crate::schema::ParamCheck::Strict;
|
||||
assert_eq!(
|
||||
s.execute("render.batch", &json!({"request":{"settings":{"width":12,"height":10,"background":[7,8,9]}}})).unwrap(),
|
||||
json!({"queued":3})
|
||||
);
|
||||
assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 2));
|
||||
assert!(s.execute("render.batch", &json!({})).is_err());
|
||||
let host = s.render_job_host().unwrap().clone();
|
||||
let mut jobs = Vec::new();
|
||||
for (index, camera) in cameras.iter().enumerate() {
|
||||
let queue = s.render_queue_state();
|
||||
assert_eq!((queue.running, queue.waiting), (1, 2 - index));
|
||||
let job = queue.job.unwrap();
|
||||
let status = s.render_job_handle(job).unwrap().status().unwrap();
|
||||
assert_eq!(status.request.camera, *camera);
|
||||
assert_eq!((status.request.width, status.request.height, status.request.background), (12, 10, [7, 8, 9]));
|
||||
assert_eq!(queue.shot, Some(format!("Shot {index:02}")));
|
||||
jobs.push(job);
|
||||
for _ in 0..100 {
|
||||
if !host.pump(4096).unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let reply = s.execute("render.status", &json!({"job":job})).unwrap();
|
||||
assert_eq!(reply["progress"]["phase"], "completed");
|
||||
}
|
||||
assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0));
|
||||
assert!(s.render_queue_state().job.is_none());
|
||||
let results = s.render_retained_results().unwrap();
|
||||
assert_eq!(results.iter().map(|result| result.frame.job).collect::<Vec<_>>(), jobs);
|
||||
assert_eq!(results.iter().map(|result| result.shot.clone().unwrap()).collect::<Vec<_>>(), ["Shot 00", "Shot 01", "Shot 02"]);
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_batch_caps_at_32_and_cancel_discards_every_waiting_shot() {
|
||||
let mut s = batch_fixture(32);
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
|
||||
assert_eq!(s.execute("render.batch", &json!({})).unwrap(), json!({"queued":32}));
|
||||
let queue = s.render_queue_state();
|
||||
assert_eq!((queue.running, queue.waiting), (1, 31));
|
||||
let job = queue.job.unwrap();
|
||||
assert!(s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).is_err());
|
||||
s.execute("render.cancel", &json!({})).unwrap();
|
||||
assert_eq!(s.render_queue_state().waiting, 0);
|
||||
assert!(s.render_queue_state().job.is_none());
|
||||
s.render_job_host().unwrap().pump(4096).unwrap();
|
||||
assert!(s.render_job_handle(job).unwrap().frame().unwrap().is_none());
|
||||
for _ in 0..3 {
|
||||
assert_eq!(s.execute("render.status", &json!({})).unwrap()["queue"]["waiting"], 0);
|
||||
}
|
||||
assert!(s.render_retained_results().unwrap().is_empty());
|
||||
let next = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap();
|
||||
assert_eq!(next["job"]["serial"], 2, "Cancel must not start any waiting shot");
|
||||
s.execute("render.cancel", &json!({"job":next["job"]})).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut s.doc).render).setups.insert("Over limit".into(), Default::default());
|
||||
assert!(s.execute("render.batch", &json!({})).unwrap_err().to_string().contains("32"));
|
||||
assert_eq!(s.render_queue_state().waiting, 0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_batch_refuses_missing_shots_busy_hostile_and_failed_requests_without_queuing() {
|
||||
let mut empty = batch_fixture(0);
|
||||
assert!(empty.execute("render.batch", &json!({})).is_err());
|
||||
let mut s = batch_fixture(2);
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty());
|
||||
for request in [
|
||||
json!([]),
|
||||
json!({"request":1e300}),
|
||||
json!({"request":[]}),
|
||||
json!({"request":{"bogus":true}}),
|
||||
json!({"request":{"replace":true}}),
|
||||
json!({"request":{"settings":{"width":0}}}),
|
||||
json!({"extra":true}),
|
||||
] {
|
||||
assert!(s.execute("render.batch", &request).is_err(), "{request}");
|
||||
assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0));
|
||||
assert!(s.render_queue_state().job.is_none());
|
||||
}
|
||||
let job = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap()["job"].clone();
|
||||
assert!(s.execute("render.batch", &json!({})).is_err());
|
||||
assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 0));
|
||||
s.execute("render.cancel", &json!({"job":job})).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
s.set_render_job_host(None).unwrap();
|
||||
assert!(s.execute("render.batch", &json!({})).is_err());
|
||||
assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0));
|
||||
assert!(s.render_queue_state().error.is_some());
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_batch_cameras_and_common_setup_are_captured_before_later_shot_edits() {
|
||||
let mut s = batch_fixture(2);
|
||||
let original = s.doc.render.setups.get("Shot 01").unwrap().camera;
|
||||
s.execute("render.batch", &json!({"request":{"setup":"Shot 00"}})).unwrap();
|
||||
let first = s.render_queue_state().job.unwrap();
|
||||
let changed = solidcraft_render::Camera { yaw: 2.0, ..Default::default() };
|
||||
s.execute("render.settings.set", &json!({"name":"Shot 01","set":{"camera":changed}})).unwrap();
|
||||
s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap();
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations);
|
||||
let host = s.render_job_host().unwrap().clone();
|
||||
for _ in 0..100 {
|
||||
if !host.pump(4096).unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let reply = s.execute("render.status", &json!({})).unwrap();
|
||||
let next: solidcraft_render::job::JobId = serde_json::from_value(reply["queue"]["job"].clone()).unwrap();
|
||||
assert_ne!(next, first);
|
||||
let request = s.render_job_handle(next).unwrap().status().unwrap().request;
|
||||
assert_eq!(request.camera, original);
|
||||
assert_eq!(request.width, 8);
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations));
|
||||
s.execute("render.cancel", &json!({"job":next})).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn render_results_compare_keeps_copy_on_the_visible_result_until_a_source_is_evicted() {
|
||||
let mut s = batch_fixture(1);
|
||||
let first = complete_result(&mut s, "Shot 00");
|
||||
complete_result(&mut s, "Shot 00");
|
||||
s.execute("render.compare", &json!({"left":"live","right":0})).unwrap();
|
||||
assert_eq!(s.render_comparison(), Some([None, Some(first)]));
|
||||
assert_eq!(s.render_selected_result(), Some(first));
|
||||
let document = s.doc.clone();
|
||||
let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations);
|
||||
let mut newest = first;
|
||||
for index in 0..7 {
|
||||
newest = complete_result(&mut s, "Shot 00");
|
||||
if index < 6 {
|
||||
assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(first));
|
||||
assert_eq!(s.render_comparison(), Some([None, Some(first)]));
|
||||
}
|
||||
}
|
||||
assert!(s.render_comparison().is_none());
|
||||
assert_eq!(s.render_selected_result(), Some(newest));
|
||||
assert!(std::sync::Arc::ptr_eq(&document, &s.doc));
|
||||
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations));
|
||||
}
|
||||
@@ -36,6 +36,19 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| bad(cmd, "`feature` must be a feature object, as a design file or timeline.inspect has it"))?;
|
||||
let mut raw = raw.clone();
|
||||
if let Some(Value::Object(def)) = raw.remove("definition") {
|
||||
for (k, v) in def {
|
||||
raw.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
for meta in ["omitted", "inputs", "error", "warning", "boolean_diagnostics", "rolled_back", "type_name"] {
|
||||
raw.remove(meta);
|
||||
}
|
||||
if let Some(kind_str) = raw.get("type").and_then(Value::as_str)
|
||||
&& let Some(canonical) = FeatureKind::type_name_to_kind_key(kind_str)
|
||||
{
|
||||
raw.insert("type".into(), json!(canonical));
|
||||
}
|
||||
resolve_legacy_names(&mut raw, &s.doc);
|
||||
let feature = recorded_feature(cmd, &raw)?;
|
||||
let params = step_params(cmd, p.get("params"))?;
|
||||
|
||||
@@ -244,6 +244,34 @@ fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() {
|
||||
assert!(s.doc.feature(r["feature"].as_u64().unwrap()).is_some_and(|f| !f.param_names.is_empty()), "its inputs get parameter names");
|
||||
}
|
||||
|
||||
/// #10748: `timeline.inspect` reports a feature's design variant name in `type` and display name
|
||||
/// in `type_name`; `timeline.add` accepts `timeline.inspect` results and inspect type names.
|
||||
#[test]
|
||||
fn timeline_add_accepts_inspect_result_and_type_names() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "name": "Block"}));
|
||||
let mut inspected = run(&mut s, "timeline.inspect", json!({"feature": "Block"}));
|
||||
assert_eq!(inspected["type"], "box", "inspect type is the design file variant name");
|
||||
assert_eq!(inspected["type_name"], "BoxFeature", "inspect type_name is the display type");
|
||||
|
||||
// 1. timeline.add accepts the full inspected object directly in a new session
|
||||
let mut s2 = Session::default();
|
||||
let added = run(&mut s2, "timeline.add", json!({"feature": inspected.clone()}));
|
||||
assert!(added["error"].is_null(), "{added}");
|
||||
assert_eq!(s2.doc.features.len(), 1);
|
||||
|
||||
// 2. timeline.add with id 0 allocates a new id in the current session
|
||||
inspected["id"] = json!(0);
|
||||
let added2 = run(&mut s, "timeline.add", json!({"feature": inspected}));
|
||||
assert!(added2["error"].is_null(), "{added2}");
|
||||
assert_eq!(s.doc.features.len(), 2);
|
||||
|
||||
// 3. timeline.add accepts the inspect type name (e.g. BoxFeature, HoleFeature)
|
||||
let added_by_type_name =
|
||||
run(&mut s, "timeline.add", json!({"feature": {"type": "BoxFeature", "length": "5", "width": "5", "height": "5", "corner": [50, 0, 0]}}));
|
||||
assert!(added_by_type_name["error"].is_null(), "{added_by_type_name}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_script_is_written_to_a_file_that_replays() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -20,19 +20,50 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let camera = camera(p)?;
|
||||
let rows = rows(p)?;
|
||||
let wanted = body_names(p)?;
|
||||
let out = outline(s, &camera, wanted.as_deref(), rows)?;
|
||||
let mask: Vec<Vec<[usize; 2]>> = out.mask.iter().map(|row| spans(row)).collect();
|
||||
Ok(json!({
|
||||
"width": out.width,
|
||||
"height": out.height,
|
||||
"mm_per_px": round4(out.mm_per_px),
|
||||
"box_mm": [[round4(out.lo[0]), round4(out.lo[1])], [round4(out.hi[0]), round4(out.hi[1])]],
|
||||
"right": [clean(out.right.x), clean(out.right.y), clean(out.right.z)],
|
||||
"up": [clean(out.up.x), clean(out.up.y), clean(out.up.z)],
|
||||
"projection": if out.perspective { "perspective" } else { "parallel" },
|
||||
"bodies": out.bodies,
|
||||
"triangles": out.triangles,
|
||||
"mask": mask,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A projected, tightly framed silhouette: the pixel grid, its scale and placement, and the
|
||||
/// filled mask as one row of booleans per pixel row. `inspect.silhouette` renders this as
|
||||
/// run-length rows; `inspect.compare_picture` uses the filled rows directly.
|
||||
pub(crate) struct Silhouette {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub mm_per_px: f64,
|
||||
/// The view-plane box the mask frames, in mm (u along `right`, v along `up`).
|
||||
pub lo: [f64; 2],
|
||||
pub hi: [f64; 2],
|
||||
pub right: Vec3,
|
||||
pub up: Vec3,
|
||||
pub perspective: bool,
|
||||
pub bodies: usize,
|
||||
pub triangles: usize,
|
||||
pub mask: Vec<Vec<bool>>,
|
||||
}
|
||||
|
||||
pub(crate) fn outline(s: &Session, camera: &Camera, wanted: Option<&[String]>, rows: usize) -> Result<Silhouette> {
|
||||
let state = s.world_state()?;
|
||||
if let Some(names) = &wanted {
|
||||
if let Some(names) = wanted {
|
||||
for name in names {
|
||||
if !state.bodies.iter().any(|b| b.name == *name) {
|
||||
return Err(bad(CMD, format!("unknown body name `{name}`")));
|
||||
}
|
||||
}
|
||||
}
|
||||
let bodies: Vec<_> = state
|
||||
.bodies
|
||||
.iter()
|
||||
.filter(|b| wanted.as_ref().map_or_else(|| s.body_visible(&b.name), |names| names.iter().any(|name| name == &b.name)))
|
||||
.collect();
|
||||
let bodies: Vec<_> = state.bodies.iter().filter(|b| wanted.map_or_else(|| s.body_visible(&b.name), |names| names.contains(&b.name))).collect();
|
||||
if bodies.is_empty() {
|
||||
return Err(bad(CMD, "nothing visible to outline"));
|
||||
}
|
||||
@@ -133,22 +164,22 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
let mask: Vec<Vec<[usize; 2]>> = covered.chunks_exact(width).map(spans).collect();
|
||||
Ok(json!({
|
||||
"width": width,
|
||||
"height": height,
|
||||
"mm_per_px": round4(mm_per_px),
|
||||
"box_mm": [[round4(lo[0]), round4(lo[1])], [round4(hi[0]), round4(hi[1])]],
|
||||
"right": [clean(right.x), clean(right.y), clean(right.z)],
|
||||
"up": [clean(up.x), clean(up.y), clean(up.z)],
|
||||
"projection": if perspective { "perspective" } else { "parallel" },
|
||||
"bodies": bodies.len(),
|
||||
"triangles": triangle_count,
|
||||
"mask": mask,
|
||||
}))
|
||||
Ok(Silhouette {
|
||||
width,
|
||||
height,
|
||||
mm_per_px,
|
||||
lo,
|
||||
hi,
|
||||
right,
|
||||
up,
|
||||
perspective,
|
||||
bodies: bodies.len(),
|
||||
triangles: triangle_count,
|
||||
mask: covered.chunks_exact(width).map(|row| row.to_vec()).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn camera(p: &Value) -> Result<Camera> {
|
||||
pub(crate) fn camera(p: &Value) -> Result<Camera> {
|
||||
if p.get("view").is_some() && p.get("camera").is_some() {
|
||||
return Err(bad(CMD, "give `view` or `camera`, not both"));
|
||||
}
|
||||
@@ -171,7 +202,7 @@ fn camera(p: &Value) -> Result<Camera> {
|
||||
Ok(camera)
|
||||
}
|
||||
|
||||
fn body_names(p: &Value) -> Result<Option<Vec<String>>> {
|
||||
pub(crate) fn body_names(p: &Value) -> Result<Option<Vec<String>>> {
|
||||
match p.get("bodies") {
|
||||
None => Ok(None),
|
||||
Some(Value::String(name)) => Ok(Some(vec![name.clone()])),
|
||||
@@ -184,7 +215,7 @@ fn body_names(p: &Value) -> Result<Option<Vec<String>>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(p: &Value) -> Result<usize> {
|
||||
pub(crate) fn rows(p: &Value) -> Result<usize> {
|
||||
match p.get("rows") {
|
||||
None => Ok(240),
|
||||
Some(v) => {
|
||||
@@ -209,7 +240,7 @@ fn edge(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> f64 {
|
||||
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
|
||||
}
|
||||
|
||||
fn spans(row: &[bool]) -> Vec<[usize; 2]> {
|
||||
pub(crate) fn spans(row: &[bool]) -> Vec<[usize; 2]> {
|
||||
let mut out = Vec::new();
|
||||
let mut start = None;
|
||||
for (x, &on) in row.iter().enumerate() {
|
||||
|
||||
@@ -472,6 +472,9 @@ const CONNECT_TOL: f64 = 1e-6;
|
||||
|
||||
/// New points (index `first` on) that land on an existing point, the origin included, get a
|
||||
/// coincident constraint to it, as when a click snaps there; `connect: false` leaves them free.
|
||||
/// A point placed by parameter expressions is never tied: it follows its expressions, and a
|
||||
/// Coincident to where the expressions happened to come to at draw time conflicts with the
|
||||
/// next parameter change (#10703).
|
||||
fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result<Vec<String>> {
|
||||
if !bool_(p, "connect").unwrap_or(true) {
|
||||
return Ok(Vec::new());
|
||||
@@ -481,6 +484,9 @@ fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result<Vec<String
|
||||
old.sort_by(|a, b| a.0.x.total_cmp(&b.0.x));
|
||||
let mut ties = Vec::new();
|
||||
for q in first..sk.points.len() {
|
||||
if sk.points.get(q).is_some_and(|pt| pt.exprs.is_some()) {
|
||||
continue;
|
||||
}
|
||||
let Some(at) = sk.point(q) else { continue };
|
||||
let from = old.partition_point(|(o, _)| o.x < at.x - CONNECT_TOL);
|
||||
let hit =
|
||||
|
||||
@@ -16,7 +16,7 @@ use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_pa
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, num, req_vec2, str_, string_list};
|
||||
use crate::schema::sketch_create::{SplineReverseParams, SplineReverseResult};
|
||||
use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -29,6 +29,7 @@ mod text_move_tests;
|
||||
mod text_expr_tests;
|
||||
|
||||
const SPLINE_REVERSE_CONTRACT: TypedContract<SplineReverseParams> = TypedContract::new();
|
||||
const SPLINE_REMOVE_POINT_CONTRACT: TypedContract<SplineRemovePointParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line)
|
||||
@@ -88,6 +89,12 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("spline")
|
||||
.enabled(in_sketch)
|
||||
.params("curve: fit point spline id, at: [x,y]: a fit point is inserted where the curve passes nearest to it, between its neighbours (the curve still runs through it and all its old points; constraints on them stay); end?: start|end: `at` becomes the spline's new first or last point instead, and the curve runs on to it (refused when that end is joined to other geometry). Control point splines take no new points yet. Returns point: the new point's id"),
|
||||
CommandSpec::new("sketch.spline.remove_point", "Remove Spline Point", crate::checked!("sketch.spline.remove_point", spline_remove_point))
|
||||
.icon("spline")
|
||||
.enabled(in_sketch)
|
||||
.contract(&SPLINE_REMOVE_POINT_CONTRACT)
|
||||
.output(output_schema_for::<SplineRemovePointResult>)
|
||||
.params("curve: spline id, point: one of its points (a point id, or the curve's start or end such as s1.end): the spline runs through (or over) its other points only, and the point goes with the constraints on it unless another curve uses it. Fit point, control point and closed splines. Refused for a closed spline's closing point, for an end joined to other geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed spline), and for a projected, offset or patterned spline. Returns curve, point: the point's id, deleted: whether the point went too"),
|
||||
CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse))
|
||||
.icon("spline")
|
||||
.enabled(in_sketch)
|
||||
@@ -705,6 +712,22 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info}))
|
||||
}
|
||||
|
||||
/// One point taken out of a spline (#10783).
|
||||
fn spline_remove_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.spline.remove_point";
|
||||
let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string();
|
||||
let point = str_(p, "point").ok_or_else(|| bad(cmd, "`point` must be one of the spline's points"))?.to_string();
|
||||
let ((point, deleted), info) = edit(s, p, cmd, false, |sk, _| {
|
||||
let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?;
|
||||
let at = sk.resolve_point(&point).ok_or_else(|| bad(cmd, format!("unknown sketch point `{point}`")))?;
|
||||
let name = sk.points.get(at).map_or(point.clone(), |q| q.id.clone());
|
||||
let deleted = sk.remove_spline_point(c, at).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok((name, deleted))
|
||||
})?;
|
||||
let reply = SplineRemovePointResult { curve: id, point, deleted, sketch: info, param_warnings: Vec::new() };
|
||||
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
fn spline_reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.spline.reverse";
|
||||
let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string();
|
||||
|
||||
@@ -245,6 +245,11 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
let v = (q - pivot) * k;
|
||||
Vec2::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos) + off
|
||||
};
|
||||
// A dense SVG/DXF (a floorplan) can yield far more entities than a sketch takes; refuse
|
||||
// before adding so the message names the cap (#10874). Scale alone does not shrink the count.
|
||||
if geom.len() > solidcraft_sketch::MAX_POINTS {
|
||||
return Err(solidcraft_sketch::SketchError::TooLarge.into());
|
||||
}
|
||||
let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| {
|
||||
let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?;
|
||||
Ok((ids_of(sk, &cs), texts))
|
||||
@@ -371,6 +376,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #10874: a drawing with more entities than a sketch can hold is refused with the point
|
||||
/// cap and that scale alone does not help (a floorplan SVG often hits this).
|
||||
#[test]
|
||||
fn a_drawing_with_too_many_entities_names_the_sketch_cap() {
|
||||
let n = solidcraft_sketch::MAX_POINTS + 1;
|
||||
let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..n {
|
||||
dxf.push_str(&format!("0\nLINE\n10\n{i}\n20\n0\n11\n{}\n21\n1\n", i + 1));
|
||||
}
|
||||
dxf.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
let mut s = Session::default();
|
||||
let e = s.execute("sketch.insert_dxf", &json!({"text": dxf})).unwrap_err().to_string();
|
||||
assert!(e.contains("20000") && e.contains("scale"), "{e}");
|
||||
assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind");
|
||||
}
|
||||
|
||||
/// #9641: an SVG with nothing SolidCraft can draw (here only an embedded picture) is refused
|
||||
/// with a message naming the file and saying why, not "invalid parameters … no geometry"; a
|
||||
/// UTF-16 SVG file inserts.
|
||||
|
||||
@@ -48,7 +48,8 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.params(concat!(
|
||||
"curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain, including ends that only coincide). A corner is trimmed back to the crossing when the offset runs past it, and extended until the offset curves intersect when the corner falls short; ",
|
||||
"direction?: one_side|symmetric (default one_side) or symmetric?: bool (the same distance each way; no `side`, whose job it takes over), ",
|
||||
"distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions",
|
||||
"distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions; ",
|
||||
"instances?: whole number or unitless expression, 1…100 (default 1): each instance after the first offsets the instance before it by the same distance again, so instance n stands n distances from the curves picked. Every instance of a side is driven by that side's own dimension, and each entry of `sides` names its `instance`; an instance the shape cannot take refuses the whole command",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.offset.break", "Break Offset Association", break_offset).icon("sketch_break")
|
||||
@@ -112,6 +113,10 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
|
||||
const TOL: f64 = 1e-7;
|
||||
const MAX_COPIES: usize = 500;
|
||||
/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance
|
||||
/// is its own association, so this stays below the sketch's own caps on analytic offset groups
|
||||
/// and free-form associations (both 128).
|
||||
const MAX_INSTANCES: usize = 100;
|
||||
|
||||
fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result<usize> {
|
||||
let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?;
|
||||
@@ -2386,6 +2391,24 @@ fn offset_length(s: &Session, p: &Value, key: &str, positive: bool) -> Result<(f
|
||||
Ok((value, expression))
|
||||
}
|
||||
|
||||
/// `instances`: how many offsets stand one behind the other, each at the same distance from the
|
||||
/// one before it. A number or a unitless expression; one (the offset by itself) by default.
|
||||
fn offset_instances(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
let message = format!("`instances` must be a whole number from 1 to {MAX_INSTANCES}, or an expression for one");
|
||||
let count = match p.get("instances") {
|
||||
None | Some(Value::Null) => return Ok(1),
|
||||
Some(Value::Number(_)) => num(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?,
|
||||
Some(_) => {
|
||||
let expression = expr(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?.into_string();
|
||||
s.doc.eval(&expression, solidcraft_doc::expr::Kind::Unitless).map_err(|error| bad(cmd, format!("`instances`: {error}")))?
|
||||
}
|
||||
};
|
||||
if !count.is_finite() || count.fract() != 0.0 || !(1.0..=MAX_INSTANCES as f64).contains(&count) {
|
||||
return Err(bad(cmd, message));
|
||||
}
|
||||
Ok(count as usize)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct OffsetOptions {
|
||||
side: Option<Vec2>,
|
||||
@@ -2520,6 +2543,125 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha
|
||||
Ok(sides)
|
||||
}
|
||||
|
||||
/// One rung of an offset ladder: the offsets of `ids`, with the infinite flag carried over from
|
||||
/// infinite sources (#1359) and a driving dimension on each side that is linked to its source.
|
||||
/// `names` is the parameter each side is driven by, in side order, falling back to the first for
|
||||
/// a side the rung before it had none for. The sources the rung consumed come back with it.
|
||||
fn offset_rung(
|
||||
sk: &mut Sketch,
|
||||
cmd: &str,
|
||||
ids: &[String],
|
||||
eligible: &std::collections::HashSet<String>,
|
||||
options: OffsetOptions,
|
||||
names: &[String],
|
||||
) -> Result<(Vec<Side>, Vec<String>)> {
|
||||
let mut group = offset_group(sk, ids, eligible, options)?;
|
||||
let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?;
|
||||
let sources = sk
|
||||
.offsets
|
||||
.iter()
|
||||
.find(|o| o.owns_output(output))
|
||||
.map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>())
|
||||
.or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()]))
|
||||
.or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone()))
|
||||
.ok_or_else(|| bad(cmd, "offset association is missing"))?;
|
||||
// An offset of infinite lines is infinite lines too (#1359).
|
||||
let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite));
|
||||
if infinite {
|
||||
for id in group.iter().flat_map(|side| side.curves.iter()) {
|
||||
if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c))
|
||||
&& matches!(cu.kind, CurveKind::Line { .. })
|
||||
{
|
||||
cu.infinite = true;
|
||||
cu.construction = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, side) in group.iter_mut().enumerate() {
|
||||
// A trimmed offset is not linked to its source: it has no distance to drive.
|
||||
if side.unlinked_sources.is_some() {
|
||||
continue;
|
||||
}
|
||||
let name = names.get(index).or_else(|| names.first()).ok_or_else(|| bad(cmd, "offset has no driving dimension"))?;
|
||||
let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?;
|
||||
side.constraints.push(sk.add_constraint(
|
||||
ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 },
|
||||
Some(name.clone()),
|
||||
)?);
|
||||
side.param = Some(name.clone());
|
||||
}
|
||||
Ok((group, sources))
|
||||
}
|
||||
|
||||
/// Where the next instance of an offset belongs: one more step the way the rung already went.
|
||||
/// The rung's own normal-distance annotation knows that, since its ends are the middle of its
|
||||
/// first source curve and the point one signed distance away on the rung itself; the same step
|
||||
/// again lands one distance past the rung. The side is taken from the geometry this way rather
|
||||
/// than from the sign again, because an output's stored ends need not run the way the chain
|
||||
/// through them is walked, and a reversed walk reads the same sign as the other side. A trimmed
|
||||
/// offset has no annotation and is ordinary geometry: `None` leaves the sign to speak for it.
|
||||
fn offset_beyond(sk: &Sketch, rung: &[String]) -> Option<Vec2> {
|
||||
// A circle offsets concentrically: there is no chain to walk and so no walk direction to
|
||||
// mistake, and its own side is read as "outside the current radius". A step past a ring
|
||||
// smaller than the distance lands beyond the centre, which reads as outside and would turn
|
||||
// an inward ladder round into a growing one instead of letting it run out of room. Its
|
||||
// signed distance already says which way, so leave the side to it.
|
||||
let index = sk.curve_index(rung.first()?)?;
|
||||
if matches!(sk.curves.get(index)?.kind, CurveKind::Circle { .. }) {
|
||||
return None;
|
||||
}
|
||||
let (from, to) = sk.offset_dimension_points(rung.first()?)?;
|
||||
(from.dist(to) > TOL).then(|| to + (to - from))
|
||||
}
|
||||
|
||||
/// What one side of a rung leaves for the next: the curves to offset again, its own signed
|
||||
/// distance, and the dimension its whole ladder is driven by.
|
||||
fn offset_leaves(side: &Side, fallback: &str) -> (Vec<String>, f64, String) {
|
||||
(side.curves.clone(), side.distance, side.param.clone().unwrap_or_else(|| fallback.to_string()))
|
||||
}
|
||||
|
||||
/// Every offset of one connected source group: the first rung at the distances asked for, then
|
||||
/// one more rung per extra instance, each offsetting the rung before it the same way and the
|
||||
/// same distance again, so instance n stands n distances from the curves picked. Each side comes
|
||||
/// back paired with the instance it belongs to, and the first rung's sources come with them, so
|
||||
/// the caller can take those out of the selection it is still working through.
|
||||
fn offset_ladder(
|
||||
sk: &mut Sketch,
|
||||
cmd: &str,
|
||||
ids: &[String],
|
||||
eligible: &std::collections::HashSet<String>,
|
||||
options: OffsetOptions,
|
||||
instances: usize,
|
||||
names: &[String],
|
||||
) -> Result<(Vec<(usize, Side)>, Vec<String>)> {
|
||||
let primary = names.first().cloned().ok_or_else(|| bad(cmd, "offset has no driving dimension"))?;
|
||||
let (first, sources) = offset_rung(sk, cmd, ids, eligible, options, names)?;
|
||||
let mut rung: Vec<(Vec<String>, f64, String)> = first.iter().map(|side| offset_leaves(side, &primary)).collect();
|
||||
let mut sides: Vec<(usize, Side)> = first.into_iter().map(|side| (1, side)).collect();
|
||||
for instance in 2..=instances {
|
||||
let mut next = Vec::new();
|
||||
for (curves, distance, name) in &rung {
|
||||
// One side at a time from here: the side this rung follows is the whole of its
|
||||
// direction, so `side`, `symmetric` and `distance2` had their say in the first rung.
|
||||
let beyond = offset_beyond(sk, curves);
|
||||
let step = OffsetOptions { side: beyond, chain: false, distance: *distance, symmetric: false, distance2: None };
|
||||
// Which instance ran out of room is the whole of the answer, so the refusal names it
|
||||
// in front of the reason, rather than wrapping one "invalid parameters" in another.
|
||||
let (made, _) = offset_rung(sk, cmd, curves, eligible, step, std::slice::from_ref(name)).map_err(|error| {
|
||||
let reason = match &error {
|
||||
crate::EngineError::BadParams { msg, .. } => msg.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
bad(cmd, format!("instance {instance} of {instances}: {reason}"))
|
||||
})?;
|
||||
next.extend(made.iter().map(|side| offset_leaves(side, name)));
|
||||
sides.extend(made.into_iter().map(|side| (instance, side)));
|
||||
}
|
||||
rung = next;
|
||||
}
|
||||
Ok((sides, sources))
|
||||
}
|
||||
|
||||
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.offset";
|
||||
let ids = string_list(cmd, p, "curves")?;
|
||||
@@ -2550,6 +2692,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if symmetric && side.is_some() {
|
||||
return Err(bad(cmd, "`symmetric` offsets both sides, so `side` has no side left to pick: drop one of them"));
|
||||
}
|
||||
let instances = offset_instances(s, p, cmd)?;
|
||||
let ((sides, param, param2), info) = edit(s, p, cmd, true, |sk, doc| {
|
||||
sk.refresh_offsets()?;
|
||||
let rep = solve_current(sk, doc)?;
|
||||
@@ -2564,41 +2707,8 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut pending = ids.clone();
|
||||
let mut sides = Vec::new();
|
||||
while !pending.is_empty() {
|
||||
let mut group = offset_group(sk, &pending, &eligible, OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 })?;
|
||||
let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?;
|
||||
let sources = sk
|
||||
.offsets
|
||||
.iter()
|
||||
.find(|o| o.owns_output(output))
|
||||
.map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>())
|
||||
.or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()]))
|
||||
.or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone()))
|
||||
.ok_or_else(|| bad(cmd, "offset association is missing"))?;
|
||||
// An offset of infinite lines is infinite lines too (#1359).
|
||||
let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite));
|
||||
if infinite {
|
||||
for id in group.iter().flat_map(|side| side.curves.iter()) {
|
||||
if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c))
|
||||
&& matches!(cu.kind, CurveKind::Line { .. })
|
||||
{
|
||||
cu.infinite = true;
|
||||
cu.construction = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, side) in group.iter_mut().enumerate() {
|
||||
// A trimmed offset is not linked to its source: it has no distance to drive.
|
||||
if side.unlinked_sources.is_some() {
|
||||
continue;
|
||||
}
|
||||
let name = if index == 1 { param2.as_ref().unwrap_or(¶m) } else { ¶m };
|
||||
let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?;
|
||||
side.constraints.push(sk.add_constraint(
|
||||
ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 },
|
||||
Some(name.clone()),
|
||||
)?);
|
||||
side.param = Some(name.clone());
|
||||
}
|
||||
let options = OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 };
|
||||
let (group, sources) = offset_ladder(sk, cmd, &pending, &eligible, options, instances, &made)?;
|
||||
let before = pending.len();
|
||||
pending.retain(|id| !sources.contains(id));
|
||||
if pending.len() == before {
|
||||
@@ -2607,31 +2717,31 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sides.extend(group);
|
||||
}
|
||||
// Parameters made for distances that only trimmed (unlinked) offsets used drive nothing.
|
||||
let used = |name: &String| sides.iter().any(|side: &Side| side.param.as_ref() == Some(name));
|
||||
let used = |name: &String| sides.iter().any(|(_, side): &(usize, Side)| side.param.as_ref() == Some(name));
|
||||
let param = used(¶m).then_some(param);
|
||||
let param2 = param2.filter(|name| used(name));
|
||||
doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name));
|
||||
Ok((sides, param, param2))
|
||||
})?;
|
||||
let curves: Vec<&String> = sides.iter().flat_map(|side| side.curves.iter()).collect();
|
||||
let constraints: Vec<&String> = sides.iter().flat_map(|side| side.constraints.iter()).collect();
|
||||
let curves: Vec<&String> = sides.iter().flat_map(|(_, side)| side.curves.iter()).collect();
|
||||
let constraints: Vec<&String> = sides.iter().flat_map(|(_, side)| side.constraints.iter()).collect();
|
||||
let each: Vec<Value> = sides
|
||||
.iter()
|
||||
.map(|side| {
|
||||
let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param});
|
||||
.map(|(instance, side)| {
|
||||
let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param, "instance": instance});
|
||||
if let Some(association) = &side.association {
|
||||
entry["association"] = json!(association);
|
||||
}
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param});
|
||||
let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param,"instances":instances});
|
||||
if let Some(param2) = param2 {
|
||||
response["param2"] = json!(param2);
|
||||
}
|
||||
// One side keeps the single `association` it always returned. Two sides have one each, in
|
||||
// `sides`, so there is no single association left to name.
|
||||
if let [only] = sides.as_slice()
|
||||
// One side keeps the single `association` it always returned. Two sides, or an instance
|
||||
// behind another, have one each in `sides`, so there is no single association left to name.
|
||||
if let [(_, only)] = sides.as_slice()
|
||||
&& let Some(association) = &only.association
|
||||
{
|
||||
response["association"] = json!(association);
|
||||
|
||||
@@ -1492,6 +1492,64 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() {
|
||||
assert_eq!(sketch(&s), unchanged, "refusals change nothing");
|
||||
}
|
||||
|
||||
/// Remove Spline Point (#10783): one fit point goes, with the dimension on it. The spline runs
|
||||
/// through its other points, which stay where they were, and the line joined to its end stays.
|
||||
/// Undo puts the point back. The end the line joins, a line and an unknown point are refused; a
|
||||
/// control point spline gives up a point too.
|
||||
#[test]
|
||||
fn a_point_removed_from_a_spline_goes_with_its_dimension_and_undoes() {
|
||||
let mut s = new_sketch();
|
||||
let sid =
|
||||
ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0], [30, 6]], "connect": false}))["curves"])[0].clone();
|
||||
run(&mut s, "sketch.line", json!({"points": [format!("{sid}.end"), [40, 6]], "connect": false}));
|
||||
let sk = sketch(&s);
|
||||
let si = sk.curve_index(&sid).unwrap();
|
||||
let names: Vec<String> = sk.curves[si].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect();
|
||||
run(&mut s, "sketch.dimension", json!({"entities": [names[1], names[2]], "value": 12.8}));
|
||||
let before = sketch(&s);
|
||||
let at = |sk: &solidcraft_sketch::Sketch, id: &str| sk.point(sk.point_index(id).unwrap()).unwrap();
|
||||
|
||||
let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": sid, "point": names[1]}));
|
||||
assert_eq!((r["curve"].as_str(), r["point"].as_str(), r["deleted"].as_bool()), (Some(sid.as_str()), Some(names[1].as_str()), Some(true)), "{r}");
|
||||
let after = sketch(&s);
|
||||
assert!(after.point_index(&names[1]).is_none(), "the point went");
|
||||
let left: Vec<String> = after.curves[si].kind.point_ids().iter().map(|i| after.points[*i].id.clone()).collect();
|
||||
assert_eq!(left, [names[0].clone(), names[2].clone(), names[3].clone()]);
|
||||
let segs = after.exact_segs(si).unwrap();
|
||||
for id in &left {
|
||||
let q = at(&after, id);
|
||||
assert!(q.dist(at(&before, id)) < 1e-9, "{id} stays where it was");
|
||||
let off = segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min);
|
||||
assert!(off < 1e-9, "the curve runs through {id}");
|
||||
}
|
||||
assert!(after.constraints.iter().all(|c| c.kind.value().is_none()), "the dimension on the point went");
|
||||
let joined = after.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { a, .. } if after.points[a].id == names[3]));
|
||||
assert!(joined, "the line still starts at the spline's end");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(sketch(&s), before, "undo puts the point back");
|
||||
|
||||
let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone();
|
||||
for (p, why) in [
|
||||
(json!({"curve": sid, "point": format!("{sid}.end")}), "joined"),
|
||||
(json!({"curve": line, "point": names[0]}), "spline"),
|
||||
(json!({"curve": sid, "point": "nope"}), "unknown sketch point"),
|
||||
(json!({"curve": sid}), "`point`"),
|
||||
] {
|
||||
let e = s.execute("sketch.spline.remove_point", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(sketch(&s), before, "refusals change nothing");
|
||||
|
||||
let cv =
|
||||
ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [20, 20]], "connect": false}))["curves"])[0].clone();
|
||||
let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": cv, "point": format!("{cv}.start")}));
|
||||
assert_eq!(r["deleted"], json!(true), "{r}");
|
||||
let sk = sketch(&s);
|
||||
let ci = sk.curve_index(&cv).unwrap();
|
||||
let left: Vec<Vec2> = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect();
|
||||
assert_eq!(left, [Vec2::new(10.0, 30.0), Vec2::new(20.0, 20.0)]);
|
||||
}
|
||||
|
||||
/// Reverse Spline Direction (#8224): a fit, a control point and a closed spline each run the
|
||||
/// other way along the same path, their ends swapped. Their points, the constraints on them and
|
||||
/// a line joined to an end stay, and undo restores the spline. A line and the source and output
|
||||
@@ -1880,7 +1938,7 @@ fn fillet_a_line_and_an_arc() {
|
||||
fn fillet_a_line_and_an_arc_drawn_to_meet_at_a_point() {
|
||||
// #1208: the arc starts at the line's end by coordinates, so the corner is two points held
|
||||
// together by a Coincident constraint. By point and by naming the two curves.
|
||||
for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"})] {
|
||||
for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"}), json!({"a": "a1", "b": "l1"})] {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]}));
|
||||
run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"}));
|
||||
@@ -1946,6 +2004,38 @@ fn fillet_a_coincident_corner_that_a_dimension_measures_to() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fillet_coincident_line_and_arc_selection_order() {
|
||||
for held in ["l1.end", "a1.end"] {
|
||||
for (a, b) in [("l1", "a1"), ("a1", "l1")] {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]}));
|
||||
run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"}));
|
||||
// Keep the fixed sharp corner in place, whichever endpoint is fixed or picked
|
||||
// first when rounding the same corner.
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entity": held}));
|
||||
let before = serde_json::to_value(sketch(&s)).unwrap();
|
||||
let f = run(&mut s, "sketch.fillet", json!({"a": a, "b": b, "radius": 3}));
|
||||
let sk = sketch(&s);
|
||||
let ai = sk.curve_index(&ids(&f["curves"])[0]).unwrap();
|
||||
let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0);
|
||||
assert!((sk.radius(ai).unwrap() - 3.0).abs() < 1e-7, "{held}: {a}, {b}");
|
||||
assert!(sk.center(ai).unwrap().dist(want) < 1e-6, "{held}: {a}, {b}");
|
||||
let fixed = sk
|
||||
.constraints
|
||||
.iter()
|
||||
.find_map(|c| match c.kind {
|
||||
ConstraintKind::Fix { p } => Some(p),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(sk.point(fixed).unwrap().dist(Vec2::new(40.0, 0.0)) < 1e-6);
|
||||
assert_eq!(run(&mut s, "sketch.inspect", json!({}))["status"], "solved");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn chamfer_two_lines_drawn_to_meet_at_a_point() {
|
||||
let mut s = new_sketch();
|
||||
@@ -2429,6 +2519,143 @@ fn offset_two_sides_of_one_curve_follows_the_sign_of_the_distance() {
|
||||
assert!(close(one.1.x - one.0.x, 40.0) && close(two.1.x - two.0.x, 40.0), "{one:?} {two:?}");
|
||||
}
|
||||
|
||||
/// Each instance of an outward offset of a 40 by 30 rectangle, as a box one more step out.
|
||||
fn offset_rings(sk: &solidcraft_sketch::Sketch, o: &Value, out: &[f64]) {
|
||||
for (index, out) in out.iter().copied().enumerate() {
|
||||
let curves = side_curves(o, index);
|
||||
assert_eq!(curves.len(), 4, "{o}");
|
||||
assert!(box_is(sk, &curves, [-out, -out], [40.0 + out, 30.0 + out]), "instance {}: {:?}", index + 1, bounds(sk, &curves));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_stack_one_behind_another_at_the_same_distance() {
|
||||
let mut s = new_sketch();
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
let l = ids(&r["curves"]);
|
||||
// Three instances outward by 5 from a 40 by 30 rectangle: rings 5, 10 and 15 out, each the
|
||||
// offset of the one before it.
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, -10], "instances": 3}));
|
||||
assert_eq!(o["instances"], 3, "{o}");
|
||||
let sides = o["sides"].as_array().unwrap().clone();
|
||||
assert_eq!(sides.len(), 3, "{o}");
|
||||
assert_eq!(sides.iter().map(|side| side["instance"].as_u64()).collect::<Vec<_>>(), vec![Some(1), Some(2), Some(3)], "{o}");
|
||||
assert_eq!(ids(&o["curves"]).len(), 12, "{o}");
|
||||
offset_rings(&sketch(&s), &o, &[5.0, 10.0, 15.0]);
|
||||
// One dimension drives the whole ladder, so every ring moves together when it changes.
|
||||
let param = o["param"].as_str().unwrap().to_string();
|
||||
assert!(sides.iter().all(|side| side["param"].as_str() == Some(param.as_str())), "{o}");
|
||||
assert_eq!(sketch(&s).constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. })).count(), 3);
|
||||
run(&mut s, "parameters.change", json!({"name": param, "expression": "8 mm"}));
|
||||
offset_rings(&sketch(&s), &o, &[8.0, 16.0, 24.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_go_the_way_the_first_one_went() {
|
||||
let mut s = new_sketch();
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
let l = ids(&r["curves"]);
|
||||
// Inward by 5: rings at (5,5)-(35,25) and (10,10)-(30,20). A later instance reads its side
|
||||
// from the ring it follows, so it never doubles back over the one before it.
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, 15], "instances": 2}));
|
||||
let sk = sketch(&s);
|
||||
assert!(box_is(&sk, &side_curves(&o, 0), [5.0, 5.0], [35.0, 25.0]), "{:?}", bounds(&sk, &side_curves(&o, 0)));
|
||||
assert!(box_is(&sk, &side_curves(&o, 1), [10.0, 10.0], [30.0, 20.0]), "{:?}", bounds(&sk, &side_curves(&o, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_stop_where_the_shape_runs_out() {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
let before = s.doc.to_json();
|
||||
// Inward by 5 twice reaches a 20 by 10 ring; a third would have no height left, so the
|
||||
// whole command is refused and names the instance that could not be made.
|
||||
let error = s.execute("sketch.offset", &json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 3})).unwrap_err().to_string();
|
||||
assert!(error.contains("instance 3 of 3"), "{error}");
|
||||
assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone");
|
||||
// Two of them still work on the same shape.
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 2}));
|
||||
assert_eq!(o["sides"].as_array().map(Vec::len), Some(2), "{o}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_count_must_be_a_whole_number_within_the_cap() {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
for count in [json!(0), json!(-1), json!(1.5), json!(101), json!("two"), json!(true)] {
|
||||
let params = json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count.clone()});
|
||||
assert!(s.execute("sketch.offset", ¶ms).is_err(), "instances {count} must be refused");
|
||||
}
|
||||
// No count, and a count of one, are the offset by itself.
|
||||
for count in [json!(null), json!(1), json!("1")] {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count}));
|
||||
assert_eq!(o["instances"], 1, "{o}");
|
||||
assert_eq!(o["sides"].as_array().map(Vec::len), Some(1), "{o}");
|
||||
assert_eq!(ids(&o["curves"]).len(), 4, "{o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_into_a_circle_run_out_at_the_centre() {
|
||||
let mut s = new_sketch();
|
||||
let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone();
|
||||
let radii = |s: &Session, o: &Value| -> Vec<f64> {
|
||||
let sk = sketch(s);
|
||||
o["sides"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|side| match sk.curves.get(sk.curve_index(ids(&side["curves"])[0].as_str()).unwrap()).unwrap().kind {
|
||||
CurveKind::Circle { r, .. } => r,
|
||||
ref other => panic!("{other:?}"),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// Inward by 3 from a 10 mm circle: rings at 7, 4 and 1 mm.
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 3}));
|
||||
let got = radii(&s, &o);
|
||||
assert!(got.iter().zip([7.0, 4.0, 1.0]).all(|(a, b)| close(*a, b)), "{got:?}");
|
||||
let before = s.doc.to_json();
|
||||
// A fourth has nothing left to take. The ladder has to run out here: a step past a ring
|
||||
// smaller than the distance lands beyond the centre, and reading that as the outward side
|
||||
// turned the ladder round and grew it again (1, 4, 1, 4 ...) rather than refusing.
|
||||
let error = s.execute("sketch.offset", &json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 4})).unwrap_err().to_string();
|
||||
assert!(error.contains("instance 4 of 4"), "{error}");
|
||||
assert!(error.contains("no size"), "{error}");
|
||||
assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone");
|
||||
// Outward is unaffected: every ring is one distance larger than the last.
|
||||
let out = run(&mut s, "sketch.offset", json!({"curves": [c], "distance": 3, "side": [40, 0], "instances": 3}));
|
||||
let got = radii(&s, &out);
|
||||
assert!(got.iter().zip([13.0, 16.0, 19.0]).all(|(a, b)| close(*a, b)), "{got:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_instances_follow_each_side_of_a_symmetric_offset() {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
// Symmetric by 5, two instances: both ways get a second ring a further 5 out, so the four
|
||||
// rings are 5 and 10 inside and 5 and 10 outside.
|
||||
let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "symmetric": true, "instances": 2}));
|
||||
let sides = o["sides"].as_array().unwrap().clone();
|
||||
assert_eq!(sides.len(), 4, "{o}");
|
||||
assert_eq!(sides.iter().filter(|side| side["instance"] == 2).count(), 2, "{o}");
|
||||
let sk = sketch(&s);
|
||||
let mut boxes: Vec<[f64; 4]> = sides
|
||||
.iter()
|
||||
.map(|side| {
|
||||
let (lo, hi) = bounds(&sk, &ids(&side["curves"]));
|
||||
[lo.x, lo.y, hi.x, hi.y]
|
||||
})
|
||||
.collect();
|
||||
boxes.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||
let want = [[-10.0, -10.0, 50.0, 40.0], [-5.0, -5.0, 45.0, 35.0], [5.0, 5.0, 35.0, 25.0], [10.0, 10.0, 30.0, 20.0]];
|
||||
for (got, want) in boxes.iter().zip(&want) {
|
||||
assert!(got.iter().zip(want).all(|(a, b)| close(*a, *b)), "{boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_both_sides_of_a_rounded_boundary_keep_separate_associations() {
|
||||
let mut s = new_sketch();
|
||||
|
||||
@@ -400,3 +400,50 @@ fn a_rejected_size_or_corner_expression_leaves_nothing_behind() {
|
||||
assert_eq!(count(&s), before, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A corner typed as an expression that comes to 0 when drawn lands on the origin; it must not
|
||||
/// be tied to it by the automatic Coincident a snapped click gets, or the next parameter change
|
||||
/// conflicts with the tie (#10703).
|
||||
#[test]
|
||||
fn a_rectangle_corner_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": ["x0", 0], "p1": [40, 30]}));
|
||||
assert_eq!(r["constraints"].as_array().map(Vec::len), Some(4), "the four side constraints, no Coincident to the origin: {r}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10}));
|
||||
no_trouble(&s);
|
||||
assert!((volume(&mut s) - 40.0 * 30.0 * 10.0).abs() < 1e-6);
|
||||
run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"}));
|
||||
no_trouble(&s);
|
||||
assert!((volume(&mut s) - 25.0 * 30.0 * 10.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The same for a lone `sketch.point`: an expression that comes to the origin at draw time
|
||||
/// leaves the point free, and it follows the parameter from there (#10703).
|
||||
#[test]
|
||||
fn a_point_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.point", json!({"point": ["x0", 0], "id": "p"}));
|
||||
assert_eq!(r["constraints"].as_array().map(Vec::len), Some(0), "no Coincident to the origin: {r}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
no_trouble(&s);
|
||||
run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"}));
|
||||
no_trouble(&s);
|
||||
assert_eq!(solved(&s, "p"), Vec2::new(15.0, 0.0));
|
||||
}
|
||||
|
||||
/// A corner given as plain numbers on the origin still snaps to it, as a clicked point does:
|
||||
/// only expression-placed points are exempt from the automatic Coincident.
|
||||
#[test]
|
||||
fn a_plain_corner_on_the_origin_still_snaps_to_it() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]}));
|
||||
assert_eq!(r["constraints"].as_array().map(Vec::len), Some(5), "the four side constraints plus the Coincident to the origin: {r}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
no_trouble(&s);
|
||||
}
|
||||
@@ -1414,3 +1414,46 @@ fn a_spheres_silhouette_is_one_circle() {
|
||||
let done = run(&mut s, "sketch.finish", json!({}));
|
||||
assert_eq!(done["profiles"], 1, "{done}");
|
||||
}
|
||||
|
||||
/// The silhouette of a square with a conic round at each corner (rho 0.19, 0.4, 0.5 and 0.7) is
|
||||
/// one closed outline of the square's true area. Fitted arcs along a conic were snapped onto lines
|
||||
/// that ended further along the outline, which left gaps of up to 3.6 mm: no profile.
|
||||
#[test]
|
||||
fn the_silhouette_of_conic_rounds_closes() {
|
||||
let mut s = Session::default();
|
||||
let corners = [
|
||||
([-75., 65.], [-75., 75.], [-65., 75.], 0.19),
|
||||
([65., 75.], [75., 75.], [75., 65.], 0.4),
|
||||
([75., -65.], [75., -75.], [65., -75.], 0.5),
|
||||
([-65., -75.], [-75., -75.], [-75., -65.], 0.7),
|
||||
];
|
||||
run(&mut s, "sketch.create", json!({"plane": "XZ"}));
|
||||
for (i, (start, apex, end, rho)) in corners.iter().enumerate() {
|
||||
run(&mut s, "sketch.conic", json!({"start": start, "apex": apex, "end": end, "rho": rho}));
|
||||
let next = corners[(i + 1) % 4].0;
|
||||
run(&mut s, "sketch.line", json!({"points": [end, next]}));
|
||||
}
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 55, "body_name": "Part"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XZ", "offset": -10}));
|
||||
run(&mut s, "sketch.project", json!({"refs": [{"body": "Part"}]}));
|
||||
// The true area: the outline through the four rational quadratic Béziers (apex weight
|
||||
// rho / (1 - rho)), finely sampled, and the straight sides between them.
|
||||
let mut outline: Vec<[f64; 2]> = Vec::new();
|
||||
for (start, apex, end, rho) in corners {
|
||||
let w = rho / (1. - rho);
|
||||
for k in 0..=2000 {
|
||||
let t = f64::from(k) / 2000.;
|
||||
let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t);
|
||||
let sum = b0 + b1 + b2;
|
||||
outline.push([(b0 * start[0] + b1 * apex[0] + b2 * end[0]) / sum, (b0 * start[1] + b1 * apex[1] + b2 * end[1]) / sum]);
|
||||
}
|
||||
}
|
||||
let n = outline.len();
|
||||
let exact = (0..n).map(|i| outline[i][0] * outline[(i + 1) % n][1] - outline[(i + 1) % n][0] * outline[i][1]).sum::<f64>().abs() / 2.;
|
||||
let si = inspect(&mut s);
|
||||
let profiles = si["profiles"].as_array().unwrap();
|
||||
assert_eq!(profiles.len(), 1, "{}", si["profiles"]);
|
||||
let area = profiles[0]["area_mm2"].as_f64().unwrap();
|
||||
assert!((area - exact).abs() < exact * 2e-4, "area {area}, exact {exact}");
|
||||
}
|
||||
@@ -43,6 +43,55 @@ fn plane(s: &Session, name: &str) -> Plane {
|
||||
construction_planes(s).into_iter().find(|p| p.1 == name).map(|p| p.2).unwrap_or_else(|| panic!("no plane {name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_plane_names_cannot_be_reused_by_new_features() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "body_name": "Block"}));
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"}));
|
||||
let before = s.doc.clone();
|
||||
for (command, params) in [
|
||||
("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Mid"})),
|
||||
("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": " Mid "})),
|
||||
("sketch.create", json!({"plane": "XY", "name": "Mid"})),
|
||||
("solid.box", json!({"length": 1, "width": 1, "height": 1, "name": "Mid"})),
|
||||
("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Box1"})),
|
||||
] {
|
||||
let error = s.execute(command, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains("another feature is called"), "{command}: {error}");
|
||||
assert_eq!(s.doc, before, "{command}: a refused creation changes nothing");
|
||||
}
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Upper"}));
|
||||
run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "Upper"}));
|
||||
let measured = run(&mut s, "inspect.measure", json!({}));
|
||||
let mirrored = measured["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "Block (2)").unwrap();
|
||||
assert_eq!(mirrored["bbox"]["min"][2], 35.0);
|
||||
assert_eq!(mirrored["bbox"]["max"][2], 40.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redefining_a_construction_plane_keeps_its_existing_name() {
|
||||
let mut s = Session::default();
|
||||
let id = run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"}))["feature"].as_u64().unwrap();
|
||||
run(&mut s, "sketch.create", json!({"plane": "Mid", "name": "Profile"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(
|
||||
&mut s,
|
||||
"timeline.redefine",
|
||||
json!({"feature": id, "command": "construct.plane.offset", "params": {"base": "XY", "offset": 20, "name": "Mid"}}),
|
||||
);
|
||||
assert_eq!(s.doc.feature(id).unwrap().name, "Mid");
|
||||
assert_eq!(s.doc.features.len(), 2);
|
||||
assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 20.0)));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 10.0)));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
|
||||
reopened.refresh();
|
||||
assert_eq!(reopened.doc.feature(id).unwrap().name, "Mid");
|
||||
assert!(near(plane(&reopened, "Mid").origin, Vec3::new(0.0, 0.0, 20.0)));
|
||||
assert!(reopened.model.results.iter().all(|r| r.error.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renamed_construction_references_survive_edits_and_reopening() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -241,3 +241,28 @@ fn replace_face_takes_the_face_by_name() {
|
||||
// A's top moves up to B's, 15 high: 10 x 10 x 15.
|
||||
assert!((volume(&mut s, "A") - 1500.0).abs() < 1e-6, "{}", volume(&mut s, "A"));
|
||||
}
|
||||
|
||||
/// A face name on two bodies, each with one such face (two bodies one extrude made, the pieces of
|
||||
/// a split body), is not a split face: a hole placed on one of them gives no warning (#10699).
|
||||
#[test]
|
||||
fn a_face_name_on_two_bodies_is_no_split_face() {
|
||||
let said = |s: &Session, feature: &str| {
|
||||
let r = s.model.result(s.doc.find_feature(feature).unwrap().id).unwrap();
|
||||
format!("{}{}", r.error.clone().unwrap_or_default(), r.warning.clone().unwrap_or_default())
|
||||
};
|
||||
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.rectangle.two_point", json!({"p0": [14, 0], "p1": [24, 10]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 10, "operation": "new"}));
|
||||
run(&mut s, "solid.hole", json!({"position": [5, 5, 10], "diameter": 5, "depth": 5, "name": "Hole1"}));
|
||||
assert_eq!(said(&s, "Hole1"), "");
|
||||
assert!((volume(&mut s, "Body1") - (1000.0 - PI * 2.5 * 2.5 * 5.0)).abs() < 0.1);
|
||||
assert!((volume(&mut s, "Body2") - 1000.0).abs() < 1e-6);
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10}));
|
||||
run(&mut s, "solid.split_body", json!({"body": "Body1", "plane": {"origin": [20, 0, 0], "normal": [1, 0, 0]}}));
|
||||
run(&mut s, "solid.hole", json!({"position": [30, 10, 10], "diameter": 5, "name": "Hole1", "targets": ["Body1"]}));
|
||||
assert_eq!(said(&s, "Hole1"), "");
|
||||
}
|
||||
@@ -336,6 +336,48 @@ fn a_cylinders_top_circle_is_as_long_as_its_circumference() {
|
||||
assert!(close(&r["items"][0]["length_mm"], TAU * 5.0, 1e-9), "{r}");
|
||||
}
|
||||
|
||||
/// The first face whose analytic surface satisfies `want`, as a pick.
|
||||
fn face_of(s: &Session, want: impl Fn(solidcraft_kernel::FaceSurface) -> bool) -> Value {
|
||||
let st = s.model.state();
|
||||
let b = st.bodies.first().unwrap();
|
||||
let m = b.mesh();
|
||||
let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap();
|
||||
let f = (0..n).find(|&f| solidcraft_kernel::face_surface(&b.body, f).is_some_and(&want)).expect("face");
|
||||
let p = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == f).and_then(|(t, _)| m.tri(t)).unwrap()[0];
|
||||
json!({"type": "face", "body": b.name, "index": f, "point": p})
|
||||
}
|
||||
|
||||
/// A fillet round the foot of a boss is a toroidal face: it measures its radius (the fillet's)
|
||||
/// next to its area, and says it is a torus with its ring radius too.
|
||||
#[test]
|
||||
fn a_fillet_round_a_boss_reports_its_radius() {
|
||||
use solidcraft_kernel::FaceSurface;
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10}));
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [20, 20, 10], "operation": "join"}));
|
||||
run(&mut s, "solid.fillet", json!({"edges": [[25, 20, 10]], "radius": 3}));
|
||||
let fillet = face_of(&s, |f| matches!(f, FaceSurface::Torus { minor, .. } if (minor - 3.0).abs() < 1e-6));
|
||||
let r = measure(&mut s, vec![fillet]);
|
||||
assert!(close(&r["radius"], 3.0, 1e-6) && close(&r["diameter"], 6.0, 1e-6), "{r}");
|
||||
assert_eq!(r["items"][0]["surface"], "torus", "{r}");
|
||||
// The ring through the middle of the rolling ball: the boss's radius plus the fillet's.
|
||||
assert!(close(&r["items"][0]["major_radius"], 8.0, 1e-6), "{r}");
|
||||
// The area is still there.
|
||||
assert!(r["items"][0]["area_mm2"].as_f64().is_some_and(|a| a > 1.0), "{r}");
|
||||
}
|
||||
|
||||
/// A ball's face reports its radius.
|
||||
#[test]
|
||||
fn a_sphere_face_reports_its_radius() {
|
||||
use solidcraft_kernel::FaceSurface;
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.sphere", json!({"radius": 7, "center": [0, 0, 0]}));
|
||||
let ball = face_of(&s, |f| matches!(f, FaceSurface::Sphere { .. }));
|
||||
let r = measure(&mut s, vec![ball]);
|
||||
assert!(close(&r["radius"], 7.0, 1e-6) && close(&r["diameter"], 14.0, 1e-6), "{r}");
|
||||
assert_eq!(r["items"][0]["surface"], "sphere", "{r}");
|
||||
}
|
||||
|
||||
/// A plate with holes through STEP: the holes come back as cylinders, and measure the same.
|
||||
#[test]
|
||||
fn step_round_trip_of_a_plate_with_holes() {
|
||||
|
||||
@@ -36,6 +36,41 @@ pub(crate) struct Execution {
|
||||
pub executor: solidcraft_render::ExecutorId,
|
||||
pub options: solidcraft_render::job::JobOptions,
|
||||
pub environment: Option<solidcraft_render::lighting::environment_input::EnvironmentInput>,
|
||||
pub shot: Option<String>,
|
||||
}
|
||||
|
||||
struct LiveJob {
|
||||
handle: JobHandle,
|
||||
shot: Option<String>,
|
||||
}
|
||||
|
||||
/// Transient completed-image metadata. Neither pixels nor selection enter a design or undo.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RetainedResult {
|
||||
pub frame: solidcraft_render::job::FrameInfo,
|
||||
pub shot: Option<String>,
|
||||
pub seconds: f64,
|
||||
pub stale: bool,
|
||||
}
|
||||
|
||||
struct Completed {
|
||||
handle: JobHandle,
|
||||
info: RetainedResult,
|
||||
}
|
||||
|
||||
pub(crate) struct BatchShot {
|
||||
pub name: String,
|
||||
pub camera: solidcraft_render::Camera,
|
||||
pub request: Arc<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RenderQueueState {
|
||||
pub running: usize,
|
||||
pub waiting: usize,
|
||||
pub job: Option<JobId>,
|
||||
pub shot: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct Jobs {
|
||||
@@ -45,12 +80,14 @@ pub(crate) struct Jobs {
|
||||
pub(crate) host: Option<CpuHost>,
|
||||
pub(crate) descriptor: Option<ExecutorDescriptor>,
|
||||
pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>,
|
||||
live: Vec<JobHandle>,
|
||||
live: Vec<LiveJob>,
|
||||
history: VecDeque<JobStatus>,
|
||||
last_good: Option<JobHandle>,
|
||||
/// One explicitly displayed completed result, independent of a newer completion.
|
||||
/// The existing frame Arc keeps its original host reservation accounted for.
|
||||
pinned: Option<JobHandle>,
|
||||
completed: VecDeque<Completed>,
|
||||
selected: Option<solidcraft_render::job::JobId>,
|
||||
waiting: VecDeque<BatchShot>,
|
||||
batch_job: Option<JobId>,
|
||||
batch_error: Option<String>,
|
||||
comparison: Option<[Option<JobId>; 2]>,
|
||||
}
|
||||
|
||||
impl Default for Jobs {
|
||||
@@ -64,8 +101,12 @@ impl Default for Jobs {
|
||||
additional: Vec::new(),
|
||||
live: Vec::new(),
|
||||
history: VecDeque::new(),
|
||||
last_good: None,
|
||||
pinned: None,
|
||||
completed: VecDeque::new(),
|
||||
selected: None,
|
||||
waiting: VecDeque::new(),
|
||||
batch_job: None,
|
||||
batch_error: None,
|
||||
comparison: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,12 +114,26 @@ impl Default for Jobs {
|
||||
impl Drop for Jobs {
|
||||
fn drop(&mut self) {
|
||||
for job in &self.live {
|
||||
let _ = job.cancel();
|
||||
let _ = job.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Jobs {
|
||||
pub(crate) fn set_comparison(&mut self, sides: Option<[Option<JobId>; 2]>) {
|
||||
self.comparison = sides;
|
||||
if let Some([left, right]) = sides {
|
||||
self.selected = right.or(left);
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_comparison(&self) -> Option<[Option<JobId>; 2]> {
|
||||
self.comparison.filter(|sides| sides.iter().flatten().all(|job| self.completed.iter().any(|result| result.handle.id() == *job)))
|
||||
}
|
||||
pub(crate) fn has_results(&self) -> bool {
|
||||
!self.completed.is_empty() || self.live.iter().any(|job| job.handle.frame().ok().flatten().is_some())
|
||||
}
|
||||
|
||||
pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> {
|
||||
if executor.as_str() == "cpu-raytrace" {
|
||||
return self
|
||||
@@ -103,14 +158,26 @@ impl Jobs {
|
||||
pub(crate) fn collect(&mut self) -> Result<(), JobError> {
|
||||
let mut i = 0;
|
||||
while i < self.live.len() {
|
||||
let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.status()?;
|
||||
let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.handle.status()?;
|
||||
if !status.progress.phase.terminal() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let handle = self.live.remove(i);
|
||||
if status.progress.phase == Phase::Completed && self.last_good.as_ref().is_none_or(|old| old.id().serial < handle.id().serial) {
|
||||
self.last_good = Some(handle);
|
||||
let job = self.live.remove(i);
|
||||
if let Some(frame) = status.frame.as_ref().filter(|_| status.progress.phase == Phase::Completed) {
|
||||
let seconds = job.handle.completed_duration()?.map_or(0.0, |duration| duration.as_secs_f64());
|
||||
let completed_id = job.handle.id();
|
||||
self.completed.push_back(Completed {
|
||||
handle: job.handle,
|
||||
info: RetainedResult { frame: frame.clone(), shot: job.shot, seconds, stale: false },
|
||||
});
|
||||
while self.completed.len() > 8 {
|
||||
self.completed.pop_front();
|
||||
}
|
||||
if self.valid_comparison().is_none() {
|
||||
self.comparison = None;
|
||||
self.selected = Some(completed_id);
|
||||
}
|
||||
}
|
||||
self.history.push_back(status);
|
||||
while self.history.len() > 4 {
|
||||
@@ -128,12 +195,19 @@ impl Jobs {
|
||||
replace: bool,
|
||||
execution: Execution,
|
||||
) -> Result<JobStatus, JobError> {
|
||||
let Execution { executor, options, environment } = execution;
|
||||
let Execution { executor, options, environment, shot } = execution;
|
||||
if self.batch_job.is_some() {
|
||||
if !replace {
|
||||
return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before starting another render"));
|
||||
}
|
||||
self.waiting.clear();
|
||||
self.batch_job = None;
|
||||
}
|
||||
self.collect()?;
|
||||
let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone();
|
||||
if replace {
|
||||
for job in self.live.drain(..) {
|
||||
let mut status = job.cancel()?;
|
||||
let mut status = job.handle.cancel()?;
|
||||
// Replaced handles are deliberately abandoned: keep a cancellation tombstone,
|
||||
// not a permanently "cancelling" snapshot. The token already prevents any
|
||||
// publication; the host can finish releasing its buffers asynchronously.
|
||||
@@ -165,7 +239,7 @@ impl Jobs {
|
||||
let status = handle.status()?;
|
||||
self.serial = serial;
|
||||
self.generation = generation;
|
||||
self.live.push(handle);
|
||||
self.live.push(LiveJob { handle, shot });
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
@@ -174,6 +248,9 @@ impl Jobs {
|
||||
source_id: JobId,
|
||||
presentation: solidcraft_render::job::presentation::Presentation,
|
||||
) -> Result<JobStatus, JobError> {
|
||||
if self.batch_job.is_some() {
|
||||
return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before regrading"));
|
||||
}
|
||||
self.collect()?;
|
||||
let source = self.handle(source_id)?;
|
||||
let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?;
|
||||
@@ -194,7 +271,8 @@ impl Jobs {
|
||||
let status = handle.status()?;
|
||||
self.serial = serial;
|
||||
self.generation = generation;
|
||||
self.live.push(handle);
|
||||
let shot = self.completed.iter().find(|result| result.handle.id() == source_id).and_then(|result| result.info.shot.clone());
|
||||
self.live.push(LiveJob { handle, shot });
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
@@ -209,8 +287,8 @@ impl Jobs {
|
||||
self.check_owner(id)?;
|
||||
self.live
|
||||
.iter()
|
||||
.chain(self.last_good.iter())
|
||||
.chain(self.pinned.iter())
|
||||
.map(|job| &job.handle)
|
||||
.chain(self.completed.iter().map(|result| &result.handle))
|
||||
.find(|j| j.id() == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained"))
|
||||
@@ -226,17 +304,35 @@ impl Jobs {
|
||||
}
|
||||
|
||||
pub(crate) fn pin(&mut self, id: Option<JobId>) -> Result<Option<solidcraft_render::job::FrameInfo>, JobError> {
|
||||
self.collect()?;
|
||||
let Some(id) = id else {
|
||||
self.pinned = None;
|
||||
self.selected = None;
|
||||
self.comparison = None;
|
||||
return Ok(None);
|
||||
};
|
||||
let handle = self.handle(id)?;
|
||||
let frame = handle.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "only a completed result can be pinned"))?;
|
||||
let info = frame.info.clone();
|
||||
self.pinned = Some(handle);
|
||||
self.comparison = None;
|
||||
self.selected = Some(id);
|
||||
Ok(Some(info))
|
||||
}
|
||||
|
||||
pub(crate) fn result_index(&mut self, index: usize, discard: bool) -> Result<(), JobError> {
|
||||
self.collect()?;
|
||||
let id = self.completed.get(index).ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "retained result index is out of bounds"))?.handle.id();
|
||||
if discard {
|
||||
self.completed.remove(index);
|
||||
if self.selected == Some(id) {
|
||||
self.selected = self.completed.back().map(|result| result.handle.id());
|
||||
}
|
||||
} else {
|
||||
self.comparison = None;
|
||||
self.selected = Some(id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn frame(&mut self, id: JobId) -> Result<Arc<RenderFrame>, JobError> {
|
||||
self.collect()?;
|
||||
self.handle(id)?.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "render has no completed image"))
|
||||
@@ -244,6 +340,126 @@ impl Jobs {
|
||||
}
|
||||
|
||||
impl crate::Session {
|
||||
pub fn render_comparison(&self) -> Option<[Option<JobId>; 2]> {
|
||||
self.render_jobs.valid_comparison()
|
||||
}
|
||||
|
||||
pub fn render_queue_state(&self) -> RenderQueueState {
|
||||
let active = self.render_jobs.batch_job.and_then(|id| self.render_jobs.live.iter().find(|job| job.handle.id() == id));
|
||||
RenderQueueState {
|
||||
running: self.render_jobs.live.iter().filter(|job| job.handle.status().is_ok_and(|status| !status.progress.phase.terminal())).count(),
|
||||
waiting: self.render_jobs.waiting.len(),
|
||||
job: self.render_jobs.batch_job,
|
||||
shot: active.and_then(|job| job.shot.clone()),
|
||||
error: self.render_jobs.batch_error.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_batch_ready(&self) -> std::result::Result<(), String> {
|
||||
if self.doc.render.setups.is_empty() {
|
||||
return Err("no saved shots to render".into());
|
||||
}
|
||||
if self.doc.render.setups.len() > 32 {
|
||||
return Err("render all shots is limited to 32 shots".into());
|
||||
}
|
||||
if self.render_jobs.batch_job.is_some() || self.render_queue_state().running != 0 {
|
||||
return Err("a render or shot queue is already active".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn start_render_batch(&mut self, shots: VecDeque<BatchShot>) -> crate::Result<usize> {
|
||||
self.render_batch_ready().map_err(crate::EngineError::Other)?;
|
||||
if shots.is_empty() || shots.len() > 32 {
|
||||
return Err(crate::EngineError::Other("shot queue must contain 1..32 shots".into()));
|
||||
}
|
||||
let queued = shots.len();
|
||||
self.render_jobs.waiting = shots;
|
||||
self.render_jobs.batch_error = None;
|
||||
self.start_next_batch_shot()?;
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
fn start_next_batch_shot(&mut self) -> crate::Result<()> {
|
||||
let Some(shot) = self.render_jobs.waiting.pop_front() else { return Ok(()) };
|
||||
let result: crate::Result<()> = (|| {
|
||||
let mut params = (*shot.request).clone();
|
||||
let settings = params
|
||||
.get_mut("settings")
|
||||
.and_then(serde_json::Value::as_object_mut)
|
||||
.ok_or_else(|| crate::EngineError::Other("queued render settings are missing".into()))?;
|
||||
settings.insert("camera".into(), serde_json::json!(shot.camera));
|
||||
let reply = self.execute("render.start", ¶ms)?;
|
||||
let job: JobId = serde_json::from_value(reply.get("job").cloned().unwrap_or_default())
|
||||
.map_err(|error| crate::EngineError::Other(format!("invalid queued render identity: {error}")))?;
|
||||
self.label_render_job(job, &shot.name)?;
|
||||
self.render_jobs.batch_job = Some(job);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.render_jobs.waiting.clear();
|
||||
self.render_jobs.batch_error = Some(error.to_string());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Non-blocking queue scheduling. The existing host still owns all render work.
|
||||
pub fn advance_render_batch(&mut self) -> crate::Result<()> {
|
||||
let Some(job) = self.render_jobs.batch_job else { return Ok(()) };
|
||||
let status = self.render_jobs.status(job).map_err(job_error)?;
|
||||
if !status.progress.phase.terminal() {
|
||||
return Ok(());
|
||||
}
|
||||
self.render_jobs.batch_job = None;
|
||||
if status.progress.phase != Phase::Completed {
|
||||
self.render_jobs.waiting.clear();
|
||||
self.render_jobs.batch_error = status.error.map(|error| error.to_string());
|
||||
return Ok(());
|
||||
}
|
||||
self.start_next_batch_shot()
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_render_batch(&mut self, job: JobId) {
|
||||
if self.render_jobs.batch_job == Some(job) {
|
||||
self.render_jobs.waiting.clear();
|
||||
self.render_jobs.batch_job = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture the UI draft's label alongside an unnamed active request, never in the design.
|
||||
pub fn label_render_job(&mut self, id: JobId, shot: &str) -> crate::Result<()> {
|
||||
solidcraft_doc::render_settings::RenderSettings::validate_name(shot).map_err(|error| crate::EngineError::Other(error.to_string()))?;
|
||||
let job = self
|
||||
.render_jobs
|
||||
.live
|
||||
.iter_mut()
|
||||
.find(|job| job.handle.id() == id)
|
||||
.ok_or_else(|| job_error(JobError::new(ErrorCode::UnknownJob, "render job is no longer active")))?;
|
||||
if job.shot.is_none() {
|
||||
job.shot = Some(shot.to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Oldest first, capped at eight. Staleness follows the current design revision.
|
||||
pub fn render_retained_results(&mut self) -> crate::Result<Vec<RetainedResult>> {
|
||||
self.render_jobs.collect().map_err(job_error)?;
|
||||
Ok(self
|
||||
.render_jobs
|
||||
.completed
|
||||
.iter()
|
||||
.map(|result| {
|
||||
let mut info = result.info.clone();
|
||||
info.stale = info.frame.scene_generation != self.revision;
|
||||
info
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn render_selected_result(&self) -> Option<JobId> {
|
||||
self.render_jobs.selected
|
||||
}
|
||||
|
||||
/// A host is installed by the application, never by document data or a command.
|
||||
pub fn set_render_job_host(&mut self, host: Option<CpuHost>) -> crate::Result<()> {
|
||||
if self.render_jobs.host.as_ref().zip(host.as_ref()).is_some_and(|(a, b)| a.same_host(b)) {
|
||||
@@ -350,7 +566,7 @@ mod displayed_result_tests {
|
||||
panic!("bounded result fixture did not finish")
|
||||
}
|
||||
#[test]
|
||||
fn explicit_display_pin_preserves_the_old_exact_frame_without_unbounded_history() {
|
||||
fn explicit_display_pin_selects_exact_bytes_within_bounded_retention() {
|
||||
let mut s = crate::Session::default();
|
||||
let host = CpuHost::cooperative();
|
||||
s.set_render_job_host(Some(host.clone())).unwrap();
|
||||
@@ -368,10 +584,11 @@ mod displayed_result_tests {
|
||||
let foreign = JobId { session: old.session + 1, ..old };
|
||||
assert!(s.execute("render.result.pin", &json!({"job":foreign})).is_err());
|
||||
assert_eq!(host.admitted_bytes(), retained);
|
||||
assert!(s.execute("render.result.pin", &json!({})).is_err());
|
||||
assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(s.render_selected_result()));
|
||||
s.execute("render.result.pin", &json!({"job":null})).unwrap();
|
||||
assert!(s.render_job_handle(old).is_err());
|
||||
assert!(host.admitted_bytes() < retained);
|
||||
assert!(s.render_selected_result().is_none());
|
||||
assert!(s.render_job_handle(old).is_ok(), "clearing selection does not discard retained results");
|
||||
assert_eq!(host.admitted_bytes(), retained);
|
||||
assert_eq!(s.doc.to_json(), before);
|
||||
assert_eq!(s.undo.len(), undo);
|
||||
let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap();
|
||||
|
||||
@@ -3,6 +3,15 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Assistant visibility is UI-owned and takes no parameters.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct AssistantParams {}
|
||||
|
||||
/// Headless sessions refuse Assistant display requests and produce no result.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct AssistantResult {}
|
||||
|
||||
/// `edit.repeat` takes no parameters: it starts the last tool with its defaults.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
@@ -39,12 +48,13 @@ pub struct TimelinePlayResult {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::RepeatParams;
|
||||
use super::{AssistantParams, RepeatParams};
|
||||
use crate::schema::input_schema_for;
|
||||
use crate::schema::tests::assert_keys;
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<RepeatParams>(), &[]);
|
||||
assert_keys(input_schema_for::<AssistantParams>(), &[]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Contracts and result types for the commands in `cmd/file.rs`: so far the export command of
|
||||
//! each format (`file.export_step`, `file.export_stl`, `file.export_3mf`, `file.export_obj`,
|
||||
//! `file.export_urdf`), which take what `file.export` takes for that format, without `format`.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::types::StringList;
|
||||
|
||||
/// How closely an exported mesh follows curved faces.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MeshQualityParam {
|
||||
/// A chord tolerance of 2e-4 of each body's size.
|
||||
Standard,
|
||||
/// 5e-5 of each body's size.
|
||||
Fine,
|
||||
/// 1e-5 of each body's size.
|
||||
Finest,
|
||||
}
|
||||
|
||||
/// What each 3MF object holds.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ObjectsParam {
|
||||
/// One object per body.
|
||||
Body,
|
||||
/// One object for each placed component with two or more bodies, with those bodies as its
|
||||
/// parts, so a slicer loads them as one object with parts; other bodies stay objects of their own.
|
||||
Component,
|
||||
}
|
||||
|
||||
/// Export bodies as a STEP file. With no `bodies`, a design with components exports as a STEP
|
||||
/// assembly, otherwise its bodies as placed. The file is STEP whatever the path's extension.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExportStepParams {
|
||||
/// The file to write.
|
||||
pub path: String,
|
||||
/// The bodies to export, by name. Default: every body.
|
||||
#[serde(default)]
|
||||
pub bodies: Option<StringList>,
|
||||
}
|
||||
|
||||
/// Export bodies as a mesh file: binary STL for `file.export_stl`, OBJ for `file.export_obj`
|
||||
/// (the colours of the bodies go in a material library, `.mtl`, written next to it). The file
|
||||
/// has that format whatever the path's extension.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExportMeshParams {
|
||||
/// The file to write.
|
||||
pub path: String,
|
||||
/// The bodies to export, by name. Default: every body.
|
||||
#[serde(default)]
|
||||
pub bodies: Option<StringList>,
|
||||
/// How closely the mesh follows curved faces. Default: standard.
|
||||
#[serde(default)]
|
||||
pub quality: Option<MeshQualityParam>,
|
||||
}
|
||||
|
||||
/// Export bodies as a 3MF file, whatever the path's extension.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct Export3mfParams {
|
||||
/// The file to write.
|
||||
pub path: String,
|
||||
/// The bodies to export, by name. Default: every body.
|
||||
#[serde(default)]
|
||||
pub bodies: Option<StringList>,
|
||||
/// How closely the mesh follows curved faces. Default: standard.
|
||||
#[serde(default)]
|
||||
pub quality: Option<MeshQualityParam>,
|
||||
/// What each object in the file holds. Default: body.
|
||||
#[serde(default)]
|
||||
pub objects: Option<ObjectsParam>,
|
||||
}
|
||||
|
||||
/// Export the whole assembly as a robot description (URDF), with an STL mesh for each link
|
||||
/// written next to it (docs/urdf.md).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExportUrdfParams {
|
||||
/// The `.urdf` file to write; the meshes go in its folder.
|
||||
pub path: String,
|
||||
/// Put before each mesh file name in the URDF, such as `package://robot/meshes/`. Default: none.
|
||||
#[serde(default)]
|
||||
pub mesh_prefix: Option<String>,
|
||||
/// Each joint's effort limit, a positive number. Default: 1000.
|
||||
#[serde(default)]
|
||||
pub effort: Option<f64>,
|
||||
/// Each joint's velocity limit, a positive number. Default: 10.
|
||||
#[serde(default)]
|
||||
pub velocity: Option<f64>,
|
||||
}
|
||||
|
||||
/// What `file.export_step`, `file.export_stl`, `file.export_3mf` and `file.export_obj` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExportResult {
|
||||
/// The file written.
|
||||
pub path: String,
|
||||
/// Its size in bytes.
|
||||
pub bytes: usize,
|
||||
/// The format written: Step, StlBinary, ThreeMf or Obj.
|
||||
pub format: String,
|
||||
/// OBJ only: every file written, the material library first and the mesh file last.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub files: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `file.export_urdf` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct UrdfExportResult {
|
||||
/// The `.urdf` file written.
|
||||
pub path: String,
|
||||
/// Always Urdf.
|
||||
pub format: String,
|
||||
/// Every file written, the meshes first and the `.urdf` last.
|
||||
pub files: Vec<String>,
|
||||
/// How many links the robot has.
|
||||
pub links: usize,
|
||||
/// How many joints the robot has.
|
||||
pub joints: usize,
|
||||
/// What the export could not carry over as it is in the design.
|
||||
pub warnings: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "file_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,38 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::{Export3mfParams, ExportMeshParams, ExportStepParams, ExportUrdfParams};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::assert_keys;
|
||||
use crate::schema::{ParamCheck, input_schema_for};
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ExportStepParams>(), &["bodies", "path"]);
|
||||
assert_keys(input_schema_for::<ExportMeshParams>(), &["bodies", "path", "quality"]);
|
||||
assert_keys(input_schema_for::<Export3mfParams>(), &["bodies", "objects", "path", "quality"]);
|
||||
assert_keys(input_schema_for::<ExportUrdfParams>(), &["effort", "mesh_prefix", "path", "velocity"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_calls_say_what_is_wrong_and_write_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-export-schemas-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
|
||||
for cmd in ["file.export_step", "file.export_stl", "file.export_3mf", "file.export_obj", "file.export_urdf"] {
|
||||
let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains(cmd) && e.contains("path"), "{cmd}: {e}");
|
||||
}
|
||||
let at = dir.join("a.stl").to_string_lossy().to_string();
|
||||
let e = s.execute("file.export_stl", &json!({"path": at, "quality": "rough"})).unwrap_err().to_string();
|
||||
assert!(e.contains("quality"), "{e}");
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let e = s.execute("file.export_stl", &json!({"path": at, "objects": "component"})).unwrap_err().to_string();
|
||||
assert!(e.contains("objects"), "objects is for 3MF only: {e}");
|
||||
s.param_check = ParamCheck::Off;
|
||||
let e = s.execute("file.export_urdf", &json!({"path": at, "effort": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("effort"), "{e}");
|
||||
assert_eq!(std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0), 0, "nothing written");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -60,6 +60,7 @@ pub mod construct;
|
||||
pub mod diagnostics;
|
||||
pub mod edit;
|
||||
pub mod features;
|
||||
pub mod file;
|
||||
pub mod inspect;
|
||||
pub mod joints;
|
||||
pub mod mass_properties;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Clipboard requests for the Render workspace; headless calls only echo validated text.
|
||||
//! Contracts for transient Render workspace clipboard and retained-result requests.
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -9,3 +9,68 @@ pub struct CheckReport {
|
||||
#[schemars(length(min = 1, max = 65536))]
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Select or discard a retained result without editing a design.
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResultIndex {
|
||||
/// Zero-based index, oldest first. The result must still be retained.
|
||||
#[schemars(range(min = 0, max = 7))]
|
||||
pub index: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LiveSide {
|
||||
Live,
|
||||
}
|
||||
|
||||
/// A live product view or a retained result's zero-based index (oldest first).
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
|
||||
#[serde(untagged)]
|
||||
pub enum CompareSide {
|
||||
Live(LiveSide),
|
||||
Result(#[schemars(range(min = 0, max = 7))] u32),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ComparePair {
|
||||
pub left: CompareSide,
|
||||
pub right: CompareSide,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CompareOff {
|
||||
/// Must be true. Leave comparison without changing retained results.
|
||||
pub off: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum CompareParams {
|
||||
Off(CompareOff),
|
||||
Pair(ComparePair),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CompareDivider {
|
||||
/// Finite fraction of the canvas width, clamped to 0.05..0.95.
|
||||
pub position: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BatchParams {
|
||||
/// Optional render.start request. Its setup is shared, with each saved shot's camera.
|
||||
/// Without a request, use the first saved shot's setup (name order).
|
||||
pub request: Option<std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BatchResult {
|
||||
/// Total accepted shots, including the first active job. At most 32.
|
||||
pub queued: u32,
|
||||
}
|
||||
@@ -80,6 +80,50 @@ pub struct SplineReverseParams {
|
||||
pub sketch: Option<SketchRef>,
|
||||
}
|
||||
|
||||
/// Take one point out of a spline: it runs through (or over) its other points only, and the point
|
||||
/// goes with the constraints on it unless another curve uses it. Takes fit point, control point
|
||||
/// and closed splines; refused for a closed spline's closing point, for an end joined to other
|
||||
/// geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed
|
||||
/// spline), and for a projected, offset or patterned spline.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct SplineRemovePointParams {
|
||||
/// The spline's curve id.
|
||||
#[serde(deserialize_with = "spline_id")]
|
||||
pub curve: String,
|
||||
/// One of the spline's points: a point id, or the curve's `start` or `end` (`s1.end`).
|
||||
#[serde(deserialize_with = "point_ref")]
|
||||
pub point: String,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SketchRef")]
|
||||
pub sketch: Option<SketchRef>,
|
||||
}
|
||||
|
||||
/// What `sketch.spline.remove_point` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SplineRemovePointResult {
|
||||
/// The spline's curve id (unchanged).
|
||||
pub curve: String,
|
||||
/// The id the point had.
|
||||
pub point: String,
|
||||
/// Whether the point went too; `false` when another curve still uses it.
|
||||
pub deleted: bool,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A point reference, with the handler's message for anything else.
|
||||
fn point_ref<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(serde::de::Error::custom("must be one of the spline's points")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve id, with the handler's message for anything else.
|
||||
fn spline_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::{SplineReverseParams, SplineReverseResult};
|
||||
use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
@@ -8,6 +8,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<SplineReverseParams>(), &["curve", "sketch"]);
|
||||
assert_keys(input_schema_for::<SplineRemovePointParams>(), &["curve", "point", "sketch"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -17,9 +18,30 @@ fn strict_keeps_todays_errors() {
|
||||
("sketch.spline.reverse", json!({"curve": null})),
|
||||
("sketch.spline.reverse", json!({"curve": "nope"})),
|
||||
("sketch.spline.reverse", json!({"curve": "l1"})),
|
||||
("sketch.spline.remove_point", json!({"curve": 5, "point": "p1"})),
|
||||
("sketch.spline.remove_point", json!({"curve": "nope", "point": "p1"})),
|
||||
("sketch.spline.remove_point", json!({"curve": "l1", "point": 3})),
|
||||
("sketch.spline.remove_point", json!({"curve": "l1"})),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_remove_point_reply_matches_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
let c = run(&mut s, "sketch.spline.fit_point", json!({"points": [[5, 0], [10, 5], [20, 0], [30, 5], [40, 0]]}));
|
||||
let spline = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string();
|
||||
let schema = output_schema_for::<SplineRemovePointResult>();
|
||||
let schema = schema.as_value();
|
||||
let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.start")}));
|
||||
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.end"), "unknown": 1}));
|
||||
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_reverse_reply_matches_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
|
||||
@@ -1092,8 +1092,15 @@ fn hostile_params_never_panic() {
|
||||
let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
|
||||
for v in hostile_values() {
|
||||
for k in keys {
|
||||
if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") {
|
||||
continue; // parameter and script files: covered by their own tests (no stray files)
|
||||
if k == "path"
|
||||
&& (id.starts_with("parameters.")
|
||||
|| id == "timeline.export_script"
|
||||
|| matches!(
|
||||
id,
|
||||
"file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf"
|
||||
))
|
||||
{
|
||||
continue; // parameter, script and export files: covered by their own tests (no stray files)
|
||||
}
|
||||
let mut s = copy_with_history(&start);
|
||||
let p = json!({ k: v.clone() });
|
||||
@@ -1323,7 +1330,8 @@ fn timeline_inspect_shows_what_timeline_edit_changes() {
|
||||
run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Slab"}));
|
||||
run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "name": "Round"}));
|
||||
let i = run(&mut s, "timeline.inspect", json!({"feature": "Slab"}));
|
||||
assert_eq!(i["type"], "ExtrudeFeature", "{i}");
|
||||
assert_eq!(i["type"], "extrude", "{i}");
|
||||
assert_eq!(i["type_name"], "ExtrudeFeature", "{i}");
|
||||
assert_eq!(i["definition"]["extent"]["distance"], "10", "{i}");
|
||||
assert_eq!(i["definition"]["operation"], "new_body", "{i}");
|
||||
assert!(i["definition"].get("type").is_none() && i["definition"].get("param_names").is_none(), "{i}");
|
||||
@@ -3077,6 +3085,60 @@ fn press_pull_on_curved_faces() {
|
||||
assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0);
|
||||
}
|
||||
|
||||
/// #4986: Press Pull on a chamfer's flat face changes the chamfer's distance, as on a fillet's
|
||||
/// face it changes the radius, rather than extruding the face.
|
||||
#[test]
|
||||
fn press_pull_on_a_chamfer_face_edits_the_chamfer() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
|
||||
run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"}));
|
||||
let cut = |d: f64| d * d / 2.0 * 20.0;
|
||||
assert!(rel(volume(&mut s), 24000.0 - cut(3.0)) < 1e-6);
|
||||
// The chamfer's face runs from (37, 0) to (40, 3); its middle.
|
||||
let out = run(&mut s, "solid.press_pull", json!({"face": [38.5, 1.5, 10], "distance": 2}));
|
||||
assert_eq!(out["edited"], "Bevel", "{out}");
|
||||
assert_eq!(s.doc.features.len(), 2, "no extrude added");
|
||||
assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{}", volume(&mut s));
|
||||
// A point on the flat front face 0.02 mm from its edge with the chamfer (which now runs from
|
||||
// (35, 0) to (40, 5)) is the front face's: it is extruded, the chamfer is left alone.
|
||||
let mut t = Session::default();
|
||||
run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
|
||||
run(&mut t, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"}));
|
||||
let out = run(&mut t, "solid.press_pull", json!({"face": [36.98, 0, 10], "distance": 1}));
|
||||
assert!(out.get("edited").is_none(), "{out}");
|
||||
assert!(matches!(t.doc.features.last().map(|f| &f.kind), Some(solidcraft_doc::FeatureKind::Extrude { .. })), "an extrude added: {out}");
|
||||
assert!(
|
||||
matches!(&t.doc.features[1].kind, solidcraft_doc::FeatureKind::Chamfer { distance, .. } if distance == "3"),
|
||||
"{:?}",
|
||||
t.doc.features[1].kind
|
||||
);
|
||||
// Too far in (past zero) or too far out: an error, the chamfer as it was.
|
||||
let on = [39.0, 1.0, 10.0];
|
||||
for d in [-10.0, 1e9] {
|
||||
assert!(s.execute("solid.press_pull", &json!({"face": on, "distance": d})).is_err(), "{d}");
|
||||
assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{d}: {}", volume(&mut s));
|
||||
}
|
||||
// An unequal chamfer's first distance changes and its second stays; an angle chamfer keeps
|
||||
// its angle.
|
||||
// Each chamfer's face crosses the corner's bisector at legs a, b: (40 - u, u), u = ab / (a + b).
|
||||
let tan30 = (PI / 6.0).tan();
|
||||
for (extra, u) in [(json!({"distance2": 4}), 8.0 / 6.0), (json!({"angle": "30 deg"}), 2.0 * tan30 / (1.0 + tan30))] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
|
||||
let mut p = json!({"edges": [[40, 0, 10]], "distance": 2, "name": "Bevel"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
run(&mut s, "solid.chamfer", p);
|
||||
let v0 = volume(&mut s);
|
||||
let out = run(&mut s, "solid.press_pull", json!({"face": [40.0 - u, u, 10.0], "distance": 1}));
|
||||
assert_eq!(out["edited"], "Bevel", "{extra}: {out}");
|
||||
assert_eq!(s.doc.features.len(), 2, "{extra}");
|
||||
let Some(solidcraft_doc::FeatureKind::Chamfer { distance2, angle, .. }) = s.doc.features.last().map(|f| &f.kind) else { panic!("{extra}") };
|
||||
assert_eq!(distance2.as_ref().map(|e| e.to_string()), extra.get("distance2").map(|v| v.to_string()), "{extra}");
|
||||
assert_eq!(angle.as_ref().map(|e| e.to_string()), extra.get("angle").and_then(|v| v.as_str()).map(str::to_string), "{extra}");
|
||||
assert!(volume(&mut s) < v0 - 1.0, "{extra}: a bigger chamfer cuts more");
|
||||
}
|
||||
}
|
||||
|
||||
/// A cut in one component leaves other components' bodies alone unless they are named as
|
||||
/// participants; auto join/cut looks at the active component only.
|
||||
#[test]
|
||||
|
||||
@@ -107,13 +107,17 @@ impl Capturer {
|
||||
self.lost.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// [`Capturer::is_lost`], asking the driver first: an empty submission meets a loss the
|
||||
/// driver reports and marks it, where the picture's first upload would panic inside wgpu.
|
||||
/// [`Capturer::is_lost`], asking the driver first: a submission that opens a command list
|
||||
/// meets a loss the driver reports and marks it, where the picture's first upload would
|
||||
/// panic inside wgpu. As `egui_wgpu::DeviceLost::probe`: an empty submission only signals a
|
||||
/// fence, which a reset D3D12 device let through (#6528).
|
||||
fn probe_lost(&self) -> bool {
|
||||
if self.is_lost() {
|
||||
return true;
|
||||
}
|
||||
self.queue.submit([]);
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("device lost probe") });
|
||||
encoder.insert_debug_marker("device lost probe");
|
||||
self.queue.submit([encoder.finish()]);
|
||||
self.is_lost()
|
||||
}
|
||||
|
||||
|
||||
@@ -44,3 +44,6 @@ rustix = { version = "1", default-features = false, features = ["std", "fs"] }
|
||||
# The computer's name for a design's lock file (src/design_lock.rs; the browser keeps no lock files).
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
gethostname = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
solidcraft-testkit = { workspace = true }
|
||||
+270
-554
@@ -1,323 +1,40 @@
|
||||
//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of
|
||||
//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten
|
||||
//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and
|
||||
//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an
|
||||
//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a
|
||||
//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any
|
||||
//! panic, so a caught one on the desktop is a crash there.
|
||||
//!
|
||||
//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces.
|
||||
//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and
|
||||
//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a
|
||||
//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino
|
||||
//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests.
|
||||
//! Every reader of bytes the user didn't write, run over mutations of a valid file (#469): each
|
||||
//! case gives an error or a result, never a panic, within the time budget and the reader's own
|
||||
//! caps. The mutations and the check are `solidcraft_testkit`'s.
|
||||
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::time::{Duration, Instant};
|
||||
use solidcraft_geom::{Mesh, Vec2, Vec3};
|
||||
use solidcraft_testkit::{mutations, survives};
|
||||
|
||||
/// A deterministic xorshift64 stream.
|
||||
pub(crate) struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
pub(crate) fn new(seed: u64) -> Rng {
|
||||
Rng(seed | 1)
|
||||
}
|
||||
|
||||
pub(crate) fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
/// A value in `0..n` (0 when `n` is 0).
|
||||
pub(crate) fn below(&mut self, n: usize) -> usize {
|
||||
if n == 0 { 0 } else { (self.next() % n as u64) as usize }
|
||||
}
|
||||
fn cube() -> Mesh {
|
||||
let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect();
|
||||
let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]];
|
||||
Mesh { positions, triangles: t.to_vec(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Numbers a hostile file might hold in place of a real one.
|
||||
const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"];
|
||||
|
||||
/// Most truncations of one file (every length up to this, evenly spaced beyond).
|
||||
const MAX_TRUNCATIONS: usize = 1024;
|
||||
|
||||
/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number
|
||||
/// mutations (the file is UTF-8 text).
|
||||
pub(crate) fn mutations(good: &[u8], text: bool, seed: u64) -> Vec<Vec<u8>> {
|
||||
let mut out: Vec<Vec<u8>> = Vec::new();
|
||||
let n = good.len();
|
||||
let mut rng = Rng::new(seed);
|
||||
// Truncations: every length of a short file; of a long one, its first and last 64 lengths
|
||||
// (headers, final records) and evenly spaced ones between.
|
||||
if n <= MAX_TRUNCATIONS {
|
||||
out.extend((0..n).map(|k| good[..k].to_vec()));
|
||||
} else {
|
||||
let mut cuts: Vec<usize> = (0..64).chain(n - 64..n).collect();
|
||||
cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128)));
|
||||
cuts.sort_unstable();
|
||||
cuts.dedup();
|
||||
out.extend(cuts.into_iter().map(|k| good[..k].to_vec()));
|
||||
}
|
||||
if n == 0 {
|
||||
return out;
|
||||
}
|
||||
// Bytes flipped, zeroed and saturated at seeded places.
|
||||
for i in 0..384 {
|
||||
let at = rng.below(n);
|
||||
let mut b = good.to_vec();
|
||||
b[at] = match i % 3 {
|
||||
0 => b[at] ^ ((rng.next() >> 32) as u8 | 1),
|
||||
1 => 0x00,
|
||||
_ => 0xff,
|
||||
};
|
||||
out.push(b);
|
||||
}
|
||||
// Runs of bytes dropped, repeated and swapped with their neighbour.
|
||||
for _ in 0..96 {
|
||||
let at = rng.below(n);
|
||||
let len = 1 + rng.below(64.min(n - at));
|
||||
let end = at + len;
|
||||
let mut dropped = good[..at].to_vec();
|
||||
dropped.extend_from_slice(&good[end..]);
|
||||
out.push(dropped);
|
||||
let mut repeated = good[..end].to_vec();
|
||||
repeated.extend_from_slice(&good[at..]);
|
||||
out.push(repeated);
|
||||
if end + len <= n {
|
||||
let mut swapped = good[..at].to_vec();
|
||||
swapped.extend_from_slice(&good[end..end + len]);
|
||||
swapped.extend_from_slice(&good[at..end]);
|
||||
swapped.extend_from_slice(&good[end + len..]);
|
||||
out.push(swapped);
|
||||
}
|
||||
}
|
||||
// The whole file: with garbage after it, twice over, reversed.
|
||||
let mut tail = good.to_vec();
|
||||
tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8));
|
||||
out.push(tail);
|
||||
out.push([good, good].concat());
|
||||
out.push(good.iter().rev().copied().collect());
|
||||
if text && let Ok(s) = std::str::from_utf8(good) {
|
||||
out.extend(text_mutations(s, &mut rng));
|
||||
}
|
||||
out
|
||||
#[test]
|
||||
fn stl_survives_mutation() {
|
||||
let mesh = cube();
|
||||
let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz");
|
||||
let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes();
|
||||
assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12));
|
||||
assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12));
|
||||
let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len());
|
||||
survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read);
|
||||
survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read);
|
||||
}
|
||||
|
||||
/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies.
|
||||
fn text_mutations(s: &str, rng: &mut Rng) -> Vec<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
let lines: Vec<&str> = s.split_inclusive('\n').collect();
|
||||
let join = |v: &[&str]| v.concat().into_bytes();
|
||||
let picked: Vec<usize> = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() };
|
||||
for &i in &picked {
|
||||
let mut v = lines.clone();
|
||||
v.remove(i);
|
||||
out.push(join(&v));
|
||||
let mut v = lines.clone();
|
||||
v.insert(i, lines[i]);
|
||||
out.push(join(&v));
|
||||
if i + 1 < lines.len() {
|
||||
let mut v = lines.clone();
|
||||
v.swap(i, i + 1);
|
||||
out.push(join(&v));
|
||||
}
|
||||
}
|
||||
// A line in place of another (a block that inserts itself, a count where a coordinate was).
|
||||
for _ in 0..200.min(lines.len() * lines.len()) {
|
||||
let (i, j) = (rng.below(lines.len()), rng.below(lines.len()));
|
||||
let mut v = lines.clone();
|
||||
v[i] = lines[j];
|
||||
out.push(join(&v));
|
||||
}
|
||||
// A word in place of another of the file's own words: a renamed block, a swapped keyword, a
|
||||
// block that now inserts itself. Every pair in a small file, a sample in a large one.
|
||||
let words = word_spans(s);
|
||||
let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect();
|
||||
vocab.sort_unstable();
|
||||
vocab.dedup();
|
||||
let pairs = words.len().saturating_mul(vocab.len());
|
||||
let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes();
|
||||
if pairs <= 3000 {
|
||||
for &span in &words {
|
||||
for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) {
|
||||
out.push(swap(span, w));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _ in 0..400 {
|
||||
out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())]));
|
||||
}
|
||||
}
|
||||
// Numbers: each of up to 200 of them, in turn, becomes one of the liars.
|
||||
let numbers = number_spans(s);
|
||||
let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() };
|
||||
for (k, (a, b)) in chosen.into_iter().enumerate() {
|
||||
let liar = LIARS[k % LIARS.len()];
|
||||
out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes());
|
||||
}
|
||||
// Every number lying at once (two counts that are only harmless one at a time).
|
||||
let all = number_spans(s);
|
||||
for liar in LIARS {
|
||||
let mut t = String::with_capacity(s.len());
|
||||
let mut at = 0;
|
||||
for &(a, b) in &all {
|
||||
t.push_str(&s[at..a]);
|
||||
t.push_str(liar);
|
||||
at = b;
|
||||
}
|
||||
t.push_str(&s[at..]);
|
||||
out.push(t.into_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a
|
||||
/// letter).
|
||||
fn word_spans(s: &str) -> Vec<(usize, usize)> {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let a = i;
|
||||
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
|
||||
i += 1;
|
||||
}
|
||||
out.push((a, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent).
|
||||
fn number_spans(s: &str) -> Vec<(usize, usize)> {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit));
|
||||
let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_');
|
||||
if !starts || after_word {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let a = i;
|
||||
i += 1;
|
||||
while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) {
|
||||
if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out.push((a, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Panics on this thread so far, caught or not ([`count_panics`]).
|
||||
static PANICS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Count every panic per thread (tests run on several), then run the hook that was there.
|
||||
fn count_panics() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
PANICS.with(|p| p.set(p.get() + 1));
|
||||
previous(info);
|
||||
}));
|
||||
#[test]
|
||||
fn obj_survives_mutation() {
|
||||
let good = crate::obj(&[("Cube".into(), cube())]).into_bytes();
|
||||
assert!(crate::read_obj(&good, "fuzz").is_ok());
|
||||
survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| {
|
||||
crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
}
|
||||
|
||||
/// The time any one reader call may take on a mutated file (a debug build on a loaded machine:
|
||||
/// generous, but far below what unbounded work on a lying count would take).
|
||||
pub(crate) const BUDGET: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles,
|
||||
/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming
|
||||
/// the first case that breaks a rule.
|
||||
pub(crate) fn survives(what: &str, inputs: &[Vec<u8>], cap: usize, mut read: impl FnMut(&[u8]) -> Option<usize>) {
|
||||
count_panics();
|
||||
let mut slowest = (Duration::ZERO, 0);
|
||||
let mut read_ok = 0;
|
||||
for (i, input) in inputs.iter().enumerate() {
|
||||
let before = PANICS.with(std::cell::Cell::get);
|
||||
let t = Instant::now();
|
||||
let r = catch_unwind(AssertUnwindSafe(|| read(input)));
|
||||
let took = t.elapsed();
|
||||
let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned();
|
||||
let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) };
|
||||
let caught = PANICS.with(std::cell::Cell::get) - before;
|
||||
assert!(
|
||||
caught == 0,
|
||||
"{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}",
|
||||
input.len()
|
||||
);
|
||||
assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len());
|
||||
if let Some(count) = r {
|
||||
assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})");
|
||||
read_ok += 1;
|
||||
}
|
||||
slowest = slowest.max((took, i));
|
||||
}
|
||||
eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solidcraft_geom::{Mesh, Vec2, Vec3};
|
||||
|
||||
fn cube() -> Mesh {
|
||||
let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect();
|
||||
let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]];
|
||||
Mesh { positions, triangles: t.to_vec(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutations_are_deterministic_and_cover_the_file() {
|
||||
let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n";
|
||||
let a = mutations(good, true, 7);
|
||||
assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases");
|
||||
assert_ne!(a, mutations(good, true, 8));
|
||||
assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing");
|
||||
assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar");
|
||||
assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]);
|
||||
// A long file: bounded truncations, kept to the first and last bytes and spaced between.
|
||||
let long = vec![b'a'; 100_000];
|
||||
let m = mutations(&long, false, 1);
|
||||
assert!(m.len() < 3000, "{} cases", m.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stl_survives_mutation() {
|
||||
let mesh = cube();
|
||||
let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz");
|
||||
let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes();
|
||||
assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12));
|
||||
assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12));
|
||||
let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len());
|
||||
survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read);
|
||||
survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_survives_mutation() {
|
||||
let good = crate::obj(&[("Cube".into(), cube())]).into_bytes();
|
||||
assert!(crate::read_obj(&good, "fuzz").is_ok());
|
||||
survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| {
|
||||
crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_survives_mutation() {
|
||||
let good = br##"<svg xmlns="http://www.w3.org/2000/svg" width="100mm" height="50mm" viewBox="0 0 100 50">
|
||||
#[test]
|
||||
fn svg_survives_mutation() {
|
||||
let good = br##"<svg xmlns="http://www.w3.org/2000/svg" width="100mm" height="50mm" viewBox="0 0 100 50">
|
||||
<g transform="translate(10 5) rotate(15) scale(1.5)">
|
||||
<rect x="1" y="2" width="30" height="4" rx="1"/>
|
||||
<circle cx="20" cy="20" r="5"/>
|
||||
@@ -328,266 +45,265 @@ mod tests {
|
||||
<use href="#a"/><g id="a"><line x1="0" y1="0" x2="5" y2="5"/></g>
|
||||
</svg>
|
||||
"##;
|
||||
assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok());
|
||||
survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len()));
|
||||
}
|
||||
assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok());
|
||||
survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_survives_mutation() {
|
||||
let geom = [
|
||||
crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)),
|
||||
crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5),
|
||||
crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) },
|
||||
crate::Geom2::Point(Vec2::new(1.0, 1.0)),
|
||||
];
|
||||
let written = crate::write_dxf(&geom).into_bytes();
|
||||
assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3));
|
||||
survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| {
|
||||
crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())
|
||||
});
|
||||
// Blocks inside blocks, an array insert and a bulged polyline: what the block recursion,
|
||||
// the array cells and the work budget guard.
|
||||
let pairs: &[(&str, &str)] = &[
|
||||
("0", "SECTION"),
|
||||
("2", "BLOCKS"),
|
||||
("0", "BLOCK"),
|
||||
("2", "inner"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("0", "LINE"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("11", "1"),
|
||||
("21", "1"),
|
||||
("0", "ENDBLK"),
|
||||
("0", "BLOCK"),
|
||||
("2", "outer"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("0", "INSERT"),
|
||||
("2", "inner"),
|
||||
("10", "2"),
|
||||
("20", "2"),
|
||||
("0", "CIRCLE"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("40", "1"),
|
||||
("0", "ENDBLK"),
|
||||
("0", "ENDSEC"),
|
||||
("0", "SECTION"),
|
||||
("2", "ENTITIES"),
|
||||
("0", "INSERT"),
|
||||
("2", "outer"),
|
||||
("10", "5"),
|
||||
("20", "5"),
|
||||
("41", "2"),
|
||||
("42", "2"),
|
||||
("50", "30"),
|
||||
("70", "3"),
|
||||
("71", "2"),
|
||||
("44", "10"),
|
||||
("45", "10"),
|
||||
("0", "LWPOLYLINE"),
|
||||
("90", "3"),
|
||||
("70", "1"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("42", "0.5"),
|
||||
("10", "5"),
|
||||
("20", "0"),
|
||||
("10", "5"),
|
||||
("20", "5"),
|
||||
("0", "ENDSEC"),
|
||||
("0", "EOF"),
|
||||
];
|
||||
let blocks: String = pairs
|
||||
.iter()
|
||||
.map(|(c, v)| {
|
||||
format!(
|
||||
"{c}
|
||||
#[test]
|
||||
fn dxf_survives_mutation() {
|
||||
let geom = [
|
||||
crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)),
|
||||
crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5),
|
||||
crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) },
|
||||
crate::Geom2::Point(Vec2::new(1.0, 1.0)),
|
||||
];
|
||||
let written = crate::write_dxf(&geom).into_bytes();
|
||||
assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3));
|
||||
survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()));
|
||||
// Blocks inside blocks, an array insert and a bulged polyline: what the block recursion,
|
||||
// the array cells and the work budget guard.
|
||||
let pairs: &[(&str, &str)] = &[
|
||||
("0", "SECTION"),
|
||||
("2", "BLOCKS"),
|
||||
("0", "BLOCK"),
|
||||
("2", "inner"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("0", "LINE"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("11", "1"),
|
||||
("21", "1"),
|
||||
("0", "ENDBLK"),
|
||||
("0", "BLOCK"),
|
||||
("2", "outer"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("0", "INSERT"),
|
||||
("2", "inner"),
|
||||
("10", "2"),
|
||||
("20", "2"),
|
||||
("0", "CIRCLE"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("40", "1"),
|
||||
("0", "ENDBLK"),
|
||||
("0", "ENDSEC"),
|
||||
("0", "SECTION"),
|
||||
("2", "ENTITIES"),
|
||||
("0", "INSERT"),
|
||||
("2", "outer"),
|
||||
("10", "5"),
|
||||
("20", "5"),
|
||||
("41", "2"),
|
||||
("42", "2"),
|
||||
("50", "30"),
|
||||
("70", "3"),
|
||||
("71", "2"),
|
||||
("44", "10"),
|
||||
("45", "10"),
|
||||
("0", "LWPOLYLINE"),
|
||||
("90", "3"),
|
||||
("70", "1"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("42", "0.5"),
|
||||
("10", "5"),
|
||||
("20", "0"),
|
||||
("10", "5"),
|
||||
("20", "5"),
|
||||
("0", "ENDSEC"),
|
||||
("0", "EOF"),
|
||||
];
|
||||
let blocks: String = pairs
|
||||
.iter()
|
||||
.map(|(c, v)| {
|
||||
format!(
|
||||
"{c}
|
||||
{v}
|
||||
"
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0);
|
||||
assert!(n >= 12, "the array insert expands its nested blocks: {n} entities");
|
||||
survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| {
|
||||
crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())
|
||||
});
|
||||
// The two lies that need each other, written out: a block that inserts itself (the
|
||||
// depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets).
|
||||
let looped = blocks.replacen(
|
||||
"2
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0);
|
||||
assert!(n >= 12, "the array insert expands its nested blocks: {n} entities");
|
||||
survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| {
|
||||
crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())
|
||||
});
|
||||
// The two lies that need each other, written out: a block that inserts itself (the
|
||||
// depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets).
|
||||
let looped = blocks.replacen(
|
||||
"2
|
||||
inner
|
||||
10
|
||||
2",
|
||||
"2
|
||||
"2
|
||||
outer
|
||||
10
|
||||
2",
|
||||
1,
|
||||
);
|
||||
assert_ne!(looped, blocks, "the outer block now inserts itself");
|
||||
let huge = blocks.replacen(
|
||||
"70
|
||||
1,
|
||||
);
|
||||
assert_ne!(looped, blocks, "the outer block now inserts itself");
|
||||
let huge = blocks.replacen(
|
||||
"70
|
||||
3
|
||||
71
|
||||
2",
|
||||
"70
|
||||
"70
|
||||
10000
|
||||
71
|
||||
10000",
|
||||
1,
|
||||
);
|
||||
assert_ne!(huge, blocks);
|
||||
survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| {
|
||||
crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())
|
||||
});
|
||||
}
|
||||
1,
|
||||
);
|
||||
assert_ne!(huge, blocks);
|
||||
survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| {
|
||||
crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threemf_survives_mutation() {
|
||||
let mesh = cube();
|
||||
let object = crate::MeshObject {
|
||||
name: "Cube".into(),
|
||||
positions: mesh.positions,
|
||||
triangles: mesh.triangles,
|
||||
color: Some([0.8, 0.2, 0.1]),
|
||||
..Default::default()
|
||||
};
|
||||
let good = crate::write_3mf(&[object]).unwrap();
|
||||
assert!(crate::read_3mf(&good).is_ok());
|
||||
survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| {
|
||||
#[test]
|
||||
fn threemf_survives_mutation() {
|
||||
let mesh = cube();
|
||||
let object = crate::MeshObject {
|
||||
name: "Cube".into(),
|
||||
positions: mesh.positions,
|
||||
triangles: mesh.triangles,
|
||||
color: Some([0.8, 0.2, 0.1]),
|
||||
..Default::default()
|
||||
};
|
||||
let good = crate::write_3mf(&[object]).unwrap();
|
||||
assert!(crate::read_3mf(&good).is_ok());
|
||||
survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| {
|
||||
crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
// Objects in another model part (production extension), as slicers save projects.
|
||||
let production = crate::threemf::tests::production_package();
|
||||
assert!(crate::read_3mf(&production).is_ok());
|
||||
survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| {
|
||||
crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
// Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its
|
||||
// checksums, these reach the `p:path` and `objectid` handling.
|
||||
let parts = crate::threemf::tests::production_parts();
|
||||
for (k, (name, xml)) in parts.iter().enumerate() {
|
||||
let rezipped: Vec<Vec<u8>> = mutations(xml.as_bytes(), true, 0x2089 + k as u64)
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect();
|
||||
crate::threemf::tests::package_bytes(&entries)
|
||||
})
|
||||
.collect();
|
||||
survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| {
|
||||
crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
// Objects in another model part (production extension), as slicers save projects.
|
||||
let production = crate::threemf::tests::production_package();
|
||||
assert!(crate::read_3mf(&production).is_ok());
|
||||
survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| {
|
||||
crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
// Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its
|
||||
// checksums, these reach the `p:path` and `objectid` handling.
|
||||
let parts = crate::threemf::tests::production_parts();
|
||||
for (k, (name, xml)) in parts.iter().enumerate() {
|
||||
let rezipped: Vec<Vec<u8>> = mutations(xml.as_bytes(), true, 0x2089 + k as u64)
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect();
|
||||
crate::threemf::tests::package_bytes(&entries)
|
||||
})
|
||||
.collect();
|
||||
survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| {
|
||||
crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_survives_mutation() {
|
||||
let mut f = crate::gltf_in::tests::Fixture::default();
|
||||
let m = f.cube_mesh("Cube", 0.01);
|
||||
let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]}));
|
||||
let n = f.node(serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]}));
|
||||
f.roots = vec![n];
|
||||
let mut no_files = |name: &str| -> std::result::Result<Vec<u8>, String> { Err(format!("no file `{name}`")) };
|
||||
let glb = f.glb();
|
||||
assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok());
|
||||
survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1));
|
||||
// The JSON form, its buffer embedded as a data URI.
|
||||
let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin));
|
||||
let gltf = f.json(Some(&uri)).to_string().into_bytes();
|
||||
assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok());
|
||||
survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_survive_mutation() {
|
||||
let mut doc = solidcraft_doc::Document::new("Fuzz");
|
||||
doc.set_param("width", "40", Some("mm"), None).unwrap();
|
||||
let mesh = solidcraft_doc::MeshData {
|
||||
name: "Preview".into(),
|
||||
positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(),
|
||||
triangles: vec![0, 1, 2].into(),
|
||||
color: None,
|
||||
};
|
||||
let preview = crate::DesignPreview { meshes: vec![mesh] };
|
||||
let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap();
|
||||
assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some());
|
||||
survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| {
|
||||
let _ = crate::read_design_preview(b);
|
||||
let _ = crate::read_design_thumbnail(b);
|
||||
crate::read_design(b).ok().map(|d| d.features.len())
|
||||
});
|
||||
let json = crate::write_design(&doc);
|
||||
assert!(crate::read_design(&json).is_ok());
|
||||
survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len()));
|
||||
}
|
||||
|
||||
/// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing,
|
||||
/// never a panic, and `file_kind` always answers.
|
||||
#[test]
|
||||
fn drawings_survive_mutation() {
|
||||
use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet};
|
||||
let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a);
|
||||
let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape);
|
||||
let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap();
|
||||
let id = drawing.allocate_id(&mut ids).unwrap();
|
||||
drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() });
|
||||
let container = crate::write_drawing_container(&drawing).unwrap();
|
||||
assert!(crate::read_drawing(&container).is_ok());
|
||||
survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| {
|
||||
let _ = crate::file_kind(b);
|
||||
let _ = crate::read_design(b);
|
||||
crate::read_drawing(b).ok().map(|d| d.sheets.len())
|
||||
});
|
||||
let json = drawing.to_json().unwrap().into_bytes();
|
||||
assert!(crate::read_drawing(&json).is_ok());
|
||||
survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| {
|
||||
let _ = crate::file_kind(b);
|
||||
crate::read_drawing(b).ok().map(|d| d.sheets.len())
|
||||
});
|
||||
}
|
||||
|
||||
/// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document,
|
||||
/// never a panic.
|
||||
#[test]
|
||||
fn paper_scenes_survive_mutation_into_svg() {
|
||||
use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene};
|
||||
use solidcraft_geom::{Loop2, Region2, Seg2, Vec2};
|
||||
let p = Vec2::new;
|
||||
let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]);
|
||||
let items = vec![
|
||||
Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 },
|
||||
Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 },
|
||||
Item::Fill { region: Region2 { outer: border, holes: vec![] } },
|
||||
];
|
||||
let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] };
|
||||
let json = serde_json::to_vec(&scene).unwrap();
|
||||
let write = |b: &[u8]| -> Option<usize> {
|
||||
let scene: Scene = serde_json::from_slice(b).ok()?;
|
||||
let prepared = scene.prepare().ok()?;
|
||||
crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len())
|
||||
};
|
||||
assert!(write(&json).is_some());
|
||||
survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write);
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648) of `bytes`, for a data URI.
|
||||
fn base64(bytes: &[u8]) -> String {
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::new();
|
||||
for c in bytes.chunks(3) {
|
||||
let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0));
|
||||
for k in 0..4 {
|
||||
if k <= c.len() {
|
||||
s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63]));
|
||||
} else {
|
||||
s.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_survives_mutation() {
|
||||
let mut f = crate::gltf_in::tests::Fixture::default();
|
||||
let m = f.cube_mesh("Cube", 0.01);
|
||||
let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]}));
|
||||
let n = f.node(
|
||||
serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]}),
|
||||
);
|
||||
f.roots = vec![n];
|
||||
let mut no_files = |name: &str| -> std::result::Result<Vec<u8>, String> { Err(format!("no file `{name}`")) };
|
||||
let glb = f.glb();
|
||||
assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok());
|
||||
survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1));
|
||||
// The JSON form, its buffer embedded as a data URI.
|
||||
let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin));
|
||||
let gltf = f.json(Some(&uri)).to_string().into_bytes();
|
||||
assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok());
|
||||
survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_survive_mutation() {
|
||||
let mut doc = solidcraft_doc::Document::new("Fuzz");
|
||||
doc.set_param("width", "40", Some("mm"), None).unwrap();
|
||||
let mesh = solidcraft_doc::MeshData {
|
||||
name: "Preview".into(),
|
||||
positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(),
|
||||
triangles: vec![0, 1, 2].into(),
|
||||
color: None,
|
||||
};
|
||||
let preview = crate::DesignPreview { meshes: vec![mesh] };
|
||||
let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap();
|
||||
assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some());
|
||||
survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| {
|
||||
let _ = crate::read_design_preview(b);
|
||||
let _ = crate::read_design_thumbnail(b);
|
||||
crate::read_design(b).ok().map(|d| d.features.len())
|
||||
});
|
||||
let json = crate::write_design(&doc);
|
||||
assert!(crate::read_design(&json).is_ok());
|
||||
survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len()));
|
||||
}
|
||||
|
||||
/// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing,
|
||||
/// never a panic, and `file_kind` always answers.
|
||||
#[test]
|
||||
fn drawings_survive_mutation() {
|
||||
use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet};
|
||||
let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a);
|
||||
let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape);
|
||||
let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap();
|
||||
let id = drawing.allocate_id(&mut ids).unwrap();
|
||||
drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() });
|
||||
let container = crate::write_drawing_container(&drawing).unwrap();
|
||||
assert!(crate::read_drawing(&container).is_ok());
|
||||
survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| {
|
||||
let _ = crate::file_kind(b);
|
||||
let _ = crate::read_design(b);
|
||||
crate::read_drawing(b).ok().map(|d| d.sheets.len())
|
||||
});
|
||||
let json = drawing.to_json().unwrap().into_bytes();
|
||||
assert!(crate::read_drawing(&json).is_ok());
|
||||
survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| {
|
||||
let _ = crate::file_kind(b);
|
||||
crate::read_drawing(b).ok().map(|d| d.sheets.len())
|
||||
});
|
||||
}
|
||||
|
||||
/// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document,
|
||||
/// never a panic.
|
||||
#[test]
|
||||
fn paper_scenes_survive_mutation_into_svg() {
|
||||
use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene};
|
||||
use solidcraft_geom::{Loop2, Region2, Seg2, Vec2};
|
||||
let p = Vec2::new;
|
||||
let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]);
|
||||
let items = vec![
|
||||
Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 },
|
||||
Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 },
|
||||
Item::Fill { region: Region2 { outer: border, holes: vec![] } },
|
||||
];
|
||||
let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] };
|
||||
let json = serde_json::to_vec(&scene).unwrap();
|
||||
let write = |b: &[u8]| -> Option<usize> {
|
||||
let scene: Scene = serde_json::from_slice(b).ok()?;
|
||||
let prepared = scene.prepare().ok()?;
|
||||
crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len())
|
||||
};
|
||||
assert!(write(&json).is_some());
|
||||
survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write);
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648) of `bytes`, for a data URI.
|
||||
fn base64(bytes: &[u8]) -> String {
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::new();
|
||||
for c in bytes.chunks(3) {
|
||||
let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0));
|
||||
for k in 0..4 {
|
||||
if k <= c.len() {
|
||||
s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63]));
|
||||
} else {
|
||||
s.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -15,3 +15,5 @@ serde_json = { workspace = true }
|
||||
[dev-dependencies]
|
||||
# The renderer `solidcraft-cli mcp` installs, so the tests' screenshots are drawn as the server's.
|
||||
solidcraft-gpu = { workspace = true }
|
||||
# Synthetic reference pictures for the compare_picture test.
|
||||
image = { workspace = true }
|
||||
@@ -137,6 +137,7 @@ fn handshake_and_tools_list() {
|
||||
"set_parameter",
|
||||
"check_parameters",
|
||||
"screenshot",
|
||||
"compare_picture",
|
||||
"export",
|
||||
"undo",
|
||||
"redo",
|
||||
@@ -1469,6 +1470,46 @@ fn legacy_design_files_and_resource_uris() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `compare_picture` (#1486): the overlay comes back as an image block and the numbers as text.
|
||||
#[test]
|
||||
fn compare_picture_returns_the_overlay_as_an_image() {
|
||||
use image::ImageEncoder as _;
|
||||
use std::io::Cursor;
|
||||
// A scoped server, like `solidcraft-cli mcp`: the reference must be inside the folders.
|
||||
let base = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-mcp-compare-{}", std::process::id()));
|
||||
let recovery = base.join("recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
let scope = crate::agent_scope_with(Some(recovery.clone()), []);
|
||||
let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(scope));
|
||||
tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 20, "width": 10, "height": 30}}));
|
||||
// A white rectangle on grey with the box's front-view proportions (20 x 30 mm).
|
||||
let (w, h) = (200u32, 300u32);
|
||||
let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 200, 200, 255]));
|
||||
for y in 20..280 {
|
||||
for x in 20..180 {
|
||||
img.put_pixel(x, y, image::Rgba([255, 255, 255, 255]));
|
||||
}
|
||||
}
|
||||
let mut png = Cursor::new(Vec::new());
|
||||
image::codecs::png::PngEncoder::new(&mut png).write_image(img.as_raw(), w, h, image::ExtendedColorType::Rgba8).unwrap();
|
||||
let path = recovery.join("target.png");
|
||||
std::fs::write(&path, png.into_inner()).unwrap();
|
||||
|
||||
let r = raw_tool(&mut s, "compare_picture", json!({"reference": path.to_string_lossy(), "view": "front"}));
|
||||
assert_ne!(r["result"]["isError"], json!(true), "{r}");
|
||||
let content = r["result"]["content"].as_array().unwrap().clone();
|
||||
assert_eq!(content[0]["type"], "image", "{content:?}");
|
||||
assert_eq!(content[0]["mimeType"], "image/png");
|
||||
assert!(content[0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG");
|
||||
let info: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap();
|
||||
assert!(info["overlap"].as_f64().unwrap() > 0.9, "{info}");
|
||||
assert!(info.get("overlay_png").is_none(), "the base64 blob belongs in the image block only");
|
||||
// A reference outside the server's folders is refused through the existing path rules.
|
||||
let outside = raw_tool(&mut s, "compare_picture", json!({"reference": "/etc/hostname"}));
|
||||
assert_eq!(outside["result"]["isError"], json!(true), "{outside}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The default folders (#205): the recovery folder works out of the box, `screenshot` without a
|
||||
/// `path` uses the server's own scratch folder, and the open design's folder counts while the
|
||||
/// design is open there, without its hidden files. The working folder doesn't count at all.
|
||||
|
||||
+61
-1
@@ -147,7 +147,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
(as list_commands lists them). A step may also name one of these tools with that tool's arguments as params, \
|
||||
and runs the engine command it stands for: set_parameter (parameters.change; `value` or `expression`), \
|
||||
list_commands (engine.commands, with `filter`), describe_command (engine.describe), execute ({command, params}), \
|
||||
measure (inspect.measure), \
|
||||
measure (inspect.measure), compare_picture (inspect.compare_picture, numbers only: no overlay PNG), \
|
||||
inspect_design (document.inspect), undo, redo, export, save, open, new_design, crash_reports; screenshot, \
|
||||
body_topology, batch and pending can't be steps. On an error the steps already run are undone (unless \
|
||||
rollback: false), so the batch is all-or-nothing; the reply names the failing step (index from 0), its error, \
|
||||
@@ -307,6 +307,34 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
),
|
||||
Effect::Files,
|
||||
),
|
||||
tool(
|
||||
"compare_picture",
|
||||
"Compare with a reference picture",
|
||||
"Compare the model's outline with the part in a reference picture — a concept render, a product photo, one view off a design board. \
|
||||
The model's outline is `inspect.silhouette` from `view` (default front), `camera` and `bodies`; the picture's part is found by growing \
|
||||
the background in from the border, so a backdrop's gradual shading stays background. The compare is outline only: holes are not \
|
||||
compared — both the picture's and the model's holes are filled. `reference` is a PNG or JPEG inside the server's \
|
||||
folders. `crop_px` / `crop_fraction` take one view off a board: [x, y, w, h] in pixels or as fractions 0..1 of the picture; \
|
||||
`part_fills_crop: true` says the crop box is the part itself, for a crop that tightly frames it. `fit` names \
|
||||
the dimension the scale comes from (\"width\", \"height\", \"both\"; default \"width\") — one uniform scale, never stretched per axis; \
|
||||
\"both\" scales by width and reports `aspect_mismatch` when the shapes differ. Returns as text the overlap (0..1) and the model's top, \
|
||||
bottom, left and right edges against the picture's in mm at nine stations (positive where the model reaches past the picture), and as \
|
||||
an image the overlay PNG: model red, picture blue.",
|
||||
obj(
|
||||
json!({
|
||||
"reference": string("PNG or JPEG to match, inside the server's folders"),
|
||||
"view": string("Standard view (front, top, right, iso, ...) the picture is seen from (default front)"),
|
||||
"camera": {"type": "object", "description": "Look from this camera instead: {target: [x,y,z], yaw, pitch, distance, fov?} (radians, mm; as view.apply). A photo taken in perspective gets an fov"},
|
||||
"bodies": {"type": "array", "items": {"type": "string"}, "description": "Body names to outline (default: the visible bodies)"},
|
||||
"crop_px": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] in pixels"},
|
||||
"crop_fraction": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] as fractions 0..1 of the picture"},
|
||||
"fit": {"type": "string", "enum": ["width", "height", "both"], "description": "The dimension the one uniform scale comes from (default width); both scales by width and reports aspect_mismatch"},
|
||||
"rows": {"type": "integer", "description": "The model outline's height in pixels (default 240)"},
|
||||
}),
|
||||
&["reference"],
|
||||
),
|
||||
Effect::Files,
|
||||
),
|
||||
tool(
|
||||
"export",
|
||||
"Export",
|
||||
@@ -497,6 +525,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value {
|
||||
let a = args.as_object().unwrap_or(&empty);
|
||||
let r = match name {
|
||||
"screenshot" => return screenshot(b, a),
|
||||
"compare_picture" => return compare_picture(b, a),
|
||||
"batch" => return batch(b, a),
|
||||
"check_parameters" => return check_parameters(b, a),
|
||||
"execute" => return execute(b, a),
|
||||
@@ -992,6 +1021,14 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option<Narrow>), String> {
|
||||
Some(items) => mapped("inspect.measure", json!({"items": items})),
|
||||
None => Ok(("inspect.measure".into(), measure_params(a), measure_summary_wanted(a).then_some(Narrow::MeasureSummary))),
|
||||
},
|
||||
"compare_picture" => {
|
||||
// A batch step gets the numbers; the overlay PNG would be a base64 blob in text.
|
||||
let mut p = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]);
|
||||
if let Some(obj) = p.as_object_mut() {
|
||||
obj.entry("overlay".to_string()).or_insert(json!(false));
|
||||
}
|
||||
mapped("inspect.compare_picture", p)
|
||||
}
|
||||
"inspect_design" => mapped("document.inspect", json!({"measure": a.get("measure").and_then(Value::as_bool).unwrap_or(true)})),
|
||||
"undo" => mapped("edit.undo", json!({})),
|
||||
"redo" => mapped("edit.redo", json!({})),
|
||||
@@ -1020,6 +1057,7 @@ const TOOL_STEPS: &[&str] = &[
|
||||
"batch",
|
||||
"body_topology",
|
||||
"check_parameters",
|
||||
"compare_picture",
|
||||
"crash_reports",
|
||||
"describe_command",
|
||||
"execute",
|
||||
@@ -1777,6 +1815,28 @@ fn screenshot(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// `compare_picture`: run the engine comparison and hand the overlay PNG back as an MCP
|
||||
/// image block, the numbers as text — an agent sees the picture, not a base64 blob.
|
||||
fn compare_picture(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
let mut params = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]);
|
||||
params["overlay"] = json!(true);
|
||||
match exec(b, "inspect.compare_picture", params) {
|
||||
Ok(v) => {
|
||||
let overlay = v.get("overlay_png").and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
let mut info = v;
|
||||
if let Some(obj) = info.as_object_mut() {
|
||||
obj.remove("overlay_png");
|
||||
}
|
||||
let mut content = vec![json!({"type": "text", "text": info.to_string()})];
|
||||
if !overlay.is_empty() {
|
||||
content.insert(0, json!({"type": "image", "data": overlay, "mimeType": "image/png"}));
|
||||
}
|
||||
json!({"content": content})
|
||||
}
|
||||
Err(e) => text_result(&Value::String(e), true),
|
||||
}
|
||||
}
|
||||
|
||||
fn capture(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<(Vec<u8>, Value), String> {
|
||||
// `grid` and `axes` shape a model render; the window shows what it shows.
|
||||
let guides: Vec<(&str, bool)> = ["grid", "axes"].into_iter().filter_map(|k| a.get(k).and_then(Value::as_bool).map(|v| (k, v))).collect();
|
||||
|
||||
@@ -19,6 +19,7 @@ image = { workspace = true, features = ["jpeg"] }
|
||||
moxcms = { workspace = true }
|
||||
png = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
web-time = { workspace = true }
|
||||
weezl = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -362,6 +362,7 @@ pub struct JobStatus {
|
||||
}
|
||||
|
||||
struct Data {
|
||||
completed_duration: Option<std::time::Duration>,
|
||||
punctual_diagnostics: Option<super::PunctualDiagnostics>,
|
||||
sampling: Option<super::adaptive::SamplingReport>,
|
||||
progress: Progress,
|
||||
@@ -370,6 +371,7 @@ struct Data {
|
||||
preview: Option<Arc<RenderPreview>>,
|
||||
}
|
||||
struct Record {
|
||||
started: web_time::Instant,
|
||||
presentation: Option<Arc<RetainedPresentation>>,
|
||||
textures: Option<super::textures::TextureSummary>,
|
||||
options: JobOptions,
|
||||
@@ -399,6 +401,10 @@ impl JobHandle {
|
||||
pub fn id(&self) -> JobId {
|
||||
self.0.id
|
||||
}
|
||||
/// Submission-to-publication time, captured once by the host, independent of UI polling.
|
||||
pub fn completed_duration(&self) -> Result<Option<std::time::Duration>> {
|
||||
self.0.data.lock().map(|data| data.completed_duration).map_err(|_| JobError::new(ErrorCode::Internal, "render duration lock poisoned"))
|
||||
}
|
||||
pub fn status(&self) -> Result<JobStatus> {
|
||||
let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?;
|
||||
Ok(JobStatus {
|
||||
@@ -861,6 +867,7 @@ impl Running {
|
||||
}));
|
||||
data.preview = None;
|
||||
data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 };
|
||||
data.completed_duration = Some(self.handle.0.started.elapsed());
|
||||
self.handle.0.notify();
|
||||
Ok(false)
|
||||
}
|
||||
@@ -1318,6 +1325,7 @@ impl ImageHost {
|
||||
(request, None)
|
||||
};
|
||||
let handle = JobHandle(Arc::new(Record {
|
||||
started: web_time::Instant::now(),
|
||||
presentation: None,
|
||||
textures,
|
||||
options,
|
||||
@@ -1329,6 +1337,7 @@ impl ImageHost {
|
||||
resolved,
|
||||
cancel: CancelToken::default(),
|
||||
data: Mutex::new(Data {
|
||||
completed_duration: None,
|
||||
punctual_diagnostics: None,
|
||||
sampling: None,
|
||||
progress: Progress { phase: Phase::Queued, done: 0, total: 1 },
|
||||
@@ -1435,6 +1444,7 @@ impl ImageHost {
|
||||
let metadata = self.0.shared.budget.reserve(metadata_bytes)?;
|
||||
let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata });
|
||||
let handle = JobHandle(Arc::new(Record {
|
||||
started: web_time::Instant::now(),
|
||||
presentation: Some(origin),
|
||||
textures: None,
|
||||
options,
|
||||
@@ -1446,6 +1456,7 @@ impl ImageHost {
|
||||
resolved,
|
||||
cancel: CancelToken::default(),
|
||||
data: Mutex::new(Data {
|
||||
completed_duration: None,
|
||||
punctual_diagnostics: None,
|
||||
sampling: None,
|
||||
progress: Progress { phase: Phase::Queued, done: 0, total: 1 },
|
||||
|
||||
@@ -348,6 +348,25 @@ fn native_job_finishes_without_any_poll_or_ui_pump() {
|
||||
assert_eq!(frame.info.png_bytes, frame.png().len() as u64);
|
||||
assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png())));
|
||||
assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256);
|
||||
let duration = job.completed_duration().unwrap().unwrap();
|
||||
assert_eq!(job.completed_duration().unwrap(), Some(duration), "completed duration is independent of status polling");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_duration_is_captured_at_publication_and_never_for_cancelled_work() {
|
||||
let host = CpuHost::cooperative();
|
||||
let job = host.submit(id(1, 1), 12, empty(), request()).unwrap();
|
||||
assert!(job.completed_duration().unwrap().is_none());
|
||||
drain(&host);
|
||||
let duration = job.completed_duration().unwrap().unwrap();
|
||||
assert!(duration.as_secs_f64().is_finite());
|
||||
job.status().unwrap();
|
||||
host.pump(1).unwrap();
|
||||
assert_eq!(job.completed_duration().unwrap(), Some(duration));
|
||||
let cancelled = host.submit(id(1, 2), 12, empty(), request()).unwrap();
|
||||
cancelled.cancel().unwrap();
|
||||
drain(&host);
|
||||
assert!(cancelled.completed_duration().unwrap().is_none());
|
||||
}
|
||||
|
||||
/// Isolate the existing integrator-to-host completion boundary with a real PNG
|
||||
|
||||
@@ -8,6 +8,8 @@ pub const MAX_POINTS: usize = 20_000;
|
||||
pub const MAX_CONSTRAINTS: usize = 40_000;
|
||||
/// Curves need points, so this follows the point cap.
|
||||
pub const MAX_CURVES: usize = MAX_POINTS;
|
||||
// [`SketchError::TooLarge`]'s message names this number; keep them matched (#10874).
|
||||
const _: () = assert!(MAX_POINTS == 20_000);
|
||||
|
||||
/// Largest coordinate or dimension value (mm) a sketch accepts.
|
||||
pub const MAX_COORD: f64 = 1e9;
|
||||
@@ -37,7 +39,12 @@ pub enum SketchError {
|
||||
Duplicate(String),
|
||||
#[error("invalid value: {0}")]
|
||||
Invalid(String),
|
||||
#[error("sketch is too large")]
|
||||
/// Cap hit on points, curves or constraints ([`MAX_POINTS`], [`MAX_CURVES`],
|
||||
/// [`MAX_CONSTRAINTS`]). Insert SVG/DXF of a dense drawing (a floorplan) often hits this;
|
||||
/// scale alone does not reduce how many curves the file has (#10874).
|
||||
#[error(
|
||||
"sketch is too large (at most 20000 points or curves); simplify the drawing or split it across sketches — changing scale does not reduce how many curves it has"
|
||||
)]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
@@ -1703,7 +1710,7 @@ impl Sketch {
|
||||
/// Points held together only through points about to go stay together: two rectangles'
|
||||
/// corners made coincident with one arc end are tied to each other when a trim takes that
|
||||
/// end away, instead of coming apart where they still meet.
|
||||
fn keep_ties_through(&mut self, gone: &[usize]) {
|
||||
pub(crate) fn keep_ties_through(&mut self, gone: &[usize]) {
|
||||
if gone.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -1740,7 +1747,7 @@ impl Sketch {
|
||||
}
|
||||
}
|
||||
|
||||
fn point_used_by_curve(&self, p: usize) -> bool {
|
||||
pub(crate) fn point_used_by_curve(&self, p: usize) -> bool {
|
||||
self.curves.iter().any(|c| c.kind.uses(p))
|
||||
}
|
||||
|
||||
|
||||
@@ -611,6 +611,13 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
|
||||
LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value),
|
||||
PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value),
|
||||
CircleCircleDistance { a, b, value, circles } => out.push(s.circle_circle_gap(a, b, circles) - value),
|
||||
// A length within convergence tolerance of zero means the line's two ends meet:
|
||||
// the component rows keep both directions constrained even when they do, the way a
|
||||
// coincidence does (the same treatment a distance of zero gets above).
|
||||
Length { l, value } if value.abs() <= TOL => {
|
||||
let (a, b) = s.line(l);
|
||||
out.extend([b.x - a.x, b.y - a.y]);
|
||||
}
|
||||
Length { l, value } => {
|
||||
let (a, b) = s.line(l);
|
||||
out.push(a.dist(b) - value);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! New points on an existing fit spline (#6533): a fit point inserted where the curve already
|
||||
//! runs, or a new first or last point the spline runs on to. Also a spline's direction reversed
|
||||
//! (#8224).
|
||||
//! runs, or a new first or last point the spline runs on to. One point taken out of a spline
|
||||
//! (#10783). Also a spline's direction reversed (#8224).
|
||||
//!
|
||||
//! The spline keeps its curve index and every point it had (the new point is appended to
|
||||
//! `Sketch::points`), so constraints on its points and on the curve stay as they were.
|
||||
@@ -87,6 +87,77 @@ impl Sketch {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Take point `p` out of spline `ci` (#10783), and return whether the point itself went too.
|
||||
/// The spline runs through (or over) its other points, and keeps its curve index, so
|
||||
/// constraints on the curve and on its other points stay. The point goes with the constraints
|
||||
/// on it, unless another curve uses it (it stays, for that curve) or it is the origin.
|
||||
///
|
||||
/// The spline keeps at least 2 points (a closed one 3 besides its closing point, which stays).
|
||||
/// An end of an open spline joined to other geometry stays, as for [`Sketch::extend_spline`]:
|
||||
/// the spline would no longer end where it is joined.
|
||||
pub fn remove_spline_point(&mut self, ci: usize, p: usize) -> Result<bool> {
|
||||
let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?;
|
||||
let CurveKind::Spline { pts, periodic, .. } = &curve.kind else {
|
||||
return Err(SketchError::WrongKind(curve.id.clone(), "only a spline has points to remove".into()));
|
||||
};
|
||||
let (pts, periodic) = (pts.clone(), *periodic);
|
||||
if curve.link.is_some() {
|
||||
return Err(SketchError::Invalid("a projected spline follows its source; its points can't be removed".into()));
|
||||
}
|
||||
if self.freeform_offsets.iter().any(|o| o.output == curve.id) {
|
||||
return Err(SketchError::Invalid("an offset spline follows its source; break the offset association first".into()));
|
||||
}
|
||||
if self.freeform_offsets.iter().any(|o| o.source == curve.id) {
|
||||
return Err(SketchError::Invalid(
|
||||
"not supported yet: removing a point from a spline that has an offset; break the offset association first".into(),
|
||||
));
|
||||
}
|
||||
if self.patterns.iter().any(|pattern| pattern.contains(&curve.id)) {
|
||||
return Err(SketchError::Invalid("not supported yet: removing a point from a patterned spline".into()));
|
||||
}
|
||||
let at = match pts.iter().enumerate().filter(|(_, q)| **q == p).map(|(i, _)| i).collect::<Vec<_>>().as_slice() {
|
||||
[] => return Err(SketchError::Invalid(format!("that point isn't one of {}'s points", curve.id))),
|
||||
[at] => *at,
|
||||
_ => return Err(SketchError::Invalid("that point closes the spline; remove another one".into())),
|
||||
};
|
||||
let last = pts.len().saturating_sub(1);
|
||||
if periodic && (at == 0 || at == last) {
|
||||
return Err(SketchError::Invalid("a closed spline's closing point stays; remove another one".into()));
|
||||
}
|
||||
if pts.len() < if periodic { 5 } else { 3 } {
|
||||
return Err(SketchError::Invalid(format!("a spline keeps at least {} points", if periodic { 3 } else { 2 })));
|
||||
}
|
||||
if !periodic && (at == 0 || at == last) {
|
||||
let joined = self.curves.iter().enumerate().any(|(i, c)| i != ci && c.kind.uses(p))
|
||||
|| self.constraints.iter().any(|k| {
|
||||
let (points, curves) = k.kind.indices();
|
||||
points.contains(&p) || (curves.contains(&ci) && matches!(k.kind, ConstraintKind::Tangent { .. } | ConstraintKind::Smooth { .. }))
|
||||
});
|
||||
if joined {
|
||||
return Err(SketchError::Invalid(
|
||||
"that end of the spline is joined to other geometry or held by a constraint; remove those first".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut left = pts;
|
||||
left.remove(at);
|
||||
if periodic {
|
||||
let pos: Vec<Vec2> =
|
||||
left.iter().map(|i| self.point(*i).ok_or_else(|| SketchError::Unknown(format!("point {i}")))).collect::<Result<_>>()?;
|
||||
crate::periodic::validate_periodic_points(&pos)?;
|
||||
}
|
||||
if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) {
|
||||
*pts = left;
|
||||
}
|
||||
// The origin (point 0) is never removed.
|
||||
if p == 0 || self.point_used_by_curve(p) {
|
||||
return Ok(false);
|
||||
}
|
||||
self.keep_ties_through(&[p]);
|
||||
self.remove_points(&[p]);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Reverse spline `ci`'s direction: its last point becomes its first and the curve runs the
|
||||
/// other way along the same path. Its points are reversed in place, so every point, and every
|
||||
/// constraint on them and on the curve, stays. The shape doesn't change: a fit spline's chord
|
||||
|
||||
@@ -210,6 +210,27 @@ fn zero_distance_edits_preserve_dimension_rank() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A length dimension of zero still constrains the sketch: the two ends of the line meet, and
|
||||
/// the dimension holds them together instead of leaving a degree of freedom behind (#5505).
|
||||
#[test]
|
||||
fn zero_length_keeps_the_line_constrained() {
|
||||
for seed in [false, true] {
|
||||
seeded(seed, || {
|
||||
let mut sk = Sketch::new();
|
||||
let a = sk.add_point(v(0.0, 0.0), None).unwrap();
|
||||
let b = sk.add_point(v(10.0, 0.0), None).unwrap();
|
||||
let l = sk.add_line_pts(a, b, None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::Fix { p: a }, None).unwrap();
|
||||
let id = sk.add_constraint(ConstraintKind::Length { l, value: 0.0 }, None).unwrap();
|
||||
let report = solve(&mut sk);
|
||||
assert!(report.ok(), "{report:?}");
|
||||
assert_eq!(report.dof, 0, "a zero length holds the line's ends together: {report:?}");
|
||||
assert!(!report.redundant.contains(&id), "a zero length is not redundant: {report:?}");
|
||||
assert!(sk.point(b).unwrap().dist(v(0.0, 0.0)) < 1e-6, "{:?}", sk.point(b));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_constrained_reports_dof() {
|
||||
let mut sk = Sketch::new();
|
||||
@@ -1199,6 +1220,88 @@ fn a_spline_extends_to_a_new_end_unless_the_end_is_joined() {
|
||||
assert!(sk.extend_spline(s, v(-10.0, 5.0), true).is_err(), "already a point there");
|
||||
}
|
||||
|
||||
/// Where spline `s`'s points are, in order.
|
||||
fn spline_places(sk: &Sketch, s: usize) -> Vec<Vec2> {
|
||||
let CurveKind::Spline { pts, .. } = &sk.curves[s].kind else { panic!("{s} is no spline") };
|
||||
pts.iter().map(|i| sk.point(*i).unwrap()).collect()
|
||||
}
|
||||
|
||||
/// #10783: a spline gives up one of its points. The curve runs through the others, in order, and
|
||||
/// the point goes with the constraints on it; a point a line also ends at stays, for the line.
|
||||
#[test]
|
||||
fn a_point_removed_from_a_spline_goes_and_the_curve_keeps_the_others() {
|
||||
let mut sk = Sketch::new();
|
||||
let (pts, s) = wave_spline(&mut sk, false);
|
||||
let mut others = spline_places(&sk, s);
|
||||
let gone = others.remove(2);
|
||||
// A free point held on the one that goes: the constraint goes, the free point stays.
|
||||
let free = sk.add_point(gone, None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::Coincident { p: pts[2], q: free }, None).unwrap();
|
||||
let count = sk.points.len();
|
||||
assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true));
|
||||
assert_eq!(spline_places(&sk, s), others);
|
||||
for q in &others {
|
||||
assert!(off_curve(&sk, s, *q) < 1e-9, "the curve still runs through {q:?}");
|
||||
}
|
||||
assert!(matches!(sk.curves[s].kind, CurveKind::Spline { control: false, periodic: false, .. }));
|
||||
assert_eq!(sk.points.len(), count - 1, "the point went");
|
||||
assert!(sk.constraints.is_empty(), "the constraint on it went: {:?}", sk.constraints);
|
||||
// A free end goes too: the spline starts at the next point.
|
||||
let start = sk.curves[s].kind.ends().unwrap().0;
|
||||
assert_eq!(sk.remove_spline_point(s, start), Ok(true));
|
||||
others.remove(0);
|
||||
assert_eq!(spline_places(&sk, s), others);
|
||||
// An inner point a line also ends at stays, for the line.
|
||||
let CurveKind::Spline { pts: now, .. } = sk.curves[s].kind.clone() else { panic!() };
|
||||
let line = sk.add_line(others[1], v(40.0, 30.0), Some(now[1]), None, None).unwrap();
|
||||
assert_eq!(sk.remove_spline_point(s, now[1]), Ok(false));
|
||||
assert!(sk.curves[line].kind.uses(now[1]) && !sk.curves[s].kind.uses(now[1]));
|
||||
others.remove(1);
|
||||
assert_eq!(spline_places(&sk, s), others);
|
||||
// Two points are as few as a spline keeps.
|
||||
assert_eq!(others.len(), 2);
|
||||
let before = sk.clone();
|
||||
assert!(sk.remove_spline_point(s, sk.curves[s].kind.ends().unwrap().1).is_err());
|
||||
assert_eq!(sk, before, "a refused removal changes nothing");
|
||||
}
|
||||
|
||||
/// #10783: what a spline keeps: an end joined to a line or held by a constraint, a closed
|
||||
/// spline's closing point and its last three points. A control point spline gives up a point as a
|
||||
/// fit point spline does.
|
||||
#[test]
|
||||
fn a_spline_keeps_its_joined_ends_and_closing_point() {
|
||||
let mut sk = Sketch::new();
|
||||
let (pts, s) = wave_spline(&mut sk, false);
|
||||
let line = sk.add_line(sk.point(pts[4]).unwrap(), v(60.0, 0.0), Some(pts[4]), None, None).unwrap();
|
||||
let tied = sk.add_point(sk.point(pts[0]).unwrap(), None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::Coincident { p: pts[0], q: tied }, None).unwrap();
|
||||
let before = sk.clone();
|
||||
assert!(sk.remove_spline_point(s, pts[4]).is_err(), "a line ends there");
|
||||
assert!(sk.remove_spline_point(s, pts[0]).is_err(), "a constraint holds the start");
|
||||
assert!(sk.remove_spline_point(s, tied).is_err(), "not one of the spline's points");
|
||||
assert!(sk.remove_spline_point(line, pts[4]).is_err(), "a line has no spline points");
|
||||
assert_eq!(sk, before, "a refused removal changes nothing");
|
||||
|
||||
let mut sk = Sketch::new();
|
||||
let (pts, s) = wave_spline(&mut sk, true);
|
||||
assert!(sk.remove_spline_point(s, pts[0]).is_err(), "the closing point");
|
||||
assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true));
|
||||
assert_eq!(sk.remove_spline_point(s, pts[1]), Ok(true));
|
||||
let CurveKind::Spline { pts: now, periodic, .. } = sk.curves[s].kind.clone() else { panic!() };
|
||||
assert!(periodic);
|
||||
assert_eq!(now.len(), 4, "three points and the closing one: {now:?}");
|
||||
assert!(sk.remove_spline_point(s, now[1]).is_err(), "a closed spline keeps three points");
|
||||
sk.validate_periodic_splines().unwrap();
|
||||
|
||||
let mut sk = Sketch::new();
|
||||
let places = [v(0.0, 0.0), v(10.0, 10.0), v(20.0, -10.0), v(30.0, 0.0)];
|
||||
let cv: Vec<usize> = places.iter().map(|q| sk.add_point(*q, None).unwrap()).collect();
|
||||
let c = sk.add_curve(CurveKind::Spline { pts: cv.clone(), control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap();
|
||||
assert_eq!(sk.remove_spline_point(c, cv[1]), Ok(true));
|
||||
assert!(matches!(sk.curves[c].kind, CurveKind::Spline { control: true, .. }));
|
||||
assert_eq!(spline_places(&sk, c), vec![places[0], places[2], places[3]]);
|
||||
}
|
||||
|
||||
/// #755: a line drawn through a junction of a loop, but 2e-5 off it, still splits the loop. The
|
||||
/// junction lies on the loop's two curves only, so it cuts neither of them where the line
|
||||
/// crosses, and that crossing, next to the junction, was taken for one already cut there: the
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "solidcraft-testkit"
|
||||
description = "SolidCraft test tooling: deterministic mutations of valid files and the no-panic check run over them (a dev-dependency only)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of
|
||||
//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten
|
||||
//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and
|
||||
//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an
|
||||
//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a
|
||||
//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any
|
||||
//! panic, so a caught one on the desktop is a crash there.
|
||||
//!
|
||||
//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces.
|
||||
//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and
|
||||
//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a
|
||||
//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino
|
||||
//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests.
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A deterministic xorshift64 stream.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn new(seed: u64) -> Rng {
|
||||
Rng(seed | 1)
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
/// A value in `0..n` (0 when `n` is 0).
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
if n == 0 { 0 } else { (self.next() % n as u64) as usize }
|
||||
}
|
||||
}
|
||||
|
||||
/// Numbers a hostile file might hold in place of a real one.
|
||||
const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"];
|
||||
|
||||
/// Most truncations of one file (every length up to this, evenly spaced beyond).
|
||||
const MAX_TRUNCATIONS: usize = 1024;
|
||||
|
||||
/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number
|
||||
/// mutations (the file is UTF-8 text).
|
||||
pub fn mutations(good: &[u8], text: bool, seed: u64) -> Vec<Vec<u8>> {
|
||||
let mut out: Vec<Vec<u8>> = Vec::new();
|
||||
let n = good.len();
|
||||
let mut rng = Rng::new(seed);
|
||||
// Truncations: every length of a short file; of a long one, its first and last 64 lengths
|
||||
// (headers, final records) and evenly spaced ones between.
|
||||
if n <= MAX_TRUNCATIONS {
|
||||
out.extend((0..n).map(|k| good[..k].to_vec()));
|
||||
} else {
|
||||
let mut cuts: Vec<usize> = (0..64).chain(n - 64..n).collect();
|
||||
cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128)));
|
||||
cuts.sort_unstable();
|
||||
cuts.dedup();
|
||||
out.extend(cuts.into_iter().map(|k| good[..k].to_vec()));
|
||||
}
|
||||
if n == 0 {
|
||||
return out;
|
||||
}
|
||||
// Bytes flipped, zeroed and saturated at seeded places.
|
||||
for i in 0..384 {
|
||||
let at = rng.below(n);
|
||||
let mut b = good.to_vec();
|
||||
b[at] = match i % 3 {
|
||||
0 => b[at] ^ ((rng.next() >> 32) as u8 | 1),
|
||||
1 => 0x00,
|
||||
_ => 0xff,
|
||||
};
|
||||
out.push(b);
|
||||
}
|
||||
// Runs of bytes dropped, repeated and swapped with their neighbour.
|
||||
for _ in 0..96 {
|
||||
let at = rng.below(n);
|
||||
let len = 1 + rng.below(64.min(n - at));
|
||||
let end = at + len;
|
||||
let mut dropped = good[..at].to_vec();
|
||||
dropped.extend_from_slice(&good[end..]);
|
||||
out.push(dropped);
|
||||
let mut repeated = good[..end].to_vec();
|
||||
repeated.extend_from_slice(&good[at..]);
|
||||
out.push(repeated);
|
||||
if end + len <= n {
|
||||
let mut swapped = good[..at].to_vec();
|
||||
swapped.extend_from_slice(&good[end..end + len]);
|
||||
swapped.extend_from_slice(&good[at..end]);
|
||||
swapped.extend_from_slice(&good[end + len..]);
|
||||
out.push(swapped);
|
||||
}
|
||||
}
|
||||
// The whole file: with garbage after it, twice over, reversed.
|
||||
let mut tail = good.to_vec();
|
||||
tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8));
|
||||
out.push(tail);
|
||||
out.push([good, good].concat());
|
||||
out.push(good.iter().rev().copied().collect());
|
||||
if text && let Ok(s) = std::str::from_utf8(good) {
|
||||
out.extend(text_mutations(s, &mut rng));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies.
|
||||
fn text_mutations(s: &str, rng: &mut Rng) -> Vec<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
let lines: Vec<&str> = s.split_inclusive('\n').collect();
|
||||
let join = |v: &[&str]| v.concat().into_bytes();
|
||||
let picked: Vec<usize> = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() };
|
||||
for &i in &picked {
|
||||
let mut v = lines.clone();
|
||||
v.remove(i);
|
||||
out.push(join(&v));
|
||||
let mut v = lines.clone();
|
||||
v.insert(i, lines[i]);
|
||||
out.push(join(&v));
|
||||
if i + 1 < lines.len() {
|
||||
let mut v = lines.clone();
|
||||
v.swap(i, i + 1);
|
||||
out.push(join(&v));
|
||||
}
|
||||
}
|
||||
// A line in place of another (a block that inserts itself, a count where a coordinate was).
|
||||
for _ in 0..200.min(lines.len() * lines.len()) {
|
||||
let (i, j) = (rng.below(lines.len()), rng.below(lines.len()));
|
||||
let mut v = lines.clone();
|
||||
v[i] = lines[j];
|
||||
out.push(join(&v));
|
||||
}
|
||||
// A word in place of another of the file's own words: a renamed block, a swapped keyword, a
|
||||
// block that now inserts itself. Every pair in a small file, a sample in a large one.
|
||||
let words = word_spans(s);
|
||||
let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect();
|
||||
vocab.sort_unstable();
|
||||
vocab.dedup();
|
||||
let pairs = words.len().saturating_mul(vocab.len());
|
||||
let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes();
|
||||
if pairs <= 3000 {
|
||||
for &span in &words {
|
||||
for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) {
|
||||
out.push(swap(span, w));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _ in 0..400 {
|
||||
out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())]));
|
||||
}
|
||||
}
|
||||
// Numbers: each of up to 200 of them, in turn, becomes one of the liars.
|
||||
let numbers = number_spans(s);
|
||||
let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() };
|
||||
for (k, (a, b)) in chosen.into_iter().enumerate() {
|
||||
let liar = LIARS[k % LIARS.len()];
|
||||
out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes());
|
||||
}
|
||||
// Every number lying at once (two counts that are only harmless one at a time).
|
||||
let all = number_spans(s);
|
||||
for liar in LIARS {
|
||||
let mut t = String::with_capacity(s.len());
|
||||
let mut at = 0;
|
||||
for &(a, b) in &all {
|
||||
t.push_str(&s[at..a]);
|
||||
t.push_str(liar);
|
||||
at = b;
|
||||
}
|
||||
t.push_str(&s[at..]);
|
||||
out.push(t.into_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a
|
||||
/// letter).
|
||||
fn word_spans(s: &str) -> Vec<(usize, usize)> {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let a = i;
|
||||
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
|
||||
i += 1;
|
||||
}
|
||||
out.push((a, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent).
|
||||
fn number_spans(s: &str) -> Vec<(usize, usize)> {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit));
|
||||
let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_');
|
||||
if !starts || after_word {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let a = i;
|
||||
i += 1;
|
||||
while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) {
|
||||
if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out.push((a, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Panics on this thread so far, caught or not ([`count_panics`]).
|
||||
static PANICS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Count every panic per thread (tests run on several), then run the hook that was there.
|
||||
fn count_panics() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
PANICS.with(|p| p.set(p.get() + 1));
|
||||
previous(info);
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/// The time any one reader call may take on a mutated file (a debug build on a loaded machine:
|
||||
/// generous, but far below what unbounded work on a lying count would take).
|
||||
pub const BUDGET: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles,
|
||||
/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming
|
||||
/// the first case that breaks a rule.
|
||||
// Failing the calling test is this function's job; it only ever runs inside tests.
|
||||
#[allow(clippy::panic)]
|
||||
pub fn survives(what: &str, inputs: &[Vec<u8>], cap: usize, mut read: impl FnMut(&[u8]) -> Option<usize>) {
|
||||
count_panics();
|
||||
let mut slowest = (Duration::ZERO, 0);
|
||||
let mut read_ok = 0;
|
||||
for (i, input) in inputs.iter().enumerate() {
|
||||
let before = PANICS.with(std::cell::Cell::get);
|
||||
let t = Instant::now();
|
||||
let r = catch_unwind(AssertUnwindSafe(|| read(input)));
|
||||
let took = t.elapsed();
|
||||
let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned();
|
||||
let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) };
|
||||
let caught = PANICS.with(std::cell::Cell::get) - before;
|
||||
assert!(
|
||||
caught == 0,
|
||||
"{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}",
|
||||
input.len()
|
||||
);
|
||||
assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len());
|
||||
if let Some(count) = r {
|
||||
assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})");
|
||||
read_ok += 1;
|
||||
}
|
||||
slowest = slowest.max((took, i));
|
||||
}
|
||||
eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mutations_are_deterministic_and_cover_the_file() {
|
||||
let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n";
|
||||
let a = mutations(good, true, 7);
|
||||
assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases");
|
||||
assert_ne!(a, mutations(good, true, 8));
|
||||
assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing");
|
||||
assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar");
|
||||
assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]);
|
||||
// A long file: bounded truncations, kept to the first and last bytes and spaced between.
|
||||
let long = vec![b'a'; 100_000];
|
||||
let m = mutations(&long, false, 1);
|
||||
assert!(m.len() < 3000, "{} cases", m.len());
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,8 @@ impl AcpBackend {
|
||||
out.push(Event::TurnEnded { reason: "auth".into() });
|
||||
}
|
||||
out.push(Event::AuthRequired { methods: self.auth.clone() });
|
||||
} else if what == Pending::SetModel {
|
||||
out.push(Event::ModelRejected(message));
|
||||
} else if !config_error {
|
||||
if what == Pending::Prompt {
|
||||
out.push(Event::TurnEnded { reason: "error".into() });
|
||||
@@ -382,4 +384,26 @@ mod tests {
|
||||
assert!(matches!(events.as_slice(), [Event::ConfigOptionFinished { result: Ok(options), .. }] if options[0].current_value == "smart"));
|
||||
backend.shutdown(true);
|
||||
}
|
||||
|
||||
/// A refused model is the picker's business, not an error of the chat; signing in stays as it was.
|
||||
#[test]
|
||||
fn a_refused_model_is_reported_as_such() {
|
||||
let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };
|
||||
let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap();
|
||||
let mut events = Vec::new();
|
||||
backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events);
|
||||
backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events);
|
||||
events.clear();
|
||||
backend.set_model("zzz");
|
||||
backend.handle(Incoming::Reply { id: backend.next_id, result: Err((-32602, "no such model".into())) }, &mut events);
|
||||
assert!(matches!(events.as_slice(), [Event::ModelRejected(message)] if message == "no such model"), "{events:?}");
|
||||
events.clear();
|
||||
backend.set_model("fast");
|
||||
backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({})) }, &mut events);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
backend.set_model("zzz");
|
||||
backend.handle(Incoming::Reply { id: backend.next_id, result: Err((acp::AUTH_REQUIRED, "sign in".into())) }, &mut events);
|
||||
assert!(matches!(events.as_slice(), [Event::AuthRequired { .. }]), "{events:?}");
|
||||
backend.shutdown(true);
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ impl Kind {
|
||||
}
|
||||
|
||||
/// The wire protocol of an endpoint the user added.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Protocol {
|
||||
/// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak.
|
||||
#[default]
|
||||
@@ -303,9 +303,11 @@ pub struct ApiPreset {
|
||||
pub const OPENAI_PRESETS: &[ApiPreset] = &[
|
||||
ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" },
|
||||
ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" },
|
||||
ApiPreset { name: "OpenClaw", base_url: "http://localhost:18789/v1" },
|
||||
ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" },
|
||||
ApiPreset { name: "Mammouth AI", base_url: "https://api.mammouth.ai/v1" },
|
||||
ApiPreset { name: "OpenCode Go", base_url: "https://opencode.ai/zen/go/v1" },
|
||||
ApiPreset { name: "OpenRouter", base_url: "https://openrouter.ai/api/v1" },
|
||||
];
|
||||
|
||||
/// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls
|
||||
@@ -400,6 +402,18 @@ mod tests {
|
||||
assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1"));
|
||||
}
|
||||
|
||||
/// The first preset is the one an Add dialog opens with, and the one taken for Ollama.
|
||||
#[test]
|
||||
fn ollama_stays_the_first_preset_and_every_preset_can_take_a_key() {
|
||||
assert_eq!(OPENAI_PRESETS.first().map(|p| p.name), Some("Ollama"));
|
||||
assert_eq!(OPENAI_PRESETS.last().map(|p| p.name), Some("OpenRouter"));
|
||||
assert!(OPENAI_PRESETS.iter().any(|p| p.name == "OpenClaw"));
|
||||
for preset in OPENAI_PRESETS.iter().chain(ANTHROPIC_PRESETS) {
|
||||
assert_eq!(normalize_url(preset.base_url).as_deref(), Ok(preset.base_url), "{}", preset.name);
|
||||
assert!(key_safe_for(preset.base_url), "{}", preset.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_timeouts_default_to_300_s_and_stay_between_30_s_and_an_hour() {
|
||||
assert_eq!(AgentConfig::default().request_timeout_s, 300);
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::time::Duration;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::MODEL_LIST_CAP;
|
||||
use super::acp::ModelInfo;
|
||||
use super::agents::Protocol;
|
||||
use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus};
|
||||
@@ -22,6 +23,8 @@ use super::process::{AgentProcess, FromAgent, ProcessHandle};
|
||||
|
||||
/// Longest tool result handed back to the model.
|
||||
const MAX_TOOL_TEXT: usize = 20_000;
|
||||
/// Longest name kept for a listed model.
|
||||
const MODEL_NAME_CAP: usize = 256;
|
||||
/// Messages kept in the conversation (the system note stays).
|
||||
const MAX_HISTORY: usize = 240;
|
||||
/// Pictures of the view kept in the conversation. The whole history goes with every request
|
||||
@@ -795,15 +798,24 @@ impl Worker {
|
||||
}
|
||||
self.emit(Event::ToolsAvailable(!self.tools.is_empty()));
|
||||
self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true });
|
||||
// The endpoint's models for the picker; an endpoint that does not list them shows none.
|
||||
if let Ok(list) = self.model_list() {
|
||||
let mut available = list;
|
||||
if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) {
|
||||
available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() });
|
||||
// The endpoint's models for the picker. An endpoint that does not list them still shows the
|
||||
// configured model, and says why there are no others.
|
||||
let configured = ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() };
|
||||
let available = match self.model_list() {
|
||||
Ok(mut list) => {
|
||||
self.emit(Event::ModelsNote(None));
|
||||
if !self.cfg.model.is_empty() && !list.iter().any(|m| m.id == self.cfg.model) {
|
||||
list.insert(0, configured);
|
||||
}
|
||||
list
|
||||
}
|
||||
if !available.is_empty() {
|
||||
self.emit(Event::Models { current: self.cfg.model.clone(), available });
|
||||
Err(e) => {
|
||||
self.emit(Event::ModelsNote(Some(e)));
|
||||
if self.cfg.model.is_empty() { Vec::new() } else { vec![configured] }
|
||||
}
|
||||
};
|
||||
if !available.is_empty() {
|
||||
self.emit(Event::Models { current: self.cfg.model.clone(), available });
|
||||
}
|
||||
for cmd in cmds {
|
||||
match cmd {
|
||||
@@ -1628,7 +1640,7 @@ fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result<Vec<(String, S
|
||||
}
|
||||
|
||||
/// The endpoint's models for the picker. The Messages API has no models endpoint at every
|
||||
/// compatible provider (Qwen's has none), so a failure here simply leaves the picker empty.
|
||||
/// compatible provider (Qwen's has none), so a failure here leaves only the configured model.
|
||||
pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result<Vec<ModelInfo>, String> {
|
||||
let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 };
|
||||
let (status, bytes) = http(&req)?;
|
||||
@@ -1636,19 +1648,10 @@ pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) ->
|
||||
if status != 200 {
|
||||
return Err(http_error(status, &v));
|
||||
}
|
||||
Ok(v.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.take(500)
|
||||
.filter_map(|m| {
|
||||
let id = m.get("id").and_then(Value::as_str)?.to_string();
|
||||
let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone());
|
||||
Some(ModelInfo { id, name, description: String::new() })
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default())
|
||||
Ok(listed_models(&v, "display_name")?
|
||||
.into_iter()
|
||||
.map(|(id, name)| ModelInfo { name: name.unwrap_or_else(|| id.clone()), id, description: String::new() })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers
|
||||
@@ -1721,18 +1724,35 @@ fn tool_title(name: &str, args: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them.
|
||||
fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result<Vec<String>, String> {
|
||||
/// The ids of a `/models` body and the names the endpoint gives them (when not just the id), in
|
||||
/// its order. The body is the endpoint's to write: an id that could not be sent back is left out,
|
||||
/// and a name is cut. A body without a `data` array is no model list (a web page where the
|
||||
/// endpoint should be, say): an error, so the picker says so and asks again later.
|
||||
fn listed_models(body: &Value, name_key: &str) -> Result<Vec<(String, Option<String>)>, String> {
|
||||
let Some(entries) = body.get("data").and_then(Value::as_array) else {
|
||||
return Err(crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string());
|
||||
};
|
||||
Ok(entries
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let id = m.get("id").and_then(Value::as_str).filter(|id| super::model_id_valid(id))?;
|
||||
let name = m.get(name_key).and_then(Value::as_str).filter(|name| *name != id).map(|name| name.chars().take(MODEL_NAME_CAP).collect());
|
||||
Some((id.to_string(), name))
|
||||
})
|
||||
.take(MODEL_LIST_CAP)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `GET {base_url}/models`: the models, in the order the endpoint lists them. The picker shows the
|
||||
/// ids, so an endpoint's own name for a model is its description.
|
||||
fn model_entries(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result<Vec<ModelInfo>, String> {
|
||||
let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 };
|
||||
let (status, bytes) = http(&req)?;
|
||||
let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
|
||||
if status != 200 {
|
||||
return Err(http_error(status, &v));
|
||||
}
|
||||
Ok(v.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect())
|
||||
.unwrap_or_default())
|
||||
Ok(listed_models(&v, "name")?.into_iter().map(|(id, name)| ModelInfo { name: id.clone(), id, description: name.unwrap_or_default() }).collect())
|
||||
}
|
||||
|
||||
/// The endpoint's models for the picker.
|
||||
@@ -1744,7 +1764,7 @@ pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result<Ve
|
||||
}
|
||||
headers.push(("Authorization".to_string(), format!("Bearer {k}")));
|
||||
}
|
||||
Ok(model_ids(http, base_url, headers)?.into_iter().map(|id| ModelInfo { name: id.clone(), id, description: String::new() }).collect())
|
||||
model_entries(http, base_url, headers)
|
||||
}
|
||||
|
||||
/// Ask an endpoint for its models (Test connection): how many, and whether `model` is one.
|
||||
@@ -1756,10 +1776,9 @@ pub fn test_endpoint(http: &HttpFn, base_url: &str, key: Option<&str>, model: &s
|
||||
}
|
||||
headers.push(("Authorization".to_string(), format!("Bearer {k}")));
|
||||
}
|
||||
let ids = model_ids(http, base_url, headers)?;
|
||||
let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
let found = model.is_empty() || ids.contains(&model);
|
||||
Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)]))
|
||||
let models = model_entries(http, base_url, headers)?;
|
||||
let found = model.is_empty() || models.iter().any(|m| m.id == model);
|
||||
Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &models.len().to_string()), ("model", model)]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2059,6 +2078,7 @@ mod tests {
|
||||
let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") };
|
||||
assert_eq!(current, "local");
|
||||
assert_eq!(available.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["local", "big", "small"]);
|
||||
assert!(events.iter().any(|e| matches!(e, Event::ModelsNote(None))), "{events:?}");
|
||||
b.set_model("big");
|
||||
b.prompt(&[PromptPart::Text("hi".into())]);
|
||||
wait_for_seen(&seen);
|
||||
@@ -2561,6 +2581,87 @@ mod tests {
|
||||
assert!(tools[0].pointer("/parameters/additionalProperties").is_none(), "{tools:?}");
|
||||
}
|
||||
|
||||
/// An endpoint that refuses the listing still shows the configured model, and says why first.
|
||||
#[test]
|
||||
fn a_refused_listing_keeps_the_configured_model_and_says_why() {
|
||||
let http: HttpFn = Arc::new(|r: &HttpRequest| {
|
||||
assert_eq!(r.method, "GET");
|
||||
Ok((401, json!({"error": {"message": "No auth credentials"}}).to_string().into_bytes()))
|
||||
});
|
||||
let cfg = ApiConfig {
|
||||
name: "Test".into(),
|
||||
protocol: Protocol::OpenAi,
|
||||
base_url: "http://localhost:1/v1".into(),
|
||||
model: "local".into(),
|
||||
key: None,
|
||||
http,
|
||||
request_timeout_s: 300,
|
||||
reasoning_effort: String::new(),
|
||||
};
|
||||
let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };
|
||||
let mut b = ApiBackend::start(cfg, ctx).unwrap();
|
||||
let mut events = Vec::new();
|
||||
let start = std::time::Instant::now();
|
||||
while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) {
|
||||
events.extend(b.poll());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let listing: Vec<&Event> = events.iter().filter(|e| matches!(e, Event::Models { .. } | Event::ModelsNote(_))).collect();
|
||||
let [Event::ModelsNote(Some(note)), Event::Models { current, available }] = listing[..] else { panic!("{events:?}") };
|
||||
assert!(note.contains("No auth credentials"), "{note}");
|
||||
assert_eq!(current, "local");
|
||||
assert_eq!(available.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["local"]);
|
||||
b.shutdown(true);
|
||||
}
|
||||
|
||||
/// OpenRouter's shape: the name is the description, whatever else an entry holds is ignored, an
|
||||
/// id that could not be sent back is left out, and the list stays within its caps.
|
||||
#[test]
|
||||
fn a_listing_keeps_the_names_and_stays_within_its_caps() {
|
||||
let mut data = vec![
|
||||
json!({"id": "openai/gpt-x", "name": "OpenAI: GPT X", "description": "Long text", "supported_parameters": ["tools"]}),
|
||||
json!({"id": "same", "name": "same", "display_name": "Same One"}),
|
||||
json!({"id": "long", "name": "n".repeat(MODEL_NAME_CAP + 10), "display_name": "d".repeat(MODEL_NAME_CAP + 10)}),
|
||||
json!({"id": "x".repeat(super::super::MODEL_ID_CAP + 1)}),
|
||||
json!({"id": "bell\u{7}"}),
|
||||
json!({"id": ""}),
|
||||
json!({"id": 7}),
|
||||
json!({"name": "no id"}),
|
||||
];
|
||||
data.extend((0..MODEL_LIST_CAP + 500).map(|i| json!({"id": format!("m{i}")})));
|
||||
let body = json!({"data": data}).to_string().into_bytes();
|
||||
let http: HttpFn = Arc::new(move |_: &HttpRequest| Ok((200, body.clone())));
|
||||
let list = model_list(&http, "https://openrouter.ai/api/v1", None).unwrap();
|
||||
assert_eq!(list.len(), MODEL_LIST_CAP);
|
||||
let [first, same, long, next] = &list[..4] else { panic!("{}", list.len()) };
|
||||
assert_eq!((first.id.as_str(), first.name.as_str(), first.description.as_str()), ("openai/gpt-x", "openai/gpt-x", "OpenAI: GPT X"));
|
||||
assert_eq!((same.id.as_str(), same.description.as_str()), ("same", ""));
|
||||
assert_eq!(long.description.chars().count(), MODEL_NAME_CAP);
|
||||
assert_eq!(next.id, "m0");
|
||||
let list = anthropic_model_list(&http, "https://openrouter.ai/api/v1", None).unwrap();
|
||||
assert_eq!(list.len(), MODEL_LIST_CAP);
|
||||
let [first, same, long] = &list[..3] else { panic!("{}", list.len()) };
|
||||
assert_eq!(first.name, "openai/gpt-x");
|
||||
assert_eq!(same.name, "Same One");
|
||||
assert_eq!(long.name.chars().count(), MODEL_NAME_CAP);
|
||||
assert!(test_endpoint(&http, "https://openrouter.ai/api/v1", None, "openai/gpt-x").unwrap().contains(&MODEL_LIST_CAP.to_string()));
|
||||
}
|
||||
|
||||
/// A 200 that is no model list (a web page where the endpoint should be) is an error, so the
|
||||
/// picker says why and asks again later; a list with nothing in it is a list.
|
||||
#[test]
|
||||
fn an_answer_that_is_no_model_list_is_an_error() {
|
||||
let expected = crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string();
|
||||
let page: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"<!doctype html><html><body>Control UI</body></html>".to_vec())));
|
||||
assert_eq!(model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected);
|
||||
assert_eq!(anthropic_model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected);
|
||||
assert_eq!(test_endpoint(&page, "http://localhost:18789/v1", None, "").unwrap_err(), expected);
|
||||
let object: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"object": "list"}).to_string().into_bytes())));
|
||||
assert_eq!(model_list(&object, "http://localhost:18789/v1", None).unwrap_err(), expected);
|
||||
let empty: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"data": []}).to_string().into_bytes())));
|
||||
assert!(model_list(&empty, "http://localhost:18789/v1", None).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_arguments_are_an_object_or_an_error() {
|
||||
assert_eq!(tool_arguments(None), Ok(json!({})));
|
||||
|
||||
@@ -96,6 +96,11 @@ pub enum Event {
|
||||
current: String,
|
||||
available: Vec<super::acp::ModelInfo>,
|
||||
},
|
||||
/// Why an endpoint's models could not be listed (`None`: they could). It comes before the
|
||||
/// [`Event::Models`] of that listing, which then holds only the configured model.
|
||||
ModelsNote(Option<String>),
|
||||
/// The agent refused the model it was just sent, and says why.
|
||||
ModelRejected(String),
|
||||
ConfigOptions(Vec<ConfigOption>),
|
||||
ConfigOptionFinished {
|
||||
id: String,
|
||||
|
||||
@@ -50,7 +50,7 @@ use crate::{ControlRequest, SolveApp};
|
||||
use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus};
|
||||
|
||||
pub(crate) use panel::{left_inset, tool_space};
|
||||
pub use panel::{show, tip as panel_tip, toggle};
|
||||
pub use panel::{show, tip as panel_tip, toggle, toggle_shortcut};
|
||||
|
||||
/// Most entries kept in the conversation; older ones are dropped.
|
||||
const MAX_ITEMS: usize = 2000;
|
||||
@@ -316,6 +316,15 @@ impl Loading {
|
||||
}
|
||||
}
|
||||
|
||||
/// The model before an ACP agent was sent another, for when it refuses that one.
|
||||
struct ModelRevert {
|
||||
model: String,
|
||||
/// The one sent was not listed, so it leaves the list again.
|
||||
unlisted: bool,
|
||||
/// The model remembered for this agent.
|
||||
saved: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AgentChat {
|
||||
/// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A).
|
||||
@@ -402,6 +411,12 @@ pub struct AgentChat {
|
||||
/// The provider picked in the header when the models come from several providers (`None`: the
|
||||
/// current model's). It only narrows the model list; the agent keeps its model until one is chosen.
|
||||
pub model_provider: Option<String>,
|
||||
/// Why the running endpoint's models could not be listed, for the picker.
|
||||
pub models_note: Option<String>,
|
||||
/// What to put back if the running ACP agent refuses the model it was last sent.
|
||||
model_revert: Option<ModelRevert>,
|
||||
/// The typed model an agent's model option was sent, until it answers.
|
||||
typed_model: Option<String>,
|
||||
pub config_options: Option<Vec<acp::ConfigOption>>,
|
||||
pub config_pending: bool,
|
||||
/// An API endpoint's models, kept per endpoint (its base URL) for the next connection.
|
||||
@@ -484,6 +499,7 @@ impl AgentChat {
|
||||
self.model_provider = None;
|
||||
}
|
||||
self.config_pending = false;
|
||||
self.typed_model = None;
|
||||
}
|
||||
|
||||
fn apply_config_snapshot(&mut self, options: Vec<acp::ConfigOption>) {
|
||||
@@ -575,6 +591,11 @@ impl AgentChat {
|
||||
pictures.push(Picture::shared(Arc::new(png), "", true));
|
||||
}
|
||||
}
|
||||
/// Say that the agent refused a model, and in its words why.
|
||||
fn model_refused(&mut self, model: &str, error: &str) {
|
||||
let text = trf("ui.agent_chat_model_rejected", &[("model", model), ("error", error)]);
|
||||
self.notice(text.chars().take(MODELS_NOTE_CAP).collect::<String>(), true);
|
||||
}
|
||||
fn notice(&mut self, text: impl Into<String>, error: bool) {
|
||||
self.push(Item::Notice { text: text.into(), error });
|
||||
}
|
||||
@@ -718,11 +739,21 @@ impl AgentChat {
|
||||
}
|
||||
}
|
||||
Event::Models { current, available } => {
|
||||
self.model_revert = None;
|
||||
if self.config_options.is_none() && !available.is_empty() {
|
||||
if !self.running_endpoint.is_empty() {
|
||||
self.models_cache.insert(self.running_endpoint.clone(), available.clone());
|
||||
if self.models_note.is_some() {
|
||||
// The listing failed: last time's list stays, with the configured model in it.
|
||||
for model in available {
|
||||
if !self.models.iter().any(|m| m.id == model.id) {
|
||||
self.models.insert(0, model);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !self.running_endpoint.is_empty() {
|
||||
self.models_cache.insert(self.running_endpoint.clone(), available.clone());
|
||||
}
|
||||
self.models = available;
|
||||
}
|
||||
self.models = available;
|
||||
}
|
||||
if self.config_options.is_none() {
|
||||
if current != self.model {
|
||||
@@ -731,16 +762,36 @@ impl AgentChat {
|
||||
self.model = current;
|
||||
}
|
||||
}
|
||||
// Formatted here: the listing's thread has no language of its own.
|
||||
Event::ModelsNote(error) => {
|
||||
self.models_note =
|
||||
error.map(|error| trf("ui.agent_chat_models_failed", &[("error", &error)]).chars().take(MODELS_NOTE_CAP).collect());
|
||||
}
|
||||
Event::ModelRejected(message) => {
|
||||
let refused = self.model.clone();
|
||||
self.model_refused(&refused, &message);
|
||||
if let Some(revert) = self.model_revert.take() {
|
||||
if revert.unlisted {
|
||||
let refused = std::mem::take(&mut self.model);
|
||||
self.models.retain(|m| m.id != refused);
|
||||
}
|
||||
self.model = revert.model;
|
||||
self.model_provider = None;
|
||||
}
|
||||
}
|
||||
Event::ConfigOptions(options) => {
|
||||
self.apply_config_snapshot(options);
|
||||
}
|
||||
Event::ConfigOptionFinished { result, .. } => {
|
||||
self.config_pending = false;
|
||||
match result {
|
||||
Ok(options) => {
|
||||
let typed = self.typed_model.take();
|
||||
match (result, typed) {
|
||||
(Ok(options), _) => {
|
||||
self.apply_config_snapshot(options);
|
||||
}
|
||||
Err(message) => self.notice(message, true),
|
||||
// An agent's own words may not say what it refused ("Internal error").
|
||||
(Err(message), Some(model)) => self.model_refused(&model, &message),
|
||||
(Err(message), None) => self.notice(message, true),
|
||||
}
|
||||
}
|
||||
Event::AuthRequired { methods } => {
|
||||
@@ -856,7 +907,7 @@ pub(crate) fn assistant_mark(app: &SolveApp) -> AssistantMark {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn assistant_tip(mark: AssistantMark) -> String {
|
||||
pub(crate) fn assistant_tip(app: &SolveApp, mark: AssistantMark) -> String {
|
||||
let state = match mark {
|
||||
AssistantMark::Quiet => tr("ui.agent_chat_state_off").to_string(),
|
||||
AssistantMark::Ready => tr("ui.agent_chat_state_ready").to_string(),
|
||||
@@ -865,7 +916,11 @@ pub(crate) fn assistant_tip(mark: AssistantMark) -> String {
|
||||
AssistantMark::Stopped => tr("ui.agent_chat_state_exited").to_string(),
|
||||
AssistantMark::Waiting(count) => trf("ui.assistant_waiting", &[("count", &count.to_string())]),
|
||||
};
|
||||
format!("{} (Ctrl+Shift+A) — {state}", tr("ui.assistant"))
|
||||
let name = match crate::keymap::display_for(app, "ui.assistant") {
|
||||
Some(key) => format!("{} ({key})", tr("ui.assistant")),
|
||||
None => tr("ui.assistant").to_string(),
|
||||
};
|
||||
format!("{name} — {state}")
|
||||
}
|
||||
|
||||
/// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own
|
||||
@@ -986,6 +1041,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
chat.mode.clear();
|
||||
chat.models.clear();
|
||||
chat.model.clear();
|
||||
chat.models_note = None;
|
||||
chat.model_revert = None;
|
||||
chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() };
|
||||
// An endpoint's models from the last time, until the new list arrives.
|
||||
if let Some(list) = chat.models_cache.get(&chat.running_endpoint) {
|
||||
@@ -1352,6 +1409,7 @@ pub fn new_chat(app: &mut SolveApp) {
|
||||
chat.stopped = false;
|
||||
chat.ended = None;
|
||||
chat.discard_end = running;
|
||||
chat.model_revert = None;
|
||||
if matches!(chat.state(), State::Ready | State::Busy) {
|
||||
chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty());
|
||||
chat.state = Some(State::Starting);
|
||||
@@ -1880,6 +1938,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let refused = if matches!(e, Event::ModelRejected(_)) { app.agent_chat.model_revert.as_ref().map(|r| r.saved.clone()) } else { None };
|
||||
match app.agent_chat.on_event(e) {
|
||||
Some(Outcome::TurnEnd) => {
|
||||
end_turn(app);
|
||||
@@ -1895,10 +1954,19 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
if let Some(model) = confirmed_model {
|
||||
app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), model.clone());
|
||||
if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind == agents::Kind::Api) {
|
||||
if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind.is_api()) {
|
||||
a.model = model;
|
||||
}
|
||||
}
|
||||
match refused {
|
||||
Some(Some(saved)) => {
|
||||
app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), saved);
|
||||
}
|
||||
Some(None) => {
|
||||
app.preferences.agent_models.remove(&app.agent_chat.running_id);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if ready {
|
||||
apply_saved_model(app);
|
||||
}
|
||||
@@ -1919,6 +1987,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
settings::poll_capabilities(app, ctx);
|
||||
settings::poll_listing(app, ctx);
|
||||
connect_at_start(app, ctx);
|
||||
}
|
||||
pump_tools(app);
|
||||
@@ -1953,15 +2022,66 @@ pub fn set_model(app: &mut SolveApp, model: &str) {
|
||||
set_config_option(app, &id, model);
|
||||
return;
|
||||
}
|
||||
if !app.agent_chat.models.iter().any(|m| m.id == model) {
|
||||
return;
|
||||
if app.agent_chat.models.iter().any(|m| m.id == model) {
|
||||
send_model(app, model);
|
||||
}
|
||||
if let Some(b) = app.agent_chat.backend.as_mut() {
|
||||
}
|
||||
|
||||
/// Whether a model the agent did not list can be sent: an endpoint, an ACP agent with a model
|
||||
/// option, or a legacy ACP agent that listed models.
|
||||
pub fn custom_models_accepted(app: &SolveApp) -> bool {
|
||||
let chat = &app.agent_chat;
|
||||
if chat.backend.is_none() || !chat.state().running() {
|
||||
return false;
|
||||
}
|
||||
match chat.config_options.as_ref() {
|
||||
Some(options) => options.iter().any(|o| o.category == "model"),
|
||||
None => !chat.running_endpoint.is_empty() || !chat.models.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed model (the pickers' custom row). A listed id goes the usual way, others by the agent's
|
||||
/// kind; an agent that refuses it keeps its model and the chat says so. Returns whether it was sent.
|
||||
pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool {
|
||||
let model = text.trim();
|
||||
if !model_id_valid(model) || !custom_models_accepted(app) {
|
||||
return false;
|
||||
}
|
||||
let option = app.agent_chat.config_options.as_ref().and_then(|options| options.iter().find(|o| o.category == "model"));
|
||||
if let Some(id) = option.map(|o| o.id.clone()) {
|
||||
let sent = set_config_option_checked(app, &id, model, false);
|
||||
if sent {
|
||||
app.agent_chat.typed_model = Some(model.to_string());
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
send_model(app, model);
|
||||
true
|
||||
}
|
||||
|
||||
/// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is
|
||||
/// remembered for this agent; an endpoint also keeps it as its default model.
|
||||
fn send_model(app: &mut SolveApp, model: &str) {
|
||||
let agent = app.agent_chat.running_id.clone();
|
||||
let chat = &mut app.agent_chat;
|
||||
let unlisted = !chat.models.iter().any(|m| m.id == model);
|
||||
let entry = || acp::ModelInfo { id: model.to_string(), name: model.to_string(), description: String::new() };
|
||||
if unlisted {
|
||||
chat.models.insert(0, entry());
|
||||
chat.models.truncate(MODEL_LIST_CAP);
|
||||
}
|
||||
if chat.running_endpoint.is_empty() {
|
||||
chat.model_revert = Some(ModelRevert { model: chat.model.clone(), unlisted, saved: app.preferences.agent_models.get(&agent).cloned() });
|
||||
} else if unlisted {
|
||||
let cached = chat.models_cache.entry(chat.running_endpoint.clone()).or_default();
|
||||
cached.insert(0, entry());
|
||||
cached.truncate(MODEL_LIST_CAP);
|
||||
}
|
||||
if let Some(b) = chat.backend.as_mut() {
|
||||
b.set_model(model);
|
||||
}
|
||||
app.agent_chat.model = model.to_string();
|
||||
app.agent_chat.model_provider = None;
|
||||
let agent = app.agent_chat.running_id.clone();
|
||||
chat.model = model.to_string();
|
||||
chat.model_provider = None;
|
||||
if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) {
|
||||
a.model = model.to_string();
|
||||
}
|
||||
@@ -1984,10 +2104,22 @@ pub fn models_shown(app: &SolveApp) -> bool {
|
||||
|
||||
/// Longest provider name kept from an agent's model list.
|
||||
const PROVIDER_NAME_CAP: usize = 128;
|
||||
/// Most models kept for a picker, whether listed or typed.
|
||||
const MODEL_LIST_CAP: usize = 2000;
|
||||
/// Longest model id kept from a listing or sent to an agent.
|
||||
pub const MODEL_ID_CAP: usize = 256;
|
||||
/// Longest note about a listing that failed or a model the agent refused.
|
||||
const MODELS_NOTE_CAP: usize = 1024;
|
||||
|
||||
/// Whether a model id can go to an agent: not empty, not too long, no control characters.
|
||||
fn model_id_valid(id: &str) -> bool {
|
||||
!id.is_empty() && id.chars().count() <= MODEL_ID_CAP && !id.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
/// A model's provider and its name at that provider, when the agent says which provider serves it:
|
||||
/// a name `Provider · model` (Hermes, OpenCode) or a description `Provider: …` (up to a ` • `).
|
||||
/// `None`: the agent names no provider.
|
||||
/// a name `Provider · model` (Hermes, OpenCode), a description `Provider: …` (up to a ` • `), or
|
||||
/// an endpoint's listing whose id reads `vendor/model` and whose description (the endpoint's own
|
||||
/// name for it) reads `Vendor: Model` (OpenRouter). `None`: the agent names no provider.
|
||||
pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> {
|
||||
let cap = |s: &str| s.trim().chars().take(PROVIDER_NAME_CAP).collect::<String>();
|
||||
if let Some((provider, name)) = m.name.split_once(" · ")
|
||||
@@ -1996,9 +2128,48 @@ pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> {
|
||||
{
|
||||
return Some((cap(provider), name.trim().to_string()));
|
||||
}
|
||||
let rest = m.description.strip_prefix("Provider:")?;
|
||||
let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or("");
|
||||
(!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone()))
|
||||
if let Some(rest) = m.description.strip_prefix("Provider:") {
|
||||
let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or("");
|
||||
return (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone()));
|
||||
}
|
||||
let first_line = m.description.lines().next().unwrap_or("");
|
||||
if m.id.contains('/')
|
||||
&& let Some((vendor, name)) = first_line.split_once(": ")
|
||||
&& !vendor.trim().is_empty()
|
||||
&& vendor.chars().count() <= PROVIDER_NAME_CAP
|
||||
&& !name.trim().is_empty()
|
||||
{
|
||||
return Some((cap(vendor), name.trim().to_string()));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// How a picker shows `models`: each one's label, the group it folds under and its tooltip. With
|
||||
/// models from two or more providers the label is the name at the provider, the group the
|
||||
/// provider and the tooltip the id (or the description where the label already is the id);
|
||||
/// otherwise the name as it is, no group, and the description.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub fn model_rows(models: &[acp::ModelInfo]) -> Vec<(String, Option<String>, String)> {
|
||||
let mut providers: Vec<String> = Vec::new();
|
||||
for m in models {
|
||||
let p = provider_of(m);
|
||||
if !providers.contains(&p) {
|
||||
providers.push(p);
|
||||
}
|
||||
}
|
||||
let grouped = providers.len() >= 2;
|
||||
models
|
||||
.iter()
|
||||
.map(|m| {
|
||||
if grouped {
|
||||
let (provider, name) = model_provider(m).unwrap_or_else(|| (provider_of(m), m.name.clone()));
|
||||
let tip = if name == m.id { m.description.clone() } else { m.id.clone() };
|
||||
(name, Some(provider), tip)
|
||||
} else {
|
||||
(m.name.clone(), None, m.description.clone())
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The provider a model is listed under: its own, or "Other" when the agent names none.
|
||||
@@ -2051,8 +2222,17 @@ pub fn listed_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Show one provider's models in the model picker (the header's provider picker). The agent keeps
|
||||
/// its model until one of them is chosen. A provider the agent does not offer is ignored.
|
||||
/// Every model the header's picker lists, with its label, the group it folds under and its tooltip
|
||||
/// ([`model_rows`]).
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub fn grouped_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String, Option<String>, String)> {
|
||||
let rows = model_rows(&app.agent_chat.models);
|
||||
app.agent_chat.models.iter().cloned().zip(rows).map(|(m, (label, group, tip))| (m, label, group, tip)).collect()
|
||||
}
|
||||
|
||||
/// The provider whose group the header's model picker opens first (the control channel's
|
||||
/// `provider`). The agent keeps its model until one is chosen. A provider the agent does not offer
|
||||
/// is ignored.
|
||||
pub fn set_model_provider(app: &mut SolveApp, provider: &str) {
|
||||
if model_providers(app).iter().any(|(n, _)| n == provider) {
|
||||
app.agent_chat.model_provider = Some(provider.to_string());
|
||||
@@ -2079,19 +2259,25 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) {
|
||||
|
||||
/// Change a reported modern ACP configuration option; only acknowledged snapshots change state.
|
||||
pub fn set_config_option(app: &mut SolveApp, id: &str, value: &str) {
|
||||
set_config_option_checked(app, id, value, true);
|
||||
}
|
||||
|
||||
/// [`set_config_option`], with a choice the agent did not list (`listed_only` false: a typed
|
||||
/// model, which the agent may refuse). Returns whether it was sent.
|
||||
fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_only: bool) -> bool {
|
||||
let Some(option) = app.agent_chat.config_options.as_ref().and_then(|xs| xs.iter().find(|x| x.id == id)) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
if app.agent_chat.config_pending
|
||||
|| !matches!(app.agent_chat.state(), State::Ready | State::Busy)
|
||||
|| !option.options.iter().any(|x| x.value == value)
|
||||
|| (listed_only && !option.options.iter().any(|x| x.value == value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(b) = app.agent_chat.backend.as_mut() {
|
||||
b.set_config_option(id, value);
|
||||
app.agent_chat.config_pending = true;
|
||||
return false;
|
||||
}
|
||||
let Some(b) = app.agent_chat.backend.as_mut() else { return false };
|
||||
b.set_config_option(id, value);
|
||||
app.agent_chat.config_pending = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`,
|
||||
@@ -2186,7 +2372,11 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result<Val
|
||||
set_model_provider(app, m);
|
||||
}
|
||||
if let Some(m) = p.get("model").and_then(Value::as_str) {
|
||||
set_model(app, m);
|
||||
if app.agent_chat.models.iter().any(|x| x.id == m) {
|
||||
set_model(app, m);
|
||||
} else {
|
||||
set_custom_model(app, m);
|
||||
}
|
||||
}
|
||||
if let Some(option) = p.get("config_option") {
|
||||
let id = option.get("id").and_then(Value::as_str).ok_or("config_option.id must be a string")?;
|
||||
@@ -2313,7 +2503,7 @@ pub fn status(app: &SolveApp) -> Value {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let detection: Option<Value> = None;
|
||||
let pid = c.backend.as_ref().and_then(|b| b.pid());
|
||||
json!({
|
||||
let mut state = json!({
|
||||
"features": app.preferences.ai_features,
|
||||
"configOptions": c.config_options,
|
||||
"configPending": c.config_pending,
|
||||
@@ -2355,7 +2545,13 @@ pub fn status(app: &SolveApp) -> Value {
|
||||
"turnWarning": c.turn_warning,
|
||||
"detection": detection,
|
||||
"items": items,
|
||||
})
|
||||
});
|
||||
// Added apart: `json!` has reached the compiler's recursion limit above.
|
||||
if let Some(state) = state.as_object_mut() {
|
||||
state.insert("modelsNote".into(), json!(c.models_note));
|
||||
state.insert("customModels".into(), json!(custom_models_accepted(app)));
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -14,8 +14,34 @@ pub const MIN_WIDTH: f32 = 280.0;
|
||||
pub const MAX_WIDTH: f32 = 760.0;
|
||||
/// The folded panel's width.
|
||||
const STRIP: f32 = 30.0;
|
||||
/// The keyboard shortcut that shows and hides the panel (also from its own text field).
|
||||
pub const SHORTCUT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::A);
|
||||
/// Consume the configured toggle before CAD shortcuts, including in the chat's own window.
|
||||
/// Bare character keys remain text while a field owns the keyboard; chords still hide chat.
|
||||
pub fn toggle_shortcut(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if !shown(app) || crate::keymap::capturing(app) {
|
||||
return;
|
||||
}
|
||||
let keys = crate::keymap::keys(app, "ui.assistant");
|
||||
let typing = ctx.egui_wants_keyboard_input();
|
||||
let pressed = ctx.input_mut(|input| {
|
||||
let mut pressed = false;
|
||||
input.events.retain(|event| {
|
||||
if let egui::Event::Key { key, modifiers, pressed: true, repeat, .. } = event {
|
||||
if typing && !modifiers.command && !modifiers.ctrl && !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
if keys.contains(&crate::keymap::key_name(*key, *modifiers)) {
|
||||
pressed |= !repeat;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
pressed
|
||||
});
|
||||
if pressed {
|
||||
toggle(app);
|
||||
}
|
||||
}
|
||||
|
||||
fn panel_id(left: bool) -> Id {
|
||||
Id::new(if left { "sc_agent_chat_left" } else { "sc_agent_chat_right" })
|
||||
@@ -50,9 +76,11 @@ pub fn toggle(app: &mut SolveApp) {
|
||||
}
|
||||
|
||||
/// The tooltip of the chat's buttons: its name and shortcut.
|
||||
pub fn tip() -> String {
|
||||
let key = if cfg!(target_os = "macos") { "Cmd+Shift+A" } else { "Ctrl+Shift+A" };
|
||||
format!("{} ({key})", tr("ui.agent_chat"))
|
||||
pub fn tip(app: &SolveApp) -> String {
|
||||
match crate::keymap::display_for(app, "ui.assistant") {
|
||||
Some(key) => format!("{} ({key})", tr("ui.agent_chat")),
|
||||
None => tr("ui.agent_chat").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel, when the chat is turned on and open. Call before the central viewport is laid out.
|
||||
@@ -69,9 +97,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if !shown(app) {
|
||||
return;
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) {
|
||||
toggle(app);
|
||||
}
|
||||
// A window that isn't drawn this frame closes; the next one opens at the saved place.
|
||||
if !(app.agent_chat.open && app.preferences.agent_chat_popped) {
|
||||
app.agent_chat.window_placed = false;
|
||||
@@ -531,6 +556,11 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
// The side panel isn't drawn: its place no longer counts as "in the chat".
|
||||
app.agent_chat.panel_rect = None;
|
||||
ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("sc_agent_chat_window"), builder, |ui, class| {
|
||||
// Root/embedded inputs are handled by SolveApp::logic. A native chat window owns
|
||||
// its input and must see the toggle before its text editor can consume the chord.
|
||||
if class != egui::ViewportClass::EmbeddedWindow {
|
||||
toggle_shortcut(app, ui.ctx());
|
||||
}
|
||||
let t = Tokens::get();
|
||||
let frame = Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body);
|
||||
let r = Container::new(ui.ctx(), Surface::Viewport).central().frame(frame).show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, false)));
|
||||
@@ -555,9 +585,6 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if ctx.input(|i| !i.raw.hovered_files.is_empty()) {
|
||||
drop_hint(&ctx, r.response.rect);
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) {
|
||||
toggle(app);
|
||||
}
|
||||
// The whole window is the chat, so New chat works anywhere in it.
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&NEW_CHAT_SHORTCUT)) {
|
||||
request_new_chat(app);
|
||||
@@ -667,7 +694,7 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if app.preferences.agent_chat_side == "left" { [r.right_top(), r.right_bottom()] } else { [r.left_top(), r.left_bottom()] },
|
||||
t.primary_border(t.border),
|
||||
);
|
||||
let tip = format!("{} · {}", tip(), state.label());
|
||||
let tip = format!("{} · {}", tip(app), state.label());
|
||||
if resp.on_hover_text(tip).clicked() {
|
||||
app.preferences.agent_chat_minimized = false;
|
||||
}
|
||||
@@ -1044,11 +1071,8 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
);
|
||||
let models = !modern && models_shown(app);
|
||||
let providers = if models { model_providers(app) } else { Vec::new() };
|
||||
let w = (ui.available_width()
|
||||
- if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 }
|
||||
- if models { 146.0 } else { 0.0 }
|
||||
- if providers.is_empty() { 0.0 } else { 146.0 })
|
||||
.clamp(90.0, 260.0);
|
||||
let w = (ui.available_width() - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 })
|
||||
.clamp(90.0, 260.0);
|
||||
let mut picked: Option<String> = None;
|
||||
let mut add = false;
|
||||
let combo = ui
|
||||
@@ -1109,61 +1133,47 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
set_mode(app, &m);
|
||||
}
|
||||
}
|
||||
// Models from several providers: pick the provider first, then one of its models.
|
||||
if let Some(shown) = shown_provider(app).filter(|_| !providers.is_empty()) {
|
||||
let mut pick: Option<String> = None;
|
||||
let width = picker_width(ui, &shown);
|
||||
let r = ui
|
||||
.allocate_ui(vec2(width, t.control_height), |ui| {
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
ui_kit::dropdown_menu(ui, "sc_agent_provider", &shown, |ui| {
|
||||
for (name, count) in &providers {
|
||||
let row = ui_kit::list_picker(ui, &format!("provider:{name}"), name, *name == shown)
|
||||
.on_hover_text(trf("ui.agent_chat_provider_models", &[("count", &count.to_string())]));
|
||||
crate::scenario::publish_handle(&format!("agent_chat:provider:{name}"), row.rect.center());
|
||||
if row.clicked() {
|
||||
pick = Some(name.clone());
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.inner;
|
||||
crate::scenario::publish_rect("agent_chat:provider", r.rect);
|
||||
crate::scenario::publish_handle("agent_chat:provider", r.rect.center());
|
||||
r.on_hover_text(tr("ui.agent_chat_provider_tip"));
|
||||
if let Some(p) = pick {
|
||||
set_model_provider(app, &p);
|
||||
}
|
||||
}
|
||||
// The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some.
|
||||
if models {
|
||||
let list = listed_models(app);
|
||||
let cur = list.iter().find(|(m, _)| m.id == app.agent_chat.model).map_or_else(
|
||||
|| if providers.is_empty() { app.agent_chat.model.clone() } else { tr("ui.agent_chat_choose_model").to_string() },
|
||||
|(_, name)| name.clone(),
|
||||
);
|
||||
let mut pick: Option<String> = None;
|
||||
// Models from several providers fold under their providers inside the picker, the
|
||||
// current model's provider open.
|
||||
let list = grouped_models(app);
|
||||
let open = shown_provider(app).filter(|_| !providers.is_empty());
|
||||
let cur = list
|
||||
.iter()
|
||||
.find(|(m, _, _, _)| m.id == app.agent_chat.model)
|
||||
.map_or_else(|| app.agent_chat.model.clone(), |(_, name, _, _)| name.clone());
|
||||
let width = if providers.is_empty() { t.form_label_width } else { picker_width(ui, &cur) };
|
||||
let r = ui
|
||||
let choices: Vec<ui_kit::SearchChoice<'_>> =
|
||||
list.iter().map(|(m, name, group, tip)| ui_kit::SearchChoice { value: &m.id, label: name, tip, group: group.as_deref() }).collect();
|
||||
let custom = custom_models_accepted(app);
|
||||
let picker = ui
|
||||
.allocate_ui(vec2(width, t.control_height), |ui| {
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| {
|
||||
for (m, name) in &list {
|
||||
let row = ui_kit::list_picker(ui, &m.id, name, m.id == app.agent_chat.model);
|
||||
let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) };
|
||||
crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center());
|
||||
if row.clicked() {
|
||||
pick = Some(m.id.clone());
|
||||
}
|
||||
}
|
||||
})
|
||||
ui_kit::search_picker(
|
||||
ui,
|
||||
ui_kit::SearchPicker {
|
||||
id: "sc_agent_model",
|
||||
handles: "agent_chat:model",
|
||||
current: &cur,
|
||||
current_value: &app.agent_chat.model,
|
||||
hint: tr("ui.agent_chat_model_search"),
|
||||
choices: &choices,
|
||||
custom,
|
||||
note: app.agent_chat.models_note.as_deref(),
|
||||
open_group: open.as_deref(),
|
||||
enabled: true,
|
||||
},
|
||||
)
|
||||
})
|
||||
.inner;
|
||||
crate::scenario::publish_rect("agent_chat:model", r.rect);
|
||||
crate::scenario::publish_handle("agent_chat:model", r.rect.center());
|
||||
r.on_hover_text(tr("ui.agent_chat_model_tip"));
|
||||
if let Some(m) = pick {
|
||||
set_model(app, &m);
|
||||
picker.response.on_hover_text(tr("ui.agent_chat_model_tip"));
|
||||
match picker.inner {
|
||||
Some(ui_kit::Picked::Listed(m)) => set_model(app, &m),
|
||||
Some(ui_kit::Picked::Custom(m)) => {
|
||||
set_custom_model(app, &m);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1288,52 +1298,95 @@ fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOpti
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let mut picked = None;
|
||||
let response = ui
|
||||
.add_enabled_ui(!pending && !option.options.is_empty(), |ui| {
|
||||
ui.allocate_ui(vec2(width, t.control_height), |ui| {
|
||||
ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| {
|
||||
let mut previous_group: Option<&str> = None;
|
||||
for choice in &option.options {
|
||||
let group = choice.group.as_deref().filter(|g| !g.is_empty());
|
||||
if let Some(group) = group
|
||||
&& previous_group != Some(group)
|
||||
{
|
||||
ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group);
|
||||
}
|
||||
previous_group = group;
|
||||
let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value);
|
||||
let row = row.on_hover_text(
|
||||
[choice.name.as_str(), choice.description.as_str()]
|
||||
.into_iter()
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
crate::scenario::publish_handle(&format!("agent_chat:config:{}:{}", option.id, choice.value), row.rect.center());
|
||||
if option.category == "model" {
|
||||
crate::scenario::publish_handle(&format!("agent_chat:model:{}", choice.value), row.rect.center());
|
||||
}
|
||||
if row.clicked() {
|
||||
picked = Some(choice.value.clone());
|
||||
}
|
||||
}
|
||||
})
|
||||
let enabled = !pending && !option.options.is_empty();
|
||||
let handles = format!("agent_chat:config:{}", option.id);
|
||||
let response = if option.category == "model" {
|
||||
let choices: Vec<ui_kit::SearchChoice<'_>> = option
|
||||
.options
|
||||
.iter()
|
||||
.map(|choice| ui_kit::SearchChoice {
|
||||
value: &choice.value,
|
||||
label: &choice.name,
|
||||
tip: &choice.description,
|
||||
group: choice.group.as_deref(),
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner;
|
||||
crate::scenario::publish_handle(&format!("agent_chat:config:{}", option.id), response.rect.center());
|
||||
crate::scenario::publish_rect(&format!("agent_chat:config:{}", option.id), response.rect);
|
||||
if option.category == "model" {
|
||||
crate::scenario::publish_handle("agent_chat:model", response.rect.center());
|
||||
} else if option.category == "mode" {
|
||||
crate::scenario::publish_handle("agent_chat:mode", response.rect.center());
|
||||
}
|
||||
response
|
||||
.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, !pending && !option.options.is_empty(), format!("{name}: {selected}")));
|
||||
.collect();
|
||||
let id = format!("sc_agent_config:{}", option.id);
|
||||
let picker = ui
|
||||
.allocate_ui(vec2(width, t.control_height), |ui| {
|
||||
ui_kit::search_picker(
|
||||
ui,
|
||||
ui_kit::SearchPicker {
|
||||
id: &id,
|
||||
handles: &handles,
|
||||
current: &displayed,
|
||||
current_value: &option.current_value,
|
||||
hint: tr("ui.agent_chat_model_search"),
|
||||
choices: &choices,
|
||||
custom: true,
|
||||
note: None,
|
||||
open_group: None,
|
||||
enabled,
|
||||
},
|
||||
)
|
||||
})
|
||||
.inner;
|
||||
picked = picker.inner;
|
||||
// Under the names every kind of agent's model picker goes by.
|
||||
let rows = format!("{handles}:");
|
||||
for (name, at) in crate::scenario::handles(&rows) {
|
||||
if let Some(row) = name.strip_prefix(&rows) {
|
||||
crate::scenario::publish_handle(&format!("agent_chat:model:{row}"), at);
|
||||
}
|
||||
}
|
||||
crate::scenario::publish_target("agent_chat:model", picker.response.rect);
|
||||
picker.response
|
||||
} else {
|
||||
let response = ui
|
||||
.add_enabled_ui(enabled, |ui| {
|
||||
ui.allocate_ui(vec2(width, t.control_height), |ui| {
|
||||
ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| {
|
||||
let mut previous_group: Option<&str> = None;
|
||||
for choice in &option.options {
|
||||
let group = choice.group.as_deref().filter(|g| !g.is_empty());
|
||||
if let Some(group) = group
|
||||
&& previous_group != Some(group)
|
||||
{
|
||||
ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group);
|
||||
}
|
||||
previous_group = group;
|
||||
let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value);
|
||||
let row = row.on_hover_text(
|
||||
[choice.name.as_str(), choice.description.as_str()]
|
||||
.into_iter()
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
crate::scenario::publish_handle(&format!("{handles}:{}", choice.value), row.rect.center());
|
||||
if row.clicked() {
|
||||
picked = Some(ui_kit::Picked::Listed(choice.value.clone()));
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner;
|
||||
crate::scenario::publish_target(&handles, response.rect);
|
||||
if option.category == "mode" {
|
||||
crate::scenario::publish_handle("agent_chat:mode", response.rect.center());
|
||||
}
|
||||
response
|
||||
};
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, enabled, format!("{name}: {selected}")));
|
||||
response.on_hover_text(tip);
|
||||
if let Some(value) = picked {
|
||||
super::set_config_option(app, &option.id, &value);
|
||||
match picked {
|
||||
Some(ui_kit::Picked::Listed(value)) => super::set_config_option(app, &option.id, &value),
|
||||
Some(ui_kit::Picked::Custom(value)) => {
|
||||
super::set_custom_model(app, &value);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1560,6 +1613,49 @@ fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The visible **Copy message** button of one transcript message (#10675): copies the whole
|
||||
/// message — the prompt as entered, or the assistant's original Markdown — and nothing else.
|
||||
/// A streaming reply copies the stable text received so far, which is what `text` holds.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) {
|
||||
let b = ui_kit::button(ui, tr("ui.agent_chat_copy_message"), ui_kit::Button::Small);
|
||||
crate::scenario::publish_handle(&format!("agent_chat:copy:{n}"), b.rect.center());
|
||||
if b.clicked() {
|
||||
ui.ctx().copy_text(text.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// The right-click menu of one transcript message (#10675): the same single action as the
|
||||
/// visible button, on the whole message area, beside the composer's own text menu.
|
||||
/// The area stays hover-only so partial text selection keeps working, so the menu opens on a
|
||||
/// right-click released over it rather than on a click the response itself would report.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: &str) {
|
||||
crate::scenario::publish_rect(&format!("agent_chat:msg:{n}"), response.rect);
|
||||
let opened = ui
|
||||
.input(|i| i.pointer.button_released(egui::PointerButton::Secondary) && i.pointer.interact_pos().is_some_and(|p| response.rect.contains(p)));
|
||||
let mut copy = false;
|
||||
Container::new(ui.ctx(), Surface::Popup)
|
||||
.menu(response)
|
||||
.at_pointer_fixed()
|
||||
.frame(ui_kit::Menu::frame())
|
||||
.open_memory(if opened { Some(egui::SetOpenCommand::Bool(true)) } else { None })
|
||||
.show(|ui| {
|
||||
ui_kit::Menu::show(ui, crate::context_menu::LIST_W, |ui| {
|
||||
let item = ui_kit::MenuItem::new("copy_message", tr("ui.agent_chat_copy_message"), "copy");
|
||||
let row = item.show(ui);
|
||||
crate::scenario::publish_handle(&format!("agent_chat:copy_menu:{n}"), row.rect.center());
|
||||
if row.clicked() {
|
||||
copy = true;
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
if copy {
|
||||
ui.ctx().copy_text(text.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get();
|
||||
@@ -1573,6 +1669,9 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
for (n, item) in app.agent_chat.items.iter().enumerate() {
|
||||
match item {
|
||||
Item::User { text, image, pictures, context, files } => {
|
||||
// A picture-only prompt has no text to copy: no action rather than an empty copy (#10675).
|
||||
let copyable = !text.is_empty();
|
||||
let before = ui.cursor();
|
||||
ui_kit::assistant_bubble(ui, |ui| {
|
||||
if !text.is_empty() {
|
||||
ui.add(egui::Label::new(RichText::new(text).color(t.text)).selectable(true).wrap());
|
||||
@@ -1587,13 +1686,28 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
context_chips(ui, context, false);
|
||||
files_line(ui, files.iter().map(String::as_str));
|
||||
if copyable {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| copy_message_button(ui, n, text));
|
||||
}
|
||||
});
|
||||
if copyable {
|
||||
let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y);
|
||||
let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover());
|
||||
copy_message_menu(ui, &resp, n, text);
|
||||
}
|
||||
}
|
||||
Item::Agent { thought, text } => {
|
||||
if *thought {
|
||||
ui.add(egui::Label::new(RichText::new(text).italics().color(t.text_dim)).selectable(true).wrap());
|
||||
} else {
|
||||
let before = ui.cursor();
|
||||
ui_kit::assistant_prose(ui, |ui| super::markdown_view::show(ui, n, text));
|
||||
if !text.is_empty() {
|
||||
copy_message_button(ui, n, text);
|
||||
let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y);
|
||||
let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover());
|
||||
copy_message_menu(ui, &resp, n, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
Item::Tool { .. } => {
|
||||
@@ -2347,7 +2461,7 @@ mod tests {
|
||||
ui_kit::scope(ui, |ui| switcher(&mut app, ui));
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let rects: Vec<_> = ["switcher", "mode", "provider", "model"]
|
||||
let rects: Vec<_> = ["switcher", "mode", "model"]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let rect = crate::scenario::rect_of(&format!("agent_chat:{name}")).expect("picker retained");
|
||||
|
||||
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user