Merge remote-tracking branch 'origin/main' into feat/width-smooth-profile

# Conflicts:
#	docs/target-app-parity.md
This commit is contained in:
adambelis committed 2026-11-11 22:13:44 +01:00
commit a9fd0eb7c0
592 files changed
+54042 -2799

No files matched your search

+5 -1
View File
@@ -24,9 +24,13 @@ jobs:
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_PROFILE_TEST_DEBUG: "0"
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: "1.95"
- name: Fetch pinned and checksum-verified corpus
+4
View File
@@ -29,6 +29,10 @@ jobs:
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+4
View File
@@ -32,6 +32,10 @@ jobs:
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
Generated
+41 -35
View File
@@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1049,7 +1049,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1070,7 +1070,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"chrono",
"dunce",
@@ -1080,6 +1080,7 @@ dependencies = [
"image",
"log",
"plist",
"rustix 1.1.6",
"semver",
"serde",
"serde_json",
@@ -1096,7 +1097,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"flate2",
"serde",
@@ -6312,7 +6313,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -6358,7 +6359,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"crc32fast",
"flate2",
@@ -6369,14 +6370,14 @@ dependencies = [
[[package]]
name = "vectorcraft-apischema"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"serde_json",
]
[[package]]
name = "vectorcraft-brush"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -6388,7 +6389,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6404,7 +6405,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -6427,7 +6428,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -6439,7 +6440,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"chrono",
"hayro-ccitt",
@@ -6458,7 +6459,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6476,7 +6477,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"cfb",
"chrono",
@@ -6529,7 +6530,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"craft-pdf",
"encoding_rs",
@@ -6557,7 +6558,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"craft-vectorcraft-format",
"flate2",
@@ -6573,7 +6574,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -6585,16 +6586,17 @@ dependencies = [
[[package]]
name = "vectorcraft-js"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"chrono",
"getrandom 0.4.3",
"proptest",
"unicode-general-category",
]
[[package]]
name = "vectorcraft-mcp"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"log",
@@ -6613,7 +6615,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6627,7 +6629,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -6639,7 +6641,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"aes",
"chrono",
@@ -6652,6 +6654,8 @@ dependencies = [
"kurbo 0.13.1",
"log",
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
@@ -6671,7 +6675,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"craft-vectorcraft-format",
"image",
@@ -6685,11 +6689,12 @@ dependencies = [
"vectorcraft-geom",
"wasmi",
"wat",
"web-time",
]
[[package]]
name = "vectorcraft-render"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"flate2",
"gif 0.14.2",
@@ -6719,14 +6724,15 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"proptest",
"unicode-general-category",
]
[[package]]
name = "vectorcraft-svg"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"craft-docpath",
"flate2",
@@ -6753,7 +6759,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"fax",
"image",
@@ -6771,7 +6777,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"harfrust 0.13.3",
"icu_segmenter",
@@ -6792,7 +6798,7 @@ dependencies = [
[[package]]
name = "vectorcraft-three-d"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -6800,7 +6806,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6817,7 +6823,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6829,7 +6835,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"bytemuck",
"craft-keymap",
@@ -6867,7 +6873,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"craft-web-api",
"eframe",
@@ -7999,7 +8005,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.21.0"
version = "0.24.0"
dependencies = [
"serde_json",
]
+4 -4
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.21.0"
version = "0.24.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -14,16 +14,16 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
+11 -15
View File
@@ -1,21 +1,8 @@
# VectorCraft Roadmap
- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged.
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged.
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned.
- UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available.
- UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned.
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -35,7 +22,6 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
@@ -225,7 +211,13 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. |
| 2026-11-03 | minor | Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. |
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
@@ -262,10 +254,14 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. |
| 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. |
| 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. |
| 2026-10-13 | minor | PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. |
| 2026-10-13 | minor | PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. |
| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away |
| 2026-10-10 | minor | Added the essentials-user readiness score (~75%) |
| 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md |
| 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha |
| 2026-10-10 | major | Re-measured against Illustrator 2026 (30.x) from code counts, 71 open issues and public docs; stage set to alpha; moved the parity estimate, honest assessment and "Shipped so far" to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, milestones to `docs/roadmap.md`, the `.ai` scope to `docs/file-format-parity.md` |
| 2026-10-10 | minor | UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. |
| 2026-10-10 | minor | UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. |
| 2026-10-05 | major | Honest assessment by dimension and the prioritized gap list |
| 2026-10-02 | major | First 22-area weighted parity estimate |
+11 -4
View File
@@ -236,11 +236,13 @@ fn main() -> ExitCode {
}
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders
/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply
/// as they do there.
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
@@ -484,7 +486,12 @@ fn info(args: &[String]) -> Result<(), String> {
let base = h.call("engine.execute", json!({"command": "file.info", "params": {}}))?;
let doc = h.session.doc().map_err(|e| e.to_string())?.doc.clone();
let mut kinds: std::collections::BTreeMap<&'static str, usize> = Default::default();
doc.walk(|n| *kinds.entry(n.kind_label()).or_default() += 1);
// Ruler guides are not counted among the objects.
doc.walk(|n| {
if !n.is_ruler_guide() {
*kinds.entry(n.kind_label()).or_default() += 1;
}
});
let fonts = h.call("engine.execute", json!({"command": "text.fonts", "params": {}})).unwrap_or(Value::Null);
let artboards: Vec<Value> =
doc.artboards.iter().map(|a| json!({"name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()]})).collect();
+4
View File
@@ -456,11 +456,15 @@ fn main() -> std::process::ExitCode {
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
// Then Edit › Color Settings, which may name one of those profiles.
prefs_dir::attach_color_settings(&mut session);
// Before any plug-in loads: this launch's marker in the Launch folder next to the
// preferences (none for runs without preferences), and Safe Mode.
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
+16
View File
@@ -41,6 +41,14 @@ pub fn attach_profile_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Make Edit › Color Settings kept in `Color Settings.json` the active ones (#6335), and keep them
/// there when they change. After [`attach_profile_store`]: they may name a loaded profile.
pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir("Color Settings.json") {
session.attach_color_settings(path);
}
}
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
/// installed from now on there.
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
@@ -49,6 +57,14 @@ pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Have File › Scripts and `script.listInstalled` list the scripts of the `Scripts` folder. The
/// folder is only read: the user makes it.
pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Scripts") {
session.attach_scripts_dir(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
+4 -1
View File
@@ -583,7 +583,8 @@ impl<'a> Scene<'a> {
}
fn node(&mut self, n: &Node, force: bool) {
if let NodeKind::Layer { template: true, .. } = n.kind {
// Ruler guides draw on screen only: no entity and no loss warning.
if n.is_ruler_guide() || n.is_template() {
return;
}
// Symbols that hold symbols are written in full for each instance: depth alone doesn't
@@ -676,6 +677,8 @@ impl<'a> Scene<'a> {
self.node(c, false);
}
}
// Ruler guides draw on screen only.
NodeKind::RulerGuide { .. } => {}
}
self.opacity = opacity;
}
-1
View File
@@ -8,7 +8,6 @@ mod layers;
mod profile;
mod stroke_style;
pub(crate) use layers::HEAD_REACH;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
+3 -6
View File
@@ -139,10 +139,6 @@ impl StrokeGradientMode {
}
}
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
/// cut square a little behind its 4 × 4 box).
pub(crate) const HEAD_REACH: f64 = 4.6;
fn ten() -> f64 {
10.0
}
@@ -188,7 +184,8 @@ impl StrokeLayer {
}
}
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
(self.width * pct / 100.0).max(0.25)
@@ -197,7 +194,7 @@ impl StrokeLayer {
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+27 -1
View File
@@ -49,6 +49,10 @@ impl Dash {
}
}
/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Arrowhead {
@@ -94,13 +98,18 @@ pub enum Arrowhead {
Kite,
TriangleBar,
Oval,
/// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
}
impl Arrowhead {
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 40] = [
pub const ALL: [Arrowhead; 41] = [
Arrowhead::Arrow,
Arrowhead::ArrowOpen,
Arrowhead::LineArrow,
Arrowhead::Barbed,
Arrowhead::Concave,
Arrowhead::DoubleArrow,
@@ -141,6 +150,22 @@ impl Arrowhead {
Arrowhead::Fork,
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
_ => 2.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
match self {
@@ -184,6 +209,7 @@ impl Arrowhead {
Arrowhead::Kite => "Kite",
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
}
}
}
+10 -3
View File
@@ -292,7 +292,7 @@ fn profile_presets_round_trip_their_ids() {
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 40] = [
const SAVED: [&str; 41] = [
"Triangle",
"TriangleOpen",
"Circle",
@@ -333,6 +333,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
"Kite",
"TriangleBar",
"Oval",
"LineArrow",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
@@ -366,9 +367,15 @@ fn outset_covers_arrowheads() {
st.arrow_scale = (100.0, 200.0);
assert_eq!(st.arrow_weight(false), 4.0);
assert_eq!(st.arrow_weight(true), 8.0);
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
let reach = Arrowhead::Triangle.reach();
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0));
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
assert_eq!(a.outset(), reach * 8.0 + 2.0);
// The line arrow's arms spread twice as wide, so it reaches further from its tip.
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow);
assert!(Arrowhead::LineArrow.reach() > reach);
assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0);
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle);
a.stroke_mut().unwrap().width = 0.01;
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
}
+14 -7
View File
@@ -1,4 +1,4 @@
use super::{Arc, Deserialize, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip};
use super::{Arc, Deserialize, LayerColor, Node, NodeId, Rect, Serialize, SymbolBoxes, skip};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Artboard {
@@ -39,6 +39,18 @@ pub struct Artboard {
/// it behind the art ([`super::Document::with_artboard_fills`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<vectorcraft_color::Color>,
/// Guide label (Artboard Options): the color the canvas draws the artboard's own ruler guides
/// in (a guide whose [`super::Guide::artboard`] is this artboard's id), a [`LayerColor`] preset
/// or a custom RGB. None (No label) draws them in the guide color preference, as canvas guides
/// are. Only the canvas uses it: the paper, exports and print don't. Written only when set; a
/// file's preset outside [`super::LAYER_COLORS`] reads as no label.
#[serde(default, deserialize_with = "label_within_palette", skip_serializing_if = "Option::is_none")]
pub guide_label: Option<LayerColor>,
}
/// A file's guide label: a preset index outside [`super::LAYER_COLORS`] reads as no label.
fn label_within_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<LayerColor>, D::Error> {
Ok(Option::<LayerColor>::deserialize(d)?.filter(|c| !matches!(c, LayerColor::Preset(i) if usize::from(*i) >= super::LAYER_COLORS.len())))
}
/// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times
@@ -192,12 +204,7 @@ impl LockedArtboards<'_> {
/// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it
/// is new art?
pub fn overlaps(&self, n: &Node) -> bool {
if self.rects.is_empty()
|| !n.visible
|| n.is_layer()
|| matches!(n.kind, NodeKind::Path { guide: true, .. })
|| self.pattern_art.contains(&n.id)
{
if self.rects.is_empty() || !n.visible || n.is_layer() || n.is_guide() || self.pattern_art.contains(&n.id) {
return false;
}
if let Some(held) = self.held.borrow().get(&n.id) {
+44 -9
View File
@@ -123,6 +123,24 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
});
}
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
/// to `dropped`. Only layers holding one are copied.
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
}
if !holds(layer, out) {
return;
}
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let before = children.len();
children.retain(|c| !out(c));
*dropped += before - children.len();
for c in children.iter_mut().filter(|c| c.is_layer()) {
drop_guides(c, out, dropped);
}
}
impl Document {
/// Remove what a read file has beyond the canvas ([`MAX_COORD`], or not finite): objects
/// (see [`BeyondCanvas::objects`]; a top-level layer clipping by a path beyond it is emptied
@@ -141,8 +159,9 @@ impl Document {
for c in children.iter() {
layers_in(c, &mut layers);
}
gone.objects += children.len();
children.clear();
// The layer's own ruler guides stay; only its art goes.
gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count();
children.retain(|c| c.is_ruler_guide());
*clip = false;
}
} else {
@@ -161,9 +180,18 @@ impl Document {
self.retire_artboard_id(*id);
}
gone.artboards = removed.len();
let guides = self.guides.len();
self.guides.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
gone.guides = guides - self.guides.len();
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
let guides = self.saved_guides.len();
self.saved_guides
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
gone.guides = guides - self.saved_guides.len();
let out = |n: &Node| match n.kind {
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
_ => false,
};
for layer in &mut self.layers {
drop_guides(layer, &out, &mut gone.guides);
}
if !(in_range(self.ruler_origin.x) && in_range(self.ruler_origin.y)) {
self.ruler_origin = Point::ZERO;
gone.ruler_origin = true;
@@ -232,12 +260,18 @@ mod tests {
let far = Artboard { id: 9, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() };
d.artboards.push(far);
let guide = |pos: f64, artboard| Guide { artboard, ..Guide::new(false, pos) };
d.guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
d.saved_guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
d.ruler_origin = Point::new(1e17, 0.0);
// The same guides as nodes, as a document has them once read.
let mut nodes = d.clone();
assert_eq!(nodes.guides_into_nodes(), 4);
let gone = d.drop_beyond_canvas();
assert_eq!(gone, BeyondCanvas { objects: 0, artboards: 1, guides: 3, ruler_origin: true });
assert_eq!(d.artboards.len(), 1);
assert_eq!(d.guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
assert_eq!(d.saved_guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
assert_eq!(nodes.drop_beyond_canvas(), gone);
let left: Vec<(bool, f64, Option<u32>)> = nodes.ruler_guides().iter().map(|g| (g.vertical, g.pos, g.artboard)).collect();
assert_eq!(left, [(false, 50.0, None)]);
assert_eq!(d.ruler_origin, Point::ZERO);
assert_eq!(
gone.note().unwrap(),
@@ -310,7 +344,8 @@ mod tests {
let probe = Document::new(1.0, 1.0);
let sub = sublayer(&probe, 40, vec![rect(41, 1e17), rect(42, 0.0)], true);
let mut d = doc(vec![rect(10, 0.0), rect(11, 1e17), sub]);
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
d.saved_guides =
vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
d.assets = vec![
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
@@ -320,7 +355,7 @@ mod tests {
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
let gone = d.drop_beyond_canvas();
assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide");
assert_eq!(d.guides.len(), 1, "the guide of a layer that stays, stays");
assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays");
assert_eq!(d.saved_selections[0].objects, [NodeId(10)]);
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
+8 -1
View File
@@ -132,7 +132,7 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
out.push(a);
continue;
}
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
let clip = n.clips();
let (visible, locked) = (n.visible, n.locked);
let mut held = n.children_mut().map(std::mem::take).unwrap_or_default();
if clip && !held.is_empty() {
@@ -148,6 +148,13 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
// What it held takes its place, and is looked at in its turn.
left.extend(held.into_iter().rev());
}
// The ruler guides of a sublayer merged into its parent layer go above the parent's art, with
// the parent's own.
if out.iter().any(|c| c.is_ruler_guide()) {
let (guides, art): (Vec<_>, Vec<_>) = out.into_iter().partition(|c| c.is_ruler_guide());
out = art;
out.extend(guides);
}
*nodes = out;
true
}
+436 -15
View File
@@ -1,7 +1,7 @@
//! Persistent dimension recipes. Children are ordinary paths and type for all renderers/exporters.
use crate::{Document, NodeId, Unit};
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Vec2};
/// What a dimension measures.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -25,6 +25,17 @@ impl DimensionMode {
}
}
/// The direction a linear dimension measures in: along the line through its two points, or only
/// their horizontal or vertical distance.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Orientation {
#[default]
Aligned,
Horizontal,
Vertical,
}
/// The unit a length is labelled in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -295,6 +306,12 @@ pub enum DimensionSource {
a: Option<PointRef>,
b: Option<PointRef>,
vertex: Option<PointRef>,
/// The first point when it is not an anchor, held against a path's anchors.
#[serde(default, rename = "freeA", skip_serializing_if = "Option::is_none")]
free_a: Option<FreePoint>,
/// The second point when it is not an anchor.
#[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")]
free_b: Option<FreePoint>,
},
}
@@ -304,7 +321,11 @@ impl DimensionSource {
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
Self::Angle { first, second } => vec![first.node, second.node],
Self::Circle { node } => vec![*node],
Self::Points { a, b, vertex } => [a, b, vertex].into_iter().filter_map(|p| p.as_ref().map(|r| r.node)).collect(),
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
.into_iter()
.filter_map(|p| p.as_ref().map(|r| r.node))
.chain([free_a, free_b].into_iter().filter_map(|p| p.as_ref().map(FreePoint::node)))
.collect(),
}
}
/// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle
@@ -321,6 +342,34 @@ impl DimensionSource {
old.is_some() && old != counts(after)
})
}
/// The map that took the measured art from `before` to `after`, when every path it measures
/// went through one [`art_transform`] that reflects it (a negative determinant). None when a
/// measured path is unchanged, or when two of them went through different maps.
pub fn reflection(&self, before: &Document, after: &Document) -> Option<Affine> {
let mut first: Option<Affine> = None;
for id in self.nodes() {
let (old, new) = (before.node(id)?, after.node(id)?);
if std::ptr::eq(old, new) || old.path_data() == new.path_data() {
return None;
}
let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?;
match first {
None => first = Some(xf),
Some(f) => {
// The linear parts and the translations, each against its own size.
let (a, b) = (f.as_coeffs(), xf.as_coeffs());
let differ = |range: std::ops::Range<usize>, tolerance: f64| {
let size = a[range.clone()].iter().map(|c| c.abs()).fold(1.0, f64::max);
a[range.clone()].iter().zip(&b[range]).any(|(p, q)| (p - q).abs() > tolerance * size)
};
if differ(0..4, 1e-9) || differ(4..6, 1e-9) {
return None;
}
}
}
}
first
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -337,6 +386,235 @@ impl PointRef {
}
}
/// The point of an anchor that an [`AnchorWeight`] names: the anchor, or one of its handles.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AnchorPart {
#[default]
Point,
In,
Out,
}
impl AnchorPart {
fn of(self, a: &Anchor) -> Point {
match self {
Self::Point => a.p,
Self::In => a.h_in,
Self::Out => a.h_out,
}
}
}
/// One anchor's share of a [`FreePoint`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorWeight {
pub subpath: usize,
pub anchor: usize,
/// The anchor itself, or its in or out handle.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub part: AnchorPart,
pub weight: f64,
}
/// A measured point that is not an anchor (a point on a segment, or a point a Smart Guide gave),
/// linked to one path so that it moves with it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum FreePoint {
/// A point on a segment at curve parameter `t`, 0 at the segment's first anchor and 1 at its
/// last. It stays on the segment when the segment's anchors or handles are edited.
OnSegment { edge: SegmentRef, t: f64 },
/// A weighted sum of two or three anchors or handles of one path, the weights adding up to 1,
/// plus `across` times the vector from the first anchor to the second turned a quarter turn,
/// from (x, y) to (-y, x), so that a vector pointing right in the y-down document space
/// turns to point down (two anchors only). When the
/// path is moved, scaled, rotated, reflected or sheared, a point held by three moves with
/// it. A point held by two and `across`, beside a straight path, moves, turns and scales
/// uniformly with it, and a reflection or a non-uniform scale moves it as a half turn or a
/// uniform scale would.
Anchors {
node: NodeId,
anchors: Vec<AnchorWeight>,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
across: f64,
},
}
/// A point of a path: (subpath, anchor, part, place).
type PathPoint = (usize, usize, AnchorPart, Point);
/// Every anchor of `path` in order, each followed by its in and out handles when `handles` is set.
fn path_points(path: &PathData, handles: bool) -> impl Iterator<Item = PathPoint> + Clone + '_ {
let parts: &'static [AnchorPart] = if handles { &[AnchorPart::Point, AnchorPart::In, AnchorPart::Out] } else { &[AnchorPart::Point] };
path.subpaths
.iter()
.enumerate()
.flat_map(move |(si, sp)| sp.anchors.iter().enumerate().flat_map(move |(ai, a)| parts.iter().map(move |&part| (si, ai, part, part.of(a)))))
}
/// Three points that span `points`: the first, the one farthest from it, and the one farthest
/// from the line through those two. None when every point is in one place.
fn spanning(points: impl Iterator<Item = PathPoint> + Clone) -> Option<[PathPoint; 3]> {
let first = points.clone().next()?;
let o = first.3;
let second = points.clone().max_by(|x, y| x.3.distance(o).total_cmp(&y.3.distance(o)))?;
let u = second.3 - o;
let span = u.hypot();
if !span.is_finite() || span <= 1e-6 {
return None;
}
let third = points.max_by(|x, y| u.cross(x.3 - o).abs().total_cmp(&u.cross(y.3 - o).abs()))?;
Some([first, second, third])
}
/// The map that takes the anchors and handles of path `node` in `before` to where they are in
/// `after`, when one affine map does that for every one of them: the path was moved, scaled,
/// rotated, reflected or sheared as a whole. None when its anchors changed in number, moved in
/// another way, or lie on one line with all their handles, as on a straight line: a reflection
/// across a line through such a path puts its points where a turn can put them too.
pub fn art_transform(before: &Document, after: &Document, node: NodeId) -> Option<Affine> {
fitted(before, after, node, |_| true)
}
/// [`art_transform`] when the map passes `wanted`. The map is found from three points, and
/// `wanted` is asked before every other point is checked against it.
fn fitted(before: &Document, after: &Document, node: NodeId, wanted: impl Fn(&Affine) -> bool) -> Option<Affine> {
let (old, new) = (before.node(node)?.path_data()?, after.node(node)?.path_data()?);
if old.subpaths.len() != new.subpaths.len() || old.subpaths.iter().zip(&new.subpaths).any(|(o, n)| o.anchors.len() != n.anchors.len()) {
return None;
}
let [o, f, g] = spanning(path_points(old, true))?;
let place = |q: PathPoint| new.subpaths.get(q.0).and_then(|sp| sp.anchors.get(q.1)).map(|a| q.2.of(a));
let (o2, f2, g2) = (place(o)?, place(f)?, place(g)?);
let (u, v) = (f.3 - o.3, g.3 - o.3);
let span = u.hypot();
if u.cross(v).abs() <= 1e-9 * span * span {
return None;
}
let basis = |u: Vec2, v: Vec2| Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]);
let linear = basis(f2 - o2, g2 - o2) * basis(u, v).inverse();
let xf = Affine::translate(o2.to_vec2()) * linear * Affine::translate(-o.3.to_vec2());
if !xf.as_coeffs().iter().all(|c| c.is_finite()) || !wanted(&xf) {
return None;
}
let tolerance = 1e-6 * span.max(1.0);
path_points(old, true).zip(path_points(new, true)).all(|(o, n)| (xf * o.3).distance(n.3) <= tolerance).then_some(xf)
}
impl FreePoint {
/// Largest weight: a point far outside the anchors that hold it is not held.
const MAX_WEIGHT: f64 = 1e4;
/// The path it is linked to.
pub fn node(&self) -> NodeId {
match self {
Self::OnSegment { edge, .. } => edge.node,
Self::Anchors { node, .. } => *node,
}
}
/// `p` held against path `node`: three anchors that span the path; when all its anchors lie
/// on one line or in one place, as on an arch, three of its anchors and handles; when its
/// handles lie on that line too, or so nearly that the weights would be too large, two anchors
/// and `p`'s distance across that line. None when none of these holds `p`.
pub fn on(doc: &Document, node: NodeId, p: Point) -> Option<Self> {
let path = doc.node(node)?.path_data()?;
let weight = |(subpath, anchor, part, _): PathPoint, weight| AnchorWeight { subpath, anchor, part, weight };
for handles in [false, true] {
let Some([o, f, g]) = spanning(path_points(path, handles)) else { continue };
let (u, v) = (f.3 - o.3, g.3 - o.3);
let span = u.hypot();
let det = u.cross(v);
if det.abs() > 1e-9 * span * span {
let s = (p - o.3).cross(v) / det;
let t = u.cross(p - o.3) / det;
let anchors = vec![weight(o, 1.0 - s - t), weight(f, s), weight(g, t)];
// A nearly flat set of points gives weights too large to keep: the next fit is tried.
if let Some(held) = (Self::Anchors { node, anchors, across: 0.0 }).holding(doc, p, span) {
return Some(held);
}
}
}
// Every anchor and handle on one line, or nearly: along it from the first anchor, and across it.
let [o, f, _] = spanning(path_points(path, false))?;
let u = f.3 - o.3;
let span = u.hypot();
let (t, across) = ((p - o.3).dot(u) / (span * span), u.cross(p - o.3) / (span * span));
Self::Anchors { node, anchors: vec![weight(o, 1.0 - t), weight(f, t)], across }.holding(doc, p, span)
}
/// `p` on the segment `edge`, at the curve parameter of the segment's point nearest to it.
/// None when the segment is gone or `p` is not on it.
pub fn on_segment(doc: &Document, edge: &SegmentRef, p: Point) -> Option<Self> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
if edge.segment >= sp.segment_count() {
return None;
}
let (a, b) = edge.endpoints(doc)?;
let t = sp.segment(edge.segment).nearest(p, 1e-12).t;
Self::OnSegment { edge: edge.clone(), t }.holding(doc, p, a.distance(b))
}
/// Itself when it is [`Self::valid`] and puts the point at `p`, within a tolerance that grows
/// with `span`, the size of the art that holds it.
fn holding(self, doc: &Document, p: Point, span: f64) -> Option<Self> {
let at = self.position(doc)?;
(at.distance(p) <= 1e-6 * span.max(1.0)).then_some(self)
}
/// Whether its numbers can be used: a finite `t` from 0 to 1 on a segment; or two or three
/// weights that add up to 1, with `across` set only for two, each finite and at most
/// [`Self::MAX_WEIGHT`] across.
pub fn valid(&self) -> bool {
match self {
Self::OnSegment { t, .. } => (0.0..=1.0).contains(t),
Self::Anchors { anchors, across, .. } => {
(2..=3).contains(&anchors.len())
&& anchors.iter().all(|w| w.weight.is_finite() && w.weight.abs() <= Self::MAX_WEIGHT)
&& (anchors.iter().map(|w| w.weight).sum::<f64>() - 1.0).abs() <= 1e-9
&& across.is_finite()
&& across.abs() <= Self::MAX_WEIGHT
&& (*across == 0.0 || anchors.len() == 2)
}
}
}
/// Where the point is now. None when its segment or an anchor is gone or the point is not
/// [`Self::valid`].
pub fn position(&self, doc: &Document) -> Option<Point> {
use vectorcraft_geom::kurbo::ParamCurve;
if !self.valid() {
return None;
}
let at = match self {
Self::OnSegment { edge, t } => {
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
if edge.segment >= sp.segment_count() {
return None;
}
sp.segment(edge.segment).eval(*t)
}
Self::Anchors { node, anchors, across } => {
let path = doc.node(*node)?.path_data()?;
let place = |w: &AnchorWeight| path.subpaths.get(w.subpath).and_then(|sp| sp.anchors.get(w.anchor)).map(|a| w.part.of(a).to_vec2());
let mut at = Vec2::ZERO;
for w in anchors {
at += place(w)? * w.weight;
}
if *across != 0.0 {
let u = place(anchors.get(1)?)? - place(anchors.first()?)?;
at += Vec2::new(-u.y, u.x) * *across;
}
at.to_point()
}
};
(at.x.is_finite() && at.y.is_finite()).then_some(at)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Dimension {
@@ -349,6 +627,10 @@ pub struct Dimension {
pub length: f64,
pub options: DimensionOptions,
pub source: Option<DimensionSource>,
/// What a linear dimension measures: the distance between its points (aligned), or only its
/// horizontal or vertical part. Other modes ignore it.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub orientation: Orientation,
/// How far a linked dimension was moved on its own since the last refresh: the refresh turns
/// it into a new placement unless the measured art moved too.
#[serde(skip)]
@@ -359,16 +641,137 @@ impl Dimension {
/// A point on the drawn dimension line (linear), arc (angular) or radius line.
pub fn handle(&self) -> Point {
match self.mode {
DimensionMode::Linear => self.a.midpoint(self.b) + self.normal() * self.offset,
DimensionMode::Linear => {
let (a, b) = self.line_ends();
a.midpoint(b)
}
DimensionMode::Angular => self.vertex + self.bisector() * self.offset.abs().max(12.0),
DimensionMode::Radius | DimensionMode::Diameter => self.b,
}
}
/// The left normal of a → b.
/// The unit direction a linear dimension measures along: a → b when aligned, else the x axis
/// (horizontal) or the y axis (vertical), whichever way the points lie.
pub fn direction(&self) -> Vec2 {
match self.orientation {
Orientation::Horizontal if self.mode == DimensionMode::Linear => Vec2::new(1.0, 0.0),
Orientation::Vertical if self.mode == DimensionMode::Linear => Vec2::new(0.0, 1.0),
_ => {
let u = self.b - self.a;
let len = u.hypot();
if len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) }
}
}
}
/// The left normal of [`Self::direction`].
pub fn normal(&self) -> Vec2 {
let u = self.b - self.a;
let len = u.hypot();
if len > 1e-9 { Vec2::new(-u.y, u.x) / len } else { Vec2::new(0.0, 1.0) }
let u = self.direction();
Vec2::new(-u.y, u.x)
}
/// The length a linear dimension shows: the distance between its points along
/// [`Self::direction`].
pub fn measured(&self) -> f64 {
(self.b - self.a).dot(self.direction()).abs()
}
/// The two ends of a linear dimension's line: the measured points moved onto one line along
/// [`Self::direction`], `offset` from a along the normal.
pub fn line_ends(&self) -> (Point, Point) {
let (u, n) = (self.direction(), self.normal());
let a = self.a + n * self.offset;
(a, a + u * (self.b - self.a).dot(u))
}
/// A horizontal or vertical dimension whose points moved from `old`'s keeps its line as far
/// outside them as it was, on the same side: the gap is measured from the outermost point
/// on the line's side, so the line stays clear of art that turns. A line that lay between
/// the two points keeps its distance from the first point.
pub fn keep_gap(&mut self, old: &Dimension) {
if self.mode != DimensionMode::Linear
|| self.orientation == Orientation::Aligned
|| old.orientation != self.orientation
|| (self.a, self.b) == (old.a, old.b)
{
return;
}
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(old.a) + old.offset;
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let at = if line >= high {
new_high + (line - high)
} else if line <= low {
new_low + (line - low)
} else {
return;
};
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
}
/// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes
/// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far
/// past the outermost point on that side as `old`'s line was. A line that lay between the two
/// points is left as it is.
pub fn mirror_line(&mut self, old: &Dimension, image: Point) {
if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear {
return;
}
let gap = {
let n = old.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(old.a) + old.offset;
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
if line >= high {
line - high
} else if line <= low {
low - line
} else {
return;
}
};
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap };
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
}
/// Whether a linear dimension's line lies strictly between its two points along the normal.
fn line_between_points(&self) -> bool {
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(self.a) + self.offset;
across(self.a).min(across(self.b)) < line && line < across(self.a).max(across(self.b))
}
/// Makes a linear dimension measure in `orientation`, with its line on the side of the points
/// it was on. The line goes through the middle of the old line when that point lies outside
/// the two points along the new normal; otherwise it lies as far past the outermost point on
/// that side as the old line lay from its points.
pub fn set_orientation(&mut self, orientation: Orientation) {
if self.mode != DimensionMode::Linear || self.orientation == orientation {
self.orientation = orientation;
return;
}
let (handle, gap) = (self.handle(), self.offset.abs());
self.orientation = orientation;
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let h = across(handle);
let at = if h >= high || h <= low {
h
} else if 2.0 * h >= low + high {
high + gap
} else {
low - gap
};
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
self.length = self.measured();
}
fn bisector(&self) -> Vec2 {
let start = (self.a - self.vertex).atan2();
@@ -397,28 +800,46 @@ impl Dimension {
self.moved = Some((xf * at) - at + self.moved.unwrap_or_default());
return;
}
// A horizontal or vertical dimension keeps measuring along its axis, between the points
// where they now are, and its line goes through where the transform puts it. When that
// puts the line between the points (a quarter turn), the line keeps its gap from them.
let before = (self.mode == DimensionMode::Linear && self.orientation != Orientation::Aligned).then(|| (self.clone(), xf * self.handle()));
self.a = xf * self.a;
self.b = xf * self.b;
self.vertex = xf * self.vertex;
if let Some((old, p)) = before {
let offset = (p - self.a).dot(self.normal());
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
if self.line_between_points() && !old.line_between_points() {
self.keep_gap(&old);
}
}
if self.mode == DimensionMode::Linear {
self.length = self.a.distance(self.b);
self.length = self.measured();
}
}
pub fn resolve(&mut self, doc: &Document) -> Result<(), String> {
match &self.source {
Some(DimensionSource::Points { a, b, vertex }) => {
for (reference, point) in [(a, &mut self.a), (b, &mut self.b), (vertex, &mut self.vertex)] {
if let Some(r) = reference {
*point = r.position(doc).ok_or("Measured anchor no longer exists")?;
Some(DimensionSource::Points { a, b, vertex, free_a, free_b }) => {
for (reference, free, point) in [(a, free_a, &mut self.a), (b, free_b, &mut self.b), (vertex, &None, &mut self.vertex)] {
match (reference, free) {
// An end is an anchor or a free point, never both.
(Some(_), Some(_)) => return Err("Invalid measured point".into()),
(Some(r), None) => *point = r.position(doc).ok_or("Measured anchor no longer exists")?,
(None, Some(f)) if !f.valid() => return Err("Invalid measured point".into()),
(None, Some(f)) => *point = f.position(doc).ok_or("Measured anchor no longer exists")?,
(None, None) => {}
}
}
self.length = self.a.distance(self.b);
self.length = if self.mode == DimensionMode::Linear { self.measured() } else { self.a.distance(self.b) };
}
Some(DimensionSource::Segment { edge }) => {
let (a, b) = edge.endpoints(doc).ok_or("Measured segment no longer exists")?;
self.a = a;
self.b = b;
self.length = a.distance(b);
self.length = self.measured();
}
Some(DimensionSource::Angle { first, second }) => {
for edge in [first, second] {
@@ -486,7 +907,7 @@ impl Dimension {
DimensionMode::Angular => self.angle().abs().to_degrees(),
DimensionMode::Radius => self.a.distance(self.b),
DimensionMode::Diameter => self.a.distance(self.b) * 2.0,
DimensionMode::Linear => self.a.distance(self.b),
DimensionMode::Linear => self.measured(),
};
self.options.label(value, self.mode == DimensionMode::Angular)
}
+34 -10
View File
@@ -10,7 +10,7 @@ use super::{
impl Document {
/// Is everything but the layers the same in `other`, as the next version of the document after
/// an edit of its art? The id counter and the id index are left out, and art outside the layers
/// an edit of its art? The id counter and the caches are left out, and art outside the layers
/// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it
/// doesn't change: quick for every frame of an animation.
pub fn same_outside_layers(&self, other: &Self) -> bool {
@@ -38,7 +38,7 @@ impl Document {
text_threads,
symbols,
graph_designs,
guides,
saved_guides,
views,
saved_selections,
variables,
@@ -75,7 +75,9 @@ impl Document {
dimensions,
retired_artboard_id: _,
opened_artboard: _,
units_from_file: _,
index: _,
guide_cache: _,
} = self;
*version == other.version
&& *title == other.title
@@ -97,7 +99,7 @@ impl Document {
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& graph_designs.len() == other.graph_designs.len()
&& graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& *guides == other.guides
&& *saved_guides == other.saved_guides
&& *views == other.views
&& *saved_selections == other.saved_selections
&& *variables == other.variables
@@ -208,6 +210,7 @@ impl Document {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
}],
layers: vec![],
swatches: swatches.into(),
@@ -219,7 +222,7 @@ impl Document {
text_threads: vec![],
symbols: vec![],
graph_designs: vec![],
guides: vec![],
saved_guides: vec![],
views: vec![],
saved_selections: Default::default(),
variables: Default::default(),
@@ -256,7 +259,9 @@ impl Document {
dimensions: false,
retired_artboard_id: Default::default(),
opened_artboard: None,
units_from_file: false,
index: Default::default(),
guide_cache: Default::default(),
};
let id = d.alloc_id();
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
@@ -498,11 +503,13 @@ impl Document {
}
}
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top).
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]).
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
let id = node.id;
self.check_ruler_guide_place(&node, parent)?;
let ch = self.children_mut(parent)?;
let i = index.min(ch.len());
let i = Node::insert_index(ch, index, &node);
ch.insert(i, Arc::new(node));
Ok(id)
}
@@ -519,20 +526,33 @@ impl Document {
Ok(ch.remove(idx))
}
/// Move a node to `parent` at `index` (index measured after removal).
/// Move a node to `parent` at `index` (index measured after removal), clamped as
/// [`Document::insert`] clamps it.
pub fn move_node(&mut self, id: NodeId, parent: Option<NodeId>, index: usize) -> Result<(), DocError> {
if let Some(p) = parent
&& self.ancestry(p).is_some_and(|a| a.contains(&id))
{
return Err(DocError::Invalid("cannot move an object into itself".into()));
}
if let Some(n) = self.node(id) {
self.check_ruler_guide_place(n, parent)?;
}
let n = self.remove(id)?;
let ch = self.children_mut(parent)?;
let i = index.min(ch.len());
let i = Node::insert_index(ch, index, &n);
ch.insert(i, n);
Ok(())
}
/// An error when `n` is a ruler guide and `parent` is not a layer or sublayer: a ruler guide is
/// always a direct child of one ([`NodeKind::RulerGuide`]).
fn check_ruler_guide_place(&self, n: &Node, parent: Option<NodeId>) -> Result<(), DocError> {
if n.is_ruler_guide() && !parent.and_then(|p| self.node(p)).is_some_and(Node::is_layer) {
return Err(DocError::Invalid("a ruler guide goes only directly in a layer or sublayer".into()));
}
Ok(())
}
/// Position of `id` within its parent: (parent, index, sibling count).
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
let parent = self.parent_of(id);
@@ -736,7 +756,7 @@ impl Document {
for c in n.children().into_iter().flatten() {
if c.is_layer() {
objects(c, out);
} else {
} else if !c.is_ruler_guide() {
out.insert(c.id);
}
}
@@ -754,7 +774,8 @@ impl Document {
}
/// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else
/// the group or other object around it right inside a layer. None for a layer or sublayer.
/// the group or other object around it right inside a layer. None for a layer, a sublayer or a
/// ruler guide.
pub fn layer_object(&self, id: NodeId) -> Option<&Node> {
self.layer_object_at(&self.index_path(id)?)
}
@@ -765,6 +786,9 @@ impl Document {
let mut nodes = &self.layers;
for &i in path {
let n = nodes.get(i)?;
if n.is_ruler_guide() {
return None;
}
if !n.is_layer() {
return Some(n.as_ref());
}
+7 -3
View File
@@ -56,9 +56,12 @@ impl Document {
if self.saved_selections.is_empty() {
return;
}
// A saved selection names objects; ruler guides are not among them.
let mut ids = std::collections::HashSet::new();
self.walk(|n| {
ids.insert(n.id);
if !n.is_ruler_guide() {
ids.insert(n.id);
}
});
let mut kept: Vec<SavedSelection> = vec![];
for s in std::mem::take(&mut self.saved_selections) {
@@ -101,12 +104,13 @@ impl Document {
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
/// anything other than a layer is left alone.
/// anything other than a layer is left alone. Ruler guides on the layer stay in the document
/// ([`Self::remove_edit_layer`]).
pub fn drop_edit_modes(&mut self) {
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
for id in layers.into_iter().flatten() {
if self.node(id).is_some_and(Node::is_layer) {
let _ = self.remove(id);
let _ = self.remove_edit_layer(id);
}
}
}
+398 -87
View File
@@ -1,6 +1,8 @@
use super::document_ext::free_id;
use super::guides::Guide;
use super::limits::MAX_NEXT_ID;
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
use std::collections::{BTreeMap, HashSet};
impl Document {
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
@@ -151,7 +153,7 @@ impl Document {
rest.iter().any(|m| has(m, s, inside, true))
}
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)),
NodeKind::Path { guide: true, .. } => false,
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => false,
_ => art_box_meets(c, s, rect, exact),
}
}
@@ -171,6 +173,195 @@ impl Document {
art
}
/// Put the ruler guide nodes a file holds where ruler guides go: directly in a layer or
/// sublayer, above its art. A ruler guide below art in a layer moves up to the layer's other
/// guides, keeping their order. A ruler guide anywhere else (at the top level, in a group or
/// another object, in opacity-mask art, in a symbol, a graph design or a pattern) is removed.
/// Returns how many were removed.
pub fn tidy_ruler_guides(&mut self) -> usize {
let mut gone = self.layers.len();
self.layers.retain(|l| !l.is_ruler_guide());
gone -= self.layers.len();
for l in &mut self.layers {
if layer_untidy(l) {
gone += tidy_layer(Arc::make_mut(l));
}
}
let others = self
.symbols
.iter_mut()
.map(|s| &mut s.art)
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in others {
if root.is_ruler_guide() {
*root = Arc::new(Node::group(root.id, vec![]));
gone += 1;
} else if any_guide(root) {
gone += drop_guides_below(Arc::make_mut(root));
}
}
gone
}
/// Make the saved ruler guides (read from a file: [`Document::guides_to_saved`]'s list) into
/// [`NodeKind::RulerGuide`] nodes, each at the top of its layer, in list order. A guide on a
/// layer or sublayer the document has goes on it; one on no layer, or on a layer that is gone,
/// goes on the top visible, unlocked layer ([`Self::default_layer`]), or on a new "Layer 1"
/// when there is none. A guide keeps its saved id when no other node, slice or guide has it,
/// and its name, lock and visibility. The saved list is emptied, so running this again does
/// nothing. Returns how many guides became nodes.
pub fn guides_into_nodes(&mut self) -> usize {
let saved = std::mem::take(&mut self.saved_guides);
if saved.is_empty() {
return 0;
}
let mut used = HashSet::new();
self.walk(|n| {
used.insert(n.id);
});
used.extend(self.slices.iter().map(|s| s.id));
used.extend(self.assets.iter().map(|a| NodeId(a.id)));
let kept: Vec<Option<NodeId>> = saved.iter().map(|g| g.id.filter(|id| id.0 > 0 && id.0 < MAX_NEXT_ID && used.insert(*id))).collect();
if let Some(max) = kept.iter().flatten().map(|id| id.0).max() {
self.raise_next_id(max.saturating_add(1));
}
let mut home = None;
// The guides of each layer, in list order.
let mut by_layer: BTreeMap<NodeId, Vec<Arc<Node>>> = BTreeMap::new();
let mut order = vec![];
for (g, id) in saved.iter().zip(kept) {
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
Some(l) => l,
None => match home {
Some(h) => h,
None => {
let h = self.default_layer().unwrap_or_else(|| self.add_layer(None));
home = Some(h);
h
}
},
};
let id = id.unwrap_or_else(|| self.alloc_id());
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
n.name = g.name.clone();
n.locked = g.locked;
n.visible = !g.hidden;
if !by_layer.contains_key(&layer) {
order.push(layer);
}
by_layer.entry(layer).or_default().push(Arc::new(n));
}
for layer in order {
let guides = by_layer.remove(&layer).unwrap_or_default();
if let Ok(ch) = self.children_mut(Some(layer)) {
ch.extend(guides);
}
}
saved.len()
}
/// Take the ruler guide nodes out of the layers and put them in the saved list, by ascending
/// id, each naming its layer, after any entries not yet made into nodes: the form a file keeps
/// them in, readable by versions from before ruler guides were nodes. For saving a copy of
/// the document; [`Self::guides_into_nodes`] reverses it.
pub fn guides_to_saved(&mut self) {
let guides = self.ruler_guides();
if guides.is_empty() {
return;
}
for l in &mut self.layers {
if l.holds_ruler_guides() {
Arc::make_mut(l).strip_ruler_guides();
}
}
self.saved_guides.extend(guides);
}
/// Every ruler guide, by ascending id, with the layer or sublayer it is on, its id, name and
/// its own lock and visibility. A guide's place in this list is its index in the guide
/// commands.
pub fn ruler_guides(&self) -> Vec<Guide> {
if let Some(listed) = self.guide_cache.get(&self.layers) {
return listed.as_ref().clone();
}
fn visit(layer: &Node, out: &mut Vec<Guide>) {
for c in layer.children().into_iter().flatten() {
if let Some(g) = guide_of(c, layer.id) {
out.push(g);
} else if c.is_layer() {
visit(c, out);
}
}
}
let mut out = vec![];
for l in &self.layers {
visit(l, &mut out);
}
out.sort_by_key(|g| g.id);
self.guide_cache.set(&self.layers, &out);
out
}
/// Ruler guide `id`, as [`Self::ruler_guides`] lists it. None when `id` is not a ruler guide
/// on a layer.
pub fn ruler_guide(&self, id: NodeId) -> Option<Guide> {
let layer = self.parent_of(id)?;
guide_of(self.node(id)?, layer)
}
/// Change ruler guide `id` with `f` (its line, its artboard; the layer, id, name, lock and
/// visibility fields are not read back). Returns false when `id` is not a ruler guide.
pub fn edit_ruler_guide(&mut self, id: NodeId, f: impl FnOnce(&mut Guide)) -> bool {
let Some(mut g) = self.ruler_guide(id) else { return false };
f(&mut g);
let Some(n) = self.node_mut(id) else { return false };
n.kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard };
true
}
/// Add ruler guide `g` as a node with a new id at the top of its layer: `g.layer` when the
/// document has that layer or sublayer, else the top visible, unlocked layer
/// ([`Self::default_layer`]), or a new "Layer 1" when there is none. Its name, lock and
/// visibility come from `g`. Returns the new id.
pub fn add_ruler_guide(&mut self, g: &Guide) -> NodeId {
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
Some(l) => l,
None => self.default_layer().unwrap_or_else(|| self.add_layer(None)),
};
let id = self.alloc_id();
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
n.name = g.name.clone();
n.locked = g.locked;
n.visible = !g.hidden;
if let Ok(ch) = self.children_mut(Some(layer)) {
ch.push(Arc::new(n));
}
id
}
/// Remove node `id`, the temporary layer of opacity-mask, symbol or pattern editing, keeping the
/// ruler guides on it and on its sublayers: they go to the top of the top visible, unlocked
/// layer left ([`Self::default_layer`]), or of a new "Layer 1" when no layer is left, where a
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
if !layer.holds_ruler_guides() {
return Ok(layer);
}
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
Arc::make_mut(&mut layer).strip_ruler_guides();
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
}
/// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its
/// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose
/// artboard is gone.
@@ -179,79 +370,39 @@ impl Document {
Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })
}
/// The ruler guide node `g` names, if this document has it.
fn guide_node(&self, g: &Guide) -> Option<NodeId> {
g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide))
}
/// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has.
fn guide_layer(&self, g: &Guide) -> Option<NodeId> {
g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer))
}
/// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is
/// visible? A guide whose layer is gone shows as one on no layer.
/// Is ruler guide `g` shown: its node, and the layers it is on, visible? A guide that is not a
/// node of this document shows unless hidden itself or on a hidden layer.
pub fn guide_shown(&self, g: &Guide) -> bool {
self.guide_layer(g).is_none_or(|l| self.is_visible(l))
}
/// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked?
pub fn guide_editable(&self, g: &Guide) -> bool {
self.guide_layer(g).is_none_or(|l| self.is_editable(l))
}
/// Put the ruler guides on no layer this document has (from files saved before guides had
/// layers, or of layers merged into `layer`) on layer `layer`. Returns how many.
pub fn rehome_guides(&mut self, layer: NodeId) -> usize {
let lost: Vec<bool> = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect();
let mut n = 0;
for (g, lost) in self.guides.iter_mut().zip(lost) {
if lost {
g.layer = Some(layer);
n += 1;
}
match self.guide_node(g) {
Some(id) => self.is_visible(id),
None => !g.hidden && self.guide_layer(g).is_none_or(|l| self.is_visible(l)),
}
n
}
/// Put the ruler guides on no layer (from files saved before guides had layers), or on one that
/// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many.
pub fn adopt_guides(&mut self) -> usize {
self.default_layer().map_or(0, |home| self.rehome_guides(home))
/// Can ruler guide `g` be picked, moved and deleted: shown, and neither it nor its layers
/// locked?
pub fn guide_editable(&self, g: &Guide) -> bool {
match self.guide_node(g) {
Some(id) => self.is_editable(id),
None => !g.hidden && !g.locked && self.guide_layer(g).is_none_or(|l| self.is_editable(l)),
}
}
/// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in
/// step. Guides on no layer stay. Returns how many went.
pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize {
let gone: Vec<bool> = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect();
self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false))
}
/// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made
/// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies
/// the objects on it. Returns how many.
pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize {
let layers = |n: &Node| {
let mut out = vec![];
n.walk(&mut |c| {
if c.is_layer() {
out.push(c.id);
}
});
out
};
let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect();
let copies: Vec<Guide> = self
.guides
.iter()
.filter_map(|g| {
let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1;
Some(Guide { layer: Some(to), ..g.clone() })
})
.collect();
let n = copies.len();
self.guides.extend(copies);
n
}
/// The ruler guides on layer `layer` (not its sublayers'), by index.
pub fn guides_on(&self, layer: NodeId) -> impl Iterator<Item = (usize, &Guide)> + '_ {
self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer))
/// The ruler guides directly on layer `layer` (not its sublayers'), by ascending id.
pub fn guides_on(&self, layer: NodeId) -> Vec<Guide> {
let mut out: Vec<Guide> = self.children(Some(layer)).into_iter().flatten().filter_map(|c| guide_of(c, layer)).collect();
out.sort_by_key(|g| g.id);
out
}
/// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)?
@@ -260,45 +411,86 @@ impl Document {
self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol)
}
/// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their
/// place among the rest (the selected art stays selected). Returns how many went.
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize {
let kept: Vec<bool> = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect();
// Where each kept guide ends up.
let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0);
for k in &kept {
to.push(k.then_some(n));
n += usize::from(*k);
/// Keep the ruler guides `keep` accepts, deleting the others; `sel` forgets the deleted ones
/// (the selected art stays selected). Returns how many went.
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(&Guide) -> bool) -> usize {
let gone: HashSet<NodeId> = self.ruler_guides().into_iter().filter(|g| !keep(g)).filter_map(|g| g.id).collect();
if gone.is_empty() {
return 0;
}
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
}
if !holds(layer, gone) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
for c in ch.iter_mut().filter(|c| c.is_layer()) {
drop(c, gone);
}
}
for l in &mut self.layers {
drop(l, &gone);
}
sel.guides.retain(|id| !gone.contains(id));
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
sel.key_guide = None;
}
gone.len()
}
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
/// position).
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn holds(n: &Node, id: u32) -> bool {
n.is_layer()
&& n.children().is_some_and(|ch| {
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
})
}
if !holds(layer, id) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for c in ch.iter_mut() {
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
} else if c.is_layer() {
visit(c, id, f);
}
}
}
for l in &mut self.layers {
visit(l, id, f);
}
sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect();
sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten());
let before = self.guides.len();
let mut flags = kept.into_iter();
self.guides.retain(|_| flags.next().unwrap_or(true));
before - self.guides.len()
}
/// Move the guides of artboard `id` by `d` (along with their artboard).
pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) {
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
*g = g.moved(d);
}
self.edit_artboard_guides(id, &mut |vertical, pos| *pos += if vertical { d.x } else { d.y });
}
/// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork
/// with Artboard).
pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) {
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y };
}
self.edit_artboard_guides(id, &mut |vertical, pos| {
*pos = if vertical { (xf * Point::new(*pos, 0.0)).x } else { (xf * Point::new(0.0, *pos)).y };
});
}
/// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their
/// artboard).
/// artboard), each on its guide's layer with a new id.
pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) {
let copies: Vec<Guide> =
self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
self.guides.extend(copies);
self.ruler_guides().into_iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
for g in &copies {
self.add_ruler_guide(g);
}
}
/// An id for a new artboard: one no artboard has, above the ids given out before and the ids of
@@ -367,3 +559,122 @@ impl Document {
n
}
}
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
fn any_guide(n: &Node) -> bool {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
any
}
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_guides_below(n: &mut Node) -> usize {
let mut gone = drop_mask_guides(n);
if let Some(ch) = n.children_mut() {
let before = ch.len();
ch.retain(|c| !c.is_ruler_guide());
gone += before - ch.len();
for c in ch.iter_mut().filter(|c| any_guide(c)) {
gone += drop_guides_below(Arc::make_mut(c));
}
}
gone
}
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
/// becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node) -> usize {
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
if mask.art.is_ruler_guide() {
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
1
} else if any_guide(&mask.art) {
drop_guides_below(Arc::make_mut(&mut mask.art))
} else {
0
}
}
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
/// in one of its sublayers?
fn layer_untidy(l: &Node) -> bool {
let Some(ch) = l.children() else { return false };
let start = Node::guide_run_start(ch);
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
}
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
fn tidy_layer(l: &mut Node) -> usize {
let mut gone = drop_mask_guides(l);
let Some(ch) = l.children_mut() else { return gone };
for c in ch.iter_mut() {
if c.is_layer() {
if layer_untidy(c) {
gone += tidy_layer(Arc::make_mut(c));
}
} else if !c.is_ruler_guide() && any_guide(c) {
gone += drop_guides_below(Arc::make_mut(c));
}
}
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
*ch = art;
ch.extend(guides);
}
gone
}
/// Node `n`, on layer `layer`, as a [`Guide`] value, if it is a ruler guide.
fn guide_of(n: &Node, layer: NodeId) -> Option<Guide> {
let NodeKind::RulerGuide { vertical, pos, artboard } = n.kind else { return None };
Some(Guide { vertical, pos, artboard, layer: Some(layer), id: Some(n.id), name: n.name.clone(), locked: n.locked, hidden: !n.visible })
}
/// The list [`Document::ruler_guides`] last made, with weak pointers to the top-level layers it was
/// made from. While a weak pointer to a layer's allocation is held, nothing else can be at that
/// address, and the layer can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
/// moves it), so any edit inside a layer, and any layer added, removed or replaced, gives a list of
/// layers the cache does not match. Clones of a document share the cached list.
#[derive(Default)]
pub(crate) struct GuideCache(std::sync::RwLock<Option<Listed>>);
/// The top-level layers a guide list was made from, and the list.
type Listed = (Vec<std::sync::Weak<Node>>, Arc<Vec<Guide>>);
impl GuideCache {
/// The cached list, when it was made from `layers`.
fn get(&self, layers: &[Arc<Node>]) -> Option<Arc<Vec<Guide>>> {
let g = self.0.read().ok()?;
let (from, listed) = g.as_ref()?;
let same = from.len() == layers.len() && from.iter().zip(layers).all(|(w, l)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(l)));
same.then(|| listed.clone())
}
/// Keep `listed`, made from `layers`.
fn set(&self, layers: &[Arc<Node>], listed: &[Guide]) {
if let Ok(mut g) = self.0.write() {
*g = Some((layers.iter().map(Arc::downgrade).collect(), Arc::new(listed.to_vec())));
}
}
}
impl Clone for GuideCache {
fn clone(&self) -> Self {
GuideCache(std::sync::RwLock::new(self.0.read().ok().and_then(|g| g.clone())))
}
}
/// A cache, not document content: two documents are equal whatever their caches hold.
impl PartialEq for GuideCache {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl std::fmt::Debug for GuideCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("GuideCache")
}
}
+24 -4
View File
@@ -136,9 +136,11 @@ impl crate::Document {
}
}
/// The character style a graph's labels keep through regeneration once formatted (Format the text in graphs): the
/// value axis numbers, the category labels (category axis, radar spokes, pie names) and the legend labels (beside or
/// across the top, or in pie wedges). `None` draws the default 9 pt black.
/// The character style and anti-aliasing method a graph's labels keep through regeneration once formatted (Format
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
/// label's alignment.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LabelStyles {
@@ -148,6 +150,22 @@ pub struct LabelStyles {
pub categories: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub values_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_para: Option<crate::ParaStyle>,
/// The anti-aliasing method the value axis numbers keep once set (Character panel › Anti-aliasing Method).
/// `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub values_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The anti-aliasing method the category labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_anti_alias: Option<crate::text::TypeAntiAlias>,
}
impl LabelStyles {
@@ -525,7 +543,9 @@ impl GraphSpec {
out.push_str(&field(self.categories.get(i).map(String::as_str).unwrap_or_default(), true));
out.push(',');
}
out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(","));
let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(",");
// A lone blank value would be an empty line, which readers skip; a quoted empty field keeps the row.
out.push_str(if line.is_empty() && !labelled { "\"\"" } else { &line });
out.push('\n');
}
out
+17 -1
View File
@@ -1,5 +1,8 @@
use super::{Deserialize, NodeId, Serialize, Vec2};
/// A ruler guide as a value: an entry of the saved `guides` list, or a ruler guide node of a
/// document as [`crate::Document::ruler_guides`] lists it. In a document, ruler guides are
/// [`crate::NodeKind::RulerGuide`] nodes on their layers.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Guide {
/// true = vertical guide at `pos` (x), false = horizontal at `pos` (y).
@@ -14,12 +17,25 @@ pub struct Guide {
/// from before guides had layers, and from files that don't say), always there.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer: Option<NodeId>,
/// The id of its node. None in an entry written before ruler guides were nodes: it gets a new
/// id when the document is read.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<NodeId>,
/// The name it shows in the Layers panel, if it was given one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Locked on its own (its layer's lock is separate).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub locked: bool,
/// Hidden on its own (its layer's visibility is separate).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub hidden: bool,
}
impl Guide {
/// A canvas guide.
pub fn new(vertical: bool, pos: f64) -> Self {
Self { vertical, pos, artboard: None, layer: None }
Self { vertical, pos, artboard: None, layer: None, id: None, name: None, locked: false, hidden: false }
}
/// Moved by `d` (a vertical guide across, a horizontal one down).
+11 -6
View File
@@ -588,7 +588,8 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
if !c.visible || editable_only && (c.locked || c.is_template()) {
return false;
}
if opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
// A ruler guide is picked by the guide commands, never by an object hit test.
if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
return false;
}
// (An envelope's content sits where it was, not where the envelope draws it.)
@@ -870,10 +871,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline)
}
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
// #3291), and where its own fills and strokes paint ([`image_paint`]) except in outline
// mode.
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
// own fills and strokes paint ([`image_paint`]) except in outline mode.
NodeKind::Image(im) => {
if opt.path_only {
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
use vectorcraft_geom::kurbo::Shape;
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
frame.apply_affine(im.xf);
@@ -909,6 +910,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if stroke_contains(&bp, 0.0, opt.tol, p) {
return Some(HitKind::Outline);
}
// Outline mode draws the mesh lines, not the colours between them (#6437).
if opt.outline {
return stroke_contains(&m.lines().to_bezpath(), 0.0, opt.tol, p).then_some(HitKind::Outline);
}
(!opt.path_only && fill_contains(&bp, vectorcraft_geom::FillRule::NonZero, p)).then_some(HitKind::Fill)
}
_ => None,
@@ -1252,7 +1257,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
// marquee touches none of it, as clicks don't (#5309).
Some(s) if !doc.is_editable(s.id) => vec![],
Some(s) => match s.children() {
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
// A single object isolated: only it.
None => doc
.parent_of(s.id)
@@ -1281,7 +1286,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
if c.visible && !c.locked && !c.is_template() {
out.extend(layer_objects(c, r));
}
} else {
} else if !c.is_ruler_guide() {
out.push((c, r));
}
}
+39
View File
@@ -880,6 +880,45 @@ fn path_only_picks_paths_through_images() {
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
}
/// #6437: in outline mode an image is drawn as its frame and a gradient mesh as its mesh lines,
/// so a click inside them, on the outline of a path behind, picks that path, and a click on the
/// frame or a mesh line picks the image or the mesh. In Preview they cover the path as before,
/// and an image whose pixels show in outline mode (Show Images in Outline Mode) still does.
#[test]
fn outline_mode_picks_paths_through_images_and_meshes() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let (path, image, under, mesh) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0));
let im = crate::ImageObject { key: "k".into(), width: 80, height: 80, xf, link: None, placement: Default::default(), pixels: None };
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
d.insert(Some(l), 2, Node::path(under, shapes::rectangle(Rect::new(120.0, 120.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
let area = shapes::rectangle(Rect::new(110.0, 110.0, 190.0, 190.0));
let m = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
d.insert(Some(l), 3, Node::new(mesh, NodeKind::Mesh(m))).unwrap();
let outline = HitOptions { outline: true, ..Default::default() };
let hit = |d: &Document, p: Point, opt| hit_test(d, p, opt).map(|h| h.leaf);
// The image: the path's edge and the inside, then the frame.
let (path_edge, inside, frame) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(89.5, 50.0));
assert_eq!(hit(&d, path_edge, HitOptions::default()), Some(image), "Preview: the image covers the path");
assert_eq!(hit(&d, inside, HitOptions::default()), Some(image));
assert_eq!(hit(&d, path_edge, outline), Some(path), "outline: the path through the image");
assert_eq!(hit(&d, inside, outline), None, "outline: not inside the image");
assert_eq!(hit(&d, frame, outline), Some(image), "outline: the image's frame");
// The mesh: the path's edge and the inside, then its edge and a mesh line inside it.
let (under_edge, inside, edge, line) = (Point::new(120.5, 130.0), Point::new(130.0, 170.0), Point::new(189.5, 130.0), Point::new(150.0, 170.0));
assert_eq!(hit(&d, under_edge, HitOptions::default()), Some(mesh), "Preview: the mesh covers the path");
assert_eq!(hit(&d, inside, HitOptions::default()), Some(mesh));
assert_eq!(hit(&d, under_edge, outline), Some(under), "outline: the path through the mesh");
assert_eq!(hit(&d, inside, outline), None, "outline: not between the mesh lines");
assert_eq!(hit(&d, edge, outline), Some(mesh), "outline: the mesh's edge");
assert_eq!(hit(&d, line, outline), Some(mesh), "outline: a mesh line");
// Show Images in Outline Mode: the image's pixels are drawn, and it covers the path again.
d.setup.outline_images = true;
assert_eq!(hit(&d, path_edge, outline), Some(image));
}
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
/// frame and type on a path on its path, no longer anywhere in its bounds.
#[test]
+41 -5
View File
@@ -110,8 +110,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
}
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no
/// link: changes to it are dropped.
/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its
/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it
/// are dropped.
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
for it in &mut n.appearance.items {
match it {
@@ -119,8 +120,13 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f),
}
}
if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) {
visit_paint(p, f);
if let Some(e) = n.extras.0.as_deref_mut() {
if let Some(p) = e.colorize.as_deref_mut() {
visit_paint(p, f);
}
for p in e.symbol_overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
visit_paint(p, f);
}
}
match &mut n.kind {
NodeKind::Text(t) => {
@@ -144,7 +150,8 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
}
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh
/// points) given its swatch link and tint, keeping the links.
/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint,
/// keeping the links.
pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) {
visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint))));
}
@@ -158,3 +165,32 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
map_node_colors(Arc::make_mut(&mut s.art), f);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{NodeId, SymbolOverride};
use vectorcraft_geom::Affine;
#[test]
fn a_dynamic_instances_own_fills_and_strokes_are_visited() {
let red = Color::rgb(1.0, 0.0, 0.0);
let blue = Color::rgb(0.0, 0.0, 1.0);
let spot = Paint::Solid { color: red, swatch: Some("Spot".into()), tint: 0.5 };
let mut inst = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY });
inst.extras_mut().symbol_overrides = vec![
SymbolOverride { path: vec![0], fill: Some(spot), stroke: Some(Paint::solid(red)), ..Default::default() },
SymbolOverride { path: vec![1], opacity: Some(0.5), ..Default::default() },
];
let mut links = vec![];
map_node_colors(&mut inst, &mut |_, link| {
links.push(link.map(|(s, t)| (s.to_string(), t)));
blue
});
assert_eq!(links, vec![Some(("Spot".to_string(), 0.5)), None], "each override paint is visited once, with its link");
let o = &inst.extras().symbol_overrides;
assert_eq!(o[0].fill, Some(Paint::Solid { color: blue, swatch: Some("Spot".into()), tint: 0.5 }), "the link is kept");
assert_eq!(o[0].stroke, Some(Paint::solid(blue)));
assert_eq!((o[1].fill.as_ref(), o[1].stroke.as_ref()), (None, None), "an override without paint gets none");
}
}
+14 -2
View File
@@ -207,8 +207,12 @@ pub struct Document {
/// Object › Graph › Design…: art graphs can draw as markers.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_designs: Vec<GraphDesign>,
#[serde(default)]
pub guides: Vec<Guide>,
/// The saved form of the ruler guides: read from a file, then made into
/// [`NodeKind::RulerGuide`] nodes on their layers ([`Document::guides_into_nodes`]), and
/// written from those nodes when saving ([`Document::guides_to_saved`]). Empty in between.
/// Each entry read counts as an object against the read's node budget.
#[serde(default, rename = "guides", deserialize_with = "crate::node::counted_list")]
saved_guides: Vec<Guide>,
/// View → New View… (at most [`SavedView::MAX`]); saved with the document.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub views: Vec<SavedView>,
@@ -339,6 +343,11 @@ pub struct Document {
/// names it as the file's active artboard. `None`: the first. Native files do not keep it.
#[serde(skip)]
pub opened_artboard: Option<u32>,
/// The file this document was read from recorded its units (a `.ai` file's
/// `%AI5_RulerUnits`): it opens in them. A file that records none opens in Preferences ›
/// Units › General (#5820). Native files do not keep it: they always keep their units.
#[serde(skip)]
pub units_from_file: bool,
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
/// is set, so documents without any pay nothing for them.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -346,6 +355,9 @@ pub struct Document {
/// Where each node is in the tree, for lookups by id ([`id_index`]): a cache, never saved.
#[serde(skip)]
index: id_index::IdIndex,
/// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved.
#[serde(skip)]
guide_cache: document_guides::GuideCache,
}
fn ppi72() -> f64 {
+162
View File
@@ -643,6 +643,168 @@ mod tests {
assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}");
}
/// The polylines of `bp` flattened to 0.01 pt.
fn flattened(bp: &BezPath) -> Vec<Vec<Point>> {
let mut out: Vec<Vec<Point>> = vec![];
vectorcraft_geom::kurbo::flatten(bp.iter(), 0.01, |el| match el {
vectorcraft_geom::PathEl::MoveTo(p) => out.push(vec![p]),
vectorcraft_geom::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|v| v.push(p)),
vectorcraft_geom::PathEl::ClosePath => out.last_mut().into_iter().for_each(|v| v.push(v[0])),
_ => {}
});
out
}
/// The distance from `p` to the nearest of `lines`.
fn off_lines(lines: &[Vec<Point>], p: Point) -> f64 {
lines
.iter()
.flat_map(|v| v.windows(2))
.map(|w| {
let d = w[1] - w[0];
let t = if d.hypot2() > 0.0 { ((p - w[0]).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
p.distance(w[0] + d * t)
})
.fold(f64::INFINITY, f64::min)
}
/// How far apart the border of `m` and the outline of `path` are, in points: the larger of the
/// farthest a point of either lies from the other.
fn mesh_border_off_path(m: &GradientMesh, path: &PathData) -> f64 {
let (border, outline) = (flattened(&m.outline().to_bezpath()), flattened(&path.to_bezpath()));
let one = border.iter().flatten().map(|p| off_lines(&outline, *p)).fold(0.0, f64::max);
let other = outline.iter().flatten().map(|p| off_lines(&border, *p)).fold(0.0, f64::max);
one.max(other)
}
/// #2752: a gradient mesh keeps the exact outline of the path it is made from, sharp corners
/// included, whether made by Create Gradient Mesh (1×1 and 4×4) or by a Mesh tool click at a
/// point inside. Before, the border of each mesh was one cubic per edge between four corners
/// near the bounding box's: up to 49 pt off a five-point star, 54 pt off a notched rectangle.
#[test]
fn a_mesh_keeps_the_outline_of_every_shape() {
const OFF: f64 = 0.1;
let poly = |pts: &[(f64, f64)]| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), true));
let curves = |start: (f64, f64), cubics: &[[(f64, f64); 3]]| {
let mut bp = BezPath::new();
bp.move_to(start);
for [a, b, c] in cubics {
bp.curve_to(*a, *b, *c);
}
bp.close_path();
PathData::from_bezpath(&bp)
};
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
let heart = curves(
(300.0, 400.0),
&[
[(200.0, 320.0), (100.0, 250.0), (100.0, 170.0)],
[(100.0, 100.0), (180.0, 70.0), (230.0, 90.0)],
[(270.0, 105.0), (290.0, 130.0), (300.0, 150.0)],
[(310.0, 130.0), (330.0, 105.0), (370.0, 90.0)],
[(420.0, 70.0), (500.0, 100.0), (500.0, 170.0)],
[(500.0, 250.0), (400.0, 320.0), (300.0, 400.0)],
],
);
let teardrop = curves(
(300.0, 100.0),
&[
[(350.0, 200.0), (420.0, 250.0), (420.0, 320.0)],
[(420.0, 386.0), (366.0, 440.0), (300.0, 440.0)],
[(234.0, 440.0), (180.0, 386.0), (180.0, 320.0)],
[(180.0, 250.0), (250.0, 200.0), (300.0, 100.0)],
],
);
let shapes: [(&str, PathData, Point); 14] = [
("rectangle", shapes::rectangle(box_), Point::new(260.0, 230.0)),
("rotated rectangle", shapes::rectangle(box_).transformed(Affine::rotate_about(0.5, box_.center())), Point::new(280.0, 240.0)),
("triangle", poly(&[(300.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), Point::new(300.0, 320.0)),
("five-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0), Point::new(300.0, 300.0)),
("twelve-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 140.0, 12, 0.0), Point::new(300.0, 300.0)),
(
"L-shape",
poly(&[(100.0, 100.0), (200.0, 100.0), (200.0, 300.0), (400.0, 300.0), (400.0, 400.0), (100.0, 400.0)]),
Point::new(150.0, 350.0),
),
("rounded rectangle", shapes::rounded_rectangle(box_, 40.0), Point::new(260.0, 230.0)),
("heart", heart, Point::new(300.0, 250.0)),
("teardrop", teardrop, Point::new(300.0, 330.0)),
("ellipse", shapes::ellipse(box_), Point::new(200.0, 330.0)),
("thin rectangle", shapes::rectangle(Rect::new(100.0, 100.0, 500.0, 110.0)), Point::new(260.0, 104.0)),
(
"notched rectangle",
poly(&[(100.0, 100.0), (250.0, 100.0), (300.0, 200.0), (350.0, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
Point::new(260.0, 300.0),
),
// A notch shorter than the steps along the outline an edge is checked at, and deeper
// than the tolerance.
(
"rectangle with a tiny notch",
poly(&[(100.0, 100.0), (301.1, 100.0), (301.2, 100.3), (301.3, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
Point::new(260.0, 300.0),
),
// An outline that crosses itself, whose two lobes' areas cancel.
("bow tie", poly(&[(100.0, 100.0), (500.0, 400.0), (500.0, 100.0), (100.0, 400.0)]), Point::new(150.0, 250.0)),
];
// Every shape and way of making the mesh is checked, and all that stray are named.
let mut strays = vec![];
for (name, path, click) in shapes {
for (rows, cols) in [(1, 1), (4, 4)] {
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let off = mesh_border_off_path(&m, &path);
if off >= OFF {
strays.push(format!("{name}, {rows}×{cols}: border {off:.2} pt off the outline"));
}
}
let mut m = GradientMesh::for_path(&path, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.add_lines_at(click, 0.0).is_some(), "{name}: the click at {click:?} is outside the mesh");
let off = mesh_border_off_path(&m, &path);
if off >= OFF {
strays.push(format!("{name}, Mesh tool click: border {off:.2} pt off the outline"));
}
}
assert!(strays.is_empty(), "{strays:#?}");
}
/// The lines a mesh takes to keep a path's outline are as few as do it: a rectangle's and an
/// ellipse's meshes keep the rows and columns asked for, and a star's 1×1 mesh takes lines
/// through its points, at most one each way per anchor. Paths without an outline to follow
/// still give a mesh (an open path closes straight; a line there and back maps onto its box),
/// and a point that isn't finite gives none.
#[test]
fn a_mesh_takes_lines_only_where_the_outline_needs_them() {
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
for path in [shapes::rectangle(box_), shapes::ellipse(box_)] {
for (rows, cols) in [(1, 1), (4, 4), (2, 5)] {
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert_eq!((m.rows, m.cols), (rows, cols));
}
}
let star = shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0);
let m = GradientMesh::for_path(&star, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.rows > 1 && m.cols > 1 && m.rows <= 10 && m.cols <= 10 && m.is_valid(), "{}×{}", m.rows, m.cols);
// Every anchor of the star is a point of the mesh.
for a in &star.subpaths[0].anchors {
assert!(m.points.iter().any(|q| q.p.distance(a.p) < 1e-6), "{:?} is not a mesh point", a.p);
}
// An open path closes with a straight segment.
let open = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let m = GradientMesh::for_path(&open, 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let closed = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], true));
assert!(mesh_border_off_path(&m, &closed) < 0.1);
// A line there and back.
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 50.0)], true));
let m = GradientMesh::for_path(&line, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.is_valid() && m.points.iter().all(|q| q.p.is_finite()));
let mut nan = shapes::rectangle(box_);
nan.subpaths[0].anchors[1].p.x = f64::NAN;
assert!(GradientMesh::for_path(&nan, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).is_none());
// A path of many anchors stays within the line limit and keeps its outline.
let many = shapes::star(Point::new(300.0, 300.0), 200.0, 190.0, 400, 0.0);
let m = GradientMesh::for_path(&many, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.is_valid() && m.rows as usize <= mesh::MAX_BORDER_LINES && m.cols as usize <= mesh::MAX_BORDER_LINES, "{}×{}", m.rows, m.cols);
}
#[test]
fn mesh_insert_and_remove_lines() {
let mut m =
+2
View File
@@ -140,6 +140,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
}
// Its art is plain, so it warps at this depth.
NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w),
// A ruler guide has no shape to warp.
NodeKind::RulerGuide { .. } => {}
}
out
}
+481 -8
View File
@@ -470,6 +470,384 @@ fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(V
fit
}
/// The cubic from `p0` to `p3` leaving `p0` along `d0` and reaching `p3` against `d1` (unit
/// vectors; `d1` points from `p3` back into the curve) that comes closest (least squares) to the
/// points `qs`, which lie along the way in order; `None` when no such cubic has handles of positive
/// length. Each point is matched to the curve's nearest point, refined over a few rounds, as in
/// [`fit_edge`].
fn fit_tangents(qs: &[Point], (p0, d0): (Point, Vec2), (p3, d1): (Point, Vec2)) -> Option<CubicBez> {
const ROUNDS: usize = 6;
let n = qs.len() + 1;
let mut ts: Vec<f64> = (1..n).map(|i| i as f64 / n as f64).collect();
let mut fit = None;
for _ in 0..ROUNDS {
let (mut c11, mut c12, mut c22, mut x1, mut x2) = (0.0, 0.0, 0.0, 0.0, 0.0);
for (q, &t) in qs.iter().zip(&ts) {
let s = 1.0 - t;
let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
let (a1, a2) = (d0 * b1, d1 * b2);
let r = q.to_vec2() - (b0 + b1) * p0.to_vec2() - (b2 + b3) * p3.to_vec2();
c11 += a1.dot(a1);
c12 += a1.dot(a2);
c22 += a2.dot(a2);
x1 += r.dot(a1);
x2 += r.dot(a2);
}
let det = c11 * c22 - c12 * c12;
if det.abs() < 1e-12 {
break;
}
let (l1, l2) = ((c22 * x1 - c12 * x2) / det, (c11 * x2 - c12 * x1) / det);
if !(l1.is_finite() && l2.is_finite() && l1 > 0.0 && l2 > 0.0) {
break;
}
let c = CubicBez::new(p0, p0 + d0 * l1, p3 + d1 * l2, p3);
fit = Some(c);
let (a, b, k) = (c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2);
for (q, t) in qs.iter().zip(ts.iter_mut()) {
let s = 1.0 - *t;
let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k);
let acc = 6.0 * (s * (b - a) + *t * (k - b));
let e = c.eval(*t) - *q;
let den = v.hypot2() + e.dot(acc);
if den.abs() > 1e-12 {
*t = (*t - e.dot(v) / den).clamp(0.0, 1.0);
}
}
}
fit
}
/// How far (in points) a border edge of a mesh made from a path may stray from the path's outline
/// before the mesh takes a line through an anchor of the outline there; a thousandth of the outline's
/// size when that is less.
const BORDER_TOLERANCE: f64 = 0.1;
/// The most lines each way a mesh made from a path takes to keep its border on the outline
/// ([`BORDER_TOLERANCE`]); past that, each border edge keeps its closest fit.
pub(super) const MAX_BORDER_LINES: usize = 256;
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
const MAX_BORDER_ROUNDS: usize = 64;
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
const SHARP_TURN: f64 = 0.01;
/// Steps of each segment's parameter at which [`Outline`] measures the segment's length.
const LENGTH_STEPS: usize = 32;
/// Points of the outline each border edge of a mesh made from a path is fitted to
/// ([`Outline::fit`]).
const FIT_POINTS: usize = 32;
/// Points of the outline, and of the fitted edge, at which [`Outline::fit`] measures how far the
/// two stray from each other.
const CHECK_POINTS: usize = 128;
/// The outline a gradient mesh is made from: the largest subpath of a path, running clockwise on
/// screen, an open one closed by a straight segment, without segments of no length. A place on it
/// is a length from its first anchor, measured along a polyline through even steps of each
/// segment's parameter; the same length always gives the same point.
struct Outline {
segs: Vec<CubicBez>,
/// Where each segment starts, and the whole length last.
starts: Vec<f64>,
/// For each segment, the length from its start at each of [`LENGTH_STEPS`] + 1 even steps of
/// its parameter.
table: Vec<[f64; LENGTH_STEPS + 1]>,
/// Lengths closer than this are the same place.
eps: f64,
}
/// One side of the patch a mesh made from a path spans: the stretch of the outline from `start`,
/// `len` long, run backwards when `reversed` (the bottom and left sides run against the outline).
#[derive(Clone, Copy)]
struct Side {
start: f64,
len: f64,
reversed: bool,
}
impl Side {
/// The place on the outline at `f` (0 to 1) along the side.
fn at(&self, f: f64) -> f64 {
self.start + if self.reversed { (1.0 - f) * self.len } else { f * self.len }
}
}
/// The direction a cubic leaves its start in (`false`) or reaches its end in (`true`), from the
/// first handle or point that is not at the end; zero when all its points are together.
fn cubic_tangent(c: &CubicBez, end: bool) -> Vec2 {
let near = 1e-12 * (c.p0.to_vec2().hypot() + c.p3.to_vec2().hypot() + 1.0);
let options = if end { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] } else { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] };
options.into_iter().find(|v| v.hypot() > near).unwrap_or(Vec2::ZERO)
}
impl Outline {
/// The outline of `path`; `None` when it has no subpath of two anchors or more, a point that
/// isn't finite, or all its points on one line (a line there and back).
fn new(path: &PathData) -> Option<Self> {
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
if !sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
return None;
}
let mut sp = sp.clone();
if sp.signed_area() < 0.0 {
sp.reverse();
}
// A straight segment's parameter runs evenly along it.
let line = |a: Point, b: Point| CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b);
let mut segs: Vec<CubicBez> =
(0..sp.segment_count()).map(|i| if sp.segment_is_line(i) { line(sp.segment(i).p0, sp.segment(i).p3) } else { sp.segment(i) }).collect();
if !sp.closed
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
{
segs.push(line(a.p, b.p));
}
segs.retain(|c| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
if segs.len() < 2 {
return None;
}
let mut starts = Vec::with_capacity(segs.len() + 1);
let mut table = Vec::with_capacity(segs.len());
let mut total = 0.0;
for c in &segs {
let mut lens = [0.0; LENGTH_STEPS + 1];
let mut prev = c.p0;
for (k, len) in lens.iter_mut().enumerate().skip(1) {
let p = c.eval(k as f64 / LENGTH_STEPS as f64);
*len = prev.distance(p);
prev = p;
}
for k in 1..=LENGTH_STEPS {
lens[k] += lens[k - 1];
}
starts.push(total);
total += lens[LENGTH_STEPS];
table.push(lens);
}
starts.push(total);
if !(total.is_finite() && total > 0.0) {
return None;
}
// An outline whose points all lie on one line encloses nothing; one that crosses itself
// (a bow tie) may have areas that cancel, and is still followed.
let pts: Vec<Point> = segs.iter().flat_map(|c| [c.p0, c.p1, c.p2, c.p3]).collect();
let first = pts.first().copied()?;
let far = pts.iter().copied().max_by(|a, b| a.distance_squared(first).total_cmp(&b.distance_squared(first)))?;
let dir = far - first;
let width = pts.iter().map(|p| ((*p - first).cross(dir) / dir.hypot()).abs()).fold(0.0, f64::max);
if !(dir.hypot() > 0.0 && width > 1e-9 * total) {
return None;
}
Some(Self { segs, starts, table, eps: total * 1e-9 })
}
fn total(&self) -> f64 {
self.starts.last().copied().unwrap_or_default()
}
/// The bounding box of the outline.
fn bounds(&self) -> Option<Rect> {
self.segs.iter().map(|c| c.bounding_box()).reduce(|a, b| a.union(b))
}
/// The parameter of segment `i` `local` along it (clamped to the segment).
fn seg_t(&self, i: usize, local: f64) -> f64 {
let Some(lens) = self.table.get(i) else { return 0.0 };
let k = lens.partition_point(|x| *x <= local).clamp(1, LENGTH_STEPS) - 1;
let (l0, l1) = (lens[k], lens[k + 1]);
let f = if l1 > l0 { ((local - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 };
(k as f64 + f) / LENGTH_STEPS as f64
}
/// The segment and its parameter at place `s` (wrapping around); a place at the very end of a
/// segment is the start of the next.
fn locate(&self, s: f64) -> (usize, f64) {
let n = self.segs.len();
let s = s.rem_euclid(self.total());
let mut i = self.starts.partition_point(|x| *x <= s).clamp(1, n) - 1;
if self.starts.get(i + 1).is_some_and(|end| end - s <= self.eps) {
i = (i + 1) % n;
return (i, 0.0);
}
(i, self.seg_t(i, s - self.starts[i]))
}
fn point(&self, s: f64) -> Point {
let (i, t) = self.locate(s);
self.segs.get(i).map_or(Point::ZERO, |c| c.eval(t))
}
/// The anchors strictly inside the stretch from `a`, `len` long: each one's distance from `a`
/// and the segment it starts.
fn anchors_in(&self, a: f64, len: f64) -> Vec<(f64, usize)> {
let (total, n) = (self.total(), self.segs.len());
let a = a.rem_euclid(total);
let (lo, hi) = (a + self.eps, a + len - self.eps);
let mut out = vec![];
for lap in [0.0, total] {
let from = self.starts[..n].partition_point(|x| x + lap <= lo);
for (i, start) in self.starts[..n].iter().enumerate().skip(from) {
let p = start + lap;
if p >= hi {
break;
}
out.push((p - a, i));
}
}
out
}
/// The piece of the outline from `a`, `len` long, which no anchor lies inside.
fn piece(&self, a: f64, len: f64) -> CubicBez {
let (i, t0) = self.locate(a);
let Some(c) = self.segs.get(i) else { return CubicBez::new(Point::ZERO, Point::ZERO, Point::ZERO, Point::ZERO) };
// At a segment's start (a place at the end of the one before counts as that), none of it is behind.
let behind = if t0 == 0.0 { 0.0 } else { a.rem_euclid(self.total()) - self.starts[i] };
let t1 = self.seg_t(i, behind + len);
c.subsegment(t0..t1.max(t0))
}
/// The direction the outline leaves place `s` in (`into` false) or reaches it in (`into` true).
fn tangent(&self, s: f64, into: bool) -> Vec2 {
let n = self.segs.len();
let (i, t) = self.locate(s);
let c = match (into, t <= 0.0) {
(true, true) => self.segs[(i + n - 1) % n],
(true, false) => self.segs[i].subsegment(0.0..t),
(false, _) => self.segs[i].subsegment(t..1.0),
};
cubic_tangent(&c, into)
}
/// How sharply the outline turns at the anchor starting segment `i` (radians, 0 to π).
fn turn(&self, i: usize) -> f64 {
let s = self.starts[i];
let (din, dout) = (self.tangent(s, true), self.tangent(s, false));
din.cross(dout).atan2(din.dot(dout)).abs()
}
/// The place on the outline nearest `q`.
fn nearest(&self, q: Point) -> f64 {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let mut best = (f64::INFINITY, 0.0);
for (i, c) in self.segs.iter().enumerate() {
let near = c.nearest(q, 1e-9);
if near.distance_sq < best.0 {
// The length at that parameter, from the table.
let lens = &self.table[i];
let x = near.t * LENGTH_STEPS as f64;
let k = (x.floor() as usize).min(LENGTH_STEPS - 1);
let local = lens[k] + (lens[k + 1] - lens[k]) * (x - k as f64);
best = (near.distance_sq, self.starts[i] + local);
}
}
best.1
}
/// The cubic standing for the stretch from `a`, `len` long, and how far it strays from it: the
/// piece of the segment when no anchor lies inside, otherwise a cubic fitted to the outline with
/// its ends along the outline's own directions there.
fn fit(&self, a: f64, len: f64) -> (CubicBez, f64) {
let (p0, p3) = (self.point(a), self.point(a + len));
if len <= self.eps {
return (CubicBez::new(p0, p0, p0, p0), 0.0);
}
let anchors = self.anchors_in(a, len);
if anchors.is_empty() {
return (self.piece(a, len), 0.0);
}
let qs: Vec<Point> = (1..FIT_POINTS).map(|i| self.point(a + len * i as f64 / FIT_POINTS as f64)).collect();
let (d0, d1) = (self.tangent(a, false), -self.tangent(a + len, true));
let unit = |v: Vec2| if v.hypot() > 0.0 { Some(v / v.hypot()) } else { None };
let straight = CubicBez::new(p0, p0.lerp(p3, 1.0 / 3.0), p0.lerp(p3, 2.0 / 3.0), p3);
let c = match (unit(d0), unit(d1)) {
(Some(d0), Some(d1)) => fit_tangents(&qs, (p0, d0), (p3, d1)),
_ => None,
}
.unwrap_or(straight);
// Both ways: the outline's points from the cubic, and the cubic's points from the outline.
// The outline is checked at even steps and at every anchor inside, so a spike or a notch
// narrower than a step is not missed.
use vectorcraft_geom::kurbo::ParamCurveNearest;
let mut at: Vec<f64> = (0..=CHECK_POINTS).map(|i| len * i as f64 / CHECK_POINTS as f64).chain(anchors.iter().map(|(o, _)| *o)).collect();
at.sort_by(f64::total_cmp);
let line: Vec<Point> = at.iter().map(|o| self.point(a + o)).collect();
let off_outline = line.iter().map(|q| c.nearest(*q, 1e-9).distance_sq.sqrt()).fold(0.0, f64::max);
let off_cubic = (0..=CHECK_POINTS)
.map(|i| {
let p = c.eval(i as f64 / CHECK_POINTS as f64);
line.windows(2)
.map(|w| {
let (u, v) = (w[0], w[1]);
let d = v - u;
let t = if d.hypot2() > 0.0 { ((p - u).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
p.distance(u + d * t)
})
.fold(f64::INFINITY, f64::min)
})
.fold(0.0, f64::max);
(c, off_outline.max(off_cubic))
}
/// The border edge of `side` from `f0` to `f1` (0 to 1 along it, rising), run the way the side
/// runs, and when it strays from the outline by more than `tol`, where along the side (0 to 1)
/// a mesh line through an anchor would help: the sharpest corner inside it, or the anchor
/// nearest its middle when none is sharp.
fn edge(&self, side: &Side, f0: f64, f1: f64, tol: f64) -> (CubicBez, Option<f64>) {
let len = (f1 - f0) * side.len;
let a = side.at(if side.reversed { f1 } else { f0 });
let (c, off) = self.fit(a, len);
let c = if side.reversed { CubicBez::new(c.p3, c.p2, c.p1, c.p0) } else { c };
if off <= tol || side.len <= 0.0 {
return (c, None);
}
let anchors = self.anchors_in(a, len);
let sharpest = anchors.iter().map(|&(o, i)| (self.turn(i), o)).max_by(|x, y| x.0.total_cmp(&y.0));
let at = match sharpest {
Some((turn, o)) if turn > SHARP_TURN => Some(o),
_ => anchors.iter().map(|&(o, _)| o).min_by(|x, y| (x - len / 2.0).abs().total_cmp(&(y - len / 2.0).abs())),
};
let split = at.map(|o| if side.reversed { f1 - o / side.len } else { f0 + o / side.len });
(c, split.filter(|f| *f > f0 && *f < f1))
}
/// The cuts (0 to 1) of the lines across sides `one` and `other`: `even`, and as many more as
/// keep every border edge along them within `tol` of the outline (see [`Self::edge`]), at most
/// [`MAX_BORDER_LINES`] in all.
fn cuts(&self, one: &Side, other: &Side, even: Vec<f64>, tol: f64) -> Vec<f64> {
let mut cuts = even;
for _ in 0..MAX_BORDER_ROUNDS {
let mut add: Vec<f64> =
[one, other].iter().flat_map(|s| cuts.windows(2).filter_map(|w| self.edge(s, w[0], w[1], tol).1).collect::<Vec<_>>()).collect();
add.retain(|f| cuts.iter().all(|c| (c - f).abs() > 1e-9));
add.truncate((MAX_BORDER_LINES + 1).saturating_sub(cuts.len()));
if add.is_empty() {
break;
}
cuts.extend(add);
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
}
cuts
}
/// The points along `side` at `knots` (rising, 0 to 1).
fn side_points(&self, side: &Side, knots: &[f64]) -> Vec<Point> {
knots.iter().map(|f| self.point(side.at(*f))).collect()
}
}
/// The sorted union of `cuts` and `SIDE` even steps.
fn side_knots(cuts: &[f64]) -> Vec<f64> {
let mut k: Vec<f64> = (0..SIDE).map(|i| i as f64 / (SIDE - 1) as f64).chain(cuts.iter().copied()).collect();
k.sort_by(f64::total_cmp);
k.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
k
}
/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles
/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer
/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the
@@ -599,19 +977,104 @@ impl GradientMesh {
/// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`.
pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option<Self> {
let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?;
m.highlight(appearance, highlight);
Self::for_path_shaded(path, rows, cols, &|_| (base, 1.0), appearance, highlight)
}
/// As [`Self::for_path_with`], then lightened per `appearance` ([`Self::highlight`]), measured
/// by where each line crosses the patch.
pub fn for_path_shaded(
path: &PathData,
rows: u32,
cols: u32,
color_at: &dyn Fn(Point) -> (Color, f32),
appearance: MeshAppearance,
highlight: f64,
) -> Option<Self> {
let (mut m, us, vs) = Self::build_for_path(path, rows, cols, color_at)?;
m.highlight_at(appearance, highlight, &us, &vs);
Some(m)
}
/// Create Gradient Mesh for a path: the outline split at its corners, each point taking the
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
let coons = Coons::from_path(path)?;
Self::build_for_path(path, rows, cols, color_at).map(|(m, ..)| m)
}
/// The mesh of [`Self::for_path_with`] and where its column and row lines cross the patch (0
/// to 1). Its border lies on the outline of the path's largest subpath (#2752): the patch's
/// corners are the outline's places nearest the corners of its bounding box (when those don't
/// come in order round the outline, the top left one and the places a quarter, a half and three
/// quarters of the way round from it), its points on the
/// border sit on the outline, and each border edge is the piece of the outline between its
/// points, a single cubic. Where the outline bends through an anchor between two of the `rows`
/// × `cols` lines and no single cubic follows it within [`BORDER_TOLERANCE`], the mesh takes a
/// line through that anchor (its sharpest corner first), as many as that needs up to
/// [`MAX_BORDER_LINES`] each way. `None` when the path has no outline or a point that isn't
/// finite; an outline whose points all lie on one line gives the mesh of its bounding box.
fn build_for_path(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<(Self, Vec<f64>, Vec<f64>)> {
if !path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
return None;
}
let (us, vs) = (even_steps(cols), even_steps(rows));
let Some((o, sides)) = Outline::new(path).and_then(|o| {
let r = o.bounds()?;
let [tl, mut tr, mut br, mut bl] = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| o.nearest(Point::new(x, y)));
let span = |a: f64, b: f64| (b - a).rem_euclid(o.total());
// Corners met out of order around the outline would make sides that overlap: the
// other three then go a quarter of the way round from the top left each.
let around = span(tl, tr) + span(tr, br) + span(br, bl) + span(bl, tl);
if (around - o.total()).abs() > 1e-6 * o.total() {
let quarter = o.total() / 4.0;
(tr, br, bl) = (tl + quarter, tl + 2.0 * quarter, tl + 3.0 * quarter);
}
let sides = [
Side { start: tl, len: span(tl, tr), reversed: false },
Side { start: tr, len: span(tr, br), reversed: false },
Side { start: br, len: span(br, bl), reversed: true },
Side { start: bl, len: span(bl, tl), reversed: true },
];
Some((o, sides))
}) else {
// No outline to follow: the patch of the flattened outline (its bounding box when it
// encloses nothing), with each border edge fitted.
let coons = Coons::from_path(path)?;
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
m.fit_border(&coons, &us, &vs);
return Some((m, us, vs));
};
let [top, right, bottom, left] = sides;
let size = o.bounds().map_or(0.0, |r| r.width() + r.height());
let tol = BORDER_TOLERANCE.min(size * 1e-3).max(o.eps);
let us = o.cuts(&top, &bottom, us, tol);
let vs = o.cuts(&left, &right, vs, tol);
let (ku, kv) = (side_knots(&us), side_knots(&vs));
let coons = Coons {
top: o.side_points(&top, &ku),
right: o.side_points(&right, &kv),
bottom: o.side_points(&bottom, &ku),
left: o.side_points(&left, &kv),
knots: Some(Box::new([ku.clone(), kv.clone(), ku, kv])),
};
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
m.fit_border(&coons, &us, &vs);
Some(m)
let (rows, cols) = (m.rows as usize, m.cols as usize);
let edges = [(0, &top), (rows, &bottom)]
.map(|(r, side)| (r, side, true))
.into_iter()
.chain([(0, &left), (cols, &right)].map(|(c, side)| (c, side, false)));
for (line, side, along_u) in edges {
let steps = if along_u { &us } else { &vs };
for (k, w) in steps.windows(2).enumerate() {
let (a, b, out, back) =
if along_u { (m.idx(line, k), m.idx(line, k + 1), H_RIGHT, H_LEFT) } else { (m.idx(k, line), m.idx(k + 1, line), H_DOWN, H_UP) };
let (c, _) = o.edge(side, w[0], w[1], tol);
m.points[a].p = c.p0;
m.points[b].p = c.p3;
m.points[a].handles[out] = c.p1 - c.p0;
m.points[b].handles[back] = c.p2 - c.p3;
}
}
Some((m, us, vs))
}
/// Give each edge on the mesh's border the handles that make it follow the outline it stands
@@ -657,11 +1120,21 @@ impl GradientMesh {
/// the edges, by at most `highlight` %. Each point lightens towards white in its own colour
/// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232).
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
let even = |n: u32| (0..=n).map(|i| f64::from(i) / f64::from(n)).collect::<Vec<_>>();
let (us, vs) = (even(self.cols), even(self.rows));
self.highlight_at(appearance, highlight, &us, &vs);
}
/// As [`Self::highlight`], with the column lines at `us` and the row lines at `vs` (0 to 1
/// across the patch); a mesh whose lines don't match them is left as it is.
fn highlight_at(&mut self, appearance: MeshAppearance, highlight: f64, us: &[f64], vs: &[f64]) {
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
let (rows, cols) = (self.rows as usize, self.cols as usize);
for r in 0..=rows {
for c in 0..=cols {
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 {
return;
}
for (r, &v) in vs.iter().enumerate() {
for (c, &u) in us.iter().enumerate() {
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
let w = match appearance {
MeshAppearance::Flat => 0.0,
+1 -1
View File
@@ -88,7 +88,7 @@ impl Document {
}
let mut n = 0;
n += vec_bytes(&self.artboards) + self.artboards.iter().map(|a| a.name.capacity()).sum::<usize>();
n += vec_bytes(&self.guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
n += vec_bytes(&self.saved_guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
n += vec_bytes(&self.text_threads) + self.text_threads.iter().map(vec_bytes).sum::<usize>();
n += self.images.iter().map(|(k, b)| 4 * size_of::<usize>() + k.capacity() + b.mime.capacity() + size_of_val(b)).sum::<usize>();
n += map_bytes(&self.export_settings) + map_bytes(&self.extra) + self.print_setup.as_ref().map_or(0, json_bytes);
+1
View File
@@ -33,6 +33,7 @@ pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
use wire::NodeWire;
pub(crate) use wire::counted_list;
pub use wire::{MAX_READ_NODES, with_node_budget};
fn yes() -> bool {
+1 -1
View File
@@ -19,7 +19,7 @@ impl Node {
fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) {
match &self.kind {
NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {}
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } | NodeKind::SymbolInstance { .. } => {}
NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)),
NodeKind::Compound { children, rule } => {
let mut bp = BezPath::new();
+26
View File
@@ -56,4 +56,30 @@ impl LayerColor {
LayerColor::Custom(c) => c,
}
}
/// The color as text: a preset's name from [`LAYER_COLORS`], else `#rrggbb` (lowercase).
pub fn label_text(self) -> String {
let preset = match self {
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(i)),
LayerColor::Custom(_) => None,
};
preset.map_or_else(
|| {
let [r, g, b] = self.rgb();
format!("#{r:02x}{g:02x}{b:02x}")
},
|(name, _)| (*name).to_string(),
)
}
/// The color [`LayerColor::label_text`] names: a preset's name exactly as [`LAYER_COLORS`]
/// spells it, or `#rrggbb` with six hex digits. None for anything else.
pub fn from_label_text(s: &str) -> Option<Self> {
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| *name == s) {
return u8::try_from(i).ok().map(LayerColor::Preset);
}
let hex = s.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?;
let byte = |k: usize| u8::from_str_radix(&hex[k..k + 2], 16).ok();
Some(LayerColor::Custom([byte(0)?, byte(2)?, byte(4)?]))
}
}
+17
View File
@@ -122,6 +122,17 @@ pub enum NodeKind {
Intertwine {
children: Vec<Arc<Node>>,
},
/// A ruler guide: a straight line across the canvas, or across one artboard, that draws on
/// screen only. It is always a direct child of a layer or sublayer, above the layer's other
/// children, and has no bounds.
RulerGuide {
/// true: a vertical guide at x = `pos`; false: a horizontal one at y = `pos`.
vertical: bool,
pos: f64,
/// The [`crate::Artboard::id`] of the artboard it runs across; None: across the canvas.
#[serde(default, skip_serializing_if = "Option::is_none")]
artboard: Option<u32>,
},
}
/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every
@@ -215,6 +226,12 @@ mod kind_de {
Intertwine {
children: Vec<Arc<Node>>,
},
RulerGuide {
vertical: bool,
pos: f64,
#[serde(default)]
artboard: Option<u32>,
},
}
impl<'de> Deserialize<'de> for NodeKind {
+80 -7
View File
@@ -80,6 +80,16 @@ impl Node {
matches!(self.kind, NodeKind::Layer { .. })
}
/// A ruler guide ([`NodeKind::RulerGuide`]).
pub fn is_ruler_guide(&self) -> bool {
matches!(self.kind, NodeKind::RulerGuide { .. })
}
/// A guide of either kind: a ruler guide, or a path made into a guide.
pub fn is_guide(&self) -> bool {
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
}
/// A template layer (Layer Options → Template).
pub fn is_template(&self) -> bool {
matches!(self.kind, NodeKind::Layer { template: true, .. })
@@ -91,7 +101,7 @@ impl Node {
pub fn layer_art(&self, editable: bool) -> Vec<NodeId> {
fn visit(n: &Node, editable: bool, out: &mut Vec<NodeId>) {
for c in n.children().into_iter().flatten() {
if editable && (!c.visible || c.locked || c.is_template()) {
if c.is_ruler_guide() || (editable && (!c.visible || c.locked || c.is_template())) {
continue;
}
if c.is_layer() {
@@ -142,6 +152,7 @@ impl Node {
NodeKind::Repeat(r) => r.kind.label(),
NodeKind::PlacedDocument(_) => "Placed Document",
NodeKind::Intertwine { .. } => "Intertwine",
NodeKind::RulerGuide { .. } => "Guide",
}
}
@@ -310,6 +321,8 @@ impl Node {
NodeKind::PlacedDocument(p) => Some(p.bounds()),
// The members drawn over the others are drawn where they are.
NodeKind::Intertwine { children } => union(children),
// A ruler guide runs across the canvas (or an artboard): it adds nothing to a box.
NodeKind::RulerGuide { .. } => None,
}
}
@@ -373,7 +386,10 @@ impl Node {
NodeKind::SymbolInstance { symbol, xf } => {
let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) {
Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric),
Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual),
// A symbol drawn at other than its natural size goes through its 9-slice guides.
Some((s, art)) if moves_only(*xf) && s.document().symbol_slice_map_of(symbol, art.geometric, *xf).is_none() => {
xf.transform_rect_bbox(art.visual)
}
Some((s, art)) => {
let placed = xf.transform_rect_bbox(art.geometric);
match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) {
@@ -519,6 +535,9 @@ impl Node {
}
NodeKind::Mesh(m) => m.transform(a),
NodeKind::Repeat(r) => r.transform(a, *sc),
// A ruler guide stays where it is when the art around it (its layer) is transformed:
// the guide commands move it.
NodeKind::RulerGuide { .. } => {}
}
// The frames of the objects attached to a path move with them, and the distances along the
// path follow the path as it is now (a live shape's path is regenerated).
@@ -554,10 +573,10 @@ impl Node {
}
}
/// Count of nodes in this subtree.
/// Count of nodes in this subtree, ruler guides left out.
pub fn count(&self) -> usize {
let mut n = 0;
self.walk(&mut |_| n += 1);
self.walk(&mut |c| n += usize::from(!c.is_ruler_guide()));
n
}
@@ -566,7 +585,7 @@ impl Node {
pub fn count_with_masks(&self) -> usize {
let mut n = 0;
self.walk(&mut |c| {
n += 1;
n += usize::from(!c.is_ruler_guide());
if let Some(m) = &c.extras().mask {
n += m.art.count_with_masks();
}
@@ -685,7 +704,7 @@ impl Node {
/// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves.
pub fn knockout_elements(children: &[Arc<Node>]) -> Vec<&Arc<Node>> {
fn push<'a>(children: &'a [Arc<Node>], out: &mut Vec<&'a Arc<Node>>) {
for c in children.iter().filter(|c| c.visible) {
for c in children.iter().filter(|c| c.visible && !c.is_ruler_guide()) {
match c.children() {
Some(ch) if c.passes_knockout_through() => push(ch, out),
_ => out.push(c),
@@ -698,8 +717,62 @@ impl Node {
}
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
/// A layer whose first child is a ruler guide holds no art, so a guide never clips it.
pub fn clips(&self) -> bool {
matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. })
match &self.kind {
NodeKind::Group { clip, .. } => *clip,
NodeKind::Layer { clip, children, .. } => *clip && children.first().is_none_or(|c| !c.is_ruler_guide()),
_ => false,
}
}
/// Where the ruler guides at the end of `children` (a layer's) begin: the index past the last
/// child that is not one. Art goes below this index and ruler guides at or above it.
pub fn guide_run_start(children: &[Arc<Node>]) -> usize {
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
}
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
pub fn strip_ruler_guides(&mut self) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
ch.retain(|c| !c.is_ruler_guide());
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
Arc::make_mut(c).strip_ruler_guides();
}
}
}
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
let c = Arc::make_mut(c);
match &mut c.kind {
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
_ => c.map_ruler_guide_positions(f),
}
}
}
}
/// Whether this layer or one of its sublayers holds a ruler guide.
pub fn holds_ruler_guides(&self) -> bool {
self.is_layer() && self.children().is_some_and(|ch| ch.iter().any(|c| c.is_ruler_guide() || c.holds_ruler_guides()))
}
/// The index that an insert into `children` at `index` uses for `node`: art stays below the
/// layer's ruler guides and a ruler guide goes among them.
pub fn insert_index(children: &[Arc<Node>], index: usize, node: &Node) -> usize {
let start = Self::guide_run_start(children);
let i = index.min(children.len());
if node.is_ruler_guide() { i.max(start) } else { i.min(start) }
}
/// Make this group or layer clip its children by its first child, or stop it.
+4 -3
View File
@@ -145,9 +145,10 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> {
}
/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol
/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed
/// file of repeated empty items stays small while they take memory once read.
fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
/// overrides, a document's saved ruler guides), each item counting against [`with_node_budget`]
/// as an object does: a compressed file of repeated empty items stays small while they take
/// memory once read.
pub(crate) fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
struct Items<T>(std::marker::PhantomData<T>);
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> {
type Value = Vec<T>;
+2
View File
@@ -584,6 +584,8 @@ impl<'a> NestedCount<'a> {
(NodeKind::Repeat(r), _) => r.in_all(self),
(NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 },
(NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) },
// A ruler guide draws nothing, so a repeat makes no copies of it.
(NodeKind::RulerGuide { .. }, _) => Cost::default(),
(_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }),
_ => Cost { instances: 0, copies: 1 },
};
+6 -6
View File
@@ -7,7 +7,6 @@ use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
use crate::appearance::HEAD_REACH;
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
/// Arc-length accuracy for placing a point along a profile (document points).
@@ -395,18 +394,19 @@ impl StrokeLayer {
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let hw = self.arrow_weight(end);
let v = p - at;
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
}
}
}
+19 -13
View File
@@ -39,16 +39,16 @@ pub struct Selection {
/// clears them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub slices: Vec<NodeId>,
/// Ruler guides selected with a selection tool, as indexes into [`Document::guides`]. A new
/// Ruler guides selected with a selection tool, by node id ([`Document::ruler_guides`]). A new
/// selection ([`Self::set`]) clears them; Shift-adding or -removing objects keeps them, so
/// guides and objects can be selected together, in either order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub guides: Vec<usize>,
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (an index
/// into [`Document::guides`], one of [`Self::guides`]): the objects line up on it. Never set
/// with `key`; [`Self::prune`] clears it when no object is selected to align to it.
pub guides: Vec<NodeId>,
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (one of
/// [`Self::guides`]): the objects line up on it. Never set with `key`; [`Self::prune`] clears
/// it when no object is selected to align to it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_guide: Option<usize>,
pub key_guide: Option<NodeId>,
/// The new art on a locked artboard that this selection keeps editable
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
/// the engine then sets the document's from it. Editing state, never saved.
@@ -139,10 +139,10 @@ impl Selection {
}
}
}
/// Select ruler guides `indexes` (see [`Selection::guides`]) and nothing else.
pub fn set_guides(&mut self, indexes: impl IntoIterator<Item = usize>) {
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for i in indexes {
for i in ids {
if !self.guides.contains(&i) {
self.guides.push(i);
}
@@ -150,7 +150,7 @@ impl Selection {
}
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
/// Shift-click on a guide).
pub fn toggle_guide(&mut self, i: usize) {
pub fn toggle_guide(&mut self, i: NodeId) {
self.symbol_part = None;
if let Some(k) = self.guides.iter().position(|g| *g == i) {
self.guides.remove(k);
@@ -201,7 +201,9 @@ impl Selection {
pub fn prune(&mut self, doc: &Document) {
// Every id this looks up, found in one walk of the tree.
let ids = self.objects.iter().chain(self.anchors.keys()).chain(self.segments.keys()).copied().chain(self.key).chain(self.target);
let found = doc.index_paths(ids);
let mut found = doc.index_paths(ids);
// A ruler guide is selected in `guides` only, never as an object, an anchor or the key.
found.retain(|_, p| !doc.node_at(p).is_some_and(|n| n.is_ruler_guide()));
self.objects.retain(|id| found.contains_key(id));
self.anchors.retain(|id, _| found.contains_key(id));
self.segments.retain(|id, refs| {
@@ -209,8 +211,12 @@ impl Selection {
refs.retain(|&(si, seg)| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count()));
!refs.is_empty() && self.objects.contains(id) && self.anchors.contains_key(id)
});
// Guides on a hidden or locked layer can't stay selected.
self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g)));
// Guides that are gone, or hidden or locked (themselves or by their layer), can't stay
// selected.
if !self.guides.is_empty() {
let editable = doc.editable();
self.guides.retain(|id| doc.node(*id).is_some_and(|n| n.is_ruler_guide()) && editable(*id));
}
// The key object stays while another selected object lies outside it, or while ruler
// guides are selected for it to line up (#2143).
let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| {
+34 -19
View File
@@ -20,25 +20,30 @@ fn basic_ops() {
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
s.add(NodeId(1));
s.set_guides([2, 0, 2]);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![2, 0]));
let (g0, g2) = (NodeId(10), NodeId(12));
s.set_guides([g2, g0, g2]);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![g2, g0]));
assert!(s.has_objects_or_guides() && s.is_empty());
// Shift-adding an object keeps them; a new selection doesn't.
s.add(NodeId(1));
assert_eq!(s.guides, vec![2, 0]);
assert_eq!(s.guides, vec![g2, g0]);
s.set([NodeId(1)]);
assert!(s.guides.is_empty());
// Toggled, a guide joins (or leaves) the selected objects.
s.toggle_guide(0);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![0]));
s.toggle_guide(0);
s.toggle_guide(g0);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![g0]));
s.toggle_guide(g0);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![]));
// Pruning drops guides the document no longer has.
// Pruning drops guides the document no longer has, ids of other objects, and guides that are
// locked or hidden themselves.
let mut d = Document::new(100.0, 100.0);
d.guides.push(crate::Guide::new(true, 10.0));
s.set_guides([0, 1]);
let layer = d.layers[0].id;
let kept = d.add_ruler_guide(&crate::Guide::new(true, 10.0));
let locked = d.add_ruler_guide(&crate::Guide { locked: true, ..crate::Guide::new(true, 20.0) });
let hidden = d.add_ruler_guide(&crate::Guide { hidden: true, ..crate::Guide::new(true, 30.0) });
s.set_guides([kept, NodeId(9999), layer, locked, hidden]);
s.prune(&d);
assert_eq!(s.guides, vec![0]);
assert_eq!(s.guides, vec![kept]);
}
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
@@ -131,16 +136,26 @@ fn guides_show_and_lock_with_their_layer() {
assert!(d.guide_shown(&crate::Guide::new(false, 5.0)));
let gone = crate::Guide { layer: Some(NodeId(9999)), ..crate::Guide::new(true, 1.0) };
assert!(d.guide_shown(&gone) && d.guide_editable(&gone));
d.guides.push(g);
assert_eq!(d.guides_on(layer).count(), 1);
// Guides on no layer, or a gone one, are adopted by the top visible, unlocked layer.
// As a node, a guide shows and locks with its layer and on its own.
let id = d.add_ruler_guide(&g);
let node = d.ruler_guide(id).unwrap();
assert_eq!(d.guides_on(layer), std::slice::from_ref(&node));
assert!(!d.guide_shown(&node) && !d.guide_editable(&node), "its layer is hidden");
d.node_mut(layer).unwrap().visible = true;
d.node_mut(layer).unwrap().locked = false;
d.guides.push(crate::Guide::new(false, 5.0));
d.guides.push(gone);
assert_eq!(d.adopt_guides(), 2);
assert!(d.guides.iter().all(|g| g.layer == Some(layer)));
assert_eq!(d.adopt_guides(), 0, "once");
assert!(d.guide_shown(&node) && d.guide_editable(&node));
d.node_mut(id).unwrap().locked = true;
let node = d.ruler_guide(id).unwrap();
assert!(d.guide_shown(&node) && !d.guide_editable(&node), "locked itself");
d.node_mut(id).unwrap().visible = false;
assert!(!d.guide_shown(&node), "hidden itself");
// Saved guides on no layer, or a gone one, go on the top visible, unlocked layer.
d.saved_guides.push(crate::Guide::new(false, 5.0));
d.saved_guides.push(gone);
assert_eq!(d.guides_into_nodes(), 2);
assert!(d.ruler_guides().iter().all(|g| g.layer == Some(layer)));
assert_eq!(d.ruler_guides().len(), 3);
assert_eq!(d.guides_into_nodes(), 0, "once");
// A guide saved before guides had layers reads as one on no layer.
let old: crate::Guide = serde_json::from_str(r#"{"vertical": true, "pos": 5.0}"#).unwrap();
assert_eq!(old.layer, None);
@@ -267,7 +282,7 @@ fn random_selection(r: &mut u64, ids: &[NodeId]) -> Selection {
s.key = s.objects.get(below(r, s.objects.len() as u64) as usize).copied();
s.target = ids.get(below(r, ids.len() as u64) as usize).copied().filter(|_| below(r, 2) == 0);
s.slices = ids.iter().copied().take(below(r, 3) as usize).collect();
s.guides = vec![1, 0];
s.guides = vec![NodeId(1), NodeId(0)];
s
}
+75
View File
@@ -158,6 +158,8 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
];
/// Built-in library `id`, made once.
@@ -453,6 +455,71 @@ fn blends_transparency() -> Vec<GraphicStyle> {
]
}
/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look).
fn game_hud() -> Vec<GraphicStyle> {
vec![
style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]),
style(
"Mana Glow",
vec![F(fill("#3498db"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))],
),
style(
"Damage Flash",
vec![F(fill("#ff6b35"))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))],
),
style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]),
style(
"Coin Shine",
vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))],
vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))],
),
style(
"Boss Alert",
vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))],
),
]
}
/// Status Effects: buffs and debuffs for RPG/gamedev art (original, catalogue stylize effects only).
fn status_effects() -> Vec<GraphicStyle> {
let stealth = GraphicStyle {
opacity: 0.45,
blend: BlendMode::Normal,
..style("Stealth Fade", vec![F(fill("#7f8c8d")), S(stroke("#2c3e50", 1.0))], vec![])
};
vec![
style(
"Poison Tint",
vec![F(fill("#2ecc71"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 80.0, "blur": 6.0, "color": "#58d68d"}))],
),
style(
"Freeze Edge",
vec![F(fill("#aed6f1")), S(stroke("#5dade2", 2.0))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 70.0, "blur": 5.0, "color": "#d6eaf8", "source": "edge"}))],
),
style(
"Burn Aura",
vec![F(fill("#e67e22"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 8.0, "color": "#f39c12"}))],
),
style(
"Stun Pulse",
vec![F(fill("#f4d03f"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 7.0, "color": "#f7dc6f"}))],
),
stealth,
style(
"Shield Buff",
vec![F(fill("#85c1e9")), S(round("#2874a6", 2.0))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 70.0, "blur": 5.0, "color": "#5dade2"}))],
),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -475,6 +542,14 @@ mod tests {
}
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
assert!(builtin_style_library("nope").is_none());
let game = builtin_style_library("game-hud").unwrap();
assert_eq!(game.name, "Game HUD");
let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
let status = builtin_style_library("status-effects").unwrap();
assert_eq!(status.name, "Status Effects");
let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
}
#[test]
+11 -3
View File
@@ -195,9 +195,10 @@ impl Document {
/// The default name of a solid swatch: its values in its own colour model ("C=10 M=20 Y=30 K=0",
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
pub fn color_name(c: Color) -> String {
// Clamped first, so a conversion's tiny negative never reads "-0".
let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round();
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round();
// Clamped first, so a conversion's tiny negative never reads "-0". `clamp` keeps a -0.0, so
// `+ 0.0` turns it into 0.
let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() + 0.0;
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() + 0.0;
match c {
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
@@ -493,6 +494,13 @@ mod tests {
assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0");
}
#[test]
fn default_names_read_negative_zero_as_zero() {
assert_eq!(color_name(Color::Rgb { r: -0.0, g: 0.5, b: -0.0 }), "R=0 G=128 B=0");
assert_eq!(color_name(Color::Cmyk { c: -0.0, m: 0.2, y: 0.3, k: -0.0 }), "C=0 M=20 Y=30 K=0");
assert_eq!(color_name(Color::Gray { k: -0.0 }), "Gray K=0");
}
#[test]
fn free_swatch_names_match_naming_each_swatch_as_it_is_added() {
let (mut d, _, _) = doc();
+4 -2
View File
@@ -492,7 +492,8 @@ impl NineSliceMap {
/// [`Self::most_placed`] for a container placed by [`Self::container`].
fn most_container(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let own = self.most_mask(n, boxes, depth).saturating_add(1);
n.children().into_iter().flatten().fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
// As [`Self::container`] places it: a layer's ruler guides left out.
n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
}
/// [`Self::most_placed`] for the opacity mask of `n` as [`Self::place_mask`] places it: a
@@ -560,7 +561,8 @@ impl NineSliceMap {
let kids = out.children_mut().map(std::mem::take).unwrap_or_default();
out.transform(center, false);
if let Some(children) = out.children_mut() {
*children = kids.iter().map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
// A ruler guide of a layer is not art: it is not placed.
*children = kids.iter().filter(|c| !c.is_ruler_guide()).map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
}
self.place_mask(n, &mut out, boxes, depth);
out
+309
View File
@@ -5,6 +5,52 @@ mod lookups;
mod slices;
mod units;
/// A guide label's text is a layer color's name or `#rrggbb`, and reads back as the same color;
/// other spellings, an alpha part and a short form are not labels.
#[test]
fn guide_label_text_names_a_layer_color_or_rgb() {
for (i, (name, _)) in LAYER_COLORS.iter().enumerate() {
let c = LayerColor::Preset(u8::try_from(i).unwrap());
assert_eq!(c.label_text(), *name);
assert_eq!(LayerColor::from_label_text(name), Some(c));
}
let custom = LayerColor::Custom([0x0a, 0xbc, 0xff]);
assert_eq!(custom.label_text(), "#0abcff");
assert_eq!(LayerColor::from_label_text("#0ABCff"), Some(custom));
// A preset past the layer colors has no name: its text is the color it draws in.
let [r, g, b] = LayerColor::Preset(200).rgb();
assert_eq!(LayerColor::Preset(200).label_text(), format!("#{r:02x}{g:02x}{b:02x}"));
for bad in ["red", "Red ", "", "#", "#fff", "#0abcff00", "0abcff", "#0abcfg", "#0abcff"] {
assert_eq!(LayerColor::from_label_text(bad), None, "{bad:?}");
}
}
/// An artboard's guide label: none unless set, left out of the JSON when none, and a preset past
/// the layer colors reading as none.
#[test]
fn artboard_guide_label_defaults_and_skips_in_json() {
let mut a = Document::new(100.0, 100.0).artboards[0].clone();
assert_eq!(a.guide_label, None);
let plain = serde_json::to_value(&a).unwrap();
assert!(plain.get("guide_label").is_none(), "{plain}");
a.guide_label = Some(LayerColor::Custom([1, 2, 3]));
let v = serde_json::to_value(&a).unwrap();
assert_eq!(v["guide_label"], serde_json::json!({"Custom": [1, 2, 3]}));
assert_eq!(serde_json::from_value::<Artboard>(v).unwrap(), a);
let read = |label: serde_json::Value| {
let mut v = plain.clone();
v["guide_label"] = label;
serde_json::from_value::<Artboard>(v).map(|a| a.guide_label)
};
assert_eq!(read(serde_json::json!({"Preset": 26})).unwrap(), Some(LayerColor::Preset(26)));
assert_eq!(read(serde_json::json!({"Preset": 27})).unwrap(), None);
assert_eq!(read(serde_json::json!({"Preset": 255})).unwrap(), None);
assert_eq!(read(serde_json::Value::Null).unwrap(), None);
assert!(read(serde_json::json!({"Preset": -1})).is_err());
assert!(read(serde_json::json!({"Tint": 1})).is_err());
assert_eq!(serde_json::from_value::<Artboard>(plain).unwrap().guide_label, None, "older files have none");
}
/// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch
/// are binary fractions now, and the minor ticks between them stay binary too; every other
/// unit is still read in tenths.
@@ -45,6 +91,268 @@ fn an_inch_ruler_steps_in_binary_fractions() {
assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0));
}
/// Ruler guide nodes on a layer and a sublayer are not art: Select All, a layer's target circle,
/// the object count, the art's bounds, clicks, the marquee and a knockout layer's elements are
/// the same as without them, and transforming the layer leaves them where they are.
#[test]
fn ruler_guide_nodes_are_not_art() {
use crate::hit::{HitOptions, hit_test, marquee, objects_at};
let (mut d, a, b) = doc_with_rects();
let layer = d.layers[0].id;
let sub = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap();
let s1 = d.alloc_id();
d.insert(Some(sub), usize::MAX, Node::path(s1, shapes::rectangle(Rect::new(40.0, 0.0, 50.0, 10.0)), Appearance::default_art())).unwrap();
let opt = HitOptions::default();
let all = Rect::new(-100.0, -100.0, 700.0, 900.0);
let before = (
d.selectable_art(),
d.layers[0].layer_art(false),
d.node_count(),
d.art_bounds(),
marquee(&d, all, None, false),
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
);
let guide = |id, vertical, pos| Node::new(id, NodeKind::RulerGuide { vertical, pos, artboard: None });
let (g1, g2, g3) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
d.insert(Some(layer), usize::MAX, guide(g1, true, 5.0)).unwrap();
d.insert(Some(layer), usize::MAX, guide(g2, false, 5.0)).unwrap();
d.insert(Some(sub), usize::MAX, guide(g3, true, 45.0)).unwrap();
let after = (
d.selectable_art(),
d.layers[0].layer_art(false),
d.node_count(),
d.art_bounds(),
marquee(&d, all, None, false),
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
);
assert_eq!(after, before);
assert_eq!(after.0, [a, b, s1]);
for p in [Point::new(5.0, 300.0), Point::new(300.0, 5.0), Point::new(45.0, 300.0)] {
assert!(hit_test(&d, p, opt).is_none(), "nothing to click on the guide at {p:?}");
assert!(objects_at(&d, p, opt, None).is_empty());
}
let mut sel = Selection::default();
sel.set_target(&d, layer);
assert_eq!(sel.objects, [a, b, s1]);
let children = d.layers[0].children().unwrap().clone();
assert_eq!(Node::knockout_elements(&children).iter().map(|c| c.id).collect::<Vec<_>>(), [a, b, s1]);
assert!(d.node(g1).is_some_and(Node::is_ruler_guide) && d.node(g1).is_some_and(Node::is_guide));
assert_eq!(d.node(g1).map(Node::geometric_bounds), Some(None));
let mut moved = (*d.layers[0]).clone();
moved.transform(Affine::translate((10.0, 10.0)), true);
let g = moved.children().unwrap().iter().find(|c| c.id == g1).unwrap();
assert!(matches!(g.kind, NodeKind::RulerGuide { pos, .. } if pos == 5.0));
}
/// Art inserted or moved onto a layer goes below the layer's ruler guides, a ruler guide goes
/// among them, and a clipped layer whose art is gone does not clip by a guide.
#[test]
fn layer_art_stays_below_its_ruler_guides() {
let (mut d, a, b) = doc_with_rects();
let layer = d.layers[0].id;
let guide = |id, pos| Node::new(id, NodeKind::RulerGuide { vertical: true, pos, artboard: None });
let (g1, g2) = (d.alloc_id(), d.alloc_id());
d.insert(Some(layer), usize::MAX, guide(g1, 5.0)).unwrap();
// Asked for the bottom, a guide still goes above the art.
d.insert(Some(layer), 0, guide(g2, 7.0)).unwrap();
let ids = |d: &Document| d.layers[0].children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&d), [a, b, g2, g1]);
let c = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(c, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
assert_eq!(ids(&d), [a, b, c, g2, g1]);
d.move_node(a, Some(layer), usize::MAX).unwrap();
assert_eq!(ids(&d), [b, c, a, g2, g1]);
d.move_node(g1, Some(layer), 0).unwrap();
assert_eq!(ids(&d), [b, c, a, g1, g2]);
assert!(d.layer_object(g1).is_none());
assert_eq!(d.layer_object(a).map(|n| n.id), Some(a));
// A clipped layer clips by its first art object; with only guides left it clips nothing.
if let Some(NodeKind::Layer { clip, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
*clip = true;
}
assert!(d.node(layer).is_some_and(Node::clips));
for id in [a, b, c] {
d.remove(id).unwrap();
}
assert!(!d.node(layer).is_some_and(Node::clips));
// Reading a file that clips a layer by a path beyond the canvas empties the layer of its art
// only: its guides stay.
let far = d.alloc_id();
d.insert(Some(layer), 0, Node::path(far, shapes::rectangle(Rect::new(0.0, 0.0, 1e9, 10.0)), Appearance::default_art())).unwrap();
assert!(d.node(layer).is_some_and(Node::clips));
let gone = d.drop_beyond_canvas();
assert_eq!(gone.objects, 1);
assert_eq!(ids(&d), [g1, g2]);
}
/// `ruler_guides` keeps its list while the layers are unchanged, and lists again after any change
/// inside a layer, made in place or on a shared copy, and after layers are added, removed or
/// reordered.
#[test]
fn ruler_guides_follow_every_edit() {
let (mut d, _, _) = doc_with_rects();
let layer = d.layers[0].id;
let sub = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 5.0) });
let g2 = d.add_ruler_guide(&Guide { layer: Some(sub), ..Guide::new(false, 6.0) });
let line = |d: &Document| d.ruler_guides().iter().map(|g| (g.id, g.pos, g.hidden, g.layer)).collect::<Vec<_>>();
assert_eq!(line(&d), [(Some(g1), 5.0, false, Some(layer)), (Some(g2), 6.0, false, Some(sub))]);
// Changed in place: the document is the only holder of its layers.
assert!(d.edit_ruler_guide(g2, |g| g.pos = 9.0));
assert_eq!(line(&d)[1], (Some(g2), 9.0, false, Some(sub)));
d.node_mut(g1).unwrap().visible = false;
assert_eq!(line(&d)[0], (Some(g1), 5.0, true, Some(layer)));
// A copy shares the list until one of them changes.
let copy = d.clone();
assert_eq!(line(&copy), line(&d));
d.remove(g1).unwrap();
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub))]);
assert_eq!(line(&copy).len(), 2);
// A new layer with a guide, then the layers reordered and one removed.
let top = d.add_layer(None);
let g3 = d.add_ruler_guide(&Guide { layer: Some(top), ..Guide::new(true, 1.0) });
assert_eq!(line(&d).len(), 2);
d.layers.reverse();
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub)), (Some(g3), 1.0, false, Some(top))]);
d.layers.retain(|l| l.id != layer);
assert_eq!(line(&d), [(Some(g3), 1.0, false, Some(top))]);
}
#[test]
fn strip_ruler_guides_leaves_a_layers_art() {
let (mut d, a, b) = doc_with_rects();
let layer = d.layers[0].id;
let guide = |id| Node::new(id, NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None });
let sub = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
let (g1, g2) = (d.alloc_id(), d.alloc_id());
d.insert(Some(layer), usize::MAX, guide(g1)).unwrap();
d.insert(Some(sub), usize::MAX, guide(g2)).unwrap();
let mut n = (*d.layers[0]).clone();
assert!(n.holds_ruler_guides());
n.strip_ruler_guides();
assert!(!n.holds_ruler_guides());
let mut left = vec![];
n.walk(&mut |c| left.push(c.id));
assert_eq!(left, [layer, a, b, sub]);
// Other nodes hold none and are left as they are.
let mut p = d.node(a).unwrap().clone();
p.strip_ruler_guides();
assert_eq!(&p, d.node(a).unwrap());
}
/// The saved `guides` list becomes ruler guide nodes and is written back from them unchanged:
/// guides on a layer, a sublayer, no layer and a deleted layer, with an artboard guide, keep their
/// order, ids, names and their own lock and visibility; a saved id that another node has is
/// replaced; and the saved form of an older entry still reads.
#[test]
fn saved_guides_become_nodes_and_are_saved_back_the_same() {
let (mut d, a, _) = doc_with_rects();
let layer = d.layers[0].id;
let top = d.add_layer(Some("Top"));
let sub = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
let json = serde_json::json!([
{"vertical": true, "pos": 10.0, "layer": layer},
{"vertical": false, "pos": 20.0, "layer": sub, "artboard": 1},
{"vertical": true, "pos": 30.0},
{"vertical": false, "pos": 40.0, "layer": 9999},
{"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true},
{"vertical": true, "pos": 60.0, "layer": layer, "id": a},
]);
d.saved_guides = serde_json::from_value(json).unwrap();
let before = d.peek_next_id();
assert_eq!(d.guides_into_nodes(), 6);
assert!(d.saved_guides.is_empty());
let guides = d.ruler_guides();
let lines: Vec<(f64, Option<NodeId>)> = guides.iter().map(|g| (g.pos, g.layer)).collect();
// A guide on no layer, or on a deleted one, goes on the top visible, unlocked layer.
assert_eq!(lines[..4], [(50.0, Some(layer)), (10.0, Some(layer)), (20.0, Some(sub)), (30.0, Some(top))], "by id: the kept id first");
assert_eq!(lines[4..], [(40.0, Some(top)), (60.0, Some(layer))]);
assert_eq!(guides[0].id, Some(NodeId(500)));
assert!(guides[1..].iter().all(|g| g.id.unwrap().0 > 500), "new ids start above a kept one");
assert_ne!(guides[5].id, Some(a), "an id another object has is not reused");
assert!(d.peek_next_id() > 500 && before <= 500);
let edge = d.node(NodeId(500)).unwrap();
assert!(edge.locked && !edge.visible && edge.name.as_deref() == Some("Edge"));
assert_eq!(guides[2].artboard, Some(1));
// Each layer's guides sit at its top, above its art and its sublayer.
let kids: Vec<bool> = d.node(layer).unwrap().children().unwrap().iter().map(|c| c.is_ruler_guide()).collect();
assert_eq!(kids, [false, false, false, true, true, true]);
assert_eq!(d.guides_into_nodes(), 0, "a second run does nothing");
// Saved back: the guides leave the layers and the list names each one's layer and id.
let mut saved = d.clone();
saved.guides_to_saved();
assert!(saved.ruler_guides().is_empty());
assert_eq!(saved.node_count(), d.node_count());
assert_eq!(saved.saved_guides, guides);
let json = serde_json::to_value(&saved).unwrap();
assert_eq!(json["guides"].as_array().map(Vec::len), Some(6));
assert_eq!(
json["guides"][0],
serde_json::json!({"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true})
);
// Read again, the same guides come back with the same ids.
let mut back: Document = serde_json::from_value(json).unwrap();
back.fix_next_id();
back.guides_into_nodes();
assert_eq!(back.ruler_guides(), guides);
// An older reader of the list ignores the new fields.
#[derive(serde::Deserialize, PartialEq, Debug)]
struct Old {
vertical: bool,
pos: f64,
#[serde(default)]
artboard: Option<u32>,
#[serde(default)]
layer: Option<NodeId>,
}
let old: Vec<Old> = serde_json::from_value(serde_json::to_value(&saved.saved_guides).unwrap()).unwrap();
assert_eq!(old[0], Old { vertical: true, pos: 50.0, artboard: None, layer: Some(layer) });
// A document with no layer gets a "Layer 1" for its guides.
let mut empty = Document::new(10.0, 10.0);
empty.layers.clear();
empty.saved_guides = vec![Guide::new(true, 1.0)];
assert_eq!(empty.guides_into_nodes(), 1);
assert_eq!(empty.layers.len(), 1);
assert_eq!(empty.layers[0].name.as_deref(), Some("Layer 1"));
assert_eq!(empty.ruler_guides().len(), 1);
}
/// Editing, deleting and the artboard moves of ruler guide nodes, and the selection keeping step.
#[test]
fn ruler_guide_nodes_are_edited_by_id() {
let (mut d, a, _) = doc_with_rects();
let layer = d.layers[0].id;
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 10.0) });
let g2 = d.add_ruler_guide(&Guide { artboard: Some(1), ..Guide::new(false, 20.0) });
assert!(d.edit_ruler_guide(g1, |g| g.pos = 15.0));
assert!(!d.edit_ruler_guide(a, |g| g.pos = 15.0), "not a guide");
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0));
d.move_artboard_guides(1, Vec2::new(5.0, 7.0));
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(27.0));
d.map_artboard_guides(1, Affine::scale(2.0));
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(54.0));
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0), "a canvas guide stays");
d.copy_artboard_guides(1, 2, Vec2::new(0.0, 100.0));
let copies: Vec<(f64, Option<u32>)> = d.ruler_guides().iter().filter(|g| g.artboard == Some(2)).map(|g| (g.pos, g.artboard)).collect();
assert_eq!(copies, [(154.0, Some(2))]);
let mut sel = Selection::default();
sel.set_guides([g1, g2]);
sel.key_guide = Some(g2);
assert_eq!(d.retain_guides(&mut sel, |g| g.artboard.is_none()), 2);
assert_eq!(sel.guides, [g1]);
assert_eq!(sel.key_guide, None);
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(g1)]);
assert_eq!(d.retain_guides(&mut sel, |_| true), 0);
}
fn doc_with_rects() -> (Document, NodeId, NodeId) {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
@@ -146,6 +454,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
let rect = |d: &mut Document, r: Rect, appearance: Appearance| {
let id = d.alloc_id();
+6
View File
@@ -77,6 +77,12 @@ pub struct TextObject {
/// them up round the inside.
#[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")]
pub path_spacing: f64,
/// Type › Dynamic Text (type on a path only): the layout scales the text by one factor so it
/// fills the span between its start and end brackets, and fits it again after each edit. The
/// stored sizes keep their proportions; the layout's `fit_scale` is the factor drawn. Off for new
/// type and for documents from before it, and saved only when on.
#[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")]
pub dynamic_text: bool,
/// Wrap objects above this area type, resolved by the engine after each edit (text space).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub wrap: Vec<WrapShape>,
+2 -2
View File
@@ -22,10 +22,10 @@ pub struct CharStyle {
/// Leading in points; None = Auto (120% of size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub leading: Option<f64>,
/// Tracking in 1/1000 em.
/// Tracking in 1/1000 em; in horizontal type, of the em as [`Self::h_scale`] draws it.
#[serde(default)]
pub tracking: f64,
/// Manual pair spacing in 1/1000 em; None uses the automatic mode.
/// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kerning: Option<f64>,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
+19
View File
@@ -89,6 +89,7 @@ impl TextObject {
path_effect: PathEffect::default(),
path_align: PathAlign::default(),
path_spacing: 0.0,
dynamic_text: false,
wrap: Vec::new(),
optical_margin: false,
anti_alias: TypeAntiAlias::Sharp,
@@ -367,6 +368,24 @@ impl TextObject {
pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool {
matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d))
}
/// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a
/// path's path to `pos` in document space, as a path's anchor takes it
/// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a
/// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space,
/// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
*a = drawn.transform(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+14
View File
@@ -1,5 +1,19 @@
use super::*;
/// Dynamic Text is off for new type and for type saved before it, and saved only when on.
#[test]
fn dynamic_text_is_saved_only_when_on() {
let t = TextObject::point(Point::ZERO, "Hi", CharStyle::default());
assert!(!t.dynamic_text);
let off = serde_json::to_value(&t).unwrap();
assert!(off.get("dynamicText").is_none());
assert!(!serde_json::from_value::<TextObject>(off).unwrap().dynamic_text);
let on = TextObject { dynamic_text: true, ..t };
let saved = serde_json::to_value(&on).unwrap();
assert_eq!(saved["dynamicText"], true);
assert!(serde_json::from_value::<TextObject>(saved).unwrap().dynamic_text);
}
/// Character Direction is saved only when set, and styles written before it existed read as
/// Default.
#[test]
+5 -3
View File
@@ -468,12 +468,14 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images
}
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art.
pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> {
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>) -> Option<Node> {
let art;
let src = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
let symbol = symbol_art
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)));
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
&art
}
+7 -6
View File
@@ -107,12 +107,13 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind {
/// `n` with its geometry effects evaluated (`None` = unchanged).
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
if !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
// A ruler guide draws nothing and stays as it is, last in its layer.
if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
return None;
}
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
if has_adjustment(n)
&& let Some(m) = adjust_in_document(d, n)
&& let Some(m) = adjust_in_document(d, n, None)
{
return Some(bake_node(d, &m).unwrap_or(m));
}
@@ -124,7 +125,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
return Some(bake_pieces(d, m));
}
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -395,7 +396,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
if !kept {
return None;
}
reshape_leaves(&mut m, &fx, Some(d));
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
m.appearance.items.clear();
m.appearance.contents_index = None;
@@ -481,7 +482,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
if let Some(m) = crate::revolve::expand_revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -551,7 +552,7 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
/// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to
/// outline nor a geometry effect, so bending first changes nothing.
pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
return Some(m);
}
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
+17 -3
View File
@@ -26,6 +26,10 @@ pub struct GeomContext<'a> {
/// The document that the swatches and patterns named by a live-effect plug-in that paints its
/// pieces are looked up in. Without one, a result that names any is refused.
pub doc: Option<&'a Document>,
/// The object, fill or stroke and effect index a deferred live-effect plug-in is listed by
/// ([`vectorcraft_plugins::deferred`]). When `None`, it is the object `seed` names, `item` and
/// the effect's index in the list being applied.
pub stage: Option<vectorcraft_plugins::deferred::Stage>,
}
impl<'a> GeomContext<'a> {
@@ -36,7 +40,17 @@ impl<'a> GeomContext<'a> {
_ => FillRule::NonZero,
};
let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0);
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None }
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None, stage: None }
}
/// The context of effect `e`, one of `list`: unless [`Self::stage`] is set, a live-effect
/// plug-in there is listed by `e`'s index in `list`.
pub(crate) fn at(self, list: &[Effect], e: &Effect) -> Self {
let stage = self.stage.or_else(|| {
let effect = list.iter().position(|x| std::ptr::eq(x, e))?;
Some(vectorcraft_plugins::deferred::Stage { object: self.seed, effect, item: self.item })
});
Self { stage, ..self }
}
/// The context of the effects on `item`, one of the same object's appearance items: a
@@ -335,7 +349,7 @@ pub(crate) fn apply_geometry_carrying_within(
}
let p = merged_params(&e.id, &e.params);
let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path)));
if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) {
if let Some(next) = apply_one(&e.id, &p, &cur, b, &ctx.at(effects, e), limit) {
if let Some(c) = carry.as_deref_mut() {
c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed));
}
@@ -377,7 +391,7 @@ fn builds_within(id: &str) -> bool {
fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData {
use util::{join, num};
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item };
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage };
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
}
match id {
+20 -4
View File
@@ -209,7 +209,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
Some(area) => Some(reshaped(&area, n, doc)),
None => {
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes follow the effects as its members do.
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
@@ -225,7 +225,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
carry.apply(&mut art.appearance);
@@ -455,6 +455,17 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
return None;
}
let source: &[Arc<Node>] = group.children()?;
// A layer's ruler guides take no part in the operation: they stay above its result.
let art = Node::guide_run_start(source);
if art < source.len() {
let mut without = group.clone();
if let Some(ch) = without.children_mut() {
ch.truncate(art);
}
let mut out = pathfinder_children(doc, &without, hook)?;
out.extend(source.iter().skip(art).cloned());
return Some(out);
}
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
match compound_shape_area(doc, group, hook) {
@@ -727,9 +738,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
return None;
}
let mut m = n.clone();
// A layer's ruler guides take no part: they go back above the evaluated art at the end.
let guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default();
if pathfinder {
let hook = |c: &Node| crate::outline_object(doc, c);
let result = pathfinder_children(doc, n, Some(&hook)).unwrap_or_default();
let result = pathfinder_children(doc, &m, Some(&hook)).unwrap_or_default();
if let Some(ch) = m.children_mut() {
*ch = result;
}
@@ -738,7 +751,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
if !fx.is_empty() {
m = crate::reshape::outlined_members(doc, &m);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
@@ -762,6 +775,9 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
m.appearance.items.clear();
m.appearance.contents_index = None;
if let Some(ch) = m.children_mut() {
ch.extend(guides);
}
Some(m)
}
+42
View File
@@ -820,3 +820,45 @@ fn nested_compound_shapes_take_part_as_their_area() {
assert!((area(&out[0]) - 50.0).abs() < 0.01);
assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape");
}
/// The ruler guides of a layer with a Pathfinder effect, a Transform effect that copies its art, or
/// fills and strokes of its own take no part: they stay last in the layer, once and unchanged.
#[test]
fn a_layers_ruler_guides_stay_last_through_its_effects() {
use vectorcraft_doc::LayerColor;
let guide = |id, pos| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos, artboard: None }));
let layer = |effect: &str, params: serde_json::Value| {
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), guide(20, 3.0), guide(21, 8.0)];
}
l.appearance.effects.push(Effect { id: effect.into(), params, visible: true });
l
};
let tail = |n: &Node| {
let ch = n.children().unwrap();
assert_eq!(ch.iter().filter(|c| c.is_ruler_guide()).count(), 2, "each guide once");
ch.iter().rev().take(2).map(|c| c.kind.clone()).collect::<Vec<_>>()
};
let guides = vec![guide(21, 8.0).kind.clone(), guide(20, 3.0).kind.clone()];
let add = layer("pathfinder.add", serde_json::json!({}));
let out = pathfinder_children(None, &add, None).unwrap();
assert_eq!(out.len(), 3, "the united area, then the two guides");
assert!((area(&out[0]) - 150.0).abs() < 0.01);
assert!(out[1].is_ruler_guide() && out[2].is_ruler_guide());
assert_eq!(tail(&evaluate_container(None, &add).unwrap()), guides);
let copies = layer("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}));
let art = evaluate_container(None, &copies).unwrap();
assert_eq!(tail(&art), guides);
assert_eq!(art.children().unwrap().len(), 5, "three groups of the art, then the two guides");
let mut art = copies.clone();
crate::reshape::reshape_leaves(&mut art, &copies.appearance.effects.iter().collect::<Vec<_>>(), &copies.appearance.effects, None);
assert_eq!(tail(&art), guides);
assert_eq!(art.children().unwrap().len(), 5, "reshaped as members too");
let mut painted = layer("distort.transform", serde_json::json!({"moveH": 30}));
painted.appearance.items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items;
assert_eq!(tail(&evaluate_container(None, &painted).unwrap()), guides);
}
+4 -3
View File
@@ -83,11 +83,12 @@ pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in};
pub use solids::{
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as,
validate_solid, validate_three_d, validate_three_d_at, validate_three_d_params, view_options,
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in,
three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at,
validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+3 -2
View File
@@ -161,7 +161,8 @@ pub fn any_plugin_paints_output() -> bool {
vectorcraft_plugins::registry::list().iter().any(|p| vectorcraft_plugins::effect::paints_output(&p.manifest().id))
}
/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed.
/// Changes whenever a plug-in is installed or removed (the registry's revision), and when deferred
/// live-effect plug-in stages give results ([`vectorcraft_plugins::deferred::revision`]).
pub fn plugin_revision() -> u64 {
vectorcraft_plugins::registry::revision()
vectorcraft_plugins::registry::revision() ^ vectorcraft_plugins::deferred::revision().rotate_left(32)
}
+57 -30
View File
@@ -573,7 +573,7 @@ fn as_art_opts(
}
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
};
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart, paint_doc);
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
if apart {
hoist_copies(&mut art);
}
@@ -636,21 +636,22 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
/// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns
/// that live-effect plug-ins painting their pieces name are looked up in `doc`
/// ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc);
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
}
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
/// strokes) follow the effects ([`crate::Carry`]).
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc)
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
}
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
#[cfg(test)]
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, budget, false, doc)
reshape_leaves_apart(art, fx, &[], budget, false, doc)
}
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
@@ -669,12 +670,15 @@ fn hoist_copies(art: &mut Node) {
}
}
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
/// `apart`, a Transform effect's copies of each path are objects
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
/// `owner` does not hold it.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
@@ -693,6 +697,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
});
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
let style_safe = leaves_safe && !art_stroke;
let listed = fx;
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
let fx = opt_fx.as_slice();
let seed = art.id.0;
@@ -703,12 +708,15 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
for e in fx {
let Some(bounds) = art.geometric_bounds() else { break };
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
if let Some(plugin) = painted_plugin(e) {
let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
for_each_leaf(art, &mut |leaf| {
let Some((path, _)) = leaf_geometry(leaf) else { return };
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc) {
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc, at) {
used = used.minus(before).plus(made);
}
});
@@ -778,7 +786,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
return;
}
}
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else {
let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
kept_ids.insert(leaf.id);
return;
};
@@ -965,7 +974,7 @@ fn effects_cost(leaf: &Node, path: &PathData) -> Budget {
/// Remove the guides anywhere under `n`.
fn without_guides(n: &mut Node) {
let Some(children) = n.children_mut() else { return };
children.retain(|c| !matches!(c.kind, NodeKind::Path { guide: true, .. }));
children.retain(|c| !c.is_guide());
children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c)));
}
@@ -975,7 +984,9 @@ fn without_guides(n: &mut Node) {
/// [`crate::distort::MAX_COPY_OBJECTS`] nodes in all, the art of opacity masks counted. Returns what
/// the art costs after.
fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
let Some(members) = art.children().cloned() else { return art_cost(art) };
let Some(mut members) = art.children().cloned() else { return art_cost(art) };
// A layer's ruler guides are not copied: they stay above the copies, once.
let guides = members.split_off(Node::guide_run_start(&members));
let original = Node::group(art.id, members);
let mut made = copy_cost(&original);
let mut drawn = original.clone();
@@ -1005,6 +1016,7 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::
// The last copy is the lowest.
placements.reverse();
placements.push(Arc::new(original));
placements.extend(guides);
if let Some(children) = art.children_mut() {
*children = placements;
}
@@ -1056,10 +1068,18 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
/// refused, or they would pass `budget`.
fn paint_leaf(leaf: &mut Node, plugin: &str, params: &serde_json::Value, bounds: Rect, budget: Budget, doc: Option<&Document>) -> Option<Budget> {
/// refused, or they would pass `budget`. A deferred run is listed by `at`.
fn paint_leaf(
leaf: &mut Node,
plugin: &str,
params: &serde_json::Value,
bounds: Rect,
budget: Budget,
doc: Option<&Document>,
at: Option<vectorcraft_plugins::deferred::Stage>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
@@ -1097,18 +1117,18 @@ fn piece_cost(path: &PathData) -> Budget {
/// other fills and strokes; one that gives none keeps the leaf's. Returns
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
/// `budget`.
/// `budget`. A deferred run is listed by `at`.
fn paint_piece(
leaf: &mut Node,
item: &AppearanceItem,
plugin: &str,
params: &serde_json::Value,
(plugin, params): (&str, &serde_json::Value),
bounds: Rect,
budget: Budget,
doc: Option<&Document>,
at: Option<vectorcraft_plugins::deferred::Stage>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0) };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
@@ -1241,6 +1261,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
};
let Some(tb) = g.bounds() else { continue };
let params = merged_params(&fx[at].id, &fx[at].params);
// Where each effect the piece keeps sits among the item's effects.
let kept: Vec<usize> = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect();
if let Some(plugin) = painted_plugin(&fx[at]) {
let mut it = item.clone();
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
@@ -1250,7 +1272,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
carry.apply(&mut one);
}
let it = one.items.pop().unwrap_or(it);
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i) };
let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) };
let painted = vectorcraft_plugins::effect::apply_painted(plugin, &params, &g, tb, rule, paints, doc)
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
@@ -1264,7 +1287,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, ctx.seed, limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
@@ -1281,7 +1304,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
set_geometry(&mut p, g.clone(), rule);
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
*used = used.plus(made);
transform_piece(&mut p, ctx.seed, limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -1297,14 +1320,17 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and
/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`.
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: Option<&Document>) {
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. `(seed, source,
/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the
/// piece was made from, and the index among that item's effects of each effect the piece kept,
/// which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) {
let mut count = 0;
for_each_leaf(p, &mut |l| {
if let Some(item) = l.appearance.items.first() {
@@ -1320,8 +1346,9 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc:
// What the other paths leave of the budget.
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
if let Some(plugin) = painted_plugin(&e) {
if let Some(made) = paint_piece(leaf, &item, plugin, &merged_params(&e.id, &e.params), bounds, room, doc) {
if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) {
*used = used.minus(before).plus(made);
}
return;
@@ -1340,7 +1367,7 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc:
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
};
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc };
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) };
let mut carry = crate::Carry::default();
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
*used = used.minus(before).plus(Budget::of(&out));
+90 -23
View File
@@ -3,11 +3,11 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, solid_paints, union_bounds};
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -25,17 +25,33 @@ const MAX_OVERLAP_TESTS: usize = 1 << 22;
/// The width of the stroke around each face that covers the seams between faces.
const SEAM_WIDTH: f64 = 0.75;
/// About the bytes one copy of `paint` takes.
/// About the bytes one copy of `paint` takes, with the strings it owns (swatch and pattern names).
fn paint_bytes(paint: &Paint) -> usize {
use std::mem::size_of;
use vectorcraft_doc::color::{FreeformPoint, GradientStop};
let own = size_of::<Paint>();
let Paint::Gradient(g) = paint else { return own };
let freeform = g
.freeform
.as_ref()
.map_or(0, |f| f.points.len() * size_of::<FreeformPoint>() + f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>());
own + size_of::<vectorcraft_doc::color::GradientPaint>() + g.gradient.stops.len() * size_of::<GradientStop>() + freeform
let name = |s: &Option<String>| s.as_ref().map_or(0, String::len);
let g = match paint {
Paint::Solid { swatch, .. } => return own + name(swatch),
Paint::Pattern { pattern, .. } => return own + pattern.len(),
Paint::Gradient(g) => g,
_ => return own,
};
let freeform = g.freeform.as_ref().map_or(0, |f| {
// Each line is a Vec: its header too, not only its indices.
f.points.len() * size_of::<FreeformPoint>()
+ f.lines.len() * size_of::<Vec<usize>>()
+ f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>()
});
let stops: usize = g.gradient.stops.iter().map(|s| size_of::<GradientStop>() + name(&s.swatch)).sum();
own + size_of::<vectorcraft_doc::color::GradientPaint>() + name(&g.swatch) + stops + freeform
}
/// Add `copies` copies of `paint` to the running byte total `used`; whether it still fits within
/// [`MAX_PAINT_COPIES`] (for the solid surfaces, whose items' copies count together).
pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) -> bool {
*used = used.saturating_add(copies.saturating_mul(paint_bytes(paint)));
*used <= MAX_PAINT_COPIES
}
fn visible(fx: &[Effect]) -> bool {
@@ -75,7 +91,14 @@ pub fn revolve_options(p: &Value) -> Revolve {
/// Validate before a command mutates the document. Loading external files is still bounded
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
validate_revolve_in(None, n, p)
}
/// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now.
pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> {
validate_revolve_params(p)?;
let n = &*resolve_for(doc, n, "Revolve", false)?;
let effects = &n.appearance.effects;
// The profile is measured before the object's one Revolve, hidden or shown.
let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects);
@@ -318,12 +341,26 @@ fn paint_of(item: &AppearanceItem) -> (Paint, f32, vectorcraft_doc::color::Blend
/// Evaluated art keeps the source's identity and transparency. Each item's opacity belongs
/// to its entire surface, not to each face, so overlapping faces don't accumulate alpha.
pub fn revolve_art(n: &Node) -> Option<Node> {
art(n, false)
revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path. The shared command and UI remain unchanged.
/// [`revolve_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
/// resolved.
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, false)
}
/// [`expand_revolve_art_in`] without a document.
#[cfg(test)]
pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
art(n, true)
expand_revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
/// command and UI remain unchanged.
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, true)
}
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
@@ -388,10 +425,11 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
Ok(out)
}
fn art(n: &Node, expand: bool) -> Option<Node> {
fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if !has_revolve(n) {
return None;
}
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
if is_container(n) {
return group_art(n, expand);
}
@@ -441,22 +479,19 @@ fn art(n: &Node, expand: bool) -> Option<Node> {
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
/// opacity and blending mode, so each applies once, to the faces it holds together.
fn scoped(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
/// opacity, blending mode and opacity mask, so each applies once, to the faces it holds together.
pub(crate) fn scoped<'a>(id: NodeId, surfaces: Vec<(&'a [Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<&Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
if let Some(scope) = scope {
let mut group = Node::group(id, scoped(id, std::mem::take(run), level + 1));
group.opacity = scope.opacity;
group.blend = scope.blend;
out.push(Arc::new(group));
out.push(Arc::new(scope.group(id, scoped(id, std::mem::take(run), level + 1))));
}
}
let mut out = vec![];
let mut run = vec![];
let mut scope = None;
let mut scope: Option<&'a Scope> = None;
for (scopes, s) in surfaces {
let at = scopes.get(level).copied();
if at.map(|a| a.key) != scope.map(|s: Scope| s.key) {
let at = scopes.get(level);
if at.map(|a| a.key) != scope.map(|s| s.key) {
close(id, &mut run, scope, level, &mut out);
scope = at;
}
@@ -1143,6 +1178,38 @@ mod tests {
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
}
#[test]
fn the_art_of_symbol_instances_and_blends_shares_the_budget_of_paint_copies() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::{BlendSpacing, BlendSpec, Symbol};
let plain = member(1, 0.0);
let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") };
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
let painted = |id: u64, x: f64| {
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut node = (*member(id, x)).clone();
node.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
Arc::new(node)
};
let mut d = Document::new(500.0, 500.0);
d.symbols.push(Symbol { dynamic: false, name: "P".into(), art: painted(0, 0.0) });
let instance = |id: u64| Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "P".into(), xf: Affine::IDENTITY }));
// One instance's art fits; two in the same place, each of whose surfaces fits alone, pass
// the budget together, as two paths would.
assert_eq!(validate_revolve_in(Some(&d), &group_with(json!({}), vec![instance(1)]), &json!({})), Ok(()));
let two = group_with(json!({}), vec![instance(1), instance(2)]);
let refused = validate_revolve_in(Some(&d), &two, &json!({})).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
assert_eq!(revolve_art_in(Some(&d), &two), None, "past the budget the source draws");
// A blend's keys and step count together too.
let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() });
let blend = Arc::new(Node::new(NodeId(3), NodeKind::Blend { children: vec![painted(4, 0.0), painted(5, 0.0)], spec }));
let refused = validate_revolve_in(Some(&d), &group_with(json!({}), vec![blend]), &json!({})).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
}
#[test]
fn the_fills_of_one_object_share_the_budget_of_paint_copies() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
+206 -59
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
@@ -17,6 +17,9 @@ use crate::{GeomContext, apply_geometry_with, is_geometry};
mod classic;
pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading};
mod source;
pub(crate) use source::{resolve, resolve_for};
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
@@ -198,10 +201,22 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
Ok(())
}
/// The name an error gives 3D effect `id`.
pub(crate) fn label_of(id: &str) -> &'static str {
crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'))
}
/// Validate before a command changes the document; the evaluator bounds loaded files too.
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
validate_solid_in(None, n, id, p)
}
/// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// build from the art they show ([`resolve`]).
pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
validate_solid_params(id, p)?;
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
let label = label_of(id);
let n = &*source::resolve_for(doc, n, label, id == ROTATE)?;
if is_container(n) {
let shapes = members(n, label)?;
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
@@ -213,31 +228,85 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
}
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
/// (empty, or only spaces) is a shape without anchors, and any other object is the wrong kind.
/// (empty, or only spaces) is a shape without anchors, an image is traced first, and any other
/// object is the wrong kind.
pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> {
profile(n).ok_or_else(|| {
if matches!(n.kind, NodeKind::Text(_)) {
format!("{label} requires a shape with at least two anchors")
} else {
format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.")
}
profile(n).ok_or_else(|| match n.kind {
NodeKind::Text(_) => format!("{label} requires a shape with at least two anchors"),
NodeKind::Image(_) => source::image_refusal(label),
_ => format!("{label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first."),
})
}
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending
/// mode is not Normal. The members of one group share its `key`.
#[derive(Clone, Copy, Debug, PartialEq)]
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100%, whose blending
/// mode is not Normal or that has an opacity mask. The members of one group share its `key`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Scope {
pub(crate) key: usize,
pub(crate) opacity: f32,
pub(crate) blend: BlendMode,
/// The object's opacity mask, unless it has none or it is disabled. The mask art is in
/// document coordinates, as the solids' faces are.
pub(crate) mask: Option<Arc<OpacityMask>>,
}
impl Scope {
/// The scope of `n` with key `key`, or `None` when `n` is opaque, blends normally and has no
/// opacity mask that applies.
fn of(n: &Node, key: usize) -> Option<Self> {
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled);
(n.opacity < 1.0 || n.blend != BlendMode::Normal || mask.is_some()).then(|| Scope {
key,
opacity: n.opacity,
blend: n.blend,
mask: mask.map(|m| Arc::new(m.clone())),
})
}
/// A group of `children` with id `id` and this scope's opacity, blending mode and opacity mask.
pub(crate) fn group(&self, id: NodeId, children: Vec<Arc<Node>>) -> Node {
let mut group = Node::group(id, children);
group.opacity = self.opacity;
group.blend = self.blend;
if let Some(mask) = &self.mask {
group.extras_mut().mask = Some(Box::new((**mask).clone()));
}
group
}
}
/// Does `scope` draw its members' faces other than plainly: does it have an opacity mask or a
/// blending mode other than Normal?
fn composites(scope: &Scope) -> bool {
scope.mask.is_some() || scope.blend != BlendMode::Normal
}
/// `surfaces`, each with the scopes of the member it was built from, in groups with the opacity
/// masks and blending modes of those scopes, so each applies to the faces of the members it holds.
/// The members' opacity is already in their paint ([`Profile::opacity`]), so these groups are
/// opaque.
fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> {
let masks: Vec<(Vec<Scope>, Arc<Node>)> = surfaces
.into_iter()
.map(|(scopes, s)| {
let masks = scopes.iter().filter(|s| composites(s)).map(|s| Scope { opacity: 1.0, ..s.clone() }).collect();
(masks, s)
})
.collect();
crate::revolve::scoped(id, masks.iter().map(|(scopes, s)| (scopes.as_slice(), s.clone())).collect(), 0)
}
/// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal?
fn has_masks(shapes: &[Profile]) -> bool {
shapes.iter().any(|s| s.scopes.iter().any(composites))
}
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
/// it, and the opacity of the objects it is in multiplied together (1 for the object with the
/// effect itself). `scopes` lists those objects with transparency of their own ([`Scope`]), from
/// the outermost group down to the member itself (none for the object itself). Group Revolve
/// applies each once, to the surfaces of the members it holds together.
/// effect itself). `scopes` lists those objects with transparency or an opacity mask of their own
/// ([`Scope`]), from the outermost group down to the member itself (none for the object itself).
/// Group Revolve applies each once, to the surfaces of the members it holds together; the other 3D
/// effects apply each opacity mask that way.
pub(crate) struct Profile {
pub(crate) path: PathData,
pub(crate) rule: FillRule,
@@ -264,8 +333,10 @@ const MAX_MEMBERS: usize = 4096;
const MAX_MESH_TRIANGLES: usize = 2_000_000;
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
/// compound path and type in it, at any depth of its groups, each through its own geometry
/// effects and painted with its own fills and strokes. Like the effect on a group in the
/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends
/// and clipping groups), at any depth of its groups, each through its own geometry
/// effects, then those of each group it is in (on that group's members together), and painted
/// with its own fills and strokes. Like the effect on a group in the
/// reference app, they turn about one shared axis (the centre of their bounds together) rather
/// than each about its own. An error names what the group holds that can't become a solid.
pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
@@ -277,28 +348,33 @@ pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
fn walk(n: &Node, opacity: f32, scopes: &[Scope], w: &mut Walk) -> Result<(), String> {
let label = w.label;
for c in n.children().into_iter().flatten() {
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
if !c.visible || c.is_guide() {
continue;
}
let opacity = opacity * c.opacity;
let mut scopes = scopes.to_vec();
if c.blend != BlendMode::Normal || c.opacity < 1.0 {
if let Some(scope) = Scope::of(c, w.keys + 1) {
w.keys += 1;
scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend });
scopes.push(scope);
}
if is_container(c) {
let first = w.out.len();
walk(c, opacity, &scopes, w)?;
// The group's own geometry effects reshape its members together, as it is drawn.
if let Some(shapes) = w.out.get_mut(first..) {
reshape_members(c, &c.appearance.effects, shapes);
}
continue;
}
let Some((path, rule)) = profile(c) else {
let what = match &c.kind {
NodeKind::Group { clip: true, .. } => "clipping groups",
NodeKind::Image(_) => "images",
NodeKind::SymbolInstance { .. } => "symbol instances",
NodeKind::Image(_) => return Err(source::image_refusal(label)),
NodeKind::Path { clipping: true, .. } => "clipping paths",
_ => "objects other than paths, compound paths and type",
_ => "other objects",
};
return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first."));
return Err(format!(
"{label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first."
));
};
if w.out.len() >= MAX_MEMBERS {
return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects"));
@@ -319,7 +395,12 @@ pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
/// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by
/// [`validate_solid`].
pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) }
validate_three_d_in(None, n, id, p)
}
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) }
}
/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of
@@ -328,10 +409,18 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
/// item's geometry effects before it, together with the object's other items that carry a Revolve.
/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws.
pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
validate_three_d_at_in(None, n, id, p, at)
}
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
match at {
Some(_) if is_container(n) => Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()),
Some(_) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
}
Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index),
_ => validate_three_d(n, id, p),
_ => validate_three_d_in(doc, n, id, p),
}
}
@@ -402,6 +491,21 @@ fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
}
}
/// `item`'s paint, borrowed (for checks that must not copy it).
fn paint_ref(item: &AppearanceItem) -> &Paint {
match item {
AppearanceItem::Fill(f) => &f.paint,
AppearanceItem::Stroke(s) => &s.paint,
}
}
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
/// lights give each facet derived paints (`lighting::solid_surface`).
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
facets.len().saturating_mul(if derived { 6 } else { 2 })
}
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
/// stroke's outline (whose contours nest as its holes do) for a stroke.
fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, FillRule) {
@@ -411,22 +515,26 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
}
}
/// One part of [`solid_parts`]: a fill or stroke, its shape's opacity, the region it paints and its
/// fill rule, and its shape's scopes.
type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]);
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
/// a group's members from the back up, each with its shape's opacity and the region it paints.
/// The solids share the bounds of all their parts (`fallback` when none has any): one center to
/// turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32, PathData, FillRule)>, Rect) {
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
/// one center to turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
let parts: Vec<Part> = shapes
.iter()
.flat_map(|s| {
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
let (area, rule) = region(&s.path, s.rule, i);
(i, s.opacity, area, rule)
(i, s.opacity, area, rule, s.scopes.as_slice())
})
})
.collect();
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
let bounds = parts.iter().filter_map(|(_, _, area, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
(parts, bounds)
}
@@ -449,12 +557,17 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance);
/// otherwise each solid is a surface of its own, in that order.
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
/// ([`masked`]).
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE;
let colored = !classic && view_options(&p).has_colored_lights();
let masks = has_masks(shapes);
// The paint copies of every solid together: past the allowance the source path is drawn.
let mut paint_bytes = 0usize;
if fx.id == ROTATE {
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
@@ -464,24 +577,28 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
out.push(Arc::new(surface(n, f, &paint, opacity, blend, colored)));
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
return None;
}
out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored))));
}
}
return Some(out);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
let built = if fx.id == INFLATE {
// One eye for every puff, as far away as the highest needs.
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
} else {
parts.iter().map(|(_, _, area, rule)| facets(&fx.id, area, *rule, bounds, &p)).collect()
parts.iter().map(|(_, _, area, rule, _)| facets(&fx.id, area, *rule, bounds, &p)).collect()
};
let mut solids = vec![];
for ((item, opacity, _, _), f) in parts.iter().zip(built) {
for ((item, opacity, _, _, scopes), f) in parts.iter().zip(built) {
let item: &AppearanceItem = item;
match f {
Ok(f) => solids.push((item, *opacity, f)),
Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None,
Ok(f) => solids.push((item, *opacity, *scopes, f)),
// A stroke's outline past the limits is left out; the fill's solid still draws.
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
// A loaded file or a shape edited past the limits keeps drawing its source path
@@ -493,30 +610,33 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
if solids.is_empty() {
return None;
}
let opaque = solids.iter().all(|(item, member, _)| {
let opaque = solids.iter().all(|(item, member, _, _)| {
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let surfaces: Vec<(Vec<f64>, Node)> = solids
let surfaces: Vec<(Vec<f64>, Node, &[Scope])> = solids
.into_iter()
.map(|(item, member, f)| {
.map(|(item, member, scopes, f)| {
let depths: Vec<f64> = f.iter().map(|f| f.depth).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
(depths, art)
(depths, art, scopes)
})
.collect();
if masks {
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
}
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets, or carry an
// opacity mask, and then it stays whole.
let plain = surfaces.iter().all(|(depths, s)| {
let plain = surfaces.iter().all(|(depths, s, _)| {
s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())
});
if !opaque || !plain {
return Some(surfaces.into_iter().map(|(_, s)| Arc::new(s)).collect());
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
}
let mut faces = vec![];
for (depths, s) in surfaces {
for (depths, s, _) in surfaces {
if let NodeKind::Group { children, .. } = s.kind {
faces.extend(depths.into_iter().zip(children));
}
@@ -535,9 +655,17 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// On a group or layer the effect builds a solid from each path, compound path and type in it,
/// all turned about one shared axis ([`members`]).
pub fn solid_art(n: &Node) -> Option<Node> {
solid_art_in(None, n)
}
/// [`solid_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
/// resolved.
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !has_solid(n) {
return None;
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(n);
}
@@ -660,11 +788,11 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
// Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel
// solid and its mesh are built as the loop reaches them.
let mut inflated = (fx.id == INFLATE).then(|| {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
});
let extrude = extrude_options(&p);
for (item, member, area, rule) in &parts {
for (item, member, area, rule, _) in &parts {
let item: &AppearanceItem = item;
let mesh = match inflated.as_mut() {
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
@@ -689,28 +817,44 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
/// such effect, its solids can't be built, none has a triangle, or together they have more than
/// [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
meshes_within(n, &mut 0, MAX_MESH_TRIANGLES)
three_d_meshes_in(None, n)
}
/// [`three_d_meshes`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// build from the art they show ([`resolve`]).
pub fn three_d_meshes_in(doc: Option<&Document>, n: &Node) -> Result<Vec<SolidMesh>, String> {
meshes_within(doc, n, &mut 0, MAX_MESH_TRIANGLES)
}
/// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports
/// them: the objects share one budget of [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
meshes_of_within(nodes, MAX_MESH_TRIANGLES)
three_d_meshes_of_in(None, nodes)
}
/// [`three_d_meshes_of`] with a budget of `limit` triangles.
fn meshes_of_within<'a>(nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
/// [`three_d_meshes_of`] with the symbols of `doc` ([`three_d_meshes_in`]).
pub fn three_d_meshes_of_in<'a>(doc: Option<&Document>, nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
meshes_of_within(doc, nodes, MAX_MESH_TRIANGLES)
}
/// [`three_d_meshes_of_in`] with a budget of `limit` triangles.
fn meshes_of_within<'a>(doc: Option<&Document>, nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
let mut total = 0usize;
let mut out = vec![];
for n in nodes {
out.extend(meshes_within(n, &mut total, limit)?);
out.extend(meshes_within(doc, n, &mut total, limit)?);
}
Ok(out)
}
/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an
/// [`three_d_meshes_in`], with the triangles of every solid added to `total` as it is built and an
/// error as soon as `total` passes `limit`.
fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
if !crate::has_revolve(n) && !has_solid(n) {
return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into());
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let n = &*resolve(doc, n, label)?;
let meshes = if crate::has_revolve(n) {
crate::revolve::revolve_meshes(n, total, limit)?
} else if !has_solid(n) {
@@ -722,7 +866,7 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidM
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
meshes_for(fx, &shapes, total, limit)?
} else {
let (path, rule) = profile(n).ok_or("3D export needs a path, compound path, type or group")?;
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
@@ -759,3 +903,6 @@ mod tests;
#[cfg(test)]
mod tests_mesh;
#[cfg(test)]
mod tests_sources;
+455
View File
@@ -0,0 +1,455 @@
//! The art a 3D effect builds its solids from when its object, or a member of its group, shows art
//! it does not hold as paths: a symbol instance its symbol's art placed by the instance, a blend its
//! key objects and steps, a clipping group (or a layer with a clipping mask) its art inside the
//! clipping path. Each becomes a plain group of that art, keeping its transparency, so the solids
//! build from what the object shows. Images build no solid: they are traced first.
use std::borrow::Cow;
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_pathops as po;
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
use crate::{GeomContext, is_geometry};
/// The deepest nesting of symbol instances, blends and clipping groups resolved for one 3D effect.
const MAX_DEPTH: usize = 64;
/// The most objects resolving one 3D effect's art may visit or make: every object listed (hidden
/// ones and guides included), every symbol instance, blend and clipping group resolved, every blend
/// step made and every object cut to a clipping path. A symbol that holds instances of another
/// repeats that symbol's art at every level, so art with few visible objects can still take this
/// many steps.
pub(super) const MAX_WORK: usize = 1 << 18;
/// The error for an image a 3D effect is asked to build from.
pub(crate) fn image_refusal(label: &str) -> String {
format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.")
}
/// Is `n` a symbol instance, a blend or a clipping group or layer?
pub(crate) fn resolves(n: &Node) -> bool {
matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. }) || n.clips()
}
/// Is `n`, or a visible member of `n` at any depth of its groups and layers, one [`resolves`] takes?
fn needs(n: &Node) -> bool {
let mut stack = vec![n];
while let Some(n) = stack.pop() {
if resolves(n) {
return true;
}
if is_container(n) {
stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| &**c));
}
}
false
}
/// `n` as a 3D effect builds from it: unchanged when neither it nor a visible member of its groups
/// is a symbol instance, a blend or a clipping group, otherwise a group with `n`'s id, appearance
/// and transparency holding that art (a symbol instance's symbol art from `doc`). An error names
/// what can't be resolved: an image, a missing symbol, art nested or numbering past the limits, or
/// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut
/// for the solid effect `n` carries ([`resolve_for`]).
pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result<Cow<'a, Node>, String> {
let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE);
resolve_for(doc, n, label, every_fill)
}
/// [`resolve`] for the 3D effect that builds from `n`: `every_fill` for Rotate, which turns every
/// fill, so each fill a clipping path cuts keeps its own place among the strokes. Otherwise the
/// effect builds from the top fill, and the fills cut go together in the top fill's place.
pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, every_fill: bool) -> Result<Cow<'a, Node>, String> {
if !needs(n) {
return Ok(Cow::Borrowed(n));
}
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None };
let children = r.content(n, 0);
#[cfg(test)]
WORK.with(|w| w.set(r.work));
let mut out = n.clone();
out.kind = NodeKind::Group { children: children?, clip: false };
Ok(Cow::Owned(out))
}
#[cfg(test)]
thread_local! {
/// The objects the last [`resolve`] on this thread visited or made ([`Resolver::work`]).
pub(super) static WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
struct Resolver<'a> {
doc: Option<&'a Document>,
label: &'a str,
/// Does each fill a clipping path cuts become a piece of its own ([`resolve_for`])?
every_fill: bool,
/// The objects other than groups and layers kept so far, counted against [`MAX_MEMBERS`].
leaves: usize,
/// The objects visited or made so far, counted against [`MAX_WORK`].
work: usize,
/// Inside clipping groups, the box of what their clipping paths show together.
shown: Option<Rect>,
}
impl Resolver<'_> {
/// Count `steps` more objects visited or made, or an error past [`MAX_WORK`].
fn spend(&mut self, steps: usize) -> Result<(), String> {
self.work = self.work.saturating_add(steps);
if self.work > MAX_WORK {
return Err(self.too_much_work());
}
Ok(())
}
fn too_much_work(&self) -> String {
format!("{} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects", self.label)
}
/// `f` run on the art of `c`. The effects of an object or group can move its art into a clip,
/// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]).
fn inside<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
let outer = self.shown;
if has_effects(c) {
self.shown = None;
}
let out = f(self);
self.shown = outer;
out
}
/// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one,
/// shows, as the members of a plain group.
fn content(&mut self, n: &Node, depth: usize) -> Result<Vec<Arc<Node>>, String> {
let label = self.label;
if depth > MAX_DEPTH {
return Err(self.too_deep());
}
self.spend(1)?;
match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => {
let missing = || format!("{label} can't build a solid from the instance of symbol \"{symbol}\": the symbol's art isn't available");
let doc = self.doc.ok_or_else(missing)?;
let sym = doc.symbols.iter().find(|s| s.name == *symbol).ok_or_else(missing)?;
// Counted before the art is placed, so a symbol past the limit is never copied:
// first its own objects, which the instance's overrides keep, then the most
// objects placing makes, with those overrides and the symbol's 9-slice guides.
if self.work.saturating_add(sym.art.count_with_masks()) > MAX_WORK {
return Err(self.too_much_work());
}
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
if (self.work as u64).saturating_add(most) > MAX_WORK as u64 {
return Err(self.too_much_work());
}
let placed = doc.place_symbol_art(symbol, &art, *xf).ok_or_else(missing)?;
Ok(self.list(&[Arc::new(placed)], depth + 1)?.0)
}
NodeKind::Blend { children, spec } => {
// Counted before the steps are made, so a blend past the limit is never expanded.
let made = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(children.len(), usize::saturating_add);
if self.leaves.saturating_add(made) > MAX_MEMBERS {
return Err(self.too_many());
}
self.spend(made)?;
let steps: Vec<Arc<Node>> = crate::expand_live(self.doc, n).into_iter().map(Arc::new).collect();
Ok(self.list(&steps, depth + 1)?.0)
}
_ if n.clips() => {
let Some((first, rest)) = kids(n).split_first() else { return Ok(vec![]) };
if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) {
return Err(self.too_deep());
}
let clip = clip_area(first);
// An image wholly outside every clip around it shows nothing and is left out.
let outer = self.shown;
let here = clip.0.bounds().unwrap_or(Rect::ZERO);
self.shown = Some(outer.map_or(here, |o| o.intersect(here)));
let listed = self.list(rest, depth + 1);
self.shown = outer;
let (inner, _) = listed?;
let mut out = vec![];
for c in &inner {
if let Some(c) = self.clipped(c, &clip, depth + 1)? {
out.push(Arc::new(c));
}
}
Ok(out)
}
_ => Ok(self.list(kids(n), depth + 1)?.0),
}
}
/// The visible members of `children` as plain art: images refused, guides left out, symbol
/// instances, blends and clipping groups resolved into groups with their transparency and
/// geometry effects, groups holding them rebuilt. Also whether any member changed: a group
/// whose members did not is kept as it is. Each object is visited once.
fn list(&mut self, children: &[Arc<Node>], depth: usize) -> Result<(Vec<Arc<Node>>, bool), String> {
let mut out = Vec::with_capacity(children.len());
let mut changed = false;
for c in children {
self.spend(1)?;
if !c.visible || c.is_guide() {
continue;
}
if matches!(c.kind, NodeKind::Image(_)) {
// Only an image with no effects or fills and strokes of its own is measured by its
// frame; any other one may draw inside the clip.
let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible());
let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0));
if hidden {
changed = true;
continue;
}
return Err(image_refusal(self.label));
}
if resolves(c) {
let kids = self.inside(c, |r| r.content(c, depth))?;
out.push(Arc::new(with_effects(wrap(c, kids), c)));
changed = true;
continue;
}
if is_container(c) {
// At the depth limit a group is kept, and not walked further, only when it holds no
// group with members and nothing in it needs resolving.
if depth >= MAX_DEPTH {
if nested_past(c, 1) || needs(c) {
return Err(self.too_deep());
}
out.push(c.clone());
continue;
}
let (kids, inner) = self.inside(c, |r| r.list(kids(c), depth + 1))?;
if inner {
out.push(Arc::new(with_effects(wrap(c, kids), c)));
changed = true;
} else {
out.push(c.clone());
}
continue;
}
self.leaves += 1;
if self.leaves > MAX_MEMBERS {
return Err(self.too_many());
}
out.push(c.clone());
}
Ok((out, changed))
}
fn too_complex(&self) -> String {
format!("{}: the clipping path is too complex to cut the art with", self.label)
}
fn too_many(&self) -> String {
format!("{} takes at most {MAX_MEMBERS} objects", self.label)
}
fn too_deep(&self) -> String {
format!("{} can't build solids from art nested more than {MAX_DEPTH} levels deep", self.label)
}
/// `n`, plain art inside a clipping group, cut to `clip`: each shape's fills as its area inside
/// the clip and each stroke as the part of its outline inside it, filled in the stroke's paint,
/// after the geometry effects of the shape and of the groups it is in; hidden objects and guides
/// left out. `None` when nothing of it is inside. Objects that build no solid stay as they are.
fn clipped(&mut self, n: &Node, clip: &(PathData, FillRule), depth: usize) -> Result<Option<Node>, String> {
if depth > MAX_DEPTH {
return Err(self.too_deep());
}
self.spend(1)?;
if is_container(n) {
let mut kids = vec![];
if n.appearance.effects.iter().any(|e| e.visible && is_geometry(&e.id)) {
// The group's geometry effects reshape its members together before the clip cuts
// them, as they are drawn: each member becomes its reshaped outline.
if nested_past(n, MAX_DEPTH.saturating_sub(depth)) {
return Err(self.too_deep());
}
let mut shapes = members(n, self.label)?;
reshape_members(n, &n.appearance.effects, &mut shapes);
let mut cut = vec![];
for s in shapes {
if let Some(c) = self.clipped(&shape(n, s.path, s.rule, s.items), clip, depth + 1)? {
cut.push((s.scopes, c));
}
}
kids = nest(n, cut, 0);
} else {
for c in n.children().into_iter().flatten() {
if !c.visible || c.is_guide() {
continue;
}
if let Some(c) = self.clipped(c, clip, depth + 1)? {
kids.push(Arc::new(c));
}
}
}
return Ok((!kids.is_empty()).then(|| wrap(n, kids)));
}
let Some((path, rule)) = profile(n) else { return Ok(Some(n.clone())) };
let items = solid_paints(n);
// The fills' piece goes where the top fill is, the one Extrude & Bevel and Inflate build
// their solid from, so the strokes above and below it keep their places. Rotate turns
// every fill, so each fill is a piece in its own place.
let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
let fill_pieces =
if self.every_fill { items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count() } else { usize::from(top_fill.is_some()) };
// Each cut makes a piece, counted before it is made: the shape was counted once already.
let made = fill_pieces + items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
self.spend(made)?;
self.leaves = self.leaves.saturating_add(made.saturating_sub(1));
if self.leaves > MAX_MEMBERS {
return Err(self.too_many());
}
let path = geometry(&path, &n.appearance.effects, &GeomContext::of(n));
let cut = |area: &PathData, rule: FillRule| -> Result<Option<PathData>, String> {
let inside =
po::try_boolean(area, rule, &clip.0, clip.1, po::BoolOp::Intersect, po::DEFAULT_PRECISION).map_err(|_| self.too_complex())?;
Ok(inside.bounds().is_some().then_some(inside))
};
let fills: Vec<AppearanceItem> = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).cloned().collect();
// Every fill paints the same area: it is cut once.
let mut fill_area: Option<Option<PathData>> = None;
let mut pieces = vec![];
for (k, item) in items.iter().enumerate() {
match item {
AppearanceItem::Fill(_) if self.every_fill || Some(k) == top_fill => {
let area = match &fill_area {
Some(area) => area.clone(),
None => fill_area.insert(cut(&path, rule)?).clone(),
};
if let Some(area) = area {
let painted = if self.every_fill { vec![item.clone()] } else { fills.clone() };
pieces.push(Arc::new(shape(n, area, FillRule::NonZero, painted)));
}
}
AppearanceItem::Fill(_) => {}
AppearanceItem::Stroke(s) => {
let (outline, outline_rule) = region(&path, rule, item);
if let Some(area) = cut(&outline, outline_rule)? {
let mut fill = FillLayer::new(s.paint.clone());
fill.opacity = s.opacity;
fill.blend = s.blend;
pieces.push(Arc::new(shape(n, area, FillRule::NonZero, vec![AppearanceItem::Fill(fill)])));
}
}
}
}
Ok((!pieces.is_empty()).then(|| wrap(n, pieces)))
}
}
/// The area clipping path `first` keeps, as the renderer clips by it ([`crate::clip_outline`]): a
/// nested clipping group's own clipping path, the union of a group's members. Empty when it keeps
/// nothing.
fn clip_area(first: &Node) -> (PathData, FillRule) {
crate::clip_outline(first).map_or_else(|| (PathData::default(), FillRule::NonZero), |(bp, rule)| (PathData::from_bezpath(&bp), rule))
}
/// `pieces`, each with the [`Scope`]s of the groups it was in, back in groups of `n`'s id with
/// those groups' opacity, blending mode and opacity mask: consecutive pieces sharing the scope at
/// `level` go into one group, so its transparency applies to them together. `level` stays below the
/// nesting the pieces came from ([`nested_past`]).
fn nest(n: &Node, pieces: Vec<(Vec<Scope>, Node)>, level: usize) -> Vec<Arc<Node>> {
let mut out = vec![];
let mut run: Vec<(Vec<Scope>, Node)> = vec![];
let mut key: Option<Scope> = None;
let close = |run: &mut Vec<(Vec<Scope>, Node)>, scope: Option<Scope>, out: &mut Vec<Arc<Node>>| {
let Some(scope) = scope else { return };
out.push(Arc::new(scope.group(n.id, nest(n, std::mem::take(run), level + 1))));
};
for (scopes, piece) in pieces {
let here = scopes.get(level).cloned();
if here.as_ref().map(|s| s.key) != key.as_ref().map(|s| s.key) {
close(&mut run, key.take(), &mut out);
key = here.clone();
}
match here {
Some(_) => run.push((scopes, piece)),
None => out.push(Arc::new(piece)),
}
}
close(&mut run, key, &mut out);
out
}
/// Does `n` carry a visible effect?
fn has_effects(n: &Node) -> bool {
n.appearance.effects.iter().any(|e| e.visible)
}
/// Does the group `n` hold shown objects nested more than `levels` deep in groups and layers?
/// Only the members [`members`] walks are followed: hidden members are skipped, and the paths of
/// a compound path are one shape. Walked without recursion.
fn nested_past(n: &Node, levels: usize) -> bool {
let mut stack = vec![(n, 0usize)];
while let Some((n, level)) = stack.pop() {
if level > levels {
return true;
}
if level == 0 || is_container(n) {
stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| (&**c, level + 1)));
}
}
false
}
/// Does the clipping path `n` reach objects nested more than `levels` deep along the members that
/// [`Node::clip_shapes`] visits: the first member of a clipping group, the shown members of other
/// groups and layers (not a group's shaper), and every member of a live object. Walked without
/// recursion.
fn clip_nested_past(n: &Node, levels: usize) -> bool {
let mut stack = vec![(n, 0usize)];
while let Some((n, level)) = stack.pop() {
if level > levels {
return true;
}
match &n.kind {
NodeKind::Group { children, clip: true } => stack.extend(children.first().map(|c| (&**c, level + 1))),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
let skip = usize::from(n.extras().shaper.is_some());
stack.extend(children.iter().skip(skip).filter(|c| c.visible).map(|c| (&**c, level + 1)));
}
NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. } => {}
_ => stack.extend(kids(n).iter().map(|c| (&**c, level + 1))),
}
}
false
}
/// The members of `n`, none for an object without members.
fn kids(n: &Node) -> &[Arc<Node>] {
n.children().map_or(&[], Vec::as_slice)
}
/// A path of `n`'s id on `path`, painted by `items` under `rule`.
fn shape(n: &Node, path: PathData, rule: FillRule, items: Vec<AppearanceItem>) -> Node {
let mut piece = Node::path(n.id, path, Appearance { items, ..Default::default() });
if let NodeKind::Path { rule: r, .. } = &mut piece.kind {
*r = rule;
}
piece
}
/// A plain group of `children` with `n`'s id, visibility, opacity, blending mode and opacity mask.
fn wrap(n: &Node, children: Vec<Arc<Node>>) -> Node {
let mut g = Node::group(n.id, children);
g.name = n.name.clone();
g.opacity = n.opacity;
g.blend = n.blend;
if let Some(mask) = &n.extras().mask {
g.extras_mut().mask = Some(mask.clone());
}
g
}
/// `g`, the group `n` was resolved into, with `n`'s appearance: a 3D effect's group reshapes its
/// members with its geometry effects ([`members`]), which read its stroke as they do when `n` is
/// drawn. A group's own fills and strokes build no solid.
fn with_effects(mut g: Node, n: &Node) -> Node {
g.appearance = n.appearance.clone();
g
}
+10 -9
View File
@@ -205,12 +205,12 @@ fn a_stroked_open_path_builds_a_ribbon() {
/// still draws.
#[test]
fn a_stroke_past_the_limits_is_left_out() {
// 1,500 corners: within the 2,048 points of the fill's solid, but not the stroke's outline.
let points: Vec<Point> = (0..1500)
// 40,000 corners: within the 65,536 points of the fill's solid, but not the stroke's outline.
let points: Vec<Point> = (0..40_000)
.map(|k| {
let (s, c) = (k as f64 * std::f64::consts::TAU / 1500.0).sin_cos();
let r = if k % 2 == 0 { 100.0 } else { 96.0 };
Point::new(200.0 + r * c, 200.0 + r * s)
let (s, c) = (k as f64 * std::f64::consts::TAU / 40_000.0).sin_cos();
let r = if k % 2 == 0 { 10_000.0 } else { 9_999.0 };
Point::new(20_000.0 + r * c, 20_000.0 + r * s)
})
.collect();
let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
@@ -591,13 +591,14 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() {
// Hidden members and guides are left out; a group holding what can't become a solid is
// refused with what to do.
let mut g = group(EXTRUDE, json!({}));
let mut clip = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]);
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
let mut woven = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]);
woven.kind = NodeKind::Intertwine { children: woven.children().unwrap().clone() };
if let NodeKind::Group { children, .. } = &mut g.kind {
children.push(Arc::new(clip));
children.push(Arc::new(woven));
}
let err = validate_solid(&g, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("clipping groups"), "{err}");
assert!(err.contains("release or expand its other objects"), "{err}");
assert!(err.contains("type, groups, clipping groups, blends and symbol instances"), "{err}");
assert!(solid_art(&g).is_none(), "drawn as the group it is");
}
+5 -5
View File
@@ -79,7 +79,7 @@ fn revolve_stops_at_the_first_mesh_past_the_budget() {
assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}");
// With room for less than the fill's mesh, the stroke's is never built.
let mut total = 0;
let capped = meshes_within(&n, &mut total, triangles - 1);
let capped = meshes_within(None, &n, &mut total, triangles - 1);
assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}");
assert_eq!(total, triangles);
}
@@ -92,10 +92,10 @@ fn the_objects_of_one_asset_share_one_triangle_budget() {
b.appearance.effects.push(fx(EXTRUDE, json!({})));
let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
let (ta, tb) = (triangles(&a), triangles(&b));
assert!(meshes_of_within([&a], ta).is_ok());
assert!(meshes_of_within([&b], tb).is_ok());
assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4));
assert!(meshes_of_within(None, [&a], ta).is_ok());
assert!(meshes_of_within(None, [&b], tb).is_ok());
assert!(meshes_of_within(None, [&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
assert_eq!(meshes_of_within(None, [&a, &b], ta + tb).map(|m| m.len()), Ok(4));
assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4));
}
+642
View File
@@ -0,0 +1,642 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{AppearanceItem, BlendSpacing, BlendSpec, Document, FillLayer, ImageObject, NodeId, StrokeLayer, Symbol};
use vectorcraft_geom::{Affine, shapes};
use super::*;
const TYPES: [&str; 5] = [EXTRUDE, CLASSIC_EXTRUDE, INFLATE, ROTATE, crate::REVOLVE];
/// Rotate facing the viewer: the art drawn where it is.
fn front() -> Value {
json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0})
}
fn rect(id: u64, x0: f64, y0: f64, x1: f64, y1: f64, stroke: f64) -> Node {
let path = shapes::rectangle(Rect::new(x0, y0, x1, y1));
let stroke_paint = if stroke > 0.0 { Paint::solid(Color::BLACK) } else { Paint::None };
Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), stroke_paint, stroke))
}
fn with(mut n: Node, id: &str, params: Value) -> Node {
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
n
}
fn art(d: &Document, n: &Node, id: &str) -> Option<Node> {
if id == crate::REVOLVE { crate::revolve_art_in(Some(d), n) } else { solid_art_in(Some(d), n) }
}
fn bounds(n: &Node) -> Rect {
n.visual_bounds().unwrap()
}
fn close(a: Rect, b: Rect, tolerance: f64) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() <= tolerance)
}
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(rect(0, 0.0, 0.0, 100.0, 100.0, 2.0)) });
d
}
/// A rectangular clipping path covering `clip`.
fn clipping_path(id: u64, clip: Rect) -> Node {
let mut path = Node::path(NodeId(id), shapes::rectangle(clip), Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut path.kind {
*clipping = true;
}
path
}
/// A clipping group: `art` inside a rectangular clipping path covering `clip`.
fn clip_group(id: u64, clip: Rect, art: Node) -> Node {
Node::new(NodeId(id), NodeKind::Group { children: vec![Arc::new(clipping_path(id + 1, clip)), Arc::new(art)], clip: true })
}
fn blend(id: u64, steps: u32) -> Node {
let keys = vec![Arc::new(rect(id + 1, 100.0, 100.0, 140.0, 140.0, 0.0)), Arc::new(rect(id + 2, 300.0, 120.0, 360.0, 180.0, 0.0))];
let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() };
Node::new(NodeId(id), NodeKind::Blend { children: keys, spec: Box::new(spec) })
}
fn instance(id: u64, symbol: &str, xf: Affine) -> Node {
Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
}
fn image(id: u64) -> Node {
Node::new(
NodeId(id),
NodeKind::Image(Box::new(ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
})),
)
}
fn sources() -> [(&'static str, Node); 3] {
[
("clipping group", clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0))),
("blend", blend(20, 3)),
("symbol instance", instance(30, "Box", Affine::translate((300.0, 0.0)))),
]
}
#[test]
fn every_three_d_type_builds_clipping_groups_blends_and_symbol_instances_alone_and_in_a_group() {
let d = document();
for (what, source) in sources() {
for id in TYPES {
let n = with(source.clone(), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id} on a {what}");
assert!(art(&d, &n, id).is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws");
assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id} on a {what} exports");
let g = with(Node::group(NodeId(90), vec![Arc::new(source.clone()), Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0))]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding a {what}");
assert!(art(&d, &g, id).is_some(), "{id} on a group holding a {what} draws");
assert!(three_d_meshes_in(Some(&d), &g).is_ok_and(|m| !m.is_empty()), "{id} on a group holding a {what} exports");
}
}
}
#[test]
fn a_clipping_groups_solid_is_built_from_its_art_inside_the_clip() {
let d = document();
let clip = Rect::new(100.0, 100.0, 150.0, 200.0);
let fill_only = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0)), ROTATE, front());
let cut = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &fill_only).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// The stroke is cut to the clip too: nothing reaches past it but the faces' seams.
let stroked = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 8.0)), EXTRUDE, front());
let b = bounds(&solid_art_in(Some(&d), &stroked).unwrap());
let outside = b.x0 < clip.x0 - 1.0 || b.x1 > clip.x1 + 1.0;
let extruded =
bounds(&solid_art(&with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), EXTRUDE, front())).unwrap());
assert!(!outside && close(b, extruded, 1.0), "{b:?} within {clip:?}");
// A clip inside a clip keeps what both show.
let nested =
with(clip_group(40, Rect::new(120.0, 0.0, 400.0, 400.0), clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))), ROTATE, front());
let both = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 120.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &nested).unwrap()), bounds(&solid_art(&both).unwrap()), 0.01));
// A clipping group used as the clipping path clips by its own clipping path, not by its art.
let mask = Arc::new(clip_group(70, clip, rect(72, 100.0, 100.0, 110.0, 110.0, 0.0)));
let by_mask = with(
Node::new(NodeId(10), NodeKind::Group { children: vec![mask, Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }),
ROTATE,
front(),
);
assert!(close(bounds(&solid_art_in(Some(&d), &by_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// A stroke between two fills keeps its place below the top fill's solid.
let mut layered = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0);
layered.appearance = Appearance {
items: vec![
AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))),
AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 6.0)),
AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))),
],
..Default::default()
}
.into();
let colors = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), EXTRUDE, json!({}))).unwrap().iter().map(|m| m.color).collect::<Vec<_>>();
let plain = colors(&Node::group(NodeId(10), vec![Arc::new(layered.clone())]));
assert_eq!(plain.len(), 2, "the stroke's solid and the top fill's");
assert_eq!(colors(&clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered.clone())), plain);
// Rotate turns both fills and the stroke, each in its own place.
let turned = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), ROTATE, front())).unwrap().iter().map(|m| m.color).collect::<Vec<_>>();
let plain = turned(&Node::group(NodeId(10), vec![Arc::new(layered.clone())]));
assert_eq!(plain.len(), 3, "both fills' surfaces and the stroke's");
let clipped = clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered);
assert_eq!(turned(&clipped), plain);
assert_eq!(validate_three_d_in(Some(&d), &clipped, ROTATE, &json!({})), Ok(()));
// Each fill Rotate turns counts against the limit on objects; another effect takes the top
// fill only, whatever 3D effect the object carries before it changes type.
let mut many = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0);
many.appearance =
Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); MAX_MEMBERS + 1], ..Default::default() }.into();
let rotated = with(clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), many), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &rotated, ROTATE, &json!({})).is_err_and(|e| e.contains("takes at most")));
for id in [EXTRUDE, crate::REVOLVE] {
assert_eq!(validate_three_d_in(Some(&d), &rotated, id, &json!({})), Ok(()), "Rotate changed to {id}");
}
// Art nested past the limit inside a clipping group is refused, not followed to any depth.
let mut deep = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0);
for i in 0..200 {
deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]);
}
let n = with(clip_group(10, clip, deep.clone()), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")));
assert!(solid_art_in(Some(&d), &n).is_none());
// So is a clipping path nested past the limit, and a symbol's art nested past it.
let by_deep =
Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(deep.clone()), Arc::new(rect(12, 0.0, 0.0, 10.0, 10.0, 0.0))], clip: true });
let mut deep_symbol = d.clone();
deep_symbol.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(deep) });
for n in [with(by_deep, ROTATE, front()), with(instance(30, "Deep", Affine::IDENTITY), ROTATE, front())] {
assert!(validate_three_d_in(Some(&deep_symbol), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")), "{:?}", n.id);
assert!(three_d_meshes_in(Some(&deep_symbol), &n).is_err());
}
// A compound path counts as one shape at the depth limit: a symbol's art nested as deep as a
// path may be also takes a compound path there.
let square = rect(80, 0.0, 0.0, 10.0, 10.0, 0.0);
let mut compound =
Node::new(NodeId(81), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: vectorcraft_geom::FillRule::NonZero });
compound.appearance = square.appearance.clone();
let mut seen = vec![];
for levels in 60..70 {
let ok = |leaf: &Node| {
let mut art = leaf.clone();
for i in 0..levels {
art = Node::group(NodeId(2000 + i), vec![Arc::new(art)]);
}
let mut doc = d.clone();
doc.symbols.push(Symbol { dynamic: false, name: "Nested".into(), art: Arc::new(art) });
validate_three_d_in(Some(&doc), &with(instance(30, "Nested", Affine::IDENTITY), ROTATE, front()), ROTATE, &json!({})).is_ok()
};
let path_ok = ok(&square);
assert_eq!(ok(&compound), path_ok, "{levels} levels");
seen.push(path_ok);
}
assert!(seen.contains(&true) && seen.contains(&false), "the levels cross the limit: {seen:?}");
// A clipping group used as the clipping path clips by its first member only, so deep art it
// clips is not walked for the clip.
let mask = Node::new(
NodeId(70),
NodeKind::Group { children: vec![Arc::new(clipping_path(71, clip)), Arc::new(deep_symbol.symbols[1].art.as_ref().clone())], clip: true },
);
let by_deep_mask = with(
Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }),
ROTATE,
front(),
);
assert_eq!(validate_three_d_in(Some(&d), &by_deep_mask, ROTATE, &json!({})), Ok(()));
assert!(close(bounds(&solid_art_in(Some(&d), &by_deep_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// A clip that shows none of the art builds nothing, and says so.
let empty = clip_group(10, Rect::new(500.0, 500.0, 550.0, 550.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0));
for id in TYPES {
let n = with(empty.clone(), id, json!({}));
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("at least two anchors")), "{id}");
assert!(art(&d, &n, id).is_none(), "{id}");
}
}
#[test]
fn a_symbol_instances_solid_is_its_symbols_art_where_the_instance_places_it() {
let d = document();
let placed = with(instance(30, "Box", Affine::translate((300.0, 50.0))), EXTRUDE, json!({}));
let same = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 300.0, 50.0, 400.0, 150.0, 2.0))]), EXTRUDE, json!({}));
assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&same).unwrap()), 0.01));
// A redefined symbol reshapes the solid.
let mut wider = d.clone();
wider.symbols[0].art = Arc::new(rect(0, 0.0, 0.0, 200.0, 100.0, 2.0));
assert!(bounds(&solid_art_in(Some(&wider), &placed).unwrap()).width() > bounds(&solid_art_in(Some(&d), &placed).unwrap()).width() + 50.0);
// Without the symbol there is nothing to build from.
let missing = with(instance(30, "Gone", Affine::IDENTITY), EXTRUDE, json!({}));
assert!(validate_three_d_in(Some(&d), &missing, EXTRUDE, &json!({})).is_err_and(|e| e.contains("\"Gone\"")));
assert!(validate_three_d(&placed, EXTRUDE, &json!({})).is_err(), "no document: no symbol art");
// A symbol holding an instance of itself is refused, not followed without end.
let mut looped = d.clone();
let inner = Arc::new(instance(0, "Loop", Affine::translate((10.0, 10.0))));
looped.symbols.push(Symbol {
dynamic: false,
name: "Loop".into(),
art: Arc::new(Node::group(NodeId(0), vec![Arc::new(rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)), inner])),
});
let n = with(instance(30, "Loop", Affine::IDENTITY), EXTRUDE, json!({}));
assert!(validate_three_d_in(Some(&looped), &n, EXTRUDE, &json!({})).is_err());
assert!(solid_art_in(Some(&looped), &n).is_none());
}
#[test]
fn a_blends_solid_is_built_from_its_keys_and_steps() {
let d = document();
for steps in [1, 3, 8] {
let n = with(blend(20, steps), ROTATE, front());
let expanded = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, steps)).into_iter().map(Arc::new).collect());
assert_eq!(expanded.children().unwrap().len(), steps as usize + 2);
let same = with(expanded, ROTATE, front());
let (a, b) = (solid_art_in(Some(&d), &n).unwrap(), solid_art(&same).unwrap());
assert_eq!(a.children().unwrap().len(), b.children().unwrap().len(), "a surface for each key and step");
assert!(close(bounds(&a), bounds(&b), 0.01));
}
// A blend making more objects than a 3D effect takes is refused.
let keys = (0..6).map(|i| Arc::new(rect(21 + i, 100.0 * i as f64, 0.0, 100.0 * i as f64 + 40.0, 40.0, 0.0))).collect();
let spec = BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() };
let n = with(Node::new(NodeId(20), NodeKind::Blend { children: keys, spec: Box::new(spec) }), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at most 4096 objects")));
}
#[test]
fn images_are_refused_alone_and_in_a_group_with_image_trace_named() {
let d = document();
for id in TYPES {
for n in [
with(image(50), id, json!({})),
with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(image(53))]), id, json!({})),
with(clip_group(60, Rect::new(0.0, 0.0, 10.0, 10.0), image(62)), id, json!({})),
] {
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}");
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err_and(|e| e.contains("Image Trace")), "{id}");
}
// An image wholly outside the clip, alone or in a group, shows nothing and is left out;
// one the clip shows part of is refused.
let clip = Rect::new(100.0, 100.0, 150.0, 150.0);
let masked = |inside: bool| {
let mut img = image(63);
if let NodeKind::Image(i) = &mut img.kind {
i.xf = Affine::translate(if inside { (95.0, 95.0) } else { (300.0, 300.0) });
}
img
};
for img in [masked(false), Node::group(NodeId(64), vec![Arc::new(masked(false))])] {
let children = vec![Arc::new(clipping_path(61, clip)), Arc::new(rect(62, 100.0, 100.0, 200.0, 200.0, 0.0)), Arc::new(img)];
let n = with(Node::new(NodeId(60), NodeKind::Group { children, clip: true }), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}");
assert!(art(&d, &n, id).is_some(), "{id}");
}
let partly = with(clip_group(60, clip, masked(true)), id, json!({}));
assert!(validate_three_d_in(Some(&d), &partly, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}");
// An effect on the image, or on a group holding it, can move it into the clip: refused.
let moved = |n: Node| with(n, "distort.transform", json!({"moveH": -200.0, "moveV": -200.0}));
for img in [moved(masked(false)), moved(Node::group(NodeId(64), vec![Arc::new(masked(false))]))] {
let n = with(clip_group(60, clip, img), id, json!({}));
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}");
}
// A hidden image is not drawn, so it builds nothing and refuses nothing.
let mut hidden = image(53);
hidden.visible = false;
let g = with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(hidden)]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id}");
}
}
/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one
/// before it.
fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "L0".into(), art: Arc::new(Node::group(NodeId(0), vec![Arc::new(leaf)])) });
for level in 1..=levels {
let below = format!("L{}", level - 1);
let members = (0..fan).map(|i| Arc::new(instance(0, &below, Affine::translate((i as f64 * 2.0, 0.0))))).collect();
d.symbols.push(Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(Node::group(NodeId(0), members)) });
}
d
}
#[test]
fn nested_symbol_instances_that_repeat_hidden_art_are_refused_past_the_work_limit() {
// Four instances at each of ten levels repeat the hidden path about a million times, with no
// object to count against the 4,096-object limit.
let mut hidden = rect(0, 0.0, 0.0, 10.0, 10.0, 0.0);
hidden.visible = false;
let d = nested_symbols(10, 4, hidden);
for id in TYPES {
let n = with(instance(30, "L10", Affine::IDENTITY), id, json!({}));
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{id}: {err}");
assert!(source::WORK.with(std::cell::Cell::get) <= source::MAX_WORK + 1, "{id}: stopped at the limit");
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}");
}
// A clipped shape with more strokes than a 3D effect takes objects is refused before its
// strokes are cut into pieces.
let mut stroked = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0);
let strokes = (0..5000).map(|_| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))).collect();
stroked.appearance = Appearance { items: strokes, ..Default::default() }.into();
let n = with(clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), stroked), ROTATE, front());
let err = validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).unwrap_err();
assert!(err.contains("takes at most 4096 objects") && !err.contains("on a group"), "{err}");
// The same nesting with 1,024 visible squares stays far below the limit and builds: each
// square, group and instance is visited once (an instance twice: listed, then resolved).
let d = nested_symbols(5, 4, rect(0, 0.0, 0.0, 10.0, 10.0, 0.0));
let n = with(instance(30, "L5", Affine::IDENTITY), ROTATE, front());
assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(()));
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 1024 + 1365 * 3, "{work}");
assert!(solid_art_in(Some(&d), &n).is_some());
}
#[test]
fn a_symbol_holding_more_objects_than_the_work_limit_is_refused_before_its_art_is_placed() {
let mut d = document();
let members = (0..=source::MAX_WORK).map(|i| Arc::new(rect(0, i as f64, 0.0, i as f64 + 1.0, 1.0, 0.0))).collect();
d.symbols.push(Symbol { dynamic: false, name: "Big".into(), art: Arc::new(Node::group(NodeId(0), members)) });
let n = with(instance(30, "Big", Affine::IDENTITY), EXTRUDE, json!({}));
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}");
}
/// A gradient fill: a path filled with one is drawn in clip groups where it crosses 9-slice guides.
fn gradient() -> Paint {
use vectorcraft_doc::color::{Gradient, GradientPaint};
Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))
}
/// A document whose symbol "Sliced" has 9-slice guides and holds `count` paths across all of them,
/// each filled with `fill`, and an Extrude on an instance of it at twice its size.
fn sliced(count: usize, fill: impl Fn() -> Paint) -> (Document, Node) {
let mut d = document();
let members = (0..count).map(|i| {
Arc::new(Node::path(NodeId(i as u64 + 1), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill(), Paint::None, 0.0)))
});
d.symbols.push(Symbol { dynamic: true, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(0), members.collect())) });
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
let n = with(instance(30, "Sliced", Affine::scale(2.0)), EXTRUDE, json!({}));
(d, n)
}
#[test]
fn a_symbol_whose_9_slice_guides_would_place_too_many_objects_is_refused_before_its_art_is_placed() {
// Each gradient path becomes a group of nine clip groups, so the art placed is far past the
// limit while the symbol itself holds less than a tenth of it.
let (d, n) = sliced(source::MAX_WORK / 20, gradient);
assert!(d.symbols[1].art.count_with_masks() < source::MAX_WORK);
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}");
}
#[test]
fn a_dynamic_symbol_whose_overrides_would_place_too_many_objects_is_refused_before_its_art_is_placed() {
// Solid paths are cut at the guides and stay one path each; the instance's overrides fill them
// with a gradient, which places each in nine clip groups.
let (d, mut n) = sliced(source::MAX_WORK / 20, || Paint::solid(Color::BLACK));
n.extras_mut().symbol_overrides = (0..source::MAX_WORK / 20)
.map(|i| vectorcraft_doc::SymbolOverride { path: vec![i as u32], fill: Some(gradient()), ..Default::default() })
.collect();
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the instance's art is placed and listed: {work}");
// A few such paths build.
let (d, n) = sliced(4, || Paint::solid(Color::BLACK));
assert!(solid_art_in(Some(&d), &n).is_some());
}
#[test]
fn empty_sources_and_sources_inside_sources_build_or_refuse_cleanly() {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) });
let clip = Rect::new(0.0, 0.0, 50.0, 100.0);
d.symbols.push(Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(clip_group(0, clip, rect(0, 0.0, 0.0, 100.0, 100.0, 0.0))) });
let empty_clip = Node::new(NodeId(10), NodeKind::Group { children: vec![], clip: true });
let empty_symbol = instance(30, "Empty", Affine::IDENTITY);
let no_keys = Node::new(NodeId(20), NodeKind::Blend { children: vec![], spec: Box::default() });
for id in TYPES {
// Alone, an empty clipping group, an instance of an empty symbol and a blend without keys
// build nothing and say so.
for empty in [&empty_clip, &empty_symbol, &no_keys] {
let n = with(empty.clone(), id, json!({}));
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("at least two anchors"), "{id} on {:?}: {err}", empty.kind);
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}");
// In a group they add nothing, and the group's other members still build.
let g = with(Node::group(NodeId(90), vec![Arc::new(empty.clone()), Arc::new(rect(91, 0.0, 0.0, 50.0, 50.0, 0.0))]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {:?}", empty.kind);
assert!(art(&d, &g, id).is_some(), "{id}");
}
// A blend set to no steps draws one step, and builds from its keys and that step.
let n = with(blend(20, 0), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}");
}
let drawn = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, 0)).into_iter().map(Arc::new).collect());
assert_eq!(drawn.children().unwrap().len(), 3);
let (a, b) = (solid_art_in(Some(&d), &with(blend(20, 0), ROTATE, front())).unwrap(), solid_art(&with(drawn, ROTATE, front())).unwrap());
assert_eq!(a.children().unwrap().len(), b.children().unwrap().len());
assert!(close(bounds(&a), bounds(&b), 0.01));
// A symbol holding a clipping group builds from the art inside the clip, where the instance
// places it.
let placed = with(instance(30, "Clipped", Affine::translate((200.0, 0.0))), ROTATE, front());
let cut = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 200.0, 0.0, 250.0, 100.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
}
/// The id of the art of [`masked_by`]'s opacity masks.
const MASK_ART: NodeId = NodeId(900);
/// `n` with an opacity mask of white art covering `r`.
fn masked_by(mut n: Node, r: Rect) -> Node {
let art = Node::path(MASK_ART, shapes::rectangle(r), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
n
}
/// The faces (paths) of `art`, and how many of them are inside an object [`masked_by`] masks with
/// a mask that is not disabled.
fn masked_faces(art: &Node) -> (usize, usize) {
fn walk(n: &Node, masked: bool, out: &mut (usize, usize)) {
let masked = masked || n.extras().mask.as_ref().is_some_and(|m| m.art.id == MASK_ART && !m.disabled);
match n.children() {
Some(children) => children.iter().for_each(|c| walk(c, masked, out)),
None => {
out.0 += 1;
out.1 += usize::from(masked);
}
}
}
let mut out = (0, 0);
walk(art, false, &mut out);
out
}
#[test]
fn an_opacity_mask_on_a_member_or_a_group_in_a_three_d_group_masks_its_solids() {
let d = document();
let mask = Rect::new(0.0, 0.0, 400.0, 400.0);
let mut members = vec![("a path", rect(1, 100.0, 100.0, 150.0, 200.0, 2.0))];
members.extend(sources());
for (what, member) in members {
let other = || Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0));
let in_group = Node::group(NodeId(80), vec![Arc::new(member.clone())]);
let cases = [
("masked", Node::group(NodeId(90), vec![Arc::new(masked_by(member.clone(), mask)), other()])),
("in a masked group", Node::group(NodeId(90), vec![Arc::new(masked_by(in_group, mask)), other()])),
];
for (how, g) in cases {
for id in TYPES {
let g = with(g.clone(), id, json!({}));
let (faces, masked) = masked_faces(&art(&d, &g, id).expect("drawn"));
assert!(masked > 0, "{id}: the faces of {what} {how} are masked");
assert!(masked < faces, "{id}: the other member's faces are not ({masked} of {faces})");
}
}
// A disabled mask masks nothing.
let mut off = masked_by(member.clone(), mask);
if let Some(m) = off.extras_mut().mask.as_mut() {
m.disabled = true;
}
for id in TYPES {
let g = with(Node::group(NodeId(90), vec![Arc::new(off.clone()), other()]), id, json!({}));
assert_eq!(masked_faces(&art(&d, &g, id).expect("drawn")).1, 0, "{id}: {what} with a disabled mask");
}
}
}
/// The leaf faces of `art` that draw something, each with its visual bounds and whether it is drawn
/// inside a group with blending mode `mode`.
fn faces_in_mode(art: &Node, mode: BlendMode) -> Vec<(Rect, bool)> {
fn walk(n: &Node, inside: bool, mode: BlendMode, out: &mut Vec<(Rect, bool)>) {
let inside = inside || (n.children().is_some() && n.blend == mode);
match n.children() {
Some(children) => children.iter().for_each(|c| walk(c, inside, mode, out)),
None => out.extend(n.visual_bounds().map(|b| (b, inside))),
}
}
let mut out = Vec::new();
walk(art, false, mode, &mut out);
out
}
#[test]
fn a_blending_mode_on_a_member_or_a_group_in_a_three_d_group_applies_to_its_solids() {
let d = document();
let mode = |mut n: Node, mode: BlendMode| {
n.blend = mode;
n
};
let other = || Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0));
let member = || rect(1, 100.0, 100.0, 150.0, 200.0, 2.0);
let cases = [
("a multiplied member", Node::group(NodeId(90), vec![Arc::new(mode(member(), BlendMode::Multiply)), other()])),
(
"a member of a multiplied group",
Node::group(NodeId(90), vec![Arc::new(mode(Node::group(NodeId(80), vec![Arc::new(member())]), BlendMode::Multiply)), other()]),
),
];
for (what, g) in cases {
for id in TYPES {
let g = with(g.clone(), id, json!({}));
// The member spans y 100 to 200 and the other member y 600 to 650, and every type keeps
// its faces near those heights (Revolve turns them around a vertical axis): a face whose
// center is above y 400 belongs to the member.
let (mine, others): (Vec<_>, Vec<_>) =
faces_in_mode(&art(&d, &g, id).expect("drawn"), BlendMode::Multiply).into_iter().partition(|(b, _)| b.center().y < 400.0);
assert!(!mine.is_empty() && !others.is_empty(), "{id}: both members draw faces ({} and {})", mine.len(), others.len());
assert!(mine.iter().all(|(_, m)| *m), "{id}: every face of {what} is drawn in Multiply");
assert!(others.iter().all(|(_, m)| !m), "{id}: no face of the other member is drawn in Multiply");
}
}
}
#[test]
fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "Left".into(), art: Arc::new(rect(0, 0.0, 100.0, 50.0, 200.0, 0.0)) });
let moved = |n: Node| with(n, "distort.transform", json!({"moveH": 100.0}));
let clip = Rect::new(100.0, 100.0, 150.0, 200.0);
let target = rect(1, 100.0, 100.0, 150.0, 200.0, 0.0);
let expected = bounds(&solid_art(&with(Node::group(NodeId(90), vec![Arc::new(target.clone())]), ROTATE, front())).unwrap());
let left = || rect(2, 0.0, 100.0, 50.0, 200.0, 0.0);
let members = [
("a symbol instance", moved(instance(30, "Left", Affine::IDENTITY))),
("a clipping group", moved(clip_group(40, Rect::new(0.0, 100.0, 50.0, 200.0), left()))),
("a plain group", moved(Node::group(NodeId(50), vec![Arc::new(left())]))),
("a group in a clipping group", clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(left())])))),
];
for (what, member) in members {
for id in TYPES {
let g = with(Node::group(NodeId(90), vec![Arc::new(member.clone())]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {what}");
}
let g = with(Node::group(NodeId(90), vec![Arc::new(member)]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &g).unwrap()), expected, 0.01), "{what} moved by its Transform effect");
}
// A blend's effect moves its keys and steps together.
let blended = with(Node::group(NodeId(90), vec![Arc::new(moved(blend(20, 3)))]), ROTATE, front());
let unmoved = with(Node::group(NodeId(90), vec![Arc::new(blend(20, 3))]), ROTATE, front());
let (a, b) = (bounds(&solid_art_in(Some(&d), &blended).unwrap()), bounds(&solid_art_in(Some(&d), &unmoved).unwrap()));
assert!(close(a, Rect::new(b.x0 + 100.0, b.y0, b.x1 + 100.0, b.y1), 0.01), "{a:?} is {b:?} moved");
// A geometry effect that reads the object's stroke reads the resolved object's, as a group's.
let stroked = |kind: NodeKind| {
let mut n = Node::new(NodeId(20), kind);
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0).into();
with(n, "path.outlineStroke", json!({}))
};
let NodeKind::Blend { children, spec } = blend(20, 3).kind else { panic!("a blend") };
let steps = crate::expand_live(Some(&d), &blend(20, 3)).into_iter().map(Arc::new).collect();
let group_of = |n: Node| with(Node::group(NodeId(90), vec![Arc::new(n)]), ROTATE, front());
let resolved = bounds(&solid_art_in(Some(&d), &group_of(stroked(NodeKind::Blend { children, spec }))).unwrap());
let plain = bounds(&solid_art(&group_of(stroked(NodeKind::Group { children: steps, clip: false }))).unwrap());
assert!(close(resolved, plain, 0.01), "{resolved:?} {plain:?}");
// A member's opacity and blending mode stay on it when its group's effects reshape it in a clip.
let mut multiplied = left();
multiplied.opacity = 0.5;
multiplied.blend = BlendMode::Multiply;
let n = clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(multiplied), Arc::new(left())])));
let resolved = resolve(Some(&d), &n, "").unwrap().into_owned();
let mut found = vec![];
resolved.walk(&mut |c| {
if c.blend == BlendMode::Multiply {
found.push((c.opacity, c.children().map_or(0, Vec::len)));
}
});
assert_eq!(found, vec![(0.5, 1)], "one Multiply group at 50% holding the one member's piece");
// Groups nested past the limit under a group with geometry effects in a clipping group are
// refused before the effects reshape them.
let mut deep = left();
for i in 0..200 {
deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]);
}
let n = with(clip_group(60, clip, moved(deep.clone())), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")));
// A hidden member nested past the limit is left out, as it is drawn, and does not refuse.
deep.visible = false;
let n = with(clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(deep), Arc::new(left())]))), ROTATE, front());
assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(()));
// Hidden members of a group inside a clipping group build nothing.
let mut hidden = rect(63, 100.0, 100.0, 150.0, 200.0, 0.0);
hidden.visible = false;
let n = with(clip_group(60, clip, Node::group(NodeId(62), vec![Arc::new(hidden)])), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at least two anchors")));
}
+15 -5
View File
@@ -1,5 +1,5 @@
//! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw`
//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! wide; the line arrow's arms reach twice as far out ([`Arrowhead::half_width`]). Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads,
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
@@ -8,7 +8,7 @@
use std::borrow::Cow;
use std::f64::consts::{FRAC_PI_2, PI};
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
@@ -264,6 +264,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
/// Flattening tolerance of the curved local heads, in units.
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
@@ -273,7 +274,7 @@ fn local_stop(kind: Arrowhead) -> Stop {
Arrowhead::Fork => Stop::At(2.7),
Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3),
Arrowhead::Swallowtail => Stop::At(1.4),
Arrowhead::Chevron => Stop::At(1.0),
Arrowhead::Chevron | Arrowhead::LineArrow => Stop::At(1.0),
Arrowhead::Slash => Stop::At(1.2),
Arrowhead::DoubleSlash => Stop::At(1.05),
Arrowhead::DoubleArrow => Stop::At(1.7),
@@ -285,8 +286,9 @@ fn local_stop(kind: Arrowhead) -> Stop {
}
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction
/// the head points). Every shape is generated here.
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
@@ -375,6 +377,14 @@ fn local(kind: Arrowhead) -> BezPath {
poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)])
}
Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)),
Arrowhead::LineArrow => {
// Arms one unit thick (the head's weight: the line's at 100 % for lines of 0.25 pt or
// more) at right angles to each other, from a sharp tip to their outer corners at
// (4, ±4), cut square across: a unit across an arm at 45° is ½√2 along each axis, and
// the arms' inner edges meet √2 behind the tip.
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+20 -3
View File
@@ -14,6 +14,10 @@ use super::{ARCLEN_ACCURACY, kink, push_seg, segments, subpaths, tangent};
/// More dashes than this (a tiny pattern on a long path) draws the line solid instead.
const MAX_DASHES: f64 = 200_000.0;
/// Pattern entries walked in all (every subpath and every corner restart starts the pattern over, and
/// zero-length entries cost no path length, so a long pattern is walked in full even on a short
/// run); past this the line is drawn solid. About 100x what real art needs.
const MAX_STEPS: f64 = 20_000_000.0;
/// A pattern whose longest entry is shorter than this can't advance along the path (each entry
/// ends within the generator's tolerance of where it starts), so it draws the line solid.
const MIN_ENTRY: f64 = 1e-6;
@@ -80,6 +84,10 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
if plans.iter().map(|p| p.periods).sum::<f64>() * pat.len() as f64 > MAX_DASHES {
return None;
}
let restarts = |p: &Plan| p.restart.iter().filter(|r| **r).count() as f64;
if plans.iter().map(|p| (p.periods.ceil().max(1.0) + restarts(p)) * pat.len() as f64).sum::<f64>() > MAX_STEPS {
return None;
}
// Where an exact pattern starts: `offset` into it.
let mut off = d.offset.rem_euclid(period);
let mut ix0 = 0;
@@ -89,8 +97,13 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
}
let phase = Phase { ix: ix0, rem: pat[ix0] - off, on: ix0 % 2 == 0 };
let mut out = Dashed::default();
// The estimates above trust the fitted scales; this counts the pattern entries actually walked,
// so entries that fit down to nothing can't keep a subpath looping.
let mut budget = MAX_STEPS as usize;
for plan in &plans {
dash_subpath(&mut out, plan, &pat, phase, keep);
if !dash_subpath(&mut out, plan, &pat, phase, keep, &mut budget) {
return None;
}
}
Some(out)
}
@@ -183,7 +196,8 @@ impl Piece {
}
}
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool) {
/// Dash one subpath; `false` when `budget` (pattern entries left to walk, shared by all subpaths) runs out.
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool, budget: &mut usize) -> bool {
let first_dot = out.dots.len();
let total: f64 = plan.lens.iter().sum();
// Fraction of the subpath's length at `x` along the plan.
@@ -244,6 +258,8 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
push_dot(out, first_dot, Dot { at: seg.eval(t), dir: tangent(seg, t), t: frac(acc + end) });
}
}
let Some(rest) = budget.checked_sub(1) else { return false };
*budget = rest;
cuts += 1;
s = end;
ph.ix = (ph.ix + 1) % pat.len();
@@ -273,7 +289,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
write(&mut out.path, &d.segs);
out.path.close_path();
out.spans.push((frac(0.0), frac(0.0) + 1.0));
return;
return true;
}
if starts_on && ends_on && dashes.len() > 1 {
// The dash running through the start point is one dash.
@@ -291,6 +307,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
let t0 = frac(d.start);
out.spans.push((t0, if total > 0.0 { t0 + (d.end - d.start) / total } else { t0 }));
}
true
}
/// Add `dot` unless the subpath's last dot (from index `first`) is already there: a run ending on
+35 -4
View File
@@ -1,6 +1,6 @@
//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut
//! arms reach a little further back), without self-intersections, and covering the end of the
//! stroke under it.
//! Every arrowhead's outline: drawn, inside its reach and half width (4 × 4 weights for most; the
//! open arrow's square-cut arms reach a little further back, the line arrow's twice as far out),
//! without self-intersections, and covering the end of the stroke under it.
use kurbo::{BezPath, PathEl, Point, Shape};
use vectorcraft_color::{Color, Paint};
@@ -53,7 +53,13 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let h = head(kind);
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}");
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
assert!(b.x1 <= 100.0 + 1e-6 && b.y0 >= -side - 1e-6 && b.y1 <= side + 1e-6, "{kind:?} leaves its box: {b:?}");
if kind.half_width() == 2.0 {
assert!(b.x0 >= 91.0 - 1e-6, "{kind:?} is longer than the 4 × 4 box: {b:?}");
}
let far = contours(&h.outline).iter().flatten().map(|p| p.distance(h.tip)).fold(0.0, f64::max);
assert!(far <= reach + 1e-6, "{kind:?} reaches {far} from its tip, past {reach}");
let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect();
assert!(edges.len() >= 3, "{kind:?}");
for (i, a) in edges.iter().enumerate() {
@@ -74,6 +80,31 @@ fn the_stroke_ends_inside_every_head() {
}
}
#[test]
fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() {
// Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt.
let h = head(Arrowhead::LineArrow);
let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y);
// A sharp tip on the end point; outer corners 4 units back and out, square-cut ends.
let pts: Vec<Point> = contours(&h.outline).concat();
for (corner, name) in [(at(0.0, 0.0), "tip"), (at(4.0, 4.0), "right corner"), (at(4.0, -4.0), "left corner")] {
assert!(pts.iter().any(|p| p.distance(corner) < 1e-9), "{name} {corner:?} in {pts:?}");
}
// Open between the arms, solid at the tip.
assert_eq!(h.outline.winding(at(2.5, 0.0)), 0);
assert_ne!(h.outline.winding(at(0.7, 0.0)), 0);
// Halfway along each arm, 45° off the line, it is one unit (the line's weight) across.
let s = std::f64::consts::FRAC_1_SQRT_2;
for side in [1.0, -1.0] {
let (mx, my) = (2.0 + 0.5 * s, side * (2.0 - 0.5 * s));
let (nx, ny) = (-side * s, s);
for (d, inside) in [(0.45, true), (-0.45, true), (0.55, false), (-0.55, false)] {
let w = h.outline.winding(at(mx + nx * d, my + ny * d));
assert_eq!(w != 0, inside, "arm {side} at {d} across");
}
}
}
#[test]
fn half_arrows_barb_on_their_own_side() {
// Pointing along +x on a y-down page, left is −y.
+14
View File
@@ -223,3 +223,17 @@ fn smooth_points_of_curves_stay_smooth_with_any_join() {
assert!((a - want).abs() / want < 0.005, "{join:?}: {a} vs {want}");
}
}
#[test]
fn a_long_pattern_restarted_on_many_short_subpaths_draws_solid() {
// Each subpath walks the zero-length entries in full although it is far shorter than a period.
let mut pattern = vec![0.0; 2000];
pattern[0] = 1.0;
let mut b = BezPath::new();
for i in 0..20_000 {
b.move_to((i as f64 * 2.0, 0.0));
b.line_to((i as f64 * 2.0 + 0.01, 0.0));
}
let d = Dash { pattern, offset: 0.0, align_corners: false };
assert!(dash(&b, &d).is_none());
}
+3 -2
View File
@@ -1101,8 +1101,9 @@ pub fn with_id(xml: &str, id: &str) -> Option<String> {
let f = filter_element(&doc).ok()?;
let at = f.attributes().find(|a| a.name() == "id" && a.namespace().is_none())?.range_value();
let (start, end) = (at.start.checked_sub(head)?, at.end.checked_sub(head)?);
// The value may sit in single quotes: those are escaped too.
let id = escaped(id).replace('\'', "&apos;");
// The value may sit in single quotes: those are escaped too. A tab, line feed or carriage
// return is written as a character reference, which attribute-value normalization keeps.
let id = escaped(id).replace('\'', "&apos;").replace('\t', "&#9;").replace('\n', "&#10;").replace('\r', "&#13;");
Some(format!("{}{}{}", xml.get(..start)?, id, xml.get(end..)?))
}
+54 -9
View File
@@ -218,34 +218,66 @@ fn visible(sources: &[TrapSource]) -> Vec<PathData> {
/// The pairs `(i, j)`, `i < j`, in ascending order, of `rects` (`None`: left out) that come within
/// `reach_x` of each other across x and `reach_y` across y. A sweep over the rects sorted by their
/// left edge, so shapes spread over the page cost about one check each rather than one per pair.
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Vec<(usize, usize)> {
/// `None` when there are more than [`MAX_NEAR_PAIRS`] (many shapes all within reach of each other
/// make the pair list grow with the square of their count) or the sweep examines more than
/// `MAX_NEAR_SCAN` pairs (many shapes sharing an x range, far apart in y).
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Option<Vec<(usize, usize)>> {
near_pairs_within(rects, reach_x, reach_y, MAX_NEAR_SCAN)
}
fn near_pairs_within(rects: &[Option<Rect>], reach_x: f64, reach_y: f64, max_scan: usize) -> Option<Vec<(usize, usize)>> {
let mut order: Vec<(usize, Rect)> = rects.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))).collect();
order.sort_unstable_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.0.cmp(&b.0)));
let mut pairs = vec![];
let mut scanned = 0usize;
for (k, &(i, a)) in order.iter().enumerate() {
// Later rects start at or right of `a`, so only how far right they start can rule them out.
for &(j, b) in order[k + 1..].iter().take_while(|(_, b)| b.x0 <= a.x1 + reach_x) {
// Rects sharing an x range but far apart in y are examined without being stored.
scanned += 1;
if scanned > max_scan {
return None;
}
if b.y0 <= a.y1 + reach_y && a.y0 <= b.y1 + reach_y {
if pairs.len() >= MAX_NEAR_PAIRS {
return None;
}
pairs.push((i.min(j), i.max(j)));
}
}
}
pairs.sort_unstable();
pairs
Some(pairs)
}
/// Most pairs the sweep in `near_pairs` examines, stored or not (a plain bounds check each).
const MAX_NEAR_SCAN: usize = 1 << 27;
/// Most candidate pairs one trap evaluation keeps; past it no traps are made (the art draws as is).
/// Each pair costs a boolean trap band, so real art stays far below this.
pub const MAX_NEAR_PAIRS: usize = 1 << 20;
/// The traps between `sources` (back to front) with options `o`: for each two sources of
/// different solid colours whose visible parts meet, the strip of the darker one's visible part
/// next to the lighter one's (the other way round with [`TrapOptions::reverse`]), painted per
/// [`trap_paint`]. Empty when no visible edges of different colours meet.
/// [`trap_paint`]. Empty when no visible edges of different colours meet, or when there are more
/// than [`MAX_NEAR_PAIRS`] candidate pairs or the pair scan is too long (see [`try_traps`] to tell
/// those apart).
pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
try_traps(sources, o).unwrap_or_default()
}
/// [`traps`], but `None` when there are more than [`MAX_NEAR_PAIRS`] candidate pairs or the scan for
/// them is too long (`MAX_NEAR_SCAN` pairs examined), as opposed to
/// `Some` of an empty list when no edges meet.
pub fn try_traps(sources: &[TrapSource], o: &TrapOptions) -> Option<Vec<TrapPiece>> {
let colors: Vec<Option<Color>> = sources.iter().map(|s| trap_color(&s.fill)).collect();
if colors.iter().flatten().count() < 2 {
return vec![];
return Some(vec![]);
}
let (w, r) = (o.thickness, o.height_width);
if !(w.is_finite() && w > 0.0 && r.is_finite() && r > 0.0) {
return vec![]; // `trap_band` cuts nothing with these.
return Some(vec![]); // `trap_band` cuts nothing with these.
}
let vis = visible(sources);
// Only pairs whose visible parts come within the trap's reach can trap (`trap_band` rejects
@@ -257,7 +289,8 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
let extent = rects.iter().flatten().flat_map(|b| [b.x0, b.y0, b.x1, b.y1]).fold(0.0_f64, |m, v| m.max(v.abs()));
let hair = 1e-9 * (1.0 + extent + w * r.max(1.0));
let mut out = vec![];
for (i, j) in near_pairs(&rects, w + hair, w * r + hair) {
let pairs = near_pairs(&rects, w + hair, w * r + hair)?;
for (i, j) in pairs {
let (Some(ci), Some(cj)) = (colors[i], colors[j]) else { continue };
if vis[i].is_empty() || vis[j].is_empty() || same_color(&sources[i].fill, &sources[j].fill, ci, cj) {
continue;
@@ -276,7 +309,7 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
let Some(color) = colors[from] else { continue };
out.push(TrapPiece { path: band, paint: trap_paint(&sources[from].fill, color, o), from, into });
}
out
Some(out)
}
/// A trap's appearance: one overprinting fill of `paint`, no stroke.
@@ -379,10 +412,19 @@ mod tests {
assert!(near(po::area(&t[0].path, FillRule::NonZero), 22.0 * 22.0 - 400.0));
}
#[test]
fn the_pair_scan_is_bounded_even_when_no_pair_is_near() {
// Eleven rects share an x range but lie far apart in y: 55 pairs are examined, none stored.
let rects: Vec<Option<Rect>> = (0..11).map(|k| Some(Rect::new(0.0, k as f64 * 1000.0, 10.0, k as f64 * 1000.0 + 10.0))).collect();
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 100), Some(vec![]));
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 54), None);
}
#[test]
fn no_trap_without_adjoining_edges_of_different_colours() {
let apart = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), yellow()), src(Rect::new(30.0, 0.0, 40.0, 10.0), blue())];
assert!(traps(&apart, &TrapOptions::default()).is_empty());
assert_eq!(try_traps(&apart, &TrapOptions::default()).map(|t| t.len()), Some(0), "no edges meet: empty, not over the cap");
let same = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), blue()), src(Rect::new(10.0, 0.0, 20.0, 10.0), blue())];
assert!(traps(&same, &TrapOptions::default()).is_empty());
let mut unfilled = abutting();
@@ -431,10 +473,13 @@ mod tests {
fn only_shapes_within_reach_are_paired() {
let s = many_apart_and_one_abutting();
let rects: Vec<Option<Rect>> = s.iter().map(|t| t.path.bounds()).collect();
assert_eq!(near_pairs(&rects, 1.0, 1.0), vec![(0, 2000)], "the squares 10 pt apart are never paired");
assert_eq!(near_pairs(&rects, 1.0, 1.0), Some(vec![(0, 2000)]), "the squares 10 pt apart are never paired");
// Reaching 10 pt, neighbours in a row pair, in ascending order; left-out rects never do.
let row: Vec<Option<Rect>> = [3, 1, 0, 2].iter().map(|&k| s[k].path.bounds()).chain([None]).collect();
assert_eq!(near_pairs(&row, 10.0, 10.0), vec![(0, 3), (1, 2), (1, 3)]);
assert_eq!(near_pairs(&row, 10.0, 10.0), Some(vec![(0, 3), (1, 2), (1, 3)]));
// Past the allowance the pair list stops growing instead of being built.
let packed = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0)); 1500];
assert_eq!(near_pairs(&packed, 1.0, 1.0), None);
let t = traps(&s, &TrapOptions { thickness: 1.0, ..Default::default() });
assert_eq!(t.len(), 1, "only the abutting pair traps");
assert_eq!((t[0].from, t[0].into), (2000, 0));
+16 -7
View File
@@ -70,6 +70,7 @@ pub mod pdfcmds;
pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
pub mod prefscmds;
pub mod print;
pub(crate) mod printadvanced;
@@ -518,17 +519,23 @@ pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str
}
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
/// given one dropped), else the selected objects.
/// given one dropped), else (`ids` left out or null) the selected objects.
pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
if p.get("ids").is_some() { Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?)) } else { edit::selected_roots(s) }
if p.get("ids").is_some_and(|v| !v.is_null()) {
Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?))
} else {
edit::selected_roots(s)
}
}
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
if s.doc()?.doc.node(id).is_none() {
return Err(bad(command, format!("no such object id {value}")));
match s.doc()?.doc.node(id) {
None => Err(bad(command, format!("no such object id {value}"))),
// The guide commands take ruler guides by index.
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
Some(_) => Ok(id),
}
Ok(id)
}
/// `v` as exactly `N` finite numbers (`[x, y]`, `[x, y, width, height]`…): `None` when it isn't an
@@ -688,10 +695,11 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns));
let mut out = vec![];
for id in ids {
let Some(n) = d.node(*id) else { continue };
// A ruler guide has no appearance to paint, given or in a layer.
let Some(n) = d.node(*id).filter(|n| !n.is_ruler_guide()) else { continue };
match &n.kind {
NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| {
if !c.is_container() || owns(c) {
if (!c.is_container() && !c.is_ruler_guide()) || owns(c) {
out.push(c.id)
}
}),
@@ -741,6 +749,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
@@ -185,7 +185,7 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> {
}
fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) {
if !n.visible || n.locked || out.len() >= MAX_OBJECTS {
if !n.visible || n.locked || n.is_ruler_guide() || out.len() >= MAX_OBJECTS {
return;
}
let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false };
@@ -216,7 +216,7 @@ fn is_generated(n: &Node) -> bool {
}
fn is_guide_or_clip(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. })
n.is_guide() || matches!(n.kind, NodeKind::Path { clipping: true, .. })
}
fn is_shape(n: &Node) -> bool {
@@ -484,7 +484,7 @@ fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result<Out
if i < d.artboards.len() {
let id = d.artboards.remove(i).id;
d.retire_artboard_id(id);
d.retain_guides(sel, |_, g| g.artboard != Some(id));
d.retain_guides(sel, |g| g.artboard != Some(id));
}
}
Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty })
+6 -2
View File
@@ -544,7 +544,11 @@ fn merge(chain: &[&Piece]) -> std::result::Result<TextObject, usize> {
for (k, w) in off.windows(2).enumerate() {
let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue };
if delta.abs() > 1e-9 {
edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0);
// Thousandths of the em as the Horizontal Scale draws it (`spacing_scale`).
let vertical = m.vertical;
edit::style_range(&mut m.runs, s, e, |st| {
st.tracking += delta / (st.size * vectorcraft_text::spacing_scale(st, vertical)).max(1e-6) * 1000.0;
});
if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) {
return Err(k + 1);
}
@@ -802,7 +806,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
};
// The characters a Type tool has selected (after Select All in threaded text, all the text of
// every frame of the story), else all the text of the selected type.
let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
let editing = if p.get("ids").is_some_and(|v| !v.is_null()) { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
let story = if editing.is_some() { editing_story(s) } else { vec![] };
let d = &s.doc()?.doc;
// Each type object with the breaks that go from it.
@@ -125,6 +125,30 @@ fn break_area_type_into_lines_paragraphs_and_glyphs() {
}
}
/// Tracked area type broken into lines or paragraphs stays where it was, however it is aligned:
/// a wrap after a hyphen or at a space becomes a line break or a paragraph's end, and the line
/// leaves the tracking after its last character out of its width there as it did at the wrap.
/// (Words chosen without a kerning pair across the wrap, which the pieces don't keep.)
#[test]
fn break_tracked_area_type_keeps_its_aligned_lines_in_place() {
for justify in ["center", "right"] {
for text_of in ["Mode-Mode-Mode", "Wave Wave Wave"] {
for by in ["paragraphs", "lines"] {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 40, "text": text_of, "size": 20, "area": {"width": 90, "height": 200}}));
s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 200})).unwrap();
s.execute("text.setStyle", &json!({"ids": [id.0], "justify": justify})).unwrap();
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(&s, id));
assert!(lay.lines.len() > 1, "{text_of}: it wraps");
let was = glyphs(&s, &[id]);
select(&mut s, &[id]);
let pieces = ids(&s.execute("addon.cleanup.breakText", &json!({"by": by})).unwrap());
assert_same_places(&was, &glyphs(&s, &pieces));
}
}
}
}
#[test]
fn break_text_refuses_what_it_cannot_break() {
let mut s = session();
@@ -176,6 +200,24 @@ fn combine_joins_only_pieces_on_one_line_turned_alike() {
assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine"));
}
/// Pieces in horizontally scaled type: the tracking that puts each back where it was is measured in
/// the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), as layout spaces it.
#[test]
fn combine_puts_horizontally_scaled_pieces_back_where_they_were() {
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 160, "y": 100, "text": "Right", "size": 20}));
for id in [a, b] {
s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 200})).unwrap();
}
let was = glyphs(&s, &[a, b]);
select(&mut s, &[a, b]);
let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap();
assert_eq!(ids(&r), [a]);
assert_eq!(obj(&s, a).plain_text(), "Left Right");
assert_same_places(&was, &glyphs(&s, &[a]));
}
/// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs,
/// pieces on a line left to right, each line's baseline where it was (its leading is the distance
/// from the line above), in one undo step. A piece turned unlike the top-left one stays.
@@ -246,6 +288,18 @@ fn remove_breaks_in_the_characters_a_type_tool_selected() {
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
}
/// `ids: null` is `ids` left out: the characters the Type tool selected lose their breaks, and
/// the rest of the text keeps them.
#[test]
fn remove_breaks_with_ids_null_in_the_characters_a_type_tool_selected() {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12}));
select(&mut s, &[id]);
edit_text(&mut s, id, 0, 2);
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": null})).unwrap();
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
}
#[test]
fn split_at_the_cursor_and_around_a_selection() {
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
@@ -107,7 +107,7 @@ impl Fixes {
let white = usize::from(self.remove_white_overprint && self.unset_white(n));
let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_)));
let mut counts = (white, usize::from(blacks && black.apply(n, spots)));
for c in n.children_mut().into_iter().flatten() {
for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
let (w, b) = self.overprint(Arc::make_mut(c), black, spots);
counts = (counts.0 + w, counts.1 + b);
}
+5 -5
View File
@@ -12,8 +12,8 @@ use vectorcraft_doc::NodeKind;
use vectorcraft_render::effects;
use super::super::edit::{copy_above, selected_roots};
use super::super::pathops::{len_param, num_param};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param};
use super::super::pathops::{length_given, number_given};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, text_param};
const C: &str = "addon.contour.set";
/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies).
@@ -44,12 +44,12 @@ fn joins_for(corners: Option<&str>) -> Result<&'static str> {
}
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
let offset = length_given(p, "offset", C)?.ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
if offset.abs() > MAX_OFFSET {
return Err(bad(C, "offset out of range"));
}
let joins = joins_for(str_param(p, "corners"))?;
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
let joins = joins_for(text_param(p, "corners", C)?)?;
let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0);
let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter}))
.ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?;
let roots = selected_roots(s)?;
@@ -158,6 +158,39 @@ fn contour_refuses_what_it_cannot_offset() {
assert!(err.contains("select paths or shapes"), "{err}");
}
/// A param of the wrong type is an error naming the param, and leaves the document, the selection
/// and the undo history as they were. Null keeps a param's default, and `offset` still takes a
/// string with a unit.
#[test]
fn contour_refuses_a_param_of_the_wrong_type() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for (p, want) in [
(json!({"offset": true}), "`offset` must be a number, not true"),
(json!({"offset": "abc"}), "`offset` must be a number, not \"abc\""),
(json!({"offset": [5]}), "`offset` must be a number, not [5]"),
(json!({"offset": 5, "corners": 3}), "`corners` must be a string"),
(json!({"offset": 5, "miterLimit": "high"}), "`miterLimit` must be a number, not \"high\""),
(json!({"offset": 5, "miterLimit": false}), "`miterLimit` must be a number, not false"),
] {
let r = s.execute("addon.contour.set", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
assert!(state(&s) == before, "{p} changed the document, the selection or the undo history");
}
// A null `offset` is a missing one.
let err = s.execute("addon.contour.set", &json!({"offset": null})).unwrap_err().to_string();
assert!(err.contains("missing `offset`"), "{err}");
// Null corners and miter limit keep sharp corners at 4; the offset takes a unit.
let r = s.execute("addon.contour.set", &json!({"offset": "1 in", "corners": null, "miterLimit": null})).unwrap();
let fx = effects_of(&s, ids_of(&r, "created")[0]);
assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone(), fx[0].1["miterLimit"].clone()), (json!(72.0), json!("miter"), json!(4.0)));
}
/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then
/// the gap taken out of the border with Minus Front, leaves a ring between the two.
#[test]
+6 -4
View File
@@ -164,11 +164,11 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds
/// no layers).
/// no layers, and no ruler guides: a layer's are left out).
fn without_layers(n: &Node) -> Node {
let mut n = n.clone();
if let NodeKind::Layer { children, clip, .. } = &n.kind {
n.kind = NodeKind::Group { children: children.clone(), clip: *clip };
n.kind = NodeKind::Group { children: children.iter().filter(|c| !c.is_ruler_guide()).cloned().collect(), clip: *clip };
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) {
@@ -203,8 +203,10 @@ fn symbols_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
let (mut made, mut skipped) = (vec![], vec![]);
for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) {
let name = layer.display_name();
let roots: Vec<NodeId> = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
let art = match layer.children().map(Vec::as_slice).unwrap_or_default() {
// The layer's ruler guides stay where they are.
let children: Vec<Arc<Node>> = layer.children().into_iter().flatten().filter(|n| !n.is_ruler_guide()).cloned().collect();
let roots: Vec<NodeId> = children.iter().map(|n| n.id).collect();
let art = match children.as_slice() {
[] => None,
[one] => Some(without_layers(one)),
many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))),
+4 -3
View File
@@ -774,8 +774,9 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let only = (segs.len() < sp.segment_count()).then_some(&segs);
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made))
.ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?;
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)).ok_or_else(|| {
bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer")
})?;
made += out.len();
for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) {
dashes += usize::from(kind == pt::Piece::Dash);
@@ -825,7 +826,7 @@ fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.expandDashes";
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
let too_many = || bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer");
let roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
// Each dashed path and its dashes, as the canvas draws them.
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Parametric Shape",
[],
None,
"{id, kind?, center?, width?, height?, rotation?, count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}",
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}",
has_doc,
set
),
+6 -6
View File
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top-left corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rectangle
),
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
"{x, y, width, height, startAngle?, endAngle?: degrees (counter-clockwise from 3 o'clock, as object.setLiveShape's pieStart and pieEnd; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
ellipse
),
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a corner straight up)} → {id}",
has_doc,
polygon
),
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Star",
[],
None,
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top point; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a point straight up)} → {id}",
has_doc,
star
),
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"3D Box",
[],
None,
"{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}",
"{x, y, width, height, angleX=30 (degrees about the level axis: positive tips the top away from you), angleY=30 (degrees about the upright axis: positive turns the right side away from you), angleZ=0 (degrees clockwise in the page), parallelX=false, parallelY=true, parallelZ=false} → {id}",
has_doc,
box3d
),
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Configure Shape",
[],
None,
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (as addon.shapes.rectangle, ellipse, polygon and star take them: an ellipse's counter-clockwise from 3 o'clock, the others' clockwise along the outline), arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?: degrees (as addon.shapes.box3d: positive tips the top, or turns the right side, away from you), angleZ?: degrees clockwise in the page, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
has_selection,
configure
),
+8 -3
View File
@@ -939,7 +939,10 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
})?;
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
// The rows removed from the active row's object, which need not come first in `ids`.
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let gone = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx);
s.remap_appearance_item(&ids, |a| (!gone.contains(&a)).then(|| a - gone.iter().filter(|i| **i < a).count()));
ok()
}
@@ -1023,10 +1026,12 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
let m = idx.len();
let landed = active_at.or(first_at);
// The rows copied in the active row's object, which need not come first in `ids`.
let copied = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx);
s.remap_appearance_item(&ids, |a| {
Some(match to {
Some(_) => a + if landed.is_some_and(|at| at <= a) { m } else { 0 },
None => a + idx.iter().filter(|i| **i < a).count(),
None => a + copied.iter().filter(|i| **i < a).count(),
})
});
ok()
@@ -1184,7 +1189,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
.iter()
.filter_map(|id| d.node(*id))
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
.flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked).map(|c| c.id))
.flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked && !c.is_ruler_guide()).map(|c| c.id))
.collect();
if ids.is_empty() {
return Err(bad("appearance.targetContents", "select a group or layer with visible, unlocked members"));
+7 -4
View File
@@ -116,13 +116,15 @@ pub(crate) fn art_under(doc: &vectorcraft_doc::Document, id: NodeId, out: &mut V
let Some(n) = doc.node(id) else { return };
if n.is_layer() {
if let Some(kids) = n.children() {
for c in kids {
for c in kids.iter().filter(|c| !c.is_ruler_guide()) {
art_under(doc, c.id, out);
}
}
return;
}
out.push(id);
if !n.is_ruler_guide() {
out.push(id);
}
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
@@ -213,7 +215,7 @@ fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
ids.dedup();
for id in &ids {
let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?;
if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) {
if let Err(e) = vectorcraft_render::effects::three_d_meshes_in(Some(d), n) {
let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0));
return Err(bad(C, format!("{what} can't be exported in 3D: {e}")));
}
@@ -281,7 +283,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::<Result<Vec<_>>>()?;
// The asset's objects share one budget of triangles.
let what = &a.name;
let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let parts =
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
+71 -3
View File
@@ -165,13 +165,14 @@ pub struct BuiltinBrushLibrary {
make: fn() -> BrushLibrary,
}
/// The built-in brush libraries, in menu order: original brushes generated in code, one library
/// per kind of brush.
/// The built-in brush libraries, in menu order: original brushes generated in code.
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
];
/// Built-in library `id`, made once.
@@ -378,6 +379,73 @@ fn scatter_shapes() -> BrushLibrary {
built("Scatter Shapes", doc, brushes)
}
/// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art).
fn game_trails() -> BrushLibrary {
let speed = {
let n = 32;
let half = |x: f64| 2.2 * (1.0 - x / 100.0).powf(1.2).max(0.08);
let xs = |i: usize| 100.0 * i as f64 / n as f64;
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect();
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x))));
PathData::single(SubPath::polyline(&pts, true))
};
let dash = group(vec![
black(shapes::rounded_rectangle(Rect::new(0.0, -1.0, 14.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(22.0, -1.0, 36.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(44.0, -1.0, 58.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(66.0, -1.0, 80.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(88.0, -1.0, 100.0, 1.0), 1.0)),
]);
let burst = {
// A wedge that flares from a tip at x=0 to a wide end at x=100.
let tip = Point::new(0.0, 0.0);
let top = Point::new(100.0, -6.0);
let bot = Point::new(100.0, 6.0);
PathData::single(SubPath::polyline(&[tip, top, bot], true))
};
let zigzag = band(100.0, 1.8, 40, |x| {
let t = (x / 12.5).floor();
let local = (x / 12.5) - t;
if (t as i32) % 2 == 0 { -3.0 + 6.0 * local } else { 3.0 - 6.0 * local }
});
let brushes = vec![
art("Speed Line", black(speed), Colorization::Tints),
art("Dash Trail", dash, Colorization::Tints),
art("Burst Ray", black(burst), Colorization::Tints),
art("Zigzag", black(zigzag), Colorization::Tints),
];
built("Game Trails", Document::new(100.0, 100.0), brushes)
}
/// Energy Beams: art brushes for laser, plasma and charge strokes (original game VFX art).
fn energy_beams() -> BrushLibrary {
let laser = {
let n = 32;
let half = |x: f64| 1.6 * (1.0 - (x / 100.0 - 0.5).abs() * 1.6).max(0.12);
let xs = |i: usize| 100.0 * i as f64 / n as f64;
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect();
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x))));
PathData::single(SubPath::polyline(&pts, true))
};
let plasma = band(100.0, 2.2, 48, |x| 4.0 * (x / 100.0 * std::f64::consts::PI).sin());
let charge = band(100.0, 1.6, 56, |x| 3.5 * (x / 100.0 * std::f64::consts::TAU).sin());
let spark = group(vec![
black(shapes::rounded_rectangle(Rect::new(0.0, -1.2, 10.0, 1.2), 0.8)),
black(shapes::rounded_rectangle(Rect::new(18.0, -0.9, 28.0, 0.9), 0.7)),
black(shapes::rounded_rectangle(Rect::new(36.0, -1.4, 48.0, 1.4), 0.9)),
black(shapes::rounded_rectangle(Rect::new(56.0, -0.8, 66.0, 0.8), 0.6)),
black(shapes::rounded_rectangle(Rect::new(74.0, -1.1, 86.0, 1.1), 0.8)),
black(shapes::rounded_rectangle(Rect::new(92.0, -0.7, 100.0, 0.7), 0.5)),
]);
let brushes = vec![
art("Laser Bolt", black(laser), Colorization::Tints),
art("Plasma Arc", black(plasma), Colorization::Tints),
art("Charge Wave", black(charge), Colorization::Tints),
art("Spark Trail", spark, Colorization::Tints),
];
built("Energy Beams", Document::new(100.0, 100.0), brushes)
}
// ---------- commands ----------
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
@@ -458,7 +526,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// nothing to apply is no edit, and a click that only applies brushes the document has is
// named for that.
let mut probe = (*st.doc).clone();
let imported = clip.import_into(&mut probe, &choices, false);
let imported = clip.import_into(&mut probe, &choices, false)?;
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] };
let paint = stroke_paint(s);
+2 -2
View File
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Symbol",
[],
None,
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}",
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
has_selection,
symbol_break_link
),
+1 -1
View File
@@ -137,7 +137,7 @@ fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
/// stroke has a Convert to Shape or Outline Object effect.
fn paint_refusal(n: &Node, key: &str, cmd: &str) -> Option<EngineError> {
Some(match &n.kind {
NodeKind::Path { guide: true, .. } => bad(cmd, format!("{key} cannot be set on a guide")),
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => bad(cmd, format!("{key} cannot be set on a guide")),
NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => return None,
NodeKind::Image(_) => {
let effects = if key == "fill" { n.appearance.fill().map(|f| &f.effects) } else { n.appearance.stroke().map(|s| &s.effects) };
+23 -8
View File
@@ -390,10 +390,11 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
most.saturating_add(1).saturating_add(mask)
}
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
/// art's ids. Fails before any edit when the instances together would make more than
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). A hidden or
/// locked instance's art stays hidden or locked. Returns each replaced instance's id with its art's
/// id. Fails before any edit when the instances together would make more than
/// [`MAX_EXPAND_NODES`] objects.
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> {
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<(NodeId, NodeId)>> {
let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own)));
if total > MAX_EXPAND_NODES as u64 {
return Err(EngineError::Other("Too many pieces to make at once".into()));
@@ -401,12 +402,14 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId
let mut out = vec![];
for id in ids {
let Some(inst) = d.node(*id).cloned() else { continue };
let Some(art) = expanded_instance(d, &inst, own) else { continue };
let Some(mut art) = expanded_instance(d, &inst, own) else { continue };
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
art.visible &= inst.visible;
art.locked |= inst.locked;
let aid = art.id;
d.remove(*id)?;
d.insert(par, idx, art)?;
out.push(aid);
out.push((*id, aid));
}
Ok(out)
}
@@ -491,10 +494,22 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
let iso = s.doc()?.isolation;
let out = s.edit("Break Link to Symbol", |d, sel| {
let out = break_links(d, &ids, true)?;
sel.set(out.iter().copied());
Ok(out)
let fresh = d.new_art.get();
let made = break_links(d, &ids, true)?;
// Art that is hidden or locked, or in a hidden or locked group or layer, is left out of the
// selection, as is art on a locked artboard unless the instance it replaces was new art.
let locks = d.locked_artboards();
sel.set(made.iter().filter_map(|(inst, art)| {
let keep = if fresh.contains(inst) {
crate::cmd::select::is_selectable_on_any_artboard(d, iso, *art)
} else {
crate::cmd::select::is_selectable(d, iso, &locks, *art)
};
keep.then_some(*art)
}));
Ok(made.into_iter().map(|(_, art)| art).collect::<Vec<_>>())
})?;
Ok(json!({ "ids": ids_json(&out) }))
}
+63 -2
View File
@@ -210,6 +210,24 @@ pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Op
if pieces.is_empty() { None } else { Some(pieces) }
}
/// Does Copy take `node` unchanged under direct selection, as [`extract_direct_selection`]
/// returning `None` means: no anchors or segments of it are picked, it is not a path, or the
/// picked ones cover every segment?
pub(crate) fn copied_whole(node: &Node, selection: &Selection) -> bool {
let seg_refs = selection.segments.get(&node.id);
let anchor_refs = selection.anchors.get(&node.id);
if seg_refs.is_none() && anchor_refs.is_none() {
return true;
}
let Some(path) = node.path_data() else { return true };
let (mut total_segs, mut total_selected) = (0, 0);
for (si, sp) in path.subpaths.iter().enumerate() {
total_segs += sp.segment_count();
total_selected += subpath_selected_segments(sp, si, seg_refs, anchor_refs).len();
}
total_selected == 0 || total_selected == total_segs
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
@@ -234,15 +252,47 @@ impl Clipboard {
let d = &*st.doc;
let mut nodes = vec![];
let mut source_layers = vec![];
// Each compound's bounds, measured once however many of its members are copied.
let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new();
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
// Gradients fitted to the compound's bounds are pinned there, as a split pins them.
let gradient_box = compound_parent
.filter(|p| p.appearance.has_unplaced_gradient())
.and_then(|p| *compound_bounds.entry(p.id).or_insert_with(|| p.geometric_bounds()));
// A compound's member or piece copied on its own takes the compound's look (its paint,
// transparency, opacity mask, pixel alignment and fill rule), so it pastes as it looked.
// It is linked to the compound's graphic style while it still has that style's look
// (a gradient pinned to the compound's bounds does not), else to none.
let inherit_appearance = |mut piece: Node| {
if let Some(parent) = compound_parent
&& piece.appearance.items.is_empty()
&& let (NodeKind::Compound { rule: compound_rule, .. }, NodeKind::Path { rule, .. }) = (&parent.kind, &mut piece.kind)
{
*rule = *compound_rule;
piece.appearance = parent.appearance.clone();
if let Some(bounds) = gradient_box {
piece.appearance.pin_gradients(bounds);
}
piece.opacity = parent.opacity;
piece.blend = parent.blend;
piece.isolate = parent.isolate;
piece.knockout = parent.knockout;
piece.knockout_shape = parent.knockout_shape;
let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned);
{
let mut extras = piece.extras_mut();
extras.mask = mask;
extras.pixel_aligned = pixel_aligned;
}
let link = parent
.extras()
.graphic_style
.and_then(|g| d.graphic_style_by_id(g))
.filter(|g| super::style::in_sync(&piece, g))
.map(|g| g.id);
piece.extras_mut().graphic_style = link;
}
piece
};
@@ -272,7 +322,18 @@ impl Clipboard {
/// Every object of `src` (each top-level layer's contents) with its resources, for Place and
/// pasting outside SVG. Their layers don't count for Paste Remembers Layers.
pub fn from_document(src: &Document) -> Self {
let nodes = src.layers.iter().flat_map(|l| l.children().into_iter().flatten()).map(|n| (**n).clone()).collect();
// Ruler guides are not objects: the ones of `src`'s layers and sublayers stay behind.
let nodes = src
.layers
.iter()
.flat_map(|l| l.children().into_iter().flatten())
.filter(|n| !n.is_ruler_guide())
.map(|n| {
let mut n = (**n).clone();
n.strip_ruler_guides();
n
})
.collect();
Self::gather(src, nodes)
}
+149 -12
View File
@@ -21,14 +21,14 @@ use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration,
TextStyleDef,
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
SymbolRegistration, TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
use super::super::patterncmds::add_pattern;
use super::super::{Result, bad, unique_name};
use super::super::{EngineError, Result, bad, unique_name};
use super::Clipboard;
/// A resource kind objects refer to (graphic styles by id, the others by name).
@@ -140,6 +140,48 @@ fn node_refs(n: &Node, f: Visit) {
});
}
/// The `(name, xml)` of `e` when it is an SVG filter effect.
fn filter_of(e: &Effect) -> Option<(String, String)> {
let text = |k: &str| e.params.get(k).and_then(Value::as_str).map(str::to_string);
if e.id != Appearance::SVG_FILTER {
return None;
}
Some((text("name")?, text("xml")?))
}
/// The SVG filter effects of appearance `a` (its own and its fills' and strokes').
fn appearance_filters(a: &Appearance, out: &mut BTreeSet<(String, String)>) {
let items = a.items.iter().flat_map(|i| i.effects().iter());
out.extend(a.effects.iter().chain(items).filter_map(filter_of));
}
/// The SVG filter effects in the subtree of `n` (opacity-mask art included).
fn node_filters(n: &Node, out: &mut BTreeSet<(String, String)>) {
n.walk(&mut |m| {
appearance_filters(&m.appearance, out);
if let Some(mask) = &m.extras().mask {
node_filters(&mask.art, out);
}
});
}
/// The names the SVG filter effects of appearance `a` give (its own and its fills' and strokes').
fn appearance_filter_names(a: &Appearance, out: &mut BTreeSet<String>) {
let items = a.items.iter().flat_map(|i| i.effects().iter());
let named = a.effects.iter().chain(items).filter(|e| e.id == Appearance::SVG_FILTER);
out.extend(named.filter_map(|e| e.params.get("name").and_then(Value::as_str)).map(str::to_string));
}
/// The names the SVG filter effects in the subtree of `n` give (opacity-mask art included).
fn node_filter_names(n: &Node, out: &mut BTreeSet<String>) {
n.walk(&mut |m| {
appearance_filter_names(&m.appearance, out);
if let Some(mask) = &m.extras().mask {
node_filter_names(&mask.art, out);
}
});
}
/// A global or spot colour of its own (not a tint of another swatch): what colours link to.
fn is_base(w: &Swatch) -> bool {
(w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. })
@@ -527,6 +569,9 @@ impl SwatchChoices {
#[derive(Clone, Debug, Default)]
struct Relink {
renames: BTreeMap<Res, BTreeMap<String, String>>,
/// An SVG filter effect's `(name, xml)` on the clipboard → its `(name, xml)` in the document
/// ([`Clipboard::filter_links`]).
filters: BTreeMap<(String, String), (String, String)>,
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
@@ -566,6 +611,15 @@ impl Relink {
});
}
fn appearance(&self, a: &mut Appearance) {
if !self.filters.is_empty() {
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items) {
if let Some((name, xml)) = filter_of(e).and_then(|k| self.filters.get(&k)) {
e.params["name"] = json!(name);
e.params["xml"] = json!(xml);
}
}
}
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
@@ -1001,8 +1055,9 @@ impl Clipboard {
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them.
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
/// free name ([`Self::filter_links`]).
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used(d, &self.used(), choices, same_doc, false)
}
@@ -1011,8 +1066,9 @@ impl Clipboard {
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
@@ -1170,8 +1226,89 @@ impl Clipboard {
}
vectorcraft_brush::store(d, &lib);
}
out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty());
out
out.relinks = !(out.relink.renames.is_empty()
&& out.relink.filters.is_empty()
&& out.relink.styles.is_empty()
&& out.relink.colors.is_empty()
&& used.styles.is_empty());
Ok(out)
}
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
/// filter of its name; one that draws another definition than that filter takes the document's
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
let mut found = BTreeSet::new();
for n in &self.nodes {
node_filters(n, &mut found);
}
for s in &self.symbols {
node_filters(&s.art, &mut found);
}
for a in self.patterns.iter().flat_map(|p| p.art.iter()) {
node_filters(a, &mut found);
}
for a in self.brushes.iter().flat_map(Brush::art) {
node_filters(a, &mut found);
}
for g in &self.graphic_styles {
appearance_filters(&g.appearance, &mut found);
}
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
let mut effects_read = false;
let mut links = BTreeMap::new();
for (name, xml) in found {
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
let to = if same_doc {
(name.clone(), held.xml.clone())
} else {
// The names the document's effects give are taken too, those whose filter was
// deleted included: defining a filter of that name later changes every effect that
// names it. They are read at the first rename only.
if !effects_read {
effects_read = true;
for root in d.art_roots() {
node_filter_names(root, &mut taken);
}
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
node_filter_names(a, &mut taken);
}
for g in &d.graphic_styles {
appearance_filter_names(&g.appearance, &mut taken);
}
}
// Free names made from the starts of the name, longest first, then free letters and
// digits, then other single printable ASCII characters: the first under which the
// filter still draws.
let mut ends: Vec<usize> = name.char_indices().map(|(i, _)| i).skip(1).collect();
ends.push(name.len());
let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty());
let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n)));
let single = ('a'..='z')
.chain('0'..='9')
.chain('A'..='Z')
.chain(('!'..='~').filter(|c| !c.is_ascii_alphanumeric()))
.map(String::from)
.filter(|n| !taken.contains(n));
let renamed = shorter.chain(single).find_map(|new| {
let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new)
.filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok_and(|id| id == new))?;
Some((new, drawn))
});
let Some((new, drawn)) = renamed else {
return Err(EngineError::Other(format!(
"the pasted SVG filter {name:?} draws differently from the document's filter of that name, and no free name fits it"
)));
};
taken.insert(new.clone());
(new, drawn)
};
links.insert((name, xml), to);
}
Ok(links)
}
/// Image blobs: a different blob under a key the document uses gets a new key.
@@ -1286,13 +1423,13 @@ pub(crate) struct LoadedStyle {
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
/// used; any other is added under a free name. → each style of `src` placed, in order, character
/// styles first.
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
/// styles first. An error, as [`Clipboard::import_into`] gives.
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Result<Vec<LoadedStyle>> {
let library = OnceCell::new();
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
@@ -1302,7 +1439,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
placed.push(LoadedStyle { para, name, added });
}
}
placed
Ok(placed)
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
+1 -1
View File
@@ -462,7 +462,7 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -
pub(crate) fn left_out(d: &Document, iso: Option<NodeId>, roots: &[NodeId]) -> Vec<(NodeId, bool)> {
fn visit(n: &Node, hidden: bool, locked: bool, all: &HashSet<NodeId>, board_locked: &dyn Fn(&Node) -> bool, out: &mut Vec<(NodeId, bool)>) {
for c in n.children().into_iter().flatten() {
if c.is_template() {
if c.is_template() || c.is_ruler_guide() {
continue;
}
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
+4 -2
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}",
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
@@ -192,6 +192,8 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
// Saved for the next start when the app attached a settings file (#6335).
s.store_color_settings(&st);
touch_all(s);
}
Ok(settings_json(&st))
@@ -580,7 +582,7 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
map_more_colors(Arc::make_mut(c), f);
}
}
@@ -478,6 +478,32 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() {
assert_eq!(actual.cached_bounds, Some(expected));
}
/// Threaded type read from a file flows through its frames in the file's own composite fonts, when
/// no open document defines them.
#[test]
fn an_opened_file_flows_its_threads_in_its_own_composite_fonts() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Threaded")]})).unwrap();
let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(4);
let a = s
.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 20, "font": "CF Threaded", "area": {"width": 150, "height": 60}}))
.unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let first = text(&s, a).plain_text();
assert!(!first.is_empty() && first.len() < story.len());
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
// A new front document without the font: the font database no longer holds it.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(vectorcraft_text::FontDb::global().composite_font("CF Threaded").is_none());
let file = crate::cmd::fileio::read_for_open("threaded.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
crate::cmd::fileio::open_read(&mut s, file).unwrap();
assert_eq!(text(&s, a).plain_text(), first);
}
/// A document replaced while in the back (File › Revert) is measured in its own composite fonts
/// when it comes to the front, not in the front document's.
#[test]
+32 -8
View File
@@ -17,19 +17,43 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, rotation?: deg (about centre)} → {id}",
"{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rectangle
),
cmd!("shape.ellipse", "Ellipse", [], None, "{x, y, width, height, rotation?: deg (about centre)} → {id}", has_doc, ellipse),
cmd!("shape.polygon", "Polygon", [], None, "{cx, cy, radius, sides=6, rotation?: deg} → {id}", has_doc, polygon),
cmd!("shape.star", "Star", [], None, "{cx, cy, radius1, radius2, points=5, rotation?: deg} → {id}", has_doc, star),
cmd!(
"shape.ellipse",
"Ellipse",
[],
None,
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
ellipse
),
cmd!(
"shape.polygon",
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}",
has_doc,
polygon
),
cmd!(
"shape.star",
"Star",
[],
None,
"{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
has_doc,
star
),
cmd!(
"shape.flare",
"Flare",
[],
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg), seed?} → {id}",
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
has_doc,
flare
),
@@ -49,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangular Grid",
[],
None,
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rect_grid
),
@@ -58,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polar Grid",
[],
None,
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
polar_grid
),
@@ -85,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
+231 -27
View File
@@ -3,7 +3,9 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
use serde_json::{Value, json};
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::dimension::{ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, TextAlignment, TextPosition};
use vectorcraft_doc::dimension::{
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
};
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
@@ -14,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}}, offset?: pt, options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -23,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Dimensions",
[],
None,
"{ids?: [dimension ids] (default selection), options?: dimension options, offset?: pt} restyle or move existing dimensions → {ids}",
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
has_doc,
update
),
@@ -92,11 +94,36 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
} else {
Point::ZERO
};
let mut d = Dimension { mode, a, b, vertex, offset: distance(p, 30.0)?, length: a.distance(b), options: options(s, p)?, source, moved: None };
let orientation = orientation(p, mode)?.unwrap_or_default();
let mut d = Dimension {
mode,
a,
b,
vertex,
offset: distance(p, 30.0)?,
length: a.distance(b),
options: options(s, p)?,
source,
orientation,
moved: None,
};
if mode == DimensionMode::Linear {
d.length = d.measured();
}
d.resolve(&s.doc()?.doc).map_err(error)?;
Ok(d)
}
/// The `orientation` param, if given: only a linear dimension is horizontal or vertical.
fn orientation(p: &Value, mode: DimensionMode) -> Result<Option<Orientation>> {
let Some(v) = p.get("orientation") else { return Ok(None) };
let orientation: Orientation = serde_json::from_value(v.clone()).map_err(|_| error("Unknown dimension orientation"))?;
if orientation != Orientation::Aligned && mode != DimensionMode::Linear {
return Err(error("Only linear dimensions are horizontal or vertical"));
}
Ok(Some(orientation))
}
fn insert(doc: &mut Document, parent: Option<NodeId>, dim: Dimension) -> Result<NodeId> {
let id = doc.alloc_id();
let mut group = Node::new(id, NodeKind::Group { children: vec![], clip: false });
@@ -134,21 +161,38 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
return Err(error("Select dimensions to update"));
}
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
s.edit("Update Dimensions", |doc, _| {
// Every dimension is checked before anything changes, and an update that changes none of
// them records no undo step.
let mut next = Vec::with_capacity(ids.len());
{
let doc = &s.doc()?.doc;
for id in &ids {
if !doc.is_editable(*id) {
return Err(error("Dimension is locked or hidden"));
}
let mut dim = dimension_of(doc, *id)?;
let old = dimension_of(doc, *id)?;
let mut dim = old.clone();
if let Some(o) = &o {
dim.options = o.clone();
}
if let Some(orientation) = orientation(p, dim.mode)? {
dim.set_orientation(orientation);
}
dim.offset = distance(p, dim.offset)?;
dim.resolve(doc).map_err(error)?;
replace(doc, *id, dim)?;
if dim != old {
next.push((*id, dim));
}
}
Ok(())
})?;
}
if !next.is_empty() {
s.edit("Update Dimensions", |doc, _| {
for (id, dim) in next {
replace(doc, id, dim)?;
}
Ok(())
})?;
}
Ok(json!({"ids":ids}))
}
@@ -187,9 +231,10 @@ fn apply_to_all(s: &mut Session, p: &Value) -> Result<Value> {
fn replace(doc: &mut Document, id: NodeId, dim: Dimension) -> Result<()> {
let old: Vec<NodeId> = doc.node(id).and_then(Node::children).map(|ch| ch.iter().map(|n| n.id).collect()).unwrap_or_default();
let children = artwork(doc, &dim, &old)?;
let name = format!("Dimension · {}", dim.label().map_err(error)?);
if let Some(n) = doc.node_mut(id) {
n.kind = NodeKind::Group { children, clip: false };
n.name = Some(format!("Dimension · {}", dim.label().map_err(error)?));
n.name = Some(name);
n.extras_mut().dimension = Some(Box::new(dim));
}
Ok(())
@@ -227,8 +272,9 @@ impl EndedLink {
}
/// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it
/// measured. A command that replaces art calls this before it changes anything, since replacing
/// the art a dimension measures would remove the dimension, and then [`restore_unchanged`].
/// measured. A command that replaces art calls this before it changes anything and
/// [`restore_unchanged`] after, so that a dimension whose own art the command changed stays a
/// plain group.
pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink> {
let mut ended = Vec::new();
for id in reached(doc, roots) {
@@ -241,18 +287,156 @@ pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink>
ended
}
/// The dimensions in `ended` whose art is as it was are live again.
pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec<EndedLink>) {
/// The dimensions in `ended` whose own art is as it was are live again. One whose measured art the
/// command changed from `before` so that the art no longer fits its link stays where it was, no
/// longer linked, as [`refresh`] leaves a dimension whose art was deleted.
pub(crate) fn restore_unchanged(before: &Document, doc: &mut Document, ended: Vec<EndedLink>) {
for e in ended {
if doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art)
&& let Some(n) = doc.node_mut(e.id)
{
n.extras_mut().dimension = Some(Box::new(e.recipe));
if !doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art) {
continue;
}
let recipe = if e.source_kept(before, doc) { e.recipe } else { unlinked(&e.recipe) };
if let Some(n) = doc.node_mut(e.id) {
n.extras_mut().dimension = Some(Box::new(recipe));
doc.dimensions = true;
}
}
}
/// `old` where it was, no longer linked. A move it had on its own and not yet drawn is kept when
/// the moved dimension is valid.
fn unlinked(old: &Dimension) -> Dimension {
let mut unlinked = old.clone();
unlinked.source = None;
unlinked.moved = None;
if let Some(v) = old.moved {
let mut shifted = unlinked.clone();
(shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v);
if shifted.validate().is_ok() {
unlinked = shifted;
}
}
unlinked
}
/// The whole dimensions under `roots` that are selected together with art they measure (art under
/// `roots`), each one a root or held by groups without fills, strokes or effects of their own.
/// Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave their
/// lines and label as they are. A group with an appearance of its own changes everything it holds
/// when it expands, its dimensions included.
pub(crate) fn with_their_art(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
if !doc.dimensions {
return Vec::new();
}
let mut found = Vec::new();
for root in roots {
let Some(n) = doc.node(*root) else { continue };
n.walk(&mut |c| {
if let Some(source) = c.extras().dimension.as_ref().and_then(|d| d.source.as_ref()) {
found.push((*root, c.id, source.nodes()));
}
});
}
let under_roots = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().any(|a| roots.contains(a)));
found
.into_iter()
.filter(|(root, id, _)| {
let Some(ancestry) = doc.ancestry(*id) else { return false };
let from = ancestry.iter().position(|a| a == root).unwrap_or(ancestry.len());
ancestry.get(from..ancestry.len().saturating_sub(1)).unwrap_or_default().iter().all(|a| doc.node(*a).is_some_and(plain_group))
})
.filter(|(_, _, measured)| measured.iter().any(|m| under_roots(*m)))
.map(|(_, id, _)| id)
.collect()
}
/// A group or layer without fills, strokes or effects of its own.
fn plain_group(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && n.appearance.items.is_empty() && n.appearance.effects.is_empty()
}
/// A dimension [`lift`] took out of the document, with its place, the export assets that list it or
/// its parts (with their places in the asset list) and its parts' variable bindings.
pub(crate) struct Lifted {
parent: Option<NodeId>,
index: usize,
node: Arc<Node>,
assets: Vec<(usize, vectorcraft_doc::assets::ExportAsset)>,
bindings: Vec<(NodeId, std::collections::BTreeSet<String>)>,
}
impl Lifted {
pub(crate) fn id(&self) -> NodeId {
self.node.id
}
}
/// Takes the [`with_their_art`] dimensions under `roots` out of `doc`, so a command that replaces
/// art does not reach them; [`put_back`] puts them back.
pub(crate) fn lift(doc: &mut Document, roots: &[NodeId]) -> Vec<Lifted> {
let mut lifted = Vec::new();
for id in with_their_art(doc, roots) {
let Some((parent, index, _)) = doc.position(id) else { continue };
let mut parts = std::collections::BTreeSet::new();
if let Some(n) = doc.node(id) {
n.walk(&mut |c| {
parts.insert(c.id);
});
}
let assets = doc.assets.iter().enumerate().filter(|(_, a)| a.nodes.iter().any(|n| parts.contains(n))).map(|(i, a)| (i, a.clone())).collect();
let bindings = doc.variables.bindings.iter().filter(|(n, _)| parts.contains(n)).map(|(n, b)| (*n, b.clone())).collect();
if let Ok(node) = doc.remove(id) {
lifted.push(Lifted { parent, index, node, assets, bindings });
}
}
lifted
}
/// Each dimension [`lift`] took out, as it was, back in its place in `doc`, with its parts back in
/// the export assets that listed them and their variable bindings back: edits made while it was out
/// let go of them. A dimension whose group is gone goes on top of the first layer.
pub(crate) fn put_back(doc: &mut Document, lifted: Vec<Lifted>) {
for l in lifted.into_iter().rev() {
let parent = if doc.children(l.parent).is_some() { l.parent } else { doc.layers.first().map(|layer| layer.id) };
let Ok(ch) = doc.children_mut(parent) else { continue };
let i = if parent == l.parent { l.index.min(ch.len()) } else { ch.len() };
ch.insert(i, l.node);
doc.dimensions = true;
for (at, saved) in l.assets {
let there: Vec<NodeId> = saved.nodes.iter().copied().filter(|n| doc.node(*n).is_some()).collect();
if let Some(a) = doc.assets.iter_mut().find(|a| a.id == saved.id) {
for (k, n) in there.iter().enumerate() {
if !a.nodes.contains(n) {
let k = k.min(a.nodes.len());
a.nodes.insert(k, *n);
}
}
} else if !there.is_empty() {
let at = at.min(doc.assets.len());
doc.assets.insert(at, vectorcraft_doc::assets::ExportAsset { nodes: there, ..saved });
}
}
for (n, b) in l.bindings {
doc.variables.bindings.entry(n).or_insert(b);
}
}
}
/// `doc` without the [`with_their_art`] dimensions under `roots`, to see what a command that leaves
/// them alone would change: `doc` itself when there are none.
pub(crate) fn without_kept<'a>(doc: &'a Document, roots: &[NodeId]) -> std::borrow::Cow<'a, Document> {
let ids = with_their_art(doc, roots);
if ids.is_empty() {
return std::borrow::Cow::Borrowed(doc);
}
let mut view = doc.clone();
for id in ids {
// A dimension already gone (inside another one removed) needs nothing more.
let _ = view.remove(id);
}
std::borrow::Cow::Owned(view)
}
/// Called inside every edit, so dimensions and their undo history stay in step with the art they
/// measure. Returns at once in documents without dimensions.
pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
@@ -271,17 +455,27 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
let mut next = old.clone();
let moved = next.moved.take();
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
// A deleted/degenerate source has no valid measurement. Remove its annotation in
// this same undo step instead of keeping a silently wrong number.
doc.remove(id)?;
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
// same undo step, rather than attaching to a different edge.
if replace(doc, id, unlinked(&old)).is_err()
&& let Some(n) = doc.node_mut(id)
{
// Its recipe cannot be drawn again: its art stays as it is, as a plain group.
n.extras_mut().dimension = None;
}
changed = true;
continue;
}
next.keep_gap(&old);
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
next.mirror_line(&old, xf * old.handle());
}
// Moved on its own (the art it measures stayed put): it keeps its new place.
if let Some(v) = moved
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
{
next.place(next.handle() + v);
next.place(old.handle() + v);
if next.resolve(doc).is_err() {
next = old.clone();
next.moved = None;
@@ -424,17 +618,19 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
text_at = d.vertex + dir * if away { r + gap } else { (r - gap).max(o.font_size * 0.5) };
} else {
let delta = d.b - d.a;
let u = delta / delta.hypot();
// A linear dimension measures along its direction (a → b, or the horizontal or vertical axis).
let u = if d.mode == DimensionMode::Linear { d.direction() } else { delta / delta.hypot() };
let n = Vec2::new(-u.y, u.x);
let (a, b) = match d.mode {
DimensionMode::Radius => (d.a, d.b),
DimensionMode::Diameter => (d.a - delta, d.b),
_ => (d.a + n * d.offset, d.b + n * d.offset),
_ => d.line_ends(),
};
// The side of the line facing away from the object.
// The side of the line facing away from the object: the side the line is on, seen from
// the middle of the measured points.
let outward = match d.mode {
DimensionMode::Linear => {
if d.offset < 0.0 {
if (a.midpoint(b) - d.a.midpoint(d.b)).dot(n) < 0.0 {
-n
} else {
n
@@ -443,8 +639,16 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
_ => n,
};
if d.mode == DimensionMode::Linear && !o.hide_extensions {
// Each extension line runs from its point toward the dimension line, which can lie on
// different sides of the two points of a horizontal or vertical dimension.
for (p, q) in [(d.a, a), (d.b, b)] {
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, mode, true, false)));
let side = (q - p).dot(n);
let toward = match side {
s if s < 0.0 => -n,
s if s > 0.0 => n,
_ => outward,
};
paths.push((line(p + toward * o.extension_offset, q + toward * o.extension_length), appearance(o, mode, true, false)));
}
}
angle = u.atan2();
+3 -3
View File
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Liquify",
[],
None,
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle? (deg clockwise: the brush's width axis from level), intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °, positive turns clockwise), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
has_doc,
liquify
),
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Puppet Warp",
[],
None,
"{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)",
"{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, clockwise, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)",
has_doc,
puppet_warp
),
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Puppet Warp Pins",
[],
None,
"{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp",
"{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg clockwise, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp",
has_doc,
puppet_pins
),
@@ -263,6 +263,22 @@ fn record_again(s: &mut Session, again: Value) -> Result<()> {
Ok(())
}
/// `d` with each of `ids` that is not in perspective attached to `fallback` as [`persp_edit`] attaches
/// it; `d` itself when every one is in perspective already, there is no `fallback`, or one of them
/// cannot attach.
fn with_fallback<'a>(d: &'a Document, ids: &[NodeId], fallback: Option<Plane>) -> std::borrow::Cow<'a, Document> {
let mut g = grid_of(d);
let loose: Vec<NodeId> = ids.iter().copied().filter(|id| g.attachment_of(d, *id).is_none()).collect();
let Some(plane) = fallback.filter(|_| !loose.is_empty()) else { return std::borrow::Cow::Borrowed(d) };
let mut out = d.clone();
for id in loose {
if attach_in(&mut out, &mut g, id, plane, false, None).is_err() {
return std::borrow::Cow::Borrowed(d);
}
}
std::borrow::Cow::Owned(out)
}
fn ids_json(ids: &[NodeId]) -> Value {
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
}
@@ -285,9 +301,11 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
let constrain = switch_or(p, "constrain", false, C)?;
// `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false.
check_switches(p, &["snap"], C)?;
// Shift and Snap to Grid read the objects as they are once those not in perspective are attached.
let doc = if perp { std::borrow::Cow::Borrowed(&*s.doc()?.doc) } else { with_fallback(&s.doc()?.doc, &ids, fallback) };
// Shift: the constrained end point, read on the first object's plane and depth.
let snap_to = if constrain && !perp {
let doc = &s.doc()?.doc;
let doc = &*doc;
let g = grid_of(doc);
g.plane_bounds(doc, &ids)
.and_then(|(plane, depth, _)| {
@@ -305,10 +323,10 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
let fix = if perp {
None
} else {
let doc = &s.doc()?.doc;
crate::cmd::perspgrid::snap_fix(doc, &ids, p, (from, snap_to))
.and_then(|(plane, depth, correction)| Some((plane, grid_of(doc).plane_delta(plane, depth, from, to)?, correction)))
crate::cmd::perspgrid::snap_fix(&doc, &ids, p, (from, snap_to))
.and_then(|(plane, depth, correction)| Some((plane, grid_of(&doc).plane_delta(plane, depth, from, to)?, correction)))
};
drop(doc);
let snapped = move |pl: Plane, raw: vectorcraft_geom::Vec2| {
let raw = fix.filter(|f| f.0 == pl).map_or(raw, |f| f.1);
let (direction, dv) =
+2 -1
View File
@@ -370,7 +370,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
return;
}
let k = match &n.kind {
NodeKind::Layer { .. } => None,
// The Guides row counts paths made into guides; ruler guides are not objects.
NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => None,
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
NodeKind::Group { .. } => Some("groups"),
NodeKind::Path { guide: true, .. } => Some("guides"),
+64 -46
View File
@@ -666,7 +666,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
if (index.is_some() || ids.is_some()) && s.menu.guides_locked {
return Err(EngineError::Other("guides are locked".into()));
}
let (rulers, paths): (Vec<usize>, Vec<NodeId>) = if index.is_some() || ids.is_some() {
let (rulers, paths): (Vec<NodeId>, Vec<NodeId>) = if index.is_some() || ids.is_some() {
let rulers = match index {
Some(v) => vec![editable_guide_index(s, Some(v), C)?],
None => vec![],
@@ -689,10 +689,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let all = guide_paths(&st.doc);
let sel: Vec<NodeId> = all.iter().copied().filter(|id| st.selection.contains(*id)).collect();
let rulers: Vec<usize> = if s.menu.guides_locked {
let rulers: Vec<NodeId> = if s.menu.guides_locked {
vec![]
} else {
st.selection.guides.iter().copied().filter(|i| st.doc.guides.get(*i).is_some_and(|g| st.doc.guide_editable(g))).collect()
st.selection.guides.iter().copied().filter(|id| st.doc.ruler_guide(*id).is_some_and(|g| st.doc.guide_editable(&g))).collect()
};
let editable = st.doc.editable();
if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| editable(*id)).collect()) } else { (rulers, sel) }
@@ -702,8 +702,8 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b));
let mut lines = Vec::with_capacity(rulers.len());
for &i in &rulers {
let Some(g) = st.doc.guides.get(i) else { continue };
let span = st.doc.guide_span(g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }));
let Some(g) = st.doc.ruler_guide(i) else { continue };
let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }));
let Some((a, b)) = span else { continue };
let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) };
let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) {
@@ -729,7 +729,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
d.insert(parent, usize::MAX, Node::path(id, vectorcraft_geom::shapes::line(a, b), look))?;
made.push(id);
}
d.retain_guides(sel, |i, _| !lines.iter().any(|l| l.0 == i));
d.retain_guides(sel, |g| !lines.iter().any(|l| Some(l.0) == g.id));
sel.set(paths.iter().copied().chain(made));
Ok(())
})?;
@@ -745,12 +745,12 @@ fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let paths = guide_paths(&st.doc);
let n = paths.len() + st.doc.guides.len();
let n = paths.len() + st.doc.ruler_guides().len();
if n == 0 {
return Ok(json!({ "count": 0 }));
}
s.edit("Clear Guides", |d, _| {
d.guides.clear();
s.edit("Clear Guides", |d, sel| {
d.retain_guides(sel, |_| false);
let mut gone = Beside::replacing(d, &paths);
for id in &paths {
if d.node(*id).is_some() {
@@ -780,17 +780,29 @@ fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
// Where new art goes (refused when no layer is shown and unlocked), or that group's layer.
None => st.target_parent()?.and_then(|p| if st.doc.node(p).is_some_and(Node::is_layer) { Some(p) } else { st.doc.layer_containing(p) }),
};
let i = s.edit("New Guide", |d, _| {
d.guides.push(Guide { artboard, layer, ..Guide::new(vertical, pos) });
Ok(d.guides.len() - 1)
})?;
let id = s.edit("New Guide", |d, _| Ok(d.add_ruler_guide(&Guide { artboard, layer, ..Guide::new(vertical, pos) })))?;
let i = guide_indexes(&s.doc()?.doc, &[id]).first().copied();
Ok(json!({ "index": i }))
}
/// The ids of the active document's ruler guides by index: the order of `guide.list` (ascending
/// id).
pub(crate) fn guide_ids(d: &vectorcraft_doc::Document) -> Vec<NodeId> {
d.ruler_guides().into_iter().filter_map(|g| g.id).collect()
}
/// The `guide.list` indexes of ruler guides `ids`, in the order of `ids` (an id that is not a ruler
/// guide is left out).
pub fn guide_indexes(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<usize> {
let all = guide_ids(d);
ids.iter().filter_map(|id| all.binary_search(id).ok()).collect()
}
fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let row = |(i, g): (usize, &Guide)| {
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": st.selection.guides.contains(&i) });
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
r["artboard"] = json!(ab);
}
@@ -801,31 +813,38 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
r["editable"] = json!(st.doc.guide_editable(g));
r
};
Ok(Value::Array(st.doc.guides.iter().enumerate().map(row).collect()))
Ok(Value::Array(st.doc.ruler_guides().iter().enumerate().map(row).collect()))
}
/// Ruler guide `index` of the active document (`index` validated).
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> {
/// The id of ruler guide `index` in `ids` ([`guide_ids`]; `index` validated).
fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId> {
let i = v.and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "an index must be a whole number"))?;
if i >= s.doc()?.doc.guides.len() {
return Err(bad(cmd, format!("no guide {i}")));
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
}
/// The id of ruler guide `index` of the active document (`index` validated).
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
}
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
let d = &s.doc()?.doc;
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
}
Ok(i)
Ok(id)
}
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> {
let i = guide_index(s, v, cmd)?;
let d = &s.doc()?.doc;
if !d.guides.get(i).is_some_and(|g| d.guide_editable(g)) {
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
}
Ok(i)
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
check_editable_guide(s, guide_index(s, v, cmd)?)
}
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
let picked = list.iter().map(|v| guide_index(s, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
let ids = guide_ids(&s.doc()?.doc);
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
if bool_or(p, "toggle", false) {
// Added to (or taken from) what is selected, the art included.
s.select(|_, sel| {
@@ -836,12 +855,13 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
} else {
s.select(|_, sel| sel.set_guides(picked))?;
}
Ok(json!({ "selected": s.doc()?.selection.guides }))
let st = s.doc()?;
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
}
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
let gone: Vec<usize> = match p.get("index") {
let gone: Vec<NodeId> = match p.get("index") {
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
None => s.doc()?.selection.guides.clone(),
};
@@ -850,7 +870,7 @@ pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
}
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
s.edit(label, |d, sel| {
d.retain_guides(sel, |i, _| !gone.contains(&i));
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
Ok(())
})?;
Ok(json!({ "count": gone.len() }))
@@ -866,18 +886,22 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
if super::layer::locked_within(d, layer) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let moving: Vec<usize> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
(None, Some(list)) => list.iter().take(10_000).map(|v| editable_guide_index(s, Some(v), C)).collect::<Result<Vec<_>>>()?,
(None, Some(list)) => {
let ids = guide_ids(&s.doc()?.doc);
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
}
(None, None) => s.doc()?.selection.guides.clone(),
};
if moving.is_empty() {
return Err(bad(C, "no guide selected (or give an index)"));
}
s.edit("Move Guide to Layer", |d, _| {
for i in &moving {
if let Some(g) = d.guides.get_mut(*i) {
g.layer = Some(layer);
// Each keeps its id (and so its index), at the top of the layer.
for id in &moving {
if d.parent_of(*id) != Some(layer) && d.ruler_guide(*id).is_some() {
d.move_node(*id, Some(layer), usize::MAX)?;
}
}
Ok(())
@@ -891,9 +915,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let i = editable_guide_index(s, Some(v), "guide.move")?;
let pos = f64_req(p, "pos", "guide.move")?;
s.edit("Move Guide", |d, _| {
if let Some(g) = d.guides.get_mut(i) {
g.pos = pos;
}
d.edit_ruler_guide(i, |g| g.pos = pos);
Ok(())
})?;
return ok();
@@ -917,18 +939,14 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(if copy { "Copy Guide" } else { "Move Guide" }, |d, sel| {
let mut copies = vec![];
for &i in &moving {
let Some(g) = d.guides.get_mut(i) else { continue };
let moved = g.moved(Vec2::new(dx, dy));
if copy {
copies.push(moved);
copies.extend(d.ruler_guide(i).map(|g| d.add_ruler_guide(&g.moved(Vec2::new(dx, dy)))));
} else {
*g = moved;
d.edit_ruler_guide(i, |g| *g = g.moved(Vec2::new(dx, dy)));
}
}
if copy {
let first = d.guides.len();
d.guides.extend(copies);
sel.set_guides(first..d.guides.len());
sel.set_guides(copies);
}
Ok(())
})?;
+2 -2
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Path",
[],
None,
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two → {ids}",
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}",
has_doc,
split
),
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
has_doc,
erase_region
),
+10 -3
View File
@@ -200,9 +200,16 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(EngineError::Other("no such segment".into())),
};
let mut pieces = sp.cut_at(&std::collections::BTreeSet::from([k]));
// The cut leaves one of its two coincident end points selected, as `path.cutAtAnchors`
// does, so a Direct Selection drag pulls the path apart there.
let pick = |sel: &mut vectorcraft_doc::Selection, id: NodeId, si: usize| {
sel.clear();
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, 0));
};
if sp.closed {
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
sel.set([id]);
pick(sel, id, si);
return Ok(vec![id]);
}
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
@@ -211,12 +218,12 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
let node = sibling_with(d, id, PathData::single(right))?;
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let nid = d.insert(parent, idx + 1, node)?;
sel.set([id, nid]);
pick(sel, nid, 0);
Ok(vec![id, nid])
} else {
path.subpaths[si] = left;
path.subpaths.insert(si + 1, right);
sel.set([id]);
pick(sel, id, si + 1);
Ok(vec![id])
}
})?;
+46 -30
View File
@@ -157,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
has_selection_guides_or_artboard_tool,
cut
),
@@ -166,7 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides); without ids, refused while an object of a symbol instance's art is selected",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -931,7 +931,11 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
})
}
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
/// The direct-selection flag and resolved root nodes for Copy and Cut operations. A compound-path
/// member selected on its own (whole, with Direct or Group Selection, or by some of its anchors or
/// segments) is taken as itself, so Copy copies it as an ordinary path and Cut removes it alone. The
/// compound is taken whole when it is selected, or when every one of its members is selected whole
/// outside isolation mode; in an isolated compound every member is taken as itself.
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let st = s.doc()?;
// The Pen and the Curvature tool leave the anchor they placed or edited selected: Copy takes
@@ -940,9 +944,19 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature") && !picked;
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member)))
});
// A member counts as selected whole when Copy would take it unchanged: no anchors or segments
// of it are picked, the picked ones cover every segment, or a drawing tool's own anchor is
// all that is picked.
let selected: std::collections::HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let whole = |m: &vectorcraft_doc::Node| selected.contains(&m.id) && (!direct || super::clipboard::copied_whole(m, &st.selection));
// Worked out once per compound: every selected member asks about its compound.
let checked = std::cell::RefCell::new(std::collections::HashMap::new());
let all_members_whole = |compound: NodeId| {
*checked.borrow_mut().entry(compound).or_insert_with(|| {
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
})
};
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
Ok((direct, roots))
}
@@ -977,8 +991,8 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
.selection
.guides
.iter()
.filter_map(|i| st.doc.guides.get(*i))
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
.filter_map(|i| st.doc.ruler_guide(*i))
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, id: None, ..g })
.collect();
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets };
let mut clip = Clipboard::copy(st, &roots, direct);
@@ -990,7 +1004,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
// measure from, as the objects' artboard is.
if clip.nodes.is_empty()
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i))
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.ruler_guide(*i))
{
let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| {
st.doc
@@ -1016,8 +1030,8 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
copy(s, p)?;
return clear(s, &json!({}));
}
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
// Cut removes the same objects Copy takes: a compound member selected on its own, or the
// whole compound when it is selected or every member is selected whole.
let (direct, roots) = copy_cut_targets(s)?;
let res = copy(s, p)?;
if res.get("copied").and_then(Value::as_u64) == Some(0) {
@@ -1039,18 +1053,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
s.edit("Cut", |d, selection| {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct {
d.remove(*id)?;
continue;
}
if node.path_data().is_none() {
d.remove(*id)?;
if !has_direct || node.path_data().is_none() {
remove_leaving_no_empty_compound(d, *id)?;
continue;
}
let original = super::path::deletion_source(d, *id)?;
@@ -1073,13 +1083,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(*id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
remove_leaving_no_empty_compound(d, *id)?;
} else {
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
@@ -1093,6 +1097,19 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
/// A compound left with one member stays a compound path, as after Clear.
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
@@ -1136,7 +1153,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
}
if with_guides {
let gone = sel.guides.clone();
d.retain_guides(sel, |i, _| !gone.contains(&i));
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
if is_explicit {
for id in &ids {
@@ -1315,7 +1332,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
vec![Affine::IDENTITY]
};
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
let imported = clip.import_into(d, choices, same_doc);
let imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1421,8 +1438,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for g in &clip.guides {
let pos = g.pos + if g.vertical { dv.x } else { dv.y };
if pos.is_finite() {
sel.guides.push(d.guides.len());
d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() });
sel.guides.push(d.add_ruler_guide(&vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() }));
}
}
}
Loaded 100 of 592 files, more files were not shown because too many files have changed in this diff. Show more