mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60a31926e4 | ||
|
|
88b774f184 | ||
|
|
ae88f4a3de | ||
|
|
930278128d | ||
|
|
b5975e92b2 | ||
|
|
c1b15fcfdf | ||
|
|
dc0ae74cab | ||
|
|
4344f28909 | ||
|
|
8e5abf65cb | ||
|
|
e520c21b66 | ||
|
|
ca5ca863cc | ||
|
|
990d5b37cf | ||
|
|
301368a0df | ||
|
|
34dced38ba | ||
|
|
6b69a75391 | ||
|
|
13226f7049 | ||
|
|
68985868fa | ||
|
|
14d90195ad | ||
|
|
3489f9ddb1 | ||
|
|
d721bca85f | ||
|
|
006209c5d0 | ||
|
|
579bedd9ff | ||
|
|
e238753a35 | ||
|
|
8a3f133140 | ||
|
|
643d7b4432 | ||
|
|
f3720bf6f2 | ||
|
|
aa3c214bf7 | ||
|
|
781271782c | ||
|
|
eda858b6e2 | ||
|
|
96a0dada92 | ||
|
|
f72263f4f8 | ||
|
|
4696004dc9 | ||
|
|
4dfeafd65e | ||
|
|
33a31b4f17 | ||
|
|
04d7adb867 | ||
|
|
a1d85779ba | ||
|
|
878f5d3bf7 | ||
|
|
477a3f6670 | ||
|
|
b0384adabc | ||
|
|
bf7caef6fb | ||
|
|
57bf2f873e | ||
|
|
cea1a1c6a8 | ||
|
|
523cc27523 | ||
|
|
6111440afd | ||
|
|
5cacab2e39 | ||
|
|
2696abc6b3 | ||
|
|
cb4289169d | ||
|
|
76ecdc8f1b | ||
|
|
4d2e1d57fd | ||
|
|
fbefa5b827 | ||
|
|
b564579362 | ||
|
|
f6e592da5b | ||
|
|
3496e22f55 | ||
|
|
2cee9e24cd | ||
|
|
63cce26755 | ||
|
|
8a8e496058 | ||
|
|
c4678336e5 | ||
|
|
80f38d91c0 | ||
|
|
487b17a8d7 | ||
|
|
899ed5ad85 | ||
|
|
66a297df2c | ||
|
|
ddb2d744d4 | ||
|
|
9236bfcec0 | ||
|
|
6c1ccfb5bb | ||
|
|
f624edb801 | ||
|
|
e57637aab1 | ||
|
|
ea59f10b50 | ||
|
|
7a2144e31e | ||
|
|
ebf351277d | ||
|
|
2615d86934 | ||
|
|
a8e209e44c | ||
|
|
77f8bfd9ed | ||
|
|
6e7f218068 | ||
|
|
54b4ef145c | ||
|
|
5861e635fb | ||
|
|
d3b5dc5712 | ||
|
|
0022680336 | ||
|
|
c9984a8f1a | ||
|
|
4487020efb | ||
|
|
db34ac3f53 | ||
|
|
a6ff221c1e | ||
|
|
916cca4a63 | ||
|
|
1427fb93f9 | ||
|
|
9ef9b205d9 | ||
|
|
9303953cf8 | ||
|
|
2fc4896d01 | ||
|
|
1a81e45673 | ||
|
|
1f7a9188ba | ||
|
|
0a65e570a9 | ||
|
|
d5cb380328 | ||
|
|
12896a2407 | ||
|
|
90be1f42c6 | ||
|
|
23b2c5bdf2 | ||
|
|
da38f672ae | ||
|
|
478ace3349 | ||
|
|
80b8df8d42 | ||
|
|
0c3cae2ba5 | ||
|
|
d445bffe31 | ||
|
|
2dee47a6ee | ||
|
|
e60a9c36d8 | ||
|
|
471ef87801 | ||
|
|
d39308c048 | ||
|
|
3d37ef79ac | ||
|
|
a4a0e110d7 | ||
|
|
ac9fb2b02d | ||
|
|
a29802de36 | ||
|
|
5e0e11b4c1 | ||
|
|
704dad4f76 |
No files matched your search
File renamed without changes.
@@ -84,6 +84,8 @@ jobs:
|
||||
mold -run cargo fmt --all -- --check
|
||||
|
||||
- name: 🦀 Build Rust code
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
run: |
|
||||
mold -run cargo build --all-features
|
||||
|
||||
|
||||
@@ -9,8 +9,6 @@ env:
|
||||
|
||||
jobs:
|
||||
profile:
|
||||
# TODO(TrueDoctor): Fix and reenable this action
|
||||
if: false
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -48,7 +46,7 @@ jobs:
|
||||
|
||||
- name: Run baseline benchmarks
|
||||
run: |
|
||||
cargo bench --bench compile_demo_art --features=iai -- --save-baseline=master
|
||||
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
|
||||
|
||||
- name: Checkout PR branch
|
||||
run: |
|
||||
@@ -57,7 +55,7 @@ jobs:
|
||||
- name: Run PR benchmarks
|
||||
id: benchmark
|
||||
run: |
|
||||
BENCH_OUTPUT=$(cargo bench --bench compile_demo_art --features=iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g')
|
||||
BENCH_OUTPUT=$(cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g')
|
||||
echo "BENCHMARK_OUTPUT<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$BENCH_OUTPUT" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
@@ -13,7 +13,7 @@ on:
|
||||
- website/**
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.rs" data-api="/visit/event" src="/visit/script.js"></script>
|
||||
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.rs" data-api="/visit/event" src="/visit/script.hash.js"></script>
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
- name: 🕸 Install Zola
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: zola@0.19.1
|
||||
tool: zola@0.20.0
|
||||
|
||||
- name: ✂ Replace template in <head> of index.html
|
||||
run: |
|
||||
@@ -42,7 +42,8 @@ jobs:
|
||||
MODE: prod
|
||||
run: |
|
||||
cd website
|
||||
zola --config config_prod.toml build
|
||||
npm run install-fonts
|
||||
zola --config config.toml build --minify
|
||||
|
||||
- name: 🔍 Check if `website/other` directory changed
|
||||
uses: dorny/paths-filter@v3
|
||||
|
||||
+1
-1
@@ -4,4 +4,4 @@ target/
|
||||
perf.data*
|
||||
profile.json
|
||||
flamegraph.svg
|
||||
|
||||
.idea/
|
||||
Generated
+9
-9
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1743583204,
|
||||
"narHash": "sha256-F7n4+KOIfWrwoQjXrL2wD9RhFYLs2/GGe/MQY1sSdlE=",
|
||||
"lastModified": 1748190013,
|
||||
"narHash": "sha256-R5HJFflOfsP5FBtk+zE8FpL8uqE7n62jqOsADvVshhE=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "5135c59491985879812717f4c9fea69604e7f26f",
|
||||
"rev": "62b852f6c6742134ade1abdd2a21685fd617a291",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -36,11 +36,11 @@
|
||||
},
|
||||
"nixpkgs-unstable": {
|
||||
"locked": {
|
||||
"lastModified": 1739214665,
|
||||
"narHash": "sha256-26L8VAu3/1YRxS8MHgBOyOM8xALdo6N0I04PgorE7UM=",
|
||||
"lastModified": 1748190013,
|
||||
"narHash": "sha256-R5HJFflOfsP5FBtk+zE8FpL8uqE7n62jqOsADvVshhE=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "2c8d3f48d33929642c1c12cd243df4cc7d2ce434",
|
||||
"rev": "62b852f6c6742134ade1abdd2a21685fd617a291",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -65,11 +65,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1743682350,
|
||||
"narHash": "sha256-S/MyKOFajCiBm5H5laoE59wB6w0NJ4wJG53iAPfYW3k=",
|
||||
"lastModified": 1748399823,
|
||||
"narHash": "sha256-kahD8D5hOXOsGbNdoLLnqCL887cjHkx98Izc37nDjlA=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "c4a8327b0f25d1d81edecbb6105f74d7cf9d7382",
|
||||
"rev": "d68a69dc71bc19beb3479800392112c2f6218159",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
pkgs.git
|
||||
pkgs.gobject-introspection
|
||||
pkgs-unstable.cargo-tauri
|
||||
pkgs-unstable.cargo-about
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
|
||||
Generated
+4
-215
@@ -230,15 +230,6 @@ dependencies = [
|
||||
"libloading 0.8.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-mutex"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "479db852db25d9dbf6204e6cb6253698f175c15726470f78af0d918e99d6156e"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atk"
|
||||
version = "0.18.2"
|
||||
@@ -385,7 +376,6 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -864,37 +854,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compilation-client"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dyn-any",
|
||||
"gpu-compiler-bin-wrapper",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compilation-server"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"futures",
|
||||
"gpu-compiler-bin-wrapper",
|
||||
"graph-craft",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tower-http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "concurrent-queue"
|
||||
version = "2.5.0"
|
||||
@@ -1390,7 +1349,6 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"dyn-any-derive",
|
||||
"glam",
|
||||
"log",
|
||||
"reqwest",
|
||||
]
|
||||
|
||||
@@ -1503,12 +1461,6 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "2.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.73.0"
|
||||
@@ -2030,8 +1982,6 @@ version = "0.29.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc46dd3ec48fdd8e693a98d2b8bafae273a2d54c1de02a2a7e3d57d501f39677"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"libm",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -2151,19 +2101,6 @@ dependencies = [
|
||||
"windows 0.58.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpu-compiler-bin-wrapper"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpu-descriptor"
|
||||
version = "0.3.1"
|
||||
@@ -2184,41 +2121,19 @@ dependencies = [
|
||||
"bitflags 2.9.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpu-executor"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bytemuck",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"log",
|
||||
"node-macro",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-craft"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bezier-rs",
|
||||
"bytemuck",
|
||||
"criterion",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"iai-callgrind",
|
||||
"js-sys",
|
||||
"log",
|
||||
"num-traits",
|
||||
"pretty_assertions",
|
||||
"reqwest",
|
||||
"rustc-hash 2.1.1",
|
||||
@@ -2228,7 +2143,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu-executor",
|
||||
"winit",
|
||||
@@ -2238,25 +2152,16 @@ dependencies = [
|
||||
name = "graphene-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bezier-rs",
|
||||
"bitflags 2.9.0",
|
||||
"chrono",
|
||||
"clap",
|
||||
"dyn-any",
|
||||
"fern",
|
||||
"futures",
|
||||
"glam",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"image",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"wasm-bindgen",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
]
|
||||
@@ -2273,7 +2178,6 @@ dependencies = [
|
||||
"glam",
|
||||
"half",
|
||||
"image",
|
||||
"js-sys",
|
||||
"kurbo",
|
||||
"log",
|
||||
"math-parser",
|
||||
@@ -2288,12 +2192,10 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"spirv-std",
|
||||
"tinyvec",
|
||||
"tokio",
|
||||
"usvg",
|
||||
"vello",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -2305,18 +2207,13 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bezier-rs",
|
||||
"bytemuck",
|
||||
"compilation-client",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam",
|
||||
"gpu-compiler-bin-wrapper",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"image",
|
||||
"image-compare",
|
||||
"js-sys",
|
||||
"log",
|
||||
"ndarray",
|
||||
"node-macro",
|
||||
@@ -2324,21 +2221,13 @@ dependencies = [
|
||||
"rand 0.9.0",
|
||||
"rand_chacha 0.9.0",
|
||||
"reqwest",
|
||||
"resvg",
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"url",
|
||||
"usvg",
|
||||
"vello",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
"wgpu-types",
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2352,8 +2241,6 @@ dependencies = [
|
||||
"graphite-editor",
|
||||
"log",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-http",
|
||||
@@ -2365,23 +2252,19 @@ dependencies = [
|
||||
name = "graphite-editor"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-mutex",
|
||||
"bezier-rs",
|
||||
"bitflags 2.9.0",
|
||||
"convert_case 0.7.1",
|
||||
"derivative",
|
||||
"dyn-any",
|
||||
"env_logger",
|
||||
"futures",
|
||||
"glam",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"graphite-proc-macros",
|
||||
"image",
|
||||
"interpreted-executor",
|
||||
"js-sys",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num_enum",
|
||||
"once_cell",
|
||||
@@ -2414,8 +2297,6 @@ dependencies = [
|
||||
name = "graphite-wasm"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"bezier-rs",
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
@@ -2423,7 +2304,6 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"math-parser",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
"wasm-bindgen",
|
||||
@@ -2962,18 +2842,6 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image-compare"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96cd73af13ae2e7220a1c02fe7d6bb53be50612ba7fabbb5c88e7753645f1f3c"
|
||||
dependencies = [
|
||||
"image",
|
||||
"itertools 0.12.1",
|
||||
"rayon",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image-webp"
|
||||
version = "0.1.3"
|
||||
@@ -3062,17 +2930,12 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
"glob",
|
||||
"gpu-executor",
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"iai-callgrind",
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
@@ -3361,7 +3224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-targets 0.52.6",
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3477,7 +3340,6 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"num-complex",
|
||||
"pest",
|
||||
"pest_derive",
|
||||
@@ -3810,7 +3672,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3834,15 +3695,6 @@ dependencies = [
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nvtx"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad2e855e8019f99e4b94ac33670eb4e4f570a2e044f3749a0b2c7f83b841e52c"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc"
|
||||
version = "0.2.7"
|
||||
@@ -5690,15 +5542,6 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.7"
|
||||
@@ -5905,34 +5748,6 @@ dependencies = [
|
||||
"bitflags 2.9.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git#6e2c84d4fe64e32df4c060c5a7f3e35a32e45421"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"glam",
|
||||
"num-traits",
|
||||
"spirv-std-macros",
|
||||
"spirv-std-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std-macros"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git#6e2c84d4fe64e32df4c060c5a7f3e35a32e45421"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"spirv-std-types",
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spirv-std-types"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/Rust-GPU/rust-gpu.git#6e2c84d4fe64e32df4c060c5a7f3e35a32e45421"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.0"
|
||||
@@ -6634,17 +6449,15 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.44.0"
|
||||
version = "1.45.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9975ea0f48b5aa3972bf2d888c238182458437cc2a19374b81b25cdf1023fb3a"
|
||||
checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.52.0",
|
||||
@@ -6766,20 +6579,6 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697"
|
||||
dependencies = [
|
||||
"bitflags 2.9.0",
|
||||
"bytes",
|
||||
"http",
|
||||
"pin-project-lite",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
@@ -7584,21 +7383,11 @@ name = "wgpu-executor"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bytemuck",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"futures-intrusive",
|
||||
"glam",
|
||||
"gpu-executor",
|
||||
"graphene-core",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"num-traits",
|
||||
"nvtx",
|
||||
"serde",
|
||||
"spirv",
|
||||
"vello",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
|
||||
+49
-23
@@ -10,18 +10,13 @@ members = [
|
||||
"node-graph/graphene-cli",
|
||||
"node-graph/interpreted-executor",
|
||||
"node-graph/node-macro",
|
||||
"node-graph/compilation-server",
|
||||
"node-graph/compilation-client",
|
||||
"node-graph/wgpu-executor",
|
||||
"node-graph/gpu-executor",
|
||||
"node-graph/gpu-compiler/gpu-compiler-bin-wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/path-bool",
|
||||
"libraries/bezier-rs",
|
||||
"libraries/math-parser",
|
||||
"website/other/bezier-rs-demos/wasm",
|
||||
]
|
||||
exclude = ["node-graph/gpu-compiler"]
|
||||
default-members = [
|
||||
"editor",
|
||||
"frontend/wasm",
|
||||
@@ -36,19 +31,21 @@ resolver = "2"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Local dependencies
|
||||
dyn-any = { path = "libraries/dyn-any", features = ["derive", "glam", "reqwest"] }
|
||||
graphene-core = { path = "node-graph/gcore" }
|
||||
graph-craft = { path = "node-graph/graph-craft", features = ["serde"] }
|
||||
wgpu-executor = { path = "node-graph/wgpu-executor" }
|
||||
bezier-rs = { path = "libraries/bezier-rs", features = ["dyn-any"] }
|
||||
path-bool = { path = "libraries/path-bool", default-features = false }
|
||||
bezier-rs = { path = "libraries/bezier-rs", features = ["dyn-any", "serde"] }
|
||||
dyn-any = { path = "libraries/dyn-any", features = ["derive", "glam", "reqwest", "log-bad-types", "rc"] }
|
||||
math-parser = { path = "libraries/math-parser" }
|
||||
path-bool = { path = "libraries/path-bool" }
|
||||
graphene-core = { path = "node-graph/gcore" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
graphene-std = { path = "node-graph/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
node-macro = { path = "node-graph/node-macro" }
|
||||
wgpu-executor = { path = "node-graph/wgpu-executor" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
bytemuck = { version = "1.13", features = ["derive"] }
|
||||
async-trait = "0.1"
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
@@ -60,36 +57,54 @@ bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
convert_case = "0.7"
|
||||
derivative = "2.2"
|
||||
tempfile = "3.6"
|
||||
thiserror = "2"
|
||||
anyhow = "1.0"
|
||||
proc-macro2 = "1"
|
||||
proc-macro2 = { version = "1", features = [ "span-locations" ] }
|
||||
quote = "1.0"
|
||||
axum = "0.8"
|
||||
chrono = "0.4"
|
||||
ron = "0.8"
|
||||
fastnoise-lite = "1.1"
|
||||
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git" }
|
||||
wgpu-types = "23"
|
||||
wgpu = "23"
|
||||
wgpu = { version = "23", features = [
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove when `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) is stabilized in Rust 1.80 and we bump our MSRV
|
||||
wasm-bindgen = "=0.2.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.77"
|
||||
web-sys = "=0.3.77"
|
||||
web-sys = { version = "=0.3.77", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
"HtmlCanvasElement",
|
||||
"CanvasRenderingContext2d",
|
||||
"CanvasPattern",
|
||||
"OffscreenCanvas",
|
||||
"OffscreenCanvasRenderingContext2d",
|
||||
"TextMetrics",
|
||||
"Window",
|
||||
"IdleRequestOptions",
|
||||
"ImageData",
|
||||
"Navigator",
|
||||
"Gpu",
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
winit = "0.29"
|
||||
url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "io-std"] }
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt"] }
|
||||
vello = { git = "https://github.com/linebender/vello.git", rev = "3275ec8" } # TODO switch back to stable when a release is made
|
||||
resvg = "0.44"
|
||||
usvg = "0.44"
|
||||
rand = { version = "0.9", default-features = false }
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.29", default-features = false, features = ["serde"] }
|
||||
glam = { version = "0.29", default-features = false, features = ["serde", "scalar-math", "debug-glam-assert"] }
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp"] }
|
||||
rustybuzz = "0.20"
|
||||
spirv = "0.3"
|
||||
pretty_assertions = "1.4.1"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
num_enum = "0.7"
|
||||
@@ -103,11 +118,22 @@ specta = { version = "2.0.0-rc.22", features = [
|
||||
syn = { version = "2.0", default-features = false, features = [
|
||||
"full",
|
||||
"derive",
|
||||
"parsing",
|
||||
"printing",
|
||||
"visit-mut",
|
||||
"visit",
|
||||
"clone-impls",
|
||||
"extra-traits",
|
||||
"proc-macro",
|
||||
] }
|
||||
kurbo = { version = "0.11.0", features = ["serde"] }
|
||||
petgraph = { version = "0.7.1", default-features = false, features = [
|
||||
"graphmap",
|
||||
] }
|
||||
half = { version = "2.4.1", default-features = false, features = ["bytemuck", "serde"] }
|
||||
tinyvec = { version = "1" }
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
iai-callgrind = { version = "0.12.3" }
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0,"lambda":false}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0,"lambda":false}},{"Node":{"node_id":1250460246919467000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[13690529431936890000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Node":{"node_id":13897409604737649000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"U32":5},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"u32","alias":null}},"import_index":2}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::PoissonDiskPointsNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::transform::BoundlessFootprintNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::transform::FreezeRealTimeNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MemoNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[8226419277180271000,{"inputs":[{"Node":{"node_id":14061026919898233000,"output_index":0,"lambda":false}},{"Node":{"node_id":11448859343137378000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_iLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0,"lambda":false}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0,"lambda":false}},{"Node":{"node_id":12796400626461303056,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[17021405646895729000,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":1.0,"green":0.31764707,"blue":0.15686275,"alpha":1.0}],[0.5,{"red":1.0,"green":0.5686275,"blue":0.25490198,"alpha":1.0}],[1.0,{"red":1.0,"green":0.7294118,"blue":0.16078432,"alpha":1.0}]]},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::GradientValueNode"}},"visible":true,"skip_deduplication":false}],[8366826746721323000,{"inputs":[{"Node":{"node_id":5591755359500854000,"output_index":0,"lambda":false}},{"Node":{"node_id":13846904447064916285,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"graphene_core::vectoLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0,"lambda":false}}],"nodes":[[10507084483235320484,{"inputs":[{"Node":{"node_id":9157963288496356916,"output_index":0,"lambda":false}},{"Node":{"node_id":1396768435017101055,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[4741515246389989284,{"inputs":[{"Node":{"node_id":14255588039347536657,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[4105329493214975815,{"inputs":[{"Node":{"node_id":12931264630175648107,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[-261.24355652969916,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0,"lambda":false}}],"nodes":[[10507084483235320484,{"inputs":[{"Node":{"node_id":9157963288496356916,"output_index":0,"lambda":false}},{"Node":{"node_id":1396768435017101055,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[4741515246389989284,{"inputs":[{"Node":{"node_id":14255588039347536657,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[4105329493214975815,{"inputs":[{"Node":{"node_id":12931264630175648107,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[-261.24355652969916,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0,"lambda":false}}],"nodes":[[4388711862172196665,{"inputs":[],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_std::raster::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"GradientStops":[[0.3237704918032787,{"red":1.0,"green":0.0,"blue":1.0,"alpha":0.1}],[0.5655737704918032,{"red":0.8901961,"green":0.8117647,"blue":0.39215687,"alpha":1.0}],[0.8155737704918032,{"red":0.0,"green":1.0,"blue":1.0,"alpha":0.5}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::raster::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.19607843,"green":0.0,"blue":0.21176471,"alpha":1.0}],[0.12704918032786883,{"red":0.0627451,"green":0.19215687,"blue":0.39607844,"alpha":1.0}],[0.5,{"red":0.8901961,"green":0.8117647,"blue":0.39215687,"alpha":1.0}],[1.0,{"red":0.58431375,"green":0.92941177,"blue":0.92941177,"alpha":0.01}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0,"lambda":false}}],"nodes":[[4388711862172196665,{"inputs":[],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_std::raster::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"GradientStops":[[0.3237704918032787,{"red":1.0,"green":0.0,"blue":1.0,"alpha":0.1}],[0.5655737704918032,{"red":0.8901961,"green":0.8117647,"blue":0.39215687,"alpha":1.0}],[0.8155737704918032,{"red":0.0,"green":1.0,"blue":1.0,"alpha":0.5}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::raster::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.19607843,"green":0.0,"blue":0.21176471,"alpha":1.0}],[0.12704918032786883,{"red":0.0627451,"green":0.19215687,"blue":0.39607844,"alpha":1.0}],[0.5,{"red":0.8901961,"green":0.8117647,"blue":0.39215687,"alpha":1.0}],[1.0,{"red":0.58431375,"green":0.92941177,"blue":0.92941177,"alpha":0.01}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0,"lambda":false}}],"nodes":[[13353438235848911576,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[6379137305818664393,18442321214082298093,18118267825025549699,6351696498298648253,17863574903157697896,4691860614575868200,301778328144628917,10625296323957562985,533731991408535384,13357220652574593654,15992617814592812350],"remove":[],"delta":[[18118267825025549699,[642.0740740740741,0.0]],[301778328144628917,[493.5149940383244,200.29629629629628]],[15992617814592812350,[621.0370370370368,0.0]],[17863574903157697896,[606.8148151308641,95.19407372365433]],[6351696498298648253,[646.8148148148149,0.0]],[533731991408535384,[501.6296296296296,175.40740740740742]],[18442321214082298093,[565.6296296296297,122.96296296296298]],[10625296323957562985,[473.4814814814815,272.5925925925926]],[13357220652574593654,[574.2222222222222,108.44444444444449]],[4691860614575868200,[528.2962962962963,283.8518518518518]],[6379137305818664393,[625.4814814814813,0.0]]]},"segments":{"add":[13662059715350867364,3384102572540409881,12035095010819582754,10146665273368938971,318560030360358929,8462655819889292900,3303411878775644985,8661113083384527971,2035327810332855521,11346538709718766144,3710133387837274291],"remove":[],"start_point":[[12035095010819582754,18118267825025549699],[10146665273368938971,6351696498298648253],[3384102572540409881,18442321214082298093],[318560030360358929,17863574903157697896],[3710133387837274291,15992617814592812350],[11346538709718766144,13357220652574593654],[3303411878775644985,301778328144628917],[2035327810332855521,533731991408535384],[8661113083384527971,10625296323957562985],[13662059715350867364,6379137305818664393],[8462655819889292900,4691860614575868200]],"end_point":[[8661113083384527971,533731991408535384],[3384102572540409881,18118267825025549699],[3710133387837274291,6379137305818664393],[8462655819889292900,301778328144628917],[3303411878775644985,10625296323957562985],[11346538709718766144,15992617814592812350],[2035327810332855521,13357220652574593654],[13662059715350867364,18442321214082298093],[12035095010819582754,6351696498298648253],[10146665273368938971,17863574903157697896],[318560030360358929,4691860614575868200]],"handle_primary":[[3303411878775644985,[0.0,0.0]],[10146665273368938971,[0.0,0.0]],[8462655819889292900,[0.0,0.0]],[13662059715350867364,[0.0,0.0]],[12035095010819582754,[0.0,0.0]],[3710133387837274291,[0.0,0.0]],[8661113083384527971,[0.2962962962963047,0.2962962962963047]],[11346538709718766144,[9.925839724176626,-9.951533978271286]],[3384102572540409881,[0.0,0.0]],[2035327810332855521,[42.96296296296293,-41.7777777777778]],[318560030360358929,[-46.95465552079859,46.40007297527743]]],"handle_end":[[10146665273368938971,[48.16592595101224,-47.597037061827145]],[3384102572540409881,[0.5807410754567854,77.36888852918523]],[8661113083384527971,[-42.34888386913234,41.180638796880466]],[2035327810332855521,[-8.299214014278164,8.32069754812484]],[12035095010819582754,[0.0,0.0]],[318560030360358929,[-97.48148148148152,-81.18518518518522]],[11346538709718766144,[1.1377781018271662,63.71555518874077]],[3303411878775644985,[-6.2222222222222285,-40.59259259259261]],[3710133387837274291,[0.0,0.0]],[8462655819889292900,[-21.74426522093495,47.99999999999997]],[13662059715350867364,[68.68148181185177,-54.8859262904691]]],"stroke":[[3384102572540409881,0],[8661113083384527971,0],[10146665273368938971,0],[11346538709718766144,0],[3710133387837274291,0],[12035095010819582754,0],[3303411878775644985,0],[8462655819889292900,0],[318560030360358929,0],[13662059715350867364,0],[2035327810332855521,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[[{"ty":"End","segment":10146665273368938971},{"ty":"Primary","segment":318560030360358929}],[{"ty":"Primary","segment":11346538709718766144},{"ty":"End","segment":2035327810332855521}],[{"ty":"End","segment":8661113083384527971},{"ty":"Primary","segment":2035327810332855521}],[{"ty":"End","segment":12035095010819582754},{"ty":"Primary","segment":10146665273368938971}]],"remove_g1_continuous":[]}},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"outputLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0,"lambda":false}}],"nodes":[[13353438235848911576,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[6379137305818664393,18442321214082298093,18118267825025549699,6351696498298648253,17863574903157697896,4691860614575868200,301778328144628917,10625296323957562985,533731991408535384,13357220652574593654,15992617814592812350],"remove":[],"delta":[[6351696498298648253,[646.8148148148149,0.0]],[17863574903157697896,[606.8148151308641,95.19407372365433]],[18118267825025549699,[642.0740740740741,0.0]],[15992617814592812350,[621.0370370370368,0.0]],[13357220652574593654,[574.2222222222222,108.44444444444449]],[6379137305818664393,[625.4814814814813,0.0]],[10625296323957562985,[473.4814814814815,272.5925925925926]],[301778328144628917,[493.5149940383244,200.29629629629628]],[533731991408535384,[501.6296296296296,175.40740740740742]],[18442321214082298093,[565.6296296296297,122.96296296296298]],[4691860614575868200,[528.2962962962963,283.8518518518518]]]},"segments":{"add":[13662059715350867364,3384102572540409881,12035095010819582754,10146665273368938971,318560030360358929,8462655819889292900,3303411878775644985,8661113083384527971,2035327810332855521,11346538709718766144,3710133387837274291],"remove":[],"start_point":[[2035327810332855521,533731991408535384],[3710133387837274291,15992617814592812350],[11346538709718766144,13357220652574593654],[12035095010819582754,18118267825025549699],[13662059715350867364,6379137305818664393],[8462655819889292900,4691860614575868200],[8661113083384527971,10625296323957562985],[3384102572540409881,18442321214082298093],[10146665273368938971,6351696498298648253],[3303411878775644985,301778328144628917],[318560030360358929,17863574903157697896]],"end_point":[[3303411878775644985,10625296323957562985],[8462655819889292900,301778328144628917],[13662059715350867364,18442321214082298093],[8661113083384527971,533731991408535384],[11346538709718766144,15992617814592812350],[318560030360358929,4691860614575868200],[2035327810332855521,13357220652574593654],[3710133387837274291,6379137305818664393],[12035095010819582754,6351696498298648253],[10146665273368938971,17863574903157697896],[3384102572540409881,18118267825025549699]],"handle_primary":[[3384102572540409881,[0.0,0.0]],[13662059715350867364,[0.0,0.0]],[8661113083384527971,[0.2962962962963047,0.2962962962963047]],[318560030360358929,[-46.95465552079859,46.40007297527743]],[10146665273368938971,[0.0,0.0]],[11346538709718766144,[9.925839724176626,-9.951533978271286]],[12035095010819582754,[0.0,0.0]],[3303411878775644985,[0.0,0.0]],[3710133387837274291,[0.0,0.0]],[8462655819889292900,[0.0,0.0]],[2035327810332855521,[42.96296296296293,-41.7777777777778]]],"handle_end":[[11346538709718766144,[1.1377781018271662,63.71555518874077]],[3303411878775644985,[-6.2222222222222285,-40.59259259259261]],[8661113083384527971,[-42.34888386913234,41.180638796880466]],[3384102572540409881,[0.5807410754567854,77.36888852918523]],[318560030360358929,[-97.48148148148152,-81.18518518518522]],[2035327810332855521,[-8.299214014278164,8.32069754812484]],[3710133387837274291,[0.0,0.0]],[13662059715350867364,[68.68148181185177,-54.8859262904691]],[10146665273368938971,[48.16592595101224,-47.597037061827145]],[12035095010819582754,[0.0,0.0]],[8462655819889292900,[-21.74426522093495,47.99999999999997]]],"stroke":[[3384102572540409881,0],[13662059715350867364,0],[318560030360358929,0],[3710133387837274291,0],[2035327810332855521,0],[3303411878775644985,0],[11346538709718766144,0],[8462655819889292900,0],[8661113083384527971,0],[12035095010819582754,0],[10146665273368938971,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[[{"ty":"End","segment":10146665273368938971},{"ty":"Primary","segment":318560030360358929}],[{"ty":"End","segment":8661113083384527971},{"ty":"Primary","segment":2035327810332855521}],[{"ty":"Primary","segment":11346538709718766144},{"ty":"End","segment":2035327810332855521}],[{"ty":"End","segment":12035095010819582754},{"ty":"Primary","segment":10146665273368938971}]],"remove_g1_continuous":[]}},"exposed":false}}],"manual_composition":null,"implementatioLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0,"lambda":false}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0,"lambda":false}}],"nodes":[[11731553664207576737,{"inputs":[{"Node":{"node_id":5663116427189655422,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0,"lambda":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0,"lambda":false}},{"Node":{"node_id":14577956936089455769,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.4855225354961647,0.31002285853371414]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0,"lambda":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[10202767637947785546,{"inputs":[{"Node":{"node_id":11731553664207576737,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":172.90000000000003},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":2,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::SubpathSegmentLengthsNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::ImpureMemoNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"bool","alias":null}},"import_index":4}},{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"mLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0,"lambda":false}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0,"lambda":false}}],"nodes":[[11731553664207576737,{"inputs":[{"Node":{"node_id":5663116427189655422,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0,"lambda":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0,"lambda":false}},{"Node":{"node_id":14577956936089455769,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.4855225354961647,0.31002285853371414]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0,"lambda":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[10202767637947785546,{"inputs":[{"Node":{"node_id":11731553664207576737,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":172.90000000000003},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":2,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::SubpathSegmentLengthsNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::ImpureMemoNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"bool","alias":null}},"import_index":4}},{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"mLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0,"lambda":false}}],"nodes":[[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0,"lambda":false}},{"Node":{"node_id":2181148486404191200,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[13,[153.77777777777777,-1.3333333333333712]],[28,[39.111111111111086,-58.22222222222226]],[15,[111.11111111111114,-60.888888888888914]],[26,[22.66666666666663,-81.33333333333337]],[16,[159.5555555555555,-75.55555555555557]],[11,[136.88888888888886,39.111111111111086]],[14,[183.11111111111103,-19.111111111111143]],[3,[45.77777777777777,145.33333333333331]],[33,[-78.22222222222223,75.55555555555554]],[1,[-103.55555555555554,126.66666666666664]],[5,[66.22222222222223,152.88888888888886]],[9,[156.4444444444444,97.33333333333331]],[34,[-5.333333333333371,99.11111111111109]],[20,[128.4444444444444,-142.22222222222223]],[22,[71.11111111111109,-201.7777777777778]],[18,[145.77777777777777,-97.7777777777778]],[17,[123.99999999999994,-84.00000000000003]],[21,[76.0,-202.22222222222223]],[24,[57.77777777777777,-129.33333333333334]],[2,[-67.55555555555554,158.22222222222217]],[25,[0.8888888888888573,-94.66666666666669]],[31,[-53.33333333333337,13.777777777777771]],[30,[-9.333333333333371,0.0]],[6,[123.99999999999994,148.4444444444444]],[32,[9.333333333333314,38.66666666666663]],[19,[90.66666666666664,-129.33333333333334]],[12,[199.5555555555555,10.666666666666629]],[23,[19.555555555555543,-139.55555555555557]],[10,[216.4444444444444,72.4444444444444]],[4,[18.66666666666663,157.77777777777771]],[7,[229.33333333333331,152.4444444444444]],[27,[-11.111111111111144,-72.00000000000003]],[29,[-32.888888888888914,-14.666666666666686]],[8,[252.4444444444444,124.88888888888886]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[25,25],[2,2],[11,11],[26,26],[13,13],[19,19],[32,32],[17,17],[5,5],[7,7],[22,22],[18,18],[29,29],[27,27],[33,33],[28,28],[9,9],[16,16],[14,14],[10,10],[12,12],[8,8],[30,30],[4,4],[21,21],[3,3],[31,31],[1,1],[20,20],[24,24],[15,15],[6,6],[23,23],[34,34]],"end_point":[[6,7],[17,18],[11,12],[3,4],[21,22],[33,34],[29,30],[27,28],[32,33],[25,26],[30,31],[22,23],[31,32],[7,8],[2,3],[20,21],[14,15],[1,2],[13,14],[15,16],[26,27],[8,9],[4,5],[16,17],[10,11],[34,1],[12,13],[18,19],[24,25],[9,10],[19,20],[28,29],[23,24],[5,6]],"handle_primary":[[20,[0.0,0.0]],[6,[0.0,0.0]],[22,[0.0,0.0]],[1,[0.0,0.0]],[5,[0.0,0.0]],[11,[0.0,0.0]],[32,[0.0,0.0]],[14,[0.0,0.0]],[33,[0.0,0.0]],[24,[0.0,0.0]],[7,[24.88888888888891,-15.111111111111086]],[27,[0.0,0.0]],[12,[0.0,0.0]],[15,[0.0,0.0]],[21,[0.0,0.0]],[4,[0.0,0.0]],[28,[0.0,0.0]],[18,[0.0,0.0]],[3,[0.0,0.0]],[9,[0.0,0.0]],[26,[0.0,0.0]],[30,[0.0,0.0]],[19,[0.0,0.0]],[31,[0.0,0.0]],[29,[Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0,"lambda":false}}],"nodes":[[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0,"lambda":false}},{"Node":{"node_id":2181148486404191200,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[4,[18.66666666666663,157.77777777777771]],[2,[-67.55555555555554,158.22222222222217]],[19,[90.66666666666664,-129.33333333333334]],[1,[-103.55555555555554,126.66666666666664]],[10,[216.4444444444444,72.4444444444444]],[7,[229.33333333333331,152.4444444444444]],[27,[-11.111111111111144,-72.00000000000003]],[30,[-9.333333333333371,0.0]],[3,[45.77777777777777,145.33333333333331]],[18,[145.77777777777777,-97.7777777777778]],[8,[252.4444444444444,124.88888888888886]],[34,[-5.333333333333371,99.11111111111109]],[9,[156.4444444444444,97.33333333333331]],[29,[-32.888888888888914,-14.666666666666686]],[25,[0.8888888888888573,-94.66666666666669]],[23,[19.555555555555543,-139.55555555555557]],[16,[159.5555555555555,-75.55555555555557]],[6,[123.99999999999994,148.4444444444444]],[26,[22.66666666666663,-81.33333333333337]],[17,[123.99999999999994,-84.00000000000003]],[31,[-53.33333333333337,13.777777777777771]],[24,[57.77777777777777,-129.33333333333334]],[28,[39.111111111111086,-58.22222222222226]],[21,[76.0,-202.22222222222223]],[22,[71.11111111111109,-201.7777777777778]],[5,[66.22222222222223,152.88888888888886]],[11,[136.88888888888886,39.111111111111086]],[32,[9.333333333333314,38.66666666666663]],[20,[128.4444444444444,-142.22222222222223]],[14,[183.11111111111103,-19.111111111111143]],[33,[-78.22222222222223,75.55555555555554]],[15,[111.11111111111114,-60.888888888888914]],[13,[153.77777777777777,-1.3333333333333712]],[12,[199.5555555555555,10.666666666666629]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[26,26],[33,33],[27,27],[5,5],[28,28],[13,13],[15,15],[1,1],[20,20],[34,34],[19,19],[7,7],[3,3],[21,21],[17,17],[31,31],[14,14],[16,16],[18,18],[25,25],[12,12],[6,6],[9,9],[29,29],[32,32],[10,10],[30,30],[2,2],[22,22],[24,24],[4,4],[23,23],[11,11],[8,8]],"end_point":[[6,7],[10,11],[26,27],[7,8],[5,6],[14,15],[31,32],[2,3],[32,33],[27,28],[24,25],[1,2],[8,9],[16,17],[11,12],[25,26],[18,19],[34,1],[4,5],[23,24],[28,29],[3,4],[29,30],[13,14],[9,10],[22,23],[30,31],[19,20],[12,13],[33,34],[17,18],[15,16],[21,22],[20,21]],"handle_primary":[[5,[0.0,0.0]],[22,[0.0,0.0]],[4,[0.0,0.0]],[19,[0.0,0.0]],[32,[0.0,0.0]],[24,[0.0,0.0]],[17,[0.0,0.0]],[3,[0.0,0.0]],[12,[0.0,0.0]],[11,[0.0,0.0]],[7,[24.88888888888891,-15.111111111111086]],[21,[0.0,0.0]],[8,[0.0,0.0]],[18,[0.0,0.0]],[29,[0.0,0.0]],[28,[0.0,0.0]],[23,[0.0,0.0]],[31,[0.0,0.0]],[15,[0.0,0.0]],[9,[0.0,0.0]],[33,[0.0,0Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0,"lambda":false}}],"nodes":[[10127467043900015225,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[258.00000000000006,994.6666666666664]],[2,[644.0,726.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-328.66666666666674,129.33333333333337]]],"stroke":[[1,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"graphene_core::vector::vector_data::modification::VectorModification","alias":null}},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::vector_data::modification::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[15961046538654083626,{"inputs":[{"Node":{"node_id":1889157037801767612,"output_index":0,"lambda":false}},{"Node":{"node_id":4332145463108161926,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":10.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::CopyToPointsNode"}},"visible":true,"skip_deduplication":false}],[17378885078543074499,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8],"remove":[],"delta":[[6,[725.7777777777779,1026.370370370371]],[5,[740.4444444444443,857.1111111111111]],[4,[709.5555555555554,1026.6666666666667]],[2,[745.5,826.0]],[7,[727.5555555555554,1026.6666666666663]],[1,[823.2222222222221,660.4444444444445]],[8,[746.0000000000001,842.9999999999999]],[3,[707.5,1026.5]]]},"segments":{"add":[1,2,3,4,5,6,7,8],"remove":[],"start_point":[[5,5],[3,3],[8,8],[1,1],[4,4],[7,7],[2,2],[6,6]],"end_point":[[4,5],[5,6],[1,2],[7,8],[8,1],[6,7],[3,4],[2,3]],"handle_primary":[[2,[-24.5,85.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[17.33333333333337,-84.99999999999989]],[3,[0.0,0.0]],[1,[0.0,0.0]],[5,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[24.5,-85.0]],[3,[0.0,0.0]],[8,[1.772016460905547,0.9591220850479658]],[6,[0.0,0.0]],[2,[0.0,0.0]],[7,[-26.8034437596026,131.4399645903585]],[5,[-7.555555555555884,-59.25925925925992]],[4,[-23.11111111111109,90.44444444444456]]],"stroke":[[5,0],[1,0],[7,0],[2,0],[8,0],[4,0],[3,0],[6,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":8}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"manual_compositioLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0,"lambda":false}}],"nodes":[[10127467043900015225,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[2,[644.0,726.6666666666666]],[1,[258.00000000000006,994.6666666666664]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-328.66666666666674,129.33333333333337]]],"stroke":[[1,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"graphene_core::vector::vector_data::modification::VectorModification","alias":null}},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::vector_data::modification::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[15961046538654083626,{"inputs":[{"Node":{"node_id":1889157037801767612,"output_index":0,"lambda":false}},{"Node":{"node_id":4332145463108161926,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":10.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::CopyToPointsNode"}},"visible":true,"skip_deduplication":false}],[17378885078543074499,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8],"remove":[],"delta":[[5,[740.4444444444443,857.1111111111111]],[4,[709.5555555555554,1026.6666666666667]],[1,[823.2222222222221,660.4444444444445]],[6,[725.7777777777779,1026.370370370371]],[8,[746.0000000000001,842.9999999999999]],[7,[727.5555555555554,1026.6666666666663]],[3,[707.5,1026.5]],[2,[745.5,826.0]]]},"segments":{"add":[1,2,3,4,5,6,7,8],"remove":[],"start_point":[[8,8],[5,5],[4,4],[2,2],[3,3],[6,6],[1,1],[7,7]],"end_point":[[6,7],[8,1],[2,3],[1,2],[3,4],[7,8],[5,6],[4,5]],"handle_primary":[[2,[-24.5,85.0]],[7,[0.0,0.0]],[3,[0.0,0.0]],[1,[0.0,0.0]],[6,[0.0,0.0]],[5,[0.0,0.0]],[8,[17.33333333333337,-84.99999999999989]],[4,[0.0,0.0]]],"handle_end":[[3,[0.0,0.0]],[2,[0.0,0.0]],[8,[1.772016460905547,0.9591220850479658]],[7,[-26.8034437596026,131.4399645903585]],[6,[0.0,0.0]],[4,[-23.11111111111109,90.44444444444456]],[1,[24.5,-85.0]],[5,[-7.555555555555884,-59.25925925925992]]],"stroke":[[6,0],[7,0],[8,0],[3,0],[5,0],[4,0],[2,0],[1,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":8Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0,"lambda":false}}],"nodes":[[202,{"inputs":[{"Node":{"node_id":206,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[404,{"inputs":[{"Node":{"node_id":402,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.24313726,"green":0.18431373,"blue":0.19215687,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"VecF64":[]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"LineCap":"Butt"},"exposed":false}},{"Value":{"tagged_value":{"LineJoin":"Miter"},"exposed":false}},{"Value":{"tagged_value":{"F64":4.0},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::StrokeNode"}},"visible":true,"skip_deduplication":false}],[93,{"inputs":[{"Node":{"node_id":94,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[851.1666666666667,668.5377104806669]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[39.677869315599935,39.67786931560005]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[155,{"inputs":[{"Node":{"node_id":159,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":[[0.0,{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0}],[1.0,{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]],"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555],"transform":[603.3437683597715,0.0,0.0,426.45833333333366,450.87499999999994,340.8749999999998]}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0}],[1.0,{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]],"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555],"transform":[603.3437683597715,0.0,0.0,426.45833333333366,450.87499999999994,340.8749999999998]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[497,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"coloLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0,"lambda":false}}],"nodes":[[202,{"inputs":[{"Node":{"node_id":206,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[404,{"inputs":[{"Node":{"node_id":402,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.24313726,"green":0.18431373,"blue":0.19215687,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"StrokeAlign":"Center"},"exposed":false}},{"Value":{"tagged_value":{"StrokeCap":"Butt"},"exposed":false}},{"Value":{"tagged_value":{"StrokeJoin":"Miter"},"exposed":false}},{"Value":{"tagged_value":{"F64":4.0},"exposed":false}},{"Value":{"tagged_value":{"PaintOrder":"StrokeAbove"},"exposed":false}},{"Value":{"tagged_value":{"VecF64":[]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::StrokeNode"}},"visible":true,"skip_deduplication":false}],[93,{"inputs":[{"Node":{"node_id":94,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"DVec2":[851.1666666666667,668.5377104806669]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[39.677869315599935,39.67786931560005]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.5,0.5]},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}},{"Network":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":5}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[155,{"inputs":[{"Node":{"node_id":159,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":[[0.0,{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0}],[1.0,{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]],"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555],"transform":[603.3437683597715,0.0,0.0,426.45833333333366,450.87499999999994,340.8749999999998]}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0}],[1.0,{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]],"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555],"transform":[603.3437683597715,0.0,0.0,426.45833333333366,450.87499999999994,340.8749999999998]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNLine truncated
|
||||
+10
-24
@@ -15,59 +15,45 @@ default = ["wasm"]
|
||||
wasm = ["wasm-bindgen", "graphene-std/wasm", "wasm-bindgen-futures"]
|
||||
gpu = [
|
||||
"interpreted-executor/gpu",
|
||||
"graphene-std/gpu",
|
||||
"graphene-core/gpu",
|
||||
"wgpu-executor",
|
||||
"gpu-executor",
|
||||
]
|
||||
tauri = ["ron", "decouple-execution"]
|
||||
decouple-execution = []
|
||||
resvg = ["graphene-std/resvg"]
|
||||
vello = ["graphene-std/vello", "resvg", "graphene-core/vello"]
|
||||
vello = ["graphene-std/vello", "resvg"]
|
||||
ron = ["dep:ron"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { path = "../proc-macros" }
|
||||
graph-craft = { path = "../node-graph/graph-craft" }
|
||||
interpreted-executor = { path = "../node-graph/interpreted-executor", features = ["serde"] }
|
||||
graphene-core = { path = "../node-graph/gcore" }
|
||||
graphene-std = { path = "../node-graph/gstd", features = ["serde"] }
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
js-sys = { workspace = true }
|
||||
log = { workspace = true }
|
||||
bitflags = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
bezier-rs = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
glam = { workspace = true, features = ["serde", "debug-glam-assert"] }
|
||||
glam = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
derivative = { workspace = true }
|
||||
specta = { workspace = true }
|
||||
image = { workspace = true, features = ["bmp", "png"] }
|
||||
dyn-any = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
web-sys = { workspace = true, features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
"HtmlCanvasElement",
|
||||
"CanvasRenderingContext2d",
|
||||
"TextMetrics",
|
||||
] }
|
||||
web-sys = { workspace = true }
|
||||
|
||||
# Required dependencies
|
||||
async-mutex = "1.4.0"
|
||||
spin = "0.9.8"
|
||||
|
||||
# Optional local dependencies
|
||||
wgpu-executor = { path = "../node-graph/wgpu-executor", optional = true }
|
||||
gpu-executor = { path = "../node-graph/gpu-executor", optional = true }
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -78,7 +64,7 @@ ron = { workspace = true, optional = true }
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
||||
tokio = { workspace = true }
|
||||
|
||||
[lints.rust]
|
||||
# TODO: figure out why we check these features when they do not exist
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
pub use graphene_core::uuid::*;
|
||||
pub use graphene_std::uuid::*;
|
||||
|
||||
// TODO: serialize with serde to save the current editor state
|
||||
pub struct Editor {
|
||||
|
||||
+15
-1
@@ -89,6 +89,8 @@ pub const MIN_LENGTH_FOR_RESIZE_TO_INCLUDE_INTERIOR: f64 = 40.;
|
||||
///
|
||||
/// The motion of the user's cursor by an `x` pixel offset results in `x * scale_factor` pixels of offset on the other side.
|
||||
pub const MAXIMUM_ALT_SCALE_FACTOR: f64 = 25.;
|
||||
/// The width or height that the transform cage needs before it is considered to have no width or height.
|
||||
pub const MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT: f64 = 1e-4;
|
||||
|
||||
// SKEW TRIANGLES
|
||||
pub const SKEW_TRIANGLE_SIZE: f64 = 7.;
|
||||
@@ -99,8 +101,10 @@ pub const MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY: f64 = 48.;
|
||||
pub const MANIPULATOR_GROUP_MARKER_SIZE: f64 = 6.;
|
||||
pub const SELECTION_THRESHOLD: f64 = 10.;
|
||||
pub const HIDE_HANDLE_DISTANCE: f64 = 3.;
|
||||
pub const INSERT_POINT_ON_SEGMENT_TOO_FAR_DISTANCE: f64 = 50.;
|
||||
pub const HANDLE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
pub const SEGMENT_INSERTION_DISTANCE: f64 = 8.;
|
||||
pub const SEGMENT_OVERLAY_SIZE: f64 = 10.;
|
||||
pub const HANDLE_LENGTH_FACTOR: f64 = 0.5;
|
||||
|
||||
// PEN TOOL
|
||||
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
|
||||
@@ -115,6 +119,13 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
|
||||
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
|
||||
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
|
||||
|
||||
// GIZMOS
|
||||
pub const POINT_RADIUS_HANDLE_SNAP_THRESHOLD: f64 = 8.;
|
||||
pub const POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD: f64 = 7.9;
|
||||
pub const NUMBER_OF_POINTS_HANDLE_SPOKE_EXTENSION: f64 = 1.2;
|
||||
pub const NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH: f64 = 10.;
|
||||
pub const GIZMO_HIDE_THRESHOLD: f64 = 20.;
|
||||
|
||||
// SCROLLBARS
|
||||
pub const SCROLLBAR_SPACING: f64 = 0.1;
|
||||
pub const ASYMPTOTIC_EFFECT: f64 = 0.5;
|
||||
@@ -134,3 +145,6 @@ pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
|
||||
pub const FILE_SAVE_SUFFIX: &str = ".graphite";
|
||||
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
|
||||
pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 15;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
@@ -498,9 +498,14 @@ mod test {
|
||||
println!("-------------------------------------------------");
|
||||
println!("Failed test due to receiving a DisplayDialogError while loading a Graphite demo file.");
|
||||
println!();
|
||||
println!("NOTE:");
|
||||
println!("Document upgrading isn't performed in tests like when opening in the actual editor.");
|
||||
println!("You may need to open and re-save a document in the editor to apply its migrations.");
|
||||
println!();
|
||||
println!("DisplayDialogError details:");
|
||||
println!();
|
||||
println!("Description: {value}");
|
||||
println!("Description:");
|
||||
println!("{value}");
|
||||
println!("-------------------------------------------------");
|
||||
println!();
|
||||
|
||||
@@ -538,7 +543,9 @@ mod test {
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
editor.eval_graph().await;
|
||||
if let Err(e) = editor.eval_graph().await {
|
||||
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
|
||||
}
|
||||
|
||||
for response in responses {
|
||||
// Check for the existence of the file format incompatibility warning dialog after opening the test file
|
||||
|
||||
@@ -6,4 +6,4 @@ pub use animation_message::{AnimationMessage, AnimationMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use animation_message_handler::AnimationMessageHandler;
|
||||
|
||||
pub use graphene_core::application_io::TimingInformation;
|
||||
pub use graphene_std::application_io::TimingInformation;
|
||||
@@ -143,12 +143,14 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_holder(),
|
||||
];
|
||||
|
||||
let mut checkbox_id = CheckboxId::default();
|
||||
let transparent_background = vec![
|
||||
TextLabel::new("Transparency").table_align(true).min_width(100).widget_holder(),
|
||||
TextLabel::new("Transparency").table_align(true).min_width(100).for_checkbox(&mut checkbox_id).widget_holder(),
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
CheckboxInput::new(self.transparent_background)
|
||||
.disabled(self.file_type == FileType::Jpg)
|
||||
.on_update(move |value: &CheckboxInput| ExportDialogMessage::TransparentBackground(value.checked).into())
|
||||
.for_label(checkbox_id.clone())
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
|
||||
+4
-2
@@ -26,7 +26,7 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
responses.add(Message::StartBuffer);
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
artboard: graphene_core::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
|
||||
artboard: graphene_std::Artboard::new(IVec2::ZERO, self.dimensions.as_ivec2()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -77,11 +77,13 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
let mut checkbox_id = CheckboxId::default();
|
||||
let infinite = vec![
|
||||
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).widget_holder(),
|
||||
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).for_checkbox(&mut checkbox_id).widget_holder(),
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
CheckboxInput::new(self.infinite)
|
||||
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite(checkbox_input.checked).into())
|
||||
.for_label(checkbox_id.clone())
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
|
||||
+19
-3
@@ -66,6 +66,7 @@ impl PreferencesDialogMessageHandler {
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
let mut checkbox_id = CheckboxId::default();
|
||||
let zoom_with_scroll_tooltip = "Use the scroll wheel for zooming instead of vertically panning (not recommended for trackpads)";
|
||||
let zoom_with_scroll = vec![
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
@@ -78,8 +79,13 @@ impl PreferencesDialogMessageHandler {
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.for_label(checkbox_id.clone())
|
||||
.widget_holder(),
|
||||
TextLabel::new("Zoom with Scroll")
|
||||
.table_align(true)
|
||||
.tooltip(zoom_with_scroll_tooltip)
|
||||
.for_checkbox(&mut checkbox_id)
|
||||
.widget_holder(),
|
||||
TextLabel::new("Zoom with Scroll").table_align(true).tooltip(zoom_with_scroll_tooltip).widget_holder(),
|
||||
];
|
||||
|
||||
// =======
|
||||
@@ -161,6 +167,7 @@ impl PreferencesDialogMessageHandler {
|
||||
graph_wire_style,
|
||||
];
|
||||
|
||||
let mut checkbox_id = CheckboxId::default();
|
||||
let vello_tooltip = "Use the experimental Vello renderer (your browser must support WebGPU)";
|
||||
let use_vello = vec![
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
@@ -169,23 +176,32 @@ impl PreferencesDialogMessageHandler {
|
||||
.tooltip(vello_tooltip)
|
||||
.disabled(!preferences.supports_wgpu())
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::UseVello { use_vello: checkbox_input.checked }.into())
|
||||
.for_label(checkbox_id.clone())
|
||||
.widget_holder(),
|
||||
TextLabel::new("Vello Renderer")
|
||||
.table_align(true)
|
||||
.tooltip(vello_tooltip)
|
||||
.disabled(!preferences.supports_wgpu())
|
||||
.for_checkbox(&mut checkbox_id)
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
let vector_mesh_tooltip = "Allow tools to produce vector meshes, where more than two segments can connect to an anchor point.\n\nCurrently this does not properly handle line joins and fills.";
|
||||
let mut checkbox_id = CheckboxId::default();
|
||||
let vector_mesh_tooltip =
|
||||
"Allow tools to produce vector meshes, where more than two segments can connect to an anchor point.\n\nCurrently this does not properly handle stroke joins and fills.";
|
||||
let vector_meshes = vec![
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
CheckboxInput::new(preferences.vector_meshes)
|
||||
.tooltip(vector_mesh_tooltip)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::VectorMeshes { enabled: checkbox_input.checked }.into())
|
||||
.for_label(checkbox_id.clone())
|
||||
.widget_holder(),
|
||||
TextLabel::new("Vector Meshes")
|
||||
.table_align(true)
|
||||
.tooltip(vector_mesh_tooltip)
|
||||
.for_checkbox(&mut checkbox_id)
|
||||
.widget_holder(),
|
||||
TextLabel::new("Vector Meshes").table_align(true).tooltip(vector_mesh_tooltip).widget_holder(),
|
||||
];
|
||||
|
||||
// TODO: Reenable when Imaginate is restored
|
||||
|
||||
@@ -20,8 +20,9 @@ impl DialogLayoutHolder for AboutGraphiteDialog {
|
||||
|
||||
fn layout_column_2(&self) -> Layout {
|
||||
let links = [
|
||||
("Website", "Website", "https://graphite.rs"),
|
||||
("Heart", "Donate", "https://graphite.rs/donate/"),
|
||||
("Volunteer", "Volunteer", "https://graphite.rs/volunteer/"),
|
||||
("GraphiteLogo", "Website", "https://graphite.rs"),
|
||||
("Credits", "Credits", "https://github.com/GraphiteEditor/Graphite/graphs/contributors"),
|
||||
];
|
||||
let mut widgets = links
|
||||
|
||||
@@ -7,8 +7,8 @@ use crate::messages::portfolio::document::utility_types::nodes::{JsRawBuffer, La
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::utility_types::HintData;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_core::text::Font;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::text::Font;
|
||||
|
||||
#[impl_message(Message, Frontend)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
@@ -240,7 +240,17 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "hintData")]
|
||||
hint_data: HintData,
|
||||
},
|
||||
UpdateLayersPanelControlBarLayout {
|
||||
UpdateLayersPanelControlBarLeftLayout {
|
||||
#[serde(rename = "layoutTarget")]
|
||||
layout_target: LayoutTarget,
|
||||
diff: Vec<WidgetDiff>,
|
||||
},
|
||||
UpdateLayersPanelControlBarRightLayout {
|
||||
#[serde(rename = "layoutTarget")]
|
||||
layout_target: LayoutTarget,
|
||||
diff: Vec<WidgetDiff>,
|
||||
},
|
||||
UpdateLayersPanelBottomBarLayout {
|
||||
#[serde(rename = "layoutTarget")]
|
||||
layout_target: LayoutTarget,
|
||||
diff: Vec<WidgetDiff>,
|
||||
|
||||
@@ -171,12 +171,40 @@ pub fn input_mappings() -> Mapping {
|
||||
entry!(KeyDown(MouseRight); action_dispatch=GradientToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=GradientToolMessage::Abort),
|
||||
//
|
||||
// RectangleToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=RectangleToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=RectangleToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=RectangleToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=RectangleToolMessage::Abort),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift], action_dispatch=RectangleToolMessage::PointerMove { center: Alt, lock_ratio: Shift }),
|
||||
// ShapeToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=ShapeToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=ShapeToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=ShapeToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=ShapeToolMessage::Abort),
|
||||
entry!(KeyDown(BracketLeft); action_dispatch=ShapeToolMessage::DecreaseSides),
|
||||
entry!(KeyDown(BracketRight); action_dispatch=ShapeToolMessage::IncreaseSides),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift, Control], action_dispatch=ShapeToolMessage::PointerMove([Alt, Shift, Control, Shift])),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift, ArrowLeft], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift, ArrowRight], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[Shift], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: 0., delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); modifiers=[Shift, ArrowLeft], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); modifiers=[Shift, ArrowRight], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); modifiers=[Shift], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: 0., delta_y: BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); modifiers=[Shift, ArrowUp], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); modifiers=[Shift, ArrowDown], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); modifiers=[Shift], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -BIG_NUDGE_AMOUNT, delta_y: 0., resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); modifiers=[Shift, ArrowUp], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: -BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); modifiers=[Shift, ArrowDown], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: BIG_NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); modifiers=[Shift], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: BIG_NUDGE_AMOUNT, delta_y: 0., resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[ArrowLeft], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -NUDGE_AMOUNT, delta_y: -NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); modifiers=[ArrowRight], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: NUDGE_AMOUNT, delta_y: -NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: 0., delta_y: -NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); modifiers=[ArrowLeft], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -NUDGE_AMOUNT, delta_y: NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); modifiers=[ArrowRight], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: NUDGE_AMOUNT, delta_y: NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: 0., delta_y: NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); modifiers=[ArrowUp], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -NUDGE_AMOUNT, delta_y: -NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); modifiers=[ArrowDown], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -NUDGE_AMOUNT, delta_y: NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowLeft); action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: -NUDGE_AMOUNT, delta_y: 0., resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); modifiers=[ArrowUp], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: NUDGE_AMOUNT, delta_y: -NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); modifiers=[ArrowDown], action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: NUDGE_AMOUNT, delta_y: NUDGE_AMOUNT, resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=ShapeToolMessage::NudgeSelectedLayers { delta_x: NUDGE_AMOUNT, delta_y: 0., resize: Alt, resize_opposite_corner: Control }),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=ShapeToolMessage::IncreaseSides),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=ShapeToolMessage::DecreaseSides),
|
||||
//
|
||||
// ImaginateToolMessage
|
||||
// entry!(KeyDown(MouseLeft); action_dispatch=ImaginateToolMessage::DragStart),
|
||||
@@ -185,40 +213,19 @@ pub fn input_mappings() -> Mapping {
|
||||
// entry!(KeyDown(Escape); action_dispatch=ImaginateToolMessage::Abort),
|
||||
// entry!(PointerMove; refresh_keys=[Alt, Shift], action_dispatch=ImaginateToolMessage::Resize { center: Alt, lock_ratio: Shift }),
|
||||
//
|
||||
// EllipseToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=EllipseToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=EllipseToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=EllipseToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=EllipseToolMessage::Abort),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift], action_dispatch=EllipseToolMessage::PointerMove { center: Alt, lock_ratio: Shift }),
|
||||
//
|
||||
// PolygonToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=PolygonToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=PolygonToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=PolygonToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=PolygonToolMessage::Abort),
|
||||
entry!(PointerMove; refresh_keys=[Alt, Shift], action_dispatch=PolygonToolMessage::PointerMove { center: Alt, lock_ratio: Shift }),
|
||||
//
|
||||
// LineToolMessage
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=LineToolMessage::DragStart),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=LineToolMessage::DragStop),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=LineToolMessage::Abort),
|
||||
entry!(KeyDown(Escape); action_dispatch=LineToolMessage::Abort),
|
||||
entry!(PointerMove; refresh_keys=[Control, Alt, Shift], action_dispatch=LineToolMessage::PointerMove { center: Alt, lock_angle: Control, snap_angle: Shift }),
|
||||
//
|
||||
// PathToolMessage
|
||||
entry!(KeyDown(Delete); modifiers=[Accel], action_dispatch=PathToolMessage::DeleteAndBreakPath),
|
||||
entry!(KeyDown(Backspace); modifiers=[Accel], action_dispatch=PathToolMessage::DeleteAndBreakPath),
|
||||
entry!(KeyDown(Delete); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
|
||||
entry!(KeyDown(Backspace); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
|
||||
entry!(KeyDownNoRepeat(Tab); action_dispatch=PathToolMessage::SwapSelectedHandles),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=PathToolMessage::MouseDown { direct_insert_without_sliding: Control, extend_selection: Shift, lasso_select: Control, handle_drag_from_anchor: Alt }),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=PathToolMessage::MouseDown { extend_selection: Shift, lasso_select: Control, handle_drag_from_anchor: Alt, drag_restore_handle: Control }),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=PathToolMessage::RightClick),
|
||||
entry!(KeyDown(Escape); action_dispatch=PathToolMessage::Escape),
|
||||
entry!(KeyDown(KeyG); action_dispatch=PathToolMessage::GRS { key: KeyG }),
|
||||
entry!(KeyDown(KeyR); action_dispatch=PathToolMessage::GRS { key: KeyR }),
|
||||
entry!(KeyDown(KeyS); action_dispatch=PathToolMessage::GRS { key: KeyS }),
|
||||
entry!(PointerMove; refresh_keys=[KeyC, Space, Control, Shift, Alt], action_dispatch=PathToolMessage::PointerMove { toggle_colinear: KeyC, equidistant: Alt, move_anchor_with_handles: Space, snap_angle: Shift, lock_angle: Control }),
|
||||
entry!(PointerMove; refresh_keys=[KeyC, Space, Control, Shift, Alt], action_dispatch=PathToolMessage::PointerMove { toggle_colinear: KeyC, equidistant: Alt, move_anchor_with_handles: Space, snap_angle: Shift, lock_angle: Control, delete_segment: Alt, break_colinear_molding: Alt }),
|
||||
entry!(KeyDown(Delete); action_dispatch=PathToolMessage::Delete),
|
||||
entry!(KeyDown(KeyA); modifiers=[Accel], action_dispatch=PathToolMessage::SelectAllAnchors),
|
||||
entry!(KeyDown(KeyA); modifiers=[Accel, Shift], action_dispatch=PathToolMessage::DeselectAllPoints),
|
||||
@@ -282,6 +289,7 @@ pub fn input_mappings() -> Mapping {
|
||||
entry!(KeyDown(Enter); action_dispatch=SplineToolMessage::Confirm),
|
||||
//
|
||||
// FillToolMessage
|
||||
entry!(PointerMove; refresh_keys=[Shift], action_dispatch=FillToolMessage::PointerMove),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=FillToolMessage::FillPrimaryColor),
|
||||
entry!(KeyDown(MouseLeft); modifiers=[Shift], action_dispatch=FillToolMessage::FillSecondaryColor),
|
||||
entry!(KeyUp(MouseLeft); action_dispatch=FillToolMessage::PointerUp),
|
||||
@@ -307,10 +315,10 @@ pub fn input_mappings() -> Mapping {
|
||||
entry!(KeyDown(KeyA); action_dispatch=ToolMessage::ActivateToolPath),
|
||||
entry!(KeyDown(KeyP); action_dispatch=ToolMessage::ActivateToolPen),
|
||||
entry!(KeyDown(KeyN); action_dispatch=ToolMessage::ActivateToolFreehand),
|
||||
entry!(KeyDown(KeyL); action_dispatch=ToolMessage::ActivateToolLine),
|
||||
entry!(KeyDown(KeyM); action_dispatch=ToolMessage::ActivateToolRectangle),
|
||||
entry!(KeyDown(KeyE); action_dispatch=ToolMessage::ActivateToolEllipse),
|
||||
entry!(KeyDown(KeyY); action_dispatch=ToolMessage::ActivateToolPolygon),
|
||||
entry!(KeyDown(KeyL); action_dispatch=ToolMessage::ActivateToolShapeLine),
|
||||
entry!(KeyDown(KeyM); action_dispatch=ToolMessage::ActivateToolShapeRectangle),
|
||||
entry!(KeyDown(KeyE); action_dispatch=ToolMessage::ActivateToolShapeEllipse),
|
||||
entry!(KeyDown(KeyY); action_dispatch=ToolMessage::ActivateToolShape),
|
||||
entry!(KeyDown(KeyB); action_dispatch=ToolMessage::ActivateToolBrush),
|
||||
entry!(KeyDown(KeyX); modifiers=[Accel, Shift], action_dispatch=ToolMessage::ResetColors),
|
||||
entry!(KeyDown(KeyX); modifiers=[Shift], action_dispatch=ToolMessage::SwapColors),
|
||||
@@ -399,6 +407,7 @@ pub fn input_mappings() -> Mapping {
|
||||
entry!(KeyDown(NumpadAdd); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Equal); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(Minus); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomDecrease { center_on_mouse: false }),
|
||||
entry!(KeyDown(KeyF); modifiers=[Alt], action_dispatch=NavigationMessage::CanvasFlip),
|
||||
entry!(WheelScroll; modifiers=[Control], action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
|
||||
entry!(WheelScroll; modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
|
||||
entry!(WheelScroll; action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_core::text::Font;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::text::Font;
|
||||
use graphene_std::vector::style::{FillChoice, GradientStops};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -121,7 +121,10 @@ impl LayoutMessageHandler {
|
||||
};
|
||||
|
||||
(|| {
|
||||
let update_value = value.as_object().expect("ColorInput update was not of type: object");
|
||||
let Some(update_value) = value.as_object() else {
|
||||
warn!("ColorInput update was not of type: object");
|
||||
return Message::NoOp;
|
||||
};
|
||||
|
||||
// None
|
||||
let is_none = update_value.get("none").and_then(|x| x.as_bool());
|
||||
@@ -154,7 +157,8 @@ impl LayoutMessageHandler {
|
||||
return (color_button.on_update.callback)(color_button);
|
||||
}
|
||||
|
||||
panic!("ColorInput update was not able to be parsed with color data: {color_button:?}");
|
||||
warn!("ColorInput update was not able to be parsed with color data: {color_button:?}");
|
||||
Message::NoOp
|
||||
})()
|
||||
}
|
||||
};
|
||||
@@ -276,13 +280,13 @@ impl LayoutMessageHandler {
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::PivotInput(pivot_input) => {
|
||||
Widget::ReferencePointInput(reference_point_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (pivot_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (reference_point_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let update_value = value.as_str().expect("PivotInput update was not of type: u64");
|
||||
pivot_input.position = update_value.into();
|
||||
(pivot_input.on_update.callback)(pivot_input)
|
||||
let update_value = value.as_str().expect("ReferencePointInput update was not of type: u64");
|
||||
reference_point_input.value = update_value.into();
|
||||
(reference_point_input.on_update.callback)(reference_point_input)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -424,7 +428,9 @@ impl LayoutMessageHandler {
|
||||
LayoutTarget::DialogColumn2 => FrontendMessage::UpdateDialogColumn2 { layout_target, diff },
|
||||
LayoutTarget::DocumentBar => FrontendMessage::UpdateDocumentBarLayout { layout_target, diff },
|
||||
LayoutTarget::DocumentMode => FrontendMessage::UpdateDocumentModeLayout { layout_target, diff },
|
||||
LayoutTarget::LayersPanelControlBar => FrontendMessage::UpdateLayersPanelControlBarLayout { layout_target, diff },
|
||||
LayoutTarget::LayersPanelControlLeftBar => FrontendMessage::UpdateLayersPanelControlBarLeftLayout { layout_target, diff },
|
||||
LayoutTarget::LayersPanelControlRightBar => FrontendMessage::UpdateLayersPanelControlBarRightLayout { layout_target, diff },
|
||||
LayoutTarget::LayersPanelBottomBar => FrontendMessage::UpdateLayersPanelBottomBarLayout { layout_target, diff },
|
||||
LayoutTarget::MenuBar => unreachable!("Menu bar is not diffed"),
|
||||
LayoutTarget::NodeGraphControlBar => FrontendMessage::UpdateNodeGraphControlBarLayout { layout_target, diff },
|
||||
LayoutTarget::PropertiesSections => FrontendMessage::UpdatePropertyPanelSectionsLayout { layout_target, diff },
|
||||
|
||||
@@ -31,8 +31,12 @@ pub enum LayoutTarget {
|
||||
DocumentBar,
|
||||
/// Contains the dropdown for design / select / guide mode found on the top left of the canvas.
|
||||
DocumentMode,
|
||||
/// Options for opacity seen at the top of the Layers panel.
|
||||
LayersPanelControlBar,
|
||||
/// Blending options at the top of the Layers panel.
|
||||
LayersPanelControlLeftBar,
|
||||
/// Selected layer status (locked/hidden) at the top of the Layers panel.
|
||||
LayersPanelControlRightBar,
|
||||
/// Controls for adding, grouping, and deleting layers at the bottom of the Layers panel.
|
||||
LayersPanelBottomBar,
|
||||
/// The dropdown menu at the very top of the application: File, Edit, etc.
|
||||
MenuBar,
|
||||
/// Bar at the top of the node graph containing the location and the "Preview" and "Hide" buttons.
|
||||
@@ -373,7 +377,7 @@ impl LayoutGroup {
|
||||
Widget::TextInput(x) => &mut x.tooltip,
|
||||
Widget::TextLabel(x) => &mut x.tooltip,
|
||||
Widget::BreadcrumbTrailButtons(x) => &mut x.tooltip,
|
||||
Widget::InvisibleStandinInput(_) | Widget::PivotInput(_) | Widget::RadioInput(_) | Widget::Separator(_) | Widget::WorkingColorsInput(_) | Widget::NodeCatalog(_) => continue,
|
||||
Widget::InvisibleStandinInput(_) | Widget::ReferencePointInput(_) | Widget::RadioInput(_) | Widget::Separator(_) | Widget::WorkingColorsInput(_) | Widget::NodeCatalog(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
val.clone_from(&tooltip);
|
||||
@@ -546,7 +550,7 @@ pub enum Widget {
|
||||
NodeCatalog(NodeCatalog),
|
||||
NumberInput(NumberInput),
|
||||
ParameterExposeButton(ParameterExposeButton),
|
||||
PivotInput(PivotInput),
|
||||
ReferencePointInput(ReferencePointInput),
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
@@ -621,7 +625,7 @@ impl DiffUpdate {
|
||||
| Widget::CurveInput(_)
|
||||
| Widget::InvisibleStandinInput(_)
|
||||
| Widget::NodeCatalog(_)
|
||||
| Widget::PivotInput(_)
|
||||
| Widget::ReferencePointInput(_)
|
||||
| Widget::RadioInput(_)
|
||||
| Widget::Separator(_)
|
||||
| Widget::TextAreaInput(_)
|
||||
|
||||
@@ -42,6 +42,9 @@ pub struct IconButton {
|
||||
pub struct PopoverButton {
|
||||
pub style: Option<String>,
|
||||
|
||||
#[serde(rename = "menuDirection")]
|
||||
pub menu_direction: Option<MenuDirection>,
|
||||
|
||||
pub icon: Option<String>,
|
||||
|
||||
pub disabled: bool,
|
||||
@@ -58,6 +61,20 @@ pub struct PopoverButton {
|
||||
pub popover_min_width: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum MenuDirection {
|
||||
Top,
|
||||
#[default]
|
||||
Bottom,
|
||||
Left,
|
||||
Right,
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
Center,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct ParameterExposeButton {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionKeys;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use derivative::*;
|
||||
use glam::DVec2;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::raster::curve::Curve;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::curve::Curve;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
@@ -18,6 +20,9 @@ pub struct CheckboxInput {
|
||||
|
||||
pub tooltip: String,
|
||||
|
||||
#[serde(rename = "forLabel", skip_serializing_if = "checkbox_id_is_empty")]
|
||||
pub for_label: CheckboxId,
|
||||
|
||||
#[serde(skip)]
|
||||
pub tooltip_shortcut: Option<ActionKeys>,
|
||||
|
||||
@@ -39,12 +44,51 @@ impl Default for CheckboxInput {
|
||||
icon: "Checkmark".into(),
|
||||
tooltip: Default::default(),
|
||||
tooltip_shortcut: Default::default(),
|
||||
for_label: CheckboxId::default(),
|
||||
on_update: Default::default(),
|
||||
on_commit: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Debug, Eq, PartialEq)]
|
||||
pub struct CheckboxId(Arc<OnceCell<u64>>);
|
||||
|
||||
impl CheckboxId {
|
||||
pub fn fill(&mut self) {
|
||||
let _ = self.0.set(graphene_std::uuid::generate_uuid());
|
||||
}
|
||||
}
|
||||
impl specta::Type for CheckboxId {
|
||||
fn inline(_type_map: &mut specta::TypeCollection, _generics: specta::Generics) -> specta::datatype::DataType {
|
||||
// TODO: This might not be right, but it works for now. We just need the type `bigint | undefined`.
|
||||
specta::datatype::DataType::Primitive(specta::datatype::PrimitiveType::u64)
|
||||
}
|
||||
}
|
||||
impl serde::Serialize for CheckboxId {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
self.0.get().copied().serialize(serializer)
|
||||
}
|
||||
}
|
||||
impl<'a> serde::Deserialize<'a> for CheckboxId {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'a>,
|
||||
{
|
||||
let id = u64::deserialize(deserializer)?;
|
||||
let checkbox_id = CheckboxId(OnceCell::new().into());
|
||||
checkbox_id.0.set(id).map_err(serde::de::Error::custom)?;
|
||||
Ok(checkbox_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn checkbox_id_is_empty(id: &CheckboxId) -> bool {
|
||||
id.0.get().is_none()
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct DropdownInput {
|
||||
@@ -67,6 +111,13 @@ pub struct DropdownInput {
|
||||
|
||||
#[serde(skip)]
|
||||
pub tooltip_shortcut: Option<ActionKeys>,
|
||||
|
||||
// Styling
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
//
|
||||
// Callbacks
|
||||
// `on_update` exists on the `MenuListEntry`, not this parent `DropdownInput`
|
||||
@@ -208,6 +259,9 @@ pub struct NumberInput {
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
@@ -411,100 +465,18 @@ pub struct CurveInput {
|
||||
|
||||
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub struct PivotInput {
|
||||
pub struct ReferencePointInput {
|
||||
#[widget_builder(constructor)]
|
||||
pub position: PivotPosition,
|
||||
pub value: ReferencePoint,
|
||||
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<PivotInput>,
|
||||
pub on_update: WidgetCallback<ReferencePointInput>,
|
||||
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, serde::Serialize, serde::Deserialize, Debug, Default, PartialEq, Eq, specta::Type)]
|
||||
pub enum PivotPosition {
|
||||
#[default]
|
||||
None,
|
||||
TopLeft,
|
||||
TopCenter,
|
||||
TopRight,
|
||||
CenterLeft,
|
||||
Center,
|
||||
CenterRight,
|
||||
BottomLeft,
|
||||
BottomCenter,
|
||||
BottomRight,
|
||||
}
|
||||
|
||||
impl From<&str> for PivotPosition {
|
||||
fn from(input: &str) -> Self {
|
||||
match input {
|
||||
"None" => PivotPosition::None,
|
||||
"TopLeft" => PivotPosition::TopLeft,
|
||||
"TopCenter" => PivotPosition::TopCenter,
|
||||
"TopRight" => PivotPosition::TopRight,
|
||||
"CenterLeft" => PivotPosition::CenterLeft,
|
||||
"Center" => PivotPosition::Center,
|
||||
"CenterRight" => PivotPosition::CenterRight,
|
||||
"BottomLeft" => PivotPosition::BottomLeft,
|
||||
"BottomCenter" => PivotPosition::BottomCenter,
|
||||
"BottomRight" => PivotPosition::BottomRight,
|
||||
_ => panic!("Failed parsing unrecognized PivotPosition enum value '{input}'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PivotPosition> for Option<DVec2> {
|
||||
fn from(input: PivotPosition) -> Self {
|
||||
match input {
|
||||
PivotPosition::None => None,
|
||||
PivotPosition::TopLeft => Some(DVec2::new(0., 0.)),
|
||||
PivotPosition::TopCenter => Some(DVec2::new(0.5, 0.)),
|
||||
PivotPosition::TopRight => Some(DVec2::new(1., 0.)),
|
||||
PivotPosition::CenterLeft => Some(DVec2::new(0., 0.5)),
|
||||
PivotPosition::Center => Some(DVec2::new(0.5, 0.5)),
|
||||
PivotPosition::CenterRight => Some(DVec2::new(1., 0.5)),
|
||||
PivotPosition::BottomLeft => Some(DVec2::new(0., 1.)),
|
||||
PivotPosition::BottomCenter => Some(DVec2::new(0.5, 1.)),
|
||||
PivotPosition::BottomRight => Some(DVec2::new(1., 1.)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DVec2> for PivotPosition {
|
||||
fn from(input: DVec2) -> Self {
|
||||
const TOLERANCE: f64 = 1e-5_f64;
|
||||
if input.y.abs() < TOLERANCE {
|
||||
if input.x.abs() < TOLERANCE {
|
||||
return PivotPosition::TopLeft;
|
||||
} else if (input.x - 0.5).abs() < TOLERANCE {
|
||||
return PivotPosition::TopCenter;
|
||||
} else if (input.x - 1.).abs() < TOLERANCE {
|
||||
return PivotPosition::TopRight;
|
||||
}
|
||||
} else if (input.y - 0.5).abs() < TOLERANCE {
|
||||
if input.x.abs() < TOLERANCE {
|
||||
return PivotPosition::CenterLeft;
|
||||
} else if (input.x - 0.5).abs() < TOLERANCE {
|
||||
return PivotPosition::Center;
|
||||
} else if (input.x - 1.).abs() < TOLERANCE {
|
||||
return PivotPosition::CenterRight;
|
||||
}
|
||||
} else if (input.y - 1.).abs() < TOLERANCE {
|
||||
if input.x.abs() < TOLERANCE {
|
||||
return PivotPosition::BottomLeft;
|
||||
} else if (input.x - 0.5).abs() < TOLERANCE {
|
||||
return PivotPosition::BottomCenter;
|
||||
} else if (input.x - 1.).abs() < TOLERANCE {
|
||||
return PivotPosition::BottomRight;
|
||||
}
|
||||
}
|
||||
PivotPosition::None
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::input_widgets::CheckboxId;
|
||||
use derivative::*;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
@@ -56,9 +57,21 @@ pub struct TextLabel {
|
||||
|
||||
pub tooltip: String,
|
||||
|
||||
#[serde(rename = "checkboxId")]
|
||||
#[widget_builder(skip)]
|
||||
pub checkbox_id: CheckboxId,
|
||||
|
||||
// Body
|
||||
#[widget_builder(constructor)]
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl TextLabel {
|
||||
pub fn for_checkbox(mut self, id: &mut CheckboxId) -> Self {
|
||||
id.fill();
|
||||
self.checkbox_id = id.clone();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Add UserInputLabel
|
||||
@@ -1,21 +1,23 @@
|
||||
use super::utility_types::misc::{GroupFolderType, SnappingState};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlaysType;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::raster::BlendMode;
|
||||
use graphene_core::raster::Image;
|
||||
use graphene_core::vector::style::ViewMode;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::renderer::ClickTarget;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::style::ViewMode;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Document)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub enum DocumentMessage {
|
||||
Noop,
|
||||
// Sub-messages
|
||||
@@ -120,6 +122,9 @@ pub enum DocumentMessage {
|
||||
SelectedLayersReorder {
|
||||
relative_index_offset: isize,
|
||||
},
|
||||
ClipLayer {
|
||||
id: NodeId,
|
||||
},
|
||||
SelectLayer {
|
||||
id: NodeId,
|
||||
ctrl: bool,
|
||||
@@ -141,14 +146,19 @@ pub enum DocumentMessage {
|
||||
SetOpacityForSelectedLayers {
|
||||
opacity: f64,
|
||||
},
|
||||
SetFillForSelectedLayers {
|
||||
fill: f64,
|
||||
},
|
||||
SetOverlaysVisibility {
|
||||
visible: bool,
|
||||
overlays_type: Option<OverlaysType>,
|
||||
},
|
||||
SetRangeSelectionLayer {
|
||||
new_layer: Option<LayerNodeIdentifier>,
|
||||
},
|
||||
SetSnapping {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
closure: Option<for<'a> fn(&'a mut SnappingState) -> &'a mut bool>,
|
||||
snapping_state: bool,
|
||||
},
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,14 +5,14 @@ use crate::messages::prelude::*;
|
||||
use bezier_rs::Subpath;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::raster::BlendMode;
|
||||
use graphene_core::raster::image::ImageFrameTable;
|
||||
use graphene_core::text::{Font, TypesettingConfig};
|
||||
use graphene_core::vector::PointId;
|
||||
use graphene_core::vector::VectorModificationType;
|
||||
use graphene_core::vector::brush_stroke::BrushStroke;
|
||||
use graphene_core::vector::style::{Fill, Stroke};
|
||||
use graphene_core::{Artboard, Color};
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, RasterDataTable};
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::brush_stroke::BrushStroke;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -21,6 +21,10 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
fill: Fill,
|
||||
},
|
||||
BlendingFillSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
fill: f64,
|
||||
},
|
||||
OpacitySet {
|
||||
layer: LayerNodeIdentifier,
|
||||
opacity: f64,
|
||||
@@ -29,6 +33,9 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
blend_mode: BlendMode,
|
||||
},
|
||||
ClipModeToggle {
|
||||
layer: LayerNodeIdentifier,
|
||||
},
|
||||
StrokeSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
stroke: Stroke,
|
||||
@@ -66,7 +73,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
image_frame: ImageFrameTable<Color>,
|
||||
image_frame: RasterDataTable<CPU>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
|
||||
+33
-16
@@ -5,13 +5,14 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::Color;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::text::{Font, TypesettingConfig};
|
||||
use graphene_core::vector::style::{Fill, Gradient, GradientStops, GradientType, LineCap, LineJoin, Stroke};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::convert_usvg_path;
|
||||
use graphene_std::vector::style::{Fill, Gradient, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ArtboardInfo {
|
||||
@@ -41,6 +42,11 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageData<'_>> for Gr
|
||||
modify_inputs.fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::BlendingFillSet { layer, fill } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.blending_fill_set(fill);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::OpacitySet { layer, opacity } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.opacity_set(opacity);
|
||||
@@ -51,6 +57,12 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageData<'_>> for Gr
|
||||
modify_inputs.blend_mode_set(blend_mode);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::ClipModeToggle { layer } => {
|
||||
let clip_mode = get_clip_mode(layer, network_interface);
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.clip_mode_toggle(clip_mode);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::StrokeSet { layer, stroke } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.stroke_set(stroke);
|
||||
@@ -330,6 +342,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
modify_inputs.layer_node = Some(layer);
|
||||
if let Some(upstream_layer) = layer.next_sibling(modify_inputs.network_interface.document_metadata()) {
|
||||
modify_inputs.network_interface.shift_node(&upstream_layer.to_node(), IVec2::new(0, 3), &[]);
|
||||
}
|
||||
match node {
|
||||
usvg::Node::Group(group) => {
|
||||
for child in group.children() {
|
||||
@@ -359,7 +374,7 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
warn!("Skip image")
|
||||
}
|
||||
usvg::Node::Text(text) => {
|
||||
let font = Font::new(graphene_core::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_core::consts::DEFAULT_FONT_STYLE.to_string());
|
||||
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.to_string(), graphene_std::consts::DEFAULT_FONT_STYLE.to_string());
|
||||
modify_inputs.insert_text(text.chunks().iter().map(|chunk| chunk.text()).collect(), font, TypesettingConfig::default(), layer);
|
||||
modify_inputs.fill_set(Fill::Solid(Color::BLACK));
|
||||
}
|
||||
@@ -373,18 +388,20 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
|
||||
weight: stroke.width().get() as f64,
|
||||
dash_lengths: stroke.dasharray().as_ref().map(|lengths| lengths.iter().map(|&length| length as f64).collect()).unwrap_or_default(),
|
||||
dash_offset: stroke.dashoffset() as f64,
|
||||
line_cap: match stroke.linecap() {
|
||||
usvg::LineCap::Butt => LineCap::Butt,
|
||||
usvg::LineCap::Round => LineCap::Round,
|
||||
usvg::LineCap::Square => LineCap::Square,
|
||||
cap: match stroke.linecap() {
|
||||
usvg::LineCap::Butt => StrokeCap::Butt,
|
||||
usvg::LineCap::Round => StrokeCap::Round,
|
||||
usvg::LineCap::Square => StrokeCap::Square,
|
||||
},
|
||||
line_join: match stroke.linejoin() {
|
||||
usvg::LineJoin::Miter => LineJoin::Miter,
|
||||
usvg::LineJoin::MiterClip => LineJoin::Miter,
|
||||
usvg::LineJoin::Round => LineJoin::Round,
|
||||
usvg::LineJoin::Bevel => LineJoin::Bevel,
|
||||
join: match stroke.linejoin() {
|
||||
usvg::LineJoin::Miter => StrokeJoin::Miter,
|
||||
usvg::LineJoin::MiterClip => StrokeJoin::Miter,
|
||||
usvg::LineJoin::Round => StrokeJoin::Round,
|
||||
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
|
||||
},
|
||||
line_join_miter_limit: stroke.miterlimit().get() as f64,
|
||||
join_miter_limit: stroke.miterlimit().get() as f64,
|
||||
align: StrokeAlign::Center,
|
||||
paint_order: PaintOrder::StrokeAbove,
|
||||
transform,
|
||||
non_scaling: false,
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@ use bezier_rs::Subpath;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::vector::PointId;
|
||||
use graphene_std::vector::PointId;
|
||||
|
||||
/// Convert an affine transform into the tuple `(scale, angle, translation, shear)` assuming `shear.y = 0`.
|
||||
pub fn compute_scale_angle_translation_shear(transform: DAffine2) -> (DVec2, f64, DVec2, DVec2) {
|
||||
@@ -91,44 +91,48 @@ pub fn get_current_normalized_pivot(inputs: &[NodeInput]) -> DVec2 {
|
||||
if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) }
|
||||
}
|
||||
|
||||
/// 
|
||||
///
|
||||
/// Source:
|
||||
/// ```tex
|
||||
/// \begin{bmatrix}
|
||||
/// S_{x}\cos(\theta)-S_{y}\sin(\theta)H_{y} & S_{x}\cos(\theta)H_{x}-S_{y}\sin(\theta) & T_{x}\\
|
||||
/// S_{x}\sin(\theta)+S_{y}\cos(\theta)H_{y} & S_{x}\sin(\theta)H_{x}+S_{y}\cos(\theta) & T_{y}\\
|
||||
/// 0 & 0 & 1
|
||||
/// \end{bmatrix}
|
||||
/// ```
|
||||
#[test]
|
||||
fn derive_transform() {
|
||||
for shear_x in -10..=10 {
|
||||
let shear_x = (shear_x as f64) / 2.;
|
||||
for angle in (0..=360).step_by(15) {
|
||||
let angle = (angle as f64).to_radians();
|
||||
for scale_x in 1..10 {
|
||||
let scale_x = (scale_x as f64) / 5.;
|
||||
for scale_y in 1..10 {
|
||||
let scale_y = (scale_y as f64) / 5.;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// 
|
||||
///
|
||||
/// Source:
|
||||
/// ```tex
|
||||
/// \begin{bmatrix}
|
||||
/// S_{x}\cos(\theta)-S_{y}\sin(\theta)H_{y} & S_{x}\cos(\theta)H_{x}-S_{y}\sin(\theta) & T_{x}\\
|
||||
/// S_{x}\sin(\theta)+S_{y}\cos(\theta)H_{y} & S_{x}\sin(\theta)H_{x}+S_{y}\cos(\theta) & T_{y}\\
|
||||
/// 0 & 0 & 1
|
||||
/// \end{bmatrix}
|
||||
/// ```
|
||||
#[test]
|
||||
fn derive_transform() {
|
||||
for shear_x in -10..=10 {
|
||||
let shear_x = (shear_x as f64) / 2.;
|
||||
for angle in (0..=360).step_by(15) {
|
||||
let angle = (angle as f64).to_radians();
|
||||
for scale_x in 1..10 {
|
||||
let scale_x = (scale_x as f64) / 5.;
|
||||
for scale_y in 1..10 {
|
||||
let scale_y = (scale_y as f64) / 5.;
|
||||
|
||||
let shear = DVec2::new(shear_x, 0.);
|
||||
let scale = DVec2::new(scale_x, scale_y);
|
||||
let translate = DVec2::new(5666., 644.);
|
||||
let shear = DVec2::new(shear_x, 0.);
|
||||
let scale = DVec2::new(scale_x, scale_y);
|
||||
let translate = DVec2::new(5666., 644.);
|
||||
|
||||
let original_transform = DAffine2::from_cols(
|
||||
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * shear.y, scale.x * angle.sin() + scale.y * angle.cos() * shear.y),
|
||||
DVec2::new(scale.x * angle.cos() * shear.x - scale.y * angle.sin(), scale.x * angle.sin() * shear.x + scale.y * angle.cos()),
|
||||
translate,
|
||||
);
|
||||
let original_transform = DAffine2::from_cols(
|
||||
DVec2::new(scale.x * angle.cos() - scale.y * angle.sin() * shear.y, scale.x * angle.sin() + scale.y * angle.cos() * shear.y),
|
||||
DVec2::new(scale.x * angle.cos() * shear.x - scale.y * angle.sin(), scale.x * angle.sin() * shear.x + scale.y * angle.cos()),
|
||||
translate,
|
||||
);
|
||||
|
||||
let (new_scale, new_angle, new_translation, new_shear) = compute_scale_angle_translation_shear(original_transform);
|
||||
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., new_shear.y, new_shear.x, 1., 0., 0.]);
|
||||
let (new_scale, new_angle, new_translation, new_shear) = compute_scale_angle_translation_shear(original_transform);
|
||||
let new_transform = DAffine2::from_scale_angle_translation(new_scale, new_angle, new_translation) * DAffine2::from_cols_array(&[1., new_shear.y, new_shear.x, 1., 0., 0.]);
|
||||
|
||||
assert!(
|
||||
new_transform.abs_diff_eq(original_transform, 1e-10),
|
||||
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / shear {shear} / new_shear {new_shear}",
|
||||
);
|
||||
assert!(
|
||||
new_transform.abs_diff_eq(original_transform, 1e-10),
|
||||
"original_transform {original_transform} new_transform {new_transform} / scale {scale} new_scale {new_scale} / angle {angle} new_angle {new_angle} / shear {shear} / new_shear {new_shear}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,15 +8,15 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::raster::BlendMode;
|
||||
use graphene_core::raster::image::ImageFrameTable;
|
||||
use graphene_core::text::{Font, TypesettingConfig};
|
||||
use graphene_core::vector::brush_stroke::BrushStroke;
|
||||
use graphene_core::vector::style::{Fill, Stroke};
|
||||
use graphene_core::vector::{PointId, VectorModificationType};
|
||||
use graphene_core::{Artboard, Color};
|
||||
use graphene_std::GraphicGroupTable;
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, RasterDataTable};
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::brush_stroke::BrushStroke;
|
||||
use graphene_std::vector::style::{Fill, Stroke};
|
||||
use graphene_std::vector::{PointId, VectorModificationType};
|
||||
use graphene_std::vector::{VectorData, VectorDataTable};
|
||||
use graphene_std::{GraphicGroupTable, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransformIn {
|
||||
@@ -58,13 +58,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// Non layer nodes directly upstream of a layer are treated as part of that layer. See insert_index == 2 in the diagram
|
||||
/// -----> Post node
|
||||
/// | if insert_index == 0, return (Post node, Some(Layer1))
|
||||
/// -> Layer1
|
||||
/// -> Layer1
|
||||
/// ↑ if insert_index == 1, return (Layer1, Some(Layer2))
|
||||
/// -> Layer2
|
||||
/// -> Layer2
|
||||
/// ↑
|
||||
/// -> NonLayerNode
|
||||
/// ↑ if insert_index == 2, return (NonLayerNode, Some(Layer3))
|
||||
/// -> Layer3
|
||||
/// -> Layer3
|
||||
/// if insert_index == 3, return (Layer3, None)
|
||||
pub fn get_post_node_with_index(network_interface: &NodeNetworkInterface, parent: LayerNodeIdentifier, insert_index: usize) -> InputConnector {
|
||||
let mut post_node_input_connector = if parent == LayerNodeIdentifier::ROOT_PARENT {
|
||||
@@ -124,7 +124,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, artboard: Artboard) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_document_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::ArtboardGroup(graphene_std::ArtboardGroupTable::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::GraphicGroup(graphene_core::GraphicGroupTable::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::GraphicGroup(graphene_std::GraphicGroupTable::default()), true)),
|
||||
Some(NodeInput::value(TaggedValue::IVec2(artboard.location), false)),
|
||||
Some(NodeInput::value(TaggedValue::IVec2(artboard.dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(artboard.background), false)),
|
||||
@@ -209,11 +209,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
|
||||
}
|
||||
|
||||
pub fn insert_image_data(&mut self, image_frame: ImageFrameTable<Color>, layer: LayerNodeIdentifier) {
|
||||
pub fn insert_image_data(&mut self, image_frame: RasterDataTable<CPU>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
|
||||
let image = resolve_document_node_type("Image")
|
||||
.expect("Image node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::ImageFrame(image_frame), false))]);
|
||||
let image = resolve_document_node_type("Image Value")
|
||||
.expect("ImageValue node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::RasterData(image_frame), false))]);
|
||||
|
||||
let image_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_id, image, &[]);
|
||||
@@ -289,17 +289,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
log::error!("Node type {} does not exist in ModifyInputsContext::existing_node_id", reference);
|
||||
return None;
|
||||
};
|
||||
// If inserting a path node, insert a flatten vector elements if the type is a graphic group.
|
||||
// If inserting a path node, insert a Flatten Path if the type is a graphic group.
|
||||
// TODO: Allow the path node to operate on Graphic Group data by utilizing the reference for each vector data in a group.
|
||||
if node_definition.identifier == "Path" {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]).0.nested_type().clone();
|
||||
if layer_input_type == concrete!(GraphicGroupTable) {
|
||||
let Some(flatten_vector_elements_definition) = resolve_document_node_type("Flatten Vector Elements") else {
|
||||
log::error!("Flatten Vector Elements does not exist in ModifyInputsContext::existing_node_id");
|
||||
let Some(flatten_path_definition) = resolve_document_node_type("Flatten Path") else {
|
||||
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
|
||||
return None;
|
||||
};
|
||||
let node_id = NodeId::new();
|
||||
self.network_interface.insert_node(node_id, flatten_vector_elements_definition.default_node_template(), &[]);
|
||||
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
|
||||
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[]);
|
||||
}
|
||||
}
|
||||
@@ -333,37 +333,52 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Fill(fill), false), false);
|
||||
}
|
||||
|
||||
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
|
||||
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
|
||||
let input_connector = InputConnector::node(blend_node_id, 1);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
|
||||
}
|
||||
|
||||
pub fn opacity_set(&mut self, opacity: f64) {
|
||||
let Some(opacity_node_id) = self.existing_node_id("Opacity", true) else { return };
|
||||
let input_connector = InputConnector::node(opacity_node_id, 1);
|
||||
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
|
||||
let input_connector = InputConnector::node(blend_node_id, 2);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
|
||||
let Some(blend_mode_node_id) = self.existing_node_id("Blend Mode", true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(blend_mode_node_id, 1);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
|
||||
pub fn blending_fill_set(&mut self, fill: f64) {
|
||||
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
|
||||
let input_connector = InputConnector::node(blend_node_id, 3);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
|
||||
}
|
||||
|
||||
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
|
||||
let clip = !clip_mode.unwrap_or(false);
|
||||
let Some(clip_node_id) = self.existing_node_id("Blending", true) else { return };
|
||||
let input_connector = InputConnector::node(clip_node_id, 4);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
|
||||
}
|
||||
|
||||
pub fn stroke_set(&mut self, stroke: Stroke) {
|
||||
let Some(stroke_node_id) = self.existing_node_id("Stroke", true) else { return };
|
||||
|
||||
let input_connector = InputConnector::node(stroke_node_id, 1);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::ColorInput::<Option<graphene_std::Color>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::OptionalColor(stroke.color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 2);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 3);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeCap(stroke.cap), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::VecF64(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 4);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 5);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::LineCap(stroke.line_cap), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 6);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::LineJoin(stroke.line_join), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, 7);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.line_join_miter_limit), false), false);
|
||||
}
|
||||
|
||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||
@@ -413,13 +428,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn transform_set_direct(&mut self, transform: DAffine2, skip_rerender: bool, transform_node_id: Option<NodeId>) {
|
||||
// If the Transform node didn't exist yet, create it now
|
||||
let Some(transform_node_id) = transform_node_id.or_else(|| {
|
||||
// Check if the transform is the identity transform and if so, don't create a new Transform node
|
||||
if let Some((scale, angle, translation)) = (transform.matrix2.determinant() != 0.).then(|| transform.to_scale_angle_translation()) {
|
||||
// Check if the transform is the identity transform within an epsilon
|
||||
if scale.x.abs() < 1e-6 && scale.y.abs() < 1e-6 && angle.abs() < 1e-6 && translation.x.abs() < 1e-6 && translation.y.abs() < 1e-6 {
|
||||
// We don't want to pollute the graph with an unnecessary Transform node, so we avoid creating and setting it by returning None
|
||||
return None;
|
||||
}
|
||||
// Check if the transform is the identity transform (within an epsilon) and if so, don't create a new Transform node
|
||||
if transform.abs_diff_eq(DAffine2::IDENTITY, 1e-6) {
|
||||
// We don't want to pollute the graph with an unnecessary Transform node, so we avoid creating and setting it by returning None
|
||||
return None;
|
||||
}
|
||||
|
||||
// Create the Transform node
|
||||
@@ -453,7 +465,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
|
||||
let Some(brush_node_id) = self.existing_node_id("Brush", true) else { return };
|
||||
self.set_input_with_refresh(InputConnector::node(brush_node_id, 2), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
|
||||
}
|
||||
|
||||
pub fn resize_artboard(&mut self, location: IVec2, dimensions: IVec2) {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub enum NavigationMessage {
|
||||
CanvasZoomIncrease { center_on_mouse: bool },
|
||||
CanvasZoomMouseWheel,
|
||||
CanvasZoomSet { zoom_factor: f64 },
|
||||
CanvasFlip,
|
||||
EndCanvasPTZ { abort_transform: bool },
|
||||
EndCanvasPTZWithClick { commit_key: Key },
|
||||
FitViewportToBounds { bounds: [DVec2; 2], prevent_zoom_past_100: bool },
|
||||
|
||||
@@ -204,6 +204,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageData<'_>> for Navigation
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
if !graph_view_overlay_open {
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
}
|
||||
}
|
||||
NavigationMessage::CanvasZoomDecrease { center_on_mouse } => {
|
||||
@@ -273,6 +274,22 @@ impl MessageHandler<NavigationMessage, NavigationMessageData<'_>> for Navigation
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
responses.add(NodeGraphMessage::SetGridAlignedEdges);
|
||||
}
|
||||
NavigationMessage::CanvasFlip => {
|
||||
if graph_view_overlay_open {
|
||||
return;
|
||||
}
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in CanvasFlip");
|
||||
return;
|
||||
};
|
||||
|
||||
ptz.flip = !ptz.flip;
|
||||
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
responses.add(BroadcastEvent::CanvasTransformed);
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZ { abort_transform } => {
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in EndCanvasPTZ");
|
||||
@@ -393,9 +410,11 @@ impl MessageHandler<NavigationMessage, NavigationMessageData<'_>> for Navigation
|
||||
..
|
||||
} => {
|
||||
let tilt_raw_not_snapped = {
|
||||
// Compute the angle in document space to counter for the canvas being flipped
|
||||
let viewport_to_document = network_interface.document_metadata().document_to_viewport.inverse();
|
||||
let half_viewport = ipp.viewport_bounds.size() / 2.;
|
||||
let start_offset = self.mouse_position - half_viewport;
|
||||
let end_offset = ipp.mouse.position - half_viewport;
|
||||
let start_offset = viewport_to_document.transform_vector2(self.mouse_position - half_viewport);
|
||||
let end_offset = viewport_to_document.transform_vector2(ipp.mouse.position - half_viewport);
|
||||
let angle = start_offset.angle_to(end_offset);
|
||||
|
||||
tilt_raw_not_snapped + angle
|
||||
@@ -471,6 +490,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageData<'_>> for Navigation
|
||||
CanvasZoomDecrease,
|
||||
CanvasZoomIncrease,
|
||||
CanvasZoomMouseWheel,
|
||||
CanvasFlip,
|
||||
FitViewportToSelection,
|
||||
);
|
||||
|
||||
@@ -513,15 +533,16 @@ impl NavigationMessageHandler {
|
||||
let tilt = ptz.tilt();
|
||||
let zoom = ptz.zoom();
|
||||
|
||||
let scaled_center = viewport_center / self.snapped_zoom(zoom);
|
||||
let scale = self.snapped_zoom(zoom);
|
||||
let scale_vec = if ptz.flip { DVec2::new(-scale, scale) } else { DVec2::splat(scale) };
|
||||
let scaled_center = viewport_center / scale_vec;
|
||||
|
||||
// Try to avoid fractional coordinates to reduce anti aliasing.
|
||||
let scale = self.snapped_zoom(zoom);
|
||||
let rounded_pan = ((pan + scaled_center) * scale).round() / scale - scaled_center;
|
||||
|
||||
// TODO: replace with DAffine2::from_scale_angle_translation and fix the errors
|
||||
let offset_transform = DAffine2::from_translation(scaled_center);
|
||||
let scale_transform = DAffine2::from_scale(DVec2::splat(scale));
|
||||
let scale_transform = DAffine2::from_scale(scale_vec);
|
||||
let angle_transform = DAffine2::from_angle(self.snapped_tilt(tilt));
|
||||
let translation_transform = DAffine2::from_translation(rounded_pan);
|
||||
scale_transform * offset_transform * angle_transform * translation_transform
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,12 +15,13 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelEntry};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_core::*;
|
||||
use graphene_std::*;
|
||||
use renderer::Quad;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
@@ -566,10 +567,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphHandlerData<'a>> for NodeGrap
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let new_ids: HashMap<_, _> = data.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let nodes: Vec<_> = new_ids.values().copied().collect();
|
||||
responses.add(NodeGraphMessage::AddNodes {
|
||||
nodes: data,
|
||||
new_ids: new_ids.clone(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes })
|
||||
}
|
||||
NodeGraphMessage::PointerDown {
|
||||
shift_click,
|
||||
@@ -995,11 +998,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphHandlerData<'a>> for NodeGrap
|
||||
responses.add(NodeGraphMessage::TogglePreview { node_id: preview_node });
|
||||
self.preview_on_mouse_up = None;
|
||||
}
|
||||
if let Some(node_to_deselect) = self.deselect_on_pointer_up {
|
||||
let mut new_selected_nodes = selected_nodes.selected_nodes_ref().clone();
|
||||
new_selected_nodes.remove(node_to_deselect);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: new_selected_nodes });
|
||||
self.deselect_on_pointer_up = None;
|
||||
if let Some(node_to_deselect) = self.deselect_on_pointer_up.take() {
|
||||
if !self.drag_start.as_ref().is_some_and(|t| t.1) {
|
||||
let mut new_selected_nodes = selected_nodes.selected_nodes_ref().clone();
|
||||
new_selected_nodes.remove(node_to_deselect);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: new_selected_nodes });
|
||||
return;
|
||||
}
|
||||
}
|
||||
let point = network_metadata
|
||||
.persistent_metadata
|
||||
@@ -1214,11 +1219,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphHandlerData<'a>> for NodeGrap
|
||||
if is_stack_wire(&wire) { stack_wires.push(wire) } else { node_wires.push(wire) }
|
||||
}
|
||||
|
||||
// Auto convert node to layer when inserting on a single stack wire
|
||||
if stack_wires.len() == 1 && node_wires.is_empty() {
|
||||
network_interface.set_to_node_or_layer(&selected_node_id, selection_network_path, true)
|
||||
}
|
||||
|
||||
let overlapping_wire = if network_interface.is_layer(&selected_node_id, selection_network_path) {
|
||||
if stack_wires.len() == 1 {
|
||||
stack_wires.first()
|
||||
@@ -1851,11 +1851,6 @@ impl NodeGraphMessageHandler {
|
||||
//
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
//
|
||||
IconButton::new("NewLayer", 24)
|
||||
.tooltip("New Layer")
|
||||
.tooltip_shortcut(action_keys!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.widget_holder(),
|
||||
IconButton::new("Folder", 24)
|
||||
.tooltip("Group Selected")
|
||||
.tooltip_shortcut(action_keys!(DocumentMessageDiscriminant::GroupSelectedLayers))
|
||||
@@ -1865,6 +1860,11 @@ impl NodeGraphMessageHandler {
|
||||
})
|
||||
.disabled(!has_selection)
|
||||
.widget_holder(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
.tooltip("New Layer")
|
||||
.tooltip_shortcut(action_keys!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.widget_holder(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip("Delete Selected")
|
||||
.tooltip_shortcut(action_keys!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
@@ -1969,7 +1969,7 @@ impl NodeGraphMessageHandler {
|
||||
.widget_holder(),
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
];
|
||||
widgets.extend(navigation_controls(node_graph_ptz, navigation_handler, "Node Graph"));
|
||||
widgets.extend(navigation_controls(node_graph_ptz, navigation_handler, true));
|
||||
widgets.extend([
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
TextButton::new("Node Graph")
|
||||
@@ -2009,12 +2009,38 @@ impl NodeGraphMessageHandler {
|
||||
}
|
||||
|
||||
// Next, we decide what to display based on the number of layers and nodes selected
|
||||
match layers.len() {
|
||||
match *layers.as_slice() {
|
||||
// If no layers are selected, show properties for all selected nodes
|
||||
0 => {
|
||||
[] => {
|
||||
let selected_nodes = nodes.iter().map(|node_id| node_properties::generate_node_properties(*node_id, context)).collect::<Vec<_>>();
|
||||
if !selected_nodes.is_empty() {
|
||||
return selected_nodes;
|
||||
let mut properties = Vec::new();
|
||||
|
||||
if let [node_id] = *nodes.as_slice() {
|
||||
properties.push(LayoutGroup::Row {
|
||||
widgets: vec![
|
||||
Separator::new(SeparatorType::Related).widget_holder(),
|
||||
IconLabel::new("Node").tooltip("Name of the selected node").widget_holder(),
|
||||
Separator::new(SeparatorType::Related).widget_holder(),
|
||||
TextInput::new(context.network_interface.display_name(&node_id, context.selection_network_path))
|
||||
.tooltip("Name of the selected node")
|
||||
.on_update(move |text_input| {
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
alias: text_input.value.clone(),
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_holder(),
|
||||
Separator::new(SeparatorType::Related).widget_holder(),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
properties.extend(selected_nodes);
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
// TODO: Display properties for encapsulating node when no nodes are selected in a nested network
|
||||
@@ -2056,8 +2082,7 @@ impl NodeGraphMessageHandler {
|
||||
properties
|
||||
}
|
||||
// If one layer is selected, filter out all selected nodes that are not upstream of it. If there are no nodes left, show properties for the layer. Otherwise, show nothing.
|
||||
1 => {
|
||||
let layer = layers[0];
|
||||
[layer] => {
|
||||
let nodes_not_upstream_of_layer = nodes.into_iter().filter(|&selected_node_id| {
|
||||
!context
|
||||
.network_interface
|
||||
@@ -2234,7 +2259,7 @@ impl NodeGraphMessageHandler {
|
||||
let mut inputs = inputs.into_iter().map(|input| {
|
||||
input.map(|input| FrontendGraphInput {
|
||||
data_type: FrontendGraphDataType::displayed_type(&input.ty, &input.type_source),
|
||||
resolved_type: Some(format!("{:?} from {:?}", &input.ty, input.type_source)),
|
||||
resolved_type: Some(format!("{:?}", &input.ty)),
|
||||
valid_types: input.valid_types.iter().map(|ty| ty.to_string()).collect(),
|
||||
name: input.input_name.unwrap_or_else(|| input.ty.nested_type().to_string()),
|
||||
description: input.input_description.unwrap_or_default(),
|
||||
@@ -2258,7 +2283,7 @@ impl NodeGraphMessageHandler {
|
||||
data_type: frontend_data_type,
|
||||
name: "Output 1".to_string(),
|
||||
description: String::new(),
|
||||
resolved_type: primary_output_type.map(|(input, type_source)| format!("{input:?} from {type_source:?}")),
|
||||
resolved_type: primary_output_type.map(|(input, _)| format!("{input:?}")),
|
||||
connected_to,
|
||||
})
|
||||
} else {
|
||||
@@ -2292,7 +2317,7 @@ impl NodeGraphMessageHandler {
|
||||
data_type: frontend_data_type,
|
||||
name: output_name,
|
||||
description: String::new(),
|
||||
resolved_type: exposed_output.clone().map(|(input, type_source)| format!("{input:?} from {type_source:?}")),
|
||||
resolved_type: exposed_output.clone().map(|(input, _)| format!("{input:?}")),
|
||||
connected_to,
|
||||
});
|
||||
}
|
||||
@@ -2418,6 +2443,7 @@ impl NodeGraphMessageHandler {
|
||||
}
|
||||
});
|
||||
|
||||
let clippable = layer.can_be_clipped(network_interface.document_metadata());
|
||||
let data = LayerPanelEntry {
|
||||
id: node_id,
|
||||
alias: network_interface.display_name(&node_id, &[]),
|
||||
@@ -2437,6 +2463,8 @@ impl NodeGraphMessageHandler {
|
||||
selected: selected_layers.contains(&node_id),
|
||||
ancestor_of_selected: ancestors_of_selected.contains(&node_id),
|
||||
descendant_of_selected: descendants_of_selected.contains(&node_id),
|
||||
clipped: get_clip_mode(layer, network_interface).unwrap_or(false) && clippable,
|
||||
clippable,
|
||||
};
|
||||
responses.add(FrontendMessage::UpdateDocumentLayerDetails { data });
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -263,7 +263,7 @@
|
||||
|
||||
// // let transform = context
|
||||
// // .executor
|
||||
// // .introspect_node_in_network(context.network, &imaginate_node, |network| network.inputs.first().copied(), |frame: &ImageFrame<Color>| frame.transform)
|
||||
// // .introspect_node_in_network(context.network, &imaginate_node, |network| network.inputs.first().copied(), |frame: &RasterData<Color>| frame.transform)
|
||||
// // .unwrap_or_default();
|
||||
// let image_size = context
|
||||
// .executor
|
||||
@@ -283,7 +283,7 @@
|
||||
// .map(|(node_id, _)| node_id)
|
||||
// .copied()
|
||||
// },
|
||||
// |frame: &IORecord<(), ImageFrame<Color>>| (frame.output.image.width, frame.output.image.height),
|
||||
// |frame: &IORecord<(), RasterData<Color>>| (frame.output.image.width, frame.output.image.height),
|
||||
// )
|
||||
// .unwrap_or_default();
|
||||
|
||||
@@ -339,6 +339,7 @@
|
||||
// resolution_index,
|
||||
// ))
|
||||
// .on_commit(commit_value)
|
||||
// .for_label(checkbox_id.clone())
|
||||
// .widget_holder(),
|
||||
// Separator::new(SeparatorType::Related).widget_holder(),
|
||||
// NumberInput::new(Some(vec2.x))
|
||||
@@ -438,7 +439,7 @@
|
||||
// LayoutGroup::Row { widgets }.with_tooltip("A negative text prompt can be used to list things like objects or colors to avoid")
|
||||
// };
|
||||
// let base_image = {
|
||||
// let widgets = bool_widget(document_node, node_id, base_img_index, "Adapt Input Image", CheckboxInput::default(), true);
|
||||
// let widgets = bool_widget(document_node, node_id, base_img_index, "Adapt Input Image", CheckboxInput::default().for_label(checkbox_id.clone()), true);
|
||||
// LayoutGroup::Row { widgets }.with_tooltip("Generate an image based upon the bitmap data plugged into this node")
|
||||
// };
|
||||
// let image_creativity = {
|
||||
@@ -529,7 +530,7 @@
|
||||
// // }
|
||||
|
||||
// let improve_faces = {
|
||||
// let widgets = bool_widget(document_node, node_id, faces_index, "Improve Faces", CheckboxInput::default(), true);
|
||||
// let widgets = bool_widget(document_node, node_id, faces_index, "Improve Faces", CheckboxInput::default().for_label(checkbox_id.clone()), true);
|
||||
// LayoutGroup::Row { widgets }.with_tooltip(
|
||||
// "Postprocess human (or human-like) faces to look subtly less distorted.\n\
|
||||
// \n\
|
||||
@@ -537,7 +538,7 @@
|
||||
// )
|
||||
// };
|
||||
// let tiling = {
|
||||
// let widgets = bool_widget(document_node, node_id, tiling_index, "Tiling", CheckboxInput::default(), true);
|
||||
// let widgets = bool_widget(document_node, node_id, tiling_index, "Tiling", CheckboxInput::default().for_label(checkbox_id.clone()), true);
|
||||
// LayoutGroup::Row { widgets }.with_tooltip("Generate the image so its edges loop seamlessly to make repeatable patterns or textures")
|
||||
// };
|
||||
// layout.extend_from_slice(&[improve_faces, tiling]);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector, TypeSource};
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_core::Type;
|
||||
use graphene_std::Type;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum FrontendGraphDataType {
|
||||
@@ -17,7 +17,7 @@ pub enum FrontendGraphDataType {
|
||||
impl FrontendGraphDataType {
|
||||
fn with_type(input: &Type) -> Self {
|
||||
match TaggedValue::from_type_or_none(input) {
|
||||
TaggedValue::Image(_) | TaggedValue::ImageFrame(_) => Self::Raster,
|
||||
TaggedValue::Image(_) | TaggedValue::RasterData(_) => Self::Raster,
|
||||
TaggedValue::Subpaths(_) | TaggedValue::VectorData(_) => Self::VectorData,
|
||||
TaggedValue::U32(_)
|
||||
| TaggedValue::U64(_)
|
||||
|
||||
@@ -3,8 +3,8 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayContex
|
||||
use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
|
||||
@@ -236,12 +236,24 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
TextLabel::new("Type").table_align(true).widget_holder(),
|
||||
Separator::new(SeparatorType::Unrelated).widget_holder(),
|
||||
RadioInput::new(vec![
|
||||
RadioEntryData::new("rectangular")
|
||||
.label("Rectangular")
|
||||
.on_update(update_val(grid, |grid, _| grid.grid_type = GridType::RECTANGULAR)),
|
||||
RadioEntryData::new("isometric")
|
||||
.label("Isometric")
|
||||
.on_update(update_val(grid, |grid, _| grid.grid_type = GridType::ISOMETRIC)),
|
||||
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
|
||||
if let GridType::Isometric { y_axis_spacing, angle_a, angle_b } = grid.grid_type {
|
||||
grid.isometric_y_spacing = y_axis_spacing;
|
||||
grid.isometric_angle_a = angle_a;
|
||||
grid.isometric_angle_b = angle_b;
|
||||
}
|
||||
grid.grid_type = GridType::Rectangular { spacing: grid.rectangular_spacing };
|
||||
})),
|
||||
RadioEntryData::new("isometric").label("Isometric").on_update(update_val(grid, |grid, _| {
|
||||
if let GridType::Rectangular { spacing } = grid.grid_type {
|
||||
grid.rectangular_spacing = spacing;
|
||||
}
|
||||
grid.grid_type = GridType::Isometric {
|
||||
y_axis_spacing: grid.isometric_y_spacing,
|
||||
angle_a: grid.isometric_angle_a,
|
||||
angle_b: grid.isometric_angle_b,
|
||||
};
|
||||
})),
|
||||
])
|
||||
.min_width(200)
|
||||
.selected_index(Some(match grid.grid_type {
|
||||
|
||||
@@ -2,10 +2,19 @@ use super::utility_types::{OverlayProvider, empty_provider};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, DocumentMessage, Overlays)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
pub enum OverlaysMessage {
|
||||
Draw,
|
||||
// Serde functionality isn't used but is required by the message system macros
|
||||
AddProvider(#[serde(skip, default = "empty_provider")] OverlayProvider),
|
||||
RemoveProvider(#[serde(skip, default = "empty_provider")] OverlayProvider),
|
||||
AddProvider(
|
||||
#[serde(skip, default = "empty_provider")]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
OverlayProvider,
|
||||
),
|
||||
RemoveProvider(
|
||||
#[serde(skip, default = "empty_provider")]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
OverlayProvider,
|
||||
),
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::utility_types::OverlayProvider;
|
||||
use super::utility_types::{OverlayProvider, OverlaysVisibilitySettings};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
pub struct OverlaysMessageData<'a> {
|
||||
pub overlays_visible: bool,
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub device_pixel_ratio: f64,
|
||||
}
|
||||
@@ -18,7 +18,7 @@ pub struct OverlaysMessageHandler {
|
||||
|
||||
impl MessageHandler<OverlaysMessage, OverlaysMessageData<'_>> for OverlaysMessageHandler {
|
||||
fn process_message(&mut self, message: OverlaysMessage, responses: &mut VecDeque<Message>, data: OverlaysMessageData) {
|
||||
let OverlaysMessageData { overlays_visible, ipp, .. } = data;
|
||||
let OverlaysMessageData { visibility_settings, ipp, .. } = data;
|
||||
|
||||
match message {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -50,24 +50,26 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageData<'_>> for OverlaysMessag
|
||||
context.clear_rect(0., 0., ipp.viewport_bounds.size().x, ipp.viewport_bounds.size().y);
|
||||
let _ = context.reset_transform();
|
||||
|
||||
if overlays_visible {
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays(OverlayContext {
|
||||
render_context: context.clone(),
|
||||
size: size.as_dvec2(),
|
||||
device_pixel_ratio,
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
}));
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(OverlayContext {
|
||||
render_context: context.clone(),
|
||||
size: size.as_dvec2(),
|
||||
device_pixel_ratio,
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
OverlaysMessage::Draw => {
|
||||
warn!("Cannot render overlays on non-Wasm targets.\n{responses:?} {overlays_visible} {ipp:?}",);
|
||||
warn!("Cannot render overlays on non-Wasm targets.\n{responses:?} {visibility_settings:?} {ipp:?}",);
|
||||
}
|
||||
OverlaysMessage::AddProvider(message) => {
|
||||
self.overlay_providers.insert(message);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::utility_types::{DrawHandles, OverlayContext};
|
||||
use crate::consts::HIDE_HANDLE_DISTANCE;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{DocumentMessageHandler, PreferencesMessageHandler};
|
||||
use bezier_rs::{Bezier, BezierHandles};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::vector::ManipulatorPointId;
|
||||
use graphene_std::vector::ManipulatorPointId;
|
||||
use graphene_std::vector::{PointId, SegmentId};
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
@@ -23,7 +24,7 @@ pub fn overlay_canvas_context() -> web_sys::CanvasRenderingContext2d {
|
||||
create_context().expect("Failed to get canvas context")
|
||||
}
|
||||
|
||||
pub fn selected_segments(document: &DocumentMessageHandler, shape_editor: &mut ShapeState) -> Vec<SegmentId> {
|
||||
pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor: &ShapeState) -> Vec<SegmentId> {
|
||||
let selected_points = shape_editor.selected_points();
|
||||
let selected_anchors = selected_points
|
||||
.filter_map(|point_id| if let ManipulatorPointId::Anchor(p) = point_id { Some(*p) } else { None })
|
||||
@@ -40,8 +41,8 @@ pub fn selected_segments(document: &DocumentMessageHandler, shape_editor: &mut S
|
||||
|
||||
// TODO: Currently if there are two duplicate layers, both of their segments get overlays
|
||||
// Adding segments which are are connected to selected anchors
|
||||
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
|
||||
let Some(vector_data) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
for layer in network_interface.selected_nodes().selected_layers(network_interface.document_metadata()) {
|
||||
let Some(vector_data) = network_interface.compute_modified_vector(layer) else { continue };
|
||||
|
||||
for (segment_id, _bezier, start, end) in vector_data.segment_bezier_iter() {
|
||||
if selected_anchors.contains(&start) || selected_anchors.contains(&end) {
|
||||
@@ -77,7 +78,7 @@ fn overlay_bezier_handles(bezier: Bezier, segment_id: SegmentId, transform: DAff
|
||||
}
|
||||
}
|
||||
|
||||
pub fn overlay_bezier_handle_specific_point(
|
||||
fn overlay_bezier_handle_specific_point(
|
||||
bezier: Bezier,
|
||||
segment_id: SegmentId,
|
||||
(start, end): (PointId, PointId),
|
||||
@@ -112,59 +113,73 @@ pub fn overlay_bezier_handle_specific_point(
|
||||
}
|
||||
|
||||
pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandles, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) {
|
||||
let display_path = overlay_context.visibility_settings.path();
|
||||
let display_handles = overlay_context.visibility_settings.handles();
|
||||
let display_anchors = overlay_context.visibility_settings.anchors();
|
||||
|
||||
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
|
||||
let Some(vector_data) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
overlay_context.outline_vector(&vector_data, transform);
|
||||
if display_path {
|
||||
overlay_context.outline_vector(&vector_data, transform);
|
||||
}
|
||||
|
||||
let selected = shape_editor.selected_shape_state.get(&layer);
|
||||
let is_selected = |point: ManipulatorPointId| selected.is_some_and(|selected| selected.is_selected(point));
|
||||
|
||||
let opposite_handles_data: Vec<(PointId, SegmentId)> = shape_editor.selected_points().filter_map(|point_id| vector_data.adjacent_segment(point_id)).collect();
|
||||
if display_handles {
|
||||
let opposite_handles_data: Vec<(PointId, SegmentId)> = shape_editor.selected_points().filter_map(|point_id| vector_data.adjacent_segment(point_id)).collect();
|
||||
|
||||
match draw_handles {
|
||||
DrawHandles::All => {
|
||||
vector_data.segment_bezier_iter().for_each(|(segment_id, bezier, _start, _end)| {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
});
|
||||
}
|
||||
DrawHandles::SelectedAnchors(ref selected_segments) => {
|
||||
vector_data
|
||||
.segment_bezier_iter()
|
||||
.filter(|(segment_id, ..)| selected_segments.contains(segment_id))
|
||||
.for_each(|(segment_id, bezier, _start, _end)| {
|
||||
match draw_handles {
|
||||
DrawHandles::All => {
|
||||
vector_data.segment_bezier_iter().for_each(|(segment_id, bezier, _start, _end)| {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
});
|
||||
}
|
||||
DrawHandles::SelectedAnchors(ref selected_segments) => {
|
||||
vector_data
|
||||
.segment_bezier_iter()
|
||||
.filter(|(segment_id, ..)| selected_segments.contains(segment_id))
|
||||
.for_each(|(segment_id, bezier, _start, _end)| {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
});
|
||||
|
||||
for (segment_id, bezier, start, end) in vector_data.segment_bezier_iter() {
|
||||
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) {
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
|
||||
for (segment_id, bezier, start, end) in vector_data.segment_bezier_iter() {
|
||||
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) {
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
DrawHandles::FrontierHandles(ref segment_endpoints) => {
|
||||
vector_data
|
||||
.segment_bezier_iter()
|
||||
.filter(|(segment_id, ..)| segment_endpoints.contains_key(segment_id))
|
||||
.for_each(|(segment_id, bezier, start, end)| {
|
||||
if segment_endpoints.get(&segment_id).unwrap().len() == 1 {
|
||||
let point_to_render = segment_endpoints.get(&segment_id).unwrap()[0];
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
|
||||
} else {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
}
|
||||
});
|
||||
}
|
||||
DrawHandles::None => {}
|
||||
}
|
||||
DrawHandles::FrontierHandles(ref segment_endpoints) => {
|
||||
vector_data
|
||||
.segment_bezier_iter()
|
||||
.filter(|(segment_id, ..)| segment_endpoints.contains_key(segment_id))
|
||||
.for_each(|(segment_id, bezier, start, end)| {
|
||||
if segment_endpoints.get(&segment_id).unwrap().len() == 1 {
|
||||
let point_to_render = segment_endpoints.get(&segment_id).unwrap()[0];
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
|
||||
} else {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
}
|
||||
});
|
||||
}
|
||||
DrawHandles::None => {}
|
||||
}
|
||||
|
||||
for (&id, &position) in vector_data.point_domain.ids().iter().zip(vector_data.point_domain.positions()) {
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None);
|
||||
if display_anchors {
|
||||
for (&id, &position) in vector_data.point_domain.ids().iter().zip(vector_data.point_domain.positions()) {
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext, preferences: &PreferencesMessageHandler) {
|
||||
if !overlay_context.visibility_settings.anchors() {
|
||||
return;
|
||||
}
|
||||
|
||||
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
|
||||
let Some(vector_data) = document.network_interface.compute_modified_vector(layer) else {
|
||||
continue;
|
||||
|
||||
@@ -8,10 +8,13 @@ use bezier_rs::{Bezier, Subpath};
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::ClickTargetType;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorData};
|
||||
use std::collections::HashMap;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
use web_sys::{OffscreenCanvas, OffscreenCanvasRenderingContext2d};
|
||||
|
||||
pub type OverlayProvider = fn(OverlayContext) -> Message;
|
||||
|
||||
@@ -19,6 +22,107 @@ pub fn empty_provider() -> OverlayProvider {
|
||||
|_| Message::NoOp
|
||||
}
|
||||
|
||||
// Types of overlays used by DocumentMessage to enable/disable select group of overlays in the frontend
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum OverlaysType {
|
||||
ArtboardName,
|
||||
CompassRose,
|
||||
QuickMeasurement,
|
||||
TransformMeasurement,
|
||||
TransformCage,
|
||||
HoverOutline,
|
||||
SelectionOutline,
|
||||
Pivot,
|
||||
Path,
|
||||
Anchors,
|
||||
Handles,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct OverlaysVisibilitySettings {
|
||||
pub all: bool,
|
||||
pub artboard_name: bool,
|
||||
pub compass_rose: bool,
|
||||
pub quick_measurement: bool,
|
||||
pub transform_measurement: bool,
|
||||
pub transform_cage: bool,
|
||||
pub hover_outline: bool,
|
||||
pub selection_outline: bool,
|
||||
pub pivot: bool,
|
||||
pub path: bool,
|
||||
pub anchors: bool,
|
||||
pub handles: bool,
|
||||
}
|
||||
|
||||
impl Default for OverlaysVisibilitySettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
all: true,
|
||||
artboard_name: true,
|
||||
compass_rose: true,
|
||||
quick_measurement: true,
|
||||
transform_measurement: true,
|
||||
transform_cage: true,
|
||||
hover_outline: true,
|
||||
selection_outline: true,
|
||||
pivot: true,
|
||||
path: true,
|
||||
anchors: true,
|
||||
handles: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OverlaysVisibilitySettings {
|
||||
pub fn all(&self) -> bool {
|
||||
self.all
|
||||
}
|
||||
|
||||
pub fn artboard_name(&self) -> bool {
|
||||
self.all && self.artboard_name
|
||||
}
|
||||
|
||||
pub fn compass_rose(&self) -> bool {
|
||||
self.all && self.compass_rose
|
||||
}
|
||||
|
||||
pub fn quick_measurement(&self) -> bool {
|
||||
self.all && self.quick_measurement
|
||||
}
|
||||
|
||||
pub fn transform_measurement(&self) -> bool {
|
||||
self.all && self.transform_measurement
|
||||
}
|
||||
|
||||
pub fn transform_cage(&self) -> bool {
|
||||
self.all && self.transform_cage
|
||||
}
|
||||
|
||||
pub fn hover_outline(&self) -> bool {
|
||||
self.all && self.hover_outline
|
||||
}
|
||||
|
||||
pub fn selection_outline(&self) -> bool {
|
||||
self.all && self.selection_outline
|
||||
}
|
||||
|
||||
pub fn pivot(&self) -> bool {
|
||||
self.all && self.pivot
|
||||
}
|
||||
|
||||
pub fn path(&self) -> bool {
|
||||
self.all && self.path
|
||||
}
|
||||
|
||||
pub fn anchors(&self) -> bool {
|
||||
self.all && self.anchors
|
||||
}
|
||||
|
||||
pub fn handles(&self) -> bool {
|
||||
self.all && self.anchors && self.handles
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct OverlayContext {
|
||||
// Serde functionality isn't used but is required by the message system macros
|
||||
@@ -29,6 +133,7 @@ pub struct OverlayContext {
|
||||
// The device pixel ratio is a property provided by the browser window and is the CSS pixel size divided by the physical monitor's pixel size.
|
||||
// It allows better pixel density of visualizations on high-DPI displays where the OS display scaling is not 100%, or where the browser is zoomed.
|
||||
pub device_pixel_ratio: f64,
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
// Message hashing isn't used but is required by the message system macros
|
||||
impl core::hash::Hash for OverlayContext {
|
||||
@@ -36,8 +141,8 @@ impl core::hash::Hash for OverlayContext {
|
||||
}
|
||||
|
||||
impl OverlayContext {
|
||||
pub fn quad(&mut self, quad: Quad, color_fill: Option<&str>) {
|
||||
self.dashed_polygon(&quad.0, color_fill, None, None, None);
|
||||
pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
|
||||
self.dashed_polygon(&quad.0, stroke_color, color_fill, None, None, None);
|
||||
}
|
||||
|
||||
pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
@@ -64,15 +169,15 @@ impl OverlayContext {
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
pub fn dashed_quad(&mut self, quad: Quad, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
self.dashed_polygon(&quad.0, color_fill, dash_width, dash_gap_width, dash_offset);
|
||||
pub fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
self.dashed_polygon(&quad.0, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
|
||||
}
|
||||
|
||||
pub fn polygon(&mut self, polygon: &[DVec2], color_fill: Option<&str>) {
|
||||
self.dashed_polygon(polygon, color_fill, None, None, None);
|
||||
pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
|
||||
self.dashed_polygon(polygon, stroke_color, color_fill, None, None, None);
|
||||
}
|
||||
|
||||
pub fn dashed_polygon(&mut self, polygon: &[DVec2], color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
pub fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
if polygon.len() < 2 {
|
||||
return;
|
||||
}
|
||||
@@ -110,7 +215,8 @@ impl OverlayContext {
|
||||
self.render_context.fill();
|
||||
}
|
||||
|
||||
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
|
||||
let stroke_color = stroke_color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
self.render_context.set_stroke_style_str(stroke_color);
|
||||
self.render_context.stroke();
|
||||
|
||||
// Reset the dash pattern back to solid
|
||||
@@ -308,13 +414,10 @@ impl OverlayContext {
|
||||
}
|
||||
|
||||
pub fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
|
||||
let color_line = COLOR_OVERLAY_BLUE;
|
||||
|
||||
let end_point1 = pivot + radius * DVec2::from_angle(angle + offset_angle);
|
||||
let end_point2 = pivot + radius * DVec2::from_angle(offset_angle);
|
||||
self.line(pivot, end_point1, Some(color_line), None);
|
||||
self.line(pivot, end_point2, Some(color_line), None);
|
||||
|
||||
self.line(pivot, end_point1, None, None);
|
||||
self.dashed_line(pivot, end_point2, None, None, Some(2.), Some(2.), Some(0.5));
|
||||
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
|
||||
}
|
||||
|
||||
@@ -447,6 +550,7 @@ impl OverlayContext {
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
/// Used by the Pen and Path tools to outline the path of the shape.
|
||||
pub fn outline_vector(&mut self, vector_data: &VectorData, transform: DAffine2) {
|
||||
self.start_dpi_aware_transform();
|
||||
|
||||
@@ -465,6 +569,7 @@ impl OverlayContext {
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
/// Used by the Pen tool in order to show how the bezier curve would look like.
|
||||
pub fn outline_bezier(&mut self, bezier: Bezier, transform: DAffine2) {
|
||||
self.start_dpi_aware_transform();
|
||||
|
||||
@@ -493,7 +598,7 @@ impl OverlayContext {
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
pub fn outline(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
|
||||
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
|
||||
self.start_dpi_aware_transform();
|
||||
|
||||
self.render_context.begin_path();
|
||||
@@ -540,12 +645,77 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
|
||||
self.render_context.stroke();
|
||||
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
/// Used by the Select tool to outline a path or a free point when selected or hovered.
|
||||
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
|
||||
let mut subpaths: Vec<bezier_rs::Subpath<PointId>> = vec![];
|
||||
|
||||
target_types.for_each(|target_type| match target_type.borrow() {
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
|
||||
}
|
||||
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
|
||||
});
|
||||
|
||||
if !subpaths.is_empty() {
|
||||
self.push_path(subpaths.iter(), transform);
|
||||
|
||||
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
self.render_context.set_stroke_style_str(color);
|
||||
self.render_context.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills the area inside the path. Assumes `color` is in gamma space.
|
||||
/// Used by the Pen tool to show the path being closed.
|
||||
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
self.push_path(subpaths, transform);
|
||||
|
||||
self.render_context.set_fill_style_str(color);
|
||||
self.render_context.fill();
|
||||
}
|
||||
|
||||
/// Fills the area inside the path with a pattern. Assumes `color` is in gamma space.
|
||||
/// Used by the fill tool to show the area to be filled.
|
||||
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &Color) {
|
||||
const PATTERN_WIDTH: usize = 4;
|
||||
const PATTERN_HEIGHT: usize = 4;
|
||||
|
||||
let pattern_canvas = OffscreenCanvas::new(PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
|
||||
let pattern_context: OffscreenCanvasRenderingContext2d = pattern_canvas
|
||||
.get_context("2d")
|
||||
.ok()
|
||||
.flatten()
|
||||
.expect("Failed to get canvas context")
|
||||
.dyn_into()
|
||||
.expect("Context should be a canvas 2d context");
|
||||
|
||||
// 4x4 pixels, 4 components (RGBA) per pixel
|
||||
let mut data = [0_u8; 4 * PATTERN_WIDTH * PATTERN_HEIGHT];
|
||||
|
||||
// ┌▄▄┬──┬──┬──┐
|
||||
// ├▀▀┼──┼──┼──┤
|
||||
// ├──┼──┼▄▄┼──┤
|
||||
// ├──┼──┼▀▀┼──┤
|
||||
// └──┴──┴──┴──┘
|
||||
let pixels = [(0, 0), (2, 2)];
|
||||
for &(x, y) in &pixels {
|
||||
let index = (x + y * PATTERN_WIDTH as usize) * 4;
|
||||
data[index..index + 4].copy_from_slice(&color.to_rgba8_srgb());
|
||||
}
|
||||
|
||||
let image_data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&mut data), PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
|
||||
pattern_context.put_image_data(&image_data, 0., 0.).unwrap();
|
||||
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
|
||||
|
||||
self.push_path(subpaths, transform);
|
||||
|
||||
self.render_context.set_fill_style_canvas_pattern(&pattern);
|
||||
self.render_context.fill();
|
||||
}
|
||||
|
||||
pub fn get_width(&self, text: &str) -> f64 {
|
||||
self.render_context.measure_text(text).expect("Failed to measure text dimensions").width()
|
||||
}
|
||||
@@ -576,7 +746,7 @@ impl OverlayContext {
|
||||
);
|
||||
}
|
||||
|
||||
self.render_context.set_font("12px Source Sans Pro, Arial, sans-serif");
|
||||
self.render_context.set_font(r#"12px "Source Sans Pro", Arial, sans-serif"#);
|
||||
self.render_context.set_fill_style_str(font_color);
|
||||
self.render_context.fill_text(text, 0., 0.).expect("Failed to draw the text at the calculated position");
|
||||
self.render_context.reset_transform().expect("Failed to reset the render context transform");
|
||||
|
||||
@@ -3,9 +3,8 @@ use crate::messages::portfolio::document::graph_operation::transform_utils;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::renderer::ClickTarget;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::transform::Footprint;
|
||||
use graphene_std::renderer::{ClickTarget, ClickTargetType, Quad};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{PointId, VectorData};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroU64;
|
||||
@@ -134,7 +133,10 @@ impl DocumentMetadata {
|
||||
pub fn bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.click_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| click_target.subpath().bounding_box_with_transform(transform))
|
||||
.filter_map(|click_target| match click_target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => subpath.bounding_box_with_transform(transform),
|
||||
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
|
||||
})
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
@@ -177,7 +179,16 @@ impl DocumentMetadata {
|
||||
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &bezier_rs::Subpath<PointId>> {
|
||||
static EMPTY: Vec<ClickTarget> = Vec::new();
|
||||
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
|
||||
click_targets.iter().map(ClickTarget::subpath)
|
||||
click_targets.iter().filter_map(|target| match target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => Some(subpath),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
|
||||
static EMPTY: Vec<ClickTarget> = Vec::new();
|
||||
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
|
||||
click_targets.iter().map(|target| target.target_type())
|
||||
}
|
||||
|
||||
pub fn is_clip(&self, node: NodeId) -> bool {
|
||||
@@ -261,13 +272,29 @@ impl LayerNodeIdentifier {
|
||||
metadata.get_relations(self).and_then(|relations| relations.last_child)
|
||||
}
|
||||
|
||||
/// Does the layer have children? If so, then it is a folder
|
||||
/// Does the layer have children? If so, then it is a folder.
|
||||
pub fn has_children(self, metadata: &DocumentMetadata) -> bool {
|
||||
self.first_child(metadata).is_some()
|
||||
}
|
||||
|
||||
/// Is the layer a child of the given layer?
|
||||
pub fn is_child_of(self, metadata: &DocumentMetadata, parent: &LayerNodeIdentifier) -> bool {
|
||||
parent.children(metadata).any(|child| child == self)
|
||||
}
|
||||
|
||||
/// Is the layer an ancestor of the given layer?
|
||||
pub fn is_ancestor_of(self, metadata: &DocumentMetadata, child: &LayerNodeIdentifier) -> bool {
|
||||
child.ancestors(metadata).any(|ancestor| ancestor == self)
|
||||
}
|
||||
|
||||
/// Is the layer last child of parent group? Used for clipping
|
||||
pub fn can_be_clipped(self, metadata: &DocumentMetadata) -> bool {
|
||||
self.parent(metadata)
|
||||
.map_or(false, |layer| layer.last_child(metadata).expect("Parent accessed via child should have children") != self)
|
||||
}
|
||||
|
||||
/// Iterator over all direct children (excluding self and recursive children)
|
||||
pub fn children(self, metadata: &DocumentMetadata) -> AxisIter {
|
||||
pub fn children(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
|
||||
AxisIter {
|
||||
layer_node: self.first_child(metadata),
|
||||
next_node: Self::next_sibling,
|
||||
@@ -275,7 +302,7 @@ impl LayerNodeIdentifier {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn downstream_siblings(self, metadata: &DocumentMetadata) -> AxisIter {
|
||||
pub fn downstream_siblings(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
|
||||
AxisIter {
|
||||
layer_node: Some(self),
|
||||
next_node: Self::previous_sibling,
|
||||
@@ -284,7 +311,7 @@ impl LayerNodeIdentifier {
|
||||
}
|
||||
|
||||
/// All ancestors of this layer, including self, going to the document root
|
||||
pub fn ancestors(self, metadata: &DocumentMetadata) -> AxisIter {
|
||||
pub fn ancestors(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
|
||||
AxisIter {
|
||||
layer_node: Some(self),
|
||||
next_node: Self::parent,
|
||||
@@ -293,7 +320,7 @@ impl LayerNodeIdentifier {
|
||||
}
|
||||
|
||||
/// Iterator through all the last children, starting from self
|
||||
pub fn last_children(self, metadata: &DocumentMetadata) -> AxisIter {
|
||||
pub fn last_children(self, metadata: &DocumentMetadata) -> AxisIter<'_> {
|
||||
AxisIter {
|
||||
layer_node: Some(self),
|
||||
next_node: Self::last_child,
|
||||
@@ -302,7 +329,7 @@ impl LayerNodeIdentifier {
|
||||
}
|
||||
|
||||
/// Iterator through all descendants, including recursive children (not including self)
|
||||
pub fn descendants(self, metadata: &DocumentMetadata) -> DescendantsIter {
|
||||
pub fn descendants(self, metadata: &DocumentMetadata) -> DescendantsIter<'_> {
|
||||
DescendantsIter {
|
||||
front: self.first_child(metadata),
|
||||
back: self.last_child(metadata).and_then(|child| child.last_children(metadata).last()),
|
||||
@@ -495,49 +522,53 @@ pub struct NodeRelations {
|
||||
// Helper functions
|
||||
// ================
|
||||
|
||||
#[test]
|
||||
fn test_tree() {
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
let root = LayerNodeIdentifier::ROOT_PARENT;
|
||||
let metadata = &mut metadata;
|
||||
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(3)));
|
||||
assert_eq!(root.children(metadata).collect::<Vec<_>>(), vec![LayerNodeIdentifier::new_unchecked(NodeId(3))]);
|
||||
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(6)));
|
||||
assert_eq!(root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
|
||||
assert_eq!(root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(4)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(2)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(5)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(9)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(8)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(7)));
|
||||
root.push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(1)));
|
||||
assert_eq!(
|
||||
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(7), NodeId(8), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
|
||||
vec![NodeId(9), NodeId(8), NodeId(7), NodeId(6), NodeId(5), NodeId(4), NodeId(3), NodeId(2), NodeId(1)]
|
||||
);
|
||||
assert!(root.children(metadata).all(|child| child.parent(metadata) == Some(root)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).delete(metadata);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(1)).delete(metadata);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(9)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(10)));
|
||||
assert_eq!(
|
||||
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9), NodeId(10)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
|
||||
vec![NodeId(10), NodeId(9), NodeId(5), NodeId(4), NodeId(3), NodeId(2)]
|
||||
);
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_tree() {
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
let root = LayerNodeIdentifier::ROOT_PARENT;
|
||||
let metadata = &mut metadata;
|
||||
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(3)));
|
||||
assert_eq!(root.children(metadata).collect::<Vec<_>>(), vec![LayerNodeIdentifier::new_unchecked(NodeId(3))]);
|
||||
root.push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(6)));
|
||||
assert_eq!(root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
|
||||
assert_eq!(root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(), vec![NodeId(3), NodeId(6)]);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(4)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(3)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(2)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_before(metadata, LayerNodeIdentifier::new_unchecked(NodeId(5)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).add_after(metadata, LayerNodeIdentifier::new_unchecked(NodeId(9)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(8)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(7)));
|
||||
root.push_front_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(1)));
|
||||
assert_eq!(
|
||||
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(6), NodeId(7), NodeId(8), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
|
||||
vec![NodeId(9), NodeId(8), NodeId(7), NodeId(6), NodeId(5), NodeId(4), NodeId(3), NodeId(2), NodeId(1)]
|
||||
);
|
||||
assert!(root.children(metadata).all(|child| child.parent(metadata) == Some(root)));
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(6)).delete(metadata);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(1)).delete(metadata);
|
||||
LayerNodeIdentifier::new_unchecked(NodeId(9)).push_child(metadata, LayerNodeIdentifier::new_unchecked(NodeId(10)));
|
||||
assert_eq!(
|
||||
root.children(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).collect::<Vec<_>>(),
|
||||
vec![NodeId(2), NodeId(3), NodeId(4), NodeId(5), NodeId(9), NodeId(10)]
|
||||
);
|
||||
assert_eq!(
|
||||
root.descendants(metadata).map(LayerNodeIdentifier::to_node).rev().collect::<Vec<_>>(),
|
||||
vec![NodeId(10), NodeId(9), NodeId(5), NodeId(4), NodeId(3), NodeId(2)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_std::raster::color::Color;
|
||||
use thiserror::Error;
|
||||
|
||||
/// The error type used by the Graphite editor.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::consts::COLOR_OVERLAY_GRAY;
|
||||
use glam::DVec2;
|
||||
use graphene_core::raster::Color;
|
||||
use graphene_std::raster::Color;
|
||||
use std::fmt;
|
||||
|
||||
#[repr(transparent)]
|
||||
@@ -176,17 +176,11 @@ pub enum GridType {
|
||||
|
||||
impl Default for GridType {
|
||||
fn default() -> Self {
|
||||
Self::RECTANGULAR
|
||||
Self::Rectangular { spacing: DVec2::ONE }
|
||||
}
|
||||
}
|
||||
|
||||
impl GridType {
|
||||
pub const RECTANGULAR: Self = GridType::Rectangular { spacing: DVec2::ONE };
|
||||
pub const ISOMETRIC: Self = GridType::Isometric {
|
||||
y_axis_spacing: 1.,
|
||||
angle_a: 30.,
|
||||
angle_b: 30.,
|
||||
};
|
||||
pub fn rectangular_spacing(&mut self) -> Option<&mut DVec2> {
|
||||
match self {
|
||||
Self::Rectangular { spacing } => Some(spacing),
|
||||
@@ -218,6 +212,10 @@ impl GridType {
|
||||
pub struct GridSnapping {
|
||||
pub origin: DVec2,
|
||||
pub grid_type: GridType,
|
||||
pub rectangular_spacing: DVec2,
|
||||
pub isometric_y_spacing: f64,
|
||||
pub isometric_angle_a: f64,
|
||||
pub isometric_angle_b: f64,
|
||||
pub grid_color: Color,
|
||||
pub dot_display: bool,
|
||||
}
|
||||
@@ -227,6 +225,10 @@ impl Default for GridSnapping {
|
||||
Self {
|
||||
origin: DVec2::ZERO,
|
||||
grid_type: Default::default(),
|
||||
rectangular_spacing: DVec2::ONE,
|
||||
isometric_y_spacing: 1.,
|
||||
isometric_angle_a: 30.,
|
||||
isometric_angle_b: 30.,
|
||||
grid_color: Color::from_rgb_str(COLOR_OVERLAY_GRAY.strip_prefix('#').unwrap()).unwrap(),
|
||||
dot_display: false,
|
||||
}
|
||||
@@ -404,8 +406,7 @@ pub const SNAP_FUNCTIONS_FOR_BOUNDING_BOXES: [(&str, GetSnapState, &str); 5] = [
|
||||
(
|
||||
"Distribute Evenly",
|
||||
(|snapping_state| &mut snapping_state.bounding_box.distribute_evenly) as GetSnapState,
|
||||
// TODO: Fix the bug/limitation that requires 'Center Points' and 'Corner Points' to be enabled
|
||||
"Snaps to a consistent distance offset established by the bounding boxes of nearby layers\n(due to a bug, 'Center Points' and 'Corner Points' must be enabled)",
|
||||
"Snaps to a consistent distance offset established by the bounding boxes of nearby layers",
|
||||
),
|
||||
];
|
||||
pub const SNAP_FUNCTIONS_FOR_PATHS: [(&str, GetSnapState, &str); 7] = [
|
||||
@@ -648,11 +649,18 @@ pub struct PTZ {
|
||||
tilt: f64,
|
||||
/// Scale factor.
|
||||
zoom: f64,
|
||||
/// Flipped status.
|
||||
pub flip: bool,
|
||||
}
|
||||
|
||||
impl Default for PTZ {
|
||||
fn default() -> Self {
|
||||
Self { pan: DVec2::ZERO, tilt: 0., zoom: 1. }
|
||||
Self {
|
||||
pan: DVec2::ZERO,
|
||||
tilt: 0.,
|
||||
zoom: 1.,
|
||||
flip: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::renderer::{ClickTarget, Quad};
|
||||
use graphene_std::renderer::{ClickTarget, ClickTargetType, Quad};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{PointId, VectorData, VectorModificationType};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypes;
|
||||
@@ -485,7 +485,7 @@ impl NodeNetworkInterface {
|
||||
InputConnector::Export(export_index) => {
|
||||
let Some((encapsulating_node_id, encapsulating_node_id_path)) = network_path.split_last() else {
|
||||
// The outermost network export defaults to an ArtboardGroupTable.
|
||||
return Some((concrete!(graphene_core::ArtboardGroupTable), TypeSource::OuterMostExportDefault));
|
||||
return Some((concrete!(graphene_std::ArtboardGroupTable), TypeSource::OuterMostExportDefault));
|
||||
};
|
||||
|
||||
let output_type = self.output_types(encapsulating_node_id, encapsulating_node_id_path).into_iter().nth(export_index).flatten();
|
||||
@@ -816,7 +816,7 @@ impl NodeNetworkInterface {
|
||||
data_type,
|
||||
name: import_name,
|
||||
description: String::new(),
|
||||
resolved_type: Some(format!("{input_type:?} from {type_source:?}")),
|
||||
resolved_type: Some(format!("{input_type:?}")),
|
||||
connected_to,
|
||||
},
|
||||
click_target,
|
||||
@@ -901,7 +901,7 @@ impl NodeNetworkInterface {
|
||||
data_type: frontend_data_type,
|
||||
name: export_name,
|
||||
description: String::new(),
|
||||
resolved_type: input_type.map(|(export_type, source)| format!("{export_type:?} from {source:?}")),
|
||||
resolved_type: input_type.map(|(export_type, _source)| format!("{export_type:?}")),
|
||||
valid_types: self.valid_input_types(&InputConnector::Export(*export_index), network_path).iter().map(|ty| ty.to_string()).collect(),
|
||||
connected_to,
|
||||
},
|
||||
@@ -1141,7 +1141,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn input_description<'a>(&'a self, node_id: NodeId, index: usize, network_path: &[NodeId]) -> Option<&'a str> {
|
||||
let Some(input_row) = self.input_properties_row(&node_id, index, network_path) else {
|
||||
log::error!("Could not get node_metadata in input_description");
|
||||
log::error!("Could not get input_row in input_description");
|
||||
return None;
|
||||
};
|
||||
let description = input_row.input_description.as_str();
|
||||
@@ -1160,9 +1160,16 @@ impl NodeNetworkInterface {
|
||||
.and_then(|node_metadata| node_metadata.persistent_metadata.input_properties.get(index))
|
||||
}
|
||||
|
||||
pub fn insert_input_properties_row(&mut self, node_id: &NodeId, index: usize, network_path: &[NodeId]) {
|
||||
let row = ("", "TODO").into();
|
||||
let _ = self
|
||||
.node_metadata_mut(node_id, network_path)
|
||||
.map(|node_metadata| node_metadata.persistent_metadata.input_properties.insert(index - 1, row));
|
||||
}
|
||||
|
||||
pub fn input_metadata(&self, node_id: &NodeId, index: usize, field: &str, network_path: &[NodeId]) -> Option<&Value> {
|
||||
let Some(input_row) = self.input_properties_row(node_id, index, network_path) else {
|
||||
log::error!("Could not get node_metadata in get_input_metadata");
|
||||
log::error!("Could not get input_row in get_input_metadata");
|
||||
return None;
|
||||
};
|
||||
input_row.input_data.get(field)
|
||||
@@ -2120,7 +2127,7 @@ impl NodeNetworkInterface {
|
||||
let bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_right;
|
||||
let export_top_right: DVec2 = DVec2::new(viewport_top_right.x.max(bounding_box_top_right.x), viewport_top_right.y.min(bounding_box_top_right.y));
|
||||
let add_export_center = export_top_right + DVec2::new(0., network.exports.len() as f64 * 24.);
|
||||
let add_export = ClickTarget::new(
|
||||
let add_export = ClickTarget::new_with_subpath(
|
||||
Subpath::new_rounded_rect(add_export_center - DVec2::new(12., 12.), add_export_center + DVec2::new(12., 12.), [3.; 4]),
|
||||
0.,
|
||||
);
|
||||
@@ -2146,7 +2153,7 @@ impl NodeNetworkInterface {
|
||||
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
|
||||
let import_top_left = DVec2::new(viewport_top_left.x.min(bounding_box_top_left.x), viewport_top_left.y.min(bounding_box_top_left.y));
|
||||
let add_import_center = import_top_left + DVec2::new(0., self.number_of_displayed_imports(network_path) as f64 * 24.);
|
||||
let add_import = ClickTarget::new(
|
||||
let add_import = ClickTarget::new_with_subpath(
|
||||
Subpath::new_rounded_rect(add_import_center - DVec2::new(12., 12.), add_import_center + DVec2::new(12., 12.), [3.; 4]),
|
||||
0.,
|
||||
);
|
||||
@@ -2165,8 +2172,8 @@ impl NodeNetworkInterface {
|
||||
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
|
||||
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
|
||||
|
||||
let reorder_import = ClickTarget::new(Subpath::new_rect(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_import = ClickTarget::new(Subpath::new_rect(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
let reorder_import = ClickTarget::new_with_subpath(Subpath::new_rect(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rect(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
|
||||
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
|
||||
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
|
||||
@@ -2180,8 +2187,8 @@ impl NodeNetworkInterface {
|
||||
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
|
||||
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
|
||||
|
||||
let reorder_export = ClickTarget::new(Subpath::new_rect(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_export = ClickTarget::new(Subpath::new_rect(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
let reorder_export = ClickTarget::new_with_subpath(Subpath::new_rect(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rect(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
|
||||
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
|
||||
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
|
||||
@@ -2572,7 +2579,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
let radius = 3.;
|
||||
let subpath = bezier_rs::Subpath::new_rounded_rect(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new(subpath, 0.);
|
||||
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
@@ -2597,12 +2604,12 @@ impl NodeNetworkInterface {
|
||||
// Update visibility button click target
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, 24.);
|
||||
let subpath = Subpath::new_rounded_rect(DVec2::new(-12., -12.) + visibility_offset, DVec2::new(12., 12.) + visibility_offset, [3.; 4]);
|
||||
let visibility_click_target = ClickTarget::new(subpath, 0.);
|
||||
let visibility_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
// Update grip button click target, which is positioned to the left of the left most icon
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - (GRID_SIZE as f64) / 2., 24.);
|
||||
let subpath = Subpath::new_rounded_rect(DVec2::new(-8., -12.) + grip_offset_right_edge, DVec2::new(0., 12.) + grip_offset_right_edge, [0.; 4]);
|
||||
let grip_click_target = ClickTarget::new(subpath, 0.);
|
||||
let grip_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
// Create layer click target, which is contains the layer and the chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
@@ -2611,7 +2618,7 @@ impl NodeNetworkInterface {
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * crate::consts::GRID_SIZE) as f64, 0.);
|
||||
let radius = 10.;
|
||||
let subpath = bezier_rs::Subpath::new_rounded_rect(chain_top_left, node_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new(subpath, 0.);
|
||||
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
@@ -2804,20 +2811,29 @@ impl NodeNetworkInterface {
|
||||
if let (Some(import_export_click_targets), Some(node_click_targets)) = (self.import_export_ports(network_path).cloned(), self.node_click_targets(&node_id, network_path)) {
|
||||
let mut node_path = String::new();
|
||||
|
||||
let _ = node_click_targets.node_click_target.subpath().subpath_to_svg(&mut node_path, DAffine2::IDENTITY);
|
||||
if let ClickTargetType::Subpath(subpath) = node_click_targets.node_click_target.target_type() {
|
||||
let _ = subpath.subpath_to_svg(&mut node_path, DAffine2::IDENTITY);
|
||||
}
|
||||
all_node_click_targets.push((node_id, node_path));
|
||||
for port in node_click_targets.port_click_targets.click_targets().chain(import_export_click_targets.click_targets()) {
|
||||
let mut port_path = String::new();
|
||||
let _ = port.subpath().subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
port_click_targets.push(port_path);
|
||||
if let ClickTargetType::Subpath(subpath) = port.target_type() {
|
||||
let mut port_path = String::new();
|
||||
let _ = subpath.subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
port_click_targets.push(port_path);
|
||||
}
|
||||
}
|
||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||
let mut port_path = String::new();
|
||||
let _ = layer_metadata.visibility_click_target.subpath().subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
icon_click_targets.push(port_path);
|
||||
let mut port_path = String::new();
|
||||
let _ = layer_metadata.grip_click_target.subpath().subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
icon_click_targets.push(port_path);
|
||||
if let ClickTargetType::Subpath(subpath) = layer_metadata.visibility_click_target.target_type() {
|
||||
let mut port_path = String::new();
|
||||
let _ = subpath.subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
icon_click_targets.push(port_path);
|
||||
}
|
||||
|
||||
if let ClickTargetType::Subpath(subpath) = layer_metadata.grip_click_target.target_type() {
|
||||
let mut port_path = String::new();
|
||||
let _ = subpath.subpath_to_svg(&mut port_path, DAffine2::IDENTITY);
|
||||
icon_click_targets.push(port_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -2872,9 +2888,11 @@ impl NodeNetworkInterface {
|
||||
.chain(modify_import_export_click_targets.remove_imports_exports.click_targets())
|
||||
.chain(modify_import_export_click_targets.reorder_imports_exports.click_targets())
|
||||
{
|
||||
let mut remove_string = String::new();
|
||||
let _ = click_target.subpath().subpath_to_svg(&mut remove_string, DAffine2::IDENTITY);
|
||||
modify_import_export.push(remove_string);
|
||||
if let ClickTargetType::Subpath(subpath) = click_target.target_type() {
|
||||
let mut remove_string = String::new();
|
||||
let _ = subpath.subpath_to_svg(&mut remove_string, DAffine2::IDENTITY);
|
||||
modify_import_export.push(remove_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
FrontendClickTargets {
|
||||
@@ -3113,7 +3131,7 @@ impl NodeNetworkInterface {
|
||||
self.node_click_targets(node_id, network_path)
|
||||
.and_then(|transient_node_metadata| transient_node_metadata.node_click_target.bounding_box())
|
||||
})
|
||||
.reduce(graphene_core::renderer::Quad::combine_bounds)
|
||||
.reduce(graphene_std::renderer::Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Gets the bounding box in viewport coordinates for each node in the node graph
|
||||
@@ -3174,8 +3192,8 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata
|
||||
.click_targets
|
||||
.get(&layer)
|
||||
.map(|click| click.iter().map(ClickTarget::subpath))
|
||||
.map(|subpaths| VectorData::from_subpaths(subpaths, true))
|
||||
.map(|click| click.iter().map(ClickTarget::target_type))
|
||||
.map(|target_types| VectorData::from_target_types(target_types, true))
|
||||
}
|
||||
|
||||
/// Loads the structure of layer nodes from a node graph.
|
||||
@@ -3781,6 +3799,7 @@ impl NodeNetworkInterface {
|
||||
self.unload_stack_dependents(network_path);
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
|
||||
pub fn replace_implementation(&mut self, node_id: &NodeId, network_path: &[NodeId], implementation: DocumentNodeImplementation) {
|
||||
let Some(network) = self.network_mut(network_path) else {
|
||||
@@ -3804,6 +3823,15 @@ impl NodeNetworkInterface {
|
||||
node_metadata.persistent_metadata.network_metadata = metadata.network_metadata;
|
||||
}
|
||||
|
||||
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
|
||||
pub fn replace_reference_name(&mut self, node_id: &NodeId, network_path: &[NodeId], reference_name: String) {
|
||||
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
|
||||
log::error!("Could not get node metadata in replace_reference_name");
|
||||
return;
|
||||
};
|
||||
node_metadata.persistent_metadata.reference = Some(reference_name);
|
||||
}
|
||||
|
||||
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
|
||||
pub fn set_manual_compostion(&mut self, node_id: &NodeId, network_path: &[NodeId], manual_composition: Option<Type>) {
|
||||
let Some(network) = self.network_mut(network_path) else {
|
||||
@@ -4197,9 +4225,9 @@ impl NodeNetworkInterface {
|
||||
let Some(downstream_nodes) = outward_wires.get(¤t_node) else { continue };
|
||||
for downstream_node in downstream_nodes {
|
||||
if let InputConnector::Node { node_id: downstream_id, .. } = downstream_node {
|
||||
let downstream_node_output = OutputConnector::node(*downstream_id, 0);
|
||||
if !delete_nodes.contains(downstream_id) {
|
||||
stack.push(downstream_node_output);
|
||||
can_delete = false;
|
||||
break;
|
||||
}
|
||||
// Continue traversing over the downstream sibling, if the current node is a sibling to a node that will be deleted and it is a layer
|
||||
else {
|
||||
@@ -5883,7 +5911,7 @@ impl Ports {
|
||||
|
||||
fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_input_port(input_index, ClickTarget::new(subpath, 0.));
|
||||
self.insert_custom_input_port(input_index, ClickTarget::new_with_subpath(subpath, 0.));
|
||||
}
|
||||
|
||||
fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
@@ -5892,7 +5920,7 @@ impl Ports {
|
||||
|
||||
fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_output_port(output_index, ClickTarget::new(subpath, 0.));
|
||||
self.insert_custom_output_port(output_index, ClickTarget::new_with_subpath(subpath, 0.));
|
||||
}
|
||||
|
||||
fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
|
||||
@@ -55,6 +55,8 @@ pub struct LayerPanelEntry {
|
||||
pub ancestor_of_selected: bool,
|
||||
#[serde(rename = "descendantOfSelected")]
|
||||
pub descendant_of_selected: bool,
|
||||
pub clipped: bool,
|
||||
pub clippable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
|
||||
|
||||
@@ -8,9 +8,9 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::vector::ManipulatorPointId;
|
||||
use graphene_core::vector::VectorModificationType;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::ManipulatorPointId;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::{HandleId, PointId};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::f64::consts::PI;
|
||||
@@ -635,17 +635,17 @@ impl<'a> Selected<'a> {
|
||||
}
|
||||
|
||||
pub fn apply_transformation(&mut self, transformation: DAffine2, transform_operation: Option<TransformOperation>) {
|
||||
if !self.selected.is_empty() {
|
||||
// TODO: Cache the result of `shallowest_unique_layers` to avoid this heavy computation every frame of movement, see https://github.com/GraphiteEditor/Graphite/pull/481
|
||||
for layer in self.network_interface.shallowest_unique_layers(&[]) {
|
||||
match &mut self.original_transforms {
|
||||
OriginalTransforms::Layer(layer_transforms) => {
|
||||
Self::transform_layer(self.network_interface.document_metadata(), layer, layer_transforms.get(&layer), transformation, self.responses)
|
||||
}
|
||||
OriginalTransforms::Path(path_transforms) => {
|
||||
if let Some(initial_points) = path_transforms.get_mut(&layer) {
|
||||
Self::transform_path(self.network_interface.document_metadata(), layer, initial_points, transformation, self.responses, transform_operation)
|
||||
}
|
||||
if self.selected.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Cache the result of `shallowest_unique_layers` to avoid this heavy computation every frame of movement, see https://github.com/GraphiteEditor/Graphite/pull/481
|
||||
for layer in self.network_interface.shallowest_unique_layers(&[]) {
|
||||
match &mut self.original_transforms {
|
||||
OriginalTransforms::Layer(layer_transforms) => Self::transform_layer(self.network_interface.document_metadata(), layer, layer_transforms.get(&layer), transformation, self.responses),
|
||||
OriginalTransforms::Path(path_transforms) => {
|
||||
if let Some(initial_points) = path_transforms.get_mut(&layer) {
|
||||
Self::transform_path(self.network_interface.document_metadata(), layer, initial_points, transformation, self.responses, transform_operation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ use graphene_std::vector::misc::BooleanOperation;
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MenuBarMessageHandler {
|
||||
pub has_active_document: bool,
|
||||
pub canvas_tilted: bool,
|
||||
pub canvas_flipped: bool,
|
||||
pub rulers_visible: bool,
|
||||
pub node_graph_open: bool,
|
||||
pub has_selected_nodes: bool,
|
||||
@@ -414,16 +416,15 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
action: MenuBarEntry::no_action(),
|
||||
disabled: no_active_document || !has_selected_layers,
|
||||
children: MenuBarEntryChildren(vec![{
|
||||
let operations = BooleanOperation::list();
|
||||
let icons = BooleanOperation::icons();
|
||||
operations
|
||||
.into_iter()
|
||||
.zip(icons)
|
||||
.map(move |(operation, icon)| MenuBarEntry {
|
||||
label: operation.to_string(),
|
||||
icon: Some(icon.into()),
|
||||
let list = <BooleanOperation as graphene_std::registry::ChoiceTypeStatic>::list();
|
||||
list.into_iter()
|
||||
.map(|i| i.into_iter())
|
||||
.flatten()
|
||||
.map(move |(operation, info)| MenuBarEntry {
|
||||
label: info.label.to_string(),
|
||||
icon: info.icon.as_ref().map(|i| i.to_string()),
|
||||
action: MenuBarEntry::create_action(move |_| {
|
||||
let group_folder_type = GroupFolderType::BooleanOperation(operation);
|
||||
let group_folder_type = GroupFolderType::BooleanOperation(*operation);
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
}),
|
||||
disabled: no_active_document || !has_selected_layers,
|
||||
@@ -504,7 +505,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
icon: Some("TiltReset".into()),
|
||||
shortcut: action_keys!(NavigationMessageDiscriminant::CanvasTiltSet),
|
||||
action: MenuBarEntry::create_action(|_| NavigationMessage::CanvasTiltSet { angle_radians: 0.into() }.into()),
|
||||
disabled: no_active_document || node_graph_open,
|
||||
disabled: no_active_document || node_graph_open || !self.canvas_tilted,
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
],
|
||||
@@ -526,7 +527,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
MenuBarEntry {
|
||||
label: "Zoom to Fit Selection".into(),
|
||||
label: "Zoom to Selection".into(),
|
||||
icon: Some("FrameSelected".into()),
|
||||
shortcut: action_keys!(NavigationMessageDiscriminant::FitViewportToSelection),
|
||||
action: MenuBarEntry::create_action(|_| NavigationMessage::FitViewportToSelection.into()),
|
||||
@@ -534,7 +535,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
MenuBarEntry {
|
||||
label: "Zoom to Fit All".into(),
|
||||
label: "Zoom to Fit".into(),
|
||||
icon: Some("FrameAll".into()),
|
||||
shortcut: action_keys!(DocumentMessageDiscriminant::ZoomCanvasToFitAll),
|
||||
action: MenuBarEntry::create_action(|_| DocumentMessage::ZoomCanvasToFitAll.into()),
|
||||
@@ -558,6 +559,14 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
],
|
||||
vec![MenuBarEntry {
|
||||
label: "Flip".into(),
|
||||
icon: Some(if self.canvas_flipped { "CheckboxChecked" } else { "CheckboxUnchecked" }.into()),
|
||||
shortcut: action_keys!(NavigationMessageDiscriminant::CanvasFlip),
|
||||
action: MenuBarEntry::create_action(|_| NavigationMessage::CanvasFlip.into()),
|
||||
disabled: no_active_document || node_graph_open,
|
||||
..MenuBarEntry::default()
|
||||
}],
|
||||
vec![MenuBarEntry {
|
||||
label: "Rulers".into(),
|
||||
icon: Some(if self.rulers_visible { "CheckboxChecked" } else { "CheckboxUnchecked" }.into()),
|
||||
@@ -585,18 +594,29 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
action: MenuBarEntry::create_action(|_| DialogMessage::RequestAboutGraphiteDialog.into()),
|
||||
..MenuBarEntry::default()
|
||||
}],
|
||||
vec![MenuBarEntry {
|
||||
label: "User Manual".into(),
|
||||
icon: Some("UserManual".into()),
|
||||
action: MenuBarEntry::create_action(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://graphite.rs/learn/".into(),
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
..MenuBarEntry::default()
|
||||
}],
|
||||
vec![
|
||||
MenuBarEntry {
|
||||
label: "Donate to Graphite".into(),
|
||||
icon: Some("Heart".into()),
|
||||
action: MenuBarEntry::create_action(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://graphite.rs/donate/".into(),
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
MenuBarEntry {
|
||||
label: "User Manual".into(),
|
||||
icon: Some("UserManual".into()),
|
||||
action: MenuBarEntry::create_action(|_| {
|
||||
FrontendMessage::TriggerVisitLink {
|
||||
url: "https://graphite.rs/learn/".into(),
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
..MenuBarEntry::default()
|
||||
},
|
||||
MenuBarEntry {
|
||||
label: "Report a Bug".into(),
|
||||
icon: Some("Bug".into()),
|
||||
|
||||
@@ -3,9 +3,9 @@ use super::utility_types::PanelType;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::raster::Image;
|
||||
use graphene_core::text::Font;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::text::Font;
|
||||
|
||||
#[impl_message(Message, Portfolio)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -90,6 +90,9 @@ pub enum PortfolioMessage {
|
||||
PasteSerializedData {
|
||||
data: String,
|
||||
},
|
||||
CenterPastedLayers {
|
||||
layers: Vec<LayerNodeIdentifier>,
|
||||
},
|
||||
PasteImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::FrontendDocumentDetails;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageData;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::{Clipboard, CopyBufferEntry, INTERNAL_CLIPBOARD_COUNT};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
@@ -18,11 +19,12 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, ToolType};
|
||||
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
|
||||
use bezier_rs::Subpath;
|
||||
use glam::IVec2;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graphene_core::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, FillType, Gradient};
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, FillType, Gradient, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::{VectorData, VectorDataTable};
|
||||
use std::vec;
|
||||
|
||||
@@ -69,6 +71,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
// Sub-messages
|
||||
PortfolioMessage::MenuBar(message) => {
|
||||
self.menu_bar_message_handler.has_active_document = false;
|
||||
self.menu_bar_message_handler.canvas_tilted = false;
|
||||
self.menu_bar_message_handler.canvas_flipped = false;
|
||||
self.menu_bar_message_handler.rulers_visible = false;
|
||||
self.menu_bar_message_handler.node_graph_open = false;
|
||||
self.menu_bar_message_handler.has_selected_nodes = false;
|
||||
@@ -80,6 +84,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
|
||||
if let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get_mut(&document_id)) {
|
||||
self.menu_bar_message_handler.has_active_document = true;
|
||||
self.menu_bar_message_handler.canvas_tilted = document.document_ptz.tilt() != 0.;
|
||||
self.menu_bar_message_handler.canvas_flipped = document.document_ptz.flip;
|
||||
self.menu_bar_message_handler.rulers_visible = document.rulers_visible;
|
||||
self.menu_bar_message_handler.node_graph_open = document.is_graph_overlay_open();
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
@@ -461,7 +467,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
}
|
||||
};
|
||||
|
||||
const REPLACEMENTS: [(&str, &str); 34] = [
|
||||
const REPLACEMENTS: [(&str, &str); 40] = [
|
||||
("graphene_core::AddArtboardNode", "graphene_core::graphic_element::AppendArtboardNode"),
|
||||
("graphene_core::ConstructArtboardNode", "graphene_core::graphic_element::ToArtboardNode"),
|
||||
("graphene_core::ToGraphicElementNode", "graphene_core::graphic_element::ToElementNode"),
|
||||
@@ -469,7 +475,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
("graphene_core::logic::LogicAndNode", "graphene_core::ops::LogicAndNode"),
|
||||
("graphene_core::logic::LogicNotNode", "graphene_core::ops::LogicNotNode"),
|
||||
("graphene_core::logic::LogicOrNode", "graphene_core::ops::LogicOrNode"),
|
||||
("graphene_core::ops::ConstructVector2", "graphene_core::ops::Vector2ValueNode"),
|
||||
("graphene_core::ops::ConstructVector2", "graphene_core::ops::CoordinateValueNode"),
|
||||
("graphene_core::ops::Vector2ValueNode", "graphene_core::ops::CoordinateValueNode"),
|
||||
("graphene_core::raster::BlackAndWhiteNode", "graphene_core::raster::adjustments::BlackAndWhiteNode"),
|
||||
("graphene_core::raster::BlendNode", "graphene_core::raster::adjustments::BlendNode"),
|
||||
("graphene_core::raster::ChannelMixerNode", "graphene_core::raster::adjustments::ChannelMixerNode"),
|
||||
@@ -478,8 +485,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
("graphene_core::raster::ExtractChannelNode", "graphene_core::raster::adjustments::ExtractChannelNode"),
|
||||
("graphene_core::raster::GradientMapNode", "graphene_core::raster::adjustments::GradientMapNode"),
|
||||
("graphene_core::raster::HueSaturationNode", "graphene_core::raster::adjustments::HueSaturationNode"),
|
||||
("graphene_core::vector::GenerateHandlesNode", "graphene_core::vector::AutoTangentsNode"),
|
||||
("graphene_core::vector::RemoveHandlesNode", "graphene_core::vector::AutoTangentsNode"),
|
||||
("graphene_core::raster::InvertNode", "graphene_core::raster::adjustments::InvertNode"),
|
||||
// ("graphene_core::raster::IndexNode", "graphene_core::raster::adjustments::IndexNode"),
|
||||
("graphene_core::raster::InvertRGBNode", "graphene_core::raster::adjustments::InvertNode"),
|
||||
("graphene_core::raster::LevelsNode", "graphene_core::raster::adjustments::LevelsNode"),
|
||||
("graphene_core::raster::LuminanceNode", "graphene_core::raster::adjustments::LuminanceNode"),
|
||||
@@ -500,6 +508,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
("graphene_core::vector::generator_nodes::StarGenerator", "graphene_core::vector::generator_nodes::StarNode"),
|
||||
("graphene_std::executor::BlendGpuImageNode", "graphene_std::gpu_nodes::BlendGpuImageNode"),
|
||||
("graphene_std::raster::SampleNode", "graphene_std::raster::SampleImageNode"),
|
||||
("graphene_core::transform::CullNode", "graphene_core::ops::IdentityNode"),
|
||||
("graphene_std::raster::MaskImageNode", "graphene_std::raster::MaskNode"),
|
||||
("graphene_core::vector::FlattenVectorElementsNode", "graphene_core::vector::FlattenPathNode"),
|
||||
];
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.generate_node_paths(&[]);
|
||||
@@ -667,6 +678,30 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
|
||||
if reference == "Stroke" && inputs_count == 8 {
|
||||
let node_definition = resolve_document_node_type(reference).unwrap();
|
||||
let document_node = node_definition.default_node_template().document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document.network_interface.insert_input_properties_row(node_id, 8, network_path);
|
||||
document.network_interface.insert_input_properties_row(node_id, 9, network_path);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false);
|
||||
let paint_order_input = NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeAbove), false);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 3), align_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[5].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[6].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 6), old_inputs[7].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), paint_order_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[3].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
|
||||
}
|
||||
|
||||
// Rename the old "Splines from Points" node to "Spline" and upgrade it to the new "Spline" node
|
||||
if reference == "Splines from Points" {
|
||||
document.network_interface.set_reference(node_id, network_path, Some("Spline".to_string()));
|
||||
@@ -828,6 +863,34 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the Mirror node to add the `reference_point` input and change `offset` from `DVec2` to `f64`
|
||||
if reference == "Mirror" && inputs_count == 4 {
|
||||
let node_definition = resolve_document_node_type(reference).unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
let Some(&TaggedValue::DVec2(old_offset)) = old_inputs[1].as_value() else { return };
|
||||
let old_offset = if old_offset.x.abs() > old_offset.y.abs() { old_offset.x } else { old_offset.y };
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 1),
|
||||
NodeInput::value(TaggedValue::ReferencePoint(graphene_std::transform::ReferencePoint::Center), false),
|
||||
network_path,
|
||||
);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(old_offset), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 3), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
// Upgrade artboard name being passed as hidden value input to "To Artboard"
|
||||
if reference == "Artboard" && upgrade_from_before_returning_nested_click_targets {
|
||||
let label = document.network_interface.display_name(node_id, network_path);
|
||||
@@ -862,6 +925,155 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if reference == "Instance on Points" && inputs_count == 2 {
|
||||
let node_definition = resolve_document_node_type(reference).unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
if reference == "Morph" && inputs_count == 4 {
|
||||
let node_definition = resolve_document_node_type(reference).unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
// We have removed the last input, so we don't add index 3
|
||||
}
|
||||
|
||||
if reference == "Brush" && inputs_count == 4 {
|
||||
let node_definition = resolve_document_node_type(reference).unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
// We have removed the second input ("bounds"), so we don't add index 1 and we shift the rest of the inputs down by one
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
if reference == "Flatten Vector Elements" {
|
||||
let node_definition = resolve_document_node_type("Flatten Path").unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
document.network_interface.replace_reference_name(node_id, network_path, "Flatten Path".to_string());
|
||||
}
|
||||
|
||||
if reference == "Remove Handles" {
|
||||
let node_definition = resolve_document_node_type("Auto-Tangents").unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::F64(0.), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
|
||||
document.network_interface.replace_reference_name(node_id, network_path, "Auto-Tangents".to_string());
|
||||
}
|
||||
|
||||
if reference == "Generate Handles" {
|
||||
let node_definition = resolve_document_node_type("Auto-Tangents").unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
|
||||
document.network_interface.replace_reference_name(node_id, network_path, "Auto-Tangents".to_string());
|
||||
}
|
||||
|
||||
if reference == "Merge by Distance" && inputs_count == 2 {
|
||||
let node_definition = resolve_document_node_type("Merge by Distance").unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 2),
|
||||
NodeInput::value(TaggedValue::MergeByDistanceAlgorithm(graphene_std::vector::misc::MergeByDistanceAlgorithm::Topological), false),
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
|
||||
if reference == "Spatial Merge by Distance" {
|
||||
let node_definition = resolve_document_node_type("Merge by Distance").unwrap();
|
||||
let new_node_template = node_definition.default_node_template();
|
||||
let document_node = new_node_template.document_node;
|
||||
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
|
||||
document
|
||||
.network_interface
|
||||
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 2),
|
||||
NodeInput::value(TaggedValue::MergeByDistanceAlgorithm(graphene_std::vector::misc::MergeByDistanceAlgorithm::Spatial), false),
|
||||
network_path,
|
||||
);
|
||||
|
||||
document.network_interface.replace_reference_name(node_id, network_path, "Merge by Distance".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -935,8 +1147,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
}
|
||||
PortfolioMessage::PasteSerializedData { data } => {
|
||||
if let Some(document) = self.active_document() {
|
||||
let mut all_new_ids = Vec::new();
|
||||
if let Ok(data) = serde_json::from_str::<Vec<CopyBufferEntry>>(&data) {
|
||||
let parent = document.new_layer_parent(false);
|
||||
let mut layers = Vec::new();
|
||||
|
||||
let mut added_nodes = false;
|
||||
|
||||
@@ -946,16 +1160,129 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
document.load_layer_resources(responses);
|
||||
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
|
||||
all_new_ids.extend(new_ids.values().cloned());
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
||||
layers.push(layer);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(Message::StartBuffer);
|
||||
responses.add(PortfolioMessage::CenterPastedLayers { layers });
|
||||
}
|
||||
}
|
||||
}
|
||||
PortfolioMessage::CenterPastedLayers { layers } => {
|
||||
if let Some(document) = self.active_document_mut() {
|
||||
let viewport_bounds_quad_pixels = Quad::from_box([DVec2::ZERO, ipp.viewport_bounds.size()]);
|
||||
let viewport_center_pixels = viewport_bounds_quad_pixels.center(); // In viewport pixel coordinates
|
||||
|
||||
let doc_to_viewport_transform = document.metadata().document_to_viewport;
|
||||
let viewport_to_doc_transform = doc_to_viewport_transform.inverse();
|
||||
|
||||
let viewport_quad_doc_space = viewport_to_doc_transform * viewport_bounds_quad_pixels;
|
||||
|
||||
let mut top_level_items_to_center: Vec<LayerNodeIdentifier> = Vec::new();
|
||||
let mut artboards_in_selection: Vec<LayerNodeIdentifier> = Vec::new();
|
||||
|
||||
for &layer_id in &layers {
|
||||
if document.network_interface.is_artboard(&layer_id.to_node(), &document.node_graph_handler.network) {
|
||||
artboards_in_selection.push(layer_id);
|
||||
}
|
||||
}
|
||||
|
||||
for &layer_id in &layers {
|
||||
let is_child_of_selected_artboard = artboards_in_selection.iter().any(|&artboard_id| {
|
||||
if layer_id == artboard_id {
|
||||
return false;
|
||||
}
|
||||
layer_id.ancestors(document.metadata()).any(|ancestor| ancestor == artboard_id)
|
||||
});
|
||||
|
||||
if !is_child_of_selected_artboard {
|
||||
top_level_items_to_center.push(layer_id);
|
||||
}
|
||||
}
|
||||
|
||||
if top_level_items_to_center.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut combined_min_doc = DVec2::MAX;
|
||||
let mut combined_max_doc = DVec2::MIN;
|
||||
let mut has_any_bounds = false;
|
||||
|
||||
for &item_id in &top_level_items_to_center {
|
||||
if let Some(bounds_doc) = document.metadata().bounding_box_document(item_id) {
|
||||
combined_min_doc = combined_min_doc.min(bounds_doc[0]);
|
||||
combined_max_doc = combined_max_doc.max(bounds_doc[1]);
|
||||
has_any_bounds = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !has_any_bounds {
|
||||
return;
|
||||
}
|
||||
|
||||
let combined_bounds_doc_quad = Quad::from_box([combined_min_doc, combined_max_doc]);
|
||||
|
||||
if combined_bounds_doc_quad.intersects(viewport_quad_doc_space) {
|
||||
return;
|
||||
}
|
||||
|
||||
let combined_center_doc = combined_bounds_doc_quad.center();
|
||||
let combined_center_viewport_pixels = doc_to_viewport_transform.transform_point2(combined_center_doc);
|
||||
let translation_viewport_pixels_rounded = (viewport_center_pixels - combined_center_viewport_pixels).round();
|
||||
|
||||
let final_translation_offset_doc = viewport_to_doc_transform.transform_vector2(translation_viewport_pixels_rounded);
|
||||
|
||||
if final_translation_offset_doc.abs_diff_eq(glam::DVec2::ZERO, 1e-9) {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
for &item_id in &top_level_items_to_center {
|
||||
if document.network_interface.is_artboard(&item_id.to_node(), &document.node_graph_handler.network) {
|
||||
if let Some(bounds_doc) = document.metadata().bounding_box_document(item_id) {
|
||||
let current_artboard_origin_doc = bounds_doc[0];
|
||||
let dimensions_doc = bounds_doc[1] - bounds_doc[0];
|
||||
let new_artboard_origin_doc = current_artboard_origin_doc + final_translation_offset_doc;
|
||||
|
||||
responses.add(GraphOperationMessage::ResizeArtboard {
|
||||
layer: item_id,
|
||||
location: new_artboard_origin_doc.round().as_ivec2(),
|
||||
dimensions: dimensions_doc.round().as_ivec2(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let current_abs_doc_transform = document.metadata().transform_to_document(item_id);
|
||||
|
||||
let new_abs_doc_transform = DAffine2 {
|
||||
matrix2: current_abs_doc_transform.matrix2,
|
||||
translation: current_abs_doc_transform.translation + final_translation_offset_doc,
|
||||
};
|
||||
|
||||
let transform = doc_to_viewport_transform * new_abs_doc_transform;
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer: item_id,
|
||||
transform,
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PasteImage {
|
||||
name,
|
||||
image,
|
||||
@@ -1252,6 +1579,7 @@ impl PortfolioMessageHandler {
|
||||
self.document_ids.push_back(document_id);
|
||||
}
|
||||
new_document.update_layers_panel_control_bar_widgets(responses);
|
||||
new_document.update_layers_panel_bottom_bar_widgets(responses);
|
||||
|
||||
self.documents.insert(document_id, new_document);
|
||||
|
||||
@@ -1260,7 +1588,7 @@ impl PortfolioMessageHandler {
|
||||
responses.add(ToolMessage::DeactivateTools);
|
||||
} else {
|
||||
// Load the default font upon creating the first document
|
||||
let font = Font::new(graphene_core::consts::DEFAULT_FONT_FAMILY.into(), graphene_core::consts::DEFAULT_FONT_STYLE.into());
|
||||
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into());
|
||||
responses.add(FrontendMessage::TriggerFontLoad { font });
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,14 @@ use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup,
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::Context;
|
||||
use graphene_core::GraphicGroupTable;
|
||||
use graphene_core::instances::Instances;
|
||||
use graphene_core::memo::IORecord;
|
||||
use graphene_core::vector::{VectorData, VectorDataTable};
|
||||
use graphene_core::{Artboard, ArtboardGroupTable, GraphicElement};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::Context;
|
||||
use graphene_std::GraphicGroupTable;
|
||||
use graphene_std::instances::Instances;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::vector::{VectorData, VectorDataTable};
|
||||
use graphene_std::{Artboard, ArtboardGroupTable, GraphicElement};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -154,7 +156,8 @@ impl InstanceLayout for GraphicElement {
|
||||
match self {
|
||||
Self::GraphicGroup(instances) => instances.identifier(),
|
||||
Self::VectorData(instances) => instances.identifier(),
|
||||
Self::RasterFrame(_) => "RasterFrame".to_string(),
|
||||
Self::RasterDataCPU(_) => "RasterDataCPU".to_string(),
|
||||
Self::RasterDataGPU(_) => "RasterDataGPU".to_string(),
|
||||
}
|
||||
}
|
||||
// Don't put a breadcrumb for GraphicElement
|
||||
@@ -165,7 +168,8 @@ impl InstanceLayout for GraphicElement {
|
||||
match self {
|
||||
Self::GraphicGroup(instances) => instances.layout_with_breadcrumb(data),
|
||||
Self::VectorData(instances) => instances.layout_with_breadcrumb(data),
|
||||
Self::RasterFrame(_) => label("Raster frame not supported"),
|
||||
Self::RasterDataCPU(_) => label("Raster frame not supported"),
|
||||
Self::RasterDataGPU(_) => label("Raster frame not supported"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,19 +182,42 @@ impl InstanceLayout for VectorData {
|
||||
format!("Vector Data (points={}, segments={})", self.point_domain.ids().len(), self.segment_domain.ids().len())
|
||||
}
|
||||
fn compute_layout(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let mut rows = Vec::new();
|
||||
let colinear = self.colinear_manipulators.iter().map(|[a, b]| format!("[{a} / {b}]")).collect::<Vec<_>>().join(", ");
|
||||
let colinear = if colinear.is_empty() { "None" } else { &colinear };
|
||||
let style = vec![
|
||||
TextLabel::new(format!(
|
||||
"{}\n\nColinear Handle IDs: {}\n\nUpstream Graphic Group Table: {}",
|
||||
self.style,
|
||||
colinear,
|
||||
if self.upstream_graphic_group.is_some() { "Yes" } else { "No" }
|
||||
))
|
||||
.multiline(true)
|
||||
.widget_holder(),
|
||||
];
|
||||
|
||||
let domain_entries = [VectorDataDomain::Points, VectorDataDomain::Segments, VectorDataDomain::Regions]
|
||||
.into_iter()
|
||||
.map(|domain| {
|
||||
RadioEntryData::new(format!("{domain:?}"))
|
||||
.label(format!("{domain:?}"))
|
||||
.on_update(move |_| SpreadsheetMessage::ViewVectorDataDomain { domain }.into())
|
||||
})
|
||||
.collect();
|
||||
let domain = vec![RadioInput::new(domain_entries).selected_index(Some(data.vector_data_domain as u32)).widget_holder()];
|
||||
|
||||
let mut table_rows = Vec::new();
|
||||
match data.vector_data_domain {
|
||||
VectorDataDomain::Points => {
|
||||
rows.push(column_headings(&["", "position"]));
|
||||
rows.extend(
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(
|
||||
self.point_domain
|
||||
.iter()
|
||||
.map(|(id, position)| vec![TextLabel::new(format!("{}", id.inner())).widget_holder(), TextLabel::new(format!("{}", position)).widget_holder()]),
|
||||
);
|
||||
}
|
||||
VectorDataDomain::Segments => {
|
||||
rows.push(column_headings(&["", "start_index", "end_index", "handles"]));
|
||||
rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
|
||||
table_rows.push(column_headings(&["", "start_index", "end_index", "handles"]));
|
||||
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).widget_holder(),
|
||||
TextLabel::new(format!("{}", start)).widget_holder(),
|
||||
@@ -200,8 +227,8 @@ impl InstanceLayout for VectorData {
|
||||
}));
|
||||
}
|
||||
VectorDataDomain::Regions => {
|
||||
rows.push(column_headings(&["", "segment_range", "fill"]));
|
||||
rows.extend(self.region_domain.iter().map(|(id, segment_range, fill)| {
|
||||
table_rows.push(column_headings(&["", "segment_range", "fill"]));
|
||||
table_rows.extend(self.region_domain.iter().map(|(id, segment_range, fill)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).widget_holder(),
|
||||
TextLabel::new(format!("{:?}", segment_range)).widget_holder(),
|
||||
@@ -211,17 +238,20 @@ impl InstanceLayout for VectorData {
|
||||
}
|
||||
}
|
||||
|
||||
let entries = [VectorDataDomain::Points, VectorDataDomain::Segments, VectorDataDomain::Regions]
|
||||
.into_iter()
|
||||
.map(|domain| {
|
||||
RadioEntryData::new(format!("{domain:?}"))
|
||||
.label(format!("{domain:?}"))
|
||||
.on_update(move |_| SpreadsheetMessage::ViewVectorDataDomain { domain }.into())
|
||||
})
|
||||
.collect();
|
||||
vec![LayoutGroup::Row { widgets: style }, LayoutGroup::Row { widgets: domain }, LayoutGroup::Table { rows: table_rows }]
|
||||
}
|
||||
}
|
||||
|
||||
let domain = vec![RadioInput::new(entries).selected_index(Some(data.vector_data_domain as u32)).widget_holder()];
|
||||
vec![LayoutGroup::Row { widgets: domain }, LayoutGroup::Table { rows }]
|
||||
impl InstanceLayout for Image<Color> {
|
||||
fn type_name() -> &'static str {
|
||||
"Image"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Image (width={}, height={})", self.width, self.height)
|
||||
}
|
||||
fn compute_layout(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let rows = vec![vec![TextLabel::new(format!("Image (width={}, height={})", self.width, self.height)).widget_holder()]];
|
||||
vec![LayoutGroup::Table { rows }]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,16 +288,26 @@ impl<T: InstanceLayout> InstanceLayout for Instances<T> {
|
||||
}
|
||||
|
||||
let mut rows = self
|
||||
.instances()
|
||||
.instance_ref_iter()
|
||||
.enumerate()
|
||||
.map(|(index, instance)| {
|
||||
let (scale, angle, translation) = instance.transform.to_scale_angle_translation();
|
||||
let rotation = if angle == -0. { 0. } else { angle.to_degrees() };
|
||||
let round = |x: f64| (x * 1e3).round() / 1e3;
|
||||
vec![
|
||||
TextLabel::new(format!("{}", index)).widget_holder(),
|
||||
TextButton::new(instance.instance.identifier())
|
||||
.on_update(move |_| SpreadsheetMessage::PushToInstancePath { index }.into())
|
||||
.widget_holder(),
|
||||
TextLabel::new(format!("{}", instance.transform)).widget_holder(),
|
||||
TextLabel::new(format!("{:?}", instance.alpha_blending)).widget_holder(),
|
||||
TextLabel::new(format!(
|
||||
"Location: ({} px, {} px) — Rotation: {rotation:2}° — Scale: ({}x, {}x)",
|
||||
round(translation.x),
|
||||
round(translation.y),
|
||||
round(scale.x),
|
||||
round(scale.y)
|
||||
))
|
||||
.widget_holder(),
|
||||
TextLabel::new(format!("{}", instance.alpha_blending)).widget_holder(),
|
||||
TextLabel::new(instance.source_node_id.map_or_else(|| "-".to_string(), |id| format!("{}", id.0))).widget_holder(),
|
||||
]
|
||||
})
|
||||
|
||||
@@ -34,19 +34,16 @@ pub use crate::messages::broadcast::broadcast_event::{BroadcastEvent, BroadcastE
|
||||
pub use crate::messages::message::{Message, MessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::artboard_tool::{ArtboardToolMessage, ArtboardToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::brush_tool::{BrushToolMessage, BrushToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::ellipse_tool::{EllipseToolMessage, EllipseToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::eyedropper_tool::{EyedropperToolMessage, EyedropperToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::fill_tool::{FillToolMessage, FillToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::freehand_tool::{FreehandToolMessage, FreehandToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::gradient_tool::{GradientToolMessage, GradientToolMessageDiscriminant};
|
||||
// pub use crate::messages::tool::tool_messages::imaginate_tool::{ImaginateToolMessage, ImaginateToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::line_tool::{LineToolMessage, LineToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::navigate_tool::{NavigateToolMessage, NavigateToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::path_tool::{PathToolMessage, PathToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::pen_tool::{PenToolMessage, PenToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::polygon_tool::{PolygonToolMessage, PolygonToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::rectangle_tool::{RectangleToolMessage, RectangleToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::select_tool::{SelectToolMessage, SelectToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::shape_tool::{ShapeToolMessage, ShapeToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::spline_tool::{SplineToolMessage, SplineToolMessageDiscriminant};
|
||||
pub use crate::messages::tool::tool_messages::text_tool::{TextToolMessage, TextToolMessageDiscriminant};
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_core::Color;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
@@ -60,14 +60,14 @@ impl ToolColorOptions {
|
||||
|
||||
pub fn apply_fill(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let fill = graphene_core::vector::style::Fill::solid(color.to_gamma_srgb());
|
||||
let fill = graphene_std::vector::style::Fill::solid(color.to_gamma_srgb());
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_stroke(&self, weight: f64, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let stroke = graphene_core::vector::style::Stroke::new(Some(color.to_gamma_srgb()), weight);
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(color.to_gamma_srgb()), weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,12 @@ use glam::DVec2;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::Color;
|
||||
use graphene_core::raster::BlendMode;
|
||||
use graphene_core::raster::image::ImageFrameTable;
|
||||
use graphene_core::text::{Font, TypesettingConfig};
|
||||
use graphene_core::vector::style::Gradient;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, GPU, RasterDataTable};
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use graphene_std::vector::{ManipulatorPointId, PointId, SegmentId, VectorModificationType};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -57,8 +58,10 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
|
||||
}
|
||||
|
||||
// Move the `second_layer` below the `first_layer` for positioning purposes
|
||||
let first_layer_parent = first_layer.parent(document.metadata()).unwrap();
|
||||
let first_layer_index = first_layer_parent.children(document.metadata()).position(|child| child == first_layer).unwrap();
|
||||
let Some(first_layer_parent) = first_layer.parent(document.metadata()) else { return };
|
||||
let Some(first_layer_index) = first_layer_parent.children(document.metadata()).position(|child| child == first_layer) else {
|
||||
return;
|
||||
};
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack {
|
||||
layer: second_layer,
|
||||
parent: first_layer_parent,
|
||||
@@ -91,9 +94,9 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
|
||||
delete_children: false,
|
||||
});
|
||||
|
||||
// Add a flatten vector elements node after the merge
|
||||
// Add a Flatten Path node after the merge
|
||||
let flatten_node_id = NodeId::new();
|
||||
let flatten_node = document_node_definitions::resolve_document_node_type("Flatten Vector Elements")
|
||||
let flatten_node = document_node_definitions::resolve_document_node_type("Flatten Path")
|
||||
.expect("Failed to create flatten node")
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
@@ -207,7 +210,7 @@ pub fn new_vector_layer(subpaths: Vec<Subpath<PointId>>, id: NodeId, parent: Lay
|
||||
}
|
||||
|
||||
/// Create a new bitmap layer.
|
||||
pub fn new_image_layer(image_frame: ImageFrameTable<Color>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
pub fn new_image_layer(image_frame: RasterDataTable<CPU>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
let insert_index = 0;
|
||||
responses.add(GraphOperationMessage::NewBitmapLayer {
|
||||
id,
|
||||
@@ -256,7 +259,7 @@ pub fn get_viewport_pivot(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
network_interface.document_metadata().transform_to_viewport(layer).transform_point2(min + (max - min) * pivot)
|
||||
}
|
||||
|
||||
/// Get the current gradient of a layer from the closest Fill node
|
||||
/// Get the current gradient of a layer from the closest "Fill" node.
|
||||
pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
let fill_index = 1;
|
||||
|
||||
@@ -267,7 +270,7 @@ pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
Some(gradient.clone())
|
||||
}
|
||||
|
||||
/// Get the current fill of a layer from the closest Fill node
|
||||
/// Get the current fill of a layer from the closest "Fill" node.
|
||||
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
||||
let fill_index = 1;
|
||||
|
||||
@@ -278,16 +281,16 @@ pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetwor
|
||||
Some(color.to_linear_srgb())
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest Blend Mode node
|
||||
/// Get the current blend mode of a layer from the closest "Blending" node.
|
||||
pub fn get_blend_mode(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<BlendMode> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Blend Mode")?;
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Blending")?;
|
||||
let TaggedValue::BlendMode(blend_mode) = inputs.get(1)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*blend_mode)
|
||||
}
|
||||
|
||||
/// Get the current opacity of a layer from the closest Opacity node.
|
||||
/// Get the current opacity of a layer from the closest "Blending" node.
|
||||
/// This may differ from the actual opacity contained within the data type reaching this layer, because that actual opacity may be:
|
||||
/// - Multiplied with additional opacity nodes earlier in the chain
|
||||
/// - Set by an Opacity node with an exposed input value driven by another node
|
||||
@@ -296,13 +299,29 @@ pub fn get_blend_mode(layer: LayerNodeIdentifier, network_interface: &NodeNetwor
|
||||
///
|
||||
/// With those limitations in mind, the intention of this function is to show just the value already present in an upstream Opacity node so that value can be directly edited.
|
||||
pub fn get_opacity(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Opacity")?;
|
||||
let TaggedValue::F64(opacity) = inputs.get(1)?.as_value()? else {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Blending")?;
|
||||
let TaggedValue::F64(opacity) = inputs.get(2)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*opacity)
|
||||
}
|
||||
|
||||
pub fn get_clip_mode(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<bool> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Blending")?;
|
||||
let TaggedValue::Bool(clip) = inputs.get(4)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*clip)
|
||||
}
|
||||
|
||||
pub fn get_fill(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs("Blending")?;
|
||||
let TaggedValue::F64(fill) = inputs.get(3)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*fill)
|
||||
}
|
||||
|
||||
pub fn get_fill_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name("Fill")
|
||||
}
|
||||
@@ -354,7 +373,7 @@ pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInter
|
||||
}
|
||||
|
||||
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
let weight_node_input_index = 2;
|
||||
let weight_node_input_index = graphene_std::vector::stroke::WeightInput::INDEX;
|
||||
if let TaggedValue::F64(width) = NodeGraphLayer::new(layer, network_interface).find_input("Stroke", weight_node_input_index)? {
|
||||
Some(*width)
|
||||
} else {
|
||||
@@ -424,12 +443,7 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
/// Check if a layer is a raster layer
|
||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]).0.nested_type().clone();
|
||||
if layer_input_type == concrete!(graphene_core::raster::image::ImageFrameTable<graphene_core::Color>)
|
||||
|| layer_input_type == concrete!(graphene_core::application_io::TextureFrameTable)
|
||||
|| layer_input_type == concrete!(graphene_std::RasterFrame)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
false
|
||||
|
||||
layer_input_type == concrete!(RasterDataTable<CPU>) || layer_input_type == concrete!(RasterDataTable<GPU>)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ fn draw_dashed_line(line_start: DVec2, line_end: DVec2, transform: DAffine2, ove
|
||||
|
||||
overlay_context.dashed_line(min_viewport, max_viewport, None, None, Some(2.), Some(2.), Some(0.5));
|
||||
}
|
||||
|
||||
/// Draws a solid line with a length annotation between two points transformed by the given affine transformations.
|
||||
fn draw_line_with_length(line_start: DVec2, line_end: DVec2, transform: DAffine2, document_to_viewport: DAffine2, overlay_context: &mut OverlayContext, label_alignment: LabelAlignment) {
|
||||
let transform_to_document = document_to_viewport.inverse() * transform;
|
||||
|
||||
@@ -6,6 +6,8 @@ pub mod measure;
|
||||
pub mod pivot;
|
||||
pub mod resize;
|
||||
pub mod shape_editor;
|
||||
pub mod shape_gizmos;
|
||||
pub mod shapes;
|
||||
pub mod snapping;
|
||||
pub mod transformation_cage;
|
||||
pub mod utility_functions;
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
use super::graph_modification_utils;
|
||||
use crate::consts::PIVOT_DIAMETER;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -18,7 +18,9 @@ pub struct Pivot {
|
||||
/// The viewspace pivot position (if applicable)
|
||||
pivot: Option<DVec2>,
|
||||
/// The old pivot position in the GUI, used to reduce refreshes of the document bar
|
||||
old_pivot_position: PivotPosition,
|
||||
old_pivot_position: ReferencePoint,
|
||||
/// Used to enable and disable the pivot
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Default for Pivot {
|
||||
@@ -27,7 +29,8 @@ impl Default for Pivot {
|
||||
normalized_pivot: DVec2::splat(0.5),
|
||||
transform_from_normalized: Default::default(),
|
||||
pivot: Default::default(),
|
||||
old_pivot_position: PivotPosition::Center,
|
||||
old_pivot_position: ReferencePoint::Center,
|
||||
active: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +47,10 @@ impl Pivot {
|
||||
|
||||
/// Recomputes the pivot position and transform.
|
||||
fn recalculate_pivot(&mut self, document: &DocumentMessageHandler) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut layers = selected_nodes.selected_visible_and_unlocked_layers(&document.network_interface);
|
||||
let Some(first) = layers.next() else {
|
||||
@@ -82,6 +89,13 @@ impl Pivot {
|
||||
}
|
||||
|
||||
pub fn update_pivot(&mut self, document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, draw_data: Option<(f64,)>) {
|
||||
if !overlay_context.visibility_settings.pivot() {
|
||||
self.active = false;
|
||||
return;
|
||||
} else {
|
||||
self.active = true;
|
||||
}
|
||||
|
||||
self.recalculate_pivot(document);
|
||||
if let (Some(pivot), Some(data)) = (self.pivot, draw_data) {
|
||||
overlay_context.pivot(pivot, data.0);
|
||||
@@ -90,18 +104,26 @@ impl Pivot {
|
||||
|
||||
/// Answers if the pivot widget has changed (so we should refresh the tool bar at the top of the canvas).
|
||||
pub fn should_refresh_pivot_position(&mut self) -> bool {
|
||||
if !self.active {
|
||||
return false;
|
||||
}
|
||||
|
||||
let new = self.to_pivot_position();
|
||||
let should_refresh = new != self.old_pivot_position;
|
||||
self.old_pivot_position = new;
|
||||
should_refresh
|
||||
}
|
||||
|
||||
pub fn to_pivot_position(&self) -> PivotPosition {
|
||||
pub fn to_pivot_position(&self) -> ReferencePoint {
|
||||
self.normalized_pivot.into()
|
||||
}
|
||||
|
||||
/// Sets the viewport position of the pivot for all selected layers.
|
||||
pub fn set_viewport_position(&self, position: DVec2, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
|
||||
for layer in document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface) {
|
||||
let transform = Self::get_layer_pivot_transform(layer, document);
|
||||
// Only update the pivot when computed position is finite.
|
||||
@@ -115,11 +137,18 @@ impl Pivot {
|
||||
|
||||
/// Set the pivot using the normalized transform that is set above.
|
||||
pub fn set_normalized_position(&self, position: DVec2, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
|
||||
self.set_viewport_position(self.transform_from_normalized.transform_point2(position), document, responses);
|
||||
}
|
||||
|
||||
/// Answers if the pointer is currently positioned over the pivot.
|
||||
pub fn is_over(&self, mouse: DVec2) -> bool {
|
||||
if !self.active {
|
||||
return false;
|
||||
}
|
||||
self.pivot.filter(|&pivot| mouse.distance_squared(pivot) < (PIVOT_DIAMETER / 2.).powi(2)).is_some()
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use glam::{DAffine2, DVec2, Vec2Swizzles};
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Resize {
|
||||
/// Stored as a document position so the start doesn't move if the canvas is panned.
|
||||
drag_start: DVec2,
|
||||
pub drag_start: DVec2,
|
||||
pub layer: Option<LayerNodeIdentifier>,
|
||||
pub snap_manager: SnapManager,
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
use super::graph_modification_utils::{self, merge_layers};
|
||||
use super::graph_modification_utils::merge_layers;
|
||||
use super::snapping::{SnapCache, SnapCandidatePoint, SnapData, SnapManager, SnappedPoint};
|
||||
use super::utility_functions::{adjust_handle_colinearity, calculate_segment_angle, restore_g1_continuity, restore_previous_handle_position};
|
||||
use crate::consts::HANDLE_LENGTH_FACTOR;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::selected_segments;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{PathSnapSource, SnapSource};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration;
|
||||
use crate::messages::tool::tool_messages::path_tool::PointSelectState;
|
||||
use crate::messages::tool::common_functionality::utility_functions::is_visible_point;
|
||||
use crate::messages::tool::tool_messages::path_tool::{PathOverlayMode, PointSelectState};
|
||||
use bezier_rs::{Bezier, BezierHandles, Subpath, TValue};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::transform::Transform;
|
||||
use graphene_core::vector::{ManipulatorPointId, PointId, VectorData, VectorModificationType};
|
||||
use graphene_std::vector::{HandleId, SegmentId};
|
||||
use graphene_std::vector::{ManipulatorPointId, PointId, VectorData, VectorModificationType};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum SelectionChange {
|
||||
@@ -42,24 +45,67 @@ pub enum ManipulatorAngle {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SelectedLayerState {
|
||||
selected_points: HashSet<ManipulatorPointId>,
|
||||
/// Keeps track of the current state; helps avoid unnecessary computation when called by [`ShapeState`].
|
||||
ignore_handles: bool,
|
||||
ignore_anchors: bool,
|
||||
/// Points that are selected but ignored (when their overlays are disabled) are stored here.
|
||||
ignored_handle_points: HashSet<ManipulatorPointId>,
|
||||
ignored_anchor_points: HashSet<ManipulatorPointId>,
|
||||
}
|
||||
|
||||
impl SelectedLayerState {
|
||||
pub fn selected(&self) -> impl Iterator<Item = ManipulatorPointId> + '_ {
|
||||
self.selected_points.iter().copied()
|
||||
}
|
||||
|
||||
pub fn is_selected(&self, point: ManipulatorPointId) -> bool {
|
||||
self.selected_points.contains(&point)
|
||||
}
|
||||
|
||||
pub fn select_point(&mut self, point: ManipulatorPointId) {
|
||||
self.selected_points.insert(point);
|
||||
}
|
||||
|
||||
pub fn deselect_point(&mut self, point: ManipulatorPointId) {
|
||||
self.selected_points.remove(&point);
|
||||
}
|
||||
|
||||
pub fn ignore_handles(&mut self, status: bool) {
|
||||
if self.ignore_handles != status {
|
||||
return;
|
||||
}
|
||||
|
||||
self.ignore_handles = !status;
|
||||
|
||||
if self.ignore_handles {
|
||||
self.ignored_handle_points.extend(self.selected_points.iter().copied().filter(|point| point.as_handle().is_some()));
|
||||
self.selected_points.retain(|point| !self.ignored_handle_points.contains(point));
|
||||
} else {
|
||||
self.selected_points.extend(self.ignored_handle_points.iter().copied());
|
||||
self.ignored_handle_points.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ignore_anchors(&mut self, status: bool) {
|
||||
if self.ignore_anchors != status {
|
||||
return;
|
||||
}
|
||||
|
||||
self.ignore_anchors = !status;
|
||||
|
||||
if self.ignore_anchors {
|
||||
self.ignored_anchor_points.extend(self.selected_points.iter().copied().filter(|point| point.as_anchor().is_some()));
|
||||
self.selected_points.retain(|point| !self.ignored_anchor_points.contains(point));
|
||||
} else {
|
||||
self.selected_points.extend(self.ignored_anchor_points.iter().copied());
|
||||
self.ignored_anchor_points.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_points(&mut self) {
|
||||
self.selected_points.clear();
|
||||
}
|
||||
|
||||
pub fn selected_points_count(&self) -> usize {
|
||||
self.selected_points.len()
|
||||
}
|
||||
@@ -69,8 +115,10 @@ pub type SelectedShapeState = HashMap<LayerNodeIdentifier, SelectedLayerState>;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ShapeState {
|
||||
// The layers we can select and edit manipulators (anchors and handles) from
|
||||
/// The layers we can select and edit manipulators (anchors and handles) from.
|
||||
pub selected_shape_state: SelectedShapeState,
|
||||
ignore_handles: bool,
|
||||
ignore_anchors: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -96,7 +144,6 @@ pub struct ClosestSegment {
|
||||
colinear: [Option<HandleId>; 2],
|
||||
t: f64,
|
||||
bezier_point_to_viewport: DVec2,
|
||||
stroke_width: f64,
|
||||
}
|
||||
|
||||
impl ClosestSegment {
|
||||
@@ -104,10 +151,28 @@ impl ClosestSegment {
|
||||
self.layer
|
||||
}
|
||||
|
||||
pub fn segment(&self) -> SegmentId {
|
||||
self.segment
|
||||
}
|
||||
|
||||
pub fn points(&self) -> [PointId; 2] {
|
||||
self.points
|
||||
}
|
||||
|
||||
pub fn closest_point_document(&self) -> DVec2 {
|
||||
self.bezier.evaluate(TValue::Parametric(self.t))
|
||||
}
|
||||
|
||||
pub fn closest_point_to_viewport(&self) -> DVec2 {
|
||||
self.bezier_point_to_viewport
|
||||
}
|
||||
|
||||
pub fn closest_point(&self, document_metadata: &DocumentMetadata) -> DVec2 {
|
||||
let transform = document_metadata.transform_to_viewport(self.layer);
|
||||
let bezier_point = self.bezier.evaluate(TValue::Parametric(self.t));
|
||||
transform.transform_point2(bezier_point)
|
||||
}
|
||||
|
||||
/// Updates this [`ClosestSegment`] with the viewport-space location of the closest point on the segment to the given mouse position.
|
||||
pub fn update_closest_point(&mut self, document_metadata: &DocumentMetadata, mouse_position: DVec2) {
|
||||
let transform = document_metadata.transform_to_viewport(self.layer);
|
||||
@@ -125,12 +190,8 @@ impl ClosestSegment {
|
||||
self.bezier_point_to_viewport.distance_squared(mouse_position)
|
||||
}
|
||||
|
||||
pub fn too_far(&self, mouse_position: DVec2, tolerance: f64, document_metadata: &DocumentMetadata) -> bool {
|
||||
let dist_sq = self.distance_squared(mouse_position);
|
||||
let stroke_width = document_metadata.document_to_viewport.decompose_scale().x.max(1.) * self.stroke_width;
|
||||
let stroke_width_sq = stroke_width * stroke_width;
|
||||
let tolerance_sq = tolerance * tolerance;
|
||||
(stroke_width_sq + tolerance_sq) < dist_sq
|
||||
pub fn too_far(&self, mouse_position: DVec2, tolerance: f64) -> bool {
|
||||
tolerance.powi(2) < self.distance_squared(mouse_position)
|
||||
}
|
||||
|
||||
pub fn handle_positions(&self, document_metadata: &DocumentMetadata) -> (Option<DVec2>, Option<DVec2>) {
|
||||
@@ -147,7 +208,7 @@ impl ClosestSegment {
|
||||
(first_handle, second_handle)
|
||||
}
|
||||
|
||||
pub fn adjusted_insert(&self, responses: &mut VecDeque<Message>) -> PointId {
|
||||
pub fn adjusted_insert(&self, responses: &mut VecDeque<Message>) -> (PointId, [SegmentId; 2]) {
|
||||
let layer = self.layer;
|
||||
let [first, second] = self.bezier.split(TValue::Parametric(self.t));
|
||||
|
||||
@@ -192,17 +253,108 @@ impl ClosestSegment {
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
midpoint
|
||||
(midpoint, segment_ids)
|
||||
}
|
||||
|
||||
pub fn adjusted_insert_and_select(&self, shape_editor: &mut ShapeState, responses: &mut VecDeque<Message>, extend_selection: bool) {
|
||||
let id = self.adjusted_insert(responses);
|
||||
let (id, _) = self.adjusted_insert(responses);
|
||||
shape_editor.select_anchor_point_by_id(self.layer, id, extend_selection)
|
||||
}
|
||||
|
||||
pub fn calculate_perp(&self, document: &DocumentMessageHandler) -> DVec2 {
|
||||
let tangent = if let (Some(handle1), Some(handle2)) = self.handle_positions(document.metadata()) {
|
||||
(handle1 - handle2).try_normalize()
|
||||
} else {
|
||||
let [first_point, last_point] = self.points();
|
||||
if let Some(vector_data) = document.network_interface.compute_modified_vector(self.layer()) {
|
||||
if let (Some(pos1), Some(pos2)) = (
|
||||
ManipulatorPointId::Anchor(first_point).get_position(&vector_data),
|
||||
ManipulatorPointId::Anchor(last_point).get_position(&vector_data),
|
||||
) {
|
||||
(pos1 - pos2).try_normalize()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
.unwrap_or(DVec2::ZERO);
|
||||
tangent.perp()
|
||||
}
|
||||
|
||||
/// Molding the bezier curve.
|
||||
/// Returns adjacent handles' [`HandleId`] if colinearity is broken temporarily.
|
||||
pub fn mold_handle_positions(
|
||||
&self,
|
||||
document: &DocumentMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
(c1, c2): (DVec2, DVec2),
|
||||
new_b: DVec2,
|
||||
break_colinear_molding: bool,
|
||||
temporary_adjacent_handles_while_molding: Option<[Option<HandleId>; 2]>,
|
||||
) -> Option<[Option<HandleId>; 2]> {
|
||||
let transform = document.metadata().transform_to_viewport(self.layer);
|
||||
|
||||
let start = self.bezier.start;
|
||||
let end = self.bezier.end;
|
||||
|
||||
// Apply the drag delta to the segment's handles
|
||||
let b = self.bezier_point_to_viewport;
|
||||
let delta = transform.inverse().transform_vector2(new_b - b);
|
||||
let (nc1, nc2) = (c1 + delta, c2 + delta);
|
||||
|
||||
let handle1 = HandleId::primary(self.segment);
|
||||
let handle2 = HandleId::end(self.segment);
|
||||
let layer = self.layer;
|
||||
|
||||
let modification_type = handle1.set_relative_position(nc1 - start);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
let modification_type = handle2.set_relative_position(nc2 - end);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// If adjacent segments have colinear handles, their direction is changed but their handle lengths is preserved
|
||||
// TODO: Find something which is more appropriate
|
||||
let vector_data = document.network_interface.compute_modified_vector(self.layer())?;
|
||||
|
||||
if break_colinear_molding {
|
||||
// Disable G1 continuity
|
||||
let other_handles = [
|
||||
restore_previous_handle_position(handle1, c1, start, &vector_data, layer, responses),
|
||||
restore_previous_handle_position(handle2, c2, end, &vector_data, layer, responses),
|
||||
];
|
||||
|
||||
// Store other HandleId in tool data to regain colinearity later
|
||||
if temporary_adjacent_handles_while_molding.is_some() {
|
||||
temporary_adjacent_handles_while_molding
|
||||
} else {
|
||||
Some(other_handles)
|
||||
}
|
||||
} else {
|
||||
// Move the colinear handles so that colinearity is maintained
|
||||
adjust_handle_colinearity(handle1, start, nc1, &vector_data, layer, responses);
|
||||
adjust_handle_colinearity(handle2, end, nc2, &vector_data, layer, responses);
|
||||
|
||||
if let Some(adjacent_handles) = temporary_adjacent_handles_while_molding {
|
||||
if let Some(other_handle1) = adjacent_handles[0] {
|
||||
restore_g1_continuity(handle1, other_handle1, nc1, start, &vector_data, layer, responses);
|
||||
}
|
||||
if let Some(other_handle2) = adjacent_handles[1] {
|
||||
restore_g1_continuity(handle2, other_handle2, nc2, end, &vector_data, layer, responses);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Consider keeping a list of selected manipulators to minimize traversals of the layers
|
||||
impl ShapeState {
|
||||
pub fn is_point_ignored(&self, point: &ManipulatorPointId) -> bool {
|
||||
(point.as_handle().is_some() && self.ignore_handles) || (point.as_anchor().is_some() && self.ignore_anchors)
|
||||
}
|
||||
|
||||
pub fn close_selected_path(&self, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
// First collect all selected anchor points across all layers
|
||||
let all_selected_points: Vec<(LayerNodeIdentifier, PointId)> = self
|
||||
@@ -342,12 +494,20 @@ impl ShapeState {
|
||||
|
||||
/// Select/deselect the first point within the selection threshold.
|
||||
/// Returns a tuple of the points if found and the offset, or `None` otherwise.
|
||||
pub fn change_point_selection(&mut self, network_interface: &NodeNetworkInterface, mouse_position: DVec2, select_threshold: f64, extend_selection: bool) -> Option<Option<SelectedPointsInfo>> {
|
||||
pub fn change_point_selection(
|
||||
&mut self,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
mouse_position: DVec2,
|
||||
select_threshold: f64,
|
||||
extend_selection: bool,
|
||||
path_overlay_mode: PathOverlayMode,
|
||||
frontier_handles_info: Option<HashMap<SegmentId, Vec<PointId>>>,
|
||||
) -> Option<Option<SelectedPointsInfo>> {
|
||||
if self.selected_shape_state.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some((layer, manipulator_point_id)) = self.find_nearest_point_indices(network_interface, mouse_position, select_threshold) {
|
||||
if let Some((layer, manipulator_point_id)) = self.find_nearest_visible_point_indices(network_interface, mouse_position, select_threshold, path_overlay_mode, frontier_handles_info) {
|
||||
let vector_data = network_interface.compute_modified_vector(layer)?;
|
||||
let point_position = manipulator_point_id.get_position(&vector_data)?;
|
||||
|
||||
@@ -388,7 +548,14 @@ impl ShapeState {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn get_point_selection_state(&mut self, network_interface: &NodeNetworkInterface, mouse_position: DVec2, select_threshold: f64) -> Option<(bool, Option<SelectedPointsInfo>)> {
|
||||
pub fn get_point_selection_state(
|
||||
&mut self,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
mouse_position: DVec2,
|
||||
select_threshold: f64,
|
||||
path_overlay_mode: PathOverlayMode,
|
||||
frontier_handles_info: Option<HashMap<SegmentId, Vec<PointId>>>,
|
||||
) -> Option<(bool, Option<SelectedPointsInfo>)> {
|
||||
if self.selected_shape_state.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -397,6 +564,13 @@ impl ShapeState {
|
||||
let vector_data = network_interface.compute_modified_vector(layer)?;
|
||||
let point_position = manipulator_point_id.get_position(&vector_data)?;
|
||||
|
||||
// Check if point is visible under current overlay mode or not
|
||||
let selected_segments = selected_segments(network_interface, self);
|
||||
let selected_points = self.selected_points().cloned().collect::<HashSet<_>>();
|
||||
if !is_visible_point(manipulator_point_id, &vector_data, path_overlay_mode, frontier_handles_info, selected_segments, &selected_points) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let selected_shape_state = self.selected_shape_state.get(&layer)?;
|
||||
let already_selected = selected_shape_state.is_selected(manipulator_point_id);
|
||||
|
||||
@@ -455,8 +629,9 @@ impl ShapeState {
|
||||
} else {
|
||||
// Select all connected points
|
||||
while let Some(point) = selected_stack.pop() {
|
||||
if !state.is_selected(ManipulatorPointId::Anchor(point)) {
|
||||
state.select_point(ManipulatorPointId::Anchor(point));
|
||||
let anchor_point = ManipulatorPointId::Anchor(point);
|
||||
if !state.is_selected(anchor_point) {
|
||||
state.select_point(anchor_point);
|
||||
selected_stack.extend(vector_data.connected_points(point));
|
||||
}
|
||||
}
|
||||
@@ -496,6 +671,42 @@ impl ShapeState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_selected_anchors_status(&mut self, status: bool) {
|
||||
for state in self.selected_shape_state.values_mut() {
|
||||
self.ignore_anchors = !status;
|
||||
state.ignore_anchors(status);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_selected_handles_status(&mut self, status: bool) {
|
||||
for state in self.selected_shape_state.values_mut() {
|
||||
self.ignore_handles = !status;
|
||||
state.ignore_handles(status);
|
||||
}
|
||||
}
|
||||
|
||||
/// Deselects all the anchors across every selected layer.
|
||||
pub fn deselect_all_anchors(&mut self) {
|
||||
for (_, state) in self.selected_shape_state.iter_mut() {
|
||||
let selected_anchor_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_anchor().is_some()).cloned().collect();
|
||||
|
||||
for point in selected_anchor_points {
|
||||
state.deselect_point(point);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deselects all the handles across every selected layer.
|
||||
pub fn deselect_all_handles(&mut self) {
|
||||
for (_, state) in self.selected_shape_state.iter_mut() {
|
||||
let selected_handle_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_handle().is_some()).cloned().collect();
|
||||
|
||||
for point in selected_handle_points {
|
||||
state.deselect_point(point);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the shapes we consider for selection, we will choose draggable manipulators from these shapes.
|
||||
pub fn set_selected_layers(&mut self, target_layers: Vec<LayerNodeIdentifier>) {
|
||||
self.selected_shape_state.retain(|layer_path, _| target_layers.contains(layer_path));
|
||||
@@ -577,6 +788,10 @@ impl ShapeState {
|
||||
layer: LayerNodeIdentifier,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Option<()> {
|
||||
if self.is_point_ignored(point) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let vector_data = network_interface.compute_modified_vector(layer)?;
|
||||
let transform = network_interface.document_metadata().transform_to_document(layer).inverse();
|
||||
let position = transform.transform_point2(new_position);
|
||||
@@ -604,7 +819,7 @@ impl ShapeState {
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Iterates over the selected manipulator groups exluding endpoints, returning whether their handles have mixed, colinear, or free angles.
|
||||
/// Iterates over the selected manipulator groups excluding endpoints, returning whether their handles have mixed, colinear, or free angles.
|
||||
/// If there are no points selected this function returns mixed.
|
||||
pub fn selected_manipulator_angles(&self, network_interface: &NodeNetworkInterface) -> ManipulatorAngle {
|
||||
// This iterator contains a bool indicating whether or not selected points' manipulator groups have colinear handles.
|
||||
@@ -632,6 +847,8 @@ impl ShapeState {
|
||||
return;
|
||||
};
|
||||
let handles = vector_data.all_connected(point_id).take(2).collect::<Vec<_>>();
|
||||
let non_zero_handles = handles.iter().filter(|handle| handle.length(vector_data) > 1e-6).count();
|
||||
let handle_segments = handles.iter().map(|handles| handles.segment).collect::<Vec<_>>();
|
||||
|
||||
// Grab the next and previous manipulator groups by simply looking at the next / previous index
|
||||
let points = handles.iter().map(|handle| vector_data.other_point(handle.segment, point_id));
|
||||
@@ -639,16 +856,24 @@ impl ShapeState {
|
||||
.map(|point| point.and_then(|point| ManipulatorPointId::Anchor(point).get_position(vector_data)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Use the position relative to the anchor
|
||||
let mut directions = anchor_positions
|
||||
.iter()
|
||||
.map(|position| position.map(|position| (position - anchor_position)).and_then(DVec2::try_normalize));
|
||||
let mut segment_angle = 0.;
|
||||
let mut segment_count = 0.;
|
||||
|
||||
// The direction of the handles is either the perpendicular vector to the sum of the anchors' positions or just the anchor's position (if only one)
|
||||
let mut handle_direction = match (directions.next().flatten(), directions.next().flatten()) {
|
||||
(Some(previous), Some(next)) => (previous - next).try_normalize().unwrap_or(next.perp()),
|
||||
(Some(val), None) | (None, Some(val)) => val,
|
||||
(None, None) => return,
|
||||
for segment in &handle_segments {
|
||||
let Some(angle) = calculate_segment_angle(point_id, *segment, vector_data, false) else {
|
||||
continue;
|
||||
};
|
||||
segment_angle += angle;
|
||||
segment_count += 1.;
|
||||
}
|
||||
|
||||
// For a non-endpoint anchor, handles are perpendicular to the average tangent of adjacent segments.(Refer:https://github.com/GraphiteEditor/Graphite/pull/2620#issuecomment-2881501494)
|
||||
let mut handle_direction = if segment_count > 1. {
|
||||
segment_angle /= segment_count;
|
||||
segment_angle += std::f64::consts::FRAC_PI_2;
|
||||
DVec2::new(segment_angle.cos(), segment_angle.sin())
|
||||
} else {
|
||||
DVec2::new(segment_angle.cos(), segment_angle.sin())
|
||||
};
|
||||
|
||||
// Set the manipulator to have colinear handles
|
||||
@@ -666,20 +891,41 @@ impl ShapeState {
|
||||
handle_direction *= -1.;
|
||||
}
|
||||
|
||||
// Push both in and out handles into the correct position
|
||||
for ((handle, sign), other_anchor) in handles.iter().zip([1., -1.]).zip(&anchor_positions) {
|
||||
// To find the length of the new tangent we just take the distance to the anchor and divide by 3 (pretty arbitrary)
|
||||
let Some(length) = other_anchor.map(|position| (position - anchor_position).length() / 3.) else {
|
||||
continue;
|
||||
if non_zero_handles != 0 {
|
||||
let [a, b] = handles.as_slice() else { return };
|
||||
let (non_zero_handle, zero_handle) = if a.length(vector_data) > 1e-6 { (a, b) } else { (b, a) };
|
||||
let Some(direction) = non_zero_handle
|
||||
.to_manipulator_point()
|
||||
.get_position(vector_data)
|
||||
.and_then(|position| (position - anchor_position).try_normalize())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let new_position = handle_direction * length * sign;
|
||||
let modification_type = handle.set_relative_position(new_position);
|
||||
let new_position = -direction * non_zero_handle.length(vector_data);
|
||||
let modification_type = zero_handle.set_relative_position(new_position);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
} else {
|
||||
// Push both in and out handles into the correct position
|
||||
for ((handle, sign), other_anchor) in handles.iter().zip([1., -1.]).zip(&anchor_positions) {
|
||||
let Some(anchor_vector) = other_anchor.map(|position| (position - anchor_position)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Create the opposite handle if it doesn't exist (if it is not a cubic segment)
|
||||
if handle.opposite().to_manipulator_point().get_position(vector_data).is_none() {
|
||||
let modification_type = handle.opposite().set_relative_position(DVec2::ZERO);
|
||||
let Some(unit_vector) = anchor_vector.try_normalize() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let projection = anchor_vector.length() * HANDLE_LENGTH_FACTOR * handle_direction.dot(unit_vector).abs();
|
||||
|
||||
let new_position = handle_direction * projection * sign;
|
||||
let modification_type = handle.set_relative_position(new_position);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// Create the opposite handle if it doesn't exist (if it is not a cubic segment)
|
||||
if handle.opposite().to_manipulator_point().get_position(vector_data).is_none() {
|
||||
let modification_type = handle.opposite().set_relative_position(DVec2::ZERO);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -729,7 +975,9 @@ impl ShapeState {
|
||||
let length = transform.transform_vector2(unselected_position - anchor).length();
|
||||
let position = transform.inverse().transform_vector2(direction * length);
|
||||
let modification_type = unselected_handle.set_relative_position(position);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
if (anchor - selected_position).length() > 1e-6 {
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
// If both handles are selected, average the angles of the handles
|
||||
else {
|
||||
@@ -775,6 +1023,7 @@ impl ShapeState {
|
||||
in_viewport_space: bool,
|
||||
was_alt_dragging: bool,
|
||||
opposite_handle_position: Option<DVec2>,
|
||||
skip_opposite_handle: bool,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
for (&layer, state) in &self.selected_shape_state {
|
||||
@@ -792,6 +1041,10 @@ impl ShapeState {
|
||||
let delta = delta_transform.inverse().transform_vector2(delta);
|
||||
|
||||
for &point in state.selected_points.iter() {
|
||||
if self.is_point_ignored(&point) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let handle = match point {
|
||||
ManipulatorPointId::Anchor(point) => {
|
||||
self.move_anchor(point, &vector_data, delta, layer, Some(state), responses);
|
||||
@@ -816,6 +1069,11 @@ impl ShapeState {
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
let Some(other) = vector_data.other_colinear_handle(handle) else { continue };
|
||||
|
||||
if skip_opposite_handle {
|
||||
continue;
|
||||
}
|
||||
|
||||
if state.is_selected(other.to_manipulator_point()) {
|
||||
// If two colinear handles are being dragged at the same time but not the anchor, it is necessary to break the colinear state.
|
||||
let handles = [handle, other];
|
||||
@@ -892,6 +1150,29 @@ impl ShapeState {
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
pub fn dissolve_segment(&self, responses: &mut VecDeque<Message>, layer: LayerNodeIdentifier, vector_data: &VectorData, segment: SegmentId, points: [PointId; 2]) {
|
||||
// Checking which point is terminal point
|
||||
let is_point1_terminal = vector_data.connected_count(points[0]) == 1;
|
||||
let is_point2_terminal = vector_data.connected_count(points[1]) == 1;
|
||||
|
||||
// Delete the segment and terminal points
|
||||
let modification_type = VectorModificationType::RemoveSegment { id: segment };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
for &handles in vector_data.colinear_manipulators.iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) {
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
if is_point1_terminal {
|
||||
let modification_type = VectorModificationType::RemovePoint { id: points[0] };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
if is_point2_terminal {
|
||||
let modification_type = VectorModificationType::RemovePoint { id: points[1] };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
|
||||
fn dissolve_anchor(anchor: PointId, responses: &mut VecDeque<Message>, layer: LayerNodeIdentifier, vector_data: &VectorData) -> Option<[(HandleId, PointId); 2]> {
|
||||
// Delete point
|
||||
let modification_type = VectorModificationType::RemovePoint { id: anchor };
|
||||
@@ -1134,6 +1415,42 @@ impl ShapeState {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn find_nearest_visible_point_indices(
|
||||
&mut self,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
mouse_position: DVec2,
|
||||
select_threshold: f64,
|
||||
path_overlay_mode: PathOverlayMode,
|
||||
frontier_handles_info: Option<HashMap<SegmentId, Vec<PointId>>>,
|
||||
) -> Option<(LayerNodeIdentifier, ManipulatorPointId)> {
|
||||
if self.selected_shape_state.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let select_threshold_squared = select_threshold.powi(2);
|
||||
|
||||
// Find the closest control point among all elements of shapes_to_modify
|
||||
for &layer in self.selected_shape_state.keys() {
|
||||
if let Some((manipulator_point_id, distance_squared)) = Self::closest_point_in_layer(network_interface, layer, mouse_position) {
|
||||
// Choose the first point under the threshold
|
||||
if distance_squared < select_threshold_squared {
|
||||
// Check if point is visible in current PathOverlayMode
|
||||
let vector_data = network_interface.compute_modified_vector(layer)?;
|
||||
let selected_segments = selected_segments(network_interface, self);
|
||||
let selected_points = self.selected_points().cloned().collect::<HashSet<_>>();
|
||||
|
||||
if !is_visible_point(manipulator_point_id, &vector_data, path_overlay_mode, frontier_handles_info, selected_segments, &selected_points) {
|
||||
return None;
|
||||
}
|
||||
|
||||
return Some((layer, manipulator_point_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
// TODO Use quadtree or some equivalent spatial acceleration structure to improve this to O(log(n))
|
||||
/// Find the closest manipulator, manipulator point, and distance so we can select path elements.
|
||||
/// Brute force comparison to determine which manipulator (handle or anchor) we want to select taking O(n) time.
|
||||
@@ -1199,11 +1516,6 @@ impl ShapeState {
|
||||
if distance_squared < closest_distance_squared {
|
||||
closest_distance_squared = distance_squared;
|
||||
|
||||
// 0.5 is half the line (center to side) but it's convenient to allow targeting slightly more than half the line width
|
||||
const STROKE_WIDTH_PERCENT: f64 = 0.7;
|
||||
|
||||
let stroke_width = graph_modification_utils::get_stroke_width(layer, network_interface).unwrap_or(1.) as f64 * STROKE_WIDTH_PERCENT;
|
||||
|
||||
// Convert to linear if handes are on top of control points
|
||||
if let bezier_rs::BezierHandles::Cubic { handle_start, handle_end } = bezier.handles {
|
||||
if handle_start.abs_diff_eq(bezier.start(), f64::EPSILON * 100.) && handle_end.abs_diff_eq(bezier.end(), f64::EPSILON * 100.) {
|
||||
@@ -1224,7 +1536,6 @@ impl ShapeState {
|
||||
t,
|
||||
bezier_point_to_viewport: screenspace,
|
||||
layer,
|
||||
stroke_width,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1352,6 +1663,7 @@ impl ShapeState {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a nearby clicked anchor point's handles between sharp (zero-length handles) and smooth (pulled-apart handle(s)).
|
||||
/// If both handles aren't zero-length, they are set that. If both are zero-length, they are stretched apart by a reasonable amount.
|
||||
/// This can can be activated by double clicking on an anchor with the Path tool.
|
||||
@@ -1376,50 +1688,53 @@ impl ShapeState {
|
||||
|
||||
let (id, anchor) = result?;
|
||||
let handles = vector_data.all_connected(id);
|
||||
let mut positions = handles
|
||||
let positions = handles
|
||||
.filter_map(|handle| handle.to_manipulator_point().get_position(&vector_data))
|
||||
.filter(|&handle| !anchor.abs_diff_eq(handle, 1e-5));
|
||||
.filter(|&handle| anchor.abs_diff_eq(handle, 1e-5))
|
||||
.count();
|
||||
|
||||
// Check by comparing the handle positions to the anchor if this manipulator group is a point
|
||||
let already_sharp = positions.next().is_none();
|
||||
if already_sharp {
|
||||
self.convert_manipulator_handles_to_colinear(&vector_data, id, responses, layer);
|
||||
} else {
|
||||
for handle in vector_data.all_connected(id) {
|
||||
let Some(bezier) = vector_data.segment_from_id(handle.segment) else { continue };
|
||||
for point in self.selected_points() {
|
||||
let Some(point_id) = point.as_anchor() else { continue };
|
||||
if positions != 0 {
|
||||
self.convert_manipulator_handles_to_colinear(&vector_data, point_id, responses, layer);
|
||||
} else {
|
||||
for handle in vector_data.all_connected(point_id) {
|
||||
let Some(bezier) = vector_data.segment_from_id(handle.segment) else { continue };
|
||||
|
||||
match bezier.handles {
|
||||
BezierHandles::Linear => {}
|
||||
BezierHandles::Quadratic { .. } => {
|
||||
let segment = handle.segment;
|
||||
// Convert to linear
|
||||
let modification_type = VectorModificationType::SetHandles { segment, handles: [None; 2] };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
match bezier.handles {
|
||||
BezierHandles::Linear => {}
|
||||
BezierHandles::Quadratic { .. } => {
|
||||
let segment = handle.segment;
|
||||
// Convert to linear
|
||||
let modification_type = VectorModificationType::SetHandles { segment, handles: [None; 2] };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// Set the manipulator to have non-colinear handles
|
||||
for &handles in &vector_data.colinear_manipulators {
|
||||
if handles.contains(&HandleId::primary(segment)) {
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
// Set the manipulator to have non-colinear handles
|
||||
for &handles in &vector_data.colinear_manipulators {
|
||||
if handles.contains(&HandleId::primary(segment)) {
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
BezierHandles::Cubic { .. } => {
|
||||
// Set handle position to anchor position
|
||||
let modification_type = handle.set_relative_position(DVec2::ZERO);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
BezierHandles::Cubic { .. } => {
|
||||
// Set handle position to anchor position
|
||||
let modification_type = handle.set_relative_position(DVec2::ZERO);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// Set the manipulator to have non-colinear handles
|
||||
for &handles in &vector_data.colinear_manipulators {
|
||||
if handles.contains(&handle) {
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
// Set the manipulator to have non-colinear handles
|
||||
for &handles in &vector_data.colinear_manipulators {
|
||||
if handles.contains(&handle) {
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
Some(true)
|
||||
};
|
||||
@@ -1433,7 +1748,17 @@ impl ShapeState {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn select_all_in_shape(&mut self, network_interface: &NodeNetworkInterface, selection_shape: SelectionShape, selection_change: SelectionChange) {
|
||||
pub fn select_all_in_shape(
|
||||
&mut self,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
selection_shape: SelectionShape,
|
||||
selection_change: SelectionChange,
|
||||
path_overlay_mode: PathOverlayMode,
|
||||
frontier_handles_info: Option<HashMap<SegmentId, Vec<PointId>>>,
|
||||
) {
|
||||
let selected_points = self.selected_points().cloned().collect::<HashSet<_>>();
|
||||
let selected_segments = selected_segments(network_interface, self);
|
||||
|
||||
for (&layer, state) in &mut self.selected_shape_state {
|
||||
if selection_change == SelectionChange::Clear {
|
||||
state.clear_points()
|
||||
@@ -1476,13 +1801,17 @@ impl ShapeState {
|
||||
};
|
||||
|
||||
if select {
|
||||
match selection_change {
|
||||
SelectionChange::Shrink => state.deselect_point(id),
|
||||
_ => {
|
||||
// Select only the handles which are of nonzero length
|
||||
if let Some(handle) = id.as_handle() {
|
||||
if handle.length(&vector_data) > 0. {
|
||||
state.select_point(id)
|
||||
let is_visible_handle = is_visible_point(id, &vector_data, path_overlay_mode, frontier_handles_info.clone(), selected_segments.clone(), &selected_points);
|
||||
|
||||
if is_visible_handle {
|
||||
match selection_change {
|
||||
SelectionChange::Shrink => state.deselect_point(id),
|
||||
_ => {
|
||||
// Select only the handles which are of nonzero length
|
||||
if let Some(handle) = id.as_handle() {
|
||||
if handle.length(&vector_data) > 0. {
|
||||
state.select_point(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod number_of_points_handle;
|
||||
pub mod point_radius_handle;
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
use crate::consts::{GIZMO_HIDE_THRESHOLD, NUMBER_OF_POINTS_HANDLE_SPOKE_EXTENSION, NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH, POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::prelude::Responses;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, FrontendMessage, InputPreprocessorMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{
|
||||
extract_polygon_parameters, extract_star_parameters, inside_polygon, inside_star, polygon_vertex_position, star_vertex_position,
|
||||
};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub enum NumberOfPointsHandleState {
|
||||
#[default]
|
||||
Inactive,
|
||||
Hover,
|
||||
Dragging,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NumberOfPointsHandle {
|
||||
pub layer: Option<LayerNodeIdentifier>,
|
||||
pub initial_points: u32,
|
||||
pub handle_state: NumberOfPointsHandleState,
|
||||
}
|
||||
|
||||
impl NumberOfPointsHandle {
|
||||
pub fn cleanup(&mut self) {
|
||||
self.handle_state = NumberOfPointsHandleState::Inactive;
|
||||
self.layer = None;
|
||||
}
|
||||
|
||||
pub fn update_state(&mut self, state: NumberOfPointsHandleState) {
|
||||
self.handle_state = state;
|
||||
}
|
||||
|
||||
pub fn is_hovering(&self) -> bool {
|
||||
self.handle_state == NumberOfPointsHandleState::Hover
|
||||
}
|
||||
|
||||
pub fn is_dragging(&self) -> bool {
|
||||
self.handle_state == NumberOfPointsHandleState::Dragging
|
||||
}
|
||||
|
||||
pub fn handle_actions(
|
||||
&mut self,
|
||||
document: &DocumentMessageHandler,
|
||||
input: &InputPreprocessorMessageHandler,
|
||||
mouse_position: DVec2,
|
||||
overlay_context: &mut OverlayContext,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
if input.keyboard.key(Key::Control) {
|
||||
return;
|
||||
}
|
||||
|
||||
match &self.handle_state {
|
||||
NumberOfPointsHandleState::Inactive => {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let layers = selected_nodes.selected_visible_and_unlocked_layers(&document.network_interface).filter(|layer| {
|
||||
graph_modification_utils::get_star_id(*layer, &document.network_interface).is_some() || graph_modification_utils::get_polygon_id(*layer, &document.network_interface).is_some()
|
||||
});
|
||||
for layer in layers {
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
let point_on_max_radius = star_vertex_position(viewport, 0, n, radius1, radius2);
|
||||
|
||||
if mouse_position.distance(center) < NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH && point_on_max_radius.distance(center) > GIZMO_HIDE_THRESHOLD {
|
||||
self.layer = Some(layer);
|
||||
self.initial_points = n;
|
||||
self.update_state(NumberOfPointsHandleState::Hover);
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::EWResize });
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
let point_on_max_radius = polygon_vertex_position(viewport, 0, n, radius);
|
||||
|
||||
if mouse_position.distance(center) < NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH && point_on_max_radius.distance(center) > GIZMO_HIDE_THRESHOLD {
|
||||
self.layer = Some(layer);
|
||||
self.initial_points = n;
|
||||
self.update_state(NumberOfPointsHandleState::Hover);
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::EWResize });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NumberOfPointsHandleState::Hover | NumberOfPointsHandleState::Dragging => {
|
||||
let Some(layer) = self.layer else { return };
|
||||
|
||||
let Some((n, radius)) = extract_star_parameters(Some(layer), document)
|
||||
.map(|(n, r1, r2)| (n, r1.max(r2)))
|
||||
.or_else(|| extract_polygon_parameters(Some(layer), document))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
if mouse_position.distance(center) > NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH && matches!(&self.handle_state, NumberOfPointsHandleState::Hover) {
|
||||
self.update_state(NumberOfPointsHandleState::Inactive);
|
||||
self.layer = None;
|
||||
self.draw_spokes(center, viewport, n, radius, overlay_context);
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn overlays(
|
||||
&mut self,
|
||||
document: &DocumentMessageHandler,
|
||||
input: &InputPreprocessorMessageHandler,
|
||||
shape_editor: &mut &mut ShapeState,
|
||||
mouse_position: DVec2,
|
||||
overlay_context: &mut OverlayContext,
|
||||
) {
|
||||
if input.keyboard.key(Key::Control) {
|
||||
return;
|
||||
}
|
||||
|
||||
match &self.handle_state {
|
||||
NumberOfPointsHandleState::Inactive => {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let layers = selected_nodes.selected_visible_and_unlocked_layers(&document.network_interface).filter(|layer| {
|
||||
graph_modification_utils::get_star_id(*layer, &document.network_interface).is_some() || graph_modification_utils::get_polygon_id(*layer, &document.network_interface).is_some()
|
||||
});
|
||||
for layer in layers {
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let radius = radius1.max(radius2);
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, mouse_position, POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD) {
|
||||
if closest_segment.layer() == layer {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let point_on_max_radius = star_vertex_position(viewport, 0, n, radius1, radius2);
|
||||
|
||||
if inside_star(viewport, n, radius1, radius2, mouse_position) && point_on_max_radius.distance(center) > GIZMO_HIDE_THRESHOLD {
|
||||
self.draw_spokes(center, viewport, n, radius, overlay_context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, mouse_position, POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD) {
|
||||
if closest_segment.layer() == layer {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let point_on_max_radius = polygon_vertex_position(viewport, 0, n, radius);
|
||||
|
||||
if inside_polygon(viewport, n, radius, mouse_position) && point_on_max_radius.distance(center) > GIZMO_HIDE_THRESHOLD {
|
||||
self.draw_spokes(center, viewport, n, radius, overlay_context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NumberOfPointsHandleState::Hover | NumberOfPointsHandleState::Dragging => {
|
||||
let Some(layer) = self.layer else { return };
|
||||
|
||||
let Some((n, radius)) = extract_star_parameters(Some(layer), document)
|
||||
.map(|(n, r1, r2)| (n, r1.max(r2)))
|
||||
.or_else(|| extract_polygon_parameters(Some(layer), document))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
self.draw_spokes(center, viewport, n, radius, overlay_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_spokes(&self, center: DVec2, viewport: DAffine2, n: u32, radius: f64, overlay_context: &mut OverlayContext) {
|
||||
for i in 0..n {
|
||||
let angle = ((i as f64) * TAU) / (n as f64);
|
||||
|
||||
let point = viewport.transform_point2(DVec2 {
|
||||
x: radius * angle.sin(),
|
||||
y: -radius * angle.cos(),
|
||||
});
|
||||
|
||||
let Some(direction) = (point - center).try_normalize() else { continue };
|
||||
|
||||
// If the user zooms out such that shape is very small hide the gizmo
|
||||
if point.distance(center) < GIZMO_HIDE_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
let end_point = direction * NUMBER_OF_POINTS_HANDLE_SPOKE_LENGTH;
|
||||
if matches!(self.handle_state, NumberOfPointsHandleState::Hover | NumberOfPointsHandleState::Dragging) {
|
||||
overlay_context.line(center, end_point * NUMBER_OF_POINTS_HANDLE_SPOKE_EXTENSION + center, None, None);
|
||||
} else {
|
||||
overlay_context.line(center, end_point + center, None, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_number_of_sides(&self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>, drag_start: DVec2) {
|
||||
let delta = input.mouse.position - document.metadata().document_to_viewport.transform_point2(drag_start);
|
||||
let sign = (input.mouse.position.x - document.metadata().document_to_viewport.transform_point2(drag_start).x).signum();
|
||||
let net_delta = (delta.length() / 25.).round() * sign;
|
||||
|
||||
let Some(layer) = self.layer else { return };
|
||||
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface).or(graph_modification_utils::get_polygon_id(layer, &document.network_interface)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_point_count = ((self.initial_points as i32) + (net_delta as i32)).max(3);
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::U32(new_point_count as u32), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
use crate::consts::{COLOR_OVERLAY_RED, GIZMO_HIDE_THRESHOLD, POINT_RADIUS_HANDLE_SNAP_THRESHOLD};
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::prelude::Responses;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{draw_snapping_ticks, extract_polygon_parameters, extract_star_parameters, polygon_vertex_position, star_vertex_position};
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_4, PI, SQRT_2};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub enum PointRadiusHandleState {
|
||||
#[default]
|
||||
Inactive,
|
||||
Hover,
|
||||
Dragging,
|
||||
Snapped(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PointRadiusHandle {
|
||||
pub layer: Option<LayerNodeIdentifier>,
|
||||
point: u32,
|
||||
radius_index: usize,
|
||||
snap_radii: Vec<f64>,
|
||||
initial_radius: f64,
|
||||
handle_state: PointRadiusHandleState,
|
||||
}
|
||||
|
||||
impl PointRadiusHandle {
|
||||
pub fn cleanup(&mut self) {
|
||||
self.handle_state = PointRadiusHandleState::Inactive;
|
||||
self.snap_radii.clear();
|
||||
self.layer = None;
|
||||
}
|
||||
|
||||
pub fn is_inactive(&self) -> bool {
|
||||
self.handle_state == PointRadiusHandleState::Inactive
|
||||
}
|
||||
|
||||
pub fn hovered(&self) -> bool {
|
||||
self.handle_state == PointRadiusHandleState::Hover
|
||||
}
|
||||
|
||||
pub fn update_state(&mut self, state: PointRadiusHandleState) {
|
||||
self.handle_state = state;
|
||||
}
|
||||
|
||||
pub fn handle_actions(&mut self, document: &DocumentMessageHandler, mouse_position: DVec2) {
|
||||
match &self.handle_state {
|
||||
PointRadiusHandleState::Inactive => {
|
||||
for layer in document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.filter(|layer| {
|
||||
graph_modification_utils::get_star_id(*layer, &document.network_interface).is_some() || graph_modification_utils::get_polygon_id(*layer, &document.network_interface).is_some()
|
||||
}) {
|
||||
// Draw the point handle gizmo for the star shape
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
for i in 0..2 * n {
|
||||
let (radius, radius_index) = if i % 2 == 0 { (radius1, 2) } else { (radius2, 3) };
|
||||
let point = star_vertex_position(viewport, i as i32, n, radius1, radius2);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
// If the user zooms out such that shape is very small hide the gizmo
|
||||
if point.distance(center) < GIZMO_HIDE_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
if point.distance(mouse_position) < 5. {
|
||||
self.radius_index = radius_index;
|
||||
self.layer = Some(layer);
|
||||
self.point = i;
|
||||
self.snap_radii = Self::calculate_snap_radii(document, layer, radius_index);
|
||||
self.initial_radius = radius;
|
||||
self.update_state(PointRadiusHandleState::Hover);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the point handle gizmo for the polygon shape
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
for i in 0..n {
|
||||
let point = polygon_vertex_position(viewport, i as i32, n, radius);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
// If the user zooms out so the shape is very small, hide the gizmo
|
||||
if point.distance(center) < GIZMO_HIDE_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
if point.distance(mouse_position) < 5. {
|
||||
self.radius_index = 2;
|
||||
self.layer = Some(layer);
|
||||
self.point = i;
|
||||
self.snap_radii.clear();
|
||||
self.initial_radius = radius;
|
||||
self.update_state(PointRadiusHandleState::Hover);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PointRadiusHandleState::Dragging | PointRadiusHandleState::Hover => {
|
||||
let Some(layer) = self.layer else { return };
|
||||
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let point = star_vertex_position(viewport, self.point as i32, n, radius1, radius2);
|
||||
|
||||
if matches!(&self.handle_state, PointRadiusHandleState::Hover) && (mouse_position - point).length() > 5. {
|
||||
self.update_state(PointRadiusHandleState::Inactive);
|
||||
self.layer = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let point = polygon_vertex_position(viewport, self.point as i32, n, radius);
|
||||
|
||||
if matches!(&self.handle_state, PointRadiusHandleState::Hover) && (mouse_position - point).length() > 5. {
|
||||
self.update_state(PointRadiusHandleState::Inactive);
|
||||
self.layer = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
PointRadiusHandleState::Snapped(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, other_gizmo_active: bool, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, mouse_position: DVec2, overlay_context: &mut OverlayContext) {
|
||||
match &self.handle_state {
|
||||
PointRadiusHandleState::Inactive => {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let layers = selected_nodes.selected_visible_and_unlocked_layers(&document.network_interface).filter(|layer| {
|
||||
graph_modification_utils::get_star_id(*layer, &document.network_interface).is_some() || graph_modification_utils::get_polygon_id(*layer, &document.network_interface).is_some()
|
||||
});
|
||||
for layer in layers {
|
||||
if other_gizmo_active {
|
||||
return;
|
||||
}
|
||||
// Draw the point handle gizmo for the star shape
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
for i in 0..(2 * n) {
|
||||
let point = star_vertex_position(viewport, i as i32, n, radius1, radius2);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
let viewport_diagonal = input.viewport_bounds.size().length();
|
||||
|
||||
// If the user zooms out such that shape is very small hide the gizmo
|
||||
if point.distance(center) < GIZMO_HIDE_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
if point.distance(mouse_position) < 5. {
|
||||
let Some(direction) = (point - center).try_normalize() else { continue };
|
||||
|
||||
overlay_context.manipulator_handle(point, true, None);
|
||||
let angle = ((i as f64) * PI) / (n as f64);
|
||||
overlay_context.line(center, center + direction * viewport_diagonal, None, None);
|
||||
|
||||
draw_snapping_ticks(&self.snap_radii, direction, viewport, angle, overlay_context);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
overlay_context.manipulator_handle(point, false, None);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the point handle gizmo for the Polygon shape
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
for i in 0..n {
|
||||
let point = polygon_vertex_position(viewport, i as i32, n, radius);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
let viewport_diagonal = input.viewport_bounds.size().length();
|
||||
|
||||
// If the user zooms out such that shape is very small hide the gizmo
|
||||
if point.distance(center) < GIZMO_HIDE_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
if point.distance(mouse_position) < 5. {
|
||||
let Some(direction) = (point - center).try_normalize() else { continue };
|
||||
|
||||
overlay_context.manipulator_handle(point, true, None);
|
||||
overlay_context.line(center, center + direction * viewport_diagonal, None, None);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
overlay_context.manipulator_handle(point, false, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PointRadiusHandleState::Dragging | PointRadiusHandleState::Hover => {
|
||||
let Some(layer) = self.layer else { return };
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
let viewport_diagonal = input.viewport_bounds.size().length();
|
||||
|
||||
if let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) {
|
||||
let angle = ((self.point as f64) * PI) / (n as f64);
|
||||
let point = star_vertex_position(viewport, self.point as i32, n, radius1, radius2);
|
||||
|
||||
let Some(direction) = (point - center).try_normalize() else { return };
|
||||
|
||||
// Draws the ray from the center to the dragging point extending till the viewport
|
||||
overlay_context.manipulator_handle(point, true, None);
|
||||
overlay_context.line(center, center + direction * viewport_diagonal, None, None);
|
||||
|
||||
// Makes the tick marks for snapping
|
||||
|
||||
// Only show the snapping ticks if the radius is positive
|
||||
if (mouse_position - center).dot(direction) >= 0. {
|
||||
draw_snapping_ticks(&self.snap_radii, direction, viewport, angle, overlay_context);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) {
|
||||
let point = polygon_vertex_position(viewport, self.point as i32, n, radius);
|
||||
|
||||
let Some(direction) = (point - center).try_normalize() else { return };
|
||||
|
||||
// Draws the ray from the center to the dragging point and extending until the viewport edge is reached
|
||||
overlay_context.manipulator_handle(point, true, None);
|
||||
overlay_context.line(center, center + direction * viewport_diagonal, None, None);
|
||||
}
|
||||
}
|
||||
PointRadiusHandleState::Snapped(snapping_index) => {
|
||||
let Some(layer) = self.layer else { return };
|
||||
let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) else { return };
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
let center = viewport.transform_point2(DVec2::ZERO);
|
||||
|
||||
match snapping_index {
|
||||
// Make a triangle with the previous two points
|
||||
0 => {
|
||||
let before_outer_position = star_vertex_position(viewport, (self.point as i32) - 2, n, radius1, radius2);
|
||||
let outer_position = star_vertex_position(viewport, (self.point as i32) - 1, n, radius1, radius2);
|
||||
let point_position = star_vertex_position(viewport, self.point as i32, n, radius1, radius2);
|
||||
|
||||
overlay_context.line(before_outer_position, outer_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(outer_position, point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
|
||||
let Some(l1_direction) = (before_outer_position - outer_position).try_normalize() else { return };
|
||||
let Some(l2_direction) = (point_position - outer_position).try_normalize() else { return };
|
||||
let Some(direction) = (center - outer_position).try_normalize() else { return };
|
||||
|
||||
let l1 = 0.2 * (before_outer_position - outer_position).length();
|
||||
let new_point = SQRT_2 * l1 * direction + outer_position;
|
||||
|
||||
let before_outer_position = l1 * l1_direction + outer_position;
|
||||
let point_position = l1 * l2_direction + outer_position;
|
||||
|
||||
overlay_context.line(before_outer_position, new_point, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(new_point, point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
}
|
||||
1 => {
|
||||
let before_outer_position = star_vertex_position(viewport, (self.point as i32) - 1, n, radius1, radius2);
|
||||
let after_point_position = star_vertex_position(viewport, (self.point as i32) + 1, n, radius1, radius2);
|
||||
let point_position = star_vertex_position(viewport, self.point as i32, n, radius1, radius2);
|
||||
|
||||
overlay_context.line(before_outer_position, point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(point_position, after_point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
|
||||
let Some(l1_direction) = (before_outer_position - point_position).try_normalize() else { return };
|
||||
let Some(l2_direction) = (after_point_position - point_position).try_normalize() else { return };
|
||||
let Some(direction) = (center - point_position).try_normalize() else { return };
|
||||
|
||||
let l1 = 0.2 * (before_outer_position - point_position).length();
|
||||
let new_point = SQRT_2 * l1 * direction + point_position;
|
||||
|
||||
let before_outer_position = l1 * l1_direction + point_position;
|
||||
let after_point_position = l1 * l2_direction + point_position;
|
||||
|
||||
overlay_context.line(before_outer_position, new_point, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(new_point, after_point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
}
|
||||
i => {
|
||||
// Use `self.point` as an absolute reference, as it matches the index of the star's vertices starting from 0
|
||||
if i % 2 != 0 {
|
||||
// Flipped case
|
||||
let point_position = star_vertex_position(viewport, self.point as i32, n, radius1, radius2);
|
||||
let target_index = (1 - (*i as i32)).abs() + (self.point as i32);
|
||||
let target_point_position = star_vertex_position(viewport, target_index, n, radius1, radius2);
|
||||
|
||||
let mirrored_index = 2 * (self.point as i32) - target_index;
|
||||
let mirrored = star_vertex_position(viewport, mirrored_index, n, radius1, radius2);
|
||||
|
||||
overlay_context.line(point_position, target_point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(point_position, mirrored, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
} else {
|
||||
let outer_index = (self.point as i32) - 1;
|
||||
let outer_position = star_vertex_position(viewport, outer_index, n, radius1, radius2);
|
||||
|
||||
// The vertex which is colinear with the point we are dragging and its previous outer vertex
|
||||
let target_index = (self.point as i32) + (*i as i32) - 1;
|
||||
let target_point_position = star_vertex_position(viewport, target_index, n, radius1, radius2);
|
||||
|
||||
let mirrored_index = 2 * outer_index - target_index;
|
||||
|
||||
let mirrored = star_vertex_position(viewport, mirrored_index, n, radius1, radius2);
|
||||
|
||||
overlay_context.line(outer_position, target_point_position, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
overlay_context.line(outer_position, mirrored, Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_snap_radii(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_index: usize) -> Vec<f64> {
|
||||
let mut snap_radii = Vec::new();
|
||||
|
||||
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs("Star") else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let other_index = if radius_index == 3 { 2 } else { 3 };
|
||||
let Some(&TaggedValue::F64(other_radius)) = node_inputs[other_index].as_value() else {
|
||||
return snap_radii;
|
||||
};
|
||||
let Some(&TaggedValue::U32(n)) = node_inputs[1].as_value() else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
// Inner radius for 90°
|
||||
let b = FRAC_PI_4 * 3. - PI / (n as f64);
|
||||
let angle = b.sin();
|
||||
let required_radius = (other_radius / angle) * FRAC_1_SQRT_2;
|
||||
|
||||
snap_radii.push(required_radius);
|
||||
|
||||
// Also add the case where the radius exceeds the other radius (the "flipped" case)
|
||||
let flipped = other_radius * angle * SQRT_2;
|
||||
snap_radii.push(flipped);
|
||||
|
||||
for i in 1..n {
|
||||
let n = n as f64;
|
||||
let i = i as f64;
|
||||
let denominator = 2. * ((PI * (i - 1.)) / n).cos() * ((PI * i) / n).sin();
|
||||
let numerator = ((2. * PI * i) / n).sin();
|
||||
let factor = numerator / denominator;
|
||||
|
||||
if factor < 0. {
|
||||
break;
|
||||
}
|
||||
|
||||
if other_radius * factor > 1e-6 {
|
||||
snap_radii.push(other_radius * factor);
|
||||
}
|
||||
|
||||
snap_radii.push((other_radius * 1.) / factor);
|
||||
}
|
||||
|
||||
snap_radii
|
||||
}
|
||||
|
||||
fn check_snapping(&self, new_radius: f64, original_radius: f64) -> Option<(usize, f64)> {
|
||||
self.snap_radii
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, rad)| (**rad - new_radius).abs() < POINT_RADIUS_HANDLE_SNAP_THRESHOLD)
|
||||
.min_by(|(i_a, a), (i_b, b)| {
|
||||
let dist_a = (**a - new_radius).abs();
|
||||
let dist_b = (**b - new_radius).abs();
|
||||
|
||||
// Check if either index is 0 or 1 and prioritize them
|
||||
match (*i_a == 0 || *i_a == 1, *i_b == 0 || *i_b == 1) {
|
||||
(true, false) => std::cmp::Ordering::Less, // a is priority index, b is not
|
||||
(false, true) => std::cmp::Ordering::Greater, // b is priority index, a is not
|
||||
_ => dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal), // normal comparison
|
||||
}
|
||||
})
|
||||
.map(|(i, rad)| (i, *rad - original_radius))
|
||||
}
|
||||
|
||||
pub fn update_inner_radius(
|
||||
&mut self,
|
||||
document: &DocumentMessageHandler,
|
||||
input: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
responses: &mut VecDeque<Message>,
|
||||
drag_start: DVec2,
|
||||
) {
|
||||
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface).or(graph_modification_utils::get_polygon_id(layer, &document.network_interface)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let transform = document.network_interface.document_metadata().transform_to_viewport(layer);
|
||||
let center = transform.transform_point2(DVec2::ZERO);
|
||||
let radius_index = self.radius_index;
|
||||
|
||||
let original_radius = self.initial_radius;
|
||||
|
||||
let delta = input.mouse.position - document.metadata().document_to_viewport.transform_point2(drag_start);
|
||||
let radius = document.metadata().document_to_viewport.transform_point2(drag_start) - center;
|
||||
let projection = delta.project_onto(radius);
|
||||
let sign = radius.dot(delta).signum();
|
||||
|
||||
let mut net_delta = projection.length() * sign;
|
||||
let new_radius = original_radius + net_delta;
|
||||
|
||||
self.update_state(PointRadiusHandleState::Dragging);
|
||||
if let Some((index, snapped_delta)) = self.check_snapping(new_radius, original_radius) {
|
||||
net_delta = snapped_delta;
|
||||
self.update_state(PointRadiusHandleState::Snapped(index));
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_index),
|
||||
input: NodeInput::value(TaggedValue::F64(original_radius + net_delta), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::shape_utility::ShapeToolModifierKey;
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Ellipse;
|
||||
|
||||
impl Ellipse {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_document_node_type("Ellipse").expect("Ellipse node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(0.5), false)), Some(NodeInput::value(TaggedValue::F64(0.5), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
document: &DocumentMessageHandler,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
shape_tool_data: &mut ShapeToolData,
|
||||
modifier: ShapeToolModifierKey,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let [center, lock_ratio, _, _] = modifier;
|
||||
|
||||
if let Some([start, end]) = shape_tool_data.data.calculate_points(document, ipp, center, lock_ratio) {
|
||||
let Some(node_id) = graph_modification_utils::get_ellipse_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::F64(((start.x - end.x) / 2.).abs()), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(((start.y - end.y) / 2.).abs()), false),
|
||||
});
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(start.midpoint(end)),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_ellipse {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::vector::generator_nodes::ellipse;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct ResolvedEllipse {
|
||||
radius_x: f64,
|
||||
radius_y: f64,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
async fn get_ellipse(editor: &mut EditorTestUtils) -> Vec<ResolvedEllipse> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
let document = editor.active_document();
|
||||
let layers = document.metadata().all_layers();
|
||||
layers
|
||||
.filter_map(|layer| {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::protonode_identifier())?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_simple() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Ellipse, 10., 10., 19., 0., ModifierKeys::empty()).await;
|
||||
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 1);
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(
|
||||
ellipse[0],
|
||||
ResolvedEllipse {
|
||||
radius_x: 4.5,
|
||||
radius_y: 5.,
|
||||
transform: DAffine2::from_translation(DVec2::new(14.5, 5.)) // Uses center
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_circle() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Ellipse, 10., 10., -10., 11., ModifierKeys::SHIFT).await;
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(
|
||||
ellipse[0],
|
||||
ResolvedEllipse {
|
||||
radius_x: 10.,
|
||||
radius_y: 10.,
|
||||
transform: DAffine2::from_translation(DVec2::new(0., 20.)) // Uses center
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_square_rotated() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(NavigationMessage::CanvasTiltSet {
|
||||
// 45 degree rotation of content clockwise
|
||||
angle_radians: f64::consts::FRAC_PI_4,
|
||||
})
|
||||
.await;
|
||||
editor.drag_tool(ToolType::Ellipse, 0., 0., 1., 10., ModifierKeys::SHIFT).await; // Viewport coordinates
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
println!("{ellipse:?}");
|
||||
assert_eq!(ellipse[0].radius_x, 5.);
|
||||
assert_eq!(ellipse[0].radius_y, 5.);
|
||||
|
||||
assert!(
|
||||
ellipse[0]
|
||||
.transform
|
||||
.abs_diff_eq(DAffine2::from_angle_translation(-f64::consts::FRAC_PI_4, DVec2::X * f64::consts::FRAC_1_SQRT_2 * 10.), 0.001)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_center_square_rotated() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(NavigationMessage::CanvasTiltSet {
|
||||
// 45 degree rotation of content clockwise
|
||||
angle_radians: f64::consts::FRAC_PI_4,
|
||||
})
|
||||
.await;
|
||||
editor.drag_tool(ToolType::Ellipse, 0., 0., 1., 10., ModifierKeys::SHIFT | ModifierKeys::ALT).await; // Viewport coordinates
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(ellipse[0].radius_x, 10.);
|
||||
assert_eq!(ellipse[0].radius_y, 10.);
|
||||
assert!(ellipse[0].transform.abs_diff_eq(DAffine2::from_angle(-f64::consts::FRAC_PI_4), 0.001));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_cancel() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool_cancel_rmb(ToolType::Ellipse).await;
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
use super::shape_utility::ShapeToolModifierKey;
|
||||
use crate::consts::{BOUNDS_SELECT_THRESHOLD, LINE_ROTATE_SNAP_ANGLE};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
pub use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapTypeConfiguration};
|
||||
use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, Default)]
|
||||
pub enum LineEnd {
|
||||
#[default]
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LineToolData {
|
||||
pub drag_start: DVec2,
|
||||
pub drag_current: DVec2,
|
||||
pub angle: f64,
|
||||
pub weight: f64,
|
||||
pub selected_layers_with_position: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
||||
pub editing_layer: Option<LayerNodeIdentifier>,
|
||||
pub dragging_endpoint: Option<LineEnd>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Line;
|
||||
|
||||
impl Line {
|
||||
pub fn create_node(document: &DocumentMessageHandler, drag_start: DVec2) -> NodeTemplate {
|
||||
let node_type = resolve_document_node_type("Line").expect("Line node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::DVec2(document.metadata().document_to_viewport.transform_point2(drag_start)), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(document.metadata().document_to_viewport.transform_point2(drag_start)), false)),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
document: &DocumentMessageHandler,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
shape_tool_data: &mut ShapeToolData,
|
||||
modifier: ShapeToolModifierKey,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let [center, _, lock_angle, snap_angle] = modifier;
|
||||
|
||||
shape_tool_data.line_data.drag_current = ipp.mouse.position;
|
||||
|
||||
let keyboard = &ipp.keyboard;
|
||||
let ignore = [layer];
|
||||
let snap_data = SnapData::ignore(document, ipp, &ignore);
|
||||
let mut document_points = generate_line(shape_tool_data, snap_data, keyboard.key(lock_angle), keyboard.key(snap_angle), keyboard.key(center));
|
||||
|
||||
if shape_tool_data.line_data.dragging_endpoint == Some(LineEnd::Start) {
|
||||
document_points.swap(0, 1);
|
||||
}
|
||||
|
||||
let Some(node_id) = graph_modification_utils::get_line_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::DVec2(document_points[0]), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::DVec2(document_points[1]), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
pub fn overlays(document: &DocumentMessageHandler, shape_tool_data: &mut ShapeToolData, overlay_context: &mut OverlayContext) {
|
||||
shape_tool_data.line_data.selected_layers_with_position = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs("Line")?;
|
||||
|
||||
let (Some(&TaggedValue::DVec2(start)), Some(&TaggedValue::DVec2(end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let [viewport_start, viewport_end] = [start, end].map(|point| document.metadata().transform_to_viewport(layer).transform_point2(point));
|
||||
if !start.abs_diff_eq(end, f64::EPSILON * 1000.) {
|
||||
overlay_context.line(viewport_start, viewport_end, None, None);
|
||||
overlay_context.square(viewport_start, Some(6.), None, None);
|
||||
overlay_context.square(viewport_end, Some(6.), None, None);
|
||||
}
|
||||
|
||||
Some((layer, [start, end]))
|
||||
})
|
||||
.collect::<HashMap<LayerNodeIdentifier, [DVec2; 2]>>();
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_line(tool_data: &mut ShapeToolData, snap_data: SnapData, lock_angle: bool, snap_angle: bool, center: bool) -> [DVec2; 2] {
|
||||
let document_to_viewport = snap_data.document.metadata().document_to_viewport;
|
||||
let mut document_points = [tool_data.data.drag_start, document_to_viewport.inverse().transform_point2(tool_data.line_data.drag_current)];
|
||||
|
||||
let mut angle = -(document_points[1] - document_points[0]).angle_to(DVec2::X);
|
||||
let mut line_length = (document_points[1] - document_points[0]).length();
|
||||
|
||||
if lock_angle {
|
||||
angle = tool_data.line_data.angle;
|
||||
} else if snap_angle {
|
||||
let snap_resolution = LINE_ROTATE_SNAP_ANGLE.to_radians();
|
||||
angle = (angle / snap_resolution).round() * snap_resolution;
|
||||
}
|
||||
|
||||
tool_data.line_data.angle = angle;
|
||||
|
||||
if lock_angle {
|
||||
let angle_vec = DVec2::new(angle.cos(), angle.sin());
|
||||
line_length = (document_points[1] - document_points[0]).dot(angle_vec);
|
||||
}
|
||||
|
||||
document_points[1] = document_points[0] + line_length * DVec2::new(angle.cos(), angle.sin());
|
||||
|
||||
let constrained = snap_angle || lock_angle;
|
||||
let snap = &mut tool_data.data.snap_manager;
|
||||
|
||||
let near_point = SnapCandidatePoint::handle_neighbors(document_points[1], [tool_data.data.drag_start]);
|
||||
let far_point = SnapCandidatePoint::handle_neighbors(2. * document_points[0] - document_points[1], [tool_data.data.drag_start]);
|
||||
let config = SnapTypeConfiguration::default();
|
||||
|
||||
if constrained {
|
||||
let constraint = SnapConstraint::Line {
|
||||
origin: document_points[0],
|
||||
direction: document_points[1] - document_points[0],
|
||||
};
|
||||
if center {
|
||||
let snapped = snap.constrained_snap(&snap_data, &near_point, constraint, config);
|
||||
let snapped_far = snap.constrained_snap(&snap_data, &far_point, constraint, config);
|
||||
let best = if snapped_far.other_snap_better(&snapped) { snapped } else { snapped_far };
|
||||
document_points[1] = document_points[0] * 2. - best.snapped_point_document;
|
||||
document_points[0] = best.snapped_point_document;
|
||||
snap.update_indicator(best);
|
||||
} else {
|
||||
let snapped = snap.constrained_snap(&snap_data, &near_point, constraint, config);
|
||||
document_points[1] = snapped.snapped_point_document;
|
||||
snap.update_indicator(snapped);
|
||||
}
|
||||
} else if center {
|
||||
let snapped = snap.free_snap(&snap_data, &near_point, config);
|
||||
let snapped_far = snap.free_snap(&snap_data, &far_point, config);
|
||||
let best = if snapped_far.other_snap_better(&snapped) { snapped } else { snapped_far };
|
||||
document_points[1] = document_points[0] * 2. - best.snapped_point_document;
|
||||
document_points[0] = best.snapped_point_document;
|
||||
snap.update_indicator(best);
|
||||
} else {
|
||||
let snapped = snap.free_snap(&snap_data, &near_point, config);
|
||||
document_points[1] = snapped.snapped_point_document;
|
||||
snap.update_indicator(snapped);
|
||||
}
|
||||
|
||||
document_points
|
||||
}
|
||||
|
||||
pub fn clicked_on_line_endpoints(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, shape_tool_data: &mut ShapeToolData) -> bool {
|
||||
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs("Line") else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let (Some(&TaggedValue::DVec2(document_start)), Some(&TaggedValue::DVec2(document_end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
let viewport_x = transform.transform_vector2(DVec2::X).normalize_or_zero() * BOUNDS_SELECT_THRESHOLD;
|
||||
let viewport_y = transform.transform_vector2(DVec2::Y).normalize_or_zero() * BOUNDS_SELECT_THRESHOLD;
|
||||
let threshold_x = transform.inverse().transform_vector2(viewport_x).length();
|
||||
let threshold_y = transform.inverse().transform_vector2(viewport_y).length();
|
||||
|
||||
let drag_start = input.mouse.position;
|
||||
let [start, end] = [document_start, document_end].map(|point| transform.transform_point2(point));
|
||||
|
||||
let start_click = (drag_start.y - start.y).abs() < threshold_y && (drag_start.x - start.x).abs() < threshold_x;
|
||||
let end_click = (drag_start.y - end.y).abs() < threshold_y && (drag_start.x - end.x).abs() < threshold_x;
|
||||
|
||||
if start_click || end_click {
|
||||
shape_tool_data.line_data.dragging_endpoint = Some(if end_click { LineEnd::End } else { LineEnd::Start });
|
||||
shape_tool_data.data.drag_start = if end_click { document_start } else { document_end };
|
||||
shape_tool_data.line_data.editing_layer = Some(layer);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_line_tool {
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
async fn get_line_node_inputs(editor: &mut EditorTestUtils) -> Option<(DVec2, DVec2)> {
|
||||
let document = editor.active_document();
|
||||
let network_interface = &document.network_interface;
|
||||
let node_id = network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &network_interface).find_node_inputs("Line")?;
|
||||
let (Some(&TaggedValue::DVec2(start)), Some(&TaggedValue::DVec2(end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else {
|
||||
return None;
|
||||
};
|
||||
Some((start, end))
|
||||
})
|
||||
.next();
|
||||
node_id
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_basicdraw() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
assert!((start_input - DVec2::ZERO).length() < 1., "Start point should be near (0,0)");
|
||||
assert!((end_input - DVec2::new(100., 100.)).length() < 1., "End point should be near (100,100)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_with_transformed_viewport() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2. }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100., 50.) }).await;
|
||||
editor
|
||||
.handle_message(NavigationMessage::CanvasTiltSet {
|
||||
angle_radians: (30. as f64).to_radians(),
|
||||
})
|
||||
.await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
let document = editor.active_document();
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
|
||||
let expected_start = viewport_to_document.transform_point2(DVec2::ZERO);
|
||||
let expected_end = viewport_to_document.transform_point2(DVec2::new(100., 100.));
|
||||
|
||||
assert!(
|
||||
(start_input - expected_start).length() < 1.,
|
||||
"Start point should match expected document coordinates. Got {:?}, expected {:?}",
|
||||
start_input,
|
||||
expected_start
|
||||
);
|
||||
assert!(
|
||||
(end_input - expected_end).length() < 1.,
|
||||
"End point should match expected document coordinates. Got {:?}, expected {:?}",
|
||||
end_input,
|
||||
expected_end
|
||||
);
|
||||
} else {
|
||||
panic!("Line was not created successfully with transformed viewport");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_ctrl_anglelock() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::CONTROL).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let line_vec = end_input - start_input;
|
||||
let original_angle = line_vec.angle_to(DVec2::X);
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 200., 50., ModifierKeys::CONTROL).await;
|
||||
if let Some((updated_start, updated_end)) = get_line_node_inputs(&mut editor).await {
|
||||
match (updated_start, updated_end) {
|
||||
(updated_start, updated_end) => {
|
||||
let updated_line_vec = updated_end - updated_start;
|
||||
let updated_angle = updated_line_vec.angle_to(DVec2::X);
|
||||
print!("{:?}", original_angle);
|
||||
print!("{:?}", updated_angle);
|
||||
assert!(
|
||||
line_vec.normalize().dot(updated_line_vec.normalize()).abs() - 1. < 1e-6,
|
||||
"Line angle should be locked when Ctrl is kept pressed"
|
||||
);
|
||||
assert!((updated_start - updated_end).length() > 1., "Line should be able to change length when Ctrl is kept pressed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_alt() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 100., 100., 200., 100., ModifierKeys::ALT).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let expected_start = DVec2::new(0., 100.);
|
||||
let expected_end = DVec2::new(200., 100.);
|
||||
assert!((start_input - expected_start).length() < 1., "Start point should be near (0, 100)");
|
||||
assert!((end_input - expected_end).length() < 1., "End point should be near (200, 100)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_alt_shift_drag() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 100., 100., 150., 120., ModifierKeys::ALT | ModifierKeys::SHIFT).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let line_vec = end_input - start_input;
|
||||
let angle_radians = line_vec.angle_to(DVec2::X);
|
||||
let angle_degrees = angle_radians.to_degrees();
|
||||
let nearest_angle = (angle_degrees / 15.).round() * 15.;
|
||||
|
||||
assert!((angle_degrees - nearest_angle).abs() < 1., "Angle should snap to the nearest 15 degrees");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_with_transformed_artboard() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 200., ModifierKeys::empty()).await;
|
||||
|
||||
let artboard_id = editor.get_selected_layer().await.expect("Should have selected the artboard");
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::TransformChange {
|
||||
layer: artboard_id,
|
||||
transform: DAffine2::from_angle(45_f64.to_radians()),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.drag_tool(ToolType::Line, 50., 50., 150., 150., ModifierKeys::empty()).await;
|
||||
|
||||
let (start_input, end_input) = get_line_node_inputs(&mut editor).await.expect("Line was not created successfully within transformed artboard");
|
||||
// The line should still be diagonal with equal change in x and y
|
||||
let line_vector = end_input - start_input;
|
||||
// Verifying the line is approximately 100*sqrt(2) units in length (diagonal of 100x100 square)
|
||||
let line_length = line_vector.length();
|
||||
assert!(
|
||||
(line_length - 141.42).abs() < 1., // 100 * sqrt(2) ~= 141.42
|
||||
"Line length should be approximately 141.42 units. Got: {line_length}"
|
||||
);
|
||||
assert!((line_vector.x - 100.).abs() < 1., "X-component of line vector should be approximately 100. Got: {}", line_vector.x);
|
||||
assert!(
|
||||
(line_vector.y.abs() - 100.).abs() < 1.,
|
||||
"Absolute Y-component of line vector should be approximately 100. Got: {}",
|
||||
line_vector.y.abs()
|
||||
);
|
||||
let angle_degrees = line_vector.angle_to(DVec2::X).to_degrees();
|
||||
assert!((angle_degrees - (-45.)).abs() < 1., "Line angle should be close to -45 degrees. Got: {angle_degrees}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub mod ellipse_shape;
|
||||
pub mod line_shape;
|
||||
pub mod polygon_shape;
|
||||
pub mod rectangle_shape;
|
||||
pub mod shape_utility;
|
||||
pub mod star_shape;
|
||||
|
||||
pub use super::shapes::ellipse_shape::Ellipse;
|
||||
pub use super::shapes::line_shape::{Line, LineEnd};
|
||||
pub use super::shapes::rectangle_shape::Rectangle;
|
||||
pub use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
|
||||
@@ -0,0 +1,68 @@
|
||||
use super::shape_utility::ShapeToolModifierKey;
|
||||
use super::shape_utility::update_radius_sign;
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Polygon;
|
||||
|
||||
impl Polygon {
|
||||
pub fn create_node(vertices: u32) -> NodeTemplate {
|
||||
let node_type = resolve_document_node_type("Regular Polygon").expect("Regular Polygon can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::U32(vertices), false)), Some(NodeInput::value(TaggedValue::F64(0.5), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
document: &DocumentMessageHandler,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
shape_tool_data: &mut ShapeToolData,
|
||||
modifier: ShapeToolModifierKey,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let [center, lock_ratio, _, _] = modifier;
|
||||
|
||||
if let Some([start, end]) = shape_tool_data.data.calculate_points(document, ipp, center, lock_ratio) {
|
||||
// TODO: We need to determine how to allow the polygon node to make irregular shapes
|
||||
update_radius_sign(end, start, layer, document, responses);
|
||||
|
||||
let dimensions = (start - end).abs();
|
||||
|
||||
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
|
||||
let mut scale = DVec2::ONE;
|
||||
let radius;
|
||||
if dimensions.x > dimensions.y {
|
||||
scale.x = dimensions.x / dimensions.y;
|
||||
radius = dimensions.y / 2.;
|
||||
} else {
|
||||
scale.y = dimensions.y / dimensions.x;
|
||||
radius = dimensions.x / 2.;
|
||||
}
|
||||
|
||||
let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., (start + end) / 2.),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use super::shape_utility::ShapeToolModifierKey;
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Rectangle;
|
||||
|
||||
impl Rectangle {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_document_node_type("Rectangle").expect("Rectangle node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::F64(1.), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
document: &DocumentMessageHandler,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
shape_tool_data: &mut ShapeToolData,
|
||||
modifier: ShapeToolModifierKey,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let [center, lock_ratio, _, _] = modifier;
|
||||
|
||||
if let Some([start, end]) = shape_tool_data.data.calculate_points(document, ipp, center, lock_ratio) {
|
||||
let Some(node_id) = graph_modification_utils::get_rectangle_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::F64((start.x - end.x).abs()), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64((start.y - end.y).abs()), false),
|
||||
});
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(start.midpoint(end)),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
use super::ShapeToolData;
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage, Responses};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::BoundingBoxManager;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::*;
|
||||
use bezier_rs::Subpath;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::renderer::ClickTargetType;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum ShapeType {
|
||||
#[default]
|
||||
Polygon = 0,
|
||||
Star = 1,
|
||||
Rectangle = 2,
|
||||
Ellipse = 3,
|
||||
Line = 4,
|
||||
}
|
||||
|
||||
impl ShapeType {
|
||||
pub fn name(&self) -> String {
|
||||
(match self {
|
||||
Self::Polygon => "Polygon",
|
||||
Self::Star => "Star",
|
||||
Self::Rectangle => "Rectangle",
|
||||
Self::Ellipse => "Ellipse",
|
||||
Self::Line => "Line",
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn tooltip(&self) -> String {
|
||||
(match self {
|
||||
Self::Line => "Line Tool",
|
||||
Self::Rectangle => "Rectangle Tool",
|
||||
Self::Ellipse => "Ellipse Tool",
|
||||
_ => "",
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn icon_name(&self) -> String {
|
||||
(match self {
|
||||
Self::Line => "VectorLineTool",
|
||||
Self::Rectangle => "VectorRectangleTool",
|
||||
Self::Ellipse => "VectorEllipseTool",
|
||||
_ => "",
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn tool_type(&self) -> ToolType {
|
||||
match self {
|
||||
Self::Line => ToolType::Line,
|
||||
Self::Rectangle => ToolType::Rectangle,
|
||||
Self::Ellipse => ToolType::Ellipse,
|
||||
_ => ToolType::Shape,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Center, Lock Ratio, Lock Angle, Snap Angle, Increase/Decrease Side
|
||||
pub type ShapeToolModifierKey = [Key; 4];
|
||||
|
||||
pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let sign_num = if end[1] > start[1] { 1. } else { -1. };
|
||||
let new_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
|
||||
if new_layer.find_input("Regular Polygon", 1).unwrap_or(&TaggedValue::U32(0)).to_u32() % 2 == 1 {
|
||||
let Some(polygon_node_id) = new_layer.upstream_node_id_from_name("Regular Polygon") else { return };
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(polygon_node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if new_layer.find_input("Star", 1).unwrap_or(&TaggedValue::U32(0)).to_u32() % 2 == 1 {
|
||||
let Some(star_node_id) = new_layer.upstream_node_id_from_name("Star") else { return };
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, 3),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.25), false),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn transform_cage_overlays(document: &DocumentMessageHandler, tool_data: &mut ShapeToolData, overlay_context: &mut OverlayContext) {
|
||||
let mut transform = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.find(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| document.metadata().transform_to_viewport_with_first_transform_node_if_group(layer, &document.network_interface))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Check if the matrix is not invertible
|
||||
let mut transform_tampered = false;
|
||||
if transform.matrix2.determinant() == 0. {
|
||||
transform.matrix2 += DMat2::IDENTITY * 1e-4; // TODO: Is this the cleanest way to handle this?
|
||||
transform_tampered = true;
|
||||
}
|
||||
|
||||
let bounds = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| {
|
||||
document
|
||||
.metadata()
|
||||
.bounding_box_with_transform(layer, transform.inverse() * document.metadata().transform_to_viewport(layer))
|
||||
})
|
||||
.reduce(graphene_std::renderer::Quad::combine_bounds);
|
||||
|
||||
if let Some(bounds) = bounds {
|
||||
let bounding_box_manager = tool_data.bounding_box_manager.get_or_insert(BoundingBoxManager::default());
|
||||
|
||||
bounding_box_manager.bounds = bounds;
|
||||
bounding_box_manager.transform = transform;
|
||||
bounding_box_manager.transform_tampered = transform_tampered;
|
||||
bounding_box_manager.render_overlays(overlay_context, true);
|
||||
} else {
|
||||
tool_data.bounding_box_manager.take();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext) {
|
||||
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
|
||||
let Some(vector_data) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
overlay_context.outline_vector(&vector_data, transform);
|
||||
|
||||
for (_, &position) in vector_data.point_domain.ids().iter().zip(vector_data.point_domain.positions()) {
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), false, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the node input values of Star
|
||||
pub fn extract_star_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(u32, f64, f64)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs("Star")?;
|
||||
|
||||
let (Some(&TaggedValue::U32(n)), Some(&TaggedValue::F64(outer)), Some(&TaggedValue::F64(inner))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value(), node_inputs.get(3)?.as_value())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some((n, outer, inner))
|
||||
}
|
||||
|
||||
/// Extract the node input values of Polygon
|
||||
pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(u32, f64)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs("Regular Polygon")?;
|
||||
|
||||
let (Some(&TaggedValue::U32(n)), Some(&TaggedValue::F64(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some((n, radius))
|
||||
}
|
||||
|
||||
/// Calculate the viewport position of as a star vertex given its index
|
||||
pub fn star_vertex_position(viewport: DAffine2, vertex_index: i32, n: u32, radius1: f64, radius2: f64) -> DVec2 {
|
||||
let angle = ((vertex_index as f64) * PI) / (n as f64);
|
||||
let radius = if vertex_index % 2 == 0 { radius1 } else { radius2 };
|
||||
|
||||
viewport.transform_point2(DVec2 {
|
||||
x: radius * angle.sin(),
|
||||
y: -radius * angle.cos(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Calculate the viewport position of as a polygon vertex given its index
|
||||
pub fn polygon_vertex_position(viewport: DAffine2, vertex_index: i32, n: u32, radius: f64) -> DVec2 {
|
||||
let angle = ((vertex_index as f64) * TAU) / (n as f64);
|
||||
|
||||
viewport.transform_point2(DVec2 {
|
||||
x: radius * angle.sin(),
|
||||
y: -radius * angle.cos(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Outlines the geometric shape made by the Star node
|
||||
pub fn star_outline(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, overlay_context: &mut OverlayContext) {
|
||||
let mut anchors = Vec::new();
|
||||
let Some((n, radius1, radius2)) = extract_star_parameters(Some(layer), document) else { return };
|
||||
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
for i in 0..2 * n {
|
||||
let angle = ((i as f64) * PI) / (n as f64);
|
||||
let radius = if i % 2 == 0 { radius1 } else { radius2 };
|
||||
|
||||
let point = DVec2 {
|
||||
x: radius * angle.sin(),
|
||||
y: -radius * angle.cos(),
|
||||
};
|
||||
|
||||
anchors.push(point);
|
||||
}
|
||||
|
||||
let subpath = [ClickTargetType::Subpath(Subpath::from_anchors_linear(anchors, true))];
|
||||
overlay_context.outline(subpath.iter(), viewport, None);
|
||||
}
|
||||
|
||||
/// Outlines the geometric shape made by the Polygon node
|
||||
pub fn polygon_outline(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, overlay_context: &mut OverlayContext) {
|
||||
let mut anchors = Vec::new();
|
||||
|
||||
let Some((n, radius)) = extract_polygon_parameters(Some(layer), document) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
for i in 0..2 * n {
|
||||
let angle = ((i as f64) * TAU) / (n as f64);
|
||||
|
||||
let point = DVec2 {
|
||||
x: radius * angle.sin(),
|
||||
y: -radius * angle.cos(),
|
||||
};
|
||||
|
||||
anchors.push(point);
|
||||
}
|
||||
|
||||
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::from_anchors_linear(anchors, true))];
|
||||
|
||||
overlay_context.outline(subpath.iter(), viewport, None);
|
||||
}
|
||||
|
||||
/// Check if the the cursor is inside the geometric star shape made by the Star node without any upstream node modifications
|
||||
pub fn inside_star(viewport: DAffine2, n: u32, radius1: f64, radius2: f64, mouse_position: DVec2) -> bool {
|
||||
let mut paths = Vec::new();
|
||||
|
||||
for i in 0..2 * n {
|
||||
let new_point = dvec2_to_point(star_vertex_position(viewport, i as i32, n, radius1, radius2));
|
||||
|
||||
if i == 0 {
|
||||
paths.push(PathEl::MoveTo(new_point));
|
||||
} else {
|
||||
paths.push(PathEl::LineTo(new_point));
|
||||
}
|
||||
}
|
||||
|
||||
paths.push(PathEl::ClosePath);
|
||||
|
||||
let bez_path = BezPath::from_vec(paths);
|
||||
let (shape, bbox) = (bez_path.clone(), bez_path.bounding_box());
|
||||
|
||||
if bbox.x0 > mouse_position.x || bbox.y0 > mouse_position.y || bbox.x1 < mouse_position.x || bbox.y1 < mouse_position.y {
|
||||
return false;
|
||||
}
|
||||
|
||||
let winding = shape.winding(dvec2_to_point(mouse_position));
|
||||
|
||||
// Non-zero fill rule
|
||||
winding != 0
|
||||
}
|
||||
|
||||
/// Check if the the cursor is inside the geometric polygon shape made by the Polygon node without any upstream node modifications
|
||||
pub fn inside_polygon(viewport: DAffine2, n: u32, radius: f64, mouse_position: DVec2) -> bool {
|
||||
let mut paths = Vec::new();
|
||||
|
||||
for i in 0..n {
|
||||
let new_point = dvec2_to_point(polygon_vertex_position(viewport, i as i32, n, radius));
|
||||
|
||||
if i == 0 {
|
||||
paths.push(PathEl::MoveTo(new_point));
|
||||
} else {
|
||||
paths.push(PathEl::LineTo(new_point));
|
||||
}
|
||||
}
|
||||
|
||||
paths.push(PathEl::ClosePath);
|
||||
|
||||
let bez_path = BezPath::from_vec(paths);
|
||||
let (shape, bbox) = (bez_path.clone(), bez_path.bounding_box());
|
||||
|
||||
if bbox.x0 > mouse_position.x || bbox.y0 > mouse_position.y || bbox.x1 < mouse_position.x || bbox.y1 < mouse_position.y {
|
||||
return false;
|
||||
}
|
||||
|
||||
let winding = shape.winding(dvec2_to_point(mouse_position));
|
||||
|
||||
// Non-zero fill rule
|
||||
winding != 0
|
||||
}
|
||||
|
||||
pub fn draw_snapping_ticks(snap_radii: &[f64], direction: DVec2, viewport: DAffine2, angle: f64, overlay_context: &mut OverlayContext) {
|
||||
for &snapped_radius in snap_radii {
|
||||
let Some(tick_direction) = direction.perp().try_normalize() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let tick_position = viewport.transform_point2(DVec2 {
|
||||
x: snapped_radius * angle.sin(),
|
||||
y: -snapped_radius * angle.cos(),
|
||||
});
|
||||
|
||||
overlay_context.line(tick_position, tick_position + tick_direction * 5., None, Some(2.));
|
||||
overlay_context.line(tick_position, tick_position - tick_direction * 5., None, Some(2.));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use super::shape_utility::{ShapeToolModifierKey, update_radius_sign};
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use core::f64;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Star;
|
||||
|
||||
impl Star {
|
||||
pub fn create_node(vertices: u32) -> NodeTemplate {
|
||||
let node_type = resolve_document_node_type("Star").expect("Star node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::U32(vertices), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.25), false)),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
document: &DocumentMessageHandler,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
layer: LayerNodeIdentifier,
|
||||
shape_tool_data: &mut ShapeToolData,
|
||||
modifier: ShapeToolModifierKey,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let [center, lock_ratio, _, _] = modifier;
|
||||
|
||||
if let Some([start, end]) = shape_tool_data.data.calculate_points(document, ipp, center, lock_ratio) {
|
||||
// TODO: We need to determine how to allow the polygon node to make irregular shapes
|
||||
update_radius_sign(end, start, layer, document, responses);
|
||||
|
||||
let dimensions = (start - end).abs();
|
||||
|
||||
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
|
||||
let mut scale = DVec2::ONE;
|
||||
let radius: f64;
|
||||
if dimensions.x > dimensions.y {
|
||||
scale.x = dimensions.x / dimensions.y;
|
||||
radius = dimensions.y / 2.;
|
||||
} else {
|
||||
scale.y = dimensions.y / dimensions.x;
|
||||
radius = dimensions.x / 2.;
|
||||
}
|
||||
|
||||
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 3),
|
||||
input: NodeInput::value(TaggedValue::F64(radius / 2.), false),
|
||||
});
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., (start + end) / 2.),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,10 @@ pub use alignment_snapper::*;
|
||||
use bezier_rs::TValue;
|
||||
pub use distribution_snapper::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::vector::PointId;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::Rect;
|
||||
use graphene_std::vector::NoHashBuilder;
|
||||
use graphene_std::vector::PointId;
|
||||
pub use grid_snapper::*;
|
||||
pub use layer_snapper::*;
|
||||
pub use snap_results::*;
|
||||
@@ -114,13 +114,13 @@ fn get_closest_point(points: Vec<SnappedPoint>) -> Option<SnappedPoint> {
|
||||
(Some(result), None) | (None, Some(result)) => Some(result),
|
||||
(Some(mut result), Some(align)) => {
|
||||
let SnapTarget::DistributeEvenly(distribution) = result.target else { return Some(result) };
|
||||
if distribution.is_x() && align.alignment_target_x.is_some() {
|
||||
if distribution.is_x() && align.alignment_target_horizontal.is_some() {
|
||||
result.snapped_point_document.y = align.snapped_point_document.y;
|
||||
result.alignment_target_x = align.alignment_target_x;
|
||||
result.alignment_target_horizontal = align.alignment_target_horizontal;
|
||||
}
|
||||
if distribution.is_y() && align.alignment_target_y.is_some() {
|
||||
if distribution.is_y() && align.alignment_target_vertical.is_some() {
|
||||
result.snapped_point_document.x = align.snapped_point_document.x;
|
||||
result.alignment_target_y = align.alignment_target_y;
|
||||
result.alignment_target_vertical = align.alignment_target_vertical;
|
||||
}
|
||||
|
||||
Some(result)
|
||||
@@ -250,6 +250,10 @@ impl SnapManager {
|
||||
self.update_indicator(snapped);
|
||||
}
|
||||
|
||||
pub fn indicator_pos(&self) -> Option<DVec2> {
|
||||
self.indicator.as_ref().map(|point| point.snapped_point_document)
|
||||
}
|
||||
|
||||
fn find_best_snap(snap_data: &mut SnapData, point: &SnapCandidatePoint, snap_results: SnapResults, constrained: bool, off_screen: bool, to_path: bool) -> SnappedPoint {
|
||||
let mut snapped_points = Vec::new();
|
||||
let document = snap_data.document;
|
||||
@@ -449,17 +453,21 @@ impl SnapManager {
|
||||
if let Some(ind) = &self.indicator {
|
||||
for layer in &ind.outline_layers {
|
||||
let &Some(layer) = layer else { continue };
|
||||
overlay_context.outline(snap_data.document.metadata().layer_outline(layer), snap_data.document.metadata().transform_to_viewport(layer));
|
||||
overlay_context.outline(
|
||||
snap_data.document.metadata().layer_with_free_points_outline(layer),
|
||||
snap_data.document.metadata().transform_to_viewport(layer),
|
||||
None,
|
||||
);
|
||||
}
|
||||
if let Some(quad) = ind.target_bounds {
|
||||
overlay_context.quad(to_viewport * quad, None);
|
||||
overlay_context.quad(to_viewport * quad, None, None);
|
||||
}
|
||||
let viewport = to_viewport.transform_point2(ind.snapped_point_document);
|
||||
|
||||
Self::alignment_x_overlay(&ind.distribution_boxes_x, to_viewport, overlay_context);
|
||||
Self::alignment_y_overlay(&ind.distribution_boxes_y, to_viewport, overlay_context);
|
||||
Self::alignment_x_overlay(&ind.distribution_boxes_horizontal, to_viewport, overlay_context);
|
||||
Self::alignment_y_overlay(&ind.distribution_boxes_vertical, to_viewport, overlay_context);
|
||||
|
||||
let align = [ind.alignment_target_x, ind.alignment_target_y].map(|target| target.map(|target| to_viewport.transform_point2(target)));
|
||||
let align = [ind.alignment_target_horizontal, ind.alignment_target_vertical].map(|target| target.map(|target| to_viewport.transform_point2(target)));
|
||||
let any_align = align.iter().flatten().next().is_some();
|
||||
for &target in align.iter().flatten() {
|
||||
overlay_context.line(viewport, target, None, None);
|
||||
@@ -471,7 +479,7 @@ impl SnapManager {
|
||||
overlay_context.manipulator_handle(viewport, false, None);
|
||||
}
|
||||
|
||||
if !any_align && ind.distribution_equal_distance_x.is_none() && ind.distribution_equal_distance_y.is_none() {
|
||||
if !any_align && ind.distribution_equal_distance_horizontal.is_none() && ind.distribution_equal_distance_vertical.is_none() {
|
||||
let text = format!("[{}] from [{}]", ind.target, ind.source);
|
||||
let transform = DAffine2::from_translation(viewport - DVec2::new(0., 4.));
|
||||
overlay_context.text(&text, COLOR_OVERLAY_WHITE, Some(COLOR_OVERLAY_LABEL_BACKGROUND), transform, 4., [Pivot::Start, Pivot::End]);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::utility_types::misc::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::renderer::Quad;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AlignmentSnapper {
|
||||
@@ -70,7 +70,7 @@ impl AlignmentSnapper {
|
||||
if let Some(quad) = target_point.quad.map(|q| q.0) {
|
||||
if quad[0] == quad[3] && quad[1] == quad[2] && quad[0] == target_point.document_point {
|
||||
let [p1, p2, ..] = quad;
|
||||
let direction = (p2 - p1).normalize();
|
||||
let Some(direction) = (p2 - p1).try_normalize() else { return };
|
||||
let normal = DVec2::new(-direction.y, direction.x);
|
||||
|
||||
for endpoint in [p1, p2] {
|
||||
@@ -90,7 +90,7 @@ impl AlignmentSnapper {
|
||||
distance_to_align_target,
|
||||
fully_constrained: false,
|
||||
at_intersection: true,
|
||||
alignment_target_x: Some(endpoint),
|
||||
alignment_target_horizontal: Some(endpoint),
|
||||
..Default::default()
|
||||
};
|
||||
snap_results.points.push(snap_point);
|
||||
@@ -129,7 +129,7 @@ impl AlignmentSnapper {
|
||||
distance: distance_to_snapped,
|
||||
tolerance,
|
||||
distance_to_align_target,
|
||||
alignment_target_x: Some(target_position),
|
||||
alignment_target_horizontal: Some(target_position),
|
||||
fully_constrained: true,
|
||||
at_intersection: matches!(constraint, SnapConstraint::Line { .. }),
|
||||
..Default::default()
|
||||
@@ -148,7 +148,7 @@ impl AlignmentSnapper {
|
||||
distance: distance_to_snapped,
|
||||
tolerance,
|
||||
distance_to_align_target,
|
||||
alignment_target_y: Some(target_position),
|
||||
alignment_target_vertical: Some(target_position),
|
||||
fully_constrained: true,
|
||||
at_intersection: matches!(constraint, SnapConstraint::Line { .. }),
|
||||
..Default::default()
|
||||
@@ -174,8 +174,8 @@ impl AlignmentSnapper {
|
||||
target_bounds: snap_x.target_bounds,
|
||||
distance,
|
||||
tolerance,
|
||||
alignment_target_x: snap_x.alignment_target_x,
|
||||
alignment_target_y: snap_y.alignment_target_y,
|
||||
alignment_target_horizontal: snap_x.alignment_target_horizontal,
|
||||
alignment_target_vertical: snap_y.alignment_target_vertical,
|
||||
constrained: true,
|
||||
at_intersection: true,
|
||||
..Default::default()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::*;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::renderer::Quad;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DistributionSnapper {
|
||||
@@ -79,18 +79,21 @@ impl DistributionSnapper {
|
||||
let screen_bounds = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, snap_data.input.viewport_bounds.size()])).bounding_box();
|
||||
let max_extent = (screen_bounds[1] - screen_bounds[0]).abs().max_element();
|
||||
|
||||
// Collect artboard bounds
|
||||
for layer in document.metadata().all_layers() {
|
||||
if document.network_interface.is_artboard(&layer.to_node(), &[]) && !snap_data.ignore.contains(&layer) {
|
||||
self.add_bounds(layer, snap_data, bbox_to_snap, max_extent);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect alignment candidate bounds
|
||||
for &layer in snap_data.alignment_candidates.map_or([].as_slice(), |candidates| candidates.as_slice()) {
|
||||
if !snap_data.ignore_bounds(layer) {
|
||||
self.add_bounds(layer, snap_data, bbox_to_snap, max_extent);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort and merge intersecting rectangles
|
||||
self.right.sort_unstable_by(|a, b| a.center().x.total_cmp(&b.center().x));
|
||||
self.left.sort_unstable_by(|a, b| b.center().x.total_cmp(&a.center().x));
|
||||
self.down.sort_unstable_by(|a, b| a.center().y.total_cmp(&b.center().y));
|
||||
@@ -184,20 +187,18 @@ impl DistributionSnapper {
|
||||
fn snap_bbox_points(&self, tolerance: f64, point: &SnapCandidatePoint, snap_results: &mut SnapResults, constraint: SnapConstraint, bounds: Rect) {
|
||||
let mut consider_x = true;
|
||||
let mut consider_y = true;
|
||||
|
||||
if let SnapConstraint::Line { direction, .. } = constraint {
|
||||
let direction = direction.normalize_or_zero();
|
||||
if direction.x == 0. {
|
||||
consider_x = false;
|
||||
} else if direction.y == 0. {
|
||||
consider_y = false;
|
||||
}
|
||||
consider_x = direction.x != 0.;
|
||||
consider_y = direction.y != 0.;
|
||||
}
|
||||
|
||||
let mut snap_x: Option<SnappedPoint> = None;
|
||||
let mut snap_y: Option<SnappedPoint> = None;
|
||||
|
||||
self.x(consider_x, bounds, tolerance, &mut snap_x, point);
|
||||
self.y(consider_y, bounds, tolerance, &mut snap_y, point);
|
||||
self.horizontal_snap(consider_x, bounds, tolerance, &mut snap_x, point);
|
||||
self.vertical_snap(consider_y, bounds, tolerance, &mut snap_y, point);
|
||||
|
||||
match (snap_x, snap_y) {
|
||||
(Some(x), Some(y)) => {
|
||||
@@ -209,8 +210,8 @@ impl DistributionSnapper {
|
||||
final_point.snapped_point_document += y.snapped_point_document - point.document_point;
|
||||
final_point.source_bounds = Some(final_bounds.into());
|
||||
final_point.target = SnapTarget::DistributeEvenly(DistributionSnapTarget::XY);
|
||||
final_point.distribution_boxes_y = y.distribution_boxes_y;
|
||||
final_point.distribution_equal_distance_y = y.distribution_equal_distance_y;
|
||||
final_point.distribution_boxes_vertical = y.distribution_boxes_vertical;
|
||||
final_point.distribution_equal_distance_vertical = y.distribution_equal_distance_vertical;
|
||||
final_point.distance = (final_point.distance * final_point.distance + y.distance * y.distance).sqrt();
|
||||
snap_results.points.push(final_point);
|
||||
}
|
||||
@@ -220,42 +221,55 @@ impl DistributionSnapper {
|
||||
}
|
||||
}
|
||||
|
||||
fn x(&self, consider_x: bool, bounds: Rect, tolerance: f64, snap_x: &mut Option<SnappedPoint>, point: &SnapCandidatePoint) {
|
||||
// Right
|
||||
if consider_x && !self.right.is_empty() {
|
||||
fn horizontal_snap(&self, consider_x: bool, bounds: Rect, tolerance: f64, snap_x: &mut Option<SnappedPoint>, point: &SnapCandidatePoint) {
|
||||
if !consider_x {
|
||||
return;
|
||||
}
|
||||
|
||||
// Try right distribution first
|
||||
if !self.right.is_empty() {
|
||||
let (equal_dist, mut vec_right) = Self::top_level_matches(bounds, &self.right, tolerance, dist_right);
|
||||
if let Some(distances) = equal_dist {
|
||||
let translation = DVec2::X * (distances.first - distances.equal);
|
||||
vec_right.push_front(bounds.translate(translation));
|
||||
|
||||
// Find matching left distribution
|
||||
for &left in Self::exact_further_matches(bounds.translate(translation), &self.left, dist_left, distances.equal, 2).iter().skip(1) {
|
||||
vec_right.push_front(left);
|
||||
}
|
||||
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Right, vec_right, distances, bounds, translation, tolerance))
|
||||
// Adjust bounds to maintain alignment
|
||||
if vec_right.len() > 1 {
|
||||
vec_right[0][0].y = vec_right[0][0].y.min(vec_right[1][1].y);
|
||||
vec_right[0][1].y = vec_right[0][1].y.min(vec_right[1][1].y);
|
||||
}
|
||||
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Right, vec_right, distances, bounds, translation, tolerance));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Left
|
||||
if consider_x && !self.left.is_empty() && snap_x.is_none() {
|
||||
// Try left distribution if right didn't work
|
||||
if !self.left.is_empty() {
|
||||
let (equal_dist, mut vec_left) = Self::top_level_matches(bounds, &self.left, tolerance, dist_left);
|
||||
if let Some(distances) = equal_dist {
|
||||
let translation = -DVec2::X * (distances.first - distances.equal);
|
||||
vec_left.make_contiguous().reverse();
|
||||
vec_left.push_back(bounds.translate(translation));
|
||||
|
||||
// Find matching right distribution
|
||||
for &right in Self::exact_further_matches(bounds.translate(translation), &self.right, dist_right, distances.equal, 2).iter().skip(1) {
|
||||
vec_left.push_back(right);
|
||||
}
|
||||
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Left, vec_left, distances, bounds, translation, tolerance))
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Left, vec_left, distances, bounds, translation, tolerance));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Center X
|
||||
if consider_x && !self.left.is_empty() && !self.right.is_empty() && snap_x.is_none() {
|
||||
// Try center distribution if both sides exist
|
||||
if !self.left.is_empty() && !self.right.is_empty() {
|
||||
let target_x = (self.right[0].min() + self.left[0].max()).x / 2.;
|
||||
|
||||
let offset = target_x - bounds.center().x;
|
||||
|
||||
if offset.abs() < tolerance {
|
||||
@@ -263,67 +277,93 @@ impl DistributionSnapper {
|
||||
let equal = bounds.translate(translation).min().x - self.left[0].max().x;
|
||||
let first = equal + offset;
|
||||
let distances = DistributionMatch { first, equal };
|
||||
let boxes = VecDeque::from([self.left[0], bounds.translate(translation), self.right[0]]);
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::X, boxes, distances, bounds, translation, tolerance))
|
||||
|
||||
let mut boxes = VecDeque::from([self.left[0], bounds.translate(translation), self.right[0]]);
|
||||
|
||||
// Adjust bounds to maintain alignment
|
||||
if boxes.len() > 1 {
|
||||
boxes[1][0].y = boxes[1][0].y.min(boxes[0][1].y);
|
||||
boxes[1][1].y = boxes[1][1].y.min(boxes[0][1].y);
|
||||
}
|
||||
|
||||
*snap_x = Some(SnappedPoint::distribute(point, DistributionSnapTarget::X, boxes, distances, bounds, translation, tolerance));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn y(&self, consider_y: bool, bounds: Rect, tolerance: f64, snap_y: &mut Option<SnappedPoint>, point: &SnapCandidatePoint) {
|
||||
// Down
|
||||
if consider_y && !self.down.is_empty() {
|
||||
fn vertical_snap(&self, consider_y: bool, bounds: Rect, tolerance: f64, snap_y: &mut Option<SnappedPoint>, point: &SnapCandidatePoint) {
|
||||
if !consider_y {
|
||||
return;
|
||||
}
|
||||
|
||||
// Try down distribution first
|
||||
if !self.down.is_empty() {
|
||||
let (equal_dist, mut vec_down) = Self::top_level_matches(bounds, &self.down, tolerance, dist_down);
|
||||
if let Some(distances) = equal_dist {
|
||||
let translation = DVec2::Y * (distances.first - distances.equal);
|
||||
vec_down.push_front(bounds.translate(translation));
|
||||
|
||||
// Find matching up distribution
|
||||
for &up in Self::exact_further_matches(bounds.translate(translation), &self.up, dist_up, distances.equal, 2).iter().skip(1) {
|
||||
vec_down.push_front(up);
|
||||
}
|
||||
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Down, vec_down, distances, bounds, translation, tolerance))
|
||||
// Adjust bounds to maintain alignment
|
||||
if vec_down.len() > 1 {
|
||||
vec_down[0][0].x = vec_down[0][0].x.min(vec_down[1][1].x);
|
||||
vec_down[0][1].x = vec_down[0][1].x.min(vec_down[1][1].x);
|
||||
}
|
||||
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Down, vec_down, distances, bounds, translation, tolerance));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Up
|
||||
if consider_y && !self.up.is_empty() && snap_y.is_none() {
|
||||
// Try up distribution if down didn't work
|
||||
if !self.up.is_empty() {
|
||||
let (equal_dist, mut vec_up) = Self::top_level_matches(bounds, &self.up, tolerance, dist_up);
|
||||
if let Some(distances) = equal_dist {
|
||||
let translation = -DVec2::Y * (distances.first - distances.equal);
|
||||
vec_up.make_contiguous().reverse();
|
||||
vec_up.push_back(bounds.translate(translation));
|
||||
|
||||
// Find matching down distribution
|
||||
for &down in Self::exact_further_matches(bounds.translate(translation), &self.down, dist_down, distances.equal, 2).iter().skip(1) {
|
||||
vec_up.push_back(down);
|
||||
}
|
||||
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Up, vec_up, distances, bounds, translation, tolerance))
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Up, vec_up, distances, bounds, translation, tolerance));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Center Y
|
||||
if consider_y && !self.up.is_empty() && !self.down.is_empty() && snap_y.is_none() {
|
||||
// Try center distribution if both sides exist
|
||||
if !self.up.is_empty() && !self.down.is_empty() {
|
||||
let target_y = (self.down[0].min() + self.up[0].max()).y / 2.;
|
||||
|
||||
let offset = target_y - bounds.center().y;
|
||||
|
||||
if offset.abs() < tolerance {
|
||||
let translation = DVec2::Y * offset;
|
||||
|
||||
let equal = bounds.translate(translation).min().y - self.up[0].max().y;
|
||||
let first = equal + offset;
|
||||
let distances = DistributionMatch { first, equal };
|
||||
|
||||
let boxes = VecDeque::from([self.up[0], bounds.translate(translation), self.down[0]]);
|
||||
let mut boxes = VecDeque::from([self.up[0], bounds.translate(translation), self.down[0]]);
|
||||
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Y, boxes, distances, bounds, translation, tolerance))
|
||||
// Adjust bounds to maintain alignment
|
||||
if boxes.len() > 1 {
|
||||
boxes[1][0].x = boxes[1][0].x.min(boxes[0][1].x);
|
||||
boxes[1][1].x = boxes[1][1].x.min(boxes[0][1].x);
|
||||
}
|
||||
|
||||
*snap_y = Some(SnappedPoint::distribute(point, DistributionSnapTarget::Y, boxes, distances, bounds, translation, tolerance));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn free_snap(&mut self, snap_data: &mut SnapData, point: &SnapCandidatePoint, snap_results: &mut SnapResults, config: SnapTypeConfiguration) {
|
||||
let Some(bounds) = config.bbox else { return };
|
||||
if point.source != SnapSource::BoundingBox(BoundingBoxSnapSource::CenterPoint) || !snap_data.document.snapping_state.bounding_box.distribute_evenly {
|
||||
if !snap_data.document.snapping_state.bounding_box.distribute_evenly {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -333,7 +373,7 @@ impl DistributionSnapper {
|
||||
|
||||
pub fn constrained_snap(&mut self, snap_data: &mut SnapData, point: &SnapCandidatePoint, snap_results: &mut SnapResults, constraint: SnapConstraint, config: SnapTypeConfiguration) {
|
||||
let Some(bounds) = config.bbox else { return };
|
||||
if point.source != SnapSource::BoundingBox(BoundingBoxSnapSource::CenterPoint) || !snap_data.document.snapping_state.bounding_box.distribute_evenly {
|
||||
if !snap_data.document.snapping_state.bounding_box.distribute_evenly {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -342,267 +382,321 @@ impl DistributionSnapper {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_intersecting_test() {
|
||||
let mut rectangles = vec![Rect::from_square(DVec2::ZERO, 2.), Rect::from_square(DVec2::new(10., 0.), 2.)];
|
||||
DistributionSnapper::merge_intersecting(&mut rectangles);
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
|
||||
let mut rectangles = vec![
|
||||
Rect::from_square(DVec2::ZERO, 2.),
|
||||
Rect::from_square(DVec2::new(1., 0.), 2.),
|
||||
Rect::from_square(DVec2::new(10., 0.), 2.),
|
||||
Rect::from_square(DVec2::new(11., 0.), 2.),
|
||||
];
|
||||
DistributionSnapper::merge_intersecting(&mut rectangles);
|
||||
assert_eq!(rectangles.len(), 6);
|
||||
assert_eq!(rectangles[0], Rect::from_box([DVec2::new(-2., -2.), DVec2::new(3., 2.)]));
|
||||
assert_eq!(rectangles[3], Rect::from_box([DVec2::new(8., -2.), DVec2::new(13., 2.)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_simple_2() {
|
||||
let rectangles = [10., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_simple_3() {
|
||||
let rectangles = [10., 20., 30.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_out_of_tolerance() {
|
||||
let rectangles = [10., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 0.4, dist_right);
|
||||
assert_eq!(offset, None);
|
||||
assert_eq!(rectangles.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_with_nonsense() {
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let rectangles = [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn assert_boxes_in_order(rectangles: &VecDeque<Rect>, index: usize) {
|
||||
for (&first, &second) in rectangles.iter().zip(rectangles.iter().skip(1)) {
|
||||
assert!(first.max()[index] < second.min()[index], "{first:?} {second:?} {index}")
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn merge_intersecting_test() {
|
||||
let mut rectangles = vec![Rect::from_square(DVec2::ZERO, 2.), Rect::from_square(DVec2::new(10., 0.), 2.)];
|
||||
DistributionSnapper::merge_intersecting(&mut rectangles);
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
|
||||
let mut rectangles = vec![
|
||||
Rect::from_square(DVec2::ZERO, 2.),
|
||||
Rect::from_square(DVec2::new(1., 0.), 2.),
|
||||
Rect::from_square(DVec2::new(10., 0.), 2.),
|
||||
Rect::from_square(DVec2::new(11., 0.), 2.),
|
||||
];
|
||||
DistributionSnapper::merge_intersecting(&mut rectangles);
|
||||
assert_eq!(rectangles.len(), 6);
|
||||
assert_eq!(rectangles[0], Rect::from_box([DVec2::new(-2., -2.), DVec2::new(3., 2.)]));
|
||||
assert_eq!(rectangles[3], Rect::from_box([DVec2::new(8., -2.), DVec2::new(13., 2.)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_simple_2() {
|
||||
let rectangles = [10., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_simple_3() {
|
||||
let rectangles = [10., 20., 30.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_out_of_tolerance() {
|
||||
let rectangles = [10., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 0.4, dist_right);
|
||||
assert_eq!(offset, None);
|
||||
assert_eq!(rectangles.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_with_nonsense() {
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let rectangles = [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.));
|
||||
let (offset, rectangles) = DistributionSnapper::top_level_matches(source, &rectangles, 1., dist_right);
|
||||
assert_eq!(offset, Some(DistributionMatch { first: 5.5, equal: 6. }));
|
||||
assert_eq!(rectangles.len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn assert_boxes_in_order(rectangles: &VecDeque<Rect>, index: usize) {
|
||||
for (&first, &second) in rectangles.iter().zip(rectangles.iter().skip(1)) {
|
||||
assert!(first.max()[index] < second.min()[index], "{first:?} {second:?} {index}")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_right() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
right: [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
left: [-2.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(6.));
|
||||
let mut expected_box = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
expected_box[0].y = expected_box[0].y.min(dist_snapper.left[0][1].y);
|
||||
expected_box[1].y = expected_box[1].y.min(dist_snapper.left[0][1].y);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[0], expected_box);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_right_left() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
right: [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 5);
|
||||
|
||||
let mut expected_left1 = dist_snapper.left[1];
|
||||
let mut expected_center = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
|
||||
expected_center[0].y = expected_center[0].y.min(dist_snapper.left[1][1].y).min(dist_snapper.right[0][1].y);
|
||||
expected_center[1].y = expected_center[1].y.min(dist_snapper.left[1][1].y).min(dist_snapper.right[0][1].y);
|
||||
|
||||
expected_left1[0].y = expected_left1[0].y.min(dist_snapper.left[0][1].y).min(expected_center[1].y);
|
||||
expected_left1[1].y = expected_left1[1].y.min(dist_snapper.left[0][1].y).min(expected_center[1].y);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[1], expected_left1);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[2], expected_center);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_left() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_left_right() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [2., 10., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 4);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_x() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-10., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [10., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(6.));
|
||||
|
||||
let mut expected_box = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
expected_box[0].y = expected_box[0].y.min(dist_snapper.left[0][1].y);
|
||||
expected_box[1].y = expected_box[1].y.min(dist_snapper.left[0][1].y);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal[1], expected_box);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
}
|
||||
|
||||
// ----------------------------------
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_down() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
down: [2., 10., 15., 20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
up: [-2.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
|
||||
let mut expected_box = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
expected_box[0].x = expected_box[0].x.min(dist_snapper.down[0][1].x);
|
||||
expected_box[1].x = expected_box[1].x.min(dist_snapper.down[0][1].x);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[0], expected_box);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_down_up() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
down: [2., 10., 15., 20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 5);
|
||||
|
||||
let mut expected_center = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
expected_center[0].x = expected_center[0].x.min(dist_snapper.up[1][1].x).min(dist_snapper.down[0][1].x);
|
||||
expected_center[1].x = expected_center[1].x.min(dist_snapper.up[1][1].x).min(dist_snapper.down[0][1].x);
|
||||
|
||||
let mut expected_up = Rect::from_square(DVec2::new(0., -10.), 2.);
|
||||
expected_up[0].x = expected_up[0].x.min(dist_snapper.up[0][1].x).min(expected_center[0].x);
|
||||
expected_up[1].x = expected_up[1].x.min(dist_snapper.up[0][1].x).min(expected_center[1].x);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[1], expected_up);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[2], expected_center);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_up() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_up_down() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [2., 10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 4);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_y() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-10., -15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 3);
|
||||
|
||||
let mut expected_box = Rect::from_square(DVec2::new(0., 0.), 2.);
|
||||
expected_box[0].x = expected_box[0].x.min(dist_snapper.up[0][1].x).min(dist_snapper.down[0][1].x);
|
||||
expected_box[1].x = expected_box[1].x.min(dist_snapper.up[0][1].x).min(dist_snapper.down[0][1].x);
|
||||
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical[1], expected_box);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_xy() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-10., -15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5000000000000001);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_horizontal, Some(8.));
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_vertical, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_horizontal.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_vertical.len(), 3);
|
||||
|
||||
assert!(snap_results.points[0].distribution_boxes_horizontal[1][0].y <= dist_snapper.left[0][1].y);
|
||||
assert!(snap_results.points[0].distribution_boxes_horizontal[1][1].y <= dist_snapper.left[0][1].y);
|
||||
assert!(snap_results.points[0].distribution_boxes_vertical[1][0].x <= dist_snapper.up[0][1].x);
|
||||
assert!(snap_results.points[0].distribution_boxes_vertical[1][1].x <= dist_snapper.up[0][1].x);
|
||||
|
||||
assert_eq!(Rect::from_box(snap_results.points[0].source_bounds.unwrap().bounding_box()), Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_horizontal, 0);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_vertical, 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_right() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
right: [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
left: [-2.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[0], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_right_left() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
right: [2., 10., 15., 20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 5);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[1], Rect::from_square(DVec2::new(-10., 0.), 2.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_left() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_left_right() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-2., -10., -15., -20.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [2., 10., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 4);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_x() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
left: [-10., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [10., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.5, 0.), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x[1], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
}
|
||||
|
||||
// ----------------------------------
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_down() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
down: [2., 10., 15., 20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
up: [-2.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[0], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_down_up() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
down: [2., 10., 15., 20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 5);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[1], Rect::from_square(DVec2::new(0., -10.), 2.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_up() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_up_down() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-2., -10., -15., -20.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [2., 10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 4);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[2], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_y() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-10., -15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0., 0.5), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y[1], Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_snap_point_center_xy() {
|
||||
let dist_snapper = DistributionSnapper {
|
||||
up: [-10., -15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
dist_snapper.snap_bbox_points(1., &SnapCandidatePoint::default(), snap_results, SnapConstraint::None, source);
|
||||
assert_eq!(snap_results.points.len(), 1);
|
||||
assert_eq!(snap_results.points[0].distance, 0.5000000000000001);
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_x, Some(8.));
|
||||
assert_eq!(snap_results.points[0].distribution_equal_distance_y, Some(6.));
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_x.len(), 3);
|
||||
assert_eq!(snap_results.points[0].distribution_boxes_y.len(), 3);
|
||||
assert_eq!(Rect::from_box(snap_results.points[0].source_bounds.unwrap().bounding_box()), Rect::from_square(DVec2::new(0., 0.), 2.));
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_x, 0);
|
||||
assert_boxes_in_order(&snap_results.points[0].distribution_boxes_y, 1);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::utility_types::misc::{GridSnapTarget, GridSnapping, GridType, SnapTarget};
|
||||
use glam::DVec2;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::renderer::Quad;
|
||||
|
||||
struct Line {
|
||||
pub point: DVec2,
|
||||
|
||||
@@ -5,8 +5,8 @@ use crate::messages::portfolio::document::utility_types::misc::*;
|
||||
use crate::messages::prelude::*;
|
||||
use bezier_rs::{Bezier, Identifier, Subpath, TValue};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::vector::PointId;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::PointId;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LayerSnapper {
|
||||
|
||||
@@ -4,9 +4,9 @@ use crate::messages::portfolio::document::utility_types::misc::{DistributionSnap
|
||||
use crate::messages::tool::common_functionality::snapping::SnapCandidatePoint;
|
||||
use bezier_rs::Bezier;
|
||||
use glam::DVec2;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::vector::PointId;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::Rect;
|
||||
use graphene_std::vector::PointId;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -29,17 +29,17 @@ pub struct SnappedPoint {
|
||||
pub outline_layers: [Option<LayerNodeIdentifier>; 2],
|
||||
pub distance: f64,
|
||||
pub tolerance: f64,
|
||||
pub distribution_boxes_x: VecDeque<Rect>,
|
||||
pub distribution_equal_distance_x: Option<f64>,
|
||||
pub distribution_boxes_y: VecDeque<Rect>,
|
||||
pub distribution_equal_distance_y: Option<f64>,
|
||||
pub distribution_boxes_horizontal: VecDeque<Rect>,
|
||||
pub distribution_equal_distance_horizontal: Option<f64>,
|
||||
pub distribution_boxes_vertical: VecDeque<Rect>,
|
||||
pub distribution_equal_distance_vertical: Option<f64>,
|
||||
pub distance_to_align_target: f64, // If aligning so that the top is aligned but the X pos is 200 from the target, this is 200.
|
||||
pub alignment_target_x: Option<DVec2>,
|
||||
pub alignment_target_y: Option<DVec2>,
|
||||
pub alignment_target_horizontal: Option<DVec2>,
|
||||
pub alignment_target_vertical: Option<DVec2>,
|
||||
}
|
||||
impl SnappedPoint {
|
||||
pub fn align(&self) -> bool {
|
||||
self.alignment_target_x.is_some() || self.alignment_target_y.is_some()
|
||||
self.alignment_target_horizontal.is_some() || self.alignment_target_vertical.is_some()
|
||||
}
|
||||
pub fn infinite_snap(snapped_point_document: DVec2) -> Self {
|
||||
Self {
|
||||
@@ -58,15 +58,15 @@ impl SnappedPoint {
|
||||
pub fn distribute(point: &SnapCandidatePoint, target: DistributionSnapTarget, boxes: VecDeque<Rect>, distances: DistributionMatch, bounds: Rect, translation: DVec2, tolerance: f64) -> Self {
|
||||
let is_x = target.is_x();
|
||||
|
||||
let [distribution_boxes_x, distribution_boxes_y] = if is_x { [boxes, Default::default()] } else { [Default::default(), boxes] };
|
||||
let [distribution_boxes_horizontal, distribution_boxes_vertical] = if is_x { [boxes, Default::default()] } else { [Default::default(), boxes] };
|
||||
Self {
|
||||
snapped_point_document: point.document_point + translation,
|
||||
source: point.source,
|
||||
target: SnapTarget::DistributeEvenly(target),
|
||||
distribution_boxes_x,
|
||||
distribution_equal_distance_x: is_x.then_some(distances.equal),
|
||||
distribution_boxes_y,
|
||||
distribution_equal_distance_y: (!is_x).then_some(distances.equal),
|
||||
distribution_boxes_horizontal,
|
||||
distribution_equal_distance_horizontal: is_x.then_some(distances.equal),
|
||||
distribution_boxes_vertical,
|
||||
distribution_equal_distance_vertical: (!is_x).then_some(distances.equal),
|
||||
distance: (distances.first - distances.equal).abs(),
|
||||
constrained: true,
|
||||
source_bounds: Some(bounds.translate(translation).into()),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::snapping::{self, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnappedPoint};
|
||||
use crate::consts::{
|
||||
BOUNDS_ROTATE_THRESHOLD, BOUNDS_SELECT_THRESHOLD, COLOR_OVERLAY_WHITE, MAXIMUM_ALT_SCALE_FACTOR, MIN_LENGTH_FOR_CORNERS_VISIBILITY, MIN_LENGTH_FOR_EDGE_RESIZE_PRIORITY_OVER_CORNERS,
|
||||
MIN_LENGTH_FOR_MIDPOINT_VISIBILITY, MIN_LENGTH_FOR_RESIZE_TO_INCLUDE_INTERIOR, MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY, RESIZE_HANDLE_SIZE, SELECTION_DRAG_ANGLE, SKEW_TRIANGLE_OFFSET,
|
||||
SKEW_TRIANGLE_SIZE,
|
||||
BOUNDS_ROTATE_THRESHOLD, BOUNDS_SELECT_THRESHOLD, COLOR_OVERLAY_WHITE, MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT, MAXIMUM_ALT_SCALE_FACTOR, MIN_LENGTH_FOR_CORNERS_VISIBILITY,
|
||||
MIN_LENGTH_FOR_EDGE_RESIZE_PRIORITY_OVER_CORNERS, MIN_LENGTH_FOR_MIDPOINT_VISIBILITY, MIN_LENGTH_FOR_RESIZE_TO_INCLUDE_INTERIOR, MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY, RESIZE_HANDLE_SIZE,
|
||||
SELECTION_DRAG_ANGLE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
@@ -11,7 +11,7 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::compass_rose::Axis;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::Rect;
|
||||
|
||||
/// (top, bottom, left, right)
|
||||
@@ -52,6 +52,8 @@ enum TransformCageSizeCategory {
|
||||
Narrow,
|
||||
/// - 
|
||||
Flat,
|
||||
/// A single point in space with no width or height.
|
||||
Point,
|
||||
}
|
||||
|
||||
impl SelectedEdges {
|
||||
@@ -431,46 +433,24 @@ impl BoundingBoxManager {
|
||||
}
|
||||
|
||||
pub fn check_skew_handle(&self, cursor: DVec2, edge: EdgeBool) -> bool {
|
||||
if let Some([start, end]) = self.edge_endpoints_vector_from_edge_bool(edge) {
|
||||
if (end - start).length() < MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY {
|
||||
return false;
|
||||
}
|
||||
let Some([start, end]) = self.edge_endpoints_vector_from_edge_bool(edge) else { return false };
|
||||
if (end - start).length_squared() < MIN_LENGTH_FOR_SKEW_TRIANGLE_VISIBILITY.powi(2) {
|
||||
return false;
|
||||
};
|
||||
|
||||
let touches_triangle = |base: DVec2, direction: DVec2, cursor: DVec2| -> bool {
|
||||
let normal = direction.perp();
|
||||
let top = base + direction * SKEW_TRIANGLE_SIZE;
|
||||
let edge1 = base + normal * SKEW_TRIANGLE_SIZE / 2.;
|
||||
let edge2 = base - normal * SKEW_TRIANGLE_SIZE / 2.;
|
||||
let edge_dir = (end - start).normalize();
|
||||
let mid = start.midpoint(end);
|
||||
|
||||
let v0 = edge1 - top;
|
||||
let v1 = edge2 - top;
|
||||
let v2 = cursor - top;
|
||||
for direction in [-edge_dir, edge_dir] {
|
||||
let base = mid + direction * (3. + SKEW_TRIANGLE_OFFSET + SKEW_TRIANGLE_SIZE / 2.);
|
||||
let extension = cursor - base;
|
||||
let along_edge = extension.dot(edge_dir).abs();
|
||||
let along_perp = extension.perp_dot(edge_dir).abs();
|
||||
|
||||
let d00 = v0.dot(v0);
|
||||
let d01 = v0.dot(v1);
|
||||
let d11 = v1.dot(v1);
|
||||
let d20 = v2.dot(v0);
|
||||
let d21 = v2.dot(v1);
|
||||
|
||||
let denom = d00 * d11 - d01 * d01;
|
||||
let v = (d11 * d20 - d01 * d21) / denom;
|
||||
let w = (d00 * d21 - d01 * d20) / denom;
|
||||
let u = 1. - v - w;
|
||||
|
||||
u >= 0. && v >= 0. && w >= 0.
|
||||
};
|
||||
|
||||
let edge_dir = (end - start).normalize();
|
||||
let mid = end.midpoint(start);
|
||||
|
||||
for direction in [edge_dir, -edge_dir] {
|
||||
let base = mid + direction * (3. + SKEW_TRIANGLE_OFFSET);
|
||||
if touches_triangle(base, direction, cursor) {
|
||||
return true;
|
||||
}
|
||||
if along_edge <= SKEW_TRIANGLE_SIZE / 2. && along_perp <= BOUNDS_SELECT_THRESHOLD {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
@@ -570,7 +550,7 @@ impl BoundingBoxManager {
|
||||
let quad = self.transform * Quad::from_box(self.bounds);
|
||||
|
||||
// Draw the bounding box rectangle
|
||||
overlay_context.quad(quad, None);
|
||||
overlay_context.quad(quad, None, None);
|
||||
}
|
||||
|
||||
/// Update the position of the bounding box and transform handles
|
||||
@@ -587,7 +567,7 @@ impl BoundingBoxManager {
|
||||
|
||||
let mut draw_handle = |point: DVec2, angle: f64| {
|
||||
let quad = DAffine2::from_angle_translation(angle, point) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
|
||||
overlay_context.quad(quad, Some(COLOR_OVERLAY_WHITE));
|
||||
overlay_context.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
|
||||
};
|
||||
|
||||
let horizontal_angle = (quad.top_left() - quad.bottom_left()).to_angle();
|
||||
@@ -598,7 +578,9 @@ impl BoundingBoxManager {
|
||||
category,
|
||||
TransformCageSizeCategory::Full | TransformCageSizeCategory::Narrow | TransformCageSizeCategory::ReducedLandscape
|
||||
) {
|
||||
horizontal_edges.map(|point| draw_handle(point, horizontal_angle));
|
||||
for point in horizontal_edges {
|
||||
draw_handle(point, horizontal_angle);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the vertical midpoint drag handles
|
||||
@@ -606,7 +588,9 @@ impl BoundingBoxManager {
|
||||
category,
|
||||
TransformCageSizeCategory::Full | TransformCageSizeCategory::Narrow | TransformCageSizeCategory::ReducedPortrait
|
||||
) {
|
||||
vertical_edges.map(|point| draw_handle(point, vertical_angle));
|
||||
for point in vertical_edges {
|
||||
draw_handle(point, vertical_angle);
|
||||
}
|
||||
}
|
||||
|
||||
let angle = quad
|
||||
@@ -621,7 +605,9 @@ impl BoundingBoxManager {
|
||||
category,
|
||||
TransformCageSizeCategory::Full | TransformCageSizeCategory::ReducedBoth | TransformCageSizeCategory::ReducedLandscape | TransformCageSizeCategory::ReducedPortrait
|
||||
) {
|
||||
quad.0.map(|point| draw_handle(point, angle));
|
||||
for point in quad.0 {
|
||||
draw_handle(point, angle);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the flat line endpoint drag handles
|
||||
@@ -635,7 +621,12 @@ impl BoundingBoxManager {
|
||||
fn overlay_display_category(&self) -> TransformCageSizeCategory {
|
||||
let quad = self.transform * Quad::from_box(self.bounds);
|
||||
|
||||
// Check if the area is essentially zero because either the width or height is smaller than an epsilon
|
||||
// Check if the bounds are essentially the same because the width and height are smaller than MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT
|
||||
if self.is_bounds_point() {
|
||||
return TransformCageSizeCategory::Point;
|
||||
}
|
||||
|
||||
// Check if the area is essentially zero because either the width or height is smaller than MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT
|
||||
if self.is_bounds_flat() {
|
||||
return TransformCageSizeCategory::Flat;
|
||||
}
|
||||
@@ -661,7 +652,12 @@ impl BoundingBoxManager {
|
||||
|
||||
/// Determine if these bounds are flat ([`TransformCageSizeCategory::Flat`]), which means that the width and/or height is essentially zero and the bounds are a line with effectively no area. This can happen on actual lines (axis-aligned, i.e. drawn horizontally or vertically) or when an element is scaled to zero in X or Y. A flat transform cage can still be rotated by a transformation, but its local space remains flat.
|
||||
fn is_bounds_flat(&self) -> bool {
|
||||
(self.bounds[0] - self.bounds[1]).abs().cmple(DVec2::splat(1e-4)).any()
|
||||
(self.bounds[0] - self.bounds[1]).abs().cmple(DVec2::splat(MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT)).any()
|
||||
}
|
||||
|
||||
/// Determine if these bounds are point ([`TransformCageSizeCategory::Point`]), which means that the width and height are essentially zero and the bounds are a point with no area. This can happen on points when an element is scaled to zero in both X and Y, or if an element is just a single anchor point. A point transform cage cannot be rotated by a transformation, and its local space remains a point.
|
||||
fn is_bounds_point(&self) -> bool {
|
||||
(self.bounds[0] - self.bounds[1]).abs().cmple(DVec2::splat(MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT)).all()
|
||||
}
|
||||
|
||||
/// Determine if the given point in viewport space falls within the bounds of `self`.
|
||||
@@ -699,7 +695,7 @@ impl BoundingBoxManager {
|
||||
let [edge_min_x, edge_min_y] = self.compute_viewport_threshold(MIN_LENGTH_FOR_RESIZE_TO_INCLUDE_INTERIOR);
|
||||
let [midpoint_threshold_x, midpoint_threshold_y] = self.compute_viewport_threshold(MIN_LENGTH_FOR_EDGE_RESIZE_PRIORITY_OVER_CORNERS);
|
||||
|
||||
if min.x - cursor.x < threshold_x && min.y - cursor.y < threshold_y && cursor.x - max.x < threshold_x && cursor.y - max.y < threshold_y {
|
||||
if (min.x - cursor.x < threshold_x && min.y - cursor.y < threshold_y) && (cursor.x - max.x < threshold_x && cursor.y - max.y < threshold_y) {
|
||||
let mut top = (cursor.y - min.y).abs() < threshold_y;
|
||||
let mut bottom = (max.y - cursor.y).abs() < threshold_y;
|
||||
let mut left = (cursor.x - min.x).abs() < threshold_x;
|
||||
@@ -741,11 +737,11 @@ impl BoundingBoxManager {
|
||||
}
|
||||
|
||||
// On bounds with no width/height, disallow transformation in the relevant axis
|
||||
if width < f64::EPSILON * 1000. {
|
||||
if width < MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT {
|
||||
left = false;
|
||||
right = false;
|
||||
}
|
||||
if height < f64::EPSILON * 1000. {
|
||||
if height < MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT {
|
||||
top = false;
|
||||
bottom = false;
|
||||
}
|
||||
@@ -767,9 +763,12 @@ impl BoundingBoxManager {
|
||||
let [threshold_x, threshold_y] = self.compute_viewport_threshold(BOUNDS_ROTATE_THRESHOLD);
|
||||
let cursor = self.transform.inverse().transform_point2(cursor);
|
||||
|
||||
let flat = (self.bounds[0] - self.bounds[1]).abs().cmple(DVec2::splat(1e-4)).any();
|
||||
let flat = self.is_bounds_flat();
|
||||
let point = self.is_bounds_point();
|
||||
let within_square_bounds = |center: &DVec2| center.x - threshold_x < cursor.x && cursor.x < center.x + threshold_x && center.y - threshold_y < cursor.y && cursor.y < center.y + threshold_y;
|
||||
if flat {
|
||||
if point {
|
||||
false
|
||||
} else if flat {
|
||||
[self.bounds[0], self.bounds[1]].iter().any(within_square_bounds)
|
||||
} else {
|
||||
self.evaluate_transform_handle_positions().iter().any(within_square_bounds)
|
||||
@@ -807,59 +806,64 @@ impl BoundingBoxManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skew_transform_singular() {
|
||||
for edge in [
|
||||
SelectedEdges::new(true, false, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, true, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, true, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, false, true, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
] {
|
||||
// The determinant is 0.
|
||||
let transform = DAffine2::from_cols_array(&[2.; 6]);
|
||||
// This shouldn't panic. We don't really care about the behavior in this test.
|
||||
let _ = edge.skew_transform(DVec2::new(1.5, 1.5), transform, false);
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn skew_transform_singular() {
|
||||
for edge in [
|
||||
SelectedEdges::new(true, false, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, true, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, true, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, false, true, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
] {
|
||||
// The determinant is 0.
|
||||
let transform = DAffine2::from_cols_array(&[2.; 6]);
|
||||
// This shouldn't panic. We don't really care about the behavior in this test.
|
||||
let _ = edge.skew_transform(DVec2::new(1.5, 1.5), transform, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skew_transform_correct() {
|
||||
for edge in [
|
||||
SelectedEdges::new(true, false, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, true, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, true, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, false, true, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
] {
|
||||
// Random transform with det != 0.
|
||||
let to_viewport_transform = DAffine2::from_cols_array(&[2., 1., 0., 1., 2., 3.]);
|
||||
// Random mouse position.
|
||||
let mouse = DVec2::new(1.5, 1.5);
|
||||
let final_transform = edge.skew_transform(mouse, to_viewport_transform, false);
|
||||
|
||||
// This is the current handle that goes under the mouse.
|
||||
let opposite = edge.pivot_from_bounds(edge.bounds[0], edge.bounds[1]);
|
||||
let dragging_point = edge.pivot_from_bounds(edge.bounds[1], edge.bounds[0]);
|
||||
|
||||
let viewport_dragging_point = to_viewport_transform.transform_point2(dragging_point);
|
||||
let parallel_to_x = edge.top || edge.bottom;
|
||||
let parallel_to_y = !parallel_to_x && (edge.left || edge.right);
|
||||
|
||||
let drag_vector = mouse - viewport_dragging_point;
|
||||
let document_drag_vector = to_viewport_transform.inverse().transform_vector2(drag_vector);
|
||||
|
||||
let sign = if edge.top || edge.left { -1. } else { 1. };
|
||||
let scale_factor = (edge.bounds[1] - edge.bounds[0])[parallel_to_x as usize].abs().recip() * sign;
|
||||
let scaled_document_drag = document_drag_vector * scale_factor;
|
||||
|
||||
let skew = DAffine2::from_mat2(DMat2::from_cols_array(&[
|
||||
1.,
|
||||
if parallel_to_y { scaled_document_drag.y } else { 0. },
|
||||
if parallel_to_x { scaled_document_drag.x } else { 0. },
|
||||
1.,
|
||||
]));
|
||||
|
||||
let constructed_transform = DAffine2::from_translation(opposite) * skew * DAffine2::from_translation(-opposite);
|
||||
|
||||
assert_eq!(constructed_transform, final_transform);
|
||||
|
||||
#[test]
|
||||
fn skew_transform_correct() {
|
||||
for edge in [
|
||||
SelectedEdges::new(true, false, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, true, false, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, true, false, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
SelectedEdges::new(false, false, false, true, [DVec2::NEG_ONE, DVec2::ONE]),
|
||||
] {
|
||||
// Random transform with det != 0.
|
||||
let to_viewport_transform = DAffine2::from_cols_array(&[2., 1., 0., 1., 2., 3.]);
|
||||
// Random mouse position.
|
||||
let mouse = DVec2::new(1.5, 1.5);
|
||||
let final_transform = edge.skew_transform(mouse, to_viewport_transform, false);
|
||||
|
||||
// This is the current handle that goes under the mouse.
|
||||
let opposite = edge.pivot_from_bounds(edge.bounds[0], edge.bounds[1]);
|
||||
let dragging_point = edge.pivot_from_bounds(edge.bounds[1], edge.bounds[0]);
|
||||
|
||||
let viewport_dragging_point = to_viewport_transform.transform_point2(dragging_point);
|
||||
let parallel_to_x = edge.top || edge.bottom;
|
||||
let parallel_to_y = !parallel_to_x && (edge.left || edge.right);
|
||||
|
||||
let drag_vector = mouse - viewport_dragging_point;
|
||||
let document_drag_vector = to_viewport_transform.inverse().transform_vector2(drag_vector);
|
||||
|
||||
let sign = if edge.top || edge.left { -1. } else { 1. };
|
||||
let scale_factor = (edge.bounds[1] - edge.bounds[0])[parallel_to_x as usize].abs().recip() * sign;
|
||||
let scaled_document_drag = document_drag_vector * scale_factor;
|
||||
|
||||
let skew = DAffine2::from_mat2(DMat2::from_cols_array(&[
|
||||
1.,
|
||||
if parallel_to_y { scaled_document_drag.y } else { 0. },
|
||||
if parallel_to_x { scaled_document_drag.x } else { 0. },
|
||||
1.,
|
||||
]));
|
||||
|
||||
let constructed_transform = DAffine2::from_translation(opposite) * skew * DAffine2::from_translation(-opposite);
|
||||
|
||||
assert_eq!(constructed_transform, final_transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
use super::snapping::{SnapCandidatePoint, SnapData, SnapManager};
|
||||
use super::transformation_cage::{BoundingBoxManager, SizeSnapData};
|
||||
use crate::consts::ROTATE_INCREMENT;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::transformation::Selected;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_text;
|
||||
use glam::DVec2;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_core::text::{FontCache, load_face};
|
||||
use graphene_std::vector::PointId;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::SelectedEdges;
|
||||
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use bezier_rs::Bezier;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::text::{FontCache, load_face};
|
||||
use graphene_std::vector::{HandleId, ManipulatorPointId, PointId, SegmentId, VectorData, VectorModificationType};
|
||||
|
||||
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
|
||||
pub fn should_extend(
|
||||
@@ -62,7 +70,454 @@ pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageH
|
||||
};
|
||||
|
||||
let buzz_face = font_cache.get(font).map(|data| load_face(data));
|
||||
let far = graphene_core::text::bounding_box(text, buzz_face.as_ref(), typesetting, false);
|
||||
let far = graphene_std::text::bounding_box(text, buzz_face.as_ref(), typesetting, false);
|
||||
|
||||
Quad::from_box([DVec2::ZERO, far])
|
||||
}
|
||||
|
||||
pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector_data: &VectorData, prefer_handle_direction: bool) -> Option<f64> {
|
||||
let is_start = |point: PointId, segment: SegmentId| vector_data.segment_start_from_id(segment) == Some(point);
|
||||
let anchor_position = vector_data.point_domain.position_from_id(anchor)?;
|
||||
let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector_data);
|
||||
let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector_data);
|
||||
|
||||
let start_point = if is_start(anchor, segment) {
|
||||
vector_data.segment_end_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
|
||||
} else {
|
||||
vector_data.segment_start_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
|
||||
};
|
||||
|
||||
let required_handle = if is_start(anchor, segment) {
|
||||
start_handle
|
||||
.filter(|&handle| prefer_handle_direction && handle != anchor_position)
|
||||
.or(end_handle.filter(|&handle| Some(handle) != start_point))
|
||||
.or(start_point)
|
||||
} else {
|
||||
end_handle
|
||||
.filter(|&handle| prefer_handle_direction && handle != anchor_position)
|
||||
.or(start_handle.filter(|&handle| Some(handle) != start_point))
|
||||
.or(start_point)
|
||||
};
|
||||
|
||||
required_handle.map(|handle| -(handle - anchor_position).angle_to(DVec2::X))
|
||||
}
|
||||
|
||||
pub fn adjust_handle_colinearity(handle: HandleId, anchor_position: DVec2, target_control_point: DVec2, vector_data: &VectorData, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
let Some(other_handle) = vector_data.other_colinear_handle(handle) else { return };
|
||||
let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector_data) else {
|
||||
return;
|
||||
};
|
||||
let Some(direction) = (anchor_position - target_control_point).try_normalize() else { return };
|
||||
|
||||
let new_relative_position = (handle_position - anchor_position).length() * direction;
|
||||
let modification_type = other_handle.set_relative_position(new_relative_position);
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
pub fn restore_previous_handle_position(
|
||||
handle: HandleId,
|
||||
original_c: DVec2,
|
||||
anchor_position: DVec2,
|
||||
vector_data: &VectorData,
|
||||
layer: LayerNodeIdentifier,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Option<HandleId> {
|
||||
let other_handle = vector_data.other_colinear_handle(handle)?;
|
||||
let handle_position = other_handle.to_manipulator_point().get_position(vector_data)?;
|
||||
let direction = (anchor_position - original_c).try_normalize()?;
|
||||
|
||||
let old_relative_position = (handle_position - anchor_position).length() * direction;
|
||||
let modification_type = other_handle.set_relative_position(old_relative_position);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
let handles = [handle, other_handle];
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
Some(other_handle)
|
||||
}
|
||||
|
||||
pub fn restore_g1_continuity(
|
||||
handle: HandleId,
|
||||
other_handle: HandleId,
|
||||
control_point: DVec2,
|
||||
anchor_position: DVec2,
|
||||
vector_data: &VectorData,
|
||||
layer: LayerNodeIdentifier,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector_data) else {
|
||||
return;
|
||||
};
|
||||
let Some(direction) = (anchor_position - control_point).try_normalize() else { return };
|
||||
|
||||
let new_relative_position = (handle_position - anchor_position).length() * direction;
|
||||
let modification_type = other_handle.set_relative_position(new_relative_position);
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
let handles = [handle, other_handle];
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: true };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
/// Check whether a point is visible in the current overlay mode.
|
||||
pub fn is_visible_point(
|
||||
manipulator_point_id: ManipulatorPointId,
|
||||
vector_data: &VectorData,
|
||||
path_overlay_mode: PathOverlayMode,
|
||||
frontier_handles_info: Option<HashMap<SegmentId, Vec<PointId>>>,
|
||||
selected_segments: Vec<SegmentId>,
|
||||
selected_points: &HashSet<ManipulatorPointId>,
|
||||
) -> bool {
|
||||
match manipulator_point_id {
|
||||
ManipulatorPointId::Anchor(_) => true,
|
||||
ManipulatorPointId::EndHandle(segment_id) | ManipulatorPointId::PrimaryHandle(segment_id) => {
|
||||
match (path_overlay_mode, selected_points.len() == 1) {
|
||||
(PathOverlayMode::AllHandles, _) => true,
|
||||
(PathOverlayMode::SelectedPointHandles, _) | (PathOverlayMode::FrontierHandles, true) => {
|
||||
if selected_segments.contains(&segment_id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Either the segment is a part of selected segments or the opposite handle is a part of existing selection
|
||||
let Some(handle_pair) = manipulator_point_id.get_handle_pair(vector_data) else { return false };
|
||||
let other_handle = handle_pair[1].to_manipulator_point();
|
||||
|
||||
// Return whether the list of selected points contain the other handle
|
||||
selected_points.contains(&other_handle)
|
||||
}
|
||||
(PathOverlayMode::FrontierHandles, false) => {
|
||||
let Some(anchor) = manipulator_point_id.get_anchor(vector_data) else {
|
||||
warn!("No anchor for selected handle");
|
||||
return false;
|
||||
};
|
||||
let Some(frontier_handles) = &frontier_handles_info else {
|
||||
warn!("No frontier handles info provided");
|
||||
return false;
|
||||
};
|
||||
|
||||
frontier_handles.get(&segment_id).map(|anchors| anchors.contains(&anchor)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize_bounds(
|
||||
document: &DocumentMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
bounds: &mut BoundingBoxManager,
|
||||
dragging_layers: &mut Vec<LayerNodeIdentifier>,
|
||||
snap_manager: &mut SnapManager,
|
||||
snap_candidates: &mut Vec<SnapCandidatePoint>,
|
||||
input: &InputPreprocessorMessageHandler,
|
||||
center: bool,
|
||||
constrain: bool,
|
||||
tool: ToolType,
|
||||
) {
|
||||
if let Some(movement) = &mut bounds.selected_edges {
|
||||
let center = center.then_some(bounds.center_of_transformation);
|
||||
let snap = Some(SizeSnapData {
|
||||
manager: snap_manager,
|
||||
points: snap_candidates,
|
||||
snap_data: SnapData::ignore(document, input, &dragging_layers),
|
||||
});
|
||||
let (position, size) = movement.new_size(input.mouse.position, bounds.original_bound_transform, center, constrain, snap);
|
||||
let (delta, mut pivot) = movement.bounds_to_scale_transform(position, size);
|
||||
|
||||
let pivot_transform = DAffine2::from_translation(pivot);
|
||||
let transformation = pivot_transform * delta * pivot_transform.inverse();
|
||||
|
||||
dragging_layers.retain(|layer| {
|
||||
if *layer != LayerNodeIdentifier::ROOT_PARENT {
|
||||
document.network_interface.document_network().nodes.contains_key(&layer.to_node())
|
||||
} else {
|
||||
log::error!("ROOT_PARENT should not be part of layers_dragging");
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let mut selected = Selected::new(&mut bounds.original_transforms, &mut pivot, &dragging_layers, responses, &document.network_interface, None, &tool, None);
|
||||
selected.apply_transformation(bounds.original_bound_transform * transformation * bounds.original_bound_transform.inverse(), None);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rotate_bounds(
|
||||
document: &DocumentMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
bounds: &mut BoundingBoxManager,
|
||||
dragging_layers: &mut Vec<LayerNodeIdentifier>,
|
||||
drag_start: DVec2,
|
||||
mouse_position: DVec2,
|
||||
snap_angle: bool,
|
||||
tool: ToolType,
|
||||
) {
|
||||
let angle = {
|
||||
let start_offset = drag_start - bounds.center_of_transformation;
|
||||
let end_offset = mouse_position - bounds.center_of_transformation;
|
||||
start_offset.angle_to(end_offset)
|
||||
};
|
||||
|
||||
let snapped_angle = if snap_angle {
|
||||
let snap_resolution = ROTATE_INCREMENT.to_radians();
|
||||
(angle / snap_resolution).round() * snap_resolution
|
||||
} else {
|
||||
angle
|
||||
};
|
||||
|
||||
let delta = DAffine2::from_angle(snapped_angle);
|
||||
|
||||
dragging_layers.retain(|layer| {
|
||||
if *layer != LayerNodeIdentifier::ROOT_PARENT {
|
||||
document.network_interface.document_network().nodes.contains_key(&layer.to_node())
|
||||
} else {
|
||||
log::error!("ROOT_PARENT should not be part of replacement_selected_layers");
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let mut selected = Selected::new(
|
||||
&mut bounds.original_transforms,
|
||||
&mut bounds.center_of_transformation,
|
||||
&dragging_layers,
|
||||
responses,
|
||||
&document.network_interface,
|
||||
None,
|
||||
&tool,
|
||||
None,
|
||||
);
|
||||
selected.update_transforms(delta, None, None);
|
||||
}
|
||||
|
||||
pub fn skew_bounds(
|
||||
document: &DocumentMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
bounds: &mut BoundingBoxManager,
|
||||
free_movement: bool,
|
||||
layers: &mut Vec<LayerNodeIdentifier>,
|
||||
mouse_position: DVec2,
|
||||
tool: ToolType,
|
||||
) {
|
||||
if let Some(movement) = &mut bounds.selected_edges {
|
||||
let mut pivot = DVec2::ZERO;
|
||||
|
||||
let transformation = movement.skew_transform(mouse_position, bounds.original_bound_transform, free_movement);
|
||||
|
||||
layers.retain(|layer| {
|
||||
if *layer != LayerNodeIdentifier::ROOT_PARENT {
|
||||
document.network_interface.document_network().nodes.contains_key(&layer.to_node())
|
||||
} else {
|
||||
log::error!("ROOT_PARENT should not be part of layers_dragging");
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let mut selected = Selected::new(&mut bounds.original_transforms, &mut pivot, &layers, responses, &document.network_interface, None, &tool, None);
|
||||
selected.apply_transformation(bounds.original_bound_transform * transformation * bounds.original_bound_transform.inverse(), None);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Replace returned tuple (where at most 1 element is true at a time) with an enum.
|
||||
/// Returns the tuple (resize, rotate, skew).
|
||||
pub fn transforming_transform_cage(
|
||||
document: &DocumentMessageHandler,
|
||||
mut bounding_box_manager: &mut Option<BoundingBoxManager>,
|
||||
input: &InputPreprocessorMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
layers_dragging: &mut Vec<LayerNodeIdentifier>,
|
||||
) -> (bool, bool, bool) {
|
||||
let dragging_bounds = bounding_box_manager.as_mut().and_then(|bounding_box| {
|
||||
let edges = bounding_box.check_selected_edges(input.mouse.position);
|
||||
|
||||
bounding_box.selected_edges = edges.map(|(top, bottom, left, right)| {
|
||||
let selected_edges = SelectedEdges::new(top, bottom, left, right, bounding_box.bounds);
|
||||
bounding_box.opposite_pivot = selected_edges.calculate_pivot();
|
||||
selected_edges
|
||||
});
|
||||
|
||||
edges
|
||||
});
|
||||
|
||||
let rotating_bounds = bounding_box_manager.as_ref().map(|bounding_box| bounding_box.check_rotate(input.mouse.position)).unwrap_or_default();
|
||||
|
||||
let selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
|
||||
|
||||
let is_flat_layer = bounding_box_manager.as_ref().map(|bounding_box_manager| bounding_box_manager.transform_tampered).unwrap_or(true);
|
||||
|
||||
if dragging_bounds.is_some() && !is_flat_layer {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
*layers_dragging = selected;
|
||||
|
||||
if let Some(bounds) = &mut bounding_box_manager {
|
||||
bounds.original_bound_transform = bounds.transform;
|
||||
|
||||
layers_dragging.retain(|layer| {
|
||||
if *layer != LayerNodeIdentifier::ROOT_PARENT {
|
||||
document.network_interface.document_network().nodes.contains_key(&layer.to_node())
|
||||
} else {
|
||||
log::error!("ROOT_PARENT should not be part of layers_dragging");
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let mut selected = Selected::new(
|
||||
&mut bounds.original_transforms,
|
||||
&mut bounds.center_of_transformation,
|
||||
&layers_dragging,
|
||||
responses,
|
||||
&document.network_interface,
|
||||
None,
|
||||
&ToolType::Select,
|
||||
None,
|
||||
);
|
||||
bounds.center_of_transformation = selected.mean_average_of_pivots();
|
||||
|
||||
// Check if we're hovering over a skew triangle
|
||||
let edges = bounds.check_selected_edges(input.mouse.position);
|
||||
if let Some(edges) = edges {
|
||||
let closest_edge = bounds.get_closest_edge(edges, input.mouse.position);
|
||||
if bounds.check_skew_handle(input.mouse.position, closest_edge) {
|
||||
// No resize or rotate, just skew
|
||||
return (false, false, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Just resize, no rotate or skew
|
||||
return (true, false, false);
|
||||
}
|
||||
|
||||
if rotating_bounds {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
if let Some(bounds) = &mut bounding_box_manager {
|
||||
layers_dragging.retain(|layer| {
|
||||
if *layer != LayerNodeIdentifier::ROOT_PARENT {
|
||||
document.network_interface.document_network().nodes.contains_key(&layer.to_node())
|
||||
} else {
|
||||
log::error!("ROOT_PARENT should not be part of layers_dragging");
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let mut selected = Selected::new(
|
||||
&mut bounds.original_transforms,
|
||||
&mut bounds.center_of_transformation,
|
||||
&selected,
|
||||
responses,
|
||||
&document.network_interface,
|
||||
None,
|
||||
&ToolType::Select,
|
||||
None,
|
||||
);
|
||||
|
||||
bounds.center_of_transformation = selected.mean_average_of_pivots();
|
||||
}
|
||||
|
||||
*layers_dragging = selected;
|
||||
|
||||
// No resize or skew, just rotate
|
||||
return (false, true, false);
|
||||
}
|
||||
|
||||
// No resize, rotate, or skew
|
||||
return (false, false, false);
|
||||
}
|
||||
|
||||
/// Calculates similarity metric between new bezier curve and two old beziers by using sampled points.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn log_optimization(a: f64, b: f64, p1: DVec2, p3: DVec2, d1: DVec2, d2: DVec2, points1: &[DVec2], n: usize) -> f64 {
|
||||
let start_handle_length = a.exp();
|
||||
let end_handle_length = b.exp();
|
||||
|
||||
// Compute the handle positions of new bezier curve
|
||||
let c1 = p1 + d1 * start_handle_length;
|
||||
let c2 = p3 + d2 * end_handle_length;
|
||||
|
||||
let new_curve = Bezier::from_cubic_coordinates(p1.x, p1.y, c1.x, c1.y, c2.x, c2.y, p3.x, p3.y);
|
||||
|
||||
// Sample 2*n points from new curve and get the L2 metric between all of points
|
||||
let points = new_curve.compute_lookup_table(Some(2 * n), None).collect::<Vec<_>>();
|
||||
|
||||
let dist = points1.iter().zip(points.iter()).map(|(p1, p2)| (p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sum::<f64>();
|
||||
|
||||
dist / (2 * n) as f64
|
||||
}
|
||||
|
||||
/// Calculates optimal handle lengths with adam optimization.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn find_two_param_best_approximate(p1: DVec2, p3: DVec2, d1: DVec2, d2: DVec2, min_len1: f64, min_len2: f64, farther_segment: Bezier, other_segment: Bezier) -> (DVec2, DVec2) {
|
||||
let h = 1e-6;
|
||||
let tol = 1e-6;
|
||||
let max_iter = 200;
|
||||
|
||||
let mut a = (5_f64).ln();
|
||||
let mut b = (5_f64).ln();
|
||||
|
||||
let mut m_a = 0.;
|
||||
let mut v_a = 0.;
|
||||
let mut m_b = 0.;
|
||||
let mut v_b = 0.;
|
||||
|
||||
let initial_alpha = 0.05;
|
||||
let decay_rate: f64 = 0.99;
|
||||
|
||||
let beta1 = 0.9;
|
||||
let beta2 = 0.999;
|
||||
let epsilon = 1e-8;
|
||||
|
||||
let n = 20;
|
||||
|
||||
let farther_segment = if farther_segment.start.distance(p1) >= f64::EPSILON {
|
||||
farther_segment.reverse()
|
||||
} else {
|
||||
farther_segment
|
||||
};
|
||||
|
||||
let other_segment = if other_segment.end.distance(p3) >= f64::EPSILON { other_segment.reverse() } else { other_segment };
|
||||
|
||||
// Now we sample points proportional to the lengths of the beziers
|
||||
let l1 = farther_segment.length(None);
|
||||
let l2 = other_segment.length(None);
|
||||
let ratio = l1 / (l1 + l2);
|
||||
let n_points1 = ((2 * n) as f64 * ratio).floor() as usize;
|
||||
let mut points1 = farther_segment.compute_lookup_table(Some(n_points1), None).collect::<Vec<_>>();
|
||||
let mut points2 = other_segment.compute_lookup_table(Some(n), None).collect::<Vec<_>>();
|
||||
points1.append(&mut points2);
|
||||
|
||||
let f = |a: f64, b: f64| -> f64 { log_optimization(a, b, p1, p3, d1, d2, &points1, n) };
|
||||
|
||||
for t in 1..=max_iter {
|
||||
let dfa = (f(a + h, b) - f(a - h, b)) / (2. * h);
|
||||
let dfb = (f(a, b + h) - f(a, b - h)) / (2. * h);
|
||||
|
||||
m_a = beta1 * m_a + (1. - beta1) * dfa;
|
||||
m_b = beta1 * m_b + (1. - beta1) * dfb;
|
||||
|
||||
v_a = beta2 * v_a + (1. - beta2) * dfa * dfa;
|
||||
v_b = beta2 * v_b + (1. - beta2) * dfb * dfb;
|
||||
|
||||
let m_a_hat = m_a / (1. - beta1.powi(t));
|
||||
let v_a_hat = v_a / (1. - beta2.powi(t));
|
||||
let m_b_hat = m_b / (1. - beta1.powi(t));
|
||||
let v_b_hat = v_b / (1. - beta2.powi(t));
|
||||
|
||||
let alpha_t = initial_alpha * decay_rate.powi(t);
|
||||
|
||||
// Update log-lengths
|
||||
a -= alpha_t * m_a_hat / (v_a_hat.sqrt() + epsilon);
|
||||
b -= alpha_t * m_b_hat / (v_b_hat.sqrt() + epsilon);
|
||||
|
||||
// Convergence check
|
||||
if dfa.abs() < tol && dfb.abs() < tol {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let len1 = a.exp().max(min_len1);
|
||||
let len2 = b.exp().max(min_len2);
|
||||
|
||||
(d1 * len1, d2 * len2)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::utility_types::ToolType;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
#[impl_message(Message, Tool)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -32,13 +32,7 @@ pub enum ToolMessage {
|
||||
#[child]
|
||||
Spline(SplineToolMessage),
|
||||
#[child]
|
||||
Line(LineToolMessage),
|
||||
#[child]
|
||||
Rectangle(RectangleToolMessage),
|
||||
#[child]
|
||||
Ellipse(EllipseToolMessage),
|
||||
#[child]
|
||||
Polygon(PolygonToolMessage),
|
||||
Shape(ShapeToolMessage),
|
||||
#[child]
|
||||
Text(TextToolMessage),
|
||||
|
||||
@@ -62,7 +56,6 @@ pub enum ToolMessage {
|
||||
ActivateToolArtboard,
|
||||
ActivateToolNavigate,
|
||||
ActivateToolEyedropper,
|
||||
ActivateToolText,
|
||||
ActivateToolFill,
|
||||
ActivateToolGradient,
|
||||
|
||||
@@ -70,10 +63,11 @@ pub enum ToolMessage {
|
||||
ActivateToolPen,
|
||||
ActivateToolFreehand,
|
||||
ActivateToolSpline,
|
||||
ActivateToolLine,
|
||||
ActivateToolRectangle,
|
||||
ActivateToolEllipse,
|
||||
ActivateToolPolygon,
|
||||
ActivateToolShapeLine,
|
||||
ActivateToolShapeRectangle,
|
||||
ActivateToolShapeEllipse,
|
||||
ActivateToolShape,
|
||||
ActivateToolText,
|
||||
|
||||
ActivateToolBrush,
|
||||
// ActivateToolImaginate,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::common_functionality::shape_editor::ShapeState;
|
||||
use super::common_functionality::shapes::shape_utility::ShapeType::{self, Ellipse, Line, Rectangle};
|
||||
use super::utility_types::{ToolActionHandlerData, ToolFsmState, tool_message_to_tool_type};
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
@@ -7,7 +8,7 @@ use crate::messages::portfolio::utility_types::PersistentData;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graphene_core::raster::color::Color;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
const ARTBOARD_OVERLAY_PROVIDER: OverlayProvider = |context| DocumentMessage::DrawArtboardOverlays(context).into();
|
||||
|
||||
@@ -58,21 +59,47 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
|
||||
ToolMessage::ActivateToolPen => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Pen }),
|
||||
ToolMessage::ActivateToolFreehand => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Freehand }),
|
||||
ToolMessage::ActivateToolSpline => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Spline }),
|
||||
ToolMessage::ActivateToolLine => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Line }),
|
||||
ToolMessage::ActivateToolRectangle => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Rectangle }),
|
||||
ToolMessage::ActivateToolEllipse => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Ellipse }),
|
||||
ToolMessage::ActivateToolPolygon => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Polygon }),
|
||||
|
||||
ToolMessage::ActivateToolShape => {
|
||||
if self.tool_state.tool_data.active_shape_type.is_some() {
|
||||
self.tool_state.tool_data.active_shape_type = None;
|
||||
self.tool_state.tool_data.active_tool_type = ToolType::Shape;
|
||||
}
|
||||
responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Shape });
|
||||
responses.add(ShapeToolMessage::SetShape(ShapeType::Polygon));
|
||||
responses.add(ShapeToolMessage::HideShapeTypeWidget(false))
|
||||
}
|
||||
ToolMessage::ActivateToolBrush => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Brush }),
|
||||
ToolMessage::ActivateToolShapeLine | ToolMessage::ActivateToolShapeRectangle | ToolMessage::ActivateToolShapeEllipse => {
|
||||
let shape = match message {
|
||||
ToolMessage::ActivateToolShapeLine => Line,
|
||||
ToolMessage::ActivateToolShapeRectangle => Rectangle,
|
||||
ToolMessage::ActivateToolShapeEllipse => Ellipse,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
self.tool_state.tool_data.active_shape_type = Some(shape.tool_type());
|
||||
responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Shape });
|
||||
responses.add(ShapeToolMessage::HideShapeTypeWidget(true));
|
||||
responses.add(ShapeToolMessage::SetShape(shape));
|
||||
}
|
||||
// ToolMessage::ActivateToolImaginate => responses.add_front(ToolMessage::ActivateTool { tool_type: ToolType::Imaginate }),
|
||||
ToolMessage::ActivateTool { tool_type } => {
|
||||
let tool_data = &mut self.tool_state.tool_data;
|
||||
let old_tool = tool_data.active_tool_type;
|
||||
let old_tool = tool_data.active_tool_type.get_tool();
|
||||
let tool_type = tool_type.get_tool();
|
||||
|
||||
responses.add(ToolMessage::RefreshToolOptions);
|
||||
tool_data.send_layout(responses, LayoutTarget::ToolShelf);
|
||||
|
||||
// Do nothing if switching to the same tool
|
||||
if self.tool_is_active && tool_type == old_tool {
|
||||
return;
|
||||
}
|
||||
|
||||
if tool_type != ToolType::Shape {
|
||||
tool_data.active_shape_type = None;
|
||||
}
|
||||
|
||||
self.tool_is_active = true;
|
||||
|
||||
// Send the old and new tools a transition to their FSM Abort states
|
||||
@@ -218,7 +245,7 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
|
||||
let document_data = &mut self.tool_state.document_tool_data;
|
||||
document_data.primary_color = color;
|
||||
|
||||
self.tool_state.document_tool_data.update_working_colors(responses); // TODO: Make this an event
|
||||
document_data.update_working_colors(responses); // TODO: Make this an event
|
||||
}
|
||||
ToolMessage::SelectRandomPrimaryColor => {
|
||||
// Select a random primary color (rgba) based on an UUID
|
||||
@@ -299,7 +326,6 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
|
||||
ActivateToolArtboard,
|
||||
ActivateToolNavigate,
|
||||
ActivateToolEyedropper,
|
||||
ActivateToolText,
|
||||
ActivateToolFill,
|
||||
ActivateToolGradient,
|
||||
|
||||
@@ -307,10 +333,11 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
|
||||
ActivateToolPen,
|
||||
ActivateToolFreehand,
|
||||
ActivateToolSpline,
|
||||
ActivateToolLine,
|
||||
ActivateToolRectangle,
|
||||
ActivateToolEllipse,
|
||||
ActivateToolPolygon,
|
||||
ActivateToolShapeLine,
|
||||
ActivateToolShapeRectangle,
|
||||
ActivateToolShapeEllipse,
|
||||
ActivateToolShape,
|
||||
ActivateToolText,
|
||||
|
||||
ActivateToolBrush,
|
||||
// ActivateToolImaginate,
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::messages::tool::common_functionality::snapping::SnapData;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapManager;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::renderer::Quad;
|
||||
use graphene_std::renderer::Quad;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ArtboardTool {
|
||||
@@ -225,16 +225,17 @@ impl Fsm for ArtboardToolFsmState {
|
||||
let ToolMessage::Artboard(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(state, ArtboardToolMessage::Overlays(mut overlay_context)) => {
|
||||
if state != ArtboardToolFsmState::Drawing {
|
||||
let display_transform_cage = overlay_context.visibility_settings.transform_cage();
|
||||
if display_transform_cage && state != ArtboardToolFsmState::Drawing {
|
||||
if let Some(bounds) = tool_data.selected_artboard.and_then(|layer| document.metadata().bounding_box_document(layer)) {
|
||||
let bounding_box_manager = tool_data.bounding_box_manager.get_or_insert(BoundingBoxManager::default());
|
||||
bounding_box_manager.bounds = bounds;
|
||||
bounding_box_manager.transform = document.metadata().document_to_viewport;
|
||||
|
||||
bounding_box_manager.render_overlays(&mut overlay_context, true);
|
||||
} else {
|
||||
tool_data.bounding_box_manager.take();
|
||||
}
|
||||
} else {
|
||||
tool_data.bounding_box_manager.take();
|
||||
}
|
||||
|
||||
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
@@ -267,7 +268,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
let constrain_square = input.keyboard.get(constrain_axis_or_aspect as usize);
|
||||
tool_data.resize_artboard(responses, document, input, from_center, constrain_square);
|
||||
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }.into(),
|
||||
ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }.into(),
|
||||
@@ -306,7 +307,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
bounds.bounds[0] = position.round();
|
||||
bounds.bounds[1] = position.round() + size.round();
|
||||
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }.into(),
|
||||
ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }.into(),
|
||||
@@ -334,18 +335,18 @@ impl Fsm for ArtboardToolFsmState {
|
||||
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
artboard: graphene_core::Artboard {
|
||||
graphic_group: graphene_core::GraphicGroupTable::default(),
|
||||
artboard: graphene_std::Artboard {
|
||||
graphic_group: graphene_std::GraphicGroupTable::default(),
|
||||
label: String::from("Artboard"),
|
||||
location: start.min(end).round().as_ivec2(),
|
||||
dimensions: (start.round() - end.round()).abs().as_ivec2(),
|
||||
background: graphene_core::Color::WHITE,
|
||||
background: graphene_std::Color::WHITE,
|
||||
clip: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }.into(),
|
||||
ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }.into(),
|
||||
@@ -377,25 +378,25 @@ impl Fsm for ArtboardToolFsmState {
|
||||
ArtboardToolFsmState::Ready { hovered }
|
||||
}
|
||||
(ArtboardToolFsmState::ResizingBounds, ArtboardToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
ArtboardToolFsmState::ResizingBounds
|
||||
}
|
||||
(ArtboardToolFsmState::Dragging, ArtboardToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
ArtboardToolFsmState::Dragging
|
||||
}
|
||||
(ArtboardToolFsmState::Drawing, ArtboardToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
ArtboardToolFsmState::Drawing
|
||||
}
|
||||
(state, ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }) => {
|
||||
// AutoPanning
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
ArtboardToolMessage::PointerOutsideViewport { constrain_axis_or_aspect, center }.into(),
|
||||
ArtboardToolMessage::PointerMove { constrain_axis_or_aspect, center }.into(),
|
||||
@@ -561,9 +562,12 @@ impl Fsm for ArtboardToolFsmState {
|
||||
mod test_artboard {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> Vec<graphene_core::Artboard> {
|
||||
let instrumented = editor.eval_graph().await;
|
||||
instrumented.grab_all_input::<graphene_core::append_artboard::ArtboardInput>(&editor.runtime).collect()
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> Vec<graphene_std::Artboard> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {}", e),
|
||||
};
|
||||
instrumented.grab_all_input::<graphene_std::append_artboard::ArtboardInput>(&editor.runtime).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -7,9 +7,9 @@ use crate::messages::portfolio::document::utility_types::network_interface::Flow
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::raster::BlendMode;
|
||||
use graphene_core::vector::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::vector::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle};
|
||||
|
||||
const BRUSH_MAX_SIZE: f64 = 5000.;
|
||||
|
||||
@@ -276,15 +276,16 @@ impl BrushToolData {
|
||||
let Some(reference) = document.network_interface.reference(&node_id, &[]) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if *reference == Some("Brush".to_string()) && node_id != layer.to_node() {
|
||||
let points_input = node.inputs.get(2)?;
|
||||
let Some(TaggedValue::BrushStrokes(strokes)) = points_input.as_value() else {
|
||||
continue;
|
||||
};
|
||||
let points_input = node.inputs.get(1)?;
|
||||
let Some(TaggedValue::BrushStrokes(strokes)) = points_input.as_value() else { continue };
|
||||
self.strokes.clone_from(strokes);
|
||||
|
||||
return Some(layer);
|
||||
} else if *reference == Some("Transform".to_string()) {
|
||||
}
|
||||
|
||||
if *reference == Some("Transform".to_string()) {
|
||||
let upstream = document.metadata().upstream_transform(node_id);
|
||||
let pivot = DAffine2::from_translation(upstream.transform_point2(get_current_normalized_pivot(&node.inputs)));
|
||||
self.transform = pivot * get_current_transform(&node.inputs) * pivot.inverse() * self.transform;
|
||||
|
||||
@@ -1,441 +0,0 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::resize::Resize;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapData;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::Color;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct EllipseTool {
|
||||
fsm_state: EllipseToolFsmState,
|
||||
data: EllipseToolData,
|
||||
options: EllipseToolOptions,
|
||||
}
|
||||
|
||||
pub struct EllipseToolOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
}
|
||||
|
||||
impl Default for EllipseToolOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_secondary(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum EllipseOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
}
|
||||
|
||||
#[impl_message(Message, ToolMessage, Ellipse)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum EllipseToolMessage {
|
||||
// Standard messages
|
||||
Overlays(OverlayContext),
|
||||
Abort,
|
||||
WorkingColorChanged,
|
||||
|
||||
// Tool-specific messages
|
||||
DragStart,
|
||||
DragStop,
|
||||
PointerMove { center: Key, lock_ratio: Key },
|
||||
PointerOutsideViewport { center: Key, lock_ratio: Key },
|
||||
UpdateOptions(EllipseOptionsUpdate),
|
||||
}
|
||||
|
||||
impl ToolMetadata for EllipseTool {
|
||||
fn icon_name(&self) -> String {
|
||||
"VectorEllipseTool".into()
|
||||
}
|
||||
fn tooltip(&self) -> String {
|
||||
"Ellipse Tool".into()
|
||||
}
|
||||
fn tool_type(&self) -> crate::messages::tool::utility_types::ToolType {
|
||||
ToolType::Ellipse
|
||||
}
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetHolder {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::LineWeight(number_input.value.unwrap())).into())
|
||||
.widget_holder()
|
||||
}
|
||||
|
||||
impl LayoutHolder for EllipseTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::FillColor(None)).into(),
|
||||
|color_type: ToolColorType| WidgetCallback::new(move |_| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::FillColorType(color_type.clone())).into()),
|
||||
|color: &ColorInput| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb()))).into(),
|
||||
);
|
||||
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::StrokeColor(None)).into(),
|
||||
|color_type: ToolColorType| WidgetCallback::new(move |_| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::StrokeColorType(color_type.clone())).into()),
|
||||
|color: &ColorInput| EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb()))).into(),
|
||||
));
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
|
||||
Layout::WidgetLayout(WidgetLayout::new(vec![LayoutGroup::Row { widgets }]))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for EllipseTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, tool_data: &mut ToolActionHandlerData<'a>) {
|
||||
let ToolMessage::Ellipse(EllipseToolMessage::UpdateOptions(action)) = message else {
|
||||
self.fsm_state.process_event(message, &mut self.data, tool_data, &self.options, responses, true);
|
||||
return;
|
||||
};
|
||||
match action {
|
||||
EllipseOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
}
|
||||
EllipseOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
EllipseOptionsUpdate::LineWeight(line_weight) => self.options.line_weight = line_weight,
|
||||
EllipseOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
}
|
||||
EllipseOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
EllipseOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
}
|
||||
}
|
||||
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
match self.fsm_state {
|
||||
EllipseToolFsmState::Ready => actions!(EllipseToolMessageDiscriminant;
|
||||
DragStart,
|
||||
PointerMove,
|
||||
),
|
||||
EllipseToolFsmState::Drawing => actions!(EllipseToolMessageDiscriminant;
|
||||
DragStop,
|
||||
Abort,
|
||||
PointerMove,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolTransition for EllipseTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
overlay_provider: Some(|overlay_context| EllipseToolMessage::Overlays(overlay_context).into()),
|
||||
tool_abort: Some(EllipseToolMessage::Abort.into()),
|
||||
working_color_changed: Some(EllipseToolMessage::WorkingColorChanged.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum EllipseToolFsmState {
|
||||
#[default]
|
||||
Ready,
|
||||
Drawing,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct EllipseToolData {
|
||||
data: Resize,
|
||||
auto_panning: AutoPanning,
|
||||
}
|
||||
|
||||
impl Fsm for EllipseToolFsmState {
|
||||
type ToolData = EllipseToolData;
|
||||
type ToolOptions = EllipseToolOptions;
|
||||
|
||||
fn transition(self, event: ToolMessage, tool_data: &mut Self::ToolData, tool_action_data: &mut ToolActionHandlerData, tool_options: &Self::ToolOptions, responses: &mut VecDeque<Message>) -> Self {
|
||||
let ToolActionHandlerData {
|
||||
document, global_tool_data, input, ..
|
||||
} = tool_action_data;
|
||||
|
||||
let shape_data = &mut tool_data.data;
|
||||
|
||||
let ToolMessage::Ellipse(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(_, EllipseToolMessage::Overlays(mut overlay_context)) => {
|
||||
shape_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
self
|
||||
}
|
||||
(EllipseToolFsmState::Ready, EllipseToolMessage::DragStart) => {
|
||||
shape_data.start(document, input);
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
// Create a new ellipse vector shape
|
||||
let node_type = resolve_document_node_type("Ellipse").expect("Ellipse node does not exist");
|
||||
let node = node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(0.5), false)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
let nodes = vec![(NodeId(0), node)];
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, document.new_layer_bounding_artboard(input), responses);
|
||||
responses.add(Message::StartBuffer);
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::ONE, 0., input.mouse.position),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, responses);
|
||||
shape_data.layer = Some(layer);
|
||||
|
||||
EllipseToolFsmState::Drawing
|
||||
}
|
||||
(EllipseToolFsmState::Drawing, EllipseToolMessage::PointerMove { center, lock_ratio }) => {
|
||||
if let Some([start, end]) = shape_data.calculate_points(document, input, center, lock_ratio) {
|
||||
if let Some(layer) = shape_data.layer {
|
||||
let Some(node_id) = graph_modification_utils::get_ellipse_id(layer, &document.network_interface) else {
|
||||
return self;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::F64(((start.x - end.x) / 2.).abs()), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(((start.y - end.y) / 2.).abs()), false),
|
||||
});
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_translation((start + end) / 2.),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
EllipseToolMessage::PointerOutsideViewport { center, lock_ratio }.into(),
|
||||
EllipseToolMessage::PointerMove { center, lock_ratio }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, &messages, responses);
|
||||
|
||||
self
|
||||
}
|
||||
(_, EllipseToolMessage::PointerMove { .. }) => {
|
||||
shape_data.snap_manager.preview_draw(&SnapData::new(document, input), input.mouse.position);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
self
|
||||
}
|
||||
(EllipseToolFsmState::Drawing, EllipseToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
EllipseToolFsmState::Drawing
|
||||
}
|
||||
(state, EllipseToolMessage::PointerOutsideViewport { center, lock_ratio }) => {
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
EllipseToolMessage::PointerOutsideViewport { center, lock_ratio }.into(),
|
||||
EllipseToolMessage::PointerMove { center, lock_ratio }.into(),
|
||||
];
|
||||
tool_data.auto_panning.stop(&messages, responses);
|
||||
|
||||
state
|
||||
}
|
||||
(EllipseToolFsmState::Drawing, EllipseToolMessage::DragStop) => {
|
||||
input.mouse.finish_transaction(shape_data.viewport_drag_start(document), responses);
|
||||
shape_data.cleanup(responses);
|
||||
|
||||
EllipseToolFsmState::Ready
|
||||
}
|
||||
(EllipseToolFsmState::Drawing, EllipseToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
shape_data.cleanup(responses);
|
||||
|
||||
EllipseToolFsmState::Ready
|
||||
}
|
||||
(_, EllipseToolMessage::WorkingColorChanged) => {
|
||||
responses.add(EllipseToolMessage::UpdateOptions(EllipseOptionsUpdate::WorkingColors(
|
||||
Some(global_tool_data.primary_color),
|
||||
Some(global_tool_data.secondary_color),
|
||||
)));
|
||||
self
|
||||
}
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_hints(&self, responses: &mut VecDeque<Message>) {
|
||||
let hint_data = match self {
|
||||
EllipseToolFsmState::Ready => HintData(vec![HintGroup(vec![
|
||||
HintInfo::mouse(MouseMotion::LmbDrag, "Draw Ellipse"),
|
||||
HintInfo::keys([Key::Shift], "Constrain Circular").prepend_plus(),
|
||||
HintInfo::keys([Key::Alt], "From Center").prepend_plus(),
|
||||
])]),
|
||||
EllipseToolFsmState::Drawing => HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![HintInfo::keys([Key::Shift], "Constrain Circular"), HintInfo::keys([Key::Alt], "From Center")]),
|
||||
]),
|
||||
};
|
||||
|
||||
responses.add(FrontendMessage::UpdateInputHints { hint_data });
|
||||
}
|
||||
|
||||
fn update_cursor(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair });
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_ellipse {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_core::vector::generator_nodes::ellipse;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct ResolvedEllipse {
|
||||
radius_x: f64,
|
||||
radius_y: f64,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
async fn get_ellipse(editor: &mut EditorTestUtils) -> Vec<ResolvedEllipse> {
|
||||
let instrumented = editor.eval_graph().await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layers = document.metadata().all_layers();
|
||||
layers
|
||||
.filter_map(|layer| {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::protonode_identifier())?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_simple() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Ellipse, 10., 10., 19., 0., ModifierKeys::empty()).await;
|
||||
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 1);
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(
|
||||
ellipse[0],
|
||||
ResolvedEllipse {
|
||||
radius_x: 4.5,
|
||||
radius_y: 5.,
|
||||
transform: DAffine2::from_translation(DVec2::new(14.5, 5.)) // Uses center
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_circle() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Ellipse, 10., 10., -10., 11., ModifierKeys::SHIFT).await;
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(
|
||||
ellipse[0],
|
||||
ResolvedEllipse {
|
||||
radius_x: 10.,
|
||||
radius_y: 10.,
|
||||
transform: DAffine2::from_translation(DVec2::new(0., 20.)) // Uses center
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_square_rotated() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(NavigationMessage::CanvasTiltSet {
|
||||
// 45 degree rotation of content clockwise
|
||||
angle_radians: f64::consts::FRAC_PI_4,
|
||||
})
|
||||
.await;
|
||||
editor.drag_tool(ToolType::Ellipse, 0., 0., 1., 10., ModifierKeys::SHIFT).await; // Viewport coordinates
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
println!("{ellipse:?}");
|
||||
assert_eq!(ellipse[0].radius_x, 5.);
|
||||
assert_eq!(ellipse[0].radius_y, 5.);
|
||||
|
||||
assert!(
|
||||
ellipse[0]
|
||||
.transform
|
||||
.abs_diff_eq(DAffine2::from_angle_translation(-f64::consts::FRAC_PI_4, DVec2::X * f64::consts::FRAC_1_SQRT_2 * 10.), 0.001)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_draw_center_square_rotated() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor
|
||||
.handle_message(NavigationMessage::CanvasTiltSet {
|
||||
// 45 degree rotation of content clockwise
|
||||
angle_radians: f64::consts::FRAC_PI_4,
|
||||
})
|
||||
.await;
|
||||
editor.drag_tool(ToolType::Ellipse, 0., 0., 1., 10., ModifierKeys::SHIFT | ModifierKeys::ALT).await; // Viewport coordinates
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 1);
|
||||
assert_eq!(ellipse[0].radius_x, 10.);
|
||||
assert_eq!(ellipse[0].radius_y, 10.);
|
||||
assert!(ellipse[0].transform.abs_diff_eq(DAffine2::from_angle(-f64::consts::FRAC_PI_4), 0.001));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ellipse_cancel() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool_cancel_rmb(ToolType::Ellipse).await;
|
||||
|
||||
let ellipse = get_ellipse(&mut editor).await;
|
||||
assert_eq!(ellipse.len(), 0);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use graphene_core::vector::style::Fill;
|
||||
use graphene_std::vector::style::Fill;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FillTool {
|
||||
fsm_state: FillToolFsmState,
|
||||
}
|
||||
|
||||
#[impl_message(Message, ToolMessage, Fill)]
|
||||
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum FillToolMessage {
|
||||
// Standard messages
|
||||
Abort,
|
||||
WorkingColorChanged,
|
||||
Overlays(OverlayContext),
|
||||
|
||||
// Tool-specific messages
|
||||
PointerMove,
|
||||
PointerUp,
|
||||
FillPrimaryColor,
|
||||
FillSecondaryColor,
|
||||
@@ -45,8 +50,10 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for FillToo
|
||||
FillToolFsmState::Ready => actions!(FillToolMessageDiscriminant;
|
||||
FillPrimaryColor,
|
||||
FillSecondaryColor,
|
||||
PointerMove,
|
||||
),
|
||||
FillToolFsmState::Filling => actions!(FillToolMessageDiscriminant;
|
||||
PointerMove,
|
||||
PointerUp,
|
||||
Abort,
|
||||
),
|
||||
@@ -58,6 +65,8 @@ impl ToolTransition for FillTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
tool_abort: Some(FillToolMessage::Abort.into()),
|
||||
working_color_changed: Some(FillToolMessage::WorkingColorChanged.into()),
|
||||
overlay_provider: Some(|overlay_context| FillToolMessage::Overlays(overlay_context).into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -82,6 +91,23 @@ impl Fsm for FillToolFsmState {
|
||||
|
||||
let ToolMessage::Fill(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(_, FillToolMessage::Overlays(mut overlay_context)) => {
|
||||
// Choose the working color to preview
|
||||
let use_secondary = input.keyboard.get(Key::Shift as usize);
|
||||
let preview_color = if use_secondary { global_tool_data.secondary_color } else { global_tool_data.primary_color };
|
||||
|
||||
// Get the layer the user is hovering over
|
||||
if let Some(layer) = document.click(input) {
|
||||
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &preview_color);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
(_, FillToolMessage::PointerMove | FillToolMessage::WorkingColorChanged) => {
|
||||
// Generate the hover outline
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
self
|
||||
}
|
||||
(FillToolFsmState::Ready, color_event) => {
|
||||
let Some(layer_identifier) = document.click(input) else {
|
||||
return self;
|
||||
@@ -131,11 +157,14 @@ impl Fsm for FillToolFsmState {
|
||||
#[cfg(test)]
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_core::vector::fill;
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Fill;
|
||||
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Fill> {
|
||||
let instrumented = editor.eval_graph().await;
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
instrumented.grab_all_input::<fill::FillInput<Fill>>(&editor.runtime).collect()
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::utility_functions::should_extend;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::vector::VectorModificationType;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::{PointId, SegmentId};
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -340,3 +340,383 @@ fn extend_path_with_next_segment(tool_data: &mut FreehandToolData, position: DVe
|
||||
tool_data.dragged = true;
|
||||
tool_data.end_point = Some((position, id));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_freehand {
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_width;
|
||||
use crate::messages::tool::tool_messages::freehand_tool::FreehandOptionsUpdate;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::vector::VectorData;
|
||||
|
||||
async fn get_vector_data(editor: &mut EditorTestUtils) -> Vec<(VectorData, DAffine2)> {
|
||||
let document = editor.active_document();
|
||||
let layers = document.metadata().all_layers();
|
||||
|
||||
layers
|
||||
.filter_map(|layer| {
|
||||
let vector_data = document.network_interface.compute_modified_vector(layer)?;
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
Some((vector_data, transform))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn verify_path_points(vector_data_list: &[(VectorData, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> {
|
||||
if vector_data_list.len() == 0 {
|
||||
return Err("No vector data found after drawing".to_string());
|
||||
}
|
||||
|
||||
let path_data = vector_data_list.iter().find(|(data, _)| data.point_domain.ids().len() > 0).ok_or("Could not find path data")?;
|
||||
|
||||
let (vector_data, transform) = path_data;
|
||||
let point_count = vector_data.point_domain.ids().len();
|
||||
let segment_count = vector_data.segment_domain.ids().len();
|
||||
|
||||
let actual_positions: Vec<DVec2> = vector_data
|
||||
.point_domain
|
||||
.ids()
|
||||
.iter()
|
||||
.filter_map(|&point_id| {
|
||||
let position = vector_data.point_domain.position_from_id(point_id)?;
|
||||
Some(transform.transform_point2(position))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if segment_count != point_count - 1 {
|
||||
return Err(format!("Expected segments to be one less than points, got {} segments for {} points", segment_count, point_count));
|
||||
}
|
||||
|
||||
if point_count != expected_captured_points.len() {
|
||||
return Err(format!("Expected {} points, got {}", expected_captured_points.len(), point_count));
|
||||
}
|
||||
|
||||
for (i, (&expected, &actual)) in expected_captured_points.iter().zip(actual_positions.iter()).enumerate() {
|
||||
let distance = (expected - actual).length();
|
||||
if distance >= tolerance {
|
||||
return Err(format!("Point {} position mismatch: expected {:?}, got {:?} (distance: {})", i, expected, actual, distance));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_freehand_transformed_artboard() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.drag_tool(ToolType::Artboard, 0., 0., 500., 500., ModifierKeys::empty()).await;
|
||||
|
||||
let metadata = editor.active_document().metadata();
|
||||
let artboard = metadata.all_layers().next().unwrap();
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::TransformSet {
|
||||
layer: artboard,
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.8), 0.3, DVec2::new(10.0, -5.0)),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.select_tool(ToolType::Freehand).await;
|
||||
|
||||
let mouse_points = [DVec2::new(150.0, 100.0), DVec2::new(200.0, 150.0), DVec2::new(250.0, 130.0), DVec2::new(300.0, 170.0)];
|
||||
|
||||
// Expected points that will actually be captured by the tool
|
||||
let expected_captured_points = &mouse_points[1..];
|
||||
editor.drag_path(&mouse_points, ModifierKeys::empty()).await;
|
||||
|
||||
let vector_data_list = get_vector_data(&mut editor).await;
|
||||
verify_path_points(&vector_data_list, expected_captured_points, 1.0).expect("Path points verification failed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_extend_existing_path() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let initial_points = [DVec2::new(100.0, 100.0), DVec2::new(200.0, 200.0), DVec2::new(300.0, 100.0)];
|
||||
|
||||
editor.select_tool(ToolType::Freehand).await;
|
||||
|
||||
let first_point = initial_points[0];
|
||||
editor.move_mouse(first_point.x, first_point.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(first_point.x, first_point.y, ModifierKeys::empty()).await;
|
||||
|
||||
for &point in &initial_points[1..] {
|
||||
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
}
|
||||
|
||||
let last_initial_point = initial_points[initial_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
editor_position: last_initial_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let initial_vector_data = get_vector_data(&mut editor).await;
|
||||
assert!(!initial_vector_data.is_empty(), "No vector data found after initial drawing");
|
||||
|
||||
let (initial_data, transform) = &initial_vector_data[0];
|
||||
let initial_point_count = initial_data.point_domain.ids().len();
|
||||
let initial_segment_count = initial_data.segment_domain.ids().len();
|
||||
|
||||
assert!(initial_point_count >= 2, "Expected at least 2 points in initial path, found {}", initial_point_count);
|
||||
assert_eq!(
|
||||
initial_segment_count,
|
||||
initial_point_count - 1,
|
||||
"Expected {} segments in initial path, found {}",
|
||||
initial_point_count - 1,
|
||||
initial_segment_count
|
||||
);
|
||||
|
||||
let extendable_points = initial_data.extendable_points(false).collect::<Vec<_>>();
|
||||
assert!(!extendable_points.is_empty(), "No extendable points found in the path");
|
||||
|
||||
let endpoint_id = extendable_points[0];
|
||||
let endpoint_pos_option = initial_data.point_domain.position_from_id(endpoint_id);
|
||||
assert!(endpoint_pos_option.is_some(), "Could not find position for endpoint");
|
||||
|
||||
let endpoint_pos = endpoint_pos_option.unwrap();
|
||||
let endpoint_viewport_pos = transform.transform_point2(endpoint_pos);
|
||||
|
||||
assert!(endpoint_viewport_pos.is_finite(), "Endpoint position is not finite");
|
||||
|
||||
let extension_points = [DVec2::new(400.0, 200.0), DVec2::new(500.0, 100.0)];
|
||||
|
||||
let layer_node_id = {
|
||||
let document = editor.active_document();
|
||||
let layer = document.metadata().all_layers().next().unwrap();
|
||||
layer.to_node()
|
||||
};
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer_node_id] }).await;
|
||||
|
||||
editor.select_tool(ToolType::Freehand).await;
|
||||
|
||||
editor.move_mouse(endpoint_viewport_pos.x, endpoint_viewport_pos.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(endpoint_viewport_pos.x, endpoint_viewport_pos.y, ModifierKeys::empty()).await;
|
||||
|
||||
for &point in &extension_points {
|
||||
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
}
|
||||
|
||||
let last_extension_point = extension_points[extension_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
editor_position: last_extension_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let extended_vector_data = get_vector_data(&mut editor).await;
|
||||
assert!(!extended_vector_data.is_empty(), "No vector data found after extension");
|
||||
|
||||
let (extended_data, _) = &extended_vector_data[0];
|
||||
let extended_point_count = extended_data.point_domain.ids().len();
|
||||
let extended_segment_count = extended_data.segment_domain.ids().len();
|
||||
|
||||
assert!(
|
||||
extended_point_count > initial_point_count,
|
||||
"Expected more points after extension, initial: {}, after extension: {}",
|
||||
initial_point_count,
|
||||
extended_point_count
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
extended_segment_count,
|
||||
extended_point_count - 1,
|
||||
"Expected segments to be one less than points, points: {}, segments: {}",
|
||||
extended_point_count,
|
||||
extended_segment_count
|
||||
);
|
||||
|
||||
let layer_count = {
|
||||
let document = editor.active_document();
|
||||
document.metadata().all_layers().count()
|
||||
};
|
||||
assert_eq!(layer_count, 1, "Expected only one layer after extending path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_append_to_selected_layer_with_shift() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.select_tool(ToolType::Freehand).await;
|
||||
|
||||
let initial_points = [DVec2::new(100.0, 100.0), DVec2::new(200.0, 200.0), DVec2::new(300.0, 100.0)];
|
||||
|
||||
let first_point = initial_points[0];
|
||||
editor.move_mouse(first_point.x, first_point.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(first_point.x, first_point.y, ModifierKeys::empty()).await;
|
||||
|
||||
for &point in &initial_points[1..] {
|
||||
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
}
|
||||
|
||||
let last_initial_point = initial_points[initial_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
editor_position: last_initial_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let initial_vector_data = get_vector_data(&mut editor).await;
|
||||
assert!(!initial_vector_data.is_empty(), "No vector data found after initial drawing");
|
||||
|
||||
let (initial_data, _) = &initial_vector_data[0];
|
||||
let initial_point_count = initial_data.point_domain.ids().len();
|
||||
let initial_segment_count = initial_data.segment_domain.ids().len();
|
||||
|
||||
let existing_layer_id = {
|
||||
let document = editor.active_document();
|
||||
let layer = document.metadata().all_layers().next().unwrap();
|
||||
layer
|
||||
};
|
||||
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: vec![existing_layer_id.to_node()],
|
||||
})
|
||||
.await;
|
||||
|
||||
let second_path_points = [DVec2::new(400.0, 100.0), DVec2::new(500.0, 200.0), DVec2::new(600.0, 100.0)];
|
||||
|
||||
let first_second_point = second_path_points[0];
|
||||
editor.move_mouse(first_second_point.x, first_second_point.y, ModifierKeys::SHIFT, MouseKeys::empty()).await;
|
||||
|
||||
editor
|
||||
.mousedown(
|
||||
EditorMouseState {
|
||||
editor_position: first_second_point,
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::SHIFT,
|
||||
)
|
||||
.await;
|
||||
|
||||
for &point in &second_path_points[1..] {
|
||||
editor.move_mouse(point.x, point.y, ModifierKeys::SHIFT, MouseKeys::LEFT).await;
|
||||
}
|
||||
|
||||
let last_second_point = second_path_points[second_path_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
editor_position: last_second_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::SHIFT,
|
||||
)
|
||||
.await;
|
||||
|
||||
let final_vector_data = get_vector_data(&mut editor).await;
|
||||
assert!(!final_vector_data.is_empty(), "No vector data found after second drawing");
|
||||
|
||||
// Verify we still have only one layer
|
||||
let layer_count = {
|
||||
let document = editor.active_document();
|
||||
document.metadata().all_layers().count()
|
||||
};
|
||||
assert_eq!(layer_count, 1, "Expected only one layer after drawing with Shift key");
|
||||
|
||||
let (final_data, _) = &final_vector_data[0];
|
||||
let final_point_count = final_data.point_domain.ids().len();
|
||||
let final_segment_count = final_data.segment_domain.ids().len();
|
||||
|
||||
assert!(
|
||||
final_point_count > initial_point_count,
|
||||
"Expected more points after appending to layer, initial: {}, after append: {}",
|
||||
initial_point_count,
|
||||
final_point_count
|
||||
);
|
||||
|
||||
let expected_new_points = second_path_points.len();
|
||||
let expected_new_segments = expected_new_points - 1;
|
||||
|
||||
assert_eq!(
|
||||
final_point_count,
|
||||
initial_point_count + expected_new_points,
|
||||
"Expected {} total points after append",
|
||||
initial_point_count + expected_new_points
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
final_segment_count,
|
||||
initial_segment_count + expected_new_segments,
|
||||
"Expected {} total segments after append",
|
||||
initial_segment_count + expected_new_segments
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_weight_affects_stroke_width() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.select_tool(ToolType::Freehand).await;
|
||||
|
||||
let custom_line_weight = 5.0;
|
||||
editor
|
||||
.handle_message(ToolMessage::Freehand(FreehandToolMessage::UpdateOptions(FreehandOptionsUpdate::LineWeight(custom_line_weight))))
|
||||
.await;
|
||||
|
||||
let points = [DVec2::new(100.0, 100.0), DVec2::new(200.0, 200.0), DVec2::new(300.0, 100.0)];
|
||||
|
||||
let first_point = points[0];
|
||||
editor.move_mouse(first_point.x, first_point.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(first_point.x, first_point.y, ModifierKeys::empty()).await;
|
||||
|
||||
for &point in &points[1..] {
|
||||
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
}
|
||||
|
||||
let last_point = points[points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
editor_position: last_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = document.metadata().all_layers().next().unwrap();
|
||||
|
||||
let stroke_width = get_stroke_width(layer, &document.network_interface);
|
||||
|
||||
assert!(stroke_width.is_some(), "Stroke width should be available on the created path");
|
||||
|
||||
assert_eq!(
|
||||
stroke_width.unwrap(),
|
||||
custom_line_weight,
|
||||
"Stroke width should match the custom line weight (expected {}, got {})",
|
||||
custom_line_weight,
|
||||
stroke_width.unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_gradient};
|
||||
use crate::messages::tool::common_functionality::snapping::SnapManager;
|
||||
use graphene_core::vector::style::{Fill, Gradient, GradientType};
|
||||
use graphene_std::vector::style::{Fill, Gradient, GradientType};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct GradientTool {
|
||||
@@ -90,11 +90,11 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for Gradien
|
||||
impl LayoutHolder for GradientTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let gradient_type = RadioInput::new(vec![
|
||||
RadioEntryData::new("linear")
|
||||
RadioEntryData::new("Linear")
|
||||
.label("Linear")
|
||||
.tooltip("Linear gradient")
|
||||
.on_update(move |_| GradientToolMessage::UpdateOptions(GradientOptionsUpdate::Type(GradientType::Linear)).into()),
|
||||
RadioEntryData::new("radial")
|
||||
RadioEntryData::new("Radial")
|
||||
.label("Radial")
|
||||
.tooltip("Radial gradient")
|
||||
.on_update(move |_| GradientToolMessage::UpdateOptions(GradientOptionsUpdate::Type(GradientType::Radial)).into()),
|
||||
@@ -535,17 +535,21 @@ impl Fsm for GradientToolFsmState {
|
||||
mod test_gradient {
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::ScrollDelta;
|
||||
use crate::messages::portfolio::document::{graph_operation::utility_types::TransformIn, utility_types::misc::GroupFolderType};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_core::vector::fill;
|
||||
use graphene_core::vector::style::Gradient;
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Fill;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
|
||||
use super::gradient_space_transform;
|
||||
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<(Fill, DAffine2)> {
|
||||
let instrumented = editor.eval_graph().await;
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {}", e),
|
||||
};
|
||||
|
||||
let document = editor.active_document();
|
||||
let layers = document.metadata().all_layers();
|
||||
@@ -611,7 +615,7 @@ mod test_gradient {
|
||||
|
||||
let (gradient, transform) = get_gradient(&mut editor).await;
|
||||
|
||||
// Gradient goes from secondary colour to primary colour
|
||||
// Gradient goes from secondary color to primary color
|
||||
let stops = gradient.stops.iter().map(|stop| (stop.0, stop.1.to_rgba8_srgb())).collect::<Vec<_>>();
|
||||
assert_eq!(stops, vec![(0., Color::BLUE.to_rgba8_srgb()), (1., Color::GREEN.to_rgba8_srgb())]);
|
||||
assert!(transform.transform_point2(gradient.start).abs_diff_eq(DVec2::new(2., 3.), 1e-10));
|
||||
|
||||
@@ -1,604 +0,0 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{BOUNDS_SELECT_THRESHOLD, DEFAULT_STROKE_WIDTH, LINE_ROTATE_SNAP_ANGLE};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer};
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::Color;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LineTool {
|
||||
fsm_state: LineToolFsmState,
|
||||
tool_data: LineToolData,
|
||||
options: LineOptions,
|
||||
}
|
||||
|
||||
pub struct LineOptions {
|
||||
line_weight: f64,
|
||||
stroke: ToolColorOptions,
|
||||
}
|
||||
|
||||
impl Default for LineOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[impl_message(Message, ToolMessage, Line)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum LineToolMessage {
|
||||
// Standard messages
|
||||
Overlays(OverlayContext),
|
||||
Abort,
|
||||
WorkingColorChanged,
|
||||
|
||||
// Tool-specific messages
|
||||
DragStart,
|
||||
DragStop,
|
||||
PointerMove { center: Key, lock_angle: Key, snap_angle: Key },
|
||||
PointerOutsideViewport { center: Key, lock_angle: Key, snap_angle: Key },
|
||||
UpdateOptions(LineOptionsUpdate),
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum LineOptionsUpdate {
|
||||
LineWeight(f64),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
}
|
||||
|
||||
impl ToolMetadata for LineTool {
|
||||
fn icon_name(&self) -> String {
|
||||
"VectorLineTool".into()
|
||||
}
|
||||
fn tooltip(&self) -> String {
|
||||
"Line Tool".into()
|
||||
}
|
||||
fn tool_type(&self) -> crate::messages::tool::utility_types::ToolType {
|
||||
ToolType::Line
|
||||
}
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetHolder {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| LineToolMessage::UpdateOptions(LineOptionsUpdate::LineWeight(number_input.value.unwrap())).into())
|
||||
.widget_holder()
|
||||
}
|
||||
|
||||
impl LayoutHolder for LineTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| LineToolMessage::UpdateOptions(LineOptionsUpdate::StrokeColor(None)).into(),
|
||||
|color_type: ToolColorType| WidgetCallback::new(move |_| LineToolMessage::UpdateOptions(LineOptionsUpdate::StrokeColorType(color_type.clone())).into()),
|
||||
|color: &ColorInput| LineToolMessage::UpdateOptions(LineOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb()))).into(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
|
||||
Layout::WidgetLayout(WidgetLayout::new(vec![LayoutGroup::Row { widgets }]))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for LineTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, tool_data: &mut ToolActionHandlerData<'a>) {
|
||||
let ToolMessage::Line(LineToolMessage::UpdateOptions(action)) = message else {
|
||||
self.fsm_state.process_event(message, &mut self.tool_data, tool_data, &self.options, responses, true);
|
||||
return;
|
||||
};
|
||||
match action {
|
||||
LineOptionsUpdate::LineWeight(line_weight) => self.options.line_weight = line_weight,
|
||||
LineOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
}
|
||||
LineOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
LineOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
}
|
||||
}
|
||||
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
match self.fsm_state {
|
||||
LineToolFsmState::Ready => actions!(LineToolMessageDiscriminant; DragStart, PointerMove),
|
||||
LineToolFsmState::Drawing => actions!(LineToolMessageDiscriminant; DragStop, PointerMove, Abort),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolTransition for LineTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
overlay_provider: Some(|overlay_context| LineToolMessage::Overlays(overlay_context).into()),
|
||||
tool_abort: Some(LineToolMessage::Abort.into()),
|
||||
working_color_changed: Some(LineToolMessage::WorkingColorChanged.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
enum LineToolFsmState {
|
||||
#[default]
|
||||
Ready,
|
||||
Drawing,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum LineEnd {
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct LineToolData {
|
||||
drag_begin: DVec2,
|
||||
drag_start_shifted: DVec2,
|
||||
drag_current_shifted: DVec2,
|
||||
drag_start: DVec2,
|
||||
drag_current: DVec2,
|
||||
angle: f64,
|
||||
weight: f64,
|
||||
selected_layers_with_position: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
||||
editing_layer: Option<LayerNodeIdentifier>,
|
||||
snap_manager: SnapManager,
|
||||
auto_panning: AutoPanning,
|
||||
dragging_endpoint: Option<LineEnd>,
|
||||
}
|
||||
|
||||
impl Fsm for LineToolFsmState {
|
||||
type ToolData = LineToolData;
|
||||
type ToolOptions = LineOptions;
|
||||
|
||||
fn transition(self, event: ToolMessage, tool_data: &mut Self::ToolData, tool_action_data: &mut ToolActionHandlerData, tool_options: &Self::ToolOptions, responses: &mut VecDeque<Message>) -> Self {
|
||||
let ToolActionHandlerData {
|
||||
document, global_tool_data, input, ..
|
||||
} = tool_action_data;
|
||||
|
||||
let ToolMessage::Line(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(_, LineToolMessage::Overlays(mut overlay_context)) => {
|
||||
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
|
||||
tool_data.selected_layers_with_position = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs("Line")?;
|
||||
|
||||
let (Some(&TaggedValue::DVec2(start)), Some(&TaggedValue::DVec2(end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let [viewport_start, viewport_end] = [start, end].map(|point| document.metadata().transform_to_viewport(layer).transform_point2(point));
|
||||
if !start.abs_diff_eq(end, f64::EPSILON * 1000.) {
|
||||
overlay_context.line(viewport_start, viewport_end, None, None);
|
||||
overlay_context.square(viewport_start, Some(6.), None, None);
|
||||
overlay_context.square(viewport_end, Some(6.), None, None);
|
||||
}
|
||||
|
||||
Some((layer, [start, end]))
|
||||
})
|
||||
.collect::<HashMap<LayerNodeIdentifier, [DVec2; 2]>>();
|
||||
|
||||
self
|
||||
}
|
||||
(LineToolFsmState::Ready, LineToolMessage::DragStart) => {
|
||||
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
|
||||
let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input), &point, SnapTypeConfiguration::default());
|
||||
tool_data.drag_start = snapped.snapped_point_document;
|
||||
tool_data.drag_begin = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start);
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
for (layer, [document_start, document_end]) in tool_data.selected_layers_with_position.iter() {
|
||||
let transform = document.metadata().transform_to_viewport(*layer);
|
||||
let viewport_x = transform.transform_vector2(DVec2::X).normalize_or_zero() * BOUNDS_SELECT_THRESHOLD;
|
||||
let viewport_y = transform.transform_vector2(DVec2::Y).normalize_or_zero() * BOUNDS_SELECT_THRESHOLD;
|
||||
let threshold_x = transform.inverse().transform_vector2(viewport_x).length();
|
||||
let threshold_y = transform.inverse().transform_vector2(viewport_y).length();
|
||||
|
||||
let drag_start = input.mouse.position;
|
||||
let [start, end] = [document_start, document_end].map(|point| transform.transform_point2(*point));
|
||||
|
||||
let start_click = (drag_start.y - start.y).abs() < threshold_y && (drag_start.x - start.x).abs() < threshold_x;
|
||||
let end_click = (drag_start.y - end.y).abs() < threshold_y && (drag_start.x - end.x).abs() < threshold_x;
|
||||
|
||||
if start_click || end_click {
|
||||
tool_data.dragging_endpoint = Some(if end_click { LineEnd::End } else { LineEnd::Start });
|
||||
tool_data.drag_start = if end_click { *document_start } else { *document_end };
|
||||
tool_data.editing_layer = Some(*layer);
|
||||
return LineToolFsmState::Drawing;
|
||||
}
|
||||
}
|
||||
|
||||
let node_type = resolve_document_node_type("Line").expect("Line node does not exist");
|
||||
let node = node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(
|
||||
TaggedValue::DVec2(document.metadata().document_to_viewport.transform_point2(tool_data.drag_start)),
|
||||
false,
|
||||
)),
|
||||
Some(NodeInput::value(
|
||||
TaggedValue::DVec2(document.metadata().document_to_viewport.transform_point2(tool_data.drag_start)),
|
||||
false,
|
||||
)),
|
||||
]);
|
||||
let nodes = vec![(NodeId(0), node)];
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, document.new_layer_bounding_artboard(input), responses);
|
||||
responses.add(Message::StartBuffer);
|
||||
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, responses);
|
||||
|
||||
tool_data.editing_layer = Some(layer);
|
||||
tool_data.angle = 0.;
|
||||
tool_data.weight = tool_options.line_weight;
|
||||
|
||||
LineToolFsmState::Drawing
|
||||
}
|
||||
(LineToolFsmState::Drawing, LineToolMessage::PointerMove { center, snap_angle, lock_angle }) => {
|
||||
let Some(layer) = tool_data.editing_layer else { return LineToolFsmState::Ready };
|
||||
|
||||
tool_data.drag_current_shifted = document.metadata().transform_to_viewport(layer).inverse().transform_point2(input.mouse.position);
|
||||
tool_data.drag_current = document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position);
|
||||
tool_data.drag_start_shifted = document.metadata().transform_to_viewport(layer).inverse().transform_point2(tool_data.drag_begin);
|
||||
|
||||
let keyboard = &input.keyboard;
|
||||
let ignore = vec![layer];
|
||||
let snap_data = SnapData::ignore(document, input, &ignore);
|
||||
let mut document_points = generate_line(tool_data, snap_data, keyboard.key(lock_angle), keyboard.key(snap_angle), keyboard.key(center));
|
||||
|
||||
if tool_data.dragging_endpoint == Some(LineEnd::Start) {
|
||||
document_points.swap(0, 1);
|
||||
}
|
||||
|
||||
let Some(node_id) = graph_modification_utils::get_line_id(layer, &document.network_interface) else {
|
||||
return LineToolFsmState::Ready;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 1),
|
||||
input: NodeInput::value(TaggedValue::DVec2(document_points[0]), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::DVec2(document_points[1]), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
LineToolMessage::PointerOutsideViewport { center, snap_angle, lock_angle }.into(),
|
||||
LineToolMessage::PointerMove { center, snap_angle, lock_angle }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, &messages, responses);
|
||||
|
||||
LineToolFsmState::Drawing
|
||||
}
|
||||
(_, LineToolMessage::PointerMove { .. }) => {
|
||||
tool_data.snap_manager.preview_draw(&SnapData::new(document, input), input.mouse.position);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
self
|
||||
}
|
||||
(LineToolFsmState::Drawing, LineToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
LineToolFsmState::Drawing
|
||||
}
|
||||
(state, LineToolMessage::PointerOutsideViewport { center, lock_angle, snap_angle }) => {
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
LineToolMessage::PointerOutsideViewport { center, lock_angle, snap_angle }.into(),
|
||||
LineToolMessage::PointerMove { center, lock_angle, snap_angle }.into(),
|
||||
];
|
||||
tool_data.auto_panning.stop(&messages, responses);
|
||||
|
||||
state
|
||||
}
|
||||
(LineToolFsmState::Drawing, LineToolMessage::DragStop) => {
|
||||
tool_data.snap_manager.cleanup(responses);
|
||||
tool_data.editing_layer.take();
|
||||
input.mouse.finish_transaction(tool_data.drag_start, responses);
|
||||
LineToolFsmState::Ready
|
||||
}
|
||||
(LineToolFsmState::Drawing, LineToolMessage::Abort) => {
|
||||
tool_data.snap_manager.cleanup(responses);
|
||||
tool_data.editing_layer.take();
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
LineToolFsmState::Ready
|
||||
}
|
||||
(_, LineToolMessage::WorkingColorChanged) => {
|
||||
responses.add(LineToolMessage::UpdateOptions(LineOptionsUpdate::WorkingColors(
|
||||
Some(global_tool_data.primary_color),
|
||||
Some(global_tool_data.secondary_color),
|
||||
)));
|
||||
self
|
||||
}
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_hints(&self, responses: &mut VecDeque<Message>) {
|
||||
let hint_data = match self {
|
||||
LineToolFsmState::Ready => HintData(vec![HintGroup(vec![
|
||||
HintInfo::mouse(MouseMotion::LmbDrag, "Draw Line"),
|
||||
HintInfo::keys([Key::Shift], "15° Increments").prepend_plus(),
|
||||
HintInfo::keys([Key::Alt], "From Center").prepend_plus(),
|
||||
HintInfo::keys([Key::Control], "Lock Angle").prepend_plus(),
|
||||
])]),
|
||||
LineToolFsmState::Drawing => HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![
|
||||
HintInfo::keys([Key::Shift], "15° Increments"),
|
||||
HintInfo::keys([Key::Alt], "From Center"),
|
||||
HintInfo::keys([Key::Control], "Lock Angle"),
|
||||
]),
|
||||
]),
|
||||
};
|
||||
|
||||
responses.add(FrontendMessage::UpdateInputHints { hint_data });
|
||||
}
|
||||
|
||||
fn update_cursor(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair });
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_line(tool_data: &mut LineToolData, snap_data: SnapData, lock_angle: bool, snap_angle: bool, center: bool) -> [DVec2; 2] {
|
||||
let shift = tool_data.drag_current_shifted - tool_data.drag_current;
|
||||
let mut document_points = [tool_data.drag_start, tool_data.drag_current];
|
||||
|
||||
let mut angle = -(document_points[1] - document_points[0]).angle_to(DVec2::X);
|
||||
let mut line_length = (document_points[1] - document_points[0]).length();
|
||||
|
||||
if lock_angle {
|
||||
angle = tool_data.angle;
|
||||
} else if snap_angle {
|
||||
let snap_resolution = LINE_ROTATE_SNAP_ANGLE.to_radians();
|
||||
angle = (angle / snap_resolution).round() * snap_resolution;
|
||||
}
|
||||
|
||||
tool_data.angle = angle;
|
||||
|
||||
let angle_vec = DVec2::from_angle(angle);
|
||||
if lock_angle {
|
||||
line_length = (document_points[1] - document_points[0]).dot(angle_vec);
|
||||
}
|
||||
|
||||
document_points[1] = document_points[0] + line_length * angle_vec;
|
||||
|
||||
let constrained = snap_angle || lock_angle;
|
||||
let snap = &mut tool_data.snap_manager;
|
||||
|
||||
let near_point = SnapCandidatePoint::handle_neighbors(document_points[1], [tool_data.drag_start]);
|
||||
let far_point = SnapCandidatePoint::handle_neighbors(2. * document_points[0] - document_points[1], [tool_data.drag_start]);
|
||||
let config = SnapTypeConfiguration::default();
|
||||
|
||||
if constrained {
|
||||
let constraint = SnapConstraint::Line {
|
||||
origin: document_points[0],
|
||||
direction: document_points[1] - document_points[0],
|
||||
};
|
||||
if center {
|
||||
let snapped = snap.constrained_snap(&snap_data, &near_point, constraint, config);
|
||||
let snapped_far = snap.constrained_snap(&snap_data, &far_point, constraint, config);
|
||||
let best = if snapped_far.other_snap_better(&snapped) { snapped } else { snapped_far };
|
||||
document_points[1] = document_points[0] * 2. - best.snapped_point_document;
|
||||
document_points[0] = best.snapped_point_document;
|
||||
snap.update_indicator(best);
|
||||
} else {
|
||||
let snapped = snap.constrained_snap(&snap_data, &near_point, constraint, config);
|
||||
document_points[1] = snapped.snapped_point_document;
|
||||
snap.update_indicator(snapped);
|
||||
}
|
||||
} else if center {
|
||||
let snapped = snap.free_snap(&snap_data, &near_point, config);
|
||||
let snapped_far = snap.free_snap(&snap_data, &far_point, config);
|
||||
let best = if snapped_far.other_snap_better(&snapped) { snapped } else { snapped_far };
|
||||
document_points[1] = document_points[0] * 2. - best.snapped_point_document;
|
||||
document_points[0] = best.snapped_point_document;
|
||||
snap.update_indicator(best);
|
||||
} else {
|
||||
let snapped = snap.free_snap(&snap_data, &near_point, config);
|
||||
document_points[1] = snapped.snapped_point_document;
|
||||
snap.update_indicator(snapped);
|
||||
}
|
||||
|
||||
// Snapping happens in other space, while document graph renders in another.
|
||||
document_points.map(|vector| vector + shift)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_line_tool {
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::{messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer, test_utils::test_prelude::*};
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
async fn get_line_node_inputs(editor: &mut EditorTestUtils) -> Option<(DVec2, DVec2)> {
|
||||
let document = editor.active_document();
|
||||
let network_interface = &document.network_interface;
|
||||
let node_id = network_interface
|
||||
.selected_nodes()
|
||||
.selected_visible_and_unlocked_layers(network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &network_interface).find_node_inputs("Line")?;
|
||||
let (Some(&TaggedValue::DVec2(start)), Some(&TaggedValue::DVec2(end))) = (node_inputs[1].as_value(), node_inputs[2].as_value()) else {
|
||||
return None;
|
||||
};
|
||||
Some((start, end))
|
||||
})
|
||||
.next();
|
||||
node_id
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_basicdraw() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
assert!((start_input - DVec2::ZERO).length() < 1.0, "Start point should be near (0,0)");
|
||||
assert!((end_input - DVec2::new(100.0, 100.0)).length() < 1.0, "End point should be near (100,100)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_with_transformed_viewport() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2.0 }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100.0, 50.0) }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 30.0_f64.to_radians() }).await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
let document = editor.active_document();
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
|
||||
let expected_start = viewport_to_document.transform_point2(DVec2::ZERO);
|
||||
let expected_end = viewport_to_document.transform_point2(DVec2::new(100.0, 100.0));
|
||||
|
||||
assert!(
|
||||
(start_input - expected_start).length() < 1.0,
|
||||
"Start point should match expected document coordinates. Got {:?}, expected {:?}",
|
||||
start_input,
|
||||
expected_start
|
||||
);
|
||||
assert!(
|
||||
(end_input - expected_end).length() < 1.0,
|
||||
"End point should match expected document coordinates. Got {:?}, expected {:?}",
|
||||
end_input,
|
||||
expected_end
|
||||
);
|
||||
} else {
|
||||
panic!("Line was not created successfully with transformed viewport");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_ctrl_anglelock() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::CONTROL).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let line_vec = end_input - start_input;
|
||||
let original_angle = line_vec.angle_to(DVec2::X);
|
||||
editor.drag_tool(ToolType::Line, 0., 0., 200., 50., ModifierKeys::CONTROL).await;
|
||||
if let Some((updated_start, updated_end)) = get_line_node_inputs(&mut editor).await {
|
||||
match (updated_start, updated_end) {
|
||||
(updated_start, updated_end) => {
|
||||
let updated_line_vec = updated_end - updated_start;
|
||||
let updated_angle = updated_line_vec.angle_to(DVec2::X);
|
||||
assert!((original_angle - updated_angle).abs() < 0.1, "Line angle should be locked when Ctrl is kept pressed");
|
||||
assert!((updated_start - updated_end).length() > 1.0, "Line should be able to change length when Ctrl is kept pressed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_alt() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 100., 100., 200., 100., ModifierKeys::ALT).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let expected_start = DVec2::new(0., 100.);
|
||||
let expected_end = DVec2::new(200., 100.);
|
||||
assert!((start_input - expected_start).length() < 1.0, "start point should be near (0,100)");
|
||||
assert!((end_input - expected_end).length() < 1.0, "end point should be near (200,100)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_alt_shift_drag() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Line, 100., 100., 150., 120., ModifierKeys::ALT | ModifierKeys::SHIFT).await;
|
||||
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
|
||||
match (start_input, end_input) {
|
||||
(start_input, end_input) => {
|
||||
let line_vec = end_input - start_input;
|
||||
let angle_radians = line_vec.angle_to(DVec2::X);
|
||||
let angle_degrees = angle_radians.to_degrees();
|
||||
let nearest_angle = (angle_degrees / 15.0).round() * 15.0;
|
||||
|
||||
assert!((angle_degrees - nearest_angle).abs() < 1.0, "Angle should snap to the nearest 15 degrees");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_line_tool_with_transformed_artboard() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 200., ModifierKeys::empty()).await;
|
||||
|
||||
let artboard_id = editor.get_selected_layer().await.expect("Should have selected the artboard");
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::TransformChange {
|
||||
layer: artboard_id,
|
||||
transform: DAffine2::from_angle(45.0_f64.to_radians()),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.drag_tool(ToolType::Line, 50., 50., 150., 150., ModifierKeys::empty()).await;
|
||||
|
||||
let (start_input, end_input) = get_line_node_inputs(&mut editor).await.expect("Line was not created successfully within transformed artboard");
|
||||
// The line should still be diagonal with equal change in x and y
|
||||
let line_vector = end_input - start_input;
|
||||
// Verifying the line is approximately 100*sqrt(2) units in length (diagonal of 100x100 square)
|
||||
let line_length = line_vector.length();
|
||||
assert!(
|
||||
(line_length - 141.42).abs() < 1.0, // 100 * sqrt(2) ~= 141.42
|
||||
"Line length should be approximately 141.42 units. Got: {line_length}"
|
||||
);
|
||||
assert!((line_vector.x - 100.0).abs() < 1.0, "X-component of line vector should be approximately 100. Got: {}", line_vector.x);
|
||||
assert!(
|
||||
(line_vector.y.abs() - 100.0).abs() < 1.0,
|
||||
"Absolute Y-component of line vector should be approximately 100. Got: {}",
|
||||
line_vector.y.abs()
|
||||
);
|
||||
let angle_degrees = line_vector.angle_to(DVec2::X).to_degrees();
|
||||
assert!((angle_degrees - (-45.0)).abs() < 1.0, "Line angle should be close to -45 degrees. Got: {angle_degrees}");
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,15 @@
|
||||
pub mod artboard_tool;
|
||||
pub mod brush_tool;
|
||||
pub mod ellipse_tool;
|
||||
pub mod eyedropper_tool;
|
||||
pub mod fill_tool;
|
||||
pub mod freehand_tool;
|
||||
pub mod gradient_tool;
|
||||
// pub mod imaginate_tool;
|
||||
pub mod line_tool;
|
||||
pub mod navigate_tool;
|
||||
pub mod path_tool;
|
||||
pub mod pen_tool;
|
||||
pub mod polygon_tool;
|
||||
pub mod rectangle_tool;
|
||||
pub mod select_tool;
|
||||
pub mod shape_tool;
|
||||
pub mod spline_tool;
|
||||
pub mod text_tool;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE};
|
||||
use crate::consts::{COLOR_OVERLAY_BLUE, DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE, SEGMENT_OVERLAY_SIZE};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
|
||||
@@ -10,12 +10,12 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, merge_layers};
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
|
||||
use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend};
|
||||
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, closest_point, should_extend};
|
||||
use bezier_rs::{Bezier, BezierHandles};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::vector::{PointId, VectorModificationType};
|
||||
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, VectorData};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, StrokeId, VectorData};
|
||||
use graphene_std::vector::{PointId, VectorModificationType};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PenTool {
|
||||
@@ -361,6 +361,9 @@ struct PenToolData {
|
||||
current_layer: Option<LayerNodeIdentifier>,
|
||||
prior_segment_endpoint: Option<PointId>,
|
||||
prior_segment: Option<SegmentId>,
|
||||
|
||||
/// For vector meshes, storing all the previous segments the last anchor point was connected to
|
||||
prior_segments: Option<Vec<SegmentId>>,
|
||||
handle_type: TargetHandle,
|
||||
handle_start_offset: Option<DVec2>,
|
||||
handle_end_offset: Option<DVec2>,
|
||||
@@ -533,7 +536,15 @@ impl PenToolData {
|
||||
}
|
||||
|
||||
/// If the user places the anchor on top of the previous anchor, it becomes sharp and the outgoing handle may be dragged.
|
||||
fn bend_from_previous_point(&mut self, snap_data: SnapData, transform: DAffine2, layer: LayerNodeIdentifier, preferences: &PreferencesMessageHandler) {
|
||||
fn bend_from_previous_point(
|
||||
&mut self,
|
||||
snap_data: SnapData,
|
||||
transform: DAffine2,
|
||||
layer: LayerNodeIdentifier,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
shape_editor: &mut ShapeState,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
self.g1_continuous = true;
|
||||
let document = snap_data.document;
|
||||
self.next_handle_start = self.next_point;
|
||||
@@ -567,6 +578,43 @@ impl PenToolData {
|
||||
}
|
||||
|
||||
// Closing path
|
||||
let closing_path_on_point = self.close_path_on_point(snap_data, &vector_data, document, preferences, id, &transform);
|
||||
if !closing_path_on_point && preferences.vector_meshes {
|
||||
// Attempt to find nearest segment and close path on segment by creating an anchor point on it
|
||||
let tolerance = crate::consts::SNAP_POINT_TOLERANCE;
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, transform.transform_point2(self.next_point), tolerance) {
|
||||
let (point, _) = closest_segment.adjusted_insert(responses);
|
||||
|
||||
self.update_handle_type(TargetHandle::PreviewInHandle);
|
||||
self.handle_end_offset = None;
|
||||
self.path_closed = true;
|
||||
self.next_handle_start = self.next_point;
|
||||
|
||||
self.prior_segment_endpoint = Some(point);
|
||||
self.prior_segment_layer = Some(closest_segment.layer());
|
||||
self.prior_segments = None;
|
||||
self.prior_segment = None;
|
||||
|
||||
// Should also update the SnapCache here?
|
||||
|
||||
self.handle_mode = HandleMode::Free;
|
||||
if let (true, Some(prior_endpoint)) = (self.modifiers.lock_angle, self.prior_segment_endpoint) {
|
||||
self.set_lock_angle(&vector_data, prior_endpoint, self.prior_segment);
|
||||
self.switch_to_free_on_ctrl_release = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn close_path_on_point(
|
||||
&mut self,
|
||||
snap_data: SnapData,
|
||||
vector_data: &VectorData,
|
||||
document: &DocumentMessageHandler,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
id: PointId,
|
||||
transform: &DAffine2,
|
||||
) -> bool {
|
||||
for id in vector_data.extendable_points(preferences.vector_meshes).filter(|&point| point != id) {
|
||||
let Some(pos) = vector_data.point_domain.position_from_id(id) else { continue };
|
||||
let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(self.next_point));
|
||||
@@ -577,14 +625,16 @@ impl PenToolData {
|
||||
self.handle_end_offset = None;
|
||||
self.path_closed = true;
|
||||
self.next_handle_start = self.next_point;
|
||||
self.store_clicked_endpoint(document, &transform, snap_data.input, preferences);
|
||||
self.store_clicked_endpoint(document, transform, snap_data.input, preferences);
|
||||
self.handle_mode = HandleMode::Free;
|
||||
if let (true, Some(prior_endpoint)) = (self.modifiers.lock_angle, self.prior_segment_endpoint) {
|
||||
self.set_lock_angle(&vector_data, prior_endpoint, self.prior_segment);
|
||||
self.set_lock_angle(vector_data, prior_endpoint, self.prior_segment);
|
||||
self.switch_to_free_on_ctrl_release = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn finish_placing_handle(&mut self, snap_data: SnapData, transform: DAffine2, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<PenToolFsmState> {
|
||||
@@ -608,7 +658,9 @@ impl PenToolData {
|
||||
|
||||
// Get close path
|
||||
let mut end = None;
|
||||
let layer = self.current_layer?;
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
|
||||
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(self.current_layer)?;
|
||||
let vector_data = document.network_interface.compute_modified_vector(layer)?;
|
||||
let start = self.latest_point()?.id;
|
||||
let transform = document.metadata().document_to_viewport * transform;
|
||||
@@ -654,6 +706,7 @@ impl PenToolData {
|
||||
layer,
|
||||
modification_type: VectorModificationType::SetG1Continuous { handles, enabled: colinear },
|
||||
});
|
||||
self.cleanup(responses);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1029,7 +1082,9 @@ impl PenToolData {
|
||||
let relative = if self.path_closed { None } else { self.latest_point().map(|point| point.pos) };
|
||||
self.next_point = self.compute_snapped_angle(snap_data, transform, false, mouse, relative, true);
|
||||
|
||||
let layer = self.current_layer?;
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
|
||||
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(self.current_layer)?;
|
||||
let vector_data = document.network_interface.compute_modified_vector(layer)?;
|
||||
let transform = document.metadata().document_to_viewport * transform;
|
||||
for point in vector_data.extendable_points(preferences.vector_meshes) {
|
||||
@@ -1118,6 +1173,7 @@ impl PenToolData {
|
||||
transform.inverse().transform_point2(document_pos)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn create_initial_point(
|
||||
&mut self,
|
||||
document: &DocumentMessageHandler,
|
||||
@@ -1126,6 +1182,7 @@ impl PenToolData {
|
||||
tool_options: &PenOptions,
|
||||
append: bool,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
shape_editor: &mut ShapeState,
|
||||
) {
|
||||
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
|
||||
let snapped = self.snap_manager.free_snap(&SnapData::new(document, input), &point, SnapTypeConfiguration::default());
|
||||
@@ -1141,6 +1198,20 @@ impl PenToolData {
|
||||
self.current_layer = Some(layer);
|
||||
self.extend_existing_path(document, layer, point, position);
|
||||
return;
|
||||
} else if preferences.vector_meshes {
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, viewport, tolerance) {
|
||||
let (point, segments) = closest_segment.adjusted_insert(responses);
|
||||
let layer = closest_segment.layer();
|
||||
let position = closest_segment.closest_point_document();
|
||||
|
||||
// Setting any one of the new segments created as the previous segment
|
||||
self.prior_segment_endpoint = Some(point);
|
||||
self.prior_segment_layer = Some(layer);
|
||||
self.prior_segments = Some(segments.to_vec());
|
||||
|
||||
self.extend_existing_path(document, layer, point, position);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if append {
|
||||
@@ -1182,6 +1253,7 @@ impl PenToolData {
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, responses);
|
||||
self.prior_segment = None;
|
||||
self.prior_segments = None;
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||
|
||||
// This causes the following message to be run only after the next graph evaluation runs and the transforms are updated
|
||||
@@ -1262,6 +1334,7 @@ impl PenToolData {
|
||||
self.prior_segment = None;
|
||||
self.prior_segment_endpoint = None;
|
||||
self.prior_segment_layer = None;
|
||||
self.prior_segments = None;
|
||||
|
||||
if let Some((layer, point, _position)) = closest_point(document, viewport, tolerance, document.metadata().all_layers(), |_| false, preferences) {
|
||||
self.prior_segment_endpoint = Some(point);
|
||||
@@ -1291,31 +1364,8 @@ impl PenToolData {
|
||||
|
||||
match (self.handle_type, self.path_closed) {
|
||||
(TargetHandle::FuturePreviewOutHandle, _) | (TargetHandle::PreviewInHandle, true) => {
|
||||
let is_start = |point: PointId, segment: SegmentId| vector_data.segment_start_from_id(segment) == Some(point);
|
||||
|
||||
let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector_data);
|
||||
let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector_data);
|
||||
|
||||
let start_point = if is_start(anchor, segment) {
|
||||
vector_data.segment_end_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
|
||||
} else {
|
||||
vector_data.segment_start_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
|
||||
};
|
||||
|
||||
let required_handle = if is_start(anchor, segment) {
|
||||
start_handle
|
||||
.filter(|&handle| handle != anchor_position)
|
||||
.or(end_handle.filter(|&handle| Some(handle) != start_point))
|
||||
.or(start_point)
|
||||
} else {
|
||||
end_handle
|
||||
.filter(|&handle| handle != anchor_position)
|
||||
.or(start_handle.filter(|&handle| Some(handle) != start_point))
|
||||
.or(start_point)
|
||||
};
|
||||
|
||||
if let Some(required_handle) = required_handle {
|
||||
self.angle = -(required_handle - anchor_position).angle_to(DVec2::X);
|
||||
if let Some(required_handle) = calculate_segment_angle(anchor, segment, vector_data, true) {
|
||||
self.angle = required_handle;
|
||||
self.handle_mode = HandleMode::ColinearEquidistant;
|
||||
}
|
||||
}
|
||||
@@ -1328,8 +1378,6 @@ impl PenToolData {
|
||||
self.handle_mode = HandleMode::ColinearEquidistant;
|
||||
}
|
||||
}
|
||||
|
||||
// Closure to check if a point is the start or end of a segment
|
||||
}
|
||||
|
||||
fn add_point_layer_position(&mut self, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>, layer: LayerNodeIdentifier, viewport: DVec2) {
|
||||
@@ -1363,8 +1411,10 @@ impl Fsm for PenToolFsmState {
|
||||
preferences,
|
||||
..
|
||||
} = tool_action_data;
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
|
||||
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(tool_data.current_layer);
|
||||
|
||||
let layer = tool_data.current_layer;
|
||||
let mut transform = layer.map(|layer| document.metadata().transform_to_document(layer)).unwrap_or_default();
|
||||
|
||||
if !transform.inverse().is_finite() {
|
||||
@@ -1512,10 +1562,29 @@ impl Fsm for PenToolFsmState {
|
||||
path_overlays(document, DrawHandles::None, shape_editor, &mut overlay_context);
|
||||
}
|
||||
}
|
||||
// Check if there is an anchor within threshold
|
||||
// If not check if there is a closest segment within threshold, if yes then draw overlay
|
||||
let tolerance = crate::consts::SNAP_POINT_TOLERANCE;
|
||||
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
|
||||
let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input), &point, SnapTypeConfiguration::default());
|
||||
let viewport = document.metadata().document_to_viewport.transform_point2(snapped.snapped_point_document);
|
||||
|
||||
let close_to_point = closest_point(document, viewport, tolerance, document.metadata().all_layers(), |_| false, preferences).is_some();
|
||||
if preferences.vector_meshes && !close_to_point {
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, viewport, tolerance) {
|
||||
let pos = closest_segment.closest_point_to_viewport();
|
||||
let perp = closest_segment.calculate_perp(document);
|
||||
overlay_context.manipulator_anchor(pos, true, None);
|
||||
overlay_context.line(pos - perp * SEGMENT_OVERLAY_SIZE, pos + perp * SEGMENT_OVERLAY_SIZE, Some(COLOR_OVERLAY_BLUE), None);
|
||||
}
|
||||
}
|
||||
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
self
|
||||
}
|
||||
(_, PenToolMessage::Overlays(mut overlay_context)) => {
|
||||
let display_anchors = overlay_context.visibility_settings.anchors();
|
||||
let display_handles = overlay_context.visibility_settings.handles();
|
||||
|
||||
let valid = |point: DVec2, handle: DVec2| point.distance_squared(handle) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
|
||||
|
||||
let transform = document.metadata().document_to_viewport * transform;
|
||||
@@ -1542,8 +1611,10 @@ impl Fsm for PenToolFsmState {
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the line between the currently-being-placed anchor and its currently-being-dragged-out outgoing handle (opposite the one currently being dragged out)
|
||||
overlay_context.line(next_anchor, next_handle_start, None, None);
|
||||
if display_handles {
|
||||
// Draw the line between the currently-being-placed anchor and its currently-being-dragged-out outgoing handle (opposite the one currently being dragged out)
|
||||
overlay_context.line(next_anchor, next_handle_start, None, None);
|
||||
}
|
||||
|
||||
match tool_options.pen_overlay_mode {
|
||||
PenOverlayMode::AllHandles => {
|
||||
@@ -1552,6 +1623,12 @@ impl Fsm for PenToolFsmState {
|
||||
PenOverlayMode::FrontierHandles => {
|
||||
if let Some(latest_segment) = tool_data.prior_segment {
|
||||
path_overlays(document, DrawHandles::SelectedAnchors(vec![latest_segment]), shape_editor, &mut overlay_context);
|
||||
}
|
||||
// If a vector mesh then there can be more than one prior segments
|
||||
else if let Some(segments) = tool_data.prior_segments.clone() {
|
||||
if preferences.vector_meshes {
|
||||
path_overlays(document, DrawHandles::SelectedAnchors(segments), shape_editor, &mut overlay_context);
|
||||
}
|
||||
} else {
|
||||
path_overlays(document, DrawHandles::None, shape_editor, &mut overlay_context);
|
||||
};
|
||||
@@ -1559,11 +1636,13 @@ impl Fsm for PenToolFsmState {
|
||||
}
|
||||
|
||||
if let (Some(anchor_start), Some(handle_start), Some(handle_end)) = (anchor_start, handle_start, handle_end) {
|
||||
// Draw the line between the most recently placed anchor and its outgoing handle (which is currently influencing the currently-being-placed segment)
|
||||
overlay_context.line(anchor_start, handle_start, None, None);
|
||||
if display_handles {
|
||||
// Draw the line between the most recently placed anchor and its outgoing handle (which is currently influencing the currently-being-placed segment)
|
||||
overlay_context.line(anchor_start, handle_start, None, None);
|
||||
|
||||
// Draw the line between the currently-being-placed anchor and its incoming handle (opposite the one currently being dragged out)
|
||||
overlay_context.line(next_anchor, handle_end, None, None);
|
||||
// Draw the line between the currently-being-placed anchor and its incoming handle (opposite the one currently being dragged out)
|
||||
overlay_context.line(next_anchor, handle_end, None, None);
|
||||
}
|
||||
|
||||
if self == PenToolFsmState::PlacingAnchor && anchor_start != handle_start && tool_data.modifiers.lock_angle {
|
||||
// Draw the line between the currently-being-placed anchor and last-placed point (lock angle bent overlays)
|
||||
@@ -1575,13 +1654,16 @@ impl Fsm for PenToolFsmState {
|
||||
overlay_context.dashed_line(anchor_start, next_anchor, None, None, Some(4.), Some(4.), Some(0.5));
|
||||
}
|
||||
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, handle_end) {
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, handle_end) && display_handles {
|
||||
// Draw the handle circle for the currently-being-dragged-out incoming handle (opposite the one currently being dragged out)
|
||||
let selected = tool_data.handle_type == TargetHandle::PreviewInHandle;
|
||||
overlay_context.manipulator_handle(handle_end, selected, None);
|
||||
if display_handles {
|
||||
overlay_context.manipulator_handle(handle_end, selected, None);
|
||||
overlay_context.manipulator_handle(handle_end, selected, None);
|
||||
}
|
||||
}
|
||||
|
||||
if valid(anchor_start, handle_start) {
|
||||
if valid(anchor_start, handle_start) && display_handles {
|
||||
// Draw the handle circle for the most recently placed anchor's outgoing handle (which is currently influencing the currently-being-placed segment)
|
||||
overlay_context.manipulator_handle(handle_start, false, None);
|
||||
}
|
||||
@@ -1597,17 +1679,81 @@ impl Fsm for PenToolFsmState {
|
||||
}
|
||||
}
|
||||
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, next_handle_start) {
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && valid(next_anchor, next_handle_start) && display_handles {
|
||||
// Draw the handle circle for the currently-being-dragged-out outgoing handle (the one currently being dragged out, under the user's cursor)
|
||||
let selected = tool_data.handle_type == TargetHandle::FuturePreviewOutHandle;
|
||||
overlay_context.manipulator_handle(next_handle_start, selected, None);
|
||||
}
|
||||
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) {
|
||||
if self == PenToolFsmState::DraggingHandle(tool_data.handle_mode) && display_anchors {
|
||||
// Draw the anchor square for the most recently placed anchor
|
||||
overlay_context.manipulator_anchor(next_anchor, false, None);
|
||||
}
|
||||
|
||||
if self == PenToolFsmState::PlacingAnchor && preferences.vector_meshes {
|
||||
let tolerance = crate::consts::SNAP_POINT_TOLERANCE;
|
||||
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
|
||||
let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input), &point, SnapTypeConfiguration::default());
|
||||
let viewport = document.metadata().document_to_viewport.transform_point2(snapped.snapped_point_document);
|
||||
let close_to_point = closest_point(document, viewport, tolerance, document.metadata().all_layers(), |_| false, preferences).is_some();
|
||||
if !close_to_point {
|
||||
if let Some(closest_segment) = shape_editor.upper_closest_segment(&document.network_interface, viewport, tolerance) {
|
||||
let pos = closest_segment.closest_point_to_viewport();
|
||||
let perp = closest_segment.calculate_perp(document);
|
||||
overlay_context.manipulator_anchor(pos, true, None);
|
||||
overlay_context.line(pos - perp * SEGMENT_OVERLAY_SIZE, pos + perp * SEGMENT_OVERLAY_SIZE, Some(COLOR_OVERLAY_BLUE), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Display a filled overlay of the shape if the new point closes the path
|
||||
if let Some(latest_point) = tool_data.latest_point() {
|
||||
let handle_start = latest_point.handle_start;
|
||||
let handle_end = tool_data.handle_end.unwrap_or(tool_data.next_handle_start);
|
||||
let next_point = tool_data.next_point;
|
||||
let start = latest_point.id;
|
||||
|
||||
if let Some(layer) = layer {
|
||||
let mut vector_data = document.network_interface.compute_modified_vector(layer).unwrap();
|
||||
|
||||
let closest_point = vector_data.extendable_points(preferences.vector_meshes).filter(|&id| id != start).find(|&id| {
|
||||
vector_data.point_domain.position_from_id(id).map_or(false, |pos| {
|
||||
let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point));
|
||||
dist_sq < crate::consts::SNAP_POINT_TOLERANCE.powi(2)
|
||||
})
|
||||
});
|
||||
|
||||
// We have the point. Join the 2 vertices and check if any path is closed.
|
||||
if let Some(end) = closest_point {
|
||||
let segment_id = SegmentId::generate();
|
||||
vector_data.push(segment_id, start, end, BezierHandles::Cubic { handle_start, handle_end }, StrokeId::ZERO);
|
||||
|
||||
let grouped_segments = vector_data.auto_join_paths();
|
||||
let closed_paths = grouped_segments.iter().filter(|path| path.is_closed() && path.contains(segment_id));
|
||||
|
||||
let subpaths: Vec<_> = closed_paths
|
||||
.filter_map(|path| {
|
||||
let segments = path.edges.iter().filter_map(|edge| {
|
||||
vector_data
|
||||
.segment_domain
|
||||
.iter()
|
||||
.find(|(id, _, _, _)| id == &edge.id)
|
||||
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
|
||||
});
|
||||
vector_data.subpath_from_segments_ignore_discontinuities(segments)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut fill_color = graphene_std::Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
|
||||
.unwrap()
|
||||
.with_alpha(0.05)
|
||||
.to_rgba_hex_srgb();
|
||||
fill_color.insert(0, '#');
|
||||
overlay_context.fill_path(subpaths.iter(), transform, fill_color.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the overlays that visualize current snapping
|
||||
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
|
||||
@@ -1625,8 +1771,10 @@ impl Fsm for PenToolFsmState {
|
||||
tool_data.handle_mode = HandleMode::Free;
|
||||
|
||||
// Get the closest point and the segment it is on
|
||||
let append = input.keyboard.key(append_to_selected);
|
||||
|
||||
tool_data.store_clicked_endpoint(document, &transform, input, preferences);
|
||||
tool_data.create_initial_point(document, input, responses, tool_options, input.keyboard.key(append_to_selected), preferences);
|
||||
tool_data.create_initial_point(document, input, responses, tool_options, append, preferences, shape_editor);
|
||||
|
||||
// Enter the dragging handle state while the mouse is held down, allowing the user to move the mouse and position the handle
|
||||
PenToolFsmState::DraggingHandle(tool_data.handle_mode)
|
||||
@@ -1650,7 +1798,7 @@ impl Fsm for PenToolFsmState {
|
||||
if let Some(layer) = layer {
|
||||
tool_data.buffering_merged_vector = false;
|
||||
tool_data.handle_mode = HandleMode::ColinearLocked;
|
||||
tool_data.bend_from_previous_point(SnapData::new(document, input), transform, layer, preferences);
|
||||
tool_data.bend_from_previous_point(SnapData::new(document, input), transform, layer, preferences, shape_editor, responses);
|
||||
tool_data.place_anchor(SnapData::new(document, input), transform, input.mouse.position, preferences, responses);
|
||||
}
|
||||
tool_data.buffering_merged_vector = false;
|
||||
@@ -1666,7 +1814,13 @@ impl Fsm for PenToolFsmState {
|
||||
.descendants(document.metadata())
|
||||
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
|
||||
if let Some((other_layer, _, _)) = should_extend(document, viewport, crate::consts::SNAP_POINT_TOLERANCE, layers, preferences) {
|
||||
if let Some(current_layer) = tool_data.current_layer.filter(|layer| *layer != other_layer) {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
|
||||
if let Some(current_layer) = selected_layers
|
||||
.next()
|
||||
.filter(|current_layer| selected_layers.next().is_none() && *current_layer != other_layer)
|
||||
.or(tool_data.current_layer.filter(|layer| *layer != other_layer))
|
||||
{
|
||||
merge_layers(document, current_layer, other_layer, responses);
|
||||
}
|
||||
}
|
||||
@@ -1947,17 +2101,6 @@ impl Fsm for PenToolFsmState {
|
||||
PenToolFsmState::Ready
|
||||
}
|
||||
(PenToolFsmState::PlacingAnchor, PenToolMessage::Confirm) => {
|
||||
if let Some((vector_data, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) {
|
||||
let single_point_in_layer = vector_data.point_domain.ids().len() == 1;
|
||||
|
||||
if single_point_in_layer {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![layer.to_node()],
|
||||
delete_children: true,
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
tool_data.cleanup(responses);
|
||||
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
|
||||
@@ -1965,8 +2108,8 @@ impl Fsm for PenToolFsmState {
|
||||
PenToolFsmState::Ready
|
||||
}
|
||||
(PenToolFsmState::DraggingHandle(..), PenToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
if tool_data.handle_end.is_none() {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
tool_data.cleanup(responses);
|
||||
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
|
||||
|
||||
@@ -1977,7 +2120,7 @@ impl Fsm for PenToolFsmState {
|
||||
.unwrap_or(PenToolFsmState::Ready)
|
||||
}
|
||||
}
|
||||
(_, PenToolMessage::Abort) => {
|
||||
(PenToolFsmState::PlacingAnchor, PenToolMessage::Abort) => {
|
||||
let should_delete_layer = if let Some(vector_data) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) {
|
||||
vector_data.point_domain.ids().len() == 1
|
||||
} else {
|
||||
@@ -1999,6 +2142,7 @@ impl Fsm for PenToolFsmState {
|
||||
|
||||
PenToolFsmState::Ready
|
||||
}
|
||||
(_, PenToolMessage::Abort) => PenToolFsmState::Ready,
|
||||
(PenToolFsmState::DraggingHandle(..) | PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => {
|
||||
if tool_data.point_index > 0 {
|
||||
tool_data.point_index -= 1;
|
||||
|
||||
@@ -1,436 +0,0 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer};
|
||||
use crate::messages::tool::common_functionality::resize::Resize;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapData;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_core::Color;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PolygonTool {
|
||||
fsm_state: PolygonToolFsmState,
|
||||
tool_data: PolygonToolData,
|
||||
options: PolygonOptions,
|
||||
}
|
||||
|
||||
pub struct PolygonOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
vertices: u32,
|
||||
polygon_type: PolygonType,
|
||||
}
|
||||
|
||||
impl Default for PolygonOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
vertices: 5,
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_secondary(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
polygon_type: PolygonType::Convex,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[impl_message(Message, ToolMessage, Polygon)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum PolygonToolMessage {
|
||||
// Standard messages
|
||||
Overlays(OverlayContext),
|
||||
Abort,
|
||||
WorkingColorChanged,
|
||||
|
||||
// Tool-specific messages
|
||||
DragStart,
|
||||
DragStop,
|
||||
PointerMove { center: Key, lock_ratio: Key },
|
||||
PointerOutsideViewport { center: Key, lock_ratio: Key },
|
||||
UpdateOptions(PolygonOptionsUpdate),
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum PolygonType {
|
||||
Convex = 0,
|
||||
Star = 1,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub enum PolygonOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
PolygonType(PolygonType),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
Vertices(u32),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
}
|
||||
|
||||
impl ToolMetadata for PolygonTool {
|
||||
fn icon_name(&self) -> String {
|
||||
"VectorPolygonTool".into()
|
||||
}
|
||||
fn tooltip(&self) -> String {
|
||||
"Polygon Tool".into()
|
||||
}
|
||||
fn tool_type(&self) -> crate::messages::tool::utility_types::ToolType {
|
||||
ToolType::Polygon
|
||||
}
|
||||
}
|
||||
|
||||
fn create_sides_widget(vertices: u32) -> WidgetHolder {
|
||||
NumberInput::new(Some(vertices as f64))
|
||||
.label("Sides")
|
||||
.int()
|
||||
.min(3.)
|
||||
.max(1000.)
|
||||
.mode(NumberInputMode::Increment)
|
||||
.on_update(|number_input: &NumberInput| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::Vertices(number_input.value.unwrap() as u32)).into())
|
||||
.widget_holder()
|
||||
}
|
||||
|
||||
fn create_star_option_widget(polygon_type: PolygonType) -> WidgetHolder {
|
||||
let entries = vec![
|
||||
RadioEntryData::new("convex")
|
||||
.label("Convex")
|
||||
.on_update(move |_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::PolygonType(PolygonType::Convex)).into()),
|
||||
RadioEntryData::new("star")
|
||||
.label("Star")
|
||||
.on_update(move |_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::PolygonType(PolygonType::Star)).into()),
|
||||
];
|
||||
RadioInput::new(entries).selected_index(Some(polygon_type as u32)).widget_holder()
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetHolder {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::LineWeight(number_input.value.unwrap())).into())
|
||||
.widget_holder()
|
||||
}
|
||||
|
||||
impl LayoutHolder for PolygonTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = vec![
|
||||
create_star_option_widget(self.options.polygon_type),
|
||||
Separator::new(SeparatorType::Related).widget_holder(),
|
||||
create_sides_widget(self.options.vertices),
|
||||
];
|
||||
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
|
||||
widgets.append(&mut self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::FillColor(None)).into(),
|
||||
|color_type: ToolColorType| WidgetCallback::new(move |_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::FillColorType(color_type.clone())).into()),
|
||||
|color: &ColorInput| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb()))).into(),
|
||||
));
|
||||
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::StrokeColor(None)).into(),
|
||||
|color_type: ToolColorType| WidgetCallback::new(move |_| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::StrokeColorType(color_type.clone())).into()),
|
||||
|color: &ColorInput| PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb()))).into(),
|
||||
));
|
||||
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
|
||||
Layout::WidgetLayout(WidgetLayout::new(vec![LayoutGroup::Row { widgets }]))
|
||||
}
|
||||
}
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for PolygonTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, tool_data: &mut ToolActionHandlerData<'a>) {
|
||||
let ToolMessage::Polygon(PolygonToolMessage::UpdateOptions(action)) = message else {
|
||||
self.fsm_state.process_event(message, &mut self.tool_data, tool_data, &self.options, responses, true);
|
||||
return;
|
||||
};
|
||||
match action {
|
||||
PolygonOptionsUpdate::Vertices(vertices) => self.options.vertices = vertices,
|
||||
PolygonOptionsUpdate::PolygonType(polygon_type) => self.options.polygon_type = polygon_type,
|
||||
PolygonOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
}
|
||||
PolygonOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
PolygonOptionsUpdate::LineWeight(line_weight) => self.options.line_weight = line_weight,
|
||||
PolygonOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
}
|
||||
PolygonOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
PolygonOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
}
|
||||
}
|
||||
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
match self.fsm_state {
|
||||
PolygonToolFsmState::Ready => actions!(PolygonToolMessageDiscriminant;
|
||||
DragStart,
|
||||
PointerMove,
|
||||
),
|
||||
PolygonToolFsmState::Drawing => actions!(PolygonToolMessageDiscriminant;
|
||||
DragStop,
|
||||
Abort,
|
||||
PointerMove,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolTransition for PolygonTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
overlay_provider: Some(|overlay_context| PolygonToolMessage::Overlays(overlay_context).into()),
|
||||
tool_abort: Some(PolygonToolMessage::Abort.into()),
|
||||
working_color_changed: Some(PolygonToolMessage::WorkingColorChanged.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum PolygonToolFsmState {
|
||||
#[default]
|
||||
Ready,
|
||||
Drawing,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PolygonToolData {
|
||||
data: Resize,
|
||||
auto_panning: AutoPanning,
|
||||
}
|
||||
|
||||
impl Fsm for PolygonToolFsmState {
|
||||
type ToolData = PolygonToolData;
|
||||
type ToolOptions = PolygonOptions;
|
||||
|
||||
fn transition(self, event: ToolMessage, tool_data: &mut Self::ToolData, tool_action_data: &mut ToolActionHandlerData, tool_options: &Self::ToolOptions, responses: &mut VecDeque<Message>) -> Self {
|
||||
let ToolActionHandlerData {
|
||||
document, global_tool_data, input, ..
|
||||
} = tool_action_data;
|
||||
|
||||
let polygon_data = &mut tool_data.data;
|
||||
|
||||
let ToolMessage::Polygon(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(_, PolygonToolMessage::Overlays(mut overlay_context)) => {
|
||||
polygon_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
|
||||
self
|
||||
}
|
||||
(PolygonToolFsmState::Ready, PolygonToolMessage::DragStart) => {
|
||||
polygon_data.start(document, input);
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
let node = match tool_options.polygon_type {
|
||||
PolygonType::Convex => resolve_document_node_type("Regular Polygon")
|
||||
.expect("Regular Polygon node does not exist")
|
||||
.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::U32(tool_options.vertices), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
]),
|
||||
PolygonType::Star => resolve_document_node_type("Star").expect("Star node does not exist").node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::U32(tool_options.vertices), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.25), false)),
|
||||
]),
|
||||
};
|
||||
|
||||
let nodes = vec![(NodeId(0), node)];
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, document.new_layer_bounding_artboard(input), responses);
|
||||
responses.add(Message::StartBuffer);
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::ONE, 0., input.mouse.position),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, responses);
|
||||
polygon_data.layer = Some(layer);
|
||||
|
||||
PolygonToolFsmState::Drawing
|
||||
}
|
||||
(PolygonToolFsmState::Drawing, PolygonToolMessage::PointerMove { center, lock_ratio }) => {
|
||||
if let Some([start, end]) = tool_data.data.calculate_points(document, input, center, lock_ratio) {
|
||||
if let Some(layer) = tool_data.data.layer {
|
||||
// TODO: We need to determine how to allow the polygon node to make irregular shapes
|
||||
update_radius_sign(end, start, layer, document, responses);
|
||||
|
||||
let dimensions = (start - end).abs();
|
||||
let mut scale = DVec2::ONE;
|
||||
let radius: f64;
|
||||
|
||||
// We keep the smaller dimension's scale at 1 and scale the other dimension accordingly
|
||||
if dimensions.x > dimensions.y {
|
||||
scale.x = dimensions.x / dimensions.y;
|
||||
radius = dimensions.y / 2.;
|
||||
} else {
|
||||
scale.y = dimensions.y / dimensions.x;
|
||||
radius = dimensions.x / 2.;
|
||||
}
|
||||
|
||||
match tool_options.polygon_type {
|
||||
PolygonType::Convex => {
|
||||
let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) else {
|
||||
return self;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
}
|
||||
PolygonType::Star => {
|
||||
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) else {
|
||||
return self;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, 3),
|
||||
input: NodeInput::value(TaggedValue::F64(radius / 2.), false),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., (start + end) / 2.),
|
||||
transform_in: TransformIn::Viewport,
|
||||
skip_rerender: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
PolygonToolMessage::PointerOutsideViewport { center, lock_ratio }.into(),
|
||||
PolygonToolMessage::PointerMove { center, lock_ratio }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, &messages, responses);
|
||||
|
||||
self
|
||||
}
|
||||
(_, PolygonToolMessage::PointerMove { .. }) => {
|
||||
polygon_data.snap_manager.preview_draw(&SnapData::new(document, input), input.mouse.position);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
self
|
||||
}
|
||||
(PolygonToolFsmState::Drawing, PolygonToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, responses);
|
||||
|
||||
PolygonToolFsmState::Drawing
|
||||
}
|
||||
(state, PolygonToolMessage::PointerOutsideViewport { center, lock_ratio }) => {
|
||||
// Auto-panning
|
||||
let messages = [
|
||||
PolygonToolMessage::PointerOutsideViewport { center, lock_ratio }.into(),
|
||||
PolygonToolMessage::PointerMove { center, lock_ratio }.into(),
|
||||
];
|
||||
tool_data.auto_panning.stop(&messages, responses);
|
||||
|
||||
state
|
||||
}
|
||||
(PolygonToolFsmState::Drawing, PolygonToolMessage::DragStop) => {
|
||||
input.mouse.finish_transaction(polygon_data.viewport_drag_start(document), responses);
|
||||
polygon_data.cleanup(responses);
|
||||
|
||||
PolygonToolFsmState::Ready
|
||||
}
|
||||
(PolygonToolFsmState::Drawing, PolygonToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
|
||||
polygon_data.cleanup(responses);
|
||||
|
||||
PolygonToolFsmState::Ready
|
||||
}
|
||||
(_, PolygonToolMessage::WorkingColorChanged) => {
|
||||
responses.add(PolygonToolMessage::UpdateOptions(PolygonOptionsUpdate::WorkingColors(
|
||||
Some(global_tool_data.primary_color),
|
||||
Some(global_tool_data.secondary_color),
|
||||
)));
|
||||
self
|
||||
}
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_hints(&self, responses: &mut VecDeque<Message>) {
|
||||
let hint_data = match self {
|
||||
PolygonToolFsmState::Ready => HintData(vec![HintGroup(vec![
|
||||
HintInfo::mouse(MouseMotion::LmbDrag, "Draw Polygon"),
|
||||
HintInfo::keys([Key::Shift], "Constrain Regular").prepend_plus(),
|
||||
HintInfo::keys([Key::Alt], "From Center").prepend_plus(),
|
||||
])]),
|
||||
PolygonToolFsmState::Drawing => HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![HintInfo::keys([Key::Shift], "Constrain Regular"), HintInfo::keys([Key::Alt], "From Center")]),
|
||||
]),
|
||||
};
|
||||
|
||||
responses.add(FrontendMessage::UpdateInputHints { hint_data });
|
||||
}
|
||||
|
||||
fn update_cursor(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair });
|
||||
}
|
||||
}
|
||||
|
||||
/// In the case where the polygon/star is upside down and the number of sides is odd, we negate the radius instead of using a negative scale.
|
||||
fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier, document: &mut DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let sign_num = if end[1] > start[1] { 1. } else { -1. };
|
||||
let new_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
|
||||
if new_layer.find_input("Regular Polygon", 1).unwrap_or(&TaggedValue::U32(0)).to_u32() % 2 == 1 {
|
||||
let Some(polygon_node_id) = new_layer.upstream_node_id_from_name("Regular Polygon") else { return };
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(polygon_node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if new_layer.find_input("Star", 1).unwrap_or(&TaggedValue::U32(0)).to_u32() % 2 == 1 {
|
||||
let Some(star_node_id) = new_layer.upstream_node_id_from_name("Star") else { return };
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, 2),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, 3),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.25), false),
|
||||
});
|
||||
}
|
||||
}
|
||||
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user