From 3e8af8b7da0e1971a20866eb7457b1c5b8bc110d Mon Sep 17 00:00:00 2001 From: clover caruso Date: Sun, 29 Nov 2026 23:43:54 -0800 Subject: [PATCH] Initial wgpu node compositor with Fusion 21.1 parity core - Six-crate Rust + wgpu workspace (model, engine, flow, spline, viewer, studio) - Full Fusion .comp parser (splines, PolyPath, expressions, macros, instances, animated polylines) - 45 GPU-evaluated 2D/3D/Fuse tools verified against Fusion 21.1 render node probes (0.0%-1.3% MAE) - Dual HiQ/Fast evaluation modes, single-frame DAG memoization, LRU frame cache, and render-check harness - Conformance probe harness (scripts/fusion_probes.py) and tracked gaps (KNOWN_GAPS.md) --- .gitignore | 5 + Cargo.lock | 4689 +++++++++++++++++++++++++ Cargo.toml | 57 + KNOWN_GAPS.md | 42 + crates/engine/Cargo.toml | 21 + crates/engine/src/bin/render_check.rs | 356 ++ crates/engine/src/cache.rs | 210 ++ crates/engine/src/eval.rs | 3112 ++++++++++++++++ crates/engine/src/lib.rs | 7 + crates/engine/src/media.rs | 658 ++++ crates/engine/src/scene3d.rs | 903 +++++ crates/engine/src/shaders.wgsl | 1741 +++++++++ crates/flow/Cargo.toml | 13 + crates/flow/src/lib.rs | 1162 ++++++ crates/model/Cargo.toml | 8 + crates/model/src/comp.rs | 1246 +++++++ crates/model/src/expr.rs | 171 + crates/model/src/lib.rs | 80 + crates/model/src/lua_value.rs | 603 ++++ crates/model/src/spline.rs | 491 +++ crates/spline/Cargo.toml | 13 + crates/spline/src/lib.rs | 1282 +++++++ crates/studio/Cargo.toml | 33 + crates/studio/src/main.rs | 872 +++++ crates/viewer/Cargo.toml | 15 + crates/viewer/src/lib.rs | 803 +++++ scripts/fusion_probes.py | 1033 ++++++ 27 files changed, 19626 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 KNOWN_GAPS.md create mode 100644 crates/engine/Cargo.toml create mode 100644 crates/engine/src/bin/render_check.rs create mode 100644 crates/engine/src/cache.rs create mode 100644 crates/engine/src/eval.rs create mode 100644 crates/engine/src/lib.rs create mode 100644 crates/engine/src/media.rs create mode 100644 crates/engine/src/scene3d.rs create mode 100644 crates/engine/src/shaders.wgsl create mode 100644 crates/flow/Cargo.toml create mode 100644 crates/flow/src/lib.rs create mode 100644 crates/model/Cargo.toml create mode 100644 crates/model/src/comp.rs create mode 100644 crates/model/src/expr.rs create mode 100644 crates/model/src/lib.rs create mode 100644 crates/model/src/lua_value.rs create mode 100644 crates/model/src/spline.rs create mode 100644 crates/spline/Cargo.toml create mode 100644 crates/spline/src/lib.rs create mode 100644 crates/studio/Cargo.toml create mode 100644 crates/studio/src/main.rs create mode 100644 crates/viewer/Cargo.toml create mode 100644 crates/viewer/src/lib.rs create mode 100644 scripts/fusion_probes.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..86b8fdb94673c29c2ff3b5eeb1cce880be4e18a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/target +/private +.DS_Store +*.png +!docs/**/*.png diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..5f3a3cfb212b0b2f40d7b5853f6ce472f4060ff0 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4689 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +dependencies = [ + "enumn", + "serde", + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.1" +dependencies = [ + "accesskit", + "hashbrown 0.17.2", +] + +[[package]] +name = "accesskit_ios" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit", +] + +[[package]] +name = "accesskit_macos" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.2", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_windows" +version = "0.35.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.2", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" +dependencies = [ + "accesskit", + "accesskit_ios", + "accesskit_macos", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "allocator-api2" +version = "0.2.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.6", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.6", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.6", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "brotli-decompressor" +version = "6.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "bstr" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" +dependencies = [ + "memchr", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +dependencies = [ + "serde", +] + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "diff" +version = "0.1.0" +dependencies = [ + "highlight", + "tree-sitter", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "dock" +version = "0.1.0" +dependencies = [ + "accesskit", + "draw", + "edit", + "state", + "theme", + "ui", + "winit", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "draw" +version = "0.1.0" +dependencies = [ + "bytemuck", + "image", + "resvg", + "roxmltree 0.21.2", + "serde_json", + "state", + "text", + "wgpu", + "zeno", +] + +[[package]] +name = "edit" +version = "0.1.0" +dependencies = [ + "accesskit", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "text", + "unicode-segmentation", + "windows-sys 0.61.2", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "engine" +version = "0.1.0" +dependencies = [ + "bytemuck", + "exr", + "image", + "model", + "png", + "pollster", + "text", + "theme", + "wgpu", + "zeno", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "env_home" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "flow" +version = "0.1.0" +dependencies = [ + "draw", + "model", + "text", + "theme", + "ui", + "winit", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts 0.41.0", + "smallvec", +] + +[[package]] +name = "harfrust" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "865dcc4105d51c323d8fedbb2d75b5e9c8ecddf5613f74c82f851d0afbc97114" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts 0.46.0", + "smallvec", + "yoke", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "highlight" +version = "0.1.0" +dependencies = [ + "streaming-iterator", + "tree-sitter", + "tree-sitter-bash", + "tree-sitter-c", + "tree-sitter-cpp", + "tree-sitter-css", + "tree-sitter-diff", + "tree-sitter-go", + "tree-sitter-html", + "tree-sitter-java", + "tree-sitter-javascript", + "tree-sitter-json", + "tree-sitter-lua", + "tree-sitter-md", + "tree-sitter-python", + "tree-sitter-ruby", + "tree-sitter-rust", + "tree-sitter-sequel", + "tree-sitter-swift", + "tree-sitter-toml-ng", + "tree-sitter-typescript", + "tree-sitter-yaml", + "tree-sitter-zig", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "knife-window-host" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_winit", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "serde", + "serde_json", + "winit", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lua-src" +version = "547.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42" +dependencies = [ + "cc", +] + +[[package]] +name = "luajit-src" +version = "210.5.12+a4f56a4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671" +dependencies = [ + "cc", + "which", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mlua" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0" +dependencies = [ + "bstr", + "either", + "mlua-sys", + "num-traits", + "parking_lot", + "rustc-hash 2.1.3", + "rustversion", +] + +[[package]] +name = "mlua-sys" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93" +dependencies = [ + "cc", + "cfg-if", + "lua-src", + "luajit-src", + "pkg-config", +] + +[[package]] +name = "model" +version = "0.1.0" +dependencies = [ + "mlua", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "naga" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.2", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d" +dependencies = [ + "hashbrown 0.17.2", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nucleo-matcher" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf33f538733d1a5a3494b836ba913207f14d9d4a1d3cd67030c5061bdd2cac85" +dependencies = [ + "memchr", + "unicode-segmentation", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qrcodegen" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4339fc7a1021c9c1621d87f5e3505f2805c8c105420ba2f2a4df86814590c142" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types", + "once_cell", + "smallvec", + "yoke", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.12.0", + "usvg", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia 0.11.4", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash 0.2.0", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" +dependencies = [ + "bytemuck", + "once_cell", + "read-fonts 0.46.0", + "smallvec", + "yoke", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "spline" +version = "0.1.0" +dependencies = [ + "draw", + "model", + "text", + "theme", + "ui", + "winit", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "state" +version = "0.1.0" +dependencies = [ + "libc", + "serde_json", + "sha2", + "state-derive", + "windows-sys 0.61.2", +] + +[[package]] +name = "state-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "studio" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_winit", + "dock", + "draw", + "engine", + "flow", + "model", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "png", + "pollster", + "spline", + "state", + "text", + "theme", + "ui", + "viewer", + "wgpu", + "winit", +] + +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "text" +version = "0.1.0" +dependencies = [ + "harfrust 0.15.0", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-text", + "objc2-foundation 0.3.2", + "png", + "skrifa 0.49.0", + "unicode-bidi", + "unicode-general-category", + "unicode-linebreak", + "unicode-normalization", + "unicode-script", + "unicode-segmentation", + "wuff", + "zeno", +] + +[[package]] +name = "theme" +version = "0.1.0" +dependencies = [ + "diff", + "draw", + "highlight", + "memmap2", + "text", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path 0.11.4", +] + +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.21+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tree-sitter" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2bed8f39a73439f3b0b7ed8f452be5d2911b5e9da69d352ef113bb7448fb8" +dependencies = [ + "cc", + "regex", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-bash" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-c" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-cpp" +version = "0.23.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-css" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-diff" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfe1e5ca280a65dfe5ba4205c1bcc84edf486464fed315db53dee6da9a335889" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-go" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-html" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-java" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-javascript" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-json" +version = "0.24.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" + +[[package]] +name = "tree-sitter-lua" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-md" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed661bfe3c264961425f77cd89ad2998bf5d629e71ce8bab1e5d7e940d6246e" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-python" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-ruby" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be0484ea4ef6bb9c575b4fdabde7e31340a8d2dbc7d52b321ac83da703249f95" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-rust" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-sequel" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711e236e1ae0708f911d8413c3b5656f522416cba683ea91589aebc49eda1b5a" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-swift" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2688c06564afa397313e0db17d140a73e2c6a47f3884794614246167c9dd5dfd" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-toml-ng" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-typescript" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-yaml" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-zig" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab11fc124851b0db4dd5e55983bbd9631192e93238389dcd44521715e5d53e28" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "ui" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_consumer", + "accesskit_winit", + "arboard", + "block2 0.6.2", + "draw", + "edit", + "fontdb", + "knife-window-host", + "libc", + "nucleo-matcher", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "qrcodegen", + "serde_json", + "siphasher", + "text", + "theme", + "time", + "wgpu", + "windows-sys 0.61.2", + "winit", + "x11rb", + "zbus", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64", + "data-url", + "fontdb", + "harfrust 0.12.0", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.2", + "simplecss", + "siphasher", + "skrifa 0.44.0", + "strict-num", + "svgtypes", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "viewer" +version = "0.1.0" +dependencies = [ + "draw", + "engine", + "model", + "text", + "theme", + "ui", + "wgpu", + "winit", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.2", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.2", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ccf093bd215ae9dc4f96df293e675513ac1f2569f8293a2911cc34ca3505d1" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.2", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "which" +version = "7.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762" +dependencies = [ + "either", + "env_home", + "rustix 1.1.6", + "winsafe", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "serde", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.6", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "wuff" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd" +dependencies = [ + "brotli-decompressor", + "bytes", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.6", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" +dependencies = [ + "serde", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..12338bfbe2f2c6598bdd6ca979766fc64dcb5cf1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,57 @@ +[workspace] +members = [ + "crates/model", + "crates/engine", + "crates/flow", + "crates/spline", + "crates/viewer", + "crates/studio", +] +resolver = "3" + +[workspace.package] +edition = "2024" +version = "0.1.0" +publish = false + +[workspace.dependencies] +# Local workspace crates +model = { path = "crates/model" } +engine = { path = "crates/engine" } +flow = { path = "crates/flow" } +spline = { path = "crates/spline" } +viewer = { path = "crates/viewer" } + +# Knife toolkit (sibling checkout) +draw = { path = "../the-knife/knife/draw" } +ui = { path = "../the-knife/knife/ui" } +dock = { path = "../the-knife/knife/dock" } +state = { path = "../the-knife/knife/state" } +text = { path = "../the-knife/knife/text" } +theme = { path = "../the-knife/knife/theme" } + +# Shared versions aligned with the-knife +accesskit = "0.25.1" +accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] } +bytemuck = { version = "1.25", features = ["derive"] } +image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] } +mlua = { version = "0.10", features = ["lua54", "vendored"] } +png = "0.18" +pollster = "0.4" +wgpu = "30.0.1" +winit = "0.30.13" +zeno = "0.3.3" + +objc2 = "0.6.5" +objc2-app-kit = { version = "0.3.2", default-features = false } +objc2-foundation = { version = "0.3.2", default-features = false } + +[patch.crates-io] +accesskit_consumer = { path = "../the-knife/knife/vendor/accesskit_consumer" } + +[profile.dev] +debug = "line-tables-only" + +[profile.dev.package."*"] +opt-level = 3 +debug = false diff --git a/KNOWN_GAPS.md b/KNOWN_GAPS.md new file mode 100644 index 0000000000000000000000000000000000000000..f739a21d2155e12ed2c5968a8460f541aea13791 --- /dev/null +++ b/KNOWN_GAPS.md @@ -0,0 +1,42 @@ +# Known Gaps & Roadmap + +Tracked rendering and architecture gaps compared to Blackmagic Fusion Studio 21.1. +Items listed here are **tracked bugs / missing subsystems**, never permanent exclusions. + +--- + +## 1. Cryptomatte (`Fuse.Cryptomatte` — e.g. `01_intro.comp` human character matte) +- **Status:** Tracked known gap (not an intentional exclusion). +- **Symptom:** In `01_intro.comp` (e.g. `f0600`), the human character's orange rim/matte driven by a Cryptomatte pass over multi-channel EXR (`CryptoObject00..02` MurmurHash3 ID/coverage pairs + manifest metadata) is not yet decoded, so the character's Cryptomatte glow/isolation differs from Fusion. +- **Planned fix:** Add multi-channel EXR Cryptomatte layer decoding (`exr` crate already in workspace), parse `cryptomatte//manifest` JSON from EXR header attributes, hash selected `MatteList` names via MurmurHash3-32 (`f32` bit-cast), and accumulate matching ID/coverage rank pairs into the alpha matte. + +## 2. 3D Particle System (`pEmitter`, `pRender`, `pPointForce`) +- **Status:** Tracked missing subsystem (currently reported in `unsupported` on `01_intro.comp`). +- **Symptom:** Particle layers driven by `pEmitter` / `pPointForce` / `pRender` are skipped. +- **Planned fix:** Deterministic frame-stepped particle simulator (seeded per-frame/cached state) feeding into `Scene3D` billboard/point-sprite instancing inside `Renderer3D` / `pRender`. + +## 3. Optical Flow & Retime Vectors (`Dimension.OpticalFlow`, `OpticalFlow`) +- **Status:** Tracked missing subsystem (reported in `unsupported` on `01_intro.comp`). +- **Symptom:** Motion-vector-interpolated retiming falls back to nearest/frame-blended source frames. +- **Planned fix:** GPU dense optical-flow pass (hierarchical Lucas-Kanade / TV-L1 compute shader) writing forward/backward motion vectors for downstream `TimeStretcher` / `VectorMotionBlur`. + +## 4. Project-Defined Bit Depth (`DepthFull` / `DepthInteractive` / `ChangeDepth`) +- **Status:** Planned engine upgrade. +- **Current behavior:** Intermediate render targets currently use `Rgba8Unorm` (8-bit) in both `HiQ` and `Fast` modes. +- **Target design (per user preference):** + - **`HiQ` mode:** Respect the comp's own declared bit depth (`Comp.Prefs.Comp.FrameFormat.DepthFull` and per-node `Depth` / `ChangeDepth` overrides: `int8` -> `Rgba8Unorm`, `int16`/`f16` -> `Rgba16Float`, `f32` -> `Rgba32Float`). Do not force `f32` when the project asks for `int8` or `f16`. + - **`Fast` mode:** Collapse working targets to `Rgba8Unorm` (and downsampled blurs / capped `XGlow` octaves) for maximum interactive throughput. + +## 5. Video Decode Backend (`AVFoundation` / `VideoToolbox` + `ffmpeg` fallback) +- **Status:** Planned media layer upgrade. +- **Current behavior:** Video clips decode via `ffmpeg` subprocesses with LRU frame caching. +- **Target design:** Introduce a `VideoDecoder` trait with a native macOS `AVAssetReader` + `VideoToolbox` hardware backend for zero-copy ProRes / H.264 / HEVC scrubbing, keeping the existing `ffmpeg` CLI backend as a clean cross-platform fallback for Linux/Windows and uncommon codecs. + +## 6. Procedural `FastNoise` Internal Permutation Seed +- **Status:** Known inherent difference vs closed-source Fusion noise table. +- **Behavior:** Scale, `Detail`, `Contrast`, `Brightness`, `Seethe`, `SeetheRate`, `XScale`/`YScale`, and `Gradient` / `TwoColor` coloring match Fusion's visual distribution and density; individual hash peaks (e.g. random star positions on the 3D cylinder in `60_moon_guide_u.comp`) sit at different pseudo-random coordinates because Fusion's internal `FastNoise` permutation table is proprietary. 3D camera projection itself (`Camera3D`, `Transform3D`, `Shape3D` Cylinder, all `RotOrder` permutations, `AoV`/`FLength`/`ResolutionGateFit`) is verified to `0.1%–0.4% MAE` against Fusion 21.1 via `scripts/fusion_probes.py cam3d_fov`. + +## 7. Minor Tool Edge Cases Remaining +- `TextPlus` `ElementShape` `BorderFill` (`ElementShape2 = 2`) and custom font rendering on Linux render node (note: on Snow Globe, mounting `\(site.cloverRoot)/Asset/Font` read-only to `/usr/local/share/fonts/clover` in `~/dev/home-infra/service/fusion/service.pkl` exposes Clover's font library to `FusionRenderNode` without committing font files). +- `Displace` `Type = 0` (`Radial`) `LightPower` specular/bump lighting exact angle & color model (`0.7% MAE` vs `0.1%` without `LightPower`). +- `Glow` tool (`Glow = 0.583, GlowSize = 12`) slight Gaussian tail roll-off (`1.3% MAE`; `SoftGlow` is `0.0%–0.8%`). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..20ee34c88650e3687bae4c675c778884d05a8ba5 --- /dev/null +++ b/crates/engine/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "engine" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[[bin]] +name = "render-check" +path = "src/bin/render_check.rs" + +[dependencies] +bytemuck.workspace = true +exr = "1.74" +image.workspace = true +model.workspace = true +png.workspace = true +pollster.workspace = true +text.workspace = true +theme.workspace = true +wgpu.workspace = true +zeno.workspace = true diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs new file mode 100644 index 0000000000000000000000000000000000000000..cbcfdb72f17a52874bb28febf229fcb8d60e29ce --- /dev/null +++ b/crates/engine/src/bin/render_check.rs @@ -0,0 +1,356 @@ +//! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. + +use engine::{CacheMode, Engine}; +use model::Comp; +use std::collections::HashMap; +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64), Box> { + let mut ref_img = image::open(ref_path)?.to_rgba8(); + if [ref_img.width(), ref_img.height()] != tex_size { + ref_img = image::imageops::resize( + &ref_img, + tex_size[0], + tex_size[1], + image::imageops::FilterType::Triangle, + ); + } + let rraw = ref_img.into_raw(); + let mut sum_abs = 0u64; + let mut sum_sq = 0u64; + let n = (tex_size[0] as u64) * (tex_size[1] as u64) * 3; + for (a, b) in pixels.chunks_exact(4).zip(rraw.chunks_exact(4)) { + for c in 0..3 { + let d = (a[c] as i32 - b[c] as i32).unsigned_abs() as u64; + sum_abs += d; + sum_sq += d * d; + } + } + let mae = sum_abs as f64 / n as f64; + let rmse = (sum_sq as f64 / n as f64).sqrt(); + Ok((mae, rmse)) +} + +fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut enc = png::Encoder::new(File::create(path)?, size[0], size[1]); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.write_header()?.write_image_data(pixels)?; + Ok(()) +} + +fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box> { + let text = std::fs::read_to_string(manifest_path)?; + let mut engine = Engine::new_headless()?; + engine.hiq = hiq; + let mut comps: HashMap = HashMap::new(); + let mut passed = 0usize; + let mut failed = 0usize; + + eprintln!( + "Quality mode: {} | Manifest: {}", + if hiq { "HiQ (bar-for-bar)" } else { "Fast (perfmaxxed)" }, + manifest_path.display() + ); + eprintln!( + "{:<6} {:<20} {:>6} {:>7} {:>7} {:>8} {:>8} {:>7} {}", + "STATUS", "CASE", "FRAME", "MAE%", "RMSE", "WARM_MS", "BUST_MS", "VRAM", "UNSUPPORTED" + ); + eprintln!("{}", "-".repeat(94)); + + for (lineno, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let cols: Vec<&str> = line.split('|').map(|s| s.trim()).collect(); + if cols.len() < 6 { + return Err(format!("suite line {}: expected 6 pipe-separated columns", lineno + 1).into()); + } + let case_name = cols[0]; + let comp_path = PathBuf::from(cols[1]); + let frame: f64 = cols[2].parse()?; + let ref_path = PathBuf::from(cols[3]); + let max_mae_pct: f64 = cols[4].parse()?; + let max_bust_ms: f64 = cols[5].parse()?; + let node_opt = cols.get(6).copied().filter(|s| !s.is_empty() && *s != "-"); + + if !comps.contains_key(&comp_path) { + comps.insert(comp_path.clone(), Comp::from_fusion_file(&comp_path)?); + } + let comp = &comps[&comp_path]; + let target = match node_opt { + Some(n) => comp.find_node(n).ok_or_else(|| format!("{case_name}: no node {n}"))?, + None => comp.default_output_node().ok_or("comp has no nodes")?, + }; + + engine.set_cache_mode(CacheMode::Enabled); + let (tex, cold) = engine.evaluate(comp, target, frame); + let (_, warm) = engine.evaluate(comp, target, frame); + engine.bust_gpu_cache(); + let (_, bust) = engine.evaluate(comp, target, frame); + + let pixels = engine.readback_rgba(&tex)?; + let (mae, rmse) = compute_diff(&pixels, tex.size, &ref_path)?; + let mae_pct = mae / 2.55; + + let ok = mae_pct <= max_mae_pct && bust.eval_ms <= max_bust_ms; + if ok { + passed += 1; + } else { + failed += 1; + } + eprintln!( + "{:<6} {:<20} {:>6} {:>6.2}% {:>7.2} {:>7.2}ms {:>7.2}ms {:>5.0}MB {:?}", + if ok { "PASS" } else { "FAIL" }, + case_name, + frame as i64, + mae_pct, + rmse, + warm.eval_ms, + bust.eval_ms, + cold.cached_vram_mb, + cold.unsupported_nodes, + ); + if !ok { + eprintln!( + " budget: MAE <= {max_mae_pct:.2}% (got {mae_pct:.2}%), bust <= {max_bust_ms:.1}ms (got {:.1}ms)", + bust.eval_ms + ); + } + } + + eprintln!("{}", "-".repeat(94)); + eprintln!("Suite summary: {passed} passed, {failed} failed"); + if failed > 0 { + std::process::exit(1); + } + Ok(()) +} + +fn run_batch_render( + comp_path: &Path, + range_str: &str, + out_dir: &Path, + node_name: Option<&str>, + proxy_scale: u32, +) -> Result<(), Box> { + let comp = Comp::from_fusion_file(comp_path)?; + let (start, end) = if let Some((a, b)) = range_str.split_once("..") { + (a.parse::()?, b.parse::()?) + } else { + (comp.render_range[0], comp.render_range[1]) + }; + let target = match node_name { + Some(n) => comp.find_node(n).ok_or_else(|| format!("no such node {n}"))?, + None => comp.default_output_node().ok_or("comp has no nodes")?, + }; + std::fs::create_dir_all(out_dir)?; + let mut engine = Engine::new_headless()?; + engine.proxy_scale = proxy_scale; + + let total = (end - start + 1).max(0) as usize; + let t_all = Instant::now(); + eprintln!( + "Rendering {} ({}x{}, proxy 1:{}) node={} frames {}..{} ({total} frames) -> {}", + comp.name, + comp.width, + comp.height, + proxy_scale, + comp.node(target).name, + start, + end, + out_dir.display() + ); + for (idx, f) in (start..=end).enumerate() { + let (tex, stats) = engine.evaluate(&comp, target, f as f64); + let pixels = engine.readback_rgba(&tex)?; + let out_file = out_dir.join(format!("{f:04}.png")); + write_png(&out_file, tex.size, &pixels)?; + if idx == 0 || (idx + 1) % 10 == 0 || idx + 1 == total { + let elapsed = t_all.elapsed().as_secs_f64().max(1e-6); + let fps = (idx + 1) as f64 / elapsed; + eprintln!( + " [{:>4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", + idx + 1, + stats.eval_ms, + stats.cached_vram_mb, + stats.unsupported_nodes, + ); + } + } + eprintln!( + "Finished {total} frames in {:.2}s ({:.1} fps)", + t_all.elapsed().as_secs_f64(), + total as f64 / t_all.elapsed().as_secs_f64().max(1e-6) + ); + Ok(()) +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + if args.len() >= 3 && args[1] == "--suite" { + let hiq = !args.iter().any(|a| a == "--fast"); + return run_suite(Path::new(&args[2]), hiq); + } + if args.len() < 3 { + eprintln!( + "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --suite [--fast]" + ); + std::process::exit(2); + } + + let comp_path = PathBuf::from(&args[1]); + if args[2] == "--render" { + let mut range = String::new(); + let mut out_dir: Option = None; + let mut node_name: Option = None; + let mut proxy_scale = 1u32; + let mut i = 2; + while i < args.len() { + match args[i].as_str() { + "--render" if i + 1 < args.len() => { + range = args[i + 1].clone(); + i += 2; + } + "--out-dir" if i + 1 < args.len() => { + out_dir = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--node" if i + 1 < args.len() => { + node_name = Some(args[i + 1].clone()); + i += 2; + } + "--proxy" if i + 1 < args.len() => { + proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); + i += 2; + } + other => { + eprintln!("unexpected argument '{other}'"); + std::process::exit(2); + } + } + } + let out_dir = out_dir.ok_or("--out-dir is required with --render")?; + return run_batch_render(&comp_path, &range, &out_dir, node_name.as_deref(), proxy_scale); + } + + let frame: f64 = args[2].parse()?; + let mut out_path: Option = None; + let mut ref_path: Option = None; + let mut node_name: Option = None; + let mut proxy_scale: u32 = 1; + let mut hiq = true; + let mut bench = false; + let mut i = 3; + while i < args.len() { + match args[i].as_str() { + "--out" if i + 1 < args.len() => { + out_path = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--ref" if i + 1 < args.len() => { + ref_path = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--node" if i + 1 < args.len() => { + node_name = Some(args[i + 1].clone()); + i += 2; + } + "--proxy" if i + 1 < args.len() => { + proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); + i += 2; + } + "--fast" => { + hiq = false; + i += 1; + } + "--bench" => { + bench = true; + i += 1; + } + other => { + eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --fast, --bench)"); + std::process::exit(2); + } + } + } + + let comp = Comp::from_fusion_file(&comp_path)?; + let target = match node_name { + Some(n) => comp.find_node(&n).ok_or_else(|| format!("no such node {n}"))?, + None => comp.default_output_node().ok_or("comp has no nodes")?, + }; + eprintln!( + "Loaded {} ({}x{}, proxy 1:{}, {}, {} nodes, {} splines) -> viewing {} at frame {frame}", + comp.name, + comp.width, + comp.height, + proxy_scale, + if hiq { "HiQ" } else { "Fast" }, + comp.nodes.len(), + comp.splines.len(), + comp.node(target).name + ); + + let mut engine = Engine::new_headless()?; + engine.proxy_scale = proxy_scale; + engine.hiq = hiq; + + let (tex, cold) = engine.evaluate(&comp, target, frame); + eprintln!( + "[cold] {:.2} ms | eval={} hits={} misses={} loads={} pruned={} vram={:.1}MB unsupported={:?}", + cold.eval_ms, + cold.nodes_evaluated, + cold.cache_hits, + cold.cache_misses, + cold.source_loads, + cold.pruned_branches, + cold.cached_vram_mb, + cold.unsupported_nodes + ); + + if bench { + let (_, warm) = engine.evaluate(&comp, target, frame); + eprintln!( + "[warm] {:.2} ms | eval={} hits={} misses={}", + warm.eval_ms, warm.nodes_evaluated, warm.cache_hits, warm.cache_misses + ); + + engine.bust_gpu_cache(); + let (_, gpu_bust) = engine.evaluate(&comp, target, frame); + eprintln!( + "[bust] {:.2} ms | eval={} hits={} misses={} loads={}", + gpu_bust.eval_ms, gpu_bust.nodes_evaluated, gpu_bust.cache_hits, gpu_bust.cache_misses, gpu_bust.source_loads + ); + + engine.set_cache_mode(CacheMode::Bypass); + let (_, bypass) = engine.evaluate(&comp, target, frame); + eprintln!( + "[bypass] {:.2} ms | eval={} pruned={}", + bypass.eval_ms, bypass.nodes_evaluated, bypass.pruned_branches + ); + } + + let pixels = engine.readback_rgba(&tex)?; + if let Some(out_path) = out_path { + write_png(&out_path, tex.size, &pixels)?; + eprintln!("Wrote {} ({}x{})", out_path.display(), tex.size[0], tex.size[1]); + } + if let Some(rp) = ref_path { + let (mae, rmse) = compute_diff(&pixels, tex.size, &rp)?; + eprintln!( + "Diff vs {} ({}x{}): MAE={mae:.2}/255 ({:.1}%), RMSE={rmse:.2}/255", + rp.display(), + tex.size[0], + tex.size[1], + mae / 2.55 + ); + } + Ok(()) +} diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs new file mode 100644 index 0000000000000000000000000000000000000000..8e63222eba38428c1f560787a1a2eac538e38925 --- /dev/null +++ b/crates/engine/src/cache.rs @@ -0,0 +1,210 @@ +//! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction, +//! and surgical cache-busting modes for profiling and playback verification. + +use model::NodeId; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CacheMode { + /// Content-hashed cache across all nodes up to `budget_bytes`. + Enabled, + /// Forces full re-evaluation every frame (zero reads/writes to node cache). + Bypass, +} + +#[derive(Clone, Debug)] +pub struct CachedTexture { + pub texture: Arc, + pub view: Arc, + /// Actual allocated GPU texture dimensions `[w, h]`. + pub size: [u32; 2], + /// Domain of Definition (DoD) top-left offset in logical canvas pixels (`[0, 0]` for standard frames). + pub origin: [i32; 2], + /// Logical frame canvas dimensions (e.g. `[1920, 1080]`, matching `size` when DoD == canvas). + pub canvas_size: [u32; 2], + pub content_hash: u64, + pub bytes: u64, +} + +impl CachedTexture { + pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self { + Self::from_texture_dod(texture, size, [0, 0], size, content_hash) + } + + pub fn from_texture_dod( + texture: wgpu::Texture, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + content_hash: u64, + ) -> Self { + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let bytes = u64::from(size[0]) * u64::from(size[1]) * 4; + Self { + texture: Arc::new(texture), + view: Arc::new(view), + size, + origin, + canvas_size, + content_hash, + bytes, + } + } + + pub fn has_dod(&self) -> bool { + self.origin != [0, 0] || self.size != self.canvas_size + } +} + +#[derive(Clone, Debug, Default)] +pub struct EvalStats { + pub eval_ms: f64, + pub nodes_evaluated: usize, + pub cache_hits: usize, + pub cache_misses: usize, + pub source_loads: usize, + pub pruned_branches: usize, + pub cached_entries: usize, + pub cached_vram_mb: f64, + pub media_entries: usize, + pub media_mb: f64, + pub unsupported_nodes: Vec, +} + +struct Entry { + tex: CachedTexture, + last_used: u64, + producers: HashSet, + frames: HashSet, +} + +pub struct NodeCache { + pub mode: CacheMode, + pub budget_bytes: u64, + entries: HashMap, + total_bytes: u64, + tick: u64, + /// Monotonic salt bumped when busting GPU cache globally. + pub gpu_salt: u64, + /// Per-node salt bumped when surgically busting a subtree. + node_salts: HashMap, +} + +impl NodeCache { + pub fn new(budget_mb: u64) -> Self { + Self { + mode: CacheMode::Enabled, + budget_bytes: budget_mb * 1024 * 1024, + entries: HashMap::new(), + total_bytes: 0, + tick: 0, + gpu_salt: 0, + node_salts: HashMap::new(), + } + } + + pub fn node_salt(&self, id: NodeId) -> u64 { + self.node_salts.get(&id).copied().unwrap_or(0) + } + + pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option { + if self.mode == CacheMode::Bypass { + return None; + } + self.tick += 1; + let e = self.entries.get_mut(&key)?; + e.last_used = self.tick; + e.producers.insert(node); + e.frames.insert(frame); + Some(e.tex.clone()) + } + + pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) { + if self.mode == CacheMode::Bypass { + return; + } + self.tick += 1; + if let Some(old) = self.entries.remove(&key) { + self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); + } + self.total_bytes += tex.bytes; + let mut producers = HashSet::new(); + producers.insert(node); + let mut frames = HashSet::new(); + frames.insert(frame); + self.entries.insert( + key, + Entry { + tex, + last_used: self.tick, + producers, + frames, + }, + ); + self.evict_over_budget(); + } + + fn evict_over_budget(&mut self) { + while self.total_bytes > self.budget_bytes && self.entries.len() > 2 { + let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) + else { + break; + }; + if let Some(removed) = self.entries.remove(&oldest_key) { + self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + } + } + } + + /// Wipes every cached GPU node texture and bumps global salt. + pub fn bust_all(&mut self) { + self.entries.clear(); + self.total_bytes = 0; + self.gpu_salt += 1; + } + + /// Removes cached entries produced for a specific integer frame. + pub fn bust_frame(&mut self, frame: i64) -> usize { + let keys: Vec = self + .entries + .iter() + .filter(|(_, e)| e.frames.contains(&frame)) + .map(|(k, _)| *k) + .collect(); + let count = keys.len(); + for k in keys { + if let Some(removed) = self.entries.remove(&k) { + self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + } + } + count + } + + /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream + /// via Merkle hashing!) and evicts its existing entries. + pub fn bust_subtree(&mut self, node: NodeId) -> usize { + *self.node_salts.entry(node).or_insert(0) += 1; + let keys: Vec = self + .entries + .iter() + .filter(|(_, e)| e.producers.contains(&node)) + .map(|(k, _)| *k) + .collect(); + let count = keys.len(); + for k in keys { + if let Some(removed) = self.entries.remove(&k) { + self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + } + } + count + } + + pub fn entry_count(&self) -> usize { + self.entries.len() + } + + pub fn total_mb(&self) -> f64 { + self.total_bytes as f64 / (1024.0 * 1024.0) + } +} diff --git a/crates/engine/src/eval.rs b/crates/engine/src/eval.rs new file mode 100644 index 0000000000000000000000000000000000000000..a6821206448b037e7183566a8c717a04befbb7b7 --- /dev/null +++ b/crates/engine/src/eval.rs @@ -0,0 +1,3112 @@ +//! Headless `wgpu` 2D compositor evaluator with Merkle content-hash caching, +//! branch pruning, and surgical cache-busting. + +use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; +use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; +use bytemuck::{Pod, Zeroable}; +use model::{Comp, ExprEngine, Node, NodeId, ParamValue, default_main_input_port}; +use std::collections::{HashMap, HashSet}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::time::Instant; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct UniformParams { + p: [[f32; 4]; 16], +} + +impl Default for UniformParams { + fn default() -> Self { + Self { p: [[0.0; 4]; 16] } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DisplaySettings { + pub exposure: f32, // stops (0.0 = 1x) + pub gamma: f32, // default 1.0 + pub channel: u32, // 0=RGBA, 1=R, 2=G, 3=B, 4=A + pub checker_bg: bool, + /// False (default) = exact nearest-neighbor pixels ("raw truth" when zooming in); + /// True = bilinear "Smooth Resize". + pub smooth_resize: bool, + /// Visible normalized UV rectangle `[u0, v0, u1, v1]` sampled into the viewer output texture. + pub uv_rect: [f32; 4], +} + +impl Default for DisplaySettings { + fn default() -> Self { + Self { + exposure: 0.0, + gamma: 1.0, + channel: 0, + checker_bg: true, + smooth_resize: false, + uv_rect: [0.0, 0.0, 1.0, 1.0], + } + } +} + +struct Pipelines { + bgl: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + bg: wgpu::ComputePipeline, + merge: wgpu::ComputePipeline, + transform: wgpu::ComputePipeline, + bc: wgpu::ComputePipeline, + cc: wgpu::ComputePipeline, + color_gain: wgpu::ComputePipeline, + luma_key: wgpu::ComputePipeline, + blur: wgpu::ComputePipeline, + dir_blur: wgpu::ComputePipeline, + fast_noise: wgpu::ComputePipeline, + displace: wgpu::ComputePipeline, + mask_shape: wgpu::ComputePipeline, + mask_combine: wgpu::ComputePipeline, + mask_apply: wgpu::ComputePipeline, + colorize: wgpu::ComputePipeline, + color_curves: wgpu::ComputePipeline, + xf_chroma: wgpu::ComputePipeline, + gamut_convert: wgpu::ComputePipeline, + vari_blur: wgpu::ComputePipeline, + outline_tint: wgpu::ComputePipeline, + outline_composite: wgpu::ComputePipeline, + text_outline: wgpu::ComputePipeline, + custom_wave: wgpu::ComputePipeline, + crop: wgpu::ComputePipeline, + glow_add: wgpu::ComputePipeline, + xglow_prep: wgpu::ComputePipeline, + xglow_accum: wgpu::ComputePipeline, + display_blit: wgpu::ComputePipeline, + invert: wgpu::ComputePipeline, + channel_boolean: wgpu::ComputePipeline, +} + +impl Pipelines { + fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("compositor-shaders"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders.wgsl").into()), + }); + + let tex_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("compositor-bgl"), + entries: &[ + tex_entry(0), + tex_entry(1), + tex_entry(2), + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba8Unorm, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("compositor-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let make = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&layout), + module: &shader, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("compositor-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + + Self { + bgl, + sampler, + bg: make("bg_op"), + merge: make("merge_op"), + transform: make("transform_op"), + bc: make("bc_op"), + cc: make("cc_op"), + color_gain: make("color_gain_op"), + luma_key: make("luma_key_op"), + blur: make("blur_op"), + dir_blur: make("dir_blur_op"), + fast_noise: make("fast_noise_op"), + displace: make("displace_op"), + mask_shape: make("mask_shape_op"), + mask_combine: make("mask_combine_op"), + mask_apply: make("mask_apply_op"), + colorize: make("colorize_op"), + color_curves: make("color_curves_op"), + xf_chroma: make("xf_chroma_op"), + gamut_convert: make("gamut_convert_op"), + vari_blur: make("vari_blur_op"), + outline_tint: make("outline_tint"), + outline_composite: make("outline_composite"), + text_outline: make("text_outline_op"), + custom_wave: make("custom_wave_op"), + crop: make("crop_op"), + glow_add: make("glow_add_op"), + xglow_prep: make("xglow_prep_op"), + xglow_accum: make("xglow_accum_op"), + display_blit: make("display_blit_op"), + invert: make("invert_op"), + channel_boolean: make("channel_boolean_op"), + } + } +} + +pub struct Engine { + device: wgpu::Device, + queue: wgpu::Queue, + pipelines: Pipelines, + scene3d: crate::scene3d::Scene3DRenderer, + dummy: CachedTexture, + pub cache: NodeCache, + pub media: MediaCache, + pub expr: ExprEngine, + /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. + frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, + /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default + /// to matching the dimensions & aspect ratio of the node they mask!). + mask_target_size: Option<[u32; 2]>, + /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res. + pub proxy_scale: u32, + /// High-Quality mode (`true` = exact Fusion bar-for-bar passes; `false` = perfmaxxed pyramid blur/glow & fast taps). + pub hiq: bool, +} + +impl Engine { + pub fn new(device: wgpu::Device, queue: wgpu::Queue) -> Self { + let pipelines = Pipelines::new(&device); + let scene3d = crate::scene3d::Scene3DRenderer::new(&device); + let dummy = create_texture(&device, [1, 1], 0); + queue.write_texture( + dummy.texture.as_image_copy(), + &[0, 0, 0, 0], + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(4), + rows_per_image: Some(1), + }, + wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + ); + Self { + device, + queue, + pipelines, + scene3d, + dummy, + cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs) + media: MediaCache::new(1024), + expr: ExprEngine::new(), + frame_memo: HashMap::new(), + mask_target_size: None, + proxy_scale: 1, + hiq: true, + } + } + + pub fn new_headless() -> Result> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?; + let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?; + Ok(Self::new(device, queue)) + } + + pub fn device(&self) -> &wgpu::Device { + &self.device + } + + pub fn queue(&self) -> &wgpu::Queue { + &self.queue + } + + pub fn set_cache_mode(&mut self, mode: CacheMode) { + self.cache.mode = mode; + } + + pub fn bust_all_caches(&mut self) { + self.cache.bust_all(); + self.media.clear(); + } + + pub fn bust_gpu_cache(&mut self) { + self.cache.bust_all(); + } + + pub fn bust_frame(&mut self, frame: i64) -> usize { + self.cache.bust_frame(frame) + } + + pub fn bust_subtree(&mut self, node: NodeId) -> usize { + self.cache.bust_subtree(node) + } + + /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. + pub fn evaluate( + &mut self, + comp: &Comp, + target: NodeId, + time: f64, + ) -> (CachedTexture, EvalStats) { + let t0 = Instant::now(); + let mut stats = EvalStats::default(); + let mut visiting = HashSet::new(); + self.frame_memo.clear(); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-eval"), + }); + + let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); + if tex.has_dod() { + // Crop expanded DoD cleanly back to logical canvas_size for final readback/export + let cropped = create_texture(&self.device, tex.canvas_size, tex.content_hash ^ 0xD0D0); + let mut params = UniformParams::default(); + params.p[0] = [1.0, 1.0, 0.0, 0.0]; + params.p[4] = [ + tex.origin[0] as f32, + tex.origin[1] as f32, + tex.canvas_size[0] as f32, + tex.canvas_size[1] as f32, + ]; + self.dispatch(&mut encoder, &self.pipelines.display_blit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, ¶ms); + tex = cropped; + } + self.queue.submit(Some(encoder.finish())); + + stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; + stats.cached_entries = self.cache.entry_count(); + stats.cached_vram_mb = self.cache.total_mb(); + stats.media_entries = self.media.entry_count(); + stats.media_mb = self.media.total_mb(); + (tex, stats) + } + + /// Zero-copy render straight into a persistent viewer `wgpu::Texture` (premultiplied Rgba8Unorm). + pub fn render_into_viewer( + &mut self, + comp: &Comp, + target: NodeId, + time: f64, + dst_texture: &wgpu::Texture, + display: DisplaySettings, + ) -> EvalStats { + let t0 = Instant::now(); + let mut stats = EvalStats::default(); + let mut visiting = HashSet::new(); + self.frame_memo.clear(); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-viewer-eval"), + }); + + let tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); + + let dst_size = [dst_texture.width(), dst_texture.height()]; + let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let mut params = UniformParams::default(); + params.p[0] = [ + 2.0_f32.powf(display.exposure), + display.gamma, + display.channel as f32, + if display.checker_bg { 1.0 } else { 0.0 }, + ]; + params.p[1] = display.uv_rect; + params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; + if tex.has_dod() { + params.p[4] = [ + tex.origin[0] as f32, + tex.origin[1] as f32, + tex.canvas_size[0] as f32, + tex.canvas_size[1] as f32, + ]; + } + self.dispatch_to_view( + &mut encoder, + &self.pipelines.display_blit, + &tex.view, + &self.dummy.view, + &self.dummy.view, + &dst_view, + dst_size, + ¶ms, + ); + + self.queue.submit(Some(encoder.finish())); + + stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; + stats.cached_entries = self.cache.entry_count(); + stats.cached_vram_mb = self.cache.total_mb(); + stats.media_entries = self.media.entry_count(); + stats.media_mb = self.media.total_mb(); + stats + } + + /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export). + pub fn readback_rgba(&self, tex: &CachedTexture) -> Result, Box> { + let [w, h] = tex.size; + let bpp = 4u32; + let unpadded_bpr = w * bpp; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback"), + size: u64::from(padded_bpr) * u64::from(h), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = self.device.create_command_encoder(&Default::default()); + enc.copy_texture_to_buffer( + tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + self.queue.submit(Some(enc.finish())); + + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + self.device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + })?; + rx.recv()??; + let data = slice.get_mapped_range()?; + let mut out = Vec::with_capacity((w * h * 4) as usize); + for row in 0..h as usize { + let start = row * padded_bpr as usize; + out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); + } + drop(data); + buf.unmap(); + Ok(out) + } + + fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] { + let s = self.proxy_scale.max(1); + [(w / s).max(1), (h / s).max(1)] + } + + fn eval_node( + &mut self, + comp: &Comp, + id: NodeId, + time: f64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let frame_i = time.round() as i64; + let is_mask_node = matches!( + comp.node(id).kind.as_str(), + "EllipseMask" | "RectangleMask" | "PolylineMask" + ); + let memo_sz = if is_mask_node { self.mask_target_size } else { None }; + // Always memoize within a single frame's DAG pass so diamond graphs never explode + // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache). + if let Some(hit) = self.frame_memo.get(&(id, frame_i, memo_sz)).cloned() { + stats.cache_hits += 1; + return hit; + } + if !visiting.insert((id, frame_i)) { + return self.dummy.clone(); + } + let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats); + visiting.remove(&(id, frame_i)); + self.frame_memo.insert((id, frame_i, memo_sz), res.clone()); + res + } + + fn eval_node_inner( + &mut self, + comp: &Comp, + id: NodeId, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let node = comp.node(id); + let comp_dims = self.scaled_dims(comp.width, comp.height); + + // Bypass (`PassThrough`) or passthrough utility nodes + if node.bypassed || matches!(node.kind.as_str(), "Saver" | "PipeRouter" | "Fuse.Wireless" | "Tracker") { + let port = default_main_input_port(&node.kind); + if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { + return self.eval_node(comp, src_id, time, enc, visiting, stats); + } + return self.dummy.clone(); + } + + // MacroOperator / GroupOperator: seamlessly evaluate the unpacked internal output tool! + if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { + if let Some(out_id) = node.macro_output { + return self.eval_node(comp, out_id, time, enc, visiting, stats); + } + if let Some(src_id) = node + .connected_node("Input") + .or_else(|| node.connected_node("MainInput1")) + .and_then(|s| comp.find_node(s)) + { + return self.eval_node(comp, src_id, time, enc, visiting, stats); + } + return self.dummy.clone(); + } + + // TimeStretcher / TimeSpeed: remap time BEFORE evaluating upstream! + if node.kind == "TimeStretcher" { + let remapped = comp.eval_number(node, "SourceTime", time, time, &self.expr); + if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { + return self.eval_node(comp, src_id, remapped, enc, visiting, stats); + } + return self.dummy.clone(); + } + if node.kind == "TimeSpeed" { + let speed = comp.eval_number(node, "Speed", time, 1.0, &self.expr); + let delay = comp.eval_number(node, "Delay", time, 0.0, &self.expr); + let remapped = (time - delay) * speed; + if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { + return self.eval_node(comp, src_id, remapped, enc, visiting, stats); + } + return self.dummy.clone(); + } + if node.kind == "Switch" || node.kind == "Fuse.Switch" { + let which = comp.eval_number(node, "Which", time, 1.0, &self.expr).round().max(1.0) as usize; + let port = format!("Input{which}"); + let src_name = node.connected_node(&port).or_else(|| node.connected_node("Input1")); + if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { + return self.eval_node(comp, src_id, time, enc, visiting, stats); + } + return self.dummy.clone(); + } + + match node.kind.as_str() { + "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats), + "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats), + "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats), + "Scale" | "BetterResize" => self.eval_scale(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "Crop" => self.eval_crop(comp, node, time, frame_i, enc, visiting, stats), + "BrightnessContrast" => self.eval_bc(comp, node, time, frame_i, enc, visiting, stats), + "ColorCorrector" => self.eval_cc(comp, node, time, frame_i, enc, visiting, stats), + "ColorGain" => self.eval_color_gain(comp, node, time, frame_i, enc, visiting, stats), + "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats), + "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats), + "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats), + "ChannelBoolean" => self.eval_channel_boolean(comp, node, time, frame_i, enc, visiting, stats), + "LumaKeyer" => self.eval_luma_key(comp, node, time, frame_i, enc, visiting, stats), + "Blur" => self.eval_blur(comp, node, time, frame_i, enc, visiting, stats), + "VariBlur" => self.eval_vari_blur(comp, node, time, frame_i, enc, visiting, stats), + "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats), + "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats), + "ErodeDilate" => self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats), + "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats), + "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), + "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), + "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), + "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "BitmapMask" => self.eval_bitmap_mask(comp, node, time, enc, visiting, stats), + "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats), + "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), + "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + other => { + // Graceful passthrough for unsupported nodes (e.g. MacroOperator, 3D, etc.) + if !stats.unsupported_nodes.iter().any(|s| s == other) { + stats.unsupported_nodes.push(other.to_owned()); + } + let port = default_main_input_port(other); + if let Some(src_id) = node.connected_node(port) + .or_else(|| node.connected_node("MainInput1")) + .or_else(|| node.connected_node("Input")) + .or_else(|| node.connected_node("Background")) + .and_then(|s| comp.find_node(s)) + { + self.eval_node(comp, src_id, time, enc, visiting, stats) + } else { + self.dummy.clone() + } + } + } + } + + #[allow(clippy::too_many_arguments)] + fn eval_mask_input_sized( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + target_size: Option<[u32; 2]>, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> (Option, bool) { + let invert = comp.eval_number(node, "ApplyMaskInverted", time, 0.0, &self.expr) > 0.5; + let prev_sz = self.mask_target_size; + if target_size.is_some() { + self.mask_target_size = target_size; + } + let tex = node + .connected_node("EffectMask") + .and_then(|s| comp.find_node(s)) + .map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); + self.mask_target_size = prev_sz; + (tex, invert) + } + + fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { + let mut h = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h); + self.hiq.hash(&mut h); + self.cache.node_salt(node.id).hash(&mut h); + tag.hash(&mut h); + size.hash(&mut h); + upstream.hash(&mut h); + for &v in params { + v.to_bits().hash(&mut h); + } + h.finish() + } + + fn eval_loader( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(clip) = node.clips.first() else { + return self.dummy.clone(); + }; + let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(1.0) > 0.5; + let exr_channels = [ + node.static_str("Clip1.OpenEXRFormat.RedName"), + node.static_str("Clip1.OpenEXRFormat.GreenName"), + node.static_str("Clip1.OpenEXRFormat.BlueName"), + node.static_str("Clip1.OpenEXRFormat.AlphaName"), + ]; + let Some((resolved, local_idx, img, loaded_from_disk)) = + self.media.load_clip(clip, frame_i, post_mult, exr_channels) + else { + return self.dummy.clone(); + }; + if loaded_from_disk { + stats.source_loads += 1; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img.size[0], img.size[1])), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let target_size = self.scaled_dims(img.size[0], img.size[1]); + let mut h = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h); + self.cache.node_salt(node.id).hash(&mut h); + "Loader".hash(&mut h); + resolved.hash(&mut h); + local_idx.hash(&mut h); + post_mult.hash(&mut h); + target_size.hash(&mut h); + mask_hash.hash(&mut h); + mask_inv.hash(&mut h); + let key = h.finish(); + + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let need_post = target_size != img.size || mask.is_some(); + let full_tex = create_texture(&self.device, img.size, if need_post { 0 } else { key }); + self.queue.write_texture( + full_tex.texture.as_image_copy(), + &img.rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(img.size[0] * 4), + rows_per_image: Some(img.size[1]), + }, + wgpu::Extent3d { + width: img.size[0], + height: img.size[1], + depth_or_array_layers: 1, + }, + ); + let base_tex = if target_size != img.size { + let scaled = create_texture(&self.device, target_size, if mask.is_some() { 0 } else { key }); + let mut u = UniformParams::default(); + u.p[0] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.display_blit, &full_tex.view, &self.dummy.view, &self.dummy.view, &scaled, &u); + scaled + } else { + full_tex + }; + let tex = if let Some(m) = mask { + let masked = create_texture(&self.device, target_size, key); + let mut u = UniformParams::default(); + u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.mask_apply, &base_tex.view, &self.dummy.view, &m.view, &masked, &u); + masked + } else { + base_tex + }; + self.cache.insert(key, tex.clone(), node.id, frame_i); + tex + } + + fn eval_background( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; + let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; + + let tl = [ + comp.eval_number(node, "TopLeftRed", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "TopLeftGreen", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "TopLeftBlue", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "TopLeftAlpha", time, 1.0, &self.expr) as f32, + ]; + let tr = [ + comp.eval_number(node, "TopRightRed", time, tl[0] as f64, &self.expr) as f32, + comp.eval_number(node, "TopRightGreen", time, tl[1] as f64, &self.expr) as f32, + comp.eval_number(node, "TopRightBlue", time, tl[2] as f64, &self.expr) as f32, + comp.eval_number(node, "TopRightAlpha", time, tl[3] as f64, &self.expr) as f32, + ]; + let bl = [ + comp.eval_number(node, "BottomLeftRed", time, tl[0] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomLeftGreen", time, tl[1] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomLeftBlue", time, tl[2] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomLeftAlpha", time, tl[3] as f64, &self.expr) as f32, + ]; + let br = [ + comp.eval_number(node, "BottomRightRed", time, tr[0] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomRightGreen", time, tr[1] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomRightBlue", time, tr[2] as f64, &self.expr) as f32, + comp.eval_number(node, "BottomRightAlpha", time, tr[3] as f64, &self.expr) as f32, + ]; + + let mut kind = match node.static_str("Type").unwrap_or("Solid") { + "Horizontal" => 1.0, + "Vertical" => 2.0, + "Corner" => 3.0, + "Gradient" => match node.static_str("GradientType").unwrap_or("Linear") { + "Radial" => 5.0, + _ => 4.0, + }, + _ => 0.0, + }; + let mut c0 = tl; + let mut c1 = tr; + if kind >= 4.0 { + if let Some(grad) = comp.eval_gradient(node, "Gradient", time) { + c0 = grad.sample(0.0); + c1 = grad.sample(1.0); + } else { + kind = 0.0; + } + } + let start = comp.eval_point(node, "Start", time, [0.0, 0.5], &self.expr); + let end = comp.eval_point(node, "End", time, [1.0, 0.5], &self.expr); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = c0; + u.p[1] = c1; + u.p[2] = bl; + u.p[3] = br; + u.p[4] = [kind, 0.0, start[0] as f32, start[1] as f32]; + u.p[5] = [ + end[0] as f32, + end[1] as f32, + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + ]; + + let key = self.make_key(node, "Background", size, &[mask_hash], bytemuck::cast_slice(&u.p[..6])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = create_texture(&self.device, size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.bg, &self.dummy.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_merge( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let bg = match node.connected_node("Background").and_then(|s| comp.find_node(s)) { + Some(bid) => self.eval_node(comp, bid, time, enc, visiting, stats), + None => return self.dummy.clone(), + }; + + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + // Temporal liveness pruning — don't even evaluate Foreground! + stats.pruned_branches += 1; + return bg; + } + + let fg = match node.connected_node("Foreground").and_then(|s| comp.find_node(s)) { + Some(fid) => self.eval_node(comp, fid, time, enc, visiting, stats), + None => return bg, + }; + + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size_s = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32; + let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32; + let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32; + let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32; + let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32; + let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, &self.expr) as f32; + let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, &self.expr) as f32; + + let mode_str = node.static_str("ApplyMode").unwrap_or("Normal"); + let mode_id = match mode_str { + "Screen" => 1.0, + "Multiply" => 2.0, + "Darken" => 3.0, + "Lighten" => 4.0, + "Difference" => 5.0, + "Exclusion" => 6.0, + "Overlay" => 7.0, + "Hard Light" | "HardLight" => 8.0, + "Soft Light" | "SoftLight" => 9.0, + "LinearLight" | "Linear Light" => 10.0, + "Color Dodge" | "ColorDodge" => 11.0, + "LinearDodge" | "Linear Dodge" | "Add" => 12.0, + "VividLight" | "Vivid Light" => 13.0, + "Hypotenuse" => 14.0, + "DarkerColor" | "Darker Color" => 15.0, + "LighterColor" | "Lighter Color" => 16.0, + "PinLight" | "Pin Light" => 17.0, + "ColorBurn" | "Color Burn" => 18.0, + "LinearBurn" | "Linear Burn" => 19.0, + "Geometric" => 20.0, + "Hue" => 21.0, + "Saturation" => 22.0, + "Color" => 23.0, + "Luminosity" => 24.0, + _ => 0.0, + }; + let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; + let op_id = match node.static_str("Operator").unwrap_or("Over") { + "Under" => 1.0, + "In" => 2.0, + "Held Out" | "HeldOut" => 3.0, + "Atop" => 4.0, + "XOr" => 5.0, + _ => 0.0, // Over + }; + + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, size_s, angle_deg.to_radians()]; + u.p[1] = [blend, gain, mode_id, edges]; + u.p[2] = [flip_h, flip_v, nearest, op_id]; + u.p[3] = [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + fg.canvas_size[0] as f32, + fg.canvas_size[1] as f32, + ]; + if fg.has_dod() { + u.p[4] = [ + fg.origin[0] as f32, + fg.origin[1] as f32, + fg.canvas_size[0] as f32, + fg.canvas_size[1] as f32, + ]; + } + if bg.has_dod() { + u.p[5] = [ + bg.origin[0] as f32, + bg.origin[1] as f32, + bg.canvas_size[0] as f32, + bg.canvas_size[1] as f32, + ]; + } + u.p[6] = [burn_in, sub_add, 0.0, 0.0]; + + let key = self.make_key( + node, + "Merge", + bg.size, + &[bg.content_hash, fg.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..7]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = create_texture_dod(&self.device, bg.size, bg.origin, bg.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.merge, &bg.view, &fg.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_transform( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); + let use_xy = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, &self.expr) < 0.5; + let (sx, sy) = if use_xy { + ( + comp.eval_number(node, "XSize", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32, + ) + } else { + let s = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32; + let asp = comp.eval_number(node, "Aspect", time, 1.0, &self.expr) as f32; + (s, s * asp) + }; + let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); + let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32; + let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, &self.expr) as f32; + let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, &self.expr) as f32; + let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, pivot[0] as f32, pivot[1] as f32]; + u.p[1] = [sx, sy, angle, edges]; + u.p[2] = [flip_h, flip_v, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, 0.0, 0.0]; + if src.has_dod() { + u.p[4] = [ + src.origin[0] as f32, + src.origin[1] as f32, + src.canvas_size[0] as f32, + src.canvas_size[1] as f32, + ]; + } + + let out_size = src.canvas_size; + let key = self.make_key(node, "Transform", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = create_texture(&self.device, out_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.transform, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_scale( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let hiq_only = comp.eval_number(node, "HiQOnly", time, 0.0, &self.expr) > 0.5; + if !self.hiq && hiq_only && node.kind == "Scale" { + return src; + } + let dst_size = if node.kind == "BetterResize" { + let w = comp.eval_number(node, "Width", time, comp_dims[0] as f64, &self.expr) as u32; + let h = comp.eval_number(node, "Height", time, comp_dims[1] as f64, &self.expr) as u32; + self.scaled_dims(w, h) + } else { + let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr); + let sy = comp.eval_number(node, "YSize", time, sx, &self.expr); + [ + ((src.size[0] as f64 * sx).round() as u32).clamp(1, 8192), + ((src.size[1] as f64 * sy).round() as u32).clamp(1, 8192), + ] + }; + let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; + let mut u = UniformParams::default(); + u.p[0] = [1.0, 1.0, 0.0, 0.0]; + u.p[2] = [nearest, 0.0, 0.0, 0.0]; + let key = self.make_key(node, "Scale", dst_size, &[src.content_hash], &[nearest]); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, dst_size, key); + self.dispatch(enc, &self.pipelines.display_blit, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_crop( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let x_size = comp.eval_number(node, "XSize", time, src.size[0] as f64, &self.expr).round().max(1.0) as u32; + let y_size = comp.eval_number(node, "YSize", time, src.size[1] as f64, &self.expr).round().max(1.0) as u32; + let dst_size = self.scaled_dims(x_size, y_size); + let x_off = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32 / self.proxy_scale.max(1) as f32; + let y_off = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32 / self.proxy_scale.max(1) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [x_off, y_off, 1.0, 1.0]; + let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, dst_size, key); + self.dispatch(enc, &self.pipelines.crop, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_bc( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [ + comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Gamma", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Contrast", time, 0.0, &self.expr) as f32, + ]; + u.p[1] = [ + comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Saturation", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32, + blend, + ]; + u.p[2] = [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "High", time, 1.0, &self.expr) as f32, + ]; + u.p[3] = [ + comp.eval_number(node, "Red", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Green", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Blue", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Alpha", time, 0.0, &self.expr) as f32, + ]; + + let key = self.make_key(node, "BC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, src.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.bc, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_cc( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [ + comp.eval_number(node, "WheelHue1", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelSaturation1", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintAngle1", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintLength1", time, 0.0, &self.expr) as f32, + ]; + u.p[1] = [ + comp.eval_number(node, "MasterRGBGain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "MasterRGBLift", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "MasterRGBGamma", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "MasterRGBContrast", time, 1.0, &self.expr) as f32, + ]; + u.p[2] = [ + comp.eval_number(node, "MasterRGBBrightness", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32, + blend, + if mask.is_some() { 1.0 } else { 0.0 }, + ]; + u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + + let key = self.make_key(node, "CC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, src.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.cc, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_luma_key( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [ + comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "High", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32, + ]; + u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0]; + + let key = self.make_key(node, "LumaKeyer", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, src.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.luma_key, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_blur( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let lock_xy = comp.eval_number(node, "LockBlurXY", time, 1.0, &self.expr) > 0.5; + let mode = if node.static_str("Filter").unwrap_or("Fast Gaussian") == "Box" { 1.0 } else { 0.0 }; + // Fusion XBlurSize is in 720px-reference pixels (blur_norm = XBlurSize / 720.0). + // Gaussian blur_op uses sigma = radius * 0.45 while Fusion Gaussian has sigma ~= 0.553 * blur_px -> * 1.23. + let scale_ref = src.size[0] as f32 / 720.0; + let gauss_k = if mode < 0.5 { 1.14 } else { 1.0 }; + let x_raw = comp.eval_number(node, "XBlurSize", time, 1.0, &self.expr) as f32; + let y_raw = if lock_xy { + x_raw + } else { + comp.eval_number(node, "YBlurSize", time, x_raw as f64, &self.expr) as f32 + }; + let rx = x_raw * scale_ref * gauss_k; + let ry = y_raw * scale_ref * gauss_k; + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let max_r = rx.max(ry); + if max_r < 0.25 || blend <= 1e-6 { + return src; + } + + let key = self.make_key(node, "Blur", src.size, &[src.content_hash, mask_hash], &[rx, ry, blend, mode, clamp_edges, if mask_inv { 1.0 } else { 0.0 }]); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + // Fast mode (`!self.hiq`): downsample large blurs to 1/2 or 1/4 pyramid level for 4-16x speedup! + let down = if self.hiq { + 1u32 + } else if max_r >= 16.0 { + 4u32 + } else if max_r >= 5.0 { + 2u32 + } else { + 1u32 + }; + + if down > 1 { + let work_size = [(src.size[0] / down).max(1), (src.size[1] / down).max(1)]; + let small = create_texture(&self.device, work_size, 0); + let tmp = create_texture(&self.device, work_size, 0); + let small_blur = create_texture(&self.device, work_size, 0); + + let mut u_blit = UniformParams::default(); + u_blit.p[0] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.display_blit, &src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit); + + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, rx / down as f32, mode]; + uh.p[1] = [1.0, 0.0, 0.0, clamp_edges]; + self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp, &uh); + + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, ry / down as f32, mode]; + uv.p[1] = [1.0, 0.0, 0.0, clamp_edges]; + self.dispatch(enc, &self.pipelines.blur, &tmp.view, &self.dummy.view, &self.dummy.view, &small_blur, &uv); + + if blend >= 0.999 && mask.is_none() { + self.dispatch(enc, &self.pipelines.display_blit, &small_blur.view, &self.dummy.view, &self.dummy.view, &dst, &u_blit); + } else { + let mut um = UniformParams::default(); + um.p[0] = [0.5, 0.5, 1.0, 0.0]; + um.p[1] = [blend, 1.0, 0.0, 0.0]; + um.p[3] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, src.size[0] as f32, src.size[1] as f32]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.merge, &src.view, &small_blur.view, mv, &dst, &um); + } + } else { + let tmp = create_texture(&self.device, src.size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, rx, mode]; + uh.p[1] = [1.0, 0.0, 0.0, clamp_edges]; + self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh); + + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, ry, mode]; + uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, clamp_edges]; + uv.p[2] = [1.0, 0.0, 0.0, 0.0]; // blend against original unblurred src in src_b! + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.blur, &tmp.view, &src.view, mv, &dst, &uv); + } + + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_dir_blur( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32; + let len = comp.eval_number(node, "Length", time, 0.02, &self.expr) as f32; + let ang = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); + let glow = comp.eval_number(node, "Glow", time, 0.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let samples = if self.hiq { + ((len.abs() * 320.0).clamp(16.0, 48.0)).round() + } else { + ((len.abs() * 120.0).clamp(8.0, 12.0)).round() + }; + let mut u = UniformParams::default(); + u.p[0] = [kind, len, ang, glow]; + u.p[1] = [center[0] as f32, center[1] as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, samples, 0.0, 0.0]; + let key = self.make_key(node, "DirBlur", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, src.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.dir_blur, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_glow( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let is_soft_glow = node.kind == "SoftGlow"; + // Fusion SoftGlow/Glow sizes are in 720px-reference pixels (same as Blur). + let scale_ref = src.size[0] as f32 / 720.0 * 1.14; + let (raw_size, gain, thresh, combine_mode) = if is_soft_glow { + let sz = comp.eval_number(node, "XGlowSize", time, 10.0, &self.expr) as f32; + let g = comp.eval_number(node, "Gain", time, 2.0, &self.expr) as f32; + let th = comp.eval_number(node, "Threshold", time, 0.0, &self.expr).clamp(0.0, 0.999) as f32; + (sz, g, th, 0.0f32) // Screen blend + } else { + let sz = comp.eval_number(node, "GlowSize", time, 10.0, &self.expr) as f32; + let glow_p = comp.eval_number(node, "Glow", time, 0.8, &self.expr).clamp(0.0, 0.999) as f32; + let g = 1.0 / (1.0 - glow_p).max(1e-3); + (sz, g, 0.0f32, 1.0f32) // Replace with blurred / (1 - Glow) + }; + let size = (raw_size * scale_ref).max(0.0); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let prev_sz = self.mask_target_size; + self.mask_target_size = Some(src.size); + let glow_mask = node + .connected_node("GlowMask") + .and_then(|s| comp.find_node(s)) + .map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); + self.mask_target_size = prev_sz; + let gm_hash = glow_mask.as_ref().map_or(0, |m| m.content_hash); + + let key = self.make_key( + node, + if is_soft_glow { "SoftGlow" } else { "Glow" }, + src.size, + &[src.content_hash, mask_hash, gm_hash], + &[size, gain, thresh, blend, combine_mode, if mask_inv { 1.0 } else { 0.0 }], + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + // Pre-threshold and/or pre-mask the glow source before blurring + let glow_src = if thresh > 1e-5 || glow_mask.is_some() { + let prepped = create_texture(&self.device, src.size, 0); + let mut up = UniformParams::default(); + up.p[0] = [thresh, 1.0, 1.0, if glow_mask.is_some() { 1.0 } else { 0.0 }]; + up.p[1] = [1.0, 0.0, 0.0, 0.0]; + let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.xglow_prep, &src.view, &self.dummy.view, gmv, &prepped, &up); + prepped + } else { + src.clone() + }; + + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let down = if self.hiq { 1u32 } else if size >= 14.0 { 4u32 } else if size >= 4.0 { 2u32 } else { 1u32 }; + let work_size = [(src.size[0] / down).max(1), (src.size[1] / down).max(1)]; + + let blurred_tex = if size < 0.25 { + glow_src + } else if down > 1 { + let small = create_texture(&self.device, work_size, 0); + let tmp1 = create_texture(&self.device, work_size, 0); + let tmp2 = create_texture(&self.device, work_size, 0); + let upscaled = create_texture(&self.device, src.size, 0); + let mut u_blit = UniformParams::default(); + u_blit.p[0] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.display_blit, &glow_src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit); + + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, size / down as f32, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, size / down as f32, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + self.dispatch(enc, &self.pipelines.display_blit, &tmp2.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit); + upscaled + } else { + let tmp1 = create_texture(&self.device, src.size, 0); + let tmp2 = create_texture(&self.device, src.size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, size, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &glow_src.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, size, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + tmp2 + }; + + let mut ug = UniformParams::default(); + ug.p[0] = [gain, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + ug.p[1] = [combine_mode, 0.0, 0.0, 0.0]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.glow_add, &src.view, &blurred_tex.view, mv, &dst, &ug); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_xglow( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let prev_sz = self.mask_target_size; + self.mask_target_size = Some(src.size); + let glow_mask = node + .connected_node("GlowMask") + .and_then(|s| comp.find_node(s)) + .map(|gid| self.eval_node(comp, gid, time, enc, visiting, stats)); + self.mask_target_size = prev_sz; + let gm_hash = glow_mask.as_ref().map_or(0, |m| m.content_hash); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mode = comp.eval_number(node, "Mode", time, 1.0, &self.expr).round() as i32; // 0=Expo, 1=Fib (default) + let t_lo = comp.eval_number(node, "ThresholdLow", time, 0.0, &self.expr) as f32; + let t_hi = comp.eval_number(node, "ThresholdHigh", time, 0.0, &self.expr) as f32; + let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32; + let src_sat = comp.eval_number(node, "SrcSat", time, 1.0, &self.expr) as f32; + let glow_sat = comp.eval_number(node, "GlowSat", time, 1.0, &self.expr) as f32; + let lock_xy = comp.eval_number(node, "LockXY", time, 1.0, &self.expr) > 0.5; + let x_glow = comp.eval_number(node, "XGlowSize", time, 1.0, &self.expr) as f32; + let y_glow = if lock_xy { + x_glow + } else { + comp.eval_number(node, "YGlowSize", time, x_glow as f64, &self.expr) as f32 + }; + let raw_iters = (comp.eval_number(node, "Iterations", time, 12.0, &self.expr).round() as usize).clamp(1, 16); + let iters = if self.hiq { raw_iters } else { raw_iters.min(5) }; + let falloff = (comp.eval_number(node, "Falloff", time, 1.0, &self.expr) as f32).max(0.05); + let glow_only = comp.eval_number(node, "GlowOnly", time, 0.0, &self.expr) > 0.5; + let grad = comp.eval_gradient(node, "Gradient", time); + + let key = self.make_key( + node, + "MT_XGlow", + src.size, + &[src.content_hash, gm_hash, mask_hash], + &[ + mode as f32, t_lo, t_hi, gain, src_sat, glow_sat, x_glow, y_glow, + iters as f32, falloff, blend, + if glow_only { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + ], + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + // 1. Preprocess glow source: Threshold -> Gain -> SrcSat -> GlowMask RGB multiply (verbatim MT_XGlow.fuse!) + let prep = create_texture(&self.device, src.size, 0); + let mut up = UniformParams::default(); + up.p[0] = [t_lo, t_hi, src_sat, if glow_mask.is_some() { 1.0 } else { 0.0 }]; + up.p[1] = [gain, 0.0, 0.0, 0.0]; + let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.xglow_prep, &src.view, &self.dummy.view, gmv, &prep, &up); + + // 2. Build mip pyramid matching MT_XGlow.fuse (1x, 1/2, 1/4, 1/8, 1/16) + let mut ub = UniformParams::default(); + ub.p[0] = [1.0, 1.0, 0.0, 0.0]; + let make_mip = |engine: &Self, enc: &mut wgpu::CommandEncoder, div: u32| -> CachedTexture { + let ws = [(src.size[0] / div).max(1), (src.size[1] / div).max(1)]; + let t = create_texture(&engine.device, ws, 0); + engine.dispatch(enc, &engine.pipelines.display_blit, &prep.view, &engine.dummy.view, &engine.dummy.view, &t, &ub); + t + }; + let half = if iters > 2 || !self.hiq { Some(make_mip(self, enc, 2)) } else { None }; + let quarter = if iters > 4 { Some(make_mip(self, enc, 4)) } else { None }; + let eighth = if iters > 8 { Some(make_mip(self, enc, 8)) } else { None }; + let sixteenth = if iters > 12 { Some(make_mip(self, enc, 16)) } else { None }; + + const FIB: [f32; 16] = [1.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0, 55.0, 89.0, 144.0, 233.0, 377.0, 610.0, 987.0, 1597.0, 2584.0]; + const EXPO: [f32; 16] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, 32768.0]; + + // Fusion MT_XGlow: blur_x = XGlowSize / 720 (normalized to width -> * src.size[0] px) + // Note: Fusion Gaussian BLUR_XSize=b has sigma ~= b * width * 0.45, matching blur_op directly! + let base_rx = (x_glow / 720.0) * src.size[0] as f32; + let base_ry = (y_glow / 720.0) * src.size[0] as f32; + + let mut running: Option = if glow_only { None } else { Some(src.clone()) }; + for i in 1..=iters { + let var = i as f32 / iters as f32; + let mult = if mode == 1 { FIB[i - 1] } else { EXPO[i - 1] }; + let (mip_tex, div) = if i <= 2 && self.hiq { + (&prep, 1.0_f32) + } else if i <= 4 { + (half.as_ref().unwrap_or(&prep), 2.0_f32) + } else if i <= 8 { + (quarter.as_ref().unwrap_or(&prep), 4.0_f32) + } else if i <= 12 { + (eighth.as_ref().unwrap_or(&prep), 8.0_f32) + } else { + (sixteenth.as_ref().unwrap_or(&prep), 16.0_f32) + }; + + // MT_XGlow passes BLUR_XSize = blur_x * mult to the mip image (which is `div` times smaller, + // so in mip pixels the radius is base_rx * mult / div!). + let rx_mip = (base_rx * mult / div).max(0.0); + let ry_mip = (base_ry * mult / div).max(0.0); + let tmp1 = create_texture(&self.device, mip_tex.size, 0); + let tmp2 = create_texture(&self.device, mip_tex.size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, rx_mip, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &mip_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, ry_mip, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + + let gc = grad.as_ref().map_or([1.0, 1.0, 1.0, 1.0], |g| g.sample(var as f64)); + let falloff_scale = 1.0 / falloff.powi(i as i32); + // Verbatim MT_XGlow.fuse line 422: m:Scale(1/(falloff^i), glowSat*var, glowSat*var, 1) + let y_scale = falloff_scale; + let uv_scale = glow_sat * var; + + let is_last = i == iters && mask.is_none() && (blend - 1.0).abs() <= 1e-4; + let next = create_texture_dod( + &self.device, + src.size, + src.origin, + src.canvas_size, + if is_last { key } else { 0 }, + ); + let mut ua = UniformParams::default(); + ua.p[0] = [gc[0], gc[1], gc[2], y_scale]; + ua.p[1] = [uv_scale, if running.is_some() { 1.0 } else { 0.0 }, falloff_scale * 0.5, 0.0]; + let base_v = running.as_ref().map_or(&self.dummy.view, |r| &r.view); + self.dispatch(enc, &self.pipelines.xglow_accum, base_v, &tmp2.view, &self.dummy.view, &next, &ua); + running = Some(next); + } + + let glowed = running.unwrap_or_else(|| src.clone()); + let dst = if mask.is_some() || (blend - 1.0).abs() > 1e-4 { + let final_dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mut ug = UniformParams::default(); + ug.p[0] = [1.0, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + ug.p[1] = [1.0, 0.0, 0.0, 0.0]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.glow_add, &src.view, &glowed.view, mv, &final_dst, &ug); + final_dst + } else { + glowed + }; + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_erode_dilate( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let amt = comp.eval_number(node, "XAmount", time, 0.0, &self.expr) as f32; + let radius = amt.abs() * src.size[0] as f32; + let mode = if amt < 0.0 { 2.0 } else { 3.0 }; + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key(node, "ErodeDilate", src.size, &[src.content_hash, mask_hash], &[amt, blend, if mask_inv { 1.0 } else { 0.0 }]); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let tmp = create_texture(&self.device, src.size, 0); + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, radius, mode]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, radius, mode]; + uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; + uv.p[2] = [1.0, 0.0, 0.0, 0.0]; // blend against original src in src_b! + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.blur, &tmp.view, &src.view, mv, &dst, &uv); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_fast_noise( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; + let mut size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; + // Cap giant procedural sky-dome FastNoise textures (e.g. 11520x4000) to 4096 max dim keeping aspect! + let max_dim = size[0].max(size[1]); + if max_dim > 4096 { + let scale = 4096.0 / max_dim as f32; + size = [((size[0] as f32 * scale).round() as u32).max(1), ((size[1] as f32 * scale).round() as u32).max(1)]; + } + + let lock_scale = comp.eval_number(node, "LockScale", time, 1.0, &self.expr) > 0.5; + let x_scale = comp.eval_number(node, "XScale", time, 2.0, &self.expr) as f32; + let y_scale = if lock_scale { + x_scale + } else { + comp.eval_number(node, "YScale", time, x_scale as f64, &self.expr) as f32 + }; + let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32; + let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32; + let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32; + let seethe = comp.eval_number(node, "Seethe", time, 0.0, &self.expr) as f32 + + (comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) as f32) * (time as f32) * 0.02; + let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let inverted = comp.eval_number(node, "Inverted", time, 0.0, &self.expr) as f32; + + let c1 = [ + comp.eval_number(node, "Color1Red", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Color1Green", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Color1Blue", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Color1Alpha", time, 0.0, &self.expr) as f32, + ]; + let c2 = [ + comp.eval_number(node, "Color2Red", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Color2Green", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Color2Blue", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Color2Alpha", time, 1.0, &self.expr) as f32, + ]; + let grad = comp.eval_gradient(node, "Gradient", time); + + // Bake high-precision 256x1 RGBA gradient LUT so sharp thresholds (e.g. 0.95..0.96 stars) are exact! + let mut grad_bytes = [0u8; 256 * 4]; + for i in 0..256 { + let t = i as f64 / 255.0; + let c = if let Some(g) = &grad { + g.sample(t) + } else { + let tf = t as f32; + [ + c1[0] + (c2[0] - c1[0]) * tf, + c1[1] + (c2[1] - c1[1]) * tf, + c1[2] + (c2[2] - c1[2]) * tf, + c1[3] + (c2[3] - c1[3]) * tf, + ] + }; + grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8; + } + let mut gh = DefaultHasher::new(); + grad_bytes.hash(&mut gh); + let grad_hash = gh.finish(); + + let mut u = UniformParams::default(); + u.p[0] = [x_scale, y_scale, detail, contrast]; + u.p[1] = [brightness, seethe, disc, center[0] as f32]; + u.p[2] = [center[1] as f32, 0.0, inverted, 1.0]; + + let key = self.make_key(node, "FastNoise", size, &[grad_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let lut_tex = create_texture(&self.device, [256, 1], 0); + self.queue.write_texture( + lut_tex.texture.as_image_copy(), + &grad_bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, + ); + let dst = create_texture(&self.device, size, key); + self.dispatch(enc, &self.pipelines.fast_noise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_displace( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else { + return src; + }; + let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32; + let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32; + let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32; + let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32; + let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32; + let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32; + let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32; + let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32; + let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32; + let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [kind, xr, yr, xo]; + u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; + u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; + + let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, src.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.displace, &src.view, &fg.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn paint_mode_id(node: &Node) -> f32 { + match node.static_str("PaintMode").unwrap_or("Merge") { + "Add" => 1.0, + "Subtract" => 2.0, + "Multiply" => 3.0, + "Minimum" => 4.0, + "Maximum" => 5.0, + "Invert" => 6.0, + "Replace" => 7.0, + _ => 0.0, // Merge + } + } + + #[allow(clippy::too_many_arguments)] + fn eval_mask_shape( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + shape: u32, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let output_size_mode = node.static_str("OutputSize").unwrap_or("Default"); + let size = if output_size_mode != "Custom" { + if let Some(ts) = self.mask_target_size { + ts + } else { + let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; + if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } + } + } else { + let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; + if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } + }; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let mw = comp.eval_number(node, "Width", time, 0.5, &self.expr) as f32; + let mh = comp.eval_number(node, "Height", time, 0.5, &self.expr) as f32; + let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr) as f32; + let corner = comp.eval_number(node, "CornerRadius", time, 0.0, &self.expr) as f32; + let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32; + let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); + let paint_mode = Self::paint_mode_id(node); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, mw, mh]; + u.p[1] = [angle, soft, corner, invert]; + u.p[2] = [shape as f32, level, if prev_mask.is_some() { 1.0 } else { 0.0 }, paint_mode]; + + let key = self.make_key(node, "MaskShape", size, &[prev_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + let soft_px = soft * size[0] as f32; + let dst = if soft_px >= 0.75 { + // Fusion Mask SoftEdge runs a true 2D Gaussian blur (sigma ~ 0.45 * SoftEdge * width) + // over the sharp shape before Invert/Level/PaintMode combine! + let raw = create_texture(&self.device, size, 0); + let mut u_raw = u; + u_raw.p[1] = [angle, 0.0, corner, 0.0]; + u_raw.p[2] = [shape as f32, 1.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.mask_shape, &self.dummy.view, &self.dummy.view, &self.dummy.view, &raw, &u_raw); + + // Downsample for large SoftEdge radii (>24px or Fast mode) so 2048x2048 soft masks stay <0.5ms! + let down = if !self.hiq && soft_px >= 12.0 { + 4u32 + } else if soft_px >= 48.0 { + 4u32 + } else if soft_px >= 20.0 { + 2u32 + } else { + 1u32 + }; + let blurred = if down > 1 { + let ws = [(size[0] / down).max(1), (size[1] / down).max(1)]; + let small = create_texture(&self.device, ws, 0); + let tmp1 = create_texture(&self.device, ws, 0); + let tmp2 = create_texture(&self.device, ws, 0); + let up = create_texture(&self.device, size, 0); + let mut ub = UniformParams::default(); + ub.p[0] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.display_blit, &raw.view, &self.dummy.view, &self.dummy.view, &small, &ub); + let r_s = soft_px / down as f32; + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, r_s, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, r_s, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + self.dispatch(enc, &self.pipelines.display_blit, &tmp2.view, &self.dummy.view, &self.dummy.view, &up, &ub); + up + } else { + let tmp1 = create_texture(&self.device, size, 0); + let tmp2 = create_texture(&self.device, size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, soft_px, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &raw.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, soft_px, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + tmp2 + }; + + let out_tex = create_texture(&self.device, size, key); + let mut uc = UniformParams::default(); + uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; + self.dispatch(enc, &self.pipelines.mask_combine, &blurred.view, &self.dummy.view, mv, &out_tex, &uc); + out_tex + } else { + let out_tex = create_texture(&self.device, size, key); + self.dispatch(enc, &self.pipelines.mask_shape, &self.dummy.view, &self.dummy.view, mv, &out_tex, &u); + out_tex + }; + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + fn eval_polyline_mask( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let has_explicit_w = node.inputs.contains_key("MaskWidth"); + let has_explicit_h = node.inputs.contains_key("MaskHeight"); + let size = if has_explicit_w || has_explicit_h { + let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; + if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } + } else { + self.mask_target_size.unwrap_or(comp_dims) + }; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; + let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5; + let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); + let paint_mode = Self::paint_mode_id(node); + + let evaluated_pts: Vec; + let points: &[model::PolyPoint] = if let Some(src) = node.connected_node("Polyline") { + if let Some(pts) = comp.eval_polyline_spline(src, time) { + evaluated_pts = pts; + &evaluated_pts + } else if let Some(pp) = comp.poly_paths.get(src) { + pp.points.as_slice() + } else { + &[] + } + } else if let Some(pl_tbl) = node + .raw + .get_table("Inputs") + .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) + .and_then(|p| p.get_table("Value")) + { + evaluated_pts = model::PolyPath::parse_polyline_table(pl_tbl).1; + &evaluated_pts + } else { + &[] + }; + + let mut hash_floats = Vec::with_capacity(6 + points.len() * 6); + hash_floats.extend_from_slice(&[ + center[0] as f32, + center[1] as f32, + soft, + if invert { 1.0 } else { 0.0 }, + level, + paint_mode, + ]); + for p in points { + hash_floats.extend_from_slice(&[p.x as f32, p.y as f32, p.lx as f32, p.ly as f32, p.rx as f32, p.ry as f32]); + } + let key = self.make_key(node, "PolylineMask", size, &[prev_hash], &hash_floats); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let soft_px = soft * size[0] as f32 * 1.14; + let need_post = soft_px >= 0.35 || prev_mask.is_some(); + let pixels = rasterize_polyline_mask( + size, + points, + [center[0] as f32, center[1] as f32], + if need_post { false } else { invert }, + if need_post { 1.0 } else { level }, + ); + let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key }); + self.queue.write_texture( + raw_tex.texture.as_image_copy(), + &pixels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size[0] * 4), rows_per_image: Some(size[1]) }, + wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + ); + let tex = if need_post { + let blurred = if soft_px >= 0.35 { + let tmp1 = create_texture(&self.device, size, 0); + let tmp2 = create_texture(&self.device, size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, soft_px, 0.0]; + uh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &raw_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, soft_px, 0.0]; + uv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + tmp2 + } else { + raw_tex + }; + let combined = create_texture(&self.device, size, key); + let mut u = UniformParams::default(); + u.p[0] = [ + paint_mode, + if invert { 1.0 } else { 0.0 }, + level, + if prev_mask.is_some() { 1.0 } else { 0.0 }, + ]; + let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.mask_combine, &blurred.view, &self.dummy.view, mv, &combined, &u); + combined + } else { + raw_tex + }; + self.cache.insert(key, tex.clone(), node.id, frame_i); + tex + } + + fn eval_bitmap_mask( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + if let Some(src_id) = node.connected_node("Image").and_then(|s| comp.find_node(s)) { + self.eval_node(comp, src_id, time, enc, visiting, stats) + } else { + self.dummy.clone() + } + } + + fn eval_text_plus( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; + let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; + + let text_str = comp.eval_text(node, "StyledText", time, "", &self.expr); + let font_family = node.static_str("Font").unwrap_or("Helvetica Neue"); + let font_style = node.static_str("Style").unwrap_or("Regular"); + let size_norm = comp.eval_number(node, "Size", time, 0.08, &self.expr) as f32; + let tracking = comp.eval_number(node, "CharacterSpacing", time, 1.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center (default), +1=Right + let h_lcr = comp.eval_number(node, "HorizontalLeftCenterRight", time, 0.0, &self.expr) as f32; + let v_tcb = comp.eval_number(node, "VerticalTopCenterBottom", time, 0.0, &self.expr) as f32; + + let fill_rgba = [ + comp.eval_number(node, "Red1", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Green1", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Blue1", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Alpha1", time, 1.0, &self.expr) as f32, + ]; + let outline_enabled = comp.eval_number(node, "Enabled2", time, 0.0, &self.expr) > 0.5; + let outline_rgba = [ + comp.eval_number(node, "Red2", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Green2", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Blue2", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "Alpha2", time, 1.0, &self.expr) as f32, + ]; + let outline_thickness = comp.eval_number(node, "Thickness2", time, 0.02, &self.expr) as f32; + let write_start = comp.eval_number(node, "Start", time, 0.0, &self.expr) as f32; + let write_end = comp.eval_number(node, "End", time, 1.0, &self.expr) as f32; + let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, &self.expr) as f32; + let cls_entries = comp.text_cls_entries(node, "StyledText"); + + let mut kh = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut kh); + self.cache.node_salt(node.id).hash(&mut kh); + "TextPlus".hash(&mut kh); + size.hash(&mut kh); + text_str.hash(&mut kh); + font_family.hash(&mut kh); + font_style.hash(&mut kh); + outline_enabled.hash(&mut kh); + cls_entries.len().hash(&mut kh); + for v in [ + size_norm, tracking, center[0] as f32, center[1] as f32, h_lcr, v_tcb, + fill_rgba[0], fill_rgba[1], fill_rgba[2], fill_rgba[3], + outline_rgba[0], outline_rgba[1], outline_rgba[2], outline_rgba[3], + outline_thickness, write_start, write_end, shear_x, + ] { + v.to_bits().hash(&mut kh); + } + let key = kh.finish(); + + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let outline_radius = if outline_enabled && outline_thickness > 1e-4 { + (outline_thickness * size_norm * size[0] as f32 * 0.50).clamp(1.0, 28.0) + } else { + 0.0 + }; + let (tex_size, origin, pixels) = rasterize_text_plus( + size, + &TextPlusParams { + text: &text_str, + font_family, + font_style, + size_norm, + tracking, + center: [center[0] as f32, center[1] as f32], + h_lcr, + v_tcb, + fill_rgba, + write_on_start: write_start, + write_on_end: write_end, + shear_x, + cls: cls_entries, + }, + outline_radius.ceil() as i32 + 2, + ); + let fill_tex = create_texture_dod( + &self.device, + tex_size, + origin, + size, + if outline_enabled { 0 } else { key }, + ); + self.queue.write_texture( + fill_tex.texture.as_image_copy(), + &pixels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) }, + wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 }, + ); + + let final_tex = if outline_radius > 0.0 { + // Single-pass circular Euclidean L2 outline + fill-over-outline composite across DoD! + let dst = create_texture_dod(&self.device, tex_size, origin, size, key); + let mut u = UniformParams::default(); + u.p[0] = outline_rgba; + u.p[1] = [outline_radius, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.text_outline, &fill_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); + dst + } else { + fill_tex + }; + + self.cache.insert(key, final_tex.clone(), node.id, frame_i); + final_tex + } + + fn eval_colorize( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Image").or_else(|| node.connected_node("Input")).and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + // Colorize.fuse defaults: Color 1 = (0,0,0,0), Color 2 = (1,1,1,1) + u.p[0] = [ + comp.eval_number(node, "R1", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "G1", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "B1", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "A1", time, 0.0, &self.expr) as f32, + ]; + u.p[1] = [ + comp.eval_number(node, "R2", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "G2", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "B2", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "A2", time, 1.0, &self.expr) as f32, + ]; + u.p[2] = [ + comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32, + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + 0.0, + ]; + + let key = self.make_key(node, "Fuse.Colorize", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.colorize, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_outline( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Image").or_else(|| node.connected_node("Input")).and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let amount = (comp.eval_number(node, "Amount", time, 0.05, &self.expr) as f32) / 10.0; + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr) as f32; + if amount <= 1e-5 { + return src; + } + // Outline.fuse defaults: R=0, G=0, B=0, A=1 + let r = comp.eval_number(node, "Red", time, 0.0, &self.expr) as f32; + let g = comp.eval_number(node, "Green", time, 0.0, &self.expr) as f32; + let b = comp.eval_number(node, "Blue", time, 0.0, &self.expr) as f32; + let a = comp.eval_number(node, "Alpha", time, 1.0, &self.expr) as f32; + + let key = self.make_key(node, "Fuse.Outline", src.size, &[src.content_hash], &[amount, soft, r, g, b, a]); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + // Outline.fuse multiplies alpha by 120 in float32, then runs BoxBlur(amount) and clamps to [0,1]. + // In int8 Rgba8Unorm, multiplying by 120 would clamp early, so a separable Dilate (mode=3) + // of radius `amount * width` reproduces the exact float32 expansion faithfully! + let radius_px = (amount * src.size[0] as f32).clamp(1.0, 96.0); + let dil_h = create_texture(&self.device, src.size, 0); + let dil_v = create_texture(&self.device, src.size, 0); + let tinted = create_texture(&self.device, src.size, 0); + let dst = create_texture(&self.device, src.size, key); + + let u0 = UniformParams::default(); + let mut dh = UniformParams::default(); + dh.p[0] = [1.0, 0.0, radius_px, 3.0]; + dh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &dil_h, &dh); + + let mut dv = UniformParams::default(); + dv.p[0] = [0.0, 1.0, radius_px, 3.0]; + dv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &dil_h.view, &self.dummy.view, &self.dummy.view, &dil_v, &dv); + + let mut ut = UniformParams::default(); + ut.p[0] = [r, g, b, a]; + ut.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.outline_tint, &dil_v.view, &self.dummy.view, &self.dummy.view, &tinted, &ut); + + let outline_tex = if soft > 1e-4 { + let sr = (soft * radius_px).clamp(1.0, 96.0); + let s1 = create_texture(&self.device, src.size, 0); + let s2 = create_texture(&self.device, src.size, 0); + let mut sh = UniformParams::default(); + sh.p[0] = [1.0, 0.0, sr, 1.0]; + sh.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &tinted.view, &self.dummy.view, &self.dummy.view, &s1, &sh); + let mut sv = UniformParams::default(); + sv.p[0] = [0.0, 1.0, sr, 1.0]; + sv.p[1] = [1.0, 0.0, 0.0, 0.0]; + self.dispatch(enc, &self.pipelines.blur, &s1.view, &self.dummy.view, &self.dummy.view, &s2, &sv); + s2 + } else { + tinted + }; + + self.dispatch(enc, &self.pipelines.outline_composite, &outline_tex.view, &src.view, &self.dummy.view, &dst, &u0); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_custom( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let size = if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { + self.eval_node(comp, src_id, time, enc, visiting, stats).size + } else { + comp_dims + }; + let n1 = comp.eval_number(node, "NumberIn1", time, 1.0, &self.expr) as f32; + let n2 = comp.eval_number(node, "NumberIn2", time, 0.0, &self.expr) as f32; + let red_expr = node.inputs.get("RedExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); + let green_expr = node.inputs.get("GreenExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); + let blue_expr = node.inputs.get("BlueExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); + let wave_mode = |expr: &str| -> f32 { + if !expr.contains("sin(") { + 0.0 + } else if expr.contains("y*w") || expr.contains("y * w") { + 2.0 + } else { + 1.0 + } + }; + let rm = wave_mode(red_expr); + let gm = wave_mode(green_expr); + let bm = wave_mode(blue_expr); + if rm > 0.5 || gm > 0.5 || bm > 0.5 { + let mut u = UniformParams::default(); + // Fusion CustomTool `w` is Image1's full-res pixel width! + let w_ref = (size[0] * self.proxy_scale.max(1)) as f32; + u.p[0] = [n1, n2, w_ref, 0.0]; + u.p[1] = [rm, gm, bm, 1.0]; + let key = self.make_key(node, "CustomWave", size, &[], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, size, key); + self.dispatch(enc, &self.pipelines.custom_wave, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + return dst; + } + if red_expr.contains("1-r1") || red_expr.contains("1 - r1") { + return self.eval_invert(comp, node, time, frame_i, enc, visiting, stats); + } + // Fallback: passthrough Image1 + if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { + self.eval_node(comp, src_id, time, enc, visiting, stats) + } else { + self.dummy.clone() + } + } + + fn eval_invert( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node + .connected_node("Input") + .or_else(|| node.connected_node("Image1")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32; + let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32; + let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32; + let proc_a = comp.eval_number(node, "ProcessAlpha", time, 0.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [proc_r, proc_g, proc_b, proc_a]; + u.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; + let key = self.make_key(node, "Invert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.invert, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_color_gain( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let high_hue = comp.eval_number(node, "HighHue", time, 0.0, &self.expr) as f32; + let mid_hue = comp.eval_number(node, "MidHue", time, 0.0, &self.expr) as f32; + let dark_hue = comp.eval_number(node, "DarkHue", time, 0.0, &self.expr) as f32; + let sat_dark = comp.eval_number(node, "DarkSaturation", time, 1.0, &self.expr) as f32; + let sat_mid = comp.eval_number(node, "MidSaturation", time, 1.0, &self.expr) as f32; + let sat_high = comp.eval_number(node, "HighSaturation", time, 1.0, &self.expr) as f32; + let gain_r = comp.eval_number(node, "GainRed", time, 1.0, &self.expr) as f32; + let gain_g = comp.eval_number(node, "GainGreen", time, 1.0, &self.expr) as f32; + let gain_b = comp.eval_number(node, "GainBlue", time, 1.0, &self.expr) as f32; + let lift_r = comp.eval_number(node, "LiftRed", time, 0.0, &self.expr) as f32; + let lift_g = comp.eval_number(node, "LiftGreen", time, 0.0, &self.expr) as f32; + let lift_b = comp.eval_number(node, "LiftBlue", time, 0.0, &self.expr) as f32; + let gamma_r = comp.eval_number(node, "GammaRed", time, 1.0, &self.expr) as f32; + let gamma_g = comp.eval_number(node, "GammaGreen", time, 1.0, &self.expr) as f32; + let gamma_b = comp.eval_number(node, "GammaBlue", time, 1.0, &self.expr) as f32; + let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [gain_r, gain_g, gain_b, prediv]; + u.p[1] = [lift_r, lift_g, lift_b, blend]; + u.p[2] = [gamma_r, gamma_g, gamma_b, sat_mid]; + u.p[3] = [dark_hue, mid_hue, high_hue, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[4] = [if mask_inv { 1.0 } else { 0.0 }, sat_dark, sat_high, 0.0]; + + let key = self.make_key(node, "ColorGain", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.color_gain, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_color_curves( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; + let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s)); + let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s)); + let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s)); + let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s)); + let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty()); + + let mut lut_bytes = [0u8; 256 * 4]; + for i in 0..256 { + let x = i as f64 / 255.0; + let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); + let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); + let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); + let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); + lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8; + lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8; + lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8; + lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8; + } + let mut lh = DefaultHasher::new(); + lut_bytes.hash(&mut lh); + let lut_hash = lh.finish(); + + let mut u = UniformParams::default(); + u.p[0] = [prediv, ignore_trans, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if apply_a { 1.0 } else { 0.0 }, 0.0, 0.0]; + + let key = self.make_key( + node, + "ColorCurves", + src.size, + &[src.content_hash, mask_hash, lut_hash], + bytemuck::cast_slice(&u.p[..2]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let lut_tex = create_texture(&self.device, [256, 1], 0); + self.queue.write_texture( + lut_tex.texture.as_image_copy(), + &lut_bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, + ); + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.color_curves, &src.view, &lut_tex.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_xf_chroma( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node + .connected_node("Input") + .or_else(|| node.connected_node("Image")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let master = comp.eval_number(node, "MasterFactor", time, 1.0, &self.expr) as f32; + let raw_center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); + let use_sa = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, &self.expr) > 0.5; + let (raw_xs, raw_ys) = if use_sa { + let sz = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32; + let asp = comp.eval_number(node, "Aspect", time, 1.0, &self.expr) as f32; + (sz, sz * asp.max(1e-4)) + } else { + ( + comp.eval_number(node, "XSize", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32, + ) + }; + let raw_angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + + let cx = (raw_center[0] as f32 - 0.5) * master + 0.5; + let cy = (raw_center[1] as f32 - 0.5) * master + 0.5; + let xs = (raw_xs - 1.0) * master + 1.0; + let ys = (raw_ys - 1.0) * master + 1.0; + let angle_rad = (raw_angle * master).to_radians(); + + let raw_steps = (comp.eval_number(node, "Steps", time, 8.0, &self.expr).round() as i32).clamp(1, 32); + let steps = if self.hiq { raw_steps } else { raw_steps.min(6) } as f32; + let acc_mode = comp.eval_number(node, "AccumulationMode", time, 0.0, &self.expr) as f32; + let normalize = comp.eval_number(node, "NormalizeResult", time, 1.0, &self.expr) as f32; + let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32; + let gamma = comp.eval_number(node, "InputImageGamma", time, 1.0, &self.expr) as f32; + + // Bake 256x1 RGBA gradient LUT (default XfChroma RGB rainbow if Gradient omitted) + let grad = comp.eval_gradient(node, "Gradient", time); + let mut grad_bytes = [0u8; 256 * 4]; + for i in 0..256 { + let t = i as f64 / 255.0; + let c = if let Some(g) = &grad { + g.sample(t) + } else if t <= 0.5 { + let f = (t * 2.0) as f32; + [1.0 - f, f, 0.0, 1.0] + } else { + let f = ((t - 0.5) * 2.0) as f32; + [0.0, 1.0 - f, f, 1.0] + }; + grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8; + grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8; + } + let mut gh = DefaultHasher::new(); + grad_bytes.hash(&mut gh); + let grad_hash = gh.finish(); + + let mut u = UniformParams::default(); + u.p[0] = [cx, cy, pivot[0] as f32, pivot[1] as f32]; + u.p[1] = [xs, ys, angle_rad, steps]; + u.p[2] = [acc_mode, normalize, gain, gamma]; + u.p[3] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; + if src.has_dod() { + u.p[4] = [src.origin[0] as f32, src.origin[1] as f32, src.canvas_size[0] as f32, src.canvas_size[1] as f32]; + } + + let key = self.make_key( + node, + "XfChroma", + src.canvas_size, + &[src.content_hash, mask_hash, grad_hash], + bytemuck::cast_slice(&u.p[..5]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let grad_tex = create_texture(&self.device, [256, 1], 0); + self.queue.write_texture( + grad_tex.texture.as_image_copy(), + &grad_bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, + ); + let dst = create_texture(&self.device, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.xf_chroma, &src.view, &grad_tex.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_channel_boolean( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); + let op = comp.eval_number(node, "Operation", time, 0.0, &self.expr).round() as i32; + let to_r = comp.eval_number(node, "ToRed", time, 0.0, &self.expr).round() as i32; + let to_g = comp.eval_number(node, "ToGreen", time, 1.0, &self.expr).round() as i32; + let to_b = comp.eval_number(node, "ToBlue", time, 2.0, &self.expr).round() as i32; + let to_a = comp.eval_number(node, "ToAlpha", time, 3.0, &self.expr).round() as i32; + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return bg; + } + // Fast path: Copy BG R/G/B/A onto itself (e.g. ZBuffer-only ChannelBoolean) + if op == 0 && to_r == 5 && to_g == 6 && to_b == 7 && to_a == 8 { + return bg; + } + // When Foreground is unconnected, Fusion uses Background as Foreground + let fg = if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) { + self.eval_node(comp, fg_id, time, enc, visiting, stats) + } else { + bg.clone() + }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let mut u = UniformParams::default(); + u.p[0] = [op as f32, to_r as f32, to_g as f32, to_b as f32]; + u.p[1] = [ + to_a as f32, + blend, + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + ]; + if fg.has_dod() { + u.p[2] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32]; + } + let key = self.make_key(node, "ChannelBoolean", bg.size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture(&self.device, bg.size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.channel_boolean, &bg.view, &fg.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_gamut_convert( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let map_space = |s: Option<&str>| -> f32 { + match s.unwrap_or("NoChange") { + "sRGB" => 1.0, + "Rec709" | "Rec.709" => 2.0, + _ => 0.0, + } + }; + let remove_gamma = comp.eval_number(node, "RemoveGamma", time, 1.0, &self.expr) > 0.5; + let add_gamma = comp.eval_number(node, "AddGamma", time, 1.0, &self.expr) > 0.5; + let src_sp = if remove_gamma { map_space(node.static_str("SourceSpace")) } else { 0.0 }; + let dst_sp = if add_gamma { map_space(node.static_str("OutputSpace")) } else { 0.0 }; + if src_sp == 0.0 && dst_sp == 0.0 { + return src; + } + let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 1.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [src_sp, dst_sp, prediv, blend]; + u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0]; + let key = self.make_key(node, "GamutConvert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.gamut_convert, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn eval_vari_blur( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let rx = (comp.eval_number(node, "XBlurSize", time, 1.0, &self.expr) as f32) * 2.0 / self.proxy_scale.max(1) as f32; + let ry = (comp.eval_number(node, "YBlurSize", time, (rx * self.proxy_scale.max(1) as f32 / 2.0) as f64, &self.expr) as f32) * 2.0 / self.proxy_scale.max(1) as f32; + let bmap = node + .connected_node("BlurImage") + .and_then(|s| comp.find_node(s)) + .map(|bid| self.eval_node(comp, bid, time, enc, visiting, stats)); + let bm_hash = bmap.as_ref().map_or(0, |b| b.content_hash); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let rings = if self.hiq { 3.0 } else { 2.0 }; + + let mut u = UniformParams::default(); + u.p[0] = [rx, ry, if bmap.is_some() { 1.0 } else { 0.0 }, blend]; + u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, rings, 0.0]; + let key = self.make_key(node, "VariBlur", src.size, &[src.content_hash, bm_hash, mask_hash], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key); + let bv = bmap.as_ref().map_or(&self.dummy.view, |b| &b.view); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch(enc, &self.pipelines.vari_blur, &src.view, bv, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + fn eval_renderer3d( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; + let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; + let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4); + + let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { + return create_texture(&self.device, size, 0); + }; + + let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5; + let mut cameras = Vec::new(); + let mut mesh_specs = Vec::new(); + let mut lights = crate::scene3d::SceneLights::default(); + crate::scene3d::collect_scene( + comp, + scene_id, + time, + &self.expr, + crate::scene3d::mat4_identity(), + aspect, + &mut cameras, + &mut mesh_specs, + &mut lights, + 0, + ); + + let (view, proj, cam_pos) = if let Some(cam) = cameras.first() { + let v = crate::scene3d::mat4_inverse_rigid(cam.world); + let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far); + (v, p, [cam.world[12], cam.world[13], cam.world[14]]) + } else { + let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0); + let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0); + (v, p, [0.0, 0.0, 5.0]) + }; + let view_proj = crate::scene3d::mat4_mul(proj, view); + + let mut draw_meshes = Vec::with_capacity(mesh_specs.len()); + let mut upstream_hashes = Vec::with_capacity(mesh_specs.len()); + let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20); + hash_floats.extend_from_slice(&view_proj); + hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 }); + hash_floats.extend_from_slice(&lights.ambient); + hash_floats.extend_from_slice(&lights.dir_to_light); + hash_floats.extend_from_slice(&lights.dir_color); + for ms in mesh_specs { + let tex = ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); + upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash)); + hash_floats.extend_from_slice(&ms.world); + hash_floats.extend_from_slice(&ms.diffuse_col); + draw_meshes.push(crate::scene3d::DrawMesh { + world: ms.world, + shape: ms.shape, + tex, + diffuse_col: ms.diffuse_col, + roughness: ms.roughness, + }); + } + + let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = create_texture(&self.device, size, key); + self.scene3d.render_meshes( + &self.device, + &self.queue, + enc, + &dst, + &self.dummy, + view_proj, + view, + cam_pos, + lights, + lighting_enabled, + &draw_meshes, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + fn dispatch( + &self, + enc: &mut wgpu::CommandEncoder, + pipeline: &wgpu::ComputePipeline, + src_a: &wgpu::TextureView, + src_b: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst: &CachedTexture, + params: &UniformParams, + ) { + self.dispatch_to_view(enc, pipeline, src_a, src_b, mask, &dst.view, dst.size, params); + } + + #[allow(clippy::too_many_arguments)] + fn dispatch_to_view( + &self, + enc: &mut wgpu::CommandEncoder, + pipeline: &wgpu::ComputePipeline, + src_a: &wgpu::TextureView, + src_b: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst_view: &wgpu::TextureView, + dst_size: [u32; 2], + params: &UniformParams, + ) { + let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("op-params"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); + + let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("op-bg"), + layout: &self.pipelines.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.pipelines.sampler) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, + wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() }, + ], + }); + + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("comp-op"), + timestamp_writes: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); + } +} + +pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture { + create_texture_dod(device, size, [0, 0], size, content_hash) +} + +pub fn create_texture_dod( + device: &wgpu::Device, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + content_hash: u64, +) -> CachedTexture { + let clamped = [size[0].max(1), size[1].max(1)]; + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("comp-tex"), + size: wgpu::Extent3d { + width: clamped[0], + height: clamped[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + CachedTexture::from_texture_dod(tex, clamped, origin, [canvas_size[0].max(1), canvas_size[1].max(1)], content_hash) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..978dfade8c424e4243880e985f2467eb9ad4f5a3 --- /dev/null +++ b/crates/engine/src/lib.rs @@ -0,0 +1,7 @@ +pub mod cache; +pub mod eval; +pub mod media; +pub mod scene3d; + +pub use cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; +pub use eval::{DisplaySettings, Engine, create_texture}; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs new file mode 100644 index 0000000000000000000000000000000000000000..a1f5ab4452d2952ad47850a23d839572a4ff3566 --- /dev/null +++ b/crates/engine/src/media.rs @@ -0,0 +1,658 @@ +//! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and +//! CPU rasterizers (`TextPlus` via `knife/text` CoreText, `PolylineMask` via `zeno`). + +use model::{ClipSpec, ClsEntry, PolyPoint}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; + +#[derive(Clone)] +pub struct DecodedImage { + pub size: [u32; 2], + /// Premultiplied RGBA8 pixels, top-down. + pub rgba: Arc>, +} + +#[derive(Clone, Copy, Debug)] +struct VideoInfo { + width: u32, + height: u32, + fps: f64, + nb_frames: i64, +} + +fn is_video_path(path: &Path) -> bool { + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { + return false; + }; + matches!( + ext.to_ascii_lowercase().as_str(), + "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf" + ) +} + +fn probe_video(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height,r_frame_rate,nb_frames", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let text = String::from_utf8_lossy(&out.stdout); + let mut width = 0u32; + let mut height = 0u32; + let mut fps = 30.0_f64; + let mut nb_frames = 0i64; + for line in text.lines() { + if let Some((k, v)) = line.split_once('=') { + match k.trim() { + "width" => width = v.trim().parse().unwrap_or(0), + "height" => height = v.trim().parse().unwrap_or(0), + "nb_frames" => nb_frames = v.trim().parse().unwrap_or(0), + "r_frame_rate" => { + if let Some((n, d)) = v.trim().split_once('/') { + let num: f64 = n.parse().unwrap_or(30.0); + let den: f64 = d.parse().unwrap_or(1.0); + if den > 0.0 && num > 0.0 { + fps = num / den; + } + } else if let Ok(r) = v.trim().parse::() { + if r > 0.0 { + fps = r; + } + } + } + _ => {} + } + } + } + if width == 0 || height == 0 { + return None; + } + Some(VideoInfo { width, height, fps, nb_frames }) +} + +fn decode_video_frame(path: &Path, info: VideoInfo, frame_idx: i64) -> Option> { + let idx = frame_idx.max(0); + let ts = if idx == 0 { + 0.0 + } else { + ((idx as f64) - 0.005) / info.fps.max(1.0) + }; + let out = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-ss", + &format!("{ts:.6}"), + "-i", + ]) + .arg(path) + .args([ + "-frames:v", + "1", + "-f", + "rawvideo", + "-pix_fmt", + "rgba", + "-", + ]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let expected = (info.width as usize) * (info.height as usize) * 4; + if out.stdout.len() < expected { + return None; + } + let mut buf = out.stdout; + buf.truncate(expected); + Some(buf) +} + +fn is_exr_path(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("exr")) +} + +/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR +/// into RGBA8 (`u8`, linear [0..1] clamped so downstream `GamutConvert` applies exact sRGB!). +fn decode_exr_rgba( + path: &Path, + red_name: Option<&str>, + green_name: Option<&str>, + blue_name: Option<&str>, + alpha_name: Option<&str>, + post_multiply: bool, +) -> Option { + use exr::prelude::*; + let img = read_all_flat_layers_from_file(path).ok()?; + let layer = img.layer_data.first()?; + let w = layer.size.width(); + let h = layer.size.height(); + if w == 0 || h == 0 { + return None; + } + + let find_channel = |preferred: Option<&str>, fallbacks: &[&str]| -> Option> { + let mut names: Vec<&str> = Vec::new(); + if let Some(p) = preferred { + names.push(p); + } + names.extend_from_slice(fallbacks); + for target in names { + for ch in &layer.channel_data.list { + let cname = ch.name.to_string(); + if cname == target || cname.ends_with(&format!(".{target}")) { + let vals: Vec = ch.sample_data.values_as_f32().collect(); + if vals.len() == w * h { + return Some(vals); + } + } + } + } + None + }; + + let ch_r = find_channel(red_name, &["ViewLayer.Combined.R", "Combined.R", "R", "r"])?; + let ch_g = find_channel(green_name, &["ViewLayer.Combined.G", "Combined.G", "G", "g"]) + .unwrap_or_else(|| ch_r.clone()); + let ch_b = find_channel(blue_name, &["ViewLayer.Combined.B", "Combined.B", "B", "b"]) + .unwrap_or_else(|| ch_r.clone()); + let ch_a = find_channel(alpha_name, &["ViewLayer.Combined.A", "Combined.A", "A", "a"]); + + let mut raw = vec![0u8; w * h * 4]; + for i in 0..(w * h) { + let a = ch_a.as_ref().map_or(1.0, |v| v[i]).clamp(0.0, 1.0); + let mut r = ch_r[i].clamp(0.0, 1.0); + let mut g = ch_g[i].clamp(0.0, 1.0); + let mut b = ch_b[i].clamp(0.0, 1.0); + if post_multiply && a < 1.0 { + r *= a; + g *= a; + b *= a; + } + raw[i * 4] = (r * 255.0 + 0.5) as u8; + raw[i * 4 + 1] = (g * 255.0 + 0.5) as u8; + raw[i * 4 + 2] = (b * 255.0 + 0.5) as u8; + raw[i * 4 + 3] = (a * 255.0 + 0.5) as u8; + } + Some(DecodedImage { + size: [w as u32, h as u32], + rgba: Arc::new(raw), + }) +} + +pub struct MediaCache { + images: HashMap<(PathBuf, i64), DecodedImage>, + video_info: HashMap>, + total_bytes: u64, + budget_bytes: u64, + lru: HashMap<(PathBuf, i64), u64>, + tick: u64, +} + +impl MediaCache { + pub fn new(budget_mb: u64) -> Self { + Self { + images: HashMap::new(), + video_info: HashMap::new(), + total_bytes: 0, + budget_bytes: budget_mb * 1024 * 1024, + lru: HashMap::new(), + tick: 0, + } + } + + pub fn clear(&mut self) { + self.images.clear(); + self.lru.clear(); + self.total_bytes = 0; + } + + pub fn entry_count(&self) -> usize { + self.images.len() + } + + pub fn total_mb(&self) -> f64 { + self.total_bytes as f64 / (1024.0 * 1024.0) + } + + fn insert_cached(&mut self, cache_key: (PathBuf, i64), decoded: DecodedImage) { + let bytes = decoded.rgba.len() as u64; + self.tick += 1; + if let Some(prev) = self.images.insert(cache_key.clone(), decoded) { + self.total_bytes = self.total_bytes.saturating_sub(prev.rgba.len() as u64); + } + self.lru.insert(cache_key, self.tick); + self.total_bytes += bytes; + + while self.total_bytes > self.budget_bytes && self.images.len() > 2 { + let Some(oldest) = self.lru.iter().min_by_key(|&(_, &t)| t).map(|(k, _)| k.clone()) else { + break; + }; + self.lru.remove(&oldest); + if let Some(rem) = self.images.remove(&oldest) { + self.total_bytes = self.total_bytes.saturating_sub(rem.rgba.len() as u64); + } + } + } + + /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`. + /// Returns `(resolved_path, local_frame_idx, decoded_image, loaded_from_disk)`. + pub fn load_clip( + &mut self, + clip: &ClipSpec, + frame: i64, + post_multiply: bool, + exr_channels: [Option<&str>; 4], + ) -> Option<(PathBuf, i64, DecodedImage, bool)> { + let base = Path::new(&clip.filename); + if is_video_path(base) { + if !base.exists() { + return None; + } + // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast] + if clip.global_end >= clip.global_start && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) { + let min_f = clip.global_start - clip.extend_first.max(0); + let max_f = clip.global_end + clip.extend_last.max(0); + if frame < min_f || frame > max_f { + return None; + } + } + let base_buf = base.to_path_buf(); + let info = if let Some(cached) = self.video_info.get(&base_buf).copied() { + cached? + } else { + let probed = probe_video(base); + self.video_info.insert(base_buf.clone(), probed); + probed? + }; + + let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1); + let trim_in = clip.trim_in.clamp(0, len - 1); + let trim_out = if clip.trim_out > 0 { + clip.trim_out.clamp(trim_in, len - 1) + } else { + len - 1 + }; + let span = (trim_out - trim_in + 1).max(1); + let mut rel = frame - clip.global_start; + if rel < 0 { + rel = 0; + } else if clip.loop_clip { + rel = rel.rem_euclid(span); + } else { + rel = rel.clamp(0, span - 1); + } + let idx = if clip.reverse { trim_out - rel } else { trim_in + rel }; + let cache_key = (base_buf.clone(), idx); + if let Some(img) = self.images.get(&cache_key).cloned() { + self.tick += 1; + self.lru.insert(cache_key, self.tick); + return Some((base_buf, idx, img, false)); + } + let raw = decode_video_frame(base, info, idx)?; + let decoded = DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + }; + self.insert_cached(cache_key, decoded.clone()); + return Some((base_buf, idx, decoded, true)); + } + + let resolved = resolve_clip_path(clip, frame)?; + let cache_key = (resolved.clone(), -1); + if let Some(img) = self.images.get(&cache_key).cloned() { + self.tick += 1; + self.lru.insert(cache_key, self.tick); + return Some((resolved, -1, img, false)); + } + + let decoded = if is_exr_path(&resolved) { + // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply! + decode_exr_rgba( + &resolved, + exr_channels[0], + exr_channels[1], + exr_channels[2], + exr_channels[3], + false, + )? + } else { + let dyn_img = image::open(&resolved).ok()?; + let rgba_img = dyn_img.to_rgba8(); + let size = [rgba_img.width(), rgba_img.height()]; + let mut raw = rgba_img.into_raw(); + if post_multiply { + for px in raw.chunks_exact_mut(4) { + let a = u16::from(px[3]); + if a < 255 { + px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8; + px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8; + px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8; + } + } + } + DecodedImage { size, rgba: Arc::new(raw) } + }; + self.insert_cached(cache_key, decoded.clone()); + Some((resolved, -1, decoded, true)) + } +} + +/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`. +pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { + let base = Path::new(&clip.filename); + let len = clip.length.unwrap_or(1); + let stem = base.file_stem()?.to_str()?; + let ext = base.extension().and_then(|e| e.to_str()).unwrap_or(""); + let digit_start = stem.rfind(|c: char| !c.is_ascii_digit()).map(|i| i + 1).unwrap_or(0); + let prefix = &stem[..digit_start]; + let digits = &stem[digit_start..]; + let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty()); + if !is_seq || digits.is_empty() { + return base.exists().then(|| base.to_path_buf()); + } + + let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 }; + let len = len.max(1); + let trim_in = clip.trim_in.clamp(0, len - 1); + let trim_out = if clip.trim_out > 0 { clip.trim_out.clamp(trim_in, len - 1) } else { len - 1 }; + let span = (trim_out - trim_in + 1).max(1); + + let mut rel = frame - clip.global_start; + if clip.loop_clip { + rel = rel.rem_euclid(span); + } else { + rel = rel.clamp(0, span - 1); + } + let idx = if clip.reverse { + seq_start + trim_out - rel + } else { + seq_start + trim_in + rel + }; + + let width = digits.len(); + let new_name = if ext.is_empty() { + format!("{prefix}{idx:0width$}") + } else { + format!("{prefix}{idx:0width$}.{ext}") + }; + let candidate = base.with_file_name(new_name); + if candidate.exists() { + Some(candidate) + } else if base.exists() { + Some(base.to_path_buf()) + } else { + None + } +} + +/// Parameters for rasterizing a Fusion `TextPlus` node using `knife/text` (CoreText). +pub struct TextPlusParams<'a> { + pub text: &'a str, + pub font_family: &'a str, + pub font_style: &'a str, + pub size_norm: f32, // Fusion Size (fraction of canvas width, ~0.08 default) + pub tracking: f32, // Fusion CharacterSpacing (1.0 = normal) + pub center: [f32; 2], // Fusion normalized Y-up (0.5, 0.5) + pub h_lcr: f32, // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center, +1=Right + pub v_tcb: f32, // Fusion VerticalTopCenterBottom: -1=Top, 0=Center, +1=Bottom + pub fill_rgba: [f32; 4], + pub write_on_start: f32, + pub write_on_end: f32, + pub shear_x: f32, // Fusion CharacterShearX + pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides +} + +/// Rasterizes a `TextPlus` fill layer into premultiplied RGBA8 with automatic Domain-of-Definition +/// (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a downstream `Transform`) +/// are never clipped. Returns `(tex_size, dod_origin_px, rgba)`. +pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_pad: i32) -> ([u32; 2], [i32; 2], Vec) { + let [w, h] = dims; + if params.text.is_empty() || params.size_norm <= 1e-4 { + return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + } + + // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! + let total_chars = params.text.chars().count(); + let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; + let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; + if c_start >= c_end || c_start >= total_chars { + return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + } + + // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). + let mut cls_dx = vec![0.0_f32; total_chars]; + let mut cls_dy = vec![0.0_f32; total_chars]; + for e in params.cls { + let s = e.start.min(total_chars); + let end = (e.end + 1).min(total_chars); + for i in s..end { + if e.prop_id == 1350 { + cls_dx[i] = e.value; + } else if e.prop_id == 1351 { + cls_dy[i] = e.value; + } + } + } + + // Fusion Text+ `Size` is in frame-width units (calibrated across AT Name Sans / Helvetica / Liberation Sans: + // `0.68625 * w` equals `1.22 * h` on 16:9 and stays proportional on square/vertical frames!). + let font_px = (params.size_norm * w as f32 * 0.68625).clamp(6.0, 1024.0); + let weight = style_to_weight(params.font_style); + let italic = params.font_style.to_ascii_lowercase().contains("italic") + || params.font_style.to_ascii_lowercase().contains("oblique"); + + let families: Arc<[text::Family]> = if params.font_family.is_empty() { + Arc::from([text::Family::Sans]) + } else { + Arc::from([ + text::Family::Named(Arc::from(params.font_family)), + text::Family::Sans, + ]) + }; + let font = text::Font { + families, + size: font_px, + weight, + italic, + }; + let handle = text::FontHandle::new(&font); + let metrics = handle.metrics(); + + // Extra tracking per glyph: Fusion `CharacterSpacing = 1.0` means 0 extra; >1.0 expands cleanly. + let extra_track = (params.tracking - 1.0) * font_px * 1.15; + + let lines: Vec<&str> = params.text.split('\n').collect(); + let line_height = (metrics.ascent + metrics.descent).max(font_px * 1.15); + let total_h = line_height * lines.len() as f32; + + // Fusion Center is Y-up; convert to top-down pixel coordinates. + let cx = params.center[0] * w as f32; + let cy = (1.0 - params.center[1]) * h as f32; + + let top_y = cy - total_h * (params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5); + let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; + let fc = params.fill_rgba; + let shear_x = params.shear_x; + + // Pass 1: rasterize all visible glyphs & collect exact bounds to expand DoD if anything overflows canvas! + struct PlacedGlyph { + ox: i32, + oy: i32, + baseline_y: f32, + w: i32, + h: i32, + data: Vec, + } + let mut placed = Vec::new(); + let mut min_x = 0i32; + let mut min_y = 0i32; + let mut max_x = w as i32; + let mut max_y = h as i32; + + let mut char_cursor = 0usize; + for (li, line_str) in lines.iter().enumerate() { + let mut glyphs = Vec::new(); + let mut pen_x = 0.0_f32; + for ch in line_str.chars() { + let idx = char_cursor; + char_cursor += 1; + let adv = handle.advance(ch); + if idx >= c_start && idx < c_end { + if let Some(gid) = handle.glyph(ch) { + glyphs.push((gid, pen_x, idx)); + } + } + pen_x += adv + extra_track; + } + char_cursor += 1; // account for '\n' separator + let line_w = (pen_x - extra_track).max(0.0); + let start_x = cx - line_w * h_frac; + let baseline_y = top_y + (li as f32) * line_height + metrics.ascent; + + for (gid, gx, idx) in glyphs { + let Some(mask) = handle.rasterize(gid, 1.0, [0, 0]) else { continue }; + let cdx = cls_dx[idx] * w as f32; + let cdy = -cls_dy[idx] * w as f32; + let ox = (start_x + gx + cdx).round() as i32 + mask.left; + let g_base_y = baseline_y + cdy; + let oy = g_base_y.round() as i32 - mask.top; + let mw = mask.width as i32; + let mh = mask.height as i32; + let shear_pad = (shear_x.abs() * mh as f32).ceil() as i32; + if mw > 0 && mh > 0 { + min_x = min_x.min(ox - outline_pad - shear_pad); + min_y = min_y.min(oy - outline_pad); + max_x = max_x.max(ox + mw + outline_pad + shear_pad); + max_y = max_y.max(oy + mh + outline_pad); + placed.push(PlacedGlyph { ox, oy, baseline_y: g_base_y, w: mw, h: mh, data: mask.data }); + } + } + } + + // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. + let origin_x = min_x.max(-(w as i32)); + let origin_y = min_y.max(-(h as i32)); + let end_x = max_x.min((w as i32) * 2); + let end_y = max_y.min((h as i32) * 2); + let tw = (end_x - origin_x).max(1) as u32; + let th = (end_y - origin_y).max(1) as u32; + let mut out = vec![0u8; (tw as usize) * (th as usize) * 4]; + + for g in placed { + for my in 0..g.h { + let py = g.oy + my; + let dy = py - origin_y; + if dy < 0 || dy >= th as i32 { continue; } + let row_shear = if shear_x.abs() > 1e-4 { + (-((g.baseline_y - py as f32) * shear_x)).round() as i32 + } else { + 0 + }; + for mx in 0..g.w { + let dx = g.ox + mx + row_shear - origin_x; + if dx < 0 || dx >= tw as i32 { continue; } + let cov = g.data[(my * g.w + mx) as usize]; + if cov > 0 { + let i = ((dy as usize) * (tw as usize) + (dx as usize)) * 4; + let a = (cov as f32 / 255.0) * fc[3]; + let prev_a = out[i + 3] as f32 / 255.0; + let na = a.max(prev_a); + out[i] = (fc[0] * na * 255.0).clamp(0.0, 255.0) as u8; + out[i + 1] = (fc[1] * na * 255.0).clamp(0.0, 255.0) as u8; + out[i + 2] = (fc[2] * na * 255.0).clamp(0.0, 255.0) as u8; + out[i + 3] = (na * 255.0).clamp(0.0, 255.0) as u8; + } + } + } + } + + ([tw, th], [origin_x, origin_y], out) +} + +fn style_to_weight(style: &str) -> u16 { + let s = style.to_ascii_lowercase(); + if s.contains("black") || s.contains("heavy") { 900 } + else if s.contains("extrabold") || s.contains("ultrabold") { 800 } + else if s.contains("bold") { 700 } + else if s.contains("semibold") || s.contains("demi") { 600 } + else if s.contains("medium") { 500 } + else if s.contains("light") { 300 } + else if s.contains("thin") || s.contains("hairline") { 100 } + else { 400 } +} + +/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. +pub fn rasterize_polyline_mask( + dims: [u32; 2], + points: &[PolyPoint], + center: [f32; 2], + invert: bool, + level: f32, +) -> Vec { + let [w, h] = dims; + let mut out = vec![0u8; (w as usize) * (h as usize) * 4]; + if points.len() < 2 { + return out; + } + let to_px = |x: f64, y: f64| -> [f32; 2] { + let fx = (center[0] + x as f32) * w as f32; + let fy = (1.0 - (center[1] + y as f32)) * h as f32; + [fx, fy] + }; + let mut cmds = Vec::new(); + let p0 = to_px(points[0].x, points[0].y); + cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); + for i in 0..points.len() { + let a = &points[i]; + let b = &points[(i + 1) % points.len()]; + let c1 = to_px(a.x + a.rx, a.y + a.ry); + let c2 = to_px(b.x + b.lx, b.y + b.ly); + let p = to_px(b.x, b.y); + if a.linear && b.linear { + cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1]))); + } else { + cmds.push(zeno::Command::CurveTo( + zeno::Vector::new(c1[0], c1[1]), + zeno::Vector::new(c2[0], c2[1]), + zeno::Vector::new(p[0], p[1]), + )); + } + } + cmds.push(zeno::Command::Close); + + let mut mask = vec![0u8; (w as usize) * (h as usize)]; + let mut scratch = zeno::Scratch::new(); + let placement = zeno::Mask::with_scratch(&cmds, &mut scratch) + .size(w, h) + .origin(zeno::Origin::TopLeft) + .render_into(&mut mask, None); + let _ = placement; + for (i, &cov) in mask.iter().enumerate() { + let mut a = cov as f32 / 255.0; + if invert { a = 1.0 - a; } + let b = (a * level * 255.0).clamp(0.0, 255.0) as u8; + out[i * 4] = b; + out[i * 4 + 1] = b; + out[i * 4 + 2] = b; + out[i * 4 + 3] = b; + } + out +} diff --git a/crates/engine/src/scene3d.rs b/crates/engine/src/scene3d.rs new file mode 100644 index 0000000000000000000000000000000000000000..b4c9bed427bd5166cb32c2264ae9f9301facec0f --- /dev/null +++ b/crates/engine/src/scene3d.rs @@ -0,0 +1,903 @@ +//! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, +//! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, +//! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. +//! +//! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, +//! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, +//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. + +use crate::cache::CachedTexture; +use bytemuck::{Pod, Zeroable}; +use model::{Comp, ExprEngine, Node, NodeId}; + +pub type Mat4 = [f32; 16]; // Column-major 4x4 + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct Vertex3D { + pos: [f32; 3], + normal: [f32; 3], + uv: [f32; 2], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct MeshUniform { + mvp: [f32; 16], + model: [f32; 16], + /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) + dod: [f32; 4], + /// `[use_tex, lighting_enabled, roughness, 0]` + flags: [f32; 4], + /// Diffuse color multiplier `(r, g, b, a)` + diffuse_col: [f32; 4], + /// Ambient light `(r, g, b, 0)` + ambient: [f32; 4], + /// Directional light direction TO light `(dx, dy, dz, has_dir)` + dir_to_light: [f32; 4], + /// Directional light color * intensity `(r, g, b, 0)` + dir_color: [f32; 4], + /// Camera world position `(cx, cy, cz, 0)` + cam_pos: [f32; 4], +} + +const SHADER_3D: &str = r#" +struct MeshUniform { + mvp: mat4x4, + model: mat4x4, + dod: vec4, + flags: vec4, + diffuse_col: vec4, + ambient: vec4, + dir_to_light: vec4, + dir_color: vec4, + cam_pos: vec4, +}; + +@group(0) @binding(0) var u: MeshUniform; +@group(0) @binding(1) var mat_tex: texture_2d; +@group(0) @binding(2) var mat_samp: sampler; + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +}; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) world_pos: vec3, + @location(2) world_n: vec3, +}; + +@vertex +fn vs_mesh(v: VsIn) -> VsOut { + var out: VsOut; + let wp = u.model * vec4(v.pos, 1.0); + out.clip = u.mvp * vec4(v.pos, 1.0); + out.uv = v.uv; + out.world_pos = wp.xyz; + let wn = (u.model * vec4(v.normal, 0.0)).xyz; + let nlen = length(wn); + out.world_n = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); + return out; +} + +@fragment +fn fs_mesh(in: VsOut) -> @location(0) vec4 { + var col = u.diffuse_col; + if (u.flags.x > 0.5) { + var uv = in.uv; + if (u.dod.z > 0.5 && u.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + let canvas_px = vec2(uv.x * u.dod.z, uv.y * u.dod.w); + uv = (canvas_px - u.dod.xy) / tdims; + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + discard; + } + } + col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col; + } + if (col.a <= 0.002) { + discard; + } + + if (u.flags.y > 0.5) { + // Premultiplied -> unpremultiplied albedo for lighting + let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); + let n = normalize(in.world_n); + var lit = albedo * u.ambient.rgb; + if (u.dir_to_light.w > 0.5) { + let l = normalize(u.dir_to_light.xyz); + let ndotl = max(dot(n, l), 0.0); + lit = lit + albedo * u.dir_color.rgb * ndotl; + if (ndotl > 0.0) { + let v = normalize(u.cam_pos.xyz - in.world_pos); + let h = normalize(l + v); + let rough = clamp(u.flags.z, 0.05, 1.0); + let shininess = max(2.0 / (rough * rough) - 2.0, 2.0); + let spec = pow(max(dot(n, h), 0.0), shininess) * (1.0 - rough * 0.85) * 0.25; + lit = lit + u.dir_color.rgb * spec; + } + } + col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); + } + return col; +} +"#; + +pub struct Scene3DRenderer { + bgl: wgpu::BindGroupLayout, + pipeline: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +#[derive(Clone)] +pub struct CameraInstance { + pub world: Mat4, + pub vfov_rad: f32, + pub near: f32, + pub far: f32, +} + +#[derive(Clone, Debug)] +pub enum ShapeKind { + ImagePlane, + Sphere { radius: f32, sub_base: u32, sub_height: u32 }, + Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, + Plane { width: f32, height: f32 }, + Cube { width: f32, height: f32, depth: f32 }, +} + +#[derive(Clone)] +pub struct MeshInstance { + pub world: Mat4, + pub shape: ShapeKind, + pub material_node: Option, + pub diffuse_col: [f32; 4], + pub roughness: f32, +} + +#[derive(Clone, Copy, Debug)] +pub struct SceneLights { + pub ambient: [f32; 3], + pub dir_to_light: [f32; 3], + pub dir_color: [f32; 3], + pub has_dir: bool, +} + +impl Default for SceneLights { + fn default() -> Self { + Self { + ambient: [0.0, 0.0, 0.0], + dir_to_light: [0.0, 0.0, 1.0], + dir_color: [0.0, 0.0, 0.0], + has_dir: false, + } + } +} + +pub struct DrawMesh { + pub world: Mat4, + pub shape: ShapeKind, + pub tex: Option, + pub diffuse_col: [f32; 4], + pub roughness: f32, +} + +impl Scene3DRenderer { + pub fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("scene3d-shader"), + source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), + }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("scene3d-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let vbuf_layout = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[ + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, + ], + }; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("scene3d-mesh"), + layout: Some(&pl), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_mesh"), + compilation_options: Default::default(), + buffers: &[Some(vbuf_layout)], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_mesh"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("scene3d-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, + ..Default::default() + }); + Self { bgl, pipeline, sampler } + } + + #[allow(clippy::too_many_arguments)] + pub fn render_meshes( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + dst: &CachedTexture, + dummy: &CachedTexture, + view_proj: Mat4, + view: Mat4, + cam_pos: [f32; 3], + lights: SceneLights, + lighting_enabled: bool, + meshes: &[DrawMesh], + ) { + let depth_tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-depth"), + size: wgpu::Extent3d { + width: dst.size[0].max(1), + height: dst.size[1].max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); + + // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. + let mut order: Vec<(usize, f32)> = meshes + .iter() + .enumerate() + .map(|(i, m)| { + let wx = m.world[12]; + let wy = m.world[13]; + let wz = m.world[14]; + let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; + (i, vz) + }) + .collect(); + order.sort_by(|a, b| a.1.total_cmp(&b.1)); + + struct GpuDraw { + bg: wgpu::BindGroup, + vbuf: wgpu::Buffer, + ibuf: wgpu::Buffer, + idx_count: u32, + } + let mut draw_items = Vec::with_capacity(order.len()); + for (idx, _) in order { + let m = &meshes[idx]; + let aspect = m + .tex + .as_ref() + .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) + .unwrap_or(16.0 / 9.0); + let (verts, indices) = build_shape_mesh(&m.shape, aspect); + if indices.is_empty() { + continue; + } + let vbytes = bytemuck::cast_slice(&verts); + let ibytes = bytemuck::cast_slice(&indices); + let vbuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-vb"), + size: vbytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&vbuf, 0, vbytes); + let ibuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-ib"), + size: ibytes.len() as u64, + usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ibuf, 0, ibytes); + + let mvp = mat4_mul(view_proj, m.world); + let dod = if let Some(t) = &m.tex { + if t.has_dod() { + [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32] + } else { + [0.0; 4] + } + } else { + [0.0; 4] + }; + let uni = MeshUniform { + mvp, + model: m.world, + dod, + flags: [ + if m.tex.is_some() { 1.0 } else { 0.0 }, + if lighting_enabled { 1.0 } else { 0.0 }, + m.roughness, + 0.0, + ], + diffuse_col: m.diffuse_col, + ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], + dir_to_light: [ + lights.dir_to_light[0], + lights.dir_to_light[1], + lights.dir_to_light[2], + if lights.has_dir { 1.0 } else { 0.0 }, + ], + dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], + cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], + }; + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-u"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni)); + let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("scene3d-bg"), + layout: &self.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + draw_items.push(GpuDraw { + bg, + vbuf, + ibuf, + idx_count: indices.len() as u32, + }); + } + + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("scene3d-pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &dst.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipeline); + for d in &draw_items { + pass.set_bind_group(0, &d.bg, &[]); + pass.set_vertex_buffer(0, d.vbuf.slice(..)); + pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..d.idx_count, 0, 0..1); + } + } +} + +fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec, Vec) { + match *shape { + ShapeKind::ImagePlane => { + let hx = 0.5; + let hy = 0.5 / tex_aspect.max(1e-4); + let verts = vec![ + Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, + Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, + Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, + Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, + ]; + (verts, vec![0, 1, 2, 0, 2, 3]) + } + ShapeKind::Plane { width, height } => { + let hx = width * 0.5; + let hy = height * 0.5; + let verts = vec![ + Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, + Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, + Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, + Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, + ]; + (verts, vec![0, 1, 2, 0, 2, 3]) + } + ShapeKind::Sphere { radius, sub_base, sub_height } => { + let seg_u = sub_base.clamp(12, 96); + let seg_v = sub_height.clamp(8, 64); + let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); + let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); + for iv in 0..=seg_v { + let v = iv as f32 / seg_v as f32; + let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) + let (sp, cp) = phi.sin_cos(); + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + let theta = u * std::f32::consts::TAU; + let (st, ct) = theta.sin_cos(); + let nx = sp * st; + let ny = cp; + let nz = sp * ct; + verts.push(Vertex3D { + pos: [nx * radius, ny * radius, nz * radius], + normal: [nx, ny, nz], + uv: [u, v], + }); + } + } + let row = seg_u + 1; + for iv in 0..seg_v { + for iu in 0..seg_u { + let a = iv * row + iu; + let b = (iv + 1) * row + iu; + let c = (iv + 1) * row + iu + 1; + let d = iv * row + iu + 1; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + } + (verts, idx) + } + ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => { + let seg_u = sub_base.clamp(16, 96); + let half_h = height * 0.5; + let a0 = start_sweep_deg.to_radians(); + let a1 = end_sweep_deg.to_radians(); + let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); + let mut idx = Vec::with_capacity((seg_u * 6) as usize); + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc + let theta = a0 + (a1 - a0) * u; + let (st, ct) = theta.sin_cos(); + let nx = ct; + let nz = st; + verts.push(Vertex3D { + pos: [nx * radius, half_h, nz * radius], + normal: [nx, 0.0, nz], + uv: [1.0 - u, 0.0], + }); + verts.push(Vertex3D { + pos: [nx * radius, -half_h, nz * radius], + normal: [nx, 0.0, nz], + uv: [1.0 - u, 1.0], + }); + } + for iu in 0..seg_u { + let a = iu * 2; + let b = a + 1; + let c = a + 3; + let d = a + 2; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + (verts, idx) + } + ShapeKind::Cube { width, height, depth } => { + let hx = width * 0.5; + let hy = height * 0.5; + let hz = depth * 0.5; + let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ + ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), + ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), + ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), + ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), + ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), + ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), + ]; + let mut verts = Vec::with_capacity(24); + let mut idx = Vec::with_capacity(36); + for (n, corners) in faces { + let base = verts.len() as u32; + let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; + for (p, uv) in corners.into_iter().zip(uvs) { + verts.push(Vertex3D { pos: p, normal: n, uv }); + } + idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); + } + (verts, idx) + } + } +} + +/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, +/// `ImagePlane3D`, `Shape3D`, `LightAmbient`, `LightDirectional`). +#[allow(clippy::too_many_arguments)] +pub fn collect_scene( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Mat4, + render_aspect: f32, + cameras: &mut Vec, + meshes: &mut Vec, + lights: &mut SceneLights, + depth: usize, +) { + if depth > 32 { + return; + } + let node = comp.node(node_id); + if node.bypassed { + return; + } + let local = eval_transform3d(comp, node, time, expr); + let world = mat4_mul(parent_xform, local); + + match node.kind.as_str() { + "Merge3D" | "Transform3D" => { + let mut input_names: Vec<&String> = node + .inputs + .keys() + .filter(|k| k.starts_with("SceneInput")) + .collect(); + input_names.sort(); + for in_name in input_names { + if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { + collect_scene(comp, src_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1); + } + } + } + "Camera3D" => { + let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; + let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; + // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). + // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). + let has_aov = node.inputs.contains_key("AoV"); + let has_fl = node.inputs.contains_key("FLength"); + let aov_deg = if has_aov { + comp.eval_number(node, "AoV", time, 24.302, expr) as f32 + } else if has_fl { + let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; + let sensor_h_mm = ap_h * 25.4; + 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() + } else { + 24.302 + }; + let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Inside"); + let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); + + let half_aov = (aov_deg.to_radians() * 0.5).tan(); + let half_v = match gate_fit { + "Height" | "Stretch" => half_aov, + "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)), + "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0), + _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!) + }; + let vfov_rad = 2.0 * half_v.atan(); + let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; + let far = 5000.0_f32; + cameras.push(CameraInstance { world, vfov_rad, near, far }); + } + "LightAmbient" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + lights.ambient[0] += r * inten; + lights.ambient[1] += g * inten; + lights.ambient[2] += b * inten; + } + "LightDirectional" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! + let dx = world[8]; + let dy = world[9]; + let dz = world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + lights.dir_to_light = [dx / len, dy / len, dz / len]; + lights.dir_color = [r * inten, g * inten, b * inten]; + lights.has_dir = true; + } + "ImagePlane3D" => { + let mat_node = node + .connected_node("MaterialInput") + .or_else(|| node.connected_node("SceneInput")) + .and_then(|s| comp.find_node(s)); + let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + meshes.push(MeshInstance { + world, + shape: ShapeKind::ImagePlane, + material_node: tex_node, + diffuse_col, + roughness, + }); + } + "Shape3D" => { + let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); + let shape = match shape_name { + "SurfaceSphereInputs" => ShapeKind::Sphere { + radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 0.5, expr) as f32, + sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, + sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, + }, + "SurfaceCylinderInputs" => { + let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; + let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; + ShapeKind::Cylinder { + radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, + height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, + start_sweep_deg: start_sw, + end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, + sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, + } + } + "SurfaceCubeInputs" => ShapeKind::Cube { + width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, 1.0, expr) as f32, + depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, 1.0, expr) as f32, + }, + _ => ShapeKind::Plane { + width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, + }, + }; + let mat_node = node + .connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)); + let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + meshes.push(MeshInstance { + world, + shape, + material_node: tex_node, + diffuse_col, + roughness, + }); + } + "MacroOperator" | "GroupOperator" => { + if let Some(out_id) = node.macro_output { + collect_scene(comp, out_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1); + } + } + _ => {} + } +} + +/// Resolves a 3D material input (either a 2D image node directly or a Fusion 3D material like +/// `MtlCookTorrance` / `MtlBlinn` / `MtlPhong`) to `(diffuse_2d_node, diffuse_rgba, roughness)`. +fn resolve_material( + comp: &Comp, + mat_node: Option, + time: f64, + expr: &ExprEngine, +) -> (Option, [f32; 4], f32) { + let Some(mid) = mat_node else { + return (None, [1.0, 1.0, 1.0, 1.0], 0.5); + }; + let n = comp.node(mid); + if n.kind.starts_with("Mtl") { + let diff_tex = n + .connected_node("Diffuse.Color.Material") + .or_else(|| n.connected_node("MaterialInput")) + .and_then(|s| comp.find_node(s)); + let col = [ + comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, + ]; + let rough = comp.eval_number(n, "Specular.Roughness", time, 0.5, expr) as f32; + (diff_tex, col, rough) + } else { + (Some(mid), [1.0, 1.0, 1.0, 1.0], 0.5) + } +} + +pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { + let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; + let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; + let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; + + let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); + let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); + let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); + let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); + + let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; + let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; + let sy = if scale_lock { + sx + } else { + comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 + }; + let sz = if scale_lock { + sx + } else { + comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 + }; + + let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; + let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; + let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; + + let mx = mat4_rot_x(rx); + let my = mat4_rot_y(ry); + let mz = mat4_rot_z(rz); + let rot = match rot_order { + "XZY" => mat4_mul(my, mat4_mul(mz, mx)), + "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), + "YZX" => mat4_mul(mx, mat4_mul(mz, my)), + "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), + "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), + _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default + }; + + let t = mat4_translate(tx + px, ty + py, tz + pz); + let s = mat4_scale(sx, sy, sz); + let inv_p = mat4_translate(-px, -py, -pz); + mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) +} + +pub fn mat4_identity() -> Mat4 { + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 { + let mut out = [0.0_f32; 16]; + for col in 0..4 { + for row in 0..4 { + out[col * 4 + row] = a[row] * b[col * 4] + + a[4 + row] * b[col * 4 + 1] + + a[8 + row] * b[col * 4 + 2] + + a[12 + row] * b[col * 4 + 3]; + } + } + out +} + +pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 { + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + x, y, z, 1.0, + ] +} + +pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 { + [ + x, 0.0, 0.0, 0.0, + 0.0, y, 0.0, 0.0, + 0.0, 0.0, z, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_x(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, c, s, 0.0, + 0.0, -s, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_y(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + c, 0.0, -s, 0.0, + 0.0, 1.0, 0.0, 0.0, + s, 0.0, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_z(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + c, s, 0.0, 0.0, + -s, c, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 { + let r00 = m[0]; let r10 = m[1]; let r20 = m[2]; + let r01 = m[4]; let r11 = m[5]; let r21 = m[6]; + let r02 = m[8]; let r12 = m[9]; let r22 = m[10]; + let tx = m[12]; let ty = m[13]; let tz = m[14]; + let itx = -(r00 * tx + r10 * ty + r20 * tz); + let ity = -(r01 * tx + r11 * ty + r21 * tz); + let itz = -(r02 * tx + r12 * ty + r22 * tz); + [ + r00, r01, r02, 0.0, + r10, r11, r12, 0.0, + r20, r21, r22, 0.0, + itx, ity, itz, 1.0, + ] +} + +pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 { + let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5); + let nf = 1.0 / (near - far); + [ + f / aspect.max(1e-4), 0.0, 0.0, 0.0, + 0.0, f, 0.0, 0.0, + 0.0, 0.0, far * nf, -1.0, + 0.0, 0.0, far * near * nf, 0.0, + ] +} diff --git a/crates/engine/src/shaders.wgsl b/crates/engine/src/shaders.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..70576a07ae484c9d627c13c561218ef7173ec3e8 --- /dev/null +++ b/crates/engine/src/shaders.wgsl @@ -0,0 +1,1741 @@ +// Compositor GPU compute shaders (WGSL). +// Coordinate convention: Fusion uses normalized UV (0,0) = bottom-left, (1,1) = top-right, +// whereas textures store row 0 at the top. Helpers `pix_to_fu` / `fu_to_uv` bridge cleanly. + +@group(0) @binding(0) var src_a: texture_2d; +@group(0) @binding(1) var src_b: texture_2d; +@group(0) @binding(2) var mask_tex: texture_2d; +@group(0) @binding(3) var samp_lin: sampler; +@group(0) @binding(4) var dst_tex: texture_storage_2d; + +struct Params { + // 16 vec4 = 256 bytes of uniform parameters per dispatch. + p: array, 16>, +}; +@group(0) @binding(5) var u: Params; + +// Helper: output pixel (gid.xy, top-down) -> Fusion UV (0..1, bottom-up). +fn pix_to_fu(gid: vec2, dims: vec2) -> vec2 { + let f = vec2(dims); + return vec2((f32(gid.x) + 0.5) / f.x, 1.0 - (f32(gid.y) + 0.5) / f.y); +} + +// Helper: Fusion UV (bottom-up) -> texture UV (top-down). +fn fu_to_uv(fu: vec2) -> vec2 { + return vec2(fu.x, 1.0 - fu.y); +} + +fn sample_tex(tex: texture_2d, uv: vec2, nearest: bool) -> vec4 { + if (nearest) { + let isdims = vec2(textureDimensions(tex)); + let sx = clamp(i32(floor(uv.x * f32(isdims.x))), 0, isdims.x - 1); + let sy = clamp(i32(floor(uv.y * f32(isdims.y))), 0, isdims.y - 1); + return textureLoad(tex, vec2(sx, sy), 0); + } + return textureSampleLevel(tex, samp_lin, uv, 0.0); +} + +// Helper: Sample texture with Fusion Edges mode: 0=Canvas, 1=Wrap, 2=Duplicate, 3=Mirror. +// When `dod` (`origin_x, origin_y, canvas_w, canvas_h`) has `canvas_w > 0.5`, maps `fu` +// (normalized to `canvas`) into the texture's expanded Domain of Definition! +fn sample_dod_edges_mode(tex: texture_2d, fu: vec2, edges: i32, dod: vec4, nearest: bool) -> vec4 { + var uv: vec2; + if (dod.z > 0.5 && dod.w > 0.5) { + let tdims = vec2(textureDimensions(tex)); + let canvas_px = vec2(fu.x * dod.z, (1.0 - fu.y) * dod.w); + uv = (canvas_px - dod.xy) / tdims; + } else { + uv = fu_to_uv(fu); + } + if (edges == 0) { + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + return vec4(0.0); + } + return sample_tex(tex, uv, nearest); + } else if (edges == 1) { + uv = fract(uv); + return sample_tex(tex, uv, nearest); + } else if (edges == 2) { + uv = clamp(uv, vec2(0.0), vec2(1.0)); + return sample_tex(tex, uv, nearest); + } else { + let m = abs(fract(uv * 0.5 + 0.5) * 2.0 - 1.0); + return sample_tex(tex, m, nearest); + } +} + +fn sample_dod_edges(tex: texture_2d, fu: vec2, edges: i32, dod: vec4) -> vec4 { + return sample_dod_edges_mode(tex, fu, edges, dod, false); +} + +fn sample_edges(tex: texture_2d, fu: vec2, edges: i32) -> vec4 { + return sample_dod_edges(tex, fu, edges, vec4(0.0)); +} + +fn read_mask(gid: vec2, dims: vec2, has_mask: f32, invert: f32) -> f32 { + if (has_mask < 0.5) { + return 1.0; + } + let uv = (vec2(gid) + 0.5) / vec2(dims); + let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + return select(m, 1.0 - m, invert > 0.5); +} + +// ============================================================================ +// 1. Background (Solid + Gradients) +// p[0] = top_left rgba, p[1] = top_right rgba, p[2] = bottom_left rgba, p[3] = bottom_right rgba +// p[4] = (type: 0=Solid, 1=Horiz, 2=Vert, 3=FourCorner, 4=Gradient, 5=Radial, sub_type, start_x, start_y) +// p[5] = (end_x, end_y, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn bg_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fu = pix_to_fu(gid.xy, dims); + let kind = i32(u.p[4].x + 0.5); + var col = u.p[0]; + if (kind == 1) { + col = mix(u.p[0], u.p[1], fu.x); + } else if (kind == 2) { + col = mix(u.p[2], u.p[0], fu.y); + } else if (kind == 3) { + let top = mix(u.p[0], u.p[1], fu.x); + let bot = mix(u.p[2], u.p[3], fu.x); + col = mix(bot, top, fu.y); + } else if (kind == 4 || kind == 5) { + let s = u.p[4].zw; + let e = u.p[5].xy; + let d = e - s; + var t = 0.0; + if (kind == 5) { + let r = max(length(d), 1e-5); + t = clamp(length(fu - s) / r, 0.0, 1.0); + } else { + let len2 = max(dot(d, d), 1e-6); + t = clamp(dot(fu - s, d) / len2, 0.0, 1.0); + } + col = mix(u.p[0], u.p[1], t); + } + let m = read_mask(gid.xy, dims, u.p[5].z, u.p[5].w); + col = col * m; + // Output premultiplied RGBA + let out_col = vec4(col.rgb * col.a, col.a); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 2. Merge (Transform FG + ApplyMode + Gain + Blend + Mask) +// p[0] = (center.x, center.y, size, angle_rad) +// p[1] = (blend, gain, apply_mode_id, edges_mode) +// p[2] = (flip_h, flip_v, fg_aspect, bg_aspect) +// p[3] = (has_mask, mask_invert, fg_w, fg_h) +// ============================================================================ +fn blend_lum(c: vec3) -> f32 { + return dot(c, vec3(0.299, 0.587, 0.114)); +} + +fn clip_color(col_in: vec3) -> vec3 { + var c = col_in; + let l = blend_lum(c); + let n = min(c.r, min(c.g, c.b)); + let x = max(c.r, max(c.g, c.b)); + if (n < 0.0) { + c = vec3(l) + ((c - vec3(l)) * l) / max(l - n, 1e-5); + } + if (x > 1.0) { + c = vec3(l) + ((c - vec3(l)) * (1.0 - l)) / max(x - l, 1e-5); + } + return c; +} + +fn set_lum(c: vec3, l: f32) -> vec3 { + let d = l - blend_lum(c); + return clip_color(c + vec3(d)); +} + +fn sat_val(c: vec3) -> f32 { + return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); +} + +fn set_sat(c_in: vec3, s: f32) -> vec3 { + let mn = min(c_in.r, min(c_in.g, c_in.b)); + let mx = max(c_in.r, max(c_in.g, c_in.b)); + let span = mx - mn; + if (span <= 1e-5) { + return vec3(0.0); + } + return (c_in - vec3(mn)) * (s / span); +} + +fn apply_blend_mode(bg: vec3, fg: vec3, mode: i32) -> vec3 { + switch mode { + case 1: { // Screen + return 1.0 - (1.0 - bg) * (1.0 - fg); + } + case 2: { // Multiply + return bg * fg; + } + case 3: { // Darken + return min(bg, fg); + } + case 4: { // Lighten + return max(bg, fg); + } + case 5: { // Difference + return abs(bg - fg); + } + case 6: { // Exclusion + return bg + fg - 2.0 * bg * fg; + } + case 7: { // Overlay + let lo = 2.0 * bg * fg; + let hi = 1.0 - 2.0 * (1.0 - bg) * (1.0 - fg); + return select(hi, lo, bg < vec3(0.5)); + } + case 8: { // Hard Light + let lo = 2.0 * bg * fg; + let hi = 1.0 - 2.0 * (1.0 - bg) * (1.0 - fg); + return select(hi, lo, fg < vec3(0.5)); + } + case 9: { // Soft Light (W3C / Photoshop / Fusion exact) + let d_lo = ((16.0 * bg - 12.0) * bg + 4.0) * bg; + let d_hi = sqrt(max(bg, vec3(0.0))); + let d = select(d_hi, d_lo, bg <= vec3(0.25)); + let lo = bg - (1.0 - 2.0 * fg) * bg * (1.0 - bg); + let hi = bg + (2.0 * fg - 1.0) * (d - bg); + return select(hi, lo, fg <= vec3(0.5)); + } + case 10: { // Linear Light + return clamp(bg + 2.0 * fg - 1.0, vec3(0.0), vec3(1.0)); + } + case 11: { // Color Dodge + return clamp(bg / max(1.0 - fg, vec3(1e-4)), vec3(0.0), vec3(1.0)); + } + case 12: { // Linear Dodge / Add + return clamp(bg + fg, vec3(0.0), vec3(1.0)); + } + case 13: { // Vivid Light + let burn = 1.0 - (1.0 - bg) / max(2.0 * fg, vec3(1e-4)); + let dodge = bg / max(2.0 * (1.0 - fg), vec3(1e-4)); + return clamp(select(dodge, burn, fg < vec3(0.5)), vec3(0.0), vec3(1.0)); + } + case 14: { // Hypotenuse + return clamp(sqrt(bg * bg + fg * fg), vec3(0.0), vec3(1.0)); + } + case 15: { // Darker Color (Fusion compares Rec.601 luma, picks darker pixel whole) + let l_fg = dot(fg, vec3(0.299, 0.587, 0.114)); + let l_bg = dot(bg, vec3(0.299, 0.587, 0.114)); + return select(bg, fg, l_fg < l_bg); + } + case 16: { // Lighter Color (Fusion compares Rec.601 luma, picks lighter pixel whole) + let l_fg = dot(fg, vec3(0.299, 0.587, 0.114)); + let l_bg = dot(bg, vec3(0.299, 0.587, 0.114)); + return select(bg, fg, l_fg > l_bg); + } + case 17: { // Pin Light + let lo = min(bg, 2.0 * fg); + let hi = max(bg, 2.0 * fg - 1.0); + return select(hi, lo, fg < vec3(0.5)); + } + case 18: { // Color Burn + return 1.0 - clamp((1.0 - bg) / max(fg, vec3(1e-4)), vec3(0.0), vec3(1.0)); + } + case 19: { // Linear Burn + return clamp(bg + fg - 1.0, vec3(0.0), vec3(1.0)); + } + case 20: { // Geometric + return (2.0 * fg * bg) / max(fg + bg, vec3(1e-5)); + } + case 21: { // Hue + return set_lum(set_sat(fg, sat_val(bg)), blend_lum(bg)); + } + case 22: { // Saturation + return set_lum(set_sat(bg, sat_val(fg)), blend_lum(bg)); + } + case 23: { // Color + return set_lum(fg, blend_lum(bg)); + } + case 24: { // Luminosity + return set_lum(bg, blend_lum(fg)); + } + default: { // 0: Normal + return fg; + } + } +} + +@compute @workgroup_size(8, 8) +fn merge_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let bg_dod = u.p[5]; + let has_bg_dod = bg_dod.z > 0.5 && bg_dod.w > 0.5; + let bg_dims = select(vec2(dims), bg_dod.zw, has_bg_dod); + let fg_dims = max(u.p[3].zw, vec2(1.0)); + + let bg = textureLoad(src_a, vec2(gid.xy), 0); + // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV! + let canvas_px = select( + vec2(gid.xy) + vec2(0.5), + vec2(gid.xy) + vec2(0.5) + bg_dod.xy, + has_bg_dod, + ); + let fu = vec2(canvas_px.x / bg_dims.x, 1.0 - canvas_px.y / bg_dims.y); + + let center = u.p[0].xy; + let size = max(u.p[0].z, 1e-5); + let angle = u.p[0].w; + let blend = u.p[1].x; + let gain = u.p[1].y; + let mode = i32(u.p[1].z + 0.5); + let edges = i32(u.p[1].w + 0.5); + let nearest = u.p[2].z > 0.5; + + // Map output pixel in Fusion pixel space relative to Center into FG pixel space. + let delta_px = (fu - center) * bg_dims; + let c = cos(angle); + let s = sin(angle); + // Fusion Angle rotates CCW in Y-up, so inverse rotates CW: + let rot_px = vec2(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size; + var fg_fu = rot_px / fg_dims + vec2(0.5); + if (u.p[2].x > 0.5) { fg_fu.x = 1.0 - fg_fu.x; } + if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; } + + let fg = sample_dod_edges_mode(src_b, fg_fu, edges, u.p[4], nearest); + let mask = read_mask(gid.xy, dims, u.p[3].x, u.p[3].y); + let eff_blend = clamp(blend * mask, 0.0, 1.0); + let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr + + let burn_in = u.p[6].x; + + var out_col: vec4; + if (mode == 0) { + let fg_occ = fg.a * gain * (1.0 - burn_in); + var comp: vec4; + if (op == 1) { + // Under: FG behind BG + let bg_occ = bg.a; + comp = vec4(bg.rgb + fg.rgb * (1.0 - bg_occ), bg.a + fg.a * (1.0 - bg_occ)); + } else if (op == 2) { + // In: FG masked by BG alpha + comp = fg * bg.a; + } else if (op == 3) { + // HeldOut: BG masked by (1 - FG alpha) + comp = bg * (1.0 - fg_occ); + } else if (op == 4) { + // Atop: FG inside BG + BG outside FG + comp = vec4(fg.rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a); + } else if (op == 5) { + // XOr + comp = fg * (1.0 - bg.a) + bg * (1.0 - fg_occ); + } else { + // Over (default) with Fusion Alpha Gain, Subtractive/Additive, and BurnIn + let over_rgb = fg.rgb + bg.rgb * (1.0 - fg_occ); + let over_a = fg.a * gain + bg.a * (1.0 - fg.a * gain); + comp = vec4(over_rgb, over_a); + } + out_col = mix(bg, comp, eff_blend); + } else if (mode == 15 || mode == 16) { + // Fusion DarkerColor/LighterColor with AlphaGain: candidate is FG + BG*(1 - fg.a*gain), + // compared against BG by Rec.601 luma! (Verified bit-exact on probe_merge f09 & f10!) + let fg_a_eff = fg.a * gain; + let bg_u = select(vec3(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5); + let fg_u = select(vec3(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5); + let cand = fg_u + bg_u * (1.0 - fg_a_eff); + let blended = apply_blend_mode(bg_u, cand, mode); + let comp_rgb = bg.a * fg.a * blended + fg.rgb * (1.0 - bg.a) + (1.0 - fg.a) * bg.rgb; + let comp_a = bg.a + fg_a_eff * (1.0 - bg.a); + out_col = mix(bg, vec4(comp_rgb, comp_a), eff_blend); + } else { + let bg_u = select(vec3(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5); + let fg_u = select(vec3(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5); + // In Fusion's special fill-opacity modes (Difference, Exclusion, Screen, LinearDodge), + // Gain scales FG color intensity BEFORE blending (e.g. Difference = |bg - gain*fg|!). + let scale_fg_rgb = (mode == 5 || mode == 6 || mode == 1 || mode == 12); + let fg_blend_in = select(fg_u, fg_u * gain, scale_fg_rgb); + let blended = apply_blend_mode(bg_u, fg_blend_in, mode); + let fg_eff = select(fg.a * gain, fg.a, scale_fg_rgb); + let comp_rgb = fg_eff * bg.a * blended + fg_eff * (1.0 - bg.a) * fg_blend_in + (1.0 - fg_eff) * bg.rgb; + let comp_a = bg.a + fg_eff * (1.0 - bg.a); + out_col = mix(bg, vec4(comp_rgb, comp_a), eff_blend); + } + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 3. Transform +// p[0] = (center.x, center.y, pivot.x, pivot.y) +// p[1] = (size_x, size_y, angle_rad, edges) +// p[2] = (flip_h, flip_v, blend, has_mask) +// p[3] = (mask_invert, 0, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn transform_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fdims = vec2(dims); + let fu = pix_to_fu(gid.xy, dims); + + let center = u.p[0].xy; + let pivot = u.p[0].zw; + let sx = max(u.p[1].x, 1e-5); + let sy = max(u.p[1].y, 1e-5); + let angle = u.p[1].z; + let edges = i32(u.p[1].w + 0.5); + + // Forward in Fusion: p' = R(angle) * S(sx, sy) * (p - pivot) + pivot + (center - 0.5) + let shift = center - vec2(0.5); + let rel_px = (fu - pivot - shift) * fdims; + let c = cos(angle); + let s = sin(angle); + let unrot = vec2(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c); + var src_fu = vec2(unrot.x / sx, unrot.y / sy) / fdims + pivot; + if (u.p[2].x > 0.5) { src_fu.x = 1.0 - src_fu.x; } + if (u.p[2].y > 0.5) { src_fu.y = 1.0 - src_fu.y; } + + let nearest = u.p[3].y > 0.5; + let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest); + let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest); + let m = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x) * u.p[2].z; + let out_col = mix(orig, moved, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 4. BrightnessContrast +// p[0] = (gain, lift, gamma, contrast) +// p[1] = (brightness, saturation, prediv, blend) +// p[2] = (has_mask, mask_invert, low, high) +// p[3] = (proc_r, proc_g, proc_b, proc_a) +// ============================================================================ +fn bc_curve_scalar(v_in: f32, low: f32, high: f32, gain: f32, lift: f32, gamma: f32, contrast: f32, brightness: f32) -> f32 { + var v = v_in; + if (abs(low) > 1e-5 || abs(high - 1.0) > 1e-5) { + let span = max(high - low, 1e-5); + v = (v - low) / span; + } + v = v * (gain - lift) + lift; + v = pow(max(v, 0.0), 1.0 / gamma); + v = (v - 0.5) * (1.0 + contrast) + 0.5; + v = v + brightness; + return v; +} + +@compute @workgroup_size(8, 8) +fn bc_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let gain = u.p[0].x; + let lift = u.p[0].y; + let gamma = max(u.p[0].z, 1e-4); + let contrast = u.p[0].w; + let brightness = u.p[1].x; + let sat = u.p[1].y; + let prediv = u.p[1].z > 0.5; + let low = u.p[2].z; + let high = u.p[2].w; + let proc_r = u.p[3].x > 0.5; + let proc_g = u.p[3].y > 0.5; + let proc_b = u.p[3].z > 0.5; + let proc_a = u.p[3].w > 0.5; + + var rgb = src.rgb; + if (prediv && src.a > 1e-5) { + rgb = rgb / src.a; + } + + var adj_rgb = vec3( + bc_curve_scalar(rgb.r, low, high, gain, lift, gamma, contrast, brightness), + bc_curve_scalar(rgb.g, low, high, gain, lift, gamma, contrast, brightness), + bc_curve_scalar(rgb.b, low, high, gain, lift, gamma, contrast, brightness), + ); + let luma = dot(adj_rgb, vec3(0.299, 0.587, 0.114)); + adj_rgb = mix(vec3(luma), adj_rgb, sat); + + let out_rgb_unpre = vec3( + select(rgb.r, adj_rgb.r, proc_r), + select(rgb.g, adj_rgb.g, proc_g), + select(rgb.b, adj_rgb.b, proc_b), + ); + let out_a = select(src.a, clamp(bc_curve_scalar(src.a, low, high, gain, lift, gamma, contrast, brightness), 0.0, 1.0), proc_a); + let out_rgb = select(out_rgb_unpre, out_rgb_unpre * out_a, prediv); + let adjusted = vec4(out_rgb, out_a); + let m = read_mask(gid.xy, dims, u.p[2].x, u.p[2].y) * u.p[1].w; + let out_col = mix(src, adjusted, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 5. ColorCorrector (Lightness-preserving hue rotation + saturation + tint + LGG + contrast) +// p[0] = (hue_turns, sat, tint_angle_rad, tint_len) +// p[1] = (gain, lift, gamma, contrast) +// p[2] = (brightness, prediv, blend, has_mask) +// p[3] = (mask_invert, 0, 0, 0) +// ============================================================================ +fn rotate_hue_preserve_luma(c: vec3, angle: f32) -> vec3 { + // Paul Haeberli luminance-preserving shear-rotate-unshear around (1,1,1) with Rec.601 weights. + // Verified 0.00/255 bit-exact against Fusion Studio 21.1 ColorCorrector! + let k = vec3(0.299, 0.587, 0.114); + let y = dot(c, k); + let ch = c - vec3(y); + let ca = cos(angle); + let sa = sin(angle); + let s3 = 0.5773502691896258; // 1 / sqrt(3) + let ndv = (ch.r + ch.g + ch.b) * (1.0 / 3.0); + let nxv = vec3(ch.g - ch.b, ch.b - ch.r, ch.r - ch.g) * s3; + let v = ch * ca + nxv * sa + vec3(ndv * (1.0 - ca)); + let dy = dot(v, k); + return vec3(y) + v - vec3(dy); +} + +fn hsv_pure_hue(h_turns: f32) -> vec3 { + let h = fract(h_turns) * 6.0; + let r = clamp(abs(h - 3.0) - 1.0, 0.0, 1.0); + let g = clamp(2.0 - abs(h - 2.0), 0.0, 1.0); + let b = clamp(2.0 - abs(h - 4.0), 0.0, 1.0); + return vec3(r, g, b); +} + +@compute @workgroup_size(8, 8) +fn cc_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let hue_turns = u.p[0].x; + let sat = u.p[0].y; + let tint_turns = u.p[0].z; + let tint_len = u.p[0].w; + let gain = u.p[1].x; + let lift = u.p[1].y; + let gamma = max(u.p[1].z, 1e-4); + let contrast = u.p[1].w; + let brightness = u.p[2].x; + let prediv = u.p[2].y > 0.5; + let k_luma = vec3(0.299, 0.587, 0.114); + + var rgb = src.rgb; + if (prediv && src.a > 1e-5) { + rgb = rgb / src.a; + } + + // 1. Hue rotation (verified 0.00/255 vs Fusion 21.1: +turns rotates Red -> Yellow -> Green -> Cyan -> Blue -> Magenta) + if (abs(hue_turns) > 1e-5) { + rgb = rotate_hue_preserve_luma(rgb, -hue_turns * 6.28318530718); + } + + // 2. Fusion Color Wheel Tint (verified 0.00/255 vs Fusion 21.1: lerp toward pure HSV chroma * 2*min(Y, 1-Y)) + if (tint_len > 1e-5) { + let y_t = dot(rgb, k_luma); + let pure = hsv_pure_hue(tint_turns); + let pure_y = dot(pure, k_luma); + let tc = pure - vec3(pure_y); + let y_clamped = clamp(y_t, 0.0, 1.0); + let amp = 2.0 * min(y_clamped, 1.0 - y_clamped); + let tint_rgb = vec3(y_t) + tc * amp; + rgb = mix(rgb, tint_rgb, clamp(tint_len, 0.0, 1.0)); + } + + // 3. Saturation (Rec.601 luma, no gamut crushing — verified 0.00/255 at sat=0, 1.6, 3.0, 6.0!) + let luma = dot(rgb, k_luma); + rgb = mix(vec3(luma), rgb, sat); + + // 4. Contrast -> Lift/Gain -> Brightness -> Gamma (verified 0.00/255 vs Fusion 21.1!) + rgb = (rgb - 0.5) * contrast + 0.5; + rgb = rgb * (gain - lift) + lift; + rgb = rgb + brightness; + rgb = pow(max(rgb, vec3(0.0)), vec3(1.0 / gamma)); + + if (prediv) { + rgb = rgb * src.a; + } + let m = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x) * u.p[2].z; + let out_col = mix(src, vec4(rgb, src.a), clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 6. LumaKeyer +// p[0] = (low, high, invert, blend) +// p[1] = (has_mask, mask_invert, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn luma_key_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let low = u.p[0].x; + let high = u.p[0].y; + let invert = u.p[0].z > 0.5; + let rgb = select(vec3(0.0), src.rgb / max(src.a, 1e-5), src.a > 1e-5); + let luma = dot(rgb, vec3(0.299, 0.587, 0.114)); + var a = clamp((luma - low) / max(high - low, 1e-5), 0.0, 1.0); + if (invert) { + a = 1.0 - a; + } + let out_a = a * src.a; + let keyed = vec4(rgb * out_a, out_a); + let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * u.p[0].w; + let out_col = mix(src, keyed, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 7. Separable Gaussian / Box Blur & Directional Blur +// p[0] = (dir.x, dir.y, radius_px, mode: 0=gauss, 1=box, 2=erode, 3=dilate) +// p[1] = (blend, has_mask, mask_invert, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn blur_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fdims = vec2(dims); + let uv = (vec2(gid.xy) + 0.5) / fdims; + let dir = u.p[0].xy / fdims; + let radius = u.p[0].z; + let mode = i32(u.p[0].w + 0.5); + + if (radius < 0.25) { + textureStore(dst_tex, vec2(gid.xy), textureLoad(src_a, vec2(gid.xy), 0)); + return; + } + + let taps = clamp(i32(ceil(radius)), 1, 64); + let step_scale = radius / f32(taps); + + var acc = vec4(0.0); + var wsum = 0.0; + + let clamp_edges = u.p[1].w > 0.5; + if (mode == 2 || mode == 3) { + // Erode (min) / Dilate (max) + acc = textureLoad(src_a, vec2(gid.xy), 0); + for (var i = -taps; i <= taps; i = i + 1) { + let s = textureSampleLevel(src_a, samp_lin, clamp(uv + dir * (f32(i) * step_scale), vec2(0.0), vec2(1.0)), 0.0); + acc = select(max(acc, s), min(acc, s), mode == 2); + } + } else if (mode == 1) { + // Box blur + for (var i = -taps; i <= taps; i = i + 1) { + let off = uv + dir * (f32(i) * step_scale); + let s = select( + select(vec4(0.0), textureSampleLevel(src_a, samp_lin, off, 0.0), off.x >= 0.0 && off.x <= 1.0 && off.y >= 0.0 && off.y <= 1.0), + textureSampleLevel(src_a, samp_lin, clamp(off, vec2(0.0), vec2(1.0)), 0.0), + clamp_edges, + ); + acc = acc + s; + wsum = wsum + 1.0; + } + acc = acc / max(wsum, 1.0); + } else { + // Gaussian blur + let sigma = max(radius * 0.45, 0.5); + let inv2s2 = 0.5 / (sigma * sigma); + for (var i = -taps; i <= taps; i = i + 1) { + let d = f32(i) * step_scale; + let w = exp(-d * d * inv2s2); + let off = uv + dir * d; + let s = select( + select(vec4(0.0), textureSampleLevel(src_a, samp_lin, off, 0.0), off.x >= 0.0 && off.x <= 1.0 && off.y >= 0.0 && off.y <= 1.0), + textureSampleLevel(src_a, samp_lin, clamp(off, vec2(0.0), vec2(1.0)), 0.0), + clamp_edges, + ); + acc = acc + s * w; + wsum = wsum + w; + } + acc = acc / max(wsum, 1e-6); + } + + let orig = select( + textureLoad(src_a, vec2(gid.xy), 0), + textureLoad(src_b, vec2(gid.xy), 0), + u.p[2].x > 0.5, + ); + let m = read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x; + let out_col = mix(orig, acc, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 8. FastNoise (2D FBM value/gradient noise with Seethe & Discontinuous) +// p[0] = (x_scale, y_scale, detail, contrast) +// p[1] = (brightness, seethe, discontinuous, center_x) +// p[2] = (center_y, angle, inverted, 0) +// p[3] = color1 rgba, p[4] = color2 rgba +// ============================================================================ +fn hash3(p: vec3) -> f32 { + var q = fract(p * vec3(0.1031, 0.1030, 0.0973)); + q = q + dot(q, q.yxz + 33.33); + return fract((q.x + q.y) * q.z); +} + +fn noise3d(p: vec3) -> f32 { + let i = floor(p); + let f = fract(p); + let u_f = f * f * (3.0 - 2.0 * f); + let n000 = hash3(i + vec3(0.0, 0.0, 0.0)); + let n100 = hash3(i + vec3(1.0, 0.0, 0.0)); + let n010 = hash3(i + vec3(0.0, 1.0, 0.0)); + let n110 = hash3(i + vec3(1.0, 1.0, 0.0)); + let n001 = hash3(i + vec3(0.0, 0.0, 1.0)); + let n101 = hash3(i + vec3(1.0, 0.0, 1.0)); + let n011 = hash3(i + vec3(0.0, 1.0, 1.0)); + let n111 = hash3(i + vec3(1.0, 1.0, 1.0)); + let nx00 = mix(n000, n100, u_f.x); + let nx10 = mix(n010, n110, u_f.x); + let nx01 = mix(n001, n101, u_f.x); + let nx11 = mix(n011, n111, u_f.x); + let nxy0 = mix(nx00, nx10, u_f.y); + let nxy1 = mix(nx01, nx11, u_f.y); + return mix(nxy0, nxy1, u_f.z) * 2.0 - 1.0; +} + +@compute @workgroup_size(8, 8) +fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + let center = vec2(u.p[1].w, u.p[2].x); + let scale = u.p[0].xy; + let detail = clamp(u.p[0].z, 1.0, 10.0); + let contrast = u.p[0].w; + let brightness = u.p[1].x; + let seethe = u.p[1].y; + let disc = u.p[1].z > 0.5; + + var p = (fu - center) * vec2(aspect, 1.0) * scale; + let octaves = i32(ceil(detail)); + var sum = 0.0; + var amp = 0.5; + var freq = 1.0; + var norm = 0.0; + for (var i = 0; i < 10; i = i + 1) { + if (i >= octaves) { break; } + let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4); + var n = noise3d(vec3(p * freq, seethe * 0.37 + f32(i) * 1.7)); + if (disc) { n = abs(n) * 2.0 - 1.0; } + sum = sum + n * weight; + norm = norm + weight; + freq = freq * 2.0; + amp = amp * 0.5; + } + // Fusion FastNoise uses Perlin-scale FBM (~0.26 amplitude) so sharp high-threshold gradients (e.g. 0.95..0.96) + // isolate sparse pinpoint peaks rather than flooding 15% of the frame! + var val = (sum / max(norm, 1e-4)) * 0.26 * contrast + 0.5 + brightness; + val = clamp(val, 0.0, 1.0); + if (u.p[2].z > 0.5) { val = 1.0 - val; } + var col: vec4; + if (u.p[2].w > 0.5) { + // High-precision 256x1 gradient LUT in src_b (supports razor-sharp thresholds like starfields!) + col = textureSampleLevel(src_b, samp_lin, vec2(val, 0.5), 0.0); + } else { + let lut_pos = val * 12.0; + let i0 = u32(clamp(floor(lut_pos), 0.0, 11.0)); + let f = lut_pos - f32(i0); + col = mix(u.p[3u + i0], u.p[4u + i0], f); + } + let out_col = vec4(col.rgb * col.a, col.a); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 9. Displace (Type 0 = Radial/Bump with Spread RGB dispersion & LightPower, Type 1 = XY Refraction) +// p[0] = (type, x_ref, y_ref, x_off) +// p[1] = (y_off, ref_strength, blend, has_mask) +// p[2] = (mask_invert, spread, light_power, offset) +// p[3] = (center.x, center.y, 0, 0) +// ============================================================================ +fn pick_channel(c: vec4, ch: i32) -> f32 { + switch ch { + case 0: { return c.r; } + case 1: { return c.g; } + case 2: { return c.b; } + case 3: { return c.a; } + default: { return dot(c.rgb, vec3(0.299, 0.587, 0.114)); } + } +} + +@compute @workgroup_size(8, 8) +fn displace_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fdims = vec2(dims); + let fu = pix_to_fu(gid.xy, dims); + let uv = fu_to_uv(fu); + let kind = i32(u.p[0].x + 0.5); + let orig = textureLoad(src_a, vec2(gid.xy), 0); + + var warped: vec4; + if (kind == 1) { + // XY Refraction: Fusion formula is `(fg[channel] + offset) * refraction` with clamped (Duplicate) edges! + let fg = textureSampleLevel(src_b, samp_lin, uv, 0.0); + let xch = i32(u.p[3].z + 0.5); + let ych = i32(u.p[3].w + 0.5); + let vx = pick_channel(fg, xch); + let vy = pick_channel(fg, ych); + let disp = vec2( + (vx + u.p[0].w) * u.p[0].y, + (vy + u.p[1].x) * u.p[0].z, + ); + warped = sample_edges(src_a, fu + disp, 2); + } else { + // Radial displace: Fusion shifts radially from Center by -(fu - center) * (luma + offset) * strength * 0.51. + let fg_c = textureSampleLevel(src_b, samp_lin, uv, 0.0); + let l_c = dot(fg_c.rgb, vec3(0.299, 0.587, 0.114)); + let offset = u.p[2].w; + let strength = u.p[1].y; + let spread = u.p[2].y; + let light_power = u.p[2].z; + let center = u.p[3].xy; + let dir_c = fu - center; + let base_disp = -dir_c * (l_c + offset) * strength * 0.51; + + if (abs(spread) > 1e-4) { + let sp = spread * 0.02; + let sr = sample_edges(src_a, fu + base_disp * (1.0 - sp), 2); + let sg = sample_edges(src_a, fu + base_disp, 2); + let sb = sample_edges(src_a, fu + base_disp * (1.0 + sp), 2); + warped = vec4(sr.r, sg.g, sb.b, max(sr.a, max(sg.a, sb.a))); + } else { + warped = sample_edges(src_a, fu + base_disp, 2); + } + + if (light_power > 1e-4) { + let dx = 1.0 / fdims.x; + let dy = 1.0 / fdims.y; + let lx0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2(dx, 0.0), vec2(0.0), vec2(1.0)), 0.0).rgb, vec3(0.299, 0.587, 0.114)); + let lx1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2(dx, 0.0), vec2(0.0), vec2(1.0)), 0.0).rgb, vec3(0.299, 0.587, 0.114)); + let ly0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2(0.0, dy), vec2(0.0), vec2(1.0)), 0.0).rgb, vec3(0.299, 0.587, 0.114)); + let ly1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2(0.0, dy), vec2(0.0), vec2(1.0)), 0.0).rgb, vec3(0.299, 0.587, 0.114)); + let grad = vec2(lx1 - lx0, ly0 - ly1); + let shade = clamp(1.0 + dot(grad, vec2(0.707, 0.707)) * light_power * 1.2, 0.0, 2.0); + warped = vec4(warped.rgb * shade, warped.a); + } + } + + let m = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * u.p[1].z; + let out_col = mix(orig, warped, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 10. Mask Shapes (EllipseMask & RectangleMask) + Mask Combine / Apply +// p[0] = (center.x, center.y, width, height) +// p[1] = (angle_rad, soft_edge, corner_radius, invert) +// p[2] = (shape: 0=Ellipse, 1=Rect, level, has_prev_mask, paint_mode) +// paint_mode: 0=Merge, 1=Add, 2=Subtract, 3=Multiply, 4=Min, 5=Max, 6=Invert, 7=Replace +// ============================================================================ +fn combine_mask_val(prev: f32, cur: f32, mode: i32) -> f32 { + if (mode == 1) { return clamp(prev + cur, 0.0, 1.0); } // Add + if (mode == 2) { return clamp(prev - cur, 0.0, 1.0); } // Subtract + if (mode == 3) { return prev * cur; } // Multiply + if (mode == 4) { return min(prev, cur); } // Minimum + if (mode == 5) { return max(prev, cur); } // Maximum + if (mode == 6) { return abs(prev - cur); } // Invert + if (mode == 7) { return cur; } // Replace + return clamp(prev + cur * (1.0 - prev), 0.0, 1.0); // Merge (default) +} + +@compute @workgroup_size(8, 8) +fn mask_shape_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + + let center = u.p[0].xy; + let half_sz = max(u.p[0].zw * 0.5, vec2(1e-5)); + let angle = u.p[1].x; + let soft = max(u.p[1].y, 1.0 / max(f32(dims.x), 1.0)); + let radius = u.p[1].z; + let invert = u.p[1].w > 0.5; + let shape = i32(u.p[2].x + 0.5); + let level = u.p[2].y; + let has_prev = u.p[2].z > 0.5; + let paint_mode = i32(u.p[2].w + 0.5); + + // Work in isotropic frame-width units (1.0 = canvas width) so rotations & circles are exact! + let rel_w = (fu - center) * vec2(1.0, 1.0 / aspect); + let c = cos(angle); + let s = sin(angle); + let p_w = vec2(rel_w.x * c + rel_w.y * s, -rel_w.x * s + rel_w.y * c); + + var dist: f32; + if (shape == 0) { + // Fusion EllipseMask: BOTH Width and Height are in frame-width units (Width == Height -> circle)! + let q = p_w / half_sz; + let grad_len = max(length(q / half_sz), 1e-5); + dist = (length(q) - 1.0) * (length(q) / grad_len); + } else { + // Fusion RectangleMask: Width is in frame-width units, Height is in frame-height units! + let h_w = vec2(half_sz.x, half_sz.y / aspect); + // CornerRadius in Fusion is 0..1 fraction of the shorter half-dimension. + let r_w = clamp(radius, 0.0, 1.0) * min(h_w.x, h_w.y); + let q = abs(p_w) - (h_w - vec2(r_w)); + dist = length(max(q, vec2(0.0))) + min(max(q.x, q.y), 0.0) - r_w; + } + + var a = 1.0 - smoothstep(-soft, soft, dist); + if (invert) { a = 1.0 - a; } + a = clamp(a * level, 0.0, 1.0); + if (has_prev) { + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let prev = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + a = combine_mask_val(prev, a, paint_mode); + } + textureStore(dst_tex, vec2(gid.xy), vec4(a, a, a, a)); +} + +@compute @workgroup_size(8, 8) +fn mask_combine_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let paint_mode = i32(u.p[0].x + 0.5); + let invert = u.p[0].y > 0.5; + let level = select(1.0, u.p[0].z, u.p[0].z > -0.5); + let has_prev = u.p[0].w > 0.5; + var cur = textureLoad(src_a, vec2(gid.xy), 0).a; + if (invert) { cur = 1.0 - cur; } + cur = clamp(cur * level, 0.0, 1.0); + var a = cur; + if (has_prev) { + let prev = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + a = combine_mask_val(prev, cur, paint_mode); + } + textureStore(dst_tex, vec2(gid.xy), vec4(a, a, a, a)); +} + +@compute @workgroup_size(8, 8) +fn mask_apply_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let m = read_mask(gid.xy, dims, 1.0, u.p[0].x); + textureStore(dst_tex, vec2(gid.xy), src * m); +} + +// ============================================================================ +// 11. Fuse.Colorize (Clover's exact 2020 Colorize.fuse formula!) +// p[0] = (r1, g1, b1, a1), p[1] = (r2, g2, b2, a2), p[2] = (blend, has_mask, mask_invert, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn colorize_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let c1 = u.p[0]; + let c2 = u.p[1]; + + let ab = src.a; + let aa = c1.a + ab * (c2.a - c1.a); + let unpre = select(vec3(0.0), src.rgb / ab, ab > 1e-6); + let out_rgb = (c1.rgb + unpre * (c2.rgb - c1.rgb)) * aa; + let col = vec4(out_rgb, aa); + let m = read_mask(gid.xy, dims, u.p[2].y, u.p[2].z) * u.p[2].x; + let out_col = mix(src, col, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 12. Fuse.Outline (Clover's exact 2020 Outline.fuse passes!) +// outline_boost: boosts alpha * 120 (clamped in R/A via normalized scale, so we pass scale factor!) +// outline_finish: clamps dilated alpha, tints with outline color, then composites original on top! +// ============================================================================ +@compute @workgroup_size(8, 8) +fn outline_boost(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let a = clamp(src.a * 120.0, 0.0, 1.0); + textureStore(dst_tex, vec2(gid.xy), vec4(a, a, a, a)); +} + +@compute @workgroup_size(8, 8) +fn outline_tint(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let blurred = textureLoad(src_a, vec2(gid.xy), 0); + let col = u.p[0]; // (r, g, b, a) + // Because we clamped boosted alpha to 1.0 in u8, emulate the 120x dilation threshold + let a = clamp(blurred.a * u.p[1].x, 0.0, 1.0) * col.a; + textureStore(dst_tex, vec2(gid.xy), vec4(col.rgb * a, a)); +} + +@compute @workgroup_size(8, 8) +fn outline_composite(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let outline = textureLoad(src_a, vec2(gid.xy), 0); + let orig = textureLoad(src_b, vec2(gid.xy), 0); + // Original over outline + let out_rgb = orig.rgb + outline.rgb * (1.0 - orig.a); + let out_a = orig.a + outline.a * (1.0 - orig.a); + textureStore(dst_tex, vec2(gid.xy), clamp(vec4(out_rgb, out_a), vec4(0.0), vec4(1.0))); +} + +// ============================================================================ +// 12c. TextPlus Circular Euclidean L2 Outline + Fill-Over-Outline Composite +// p[0] = (outline_r, outline_g, outline_b, outline_a) +// p[1] = (radius_px, 0, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn text_outline_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let orig = textureLoad(src_a, p, 0); + if (orig.a >= 0.999) { + textureStore(dst_tex, p, orig); + return; + } + + let radius = clamp(u.p[1].x, 0.5, 28.0); + let r_int = i32(ceil(radius + 0.5)); + let r_max = radius + 0.5; + let r_max2 = r_max * r_max; + let max_p = vec2(dims) - vec2(1, 1); + + var max_a = orig.a; + for (var dy = -r_int; dy <= r_int; dy = dy + 1) { + let dy2 = f32(dy * dy); + for (var dx = -r_int; dx <= r_int; dx = dx + 1) { + let d2 = f32(dx * dx) + dy2; + if (d2 > r_max2) { continue; } + let sp = p + vec2(dx, dy); + if (sp.x < 0 || sp.y < 0 || sp.x > max_p.x || sp.y > max_p.y) { continue; } + let sa = textureLoad(src_a, sp, 0).a; + if (sa <= 0.0) { continue; } + let cov = clamp(r_max - sqrt(d2), 0.0, 1.0); + max_a = max(max_a, sa * cov); + } + } + + let oa = max_a * u.p[0].a; + let outline_rgb = u.p[0].rgb * oa; + let out_rgb = orig.rgb + outline_rgb * (1.0 - orig.a); + let out_a = orig.a + oa * (1.0 - orig.a); + textureStore(dst_tex, p, clamp(vec4(out_rgb, out_a), vec4(0.0), vec4(1.0))); +} + +// ============================================================================ +// 13. Custom Wave Shader (matches `sin(x|y * w * n1 + n2 * n1 * w) * 0.5 + 0.5` per channel) +// p[0] = (n1, n2, w_ref, 0) +// p[1] = (r_mode, g_mode, b_mode, a_const) where mode: 0=const 0, 1=sin(x*...), 2=sin(y*...) +// ============================================================================ +fn eval_wave_ch(mode: i32, fu: vec2, n1: f32, n2: f32, w: f32) -> f32 { + let deg2rad = 0.017453292519943295; + if (mode == 1) { + return sin((fu.x * w * n1 + n2 * n1 * w) * deg2rad) * 0.5 + 0.5; + } else if (mode == 2) { + return sin((fu.y * w * n1 + n2 * n1 * w) * deg2rad) * 0.5 + 0.5; + } + return 0.0; +} + +@compute @workgroup_size(8, 8) +fn custom_wave_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fu = pix_to_fu(gid.xy, dims); + let n1 = u.p[0].x; + let n2 = u.p[0].y; + let w = u.p[0].z; + // Fusion CustomTool trig functions operate in DEGREES! + let r = eval_wave_ch(i32(u.p[1].x + 0.5), fu, n1, n2, w); + let g = eval_wave_ch(i32(u.p[1].y + 0.5), fu, n1, n2, w); + let b = eval_wave_ch(i32(u.p[1].z + 0.5), fu, n1, n2, w); + let a = u.p[1].w; + textureStore(dst_tex, vec2(gid.xy), vec4(r, g, b, a)); +} + +// ============================================================================ +// 14. Crop / Scale / Copy +// p[0] = (x_off_norm, y_off_norm, x_scale, y_scale) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn crop_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src_dims = vec2(textureDimensions(src_a)); + let dst_dims = vec2(dims); + let x_off = u.p[0].x; + let y_off = u.p[0].y; + // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from bottom-left (x_off, y_off) + let dst_y_up = dst_dims.y - 1.0 - f32(gid.y); + let src_x = f32(gid.x) + x_off; + let src_y_up = dst_y_up + y_off; + let src_y = src_dims.y - 1.0 - src_y_up; + if (src_x < 0.0 || src_x >= src_dims.x || src_y < 0.0 || src_y >= src_dims.y) { + textureStore(dst_tex, vec2(gid.xy), vec4(0.0)); + return; + } + let uv = (vec2(src_x, src_y) + 0.5) / src_dims; + let c = textureSampleLevel(src_a, samp_lin, uv, 0.0); + textureStore(dst_tex, vec2(gid.xy), c); +} + +// ============================================================================ +// 15. Glow / SoftGlow Combine +// p[0] = (gain, blend, has_mask, mask_invert) +// p[1] = (mode: 0=Screen [SoftGlow], 1=Replace [Glow], 2=Additive, 0, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn glow_add_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let orig = textureLoad(src_a, vec2(gid.xy), 0); + let blurred = textureLoad(src_b, vec2(gid.xy), 0); + let gain = u.p[0].x; + let mode = i32(u.p[1].x + 0.5); + let m = read_mask(gid.xy, dims, u.p[0].z, u.p[0].w) * u.p[0].y; + var added: vec4; + if (mode == 1) { + // Fusion Glow tool: blurred / (1 - Glow), preserving blurred alpha + added = vec4(blurred.rgb * gain, clamp(blurred.a, 0.0, 1.0)); + } else if (mode == 2) { + added = vec4(orig.rgb + blurred.rgb * gain, clamp(orig.a + blurred.a * gain * 0.5, 0.0, 1.0)); + } else { + // Fusion SoftGlow: Screen blend `orig + g - orig * g` where `g = clamp(blurred * gain, 0, 1)` + let g = clamp(blurred * gain, vec4(0.0), vec4(1.0)); + added = orig + g - orig * g; + } + let out_col = mix(orig, added, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + +// ============================================================================ +// 15b. MT_XGlow Preprocess (Threshold -> Gain -> SrcSat -> GlowMask RGB multiply) +// p[0] = (thresh_low, thresh_high, src_sat, has_glow_mask) +// p[1] = (gain, 0, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn xglow_prep_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let t_lo = u.p[0].x; + let t_hi = u.p[0].y; + let src_sat = u.p[0].z; + let has_gm = u.p[0].w > 0.5; + let gain = u.p[1].x; + + var col = src; + if (t_lo > 1e-5 || t_hi > 1e-5) { + let hi = select(1.0, t_hi, t_hi > t_lo + 1e-5); + let denom = max(hi - t_lo, 1e-5); + col = clamp((col - vec4(t_lo)) / denom, vec4(0.0), vec4(1.0)); + } + var rgb = col.rgb * gain; + let y = dot(rgb, vec3(0.299, 0.587, 0.114)); + rgb = mix(vec3(y), rgb, src_sat); + if (has_gm) { + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let gm = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + rgb = rgb * gm; + } + textureStore(dst_tex, vec2(gid.xy), clamp(vec4(rgb, col.a), vec4(0.0), vec4(1.0))); +} + +// ============================================================================ +// 15c. MT_XGlow Octave Accumulate (Gradient tint -> YUV falloff + GlowSat -> Additive) +// src_a = running glow accumulator (or base), src_b = blurred octave (bilinearly upsampled!) +// p[0] = (grad_r, grad_g, grad_b, y_scale) where y_scale = gain / (falloff^i) +// p[1] = (uv_scale, add_base, alpha_scale, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn xglow_accum_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let base = select(vec4(0.0), textureLoad(src_a, vec2(gid.xy), 0), u.p[1].y > 0.5); + let oct = textureSampleLevel(src_b, samp_lin, uv, 0.0); + + let c = oct.rgb * u.p[0].xyz; + // Rec.601 RGB -> YUV -> scale (y_scale, uv_scale, uv_scale) -> RGB (matches MT_XGlow.fuse lines 421-423) + let y = 0.299 * c.r + 0.587 * c.g + 0.114 * c.b; + let u_c = (c.b - y) * 0.492111; + let v_c = (c.r - y) * 0.877283; + let ys = y * u.p[0].w; + let us = u_c * u.p[1].x; + let vs = v_c * u.p[1].x; + let r2 = ys + vs / 0.877283; + let b2 = ys + us / 0.492111; + let g2 = (ys - 0.299 * r2 - 0.114 * b2) / 0.587; + let add_rgb = max(vec3(r2, g2, b2), vec3(0.0)); + let add_a = max(oct.a * u.p[1].z, 0.0); + + let out_col = vec4(base.rgb + add_rgb, clamp(base.a + add_a, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 16. Blit / Scale (source -> destination of any size, premultiplied) +// p[0] = (exposure_mul, gamma, channel_mode: 0=RGBA,1=R,2=G,3=B,4=A, checker_bg) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn display_blit_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let t = (vec2(gid.xy) + 0.5) / vec2(dims); + let has_uv = (u.p[1].z > u.p[1].x) || (u.p[1].w > u.p[1].y); + let uv = select( + t, + vec2(mix(u.p[1].x, u.p[1].z, t.x), mix(u.p[1].y, u.p[1].w, t.y)), + has_uv, + ); + let has_dod = u.p[4].z > 0.5 && u.p[4].w > 0.5; + let sdims = vec2(textureDimensions(src_a)); + let sample_uv = select( + uv, + (vec2(uv.x * u.p[4].z, uv.y * u.p[4].w) - u.p[4].xy) / sdims, + has_dod, + ); + let nearest = u.p[2].x > 0.5; + var src: vec4; + if (sample_uv.x < 0.0 || sample_uv.x >= 1.0 || sample_uv.y < 0.0 || sample_uv.y >= 1.0) { + src = vec4(0.0); + } else if (nearest) { + let isdims = vec2(textureDimensions(src_a)); + let sx = clamp(i32(floor(sample_uv.x * f32(isdims.x))), 0, isdims.x - 1); + let sy = clamp(i32(floor(sample_uv.y * f32(isdims.y))), 0, isdims.y - 1); + src = textureLoad(src_a, vec2(sx, sy), 0); + } else { + src = textureSampleLevel(src_a, samp_lin, sample_uv, 0.0); + } + let exp_mul = u.p[0].x; + let inv_gamma = 1.0 / max(u.p[0].y, 1e-4); + let ch = i32(u.p[0].z + 0.5); + let checker = u.p[0].w > 0.5; + + var out_col = src; + if (ch == 1) { + out_col = vec4(src.r, src.r, src.r, 1.0); + } else if (ch == 2) { + out_col = vec4(src.g, src.g, src.g, 1.0); + } else if (ch == 3) { + out_col = vec4(src.b, src.b, src.b, 1.0); + } else if (ch == 4) { + out_col = vec4(src.a, src.a, src.a, 1.0); + } else { + var rgb = pow(max(src.rgb * exp_mul, vec3(0.0)), vec3(inv_gamma)); + if (checker) { + let cx = (gid.x / 16u) & 1u; + let cy = (gid.y / 16u) & 1u; + let bg = select(0.14, 0.20, (cx ^ cy) == 1u); + rgb = rgb + vec3(bg) * (1.0 - src.a); + out_col = vec4(rgb, 1.0); + } else { + out_col = vec4(rgb, src.a); + } + } + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + + +// ============================================================================ +// 17. InvertColor / Invert Macro +// p[0] = (proc_r, proc_g, proc_b, proc_a) +// p[1] = (blend, has_mask, mask_invert, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn invert_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let a = src.a; + let unpre = select(vec3(0.0), src.rgb / max(a, 1e-5), a > 1e-5); + let new_a = select(a, 1.0 - a, u.p[0].w > 0.5); + let inv_rgb = vec3( + select(unpre.r, 1.0 - unpre.r, u.p[0].x > 0.5), + select(unpre.g, 1.0 - unpre.g, u.p[0].y > 0.5), + select(unpre.b, 1.0 - unpre.b, u.p[0].z > 0.5), + ); + let inv = vec4(inv_rgb * new_a, new_a); + let m = read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x; + let out_col = mix(src, inv, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + +// ============================================================================ +// 17b. ChannelBoolean (full Fusion Operation + per-channel ToRed/Green/Blue/Alpha) +// src_a = Background, src_b = Foreground (or Background if unconnected) +// p[0] = (operation, to_r, to_g, to_b) +// p[1] = (to_a, blend, has_mask, mask_invert) +// ============================================================================ +fn cb_pick(ch: i32, bg: vec4, fg: vec4, bg_ch: f32) -> f32 { + switch ch { + case 0: { return fg.r; } + case 1: { return fg.g; } + case 2: { return fg.b; } + case 3: { return fg.a; } + case 4: { return bg_ch; } // Do Nothing + case 5: { return bg.r; } + case 6: { return bg.g; } + case 7: { return bg.b; } + case 8: { return bg.a; } + case 9: { return dot(bg.rgb, vec3(0.299, 0.587, 0.114)); } // Luma BG + case 10: { return dot(fg.rgb, vec3(0.299, 0.587, 0.114)); } // Luma FG + case 15: { return 0.0; } // Black / Clear + case 16: { return 1.0; } // White / Solid + default: { return fg.r; } + } +} + +fn cb_apply_op(op: i32, bg_v: f32, fg_v: f32) -> f32 { + switch op { + case 0: { return fg_v; } // Copy + case 1: { return bg_v + fg_v; } // Add + case 2: { return bg_v - fg_v; } // Subtract + case 6: { return bg_v * fg_v; } // Multiply + case 7: { return bg_v / max(fg_v, 1e-5); } // Divide + case 8: { return max(bg_v, fg_v); } // Maximum + case 9: { return min(bg_v, fg_v); } // Minimum + case 10: { return 1.0 - fg_v; } // Negative + case 11: { return 1.0; } // Solid + case 12: { return 0.0; } // Clear + case 13: { return abs(bg_v - fg_v); } // Difference + default: { return fg_v; } + } +} + +@compute @workgroup_size(8, 8) +fn channel_boolean_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let bg = textureLoad(src_a, vec2(gid.xy), 0); + let fu = pix_to_fu(gid.xy, dims); + let fg = sample_dod_edges_mode(src_b, fu, 0, u.p[2], false); + + let op = i32(u.p[0].x + 0.5); + let to_r = i32(u.p[0].y + 0.5); + let to_g = i32(u.p[0].z + 0.5); + let to_b = i32(u.p[0].w + 0.5); + let to_a = i32(u.p[1].x + 0.5); + + let vr = select(cb_apply_op(op, bg.r, cb_pick(to_r, bg, fg, bg.r)), bg.r, to_r == 4); + let vg = select(cb_apply_op(op, bg.g, cb_pick(to_g, bg, fg, bg.g)), bg.g, to_g == 4); + let vb = select(cb_apply_op(op, bg.b, cb_pick(to_b, bg, fg, bg.b)), bg.b, to_b == 4); + let va = select(cb_apply_op(op, bg.a, cb_pick(to_a, bg, fg, bg.a)), bg.a, to_a == 4); + + let res = clamp(vec4(vr, vg, vb, va), vec4(0.0), vec4(1.0)); + let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * u.p[1].y; + let out_col = mix(bg, res, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 18. DirectionalBlur (Type 0=Linear, 1=Centered, 2=Radial, 3=Zoom + Glow) +// p[0] = (type, length, angle_rad, glow) +// p[1] = (center.x, center.y, blend, has_mask) +// p[2] = (mask_invert, sample_count, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn dir_blur_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fdims = vec2(dims); + let aspect = fdims.x / max(fdims.y, 1.0); + let fu = pix_to_fu(gid.xy, dims); + let orig = textureLoad(src_a, vec2(gid.xy), 0); + + let kind = i32(u.p[0].x + 0.5); + let length_v = u.p[0].y; + let angle = u.p[0].z; + let glow = u.p[0].w; + let center = u.p[1].xy; + let blend = u.p[1].z; + let samples = clamp(i32(u.p[2].y + 0.5), 4, 64); + + if (abs(length_v) < 1e-5 && abs(angle) < 1e-5) { + textureStore(dst_tex, vec2(gid.xy), orig); + return; + } + + var acc = vec4(0.0); + let inv_n = 1.0 / f32(samples); + let dir_vec = vec2(cos(angle), sin(angle) * aspect); + + for (var i = 0; i < samples; i = i + 1) { + let u_t = (f32(i) + 0.5) * inv_n; // 0..1 + var s_fu = fu; + if (kind == 0) { + // Type 0 = Linear (one-sided along +Angle) + s_fu = fu + dir_vec * (u_t * length_v); + } else if (kind == 1) { + // Type 1 = Radial (clockwise swirl by -u_t * angle + inward radial step by -u_t * length) + let rel = (fu - center) * vec2(aspect, 1.0); + let dist = length(rel); + let a = -u_t * angle; + let ca = cos(a); + let sa = sin(a); + let r_rot = vec2(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca); + let radial_scale = select(0.0, max(1.0 - (u_t * length_v) / dist, 0.0), dist > 1e-5); + s_fu = center + (r_rot * radial_scale) / vec2(aspect, 1.0); + } else if (kind == 2) { + // Type 2 = Centered (symmetric span of total width length_v along Angle) + s_fu = fu + dir_vec * ((u_t - 0.5) * length_v); + } else { + // Type 3 = Zoom (streaks radiate outward from Center by sampling inward toward Center) + let rel = (fu - center) * vec2(aspect, 1.0); + let a = -u_t * angle; + let ca = cos(a); + let sa = sin(a); + let r_rot = vec2(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca); + let scale = max(1.0 - u_t * length_v, 0.05); + s_fu = center + (r_rot * scale) / vec2(aspect, 1.0); + } + let uv = clamp(fu_to_uv(s_fu), vec2(0.0), vec2(1.0)); + acc = acc + textureSampleLevel(src_a, samp_lin, uv, 0.0); + } + acc = acc * inv_n; + // Fusion DirectionalBlur Glow brightens streaks smoothly (~1 + 5*glow) + if (glow > 1e-4) { + acc = vec4(acc.rgb * (1.0 + glow * 5.0), acc.a); + } + + let m = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * blend; + let out_col = mix(orig, acc, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 19. ColorGain (Non-luma-preserving HSV Hue shift across Dark/Mid/High + per-channel Gain/Lift/Gamma/Sat) +// p[0] = (gain_r, gain_g, gain_b, prediv) +// p[1] = (lift_r, lift_g, lift_b, blend) +// p[2] = (gamma_r, gamma_g, gamma_b, sat_mid) +// p[3] = (dark_hue, mid_hue, high_hue, has_mask) +// p[4] = (mask_invert, sat_dark, sat_high, 0) +// ============================================================================ +fn rgb_to_hsv(c: vec3) -> vec3 { + let k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + let p = select(vec4(c.gb, k.xy), vec4(c.bg, k.wz), c.g < c.b); + let q = select(vec4(c.r, p.yzx), vec4(p.xyw, c.r), c.r < p.x); + let d = q.x - min(q.w, q.y); + let e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +fn hsv_to_rgb(c: vec3) -> vec3 { + let k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + let p = abs(fract(c.xxx + k.xyz) * 6.0 - k.www); + return c.z * mix(k.xxx, clamp(p - k.xxx, vec3(0.0), vec3(1.0)), c.y); +} + +@compute @workgroup_size(8, 8) +fn color_gain_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let gain = u.p[0].xyz; + let prediv = u.p[0].w > 0.5; + let lift = u.p[1].xyz; + let blend = u.p[1].w; + let gamma = max(u.p[2].xyz, vec3(1e-4)); + let sat_mid = u.p[2].w; + let dark_hue = u.p[3].x; + let mid_hue = u.p[3].y; + let high_hue = u.p[3].z; + let sat_dark = u.p[4].y; + let sat_high = u.p[4].z; + + var rgb = src.rgb; + if (prediv && src.a > 1e-5) { + rgb = rgb / src.a; + } + + // Per-channel Gain -> Lift -> Gamma + rgb = rgb * gain; + rgb = rgb + lift * (1.0 - rgb); + rgb = pow(max(rgb, vec3(0.0)), vec3(1.0) / gamma); + + // Tonal range weights using HSV Value max(r,g,b) so saturated primaries & outer anti-aliased + // outline edges (>= 0.5) land cleanly in Mid without reddish DarkHue halos, while RGB band blending + // completely prevents green hue-interpolation fringes! + let c_pos = max(rgb, vec3(0.0)); + let lum = clamp(max(c_pos.r, max(c_pos.g, c_pos.b)), 0.0, 1.0); + let w_dark = clamp(1.0 - lum * 2.0, 0.0, 1.0); + let w_high = clamp((lum - 0.5) * 2.0, 0.0, 1.0); + let w_mid = clamp(1.0 - w_dark - w_high, 0.0, 1.0); + + // Fusion ColorGain evaluates Dark, High, then Mid sequentially as RGB mixes against base_hsv + // using V = max(r,g,b) for the range curve — matches Fusion 21.1 to ~0.002 and stays green-fringe-free! + let any_hsv = abs(dark_hue) > 1e-5 || abs(mid_hue) > 1e-5 || abs(high_hue) > 1e-5 + || abs(sat_dark - 1.0) > 1e-4 || abs(sat_mid - 1.0) > 1e-4 || abs(sat_high - 1.0) > 1e-4; + if (any_hsv) { + let base_hsv = rgb_to_hsv(c_pos); + var cur = c_pos; + if ((abs(dark_hue) > 1e-5 || abs(sat_dark - 1.0) > 1e-4) && w_dark > 1e-5) { + let h_d = vec3(fract(base_hsv.x + dark_hue), clamp(base_hsv.y * sat_dark, 0.0, 1.0), base_hsv.z); + cur = mix(cur, hsv_to_rgb(h_d), w_dark); + } + if ((abs(high_hue) > 1e-5 || abs(sat_high - 1.0) > 1e-4) && w_high > 1e-5) { + let h_h = vec3(fract(base_hsv.x + high_hue), clamp(base_hsv.y * sat_high, 0.0, 1.0), base_hsv.z); + cur = mix(cur, hsv_to_rgb(h_h), w_high); + } + if ((abs(mid_hue) > 1e-5 || abs(sat_mid - 1.0) > 1e-4) && w_mid > 1e-5) { + let h_m = vec3(fract(base_hsv.x + mid_hue), clamp(base_hsv.y * sat_mid, 0.0, 1.0), base_hsv.z); + cur = mix(cur, hsv_to_rgb(h_m), w_mid); + } + rgb = cur; + } + + if (prediv) { + rgb = rgb * src.a; + } + let m = read_mask(gid.xy, dims, u.p[3].w, u.p[4].x) * blend; + let out_col = mix(src, vec4(rgb, src.a), clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 20. ColorCurves (per-channel 256x1 LUT texture in src_b) +// p[0] = (prediv, ignore_transparent, blend, has_mask) +// p[1] = (mask_invert, apply_alpha, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn color_curves_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let prediv = u.p[0].x > 0.5; + let ignore_trans = u.p[0].y > 0.5; + let blend = u.p[0].z; + let apply_a = u.p[1].y > 0.5; + + if (ignore_trans && src.a <= 1e-5) { + textureStore(dst_tex, vec2(gid.xy), src); + return; + } + + var rgb = src.rgb; + let unpre = (prediv || ignore_trans) && src.a > 1e-5; + if (unpre) { + rgb = clamp(rgb / src.a, vec3(0.0), vec3(1.0)); + } + + let r = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.r, 0.0, 1.0), 0.5), 0.0).r; + let g = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.g, 0.0, 1.0), 0.5), 0.0).g; + let b = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.b, 0.0, 1.0), 0.5), 0.0).b; + var a = src.a; + if (apply_a) { + a = textureSampleLevel(src_b, samp_lin, vec2(clamp(src.a, 0.0, 1.0), 0.5), 0.0).a; + } + + var out_rgb = vec3(r, g, b); + if (unpre) { + out_rgb = out_rgb * a; + } + let m = read_mask(gid.xy, dims, u.p[0].w, u.p[1].x) * blend; + let out_col = mix(src, vec4(out_rgb, a), clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 21. Fuse.XfChroma (Chromatic Aberration multi-step transform + Gradient LUT in src_b) +// p[0] = (center.x, center.y, pivot.x, pivot.y) (MasterFactor already applied) +// p[1] = (xsize, ysize, angle_rad, steps) +// p[2] = (acc_mode: 0=Add,1=Screen,2=Max,3=Merge, normalize, gain, gamma) +// p[3] = (blend, has_mask, mask_invert, 0) +// p[4] = (dod_ox, dod_oy, dod_cw, dod_ch) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let orig = textureLoad(src_a, vec2(gid.xy), 0); + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + + let center = u.p[0].xy; + let pivot = u.p[0].zw; + let xsize = u.p[1].x; + let ysize = u.p[1].y; + let angle = u.p[1].z; + let steps = clamp(i32(u.p[1].w + 0.5), 1, 32); + let acc_mode = i32(u.p[2].x + 0.5); + let normalize = u.p[2].y > 0.5; + let gain = u.p[2].z; + let gamma = max(u.p[2].w, 0.05); + let blend = u.p[3].x; + + var acc = vec4(0.0); + var grad_sum = vec4(0.0); + let inv_steps = 1.0 / f32(steps); + + for (var i = 0; i <= steps; i = i + 1) { + let n = f32(i) * inv_steps; + let grad = textureSampleLevel(src_b, samp_lin, vec2(n, 0.5), 0.0); + + let cur_c = mix(vec2(0.5, 0.5), center, n); + let cur_sx = max(mix(1.0, xsize, n), 1e-4); + let cur_sy = max(mix(1.0, ysize, n), 1e-4); + let cur_a = angle * n; + + // Inverse transform matching Fusion Transform/XfChroma around pivot + let rel = (fu - cur_c + (pivot - vec2(0.5, 0.5))) * vec2(aspect, 1.0); + let ca = cos(cur_a); + let sa = sin(cur_a); + let rot = vec2(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca); + let scaled = rot / vec2(cur_sx, cur_sy); + let src_fu = pivot + scaled / vec2(aspect, 1.0); + + var s = sample_dod_edges_mode(src_a, src_fu, 0, u.p[4], false); + if (abs(gamma - 1.0) > 1e-3) { + s = vec4(pow(max(s.rgb, vec3(0.0)), vec3(gamma)), s.a); + } + let tinted = s * grad; + grad_sum = grad_sum + grad; + + if (acc_mode == 0) { + acc = acc + tinted; + } else if (acc_mode == 1) { + acc = vec4(1.0) - (vec4(1.0) - acc) * (vec4(1.0) - tinted); + } else if (acc_mode == 2) { + acc = max(acc, tinted); + } else { + acc = tinted + acc * (1.0 - tinted.a); + } + } + + if (normalize && acc_mode == 0) { + acc = vec4( + select(acc.r, acc.r / grad_sum.r, grad_sum.r > 1e-5), + select(acc.g, acc.g / grad_sum.g, grad_sum.g > 1e-5), + select(acc.b, acc.b / grad_sum.b, grad_sum.b > 1e-5), + select(acc.a, acc.a / grad_sum.a, grad_sum.a > 1e-5), + ); + } + if (abs(gamma - 1.0) > 1e-3) { + acc = vec4(pow(max(acc.rgb, vec3(0.0)), vec3(1.0 / gamma)), acc.a); + } + acc = vec4(acc.rgb * gain, clamp(acc.a, 0.0, 1.0)); + + let m = read_mask(gid.xy, dims, u.p[3].y, u.p[3].z) * blend; + let out_col = mix(orig, acc, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 22. GamutConvert (sRGB / Rec.709 / Gamma transfer conversion) +// p[0] = (src_space: 0=None/Linear,1=sRGB,2=Rec709, dst_space: 0=None/Linear,1=sRGB,2=Rec709, prediv, blend) +// p[1] = (has_mask, mask_invert, 0, 0) +// ============================================================================ +fn srgb_to_linear_ch(c: f32) -> f32 { + if (c <= 0.04045) { return c / 12.92; } + return pow((c + 0.055) / 1.055, 2.4); +} +fn linear_to_srgb_ch(c: f32) -> f32 { + let x = max(c, 0.0); + if (x <= 0.0031308) { return x * 12.92; } + return 1.055 * pow(x, 1.0 / 2.4) - 0.055; +} +fn rec709_to_linear_ch(c: f32) -> f32 { + if (c < 0.081) { return c / 4.5; } + return pow((c + 0.099) / 1.099, 1.0 / 0.45); +} +fn linear_to_rec709_ch(c: f32) -> f32 { + let x = max(c, 0.0); + if (x < 0.018) { return x * 4.5; } + return 1.099 * pow(x, 0.45) - 0.099; +} + +@compute @workgroup_size(8, 8) +fn gamut_convert_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let src_sp = i32(u.p[0].x + 0.5); + let dst_sp = i32(u.p[0].y + 0.5); + let prediv = u.p[0].z > 0.5; + let blend = u.p[0].w; + + var rgb = src.rgb; + if (prediv && src.a > 1e-5) { + rgb = rgb / src.a; + } + + // Remove source gamma -> Linear + if (src_sp == 1) { + rgb = vec3(srgb_to_linear_ch(rgb.r), srgb_to_linear_ch(rgb.g), srgb_to_linear_ch(rgb.b)); + } else if (src_sp == 2) { + rgb = vec3(rec709_to_linear_ch(rgb.r), rec709_to_linear_ch(rgb.g), rec709_to_linear_ch(rgb.b)); + } + // Add destination gamma <- Linear + if (dst_sp == 1) { + rgb = vec3(linear_to_srgb_ch(rgb.r), linear_to_srgb_ch(rgb.g), linear_to_srgb_ch(rgb.b)); + } else if (dst_sp == 2) { + rgb = vec3(linear_to_rec709_ch(rgb.r), linear_to_rec709_ch(rgb.g), linear_to_rec709_ch(rgb.b)); + } + + if (prediv) { + rgb = rgb * src.a; + } + let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * blend; + let out_col = mix(src, vec4(rgb, src.a), clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} + + +// ============================================================================ +// 23. VariBlur (per-pixel variable blur driven by BlurImage in src_b) +// p[0] = (radius_x_px, radius_y_px, has_blur_map, blend) +// p[1] = (has_mask, mask_invert, taps, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn vari_blur_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let orig = textureLoad(src_a, vec2(gid.xy), 0); + let fdims = vec2(dims); + let uv = (vec2(gid.xy) + 0.5) / fdims; + var factor = 1.0; + if (u.p[0].z > 0.5) { + let bm = textureSampleLevel(src_b, samp_lin, uv, 0.0); + factor = dot(bm.rgb, vec3(0.299, 0.587, 0.114)); + } + let rx = u.p[0].x * factor; + let ry = u.p[0].y * factor; + if (max(rx, ry) < 0.25) { + textureStore(dst_tex, vec2(gid.xy), orig); + return; + } + // 2D Poisson-like concentric disc tap kernel + let rings = clamp(i32(u.p[1].z + 0.5), 2, 4); + var acc = orig; + var wsum = 1.0; + for (var ring = 1; ring <= rings; ring = ring + 1) { + let rf = f32(ring) / f32(rings); + let n_ang = ring * 6; + let w = exp(-rf * rf * 2.0); + for (var a = 0; a < n_ang; a = a + 1) { + let ang = f32(a) * 6.28318530718 / f32(n_ang); + let off = vec2(cos(ang) * rx * rf, sin(ang) * ry * rf) / fdims; + let suv = clamp(uv + off, vec2(0.0), vec2(1.0)); + acc = acc + textureSampleLevel(src_a, samp_lin, suv, 0.0) * w; + wsum = wsum + w; + } + } + let blurred = acc / wsum; + let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * u.p[0].w; + let out_col = mix(orig, blurred, clamp(m, 0.0, 1.0)); + textureStore(dst_tex, vec2(gid.xy), clamp(out_col, vec4(0.0), vec4(1.0))); +} diff --git a/crates/flow/Cargo.toml b/crates/flow/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d2cbe2e1e152eda05f92184d18623d28d5589b1 --- /dev/null +++ b/crates/flow/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "flow" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[dependencies] +draw.workspace = true +model.workspace = true +text.workspace = true +theme.workspace = true +ui.workspace = true +winit.workspace = true diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..d8b47dcac60b977dd6ec9c30f2235a2f66a720f9 --- /dev/null +++ b/crates/flow/src/lib.rs @@ -0,0 +1,1162 @@ +//! Node Flow canvas built on `draw` + `ui`: +//! - Sleek thin Fusion-style node bars with colored bottom stripe +//! - Auto-wrapping output/input ports that snap to whichever side faces connected nodes +//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal) +//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks +//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. + +use draw::{Glyphs, PathStyle, Primitive}; +use model::{Comp, NodeId, PortRole, default_main_input_port}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use winit::event::{ElementState, MouseButton}; +use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; + +// Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires). +const NODE_W: f32 = 84.0; +const NODE_H: f32 = 21.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TransformMode { + Grab, + Rotate, + Scale, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AxisLock { + None, + X, + Y, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Edge { + Left, + Right, + Top, + Bottom, +} + +impl Edge { + fn normal(self) -> [f32; 2] { + match self { + Edge::Left => [-1.0, 0.0], + Edge::Right => [1.0, 0.0], + Edge::Top => [0.0, -1.0], + Edge::Bottom => [0.0, 1.0], + } + } + + fn point_on_rect(self, r: [f32; 4], t: f32) -> [f32; 2] { + match self { + Edge::Left => [r[0], r[1] + (r[3] - r[1]) * t], + Edge::Right => [r[2], r[1] + (r[3] - r[1]) * t], + Edge::Top => [r[0] + (r[2] - r[0]) * t, r[1]], + Edge::Bottom => [r[0] + (r[2] - r[0]) * t, r[3]], + } + } +} + +#[derive(Clone, Debug)] +struct ModalTransform { + mode: TransformMode, + axis: AxisLock, + pivot_world: [f32; 2], + start_pointer_world: [f32; 2], + saved_positions: Vec<(NodeId, [f32; 2])>, +} + +#[derive(Clone, Debug)] +struct WireDrag { + src: NodeId, + cursor_local: [f32; 2], +} + +#[derive(Clone, Debug)] +struct BoxSelect { + start_local: [f32; 2], + cur_local: [f32; 2], +} + +#[derive(Clone, Debug)] +pub enum FlowAction { + SelectionChanged(Option), + /// Slot 0 = Viewer 1 (`1` key), Slot 1 = Viewer 2 (`2` key). + ViewNode(usize, NodeId), + /// `` ` `` key: clear both Viewer 1 and Viewer 2. + ClearViewers, + GraphMutated, +} + +#[derive(Clone, Debug)] +struct WireRef { + src: NodeId, + dst: NodeId, + port: String, +} + +#[derive(Clone, Copy, Debug)] +pub struct FlowPalette { + pub bg: [f32; 4], + pub grid_minor: [f32; 4], + pub grid_major: [f32; 4], + pub node_fill: [f32; 4], + pub node_hover: [f32; 4], + pub node_selected: [f32; 4], + pub node_border: [f32; 4], + pub text: [f32; 4], + pub text_dim: [f32; 4], + pub accent: [f32; 4], +} + +impl FlowPalette { + pub fn from_ui(theme: &ui::Theme) -> Self { + let b = theme.base; + let lift = |c: [f32; 4], d: f32| { + [(c[0] + d).clamp(0.0, 1.0), (c[1] + d).clamp(0.0, 1.0), (c[2] + d).clamp(0.0, 1.0), 1.0] + }; + Self { + bg: b, + grid_minor: lift(b, 0.012), + grid_major: lift(b, 0.028), + node_fill: lift(b, 0.036), + node_hover: lift(b, 0.056), + node_selected: lift(b, 0.078), + node_border: theme.chip, + text: theme.text, + text_dim: theme.text_dim, + accent: theme.accent, + } + } +} + +pub struct FlowView { + pub pan: [f32; 2], + pub zoom: f32, + pub size: [f32; 2], + pub selected: HashSet, + pub primary: Option, + /// `[viewer_1_node, viewer_2_node]`. + pub viewed_nodes: [Option; 2], + pub palette: FlowPalette, + hovered_node: Option, + hovered_wire: Option, + modal: Option, + wire_drag: Option, + box_select: Option, + panning: Option<([f32; 2], [f32; 2])>, + lmb_drag_node: Option<(NodeId, [f32; 2], bool)>, + pointer_local: [f32; 2], + label_cache: HashMap, + badge_cache: HashMap, + fitted_once: bool, +} + +impl FlowView { + pub fn new(theme: &ui::Theme) -> Self { + Self { + pan: [0.0, 0.0], + zoom: 1.0, + size: [800.0, 500.0], + selected: HashSet::new(), + primary: None, + viewed_nodes: [None, None], + palette: FlowPalette::from_ui(theme), + hovered_node: None, + hovered_wire: None, + modal: None, + wire_drag: None, + box_select: None, + panning: None, + lmb_drag_node: None, + pointer_local: [0.0, 0.0], + label_cache: HashMap::new(), + badge_cache: HashMap::new(), + fitted_once: false, + } + } + + pub fn resize(&mut self, size: [f32; 2]) { + self.size = [size[0].max(1.0), size[1].max(1.0)]; + } + + pub fn background(&self) -> [f32; 4] { + self.palette.bg + } + + pub fn fit_all(&mut self, comp: &Comp) { + let ids: Vec = if !self.selected.is_empty() { + self.selected.iter().copied().collect() + } else { + comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect() + }; + self.fit_ids(comp, ids); + } + + pub fn fit_comp(&mut self, comp: &Comp) { + let ids: Vec = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect(); + self.fit_ids(comp, ids); + } + + fn fit_ids(&mut self, comp: &Comp, target_ids: Vec) { + if target_ids.is_empty() { + return; + } + let mut min_x = f32::INFINITY; + let mut min_y = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut max_y = f32::NEG_INFINITY; + for id in target_ids { + let p = comp.node(id).pos; + min_x = min_x.min(p[0] - NODE_W * 0.5); + max_x = max_x.max(p[0] + NODE_W * 0.5); + min_y = min_y.min(p[1] - NODE_H * 0.5); + max_y = max_y.max(p[1] + NODE_H * 0.5); + } + let span_x = (max_x - min_x).max(200.0); + let span_y = (max_y - min_y).max(120.0); + let pad = 64.0; + let zx = ((self.size[0] - pad) / span_x).clamp(0.15, 1.5); + let zy = ((self.size[1] - pad) / span_y).clamp(0.15, 1.5); + self.zoom = zx.min(zy); + self.pan = [(min_x + max_x) * 0.5, (min_y + max_y) * 0.5]; + self.fitted_once = true; + } + + pub fn ensure_fitted(&mut self, comp: &Comp) { + if !self.fitted_once && self.size[0] > 40.0 && self.size[1] > 40.0 { + self.fit_comp(comp); + } + } + + fn world_to_local(&self, w: [f32; 2]) -> [f32; 2] { + [ + (w[0] - self.pan[0]) * self.zoom + self.size[0] * 0.5, + (w[1] - self.pan[1]) * self.zoom + self.size[1] * 0.5, + ] + } + + fn local_to_world(&self, l: [f32; 2]) -> [f32; 2] { + [ + (l[0] - self.size[0] * 0.5) / self.zoom + self.pan[0], + (l[1] - self.size[1] * 0.5) / self.zoom + self.pan[1], + ] + } + + fn node_rect_local(&self, pos: [f32; 2]) -> [f32; 4] { + let c = self.world_to_local(pos); + let hw = NODE_W * 0.5 * self.zoom; + let hh = NODE_H * 0.5 * self.zoom; + [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh] + } + + /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the + /// closest facing sides of each node (Fusion's signature clean multi-directional routing!). + fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) { + let sp = comp.node(src).pos; + let dp = comp.node(dst).pos; + let sr = self.node_rect_local(sp); + let dr = self.node_rect_local(dp); + + let dx = dp[0] - sp[0]; + let dy = dp[1] - sp[1]; + // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)! + let out_edge = closest_edge(dx, dy); + let in_edge = closest_edge_for_input(-dx, -dy, role); + + let a = out_edge.point_on_rect(sr, 0.5); + let b = in_edge.point_on_rect(dr, 0.5); + (a, out_edge, b, in_edge) + } + + /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right). + fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge { + let name = &comp.node(id).name; + let sp = comp.node(id).pos; + let mut sx = 0.0_f32; + let mut sy = 0.0_f32; + let mut count = 0; + for other in &comp.nodes { + for binding in other.inputs.values() { + if binding.source_op.as_deref() == Some(name.as_str()) { + let dx = other.pos[0] - sp[0]; + let dy = other.pos[1] - sp[1]; + let len = (dx * dx + dy * dy).sqrt().max(1.0); + sx += dx / len; + sy += dy / len; + count += 1; + } + } + } + if count == 0 { + Edge::Right + } else { + closest_edge(sx, sy) + } + } + + fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option { + for n in comp.nodes.iter().rev() { + if n.internal { continue; } + let r = self.node_rect_local(n.pos); + if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] { + return Some(n.id); + } + } + None + } + + fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option { + for n in comp.nodes.iter().rev() { + if n.internal { continue; } + let r = self.node_rect_local(n.pos); + let edge = self.node_output_edge(comp, n.id); + let nrm = edge.normal(); + let p0 = edge.point_on_rect(r, 0.5); + let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0]; + let dx = local[0] - p[0]; + let dy = local[1] - p[1]; + if dx * dx + dy * dy <= 10.0 * 10.0 { + return Some(n.id); + } + } + None + } + + fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { + for n in comp.nodes.iter().rev() { + let r = self.node_rect_local(n.pos); + if local[0] >= r[0] - 8.0 && local[0] <= r[2] + 8.0 && local[1] >= r[1] - 8.0 && local[1] <= r[3] + 8.0 { + // Pick Background/Foreground/Mask cleanly based on approach edge for Merge! + if n.kind == "Merge" || n.kind == "Displace" { + let cy = (r[1] + r[3]) * 0.5; + if local[1] < r[1] + 2.0 { + return Some((n.id, "Foreground")); + } + if local[1] > r[3] - 2.0 { + return Some((n.id, "EffectMask")); + } + let _ = cy; + } + return Some((n.id, default_main_input_port(&n.kind))); + } + } + None + } + + fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { + let mut best: Option<(f32, WireRef)> = None; + for dst in &comp.nodes { + if Some(dst.id) == ignore_node { + continue; + } + for (port, binding) in &dst.inputs { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = comp.find_node(src_name) else { continue }; + if Some(src_id) == ignore_node { + continue; + } + let role = PortRole::from_input_name(port); + let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); + let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom); + if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some(( + d, + WireRef { + src: src_id, + dst: dst.id, + port: port.clone(), + }, + )); + } + } + } + best.map(|(_, w)| w) + } + + fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) { + if self.selected.is_empty() { + return; + } + let mut cx = 0.0_f32; + let mut cy = 0.0_f32; + let mut saved = Vec::with_capacity(self.selected.len()); + for &id in &self.selected { + let p = comp.node(id).pos; + cx += p[0]; + cy += p[1]; + saved.push((id, p)); + } + let n = saved.len() as f32; + self.modal = Some(ModalTransform { + mode, + axis: AxisLock::None, + pivot_world: [cx / n, cy / n], + start_pointer_world: self.local_to_world(self.pointer_local), + saved_positions: saved, + }); + } + + fn apply_modal(&mut self, comp: &mut Comp) { + let Some(m) = &self.modal else { return }; + let cur = self.local_to_world(self.pointer_local); + let dx = cur[0] - m.start_pointer_world[0]; + let dy = cur[1] - m.start_pointer_world[1]; + let piv = m.pivot_world; + + match m.mode { + TransformMode::Grab => { + let (mx, my) = match m.axis { + AxisLock::None => (dx, dy), + AxisLock::X => (dx, 0.0), + AxisLock::Y => (0.0, dy), + }; + for &(id, orig) in &m.saved_positions { + comp.node_mut(id).pos = [orig[0] + mx, orig[1] + my]; + } + } + TransformMode::Rotate => { + let a0 = (m.start_pointer_world[1] - piv[1]).atan2(m.start_pointer_world[0] - piv[0]); + let a1 = (cur[1] - piv[1]).atan2(cur[0] - piv[0]); + let da = a1 - a0; + let (c, s) = (da.cos(), da.sin()); + for &(id, orig) in &m.saved_positions { + let rx = orig[0] - piv[0]; + let ry = orig[1] - piv[1]; + comp.node_mut(id).pos = [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c]; + } + } + TransformMode::Scale => { + let d0 = ((m.start_pointer_world[0] - piv[0]).powi(2) + (m.start_pointer_world[1] - piv[1]).powi(2)).sqrt().max(12.0); + let d1 = ((cur[0] - piv[0]).powi(2) + (cur[1] - piv[1]).powi(2)).sqrt(); + let factor = (d1 / d0).clamp(0.1, 10.0); + let (sx, sy) = match m.axis { + AxisLock::None => (factor, factor), + AxisLock::X => (factor, 1.0), + AxisLock::Y => (1.0, factor), + }; + for &(id, orig) in &m.saved_positions { + comp.node_mut(id).pos = [ + piv[0] + (orig[0] - piv[0]) * sx, + piv[1] + (orig[1] - piv[1]) * sy, + ]; + } + } + } + if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 { + let id = m.saved_positions[0].0; + let c_local = self.world_to_local(comp.node(id).pos); + self.hovered_wire = self.hit_wire(comp, c_local, Some(id)); + } else { + self.hovered_wire = None; + } + } + + fn cancel_modal(&mut self, comp: &mut Comp) { + if let Some(m) = self.modal.take() { + for (id, orig) in m.saved_positions { + comp.node_mut(id).pos = orig; + } + } + self.hovered_wire = None; + } + + fn confirm_modal(&mut self, comp: &mut Comp) -> bool { + let mut mutated = false; + if let Some(m) = self.modal.take() { + if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 { + let id = m.saved_positions[0].0; + if let Some(w) = self.hovered_wire.take() { + comp.insert_on_wire(id, w.src, w.dst, &w.port); + mutated = true; + } + } + } + self.hovered_wire = None; + mutated + } + + fn handle_key(&mut self, comp: &mut Comp, physical: Option, key: &Key, kmod: ModifiersState, actions: &mut Vec) { + // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F + if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { + self.fit_all(comp); + return; + } + if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) { + self.viewed_nodes = [None, None]; + actions.push(FlowAction::ClearViewers); + return; + } + match key { + Key::Named(NamedKey::Escape) => { + if self.modal.is_some() { + self.cancel_modal(comp); + } + self.wire_drag = None; + } + Key::Named(NamedKey::Enter) => { + if self.modal.is_some() && self.confirm_modal(comp) { + actions.push(FlowAction::GraphMutated); + } + } + Key::Character(c) => match c.to_ascii_lowercase().as_str() { + "`" | "~" => { + self.viewed_nodes = [None, None]; + actions.push(FlowAction::ClearViewers); + } + "f" if kmod.super_key() => self.fit_all(comp), + "f" if !kmod.super_key() => self.fit_all(comp), + "." if !kmod.super_key() => self.fit_all(comp), + "g" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Grab); + } + "r" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Rotate); + } + "s" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Scale); + } + "x" if self.modal.is_some() => { + if let Some(m) = &mut self.modal { + m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X }; + } + self.apply_modal(comp); + } + "y" if self.modal.is_some() => { + if let Some(m) = &mut self.modal { + m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y }; + } + self.apply_modal(comp); + } + "a" if !kmod.super_key() => { + if self.selected.len() == comp.nodes.len() { + self.selected.clear(); + self.primary = None; + } else { + self.selected = comp.nodes.iter().map(|n| n.id).collect(); + self.primary = comp.nodes.first().map(|n| n.id); + } + actions.push(FlowAction::SelectionChanged(self.primary)); + } + "1" if !kmod.super_key() => { + if let Some(id) = self.primary { + self.viewed_nodes[0] = Some(id); + actions.push(FlowAction::ViewNode(0, id)); + } + } + "2" if !kmod.super_key() => { + if let Some(id) = self.primary { + self.viewed_nodes[1] = Some(id); + actions.push(FlowAction::ViewNode(1, id)); + } + } + "p" => { + let ids: Vec = self.selected.iter().copied().collect(); + for id in ids { + comp.toggle_bypass(id); + } + if !self.selected.is_empty() { + actions.push(FlowAction::GraphMutated); + } + } + _ => {} + }, + _ => {} + } + } + + pub fn input( + &mut self, + comp: &mut Comp, + event: ui::Event, + rect: [f32; 4], + pointer_window: [f32; 2], + modifiers: ModifiersState, + ) -> Vec { + let mut actions = Vec::new(); + self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; + + match event { + ui::Event::PointerMoved(p) => { + self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; + if let Some((start_p, start_pan)) = self.panning { + self.pan = [ + start_pan[0] - (self.pointer_local[0] - start_p[0]) / self.zoom, + start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom, + ]; + } else if self.modal.is_some() { + self.apply_modal(comp); + } else if let Some(wd) = &mut self.wire_drag { + wd.cursor_local = self.pointer_local; + } else if let Some(bs) = &mut self.box_select { + bs.cur_local = self.pointer_local; + } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node { + let dx = self.pointer_local[0] - start_l[0]; + let dy = self.pointer_local[1] - start_l[1]; + if !*moved && dx * dx + dy * dy > 16.0 { + *moved = true; + if !self.selected.contains(&nid) { + self.selected.clear(); + self.selected.insert(nid); + self.primary = Some(nid); + actions.push(FlowAction::SelectionChanged(self.primary)); + } + self.begin_modal(comp, TransformMode::Grab); + } + } else { + self.hovered_node = self.hit_node(comp, self.pointer_local); + self.hovered_wire = if self.hovered_node.is_none() { + self.hit_wire(comp, self.pointer_local, None) + } else { + None + }; + } + } + ui::Event::Button { button, pressed, .. } => { + if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { + if pressed { + self.panning = Some((self.pointer_local, self.pan)); + } else { + self.panning = None; + } + } else if button == MouseButton::Right { + if pressed && self.modal.is_some() { + self.cancel_modal(comp); + } else if pressed && self.wire_drag.is_some() { + self.wire_drag = None; + } + } else if button == MouseButton::Left { + if pressed { + if self.modal.is_some() { + if self.confirm_modal(comp) { + actions.push(FlowAction::GraphMutated); + } + } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) { + self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local }); + } else if let Some(nid) = self.hit_node(comp, self.pointer_local) { + if modifiers.shift_key() { + if !self.selected.remove(&nid) { + self.selected.insert(nid); + self.primary = Some(nid); + } + } else if !self.selected.contains(&nid) { + self.selected.clear(); + self.selected.insert(nid); + self.primary = Some(nid); + } else { + self.primary = Some(nid); + } + actions.push(FlowAction::SelectionChanged(self.primary)); + self.lmb_drag_node = Some((nid, self.pointer_local, false)); + } else { + if !modifiers.shift_key() { + self.selected.clear(); + self.primary = None; + actions.push(FlowAction::SelectionChanged(None)); + } + self.box_select = Some(BoxSelect { + start_local: self.pointer_local, + cur_local: self.pointer_local, + }); + } + } else { + if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() { + if moved && self.modal.is_some() { + if self.confirm_modal(comp) { + actions.push(FlowAction::GraphMutated); + } + } + } + if let Some(wd) = self.wire_drag.take() { + if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) { + comp.connect(wd.src, dst, port); + actions.push(FlowAction::GraphMutated); + } + } + if let Some(bs) = self.box_select.take() { + let x0 = bs.start_local[0].min(bs.cur_local[0]); + let x1 = bs.start_local[0].max(bs.cur_local[0]); + let y0 = bs.start_local[1].min(bs.cur_local[1]); + let y1 = bs.start_local[1].max(bs.cur_local[1]); + if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 { + for n in &comp.nodes { + let c = self.world_to_local(n.pos); + if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 { + self.selected.insert(n.id); + self.primary = Some(n.id); + } + } + actions.push(FlowAction::SelectionChanged(self.primary)); + } + } + } + } + } + ui::Event::Wheel(delta) => { + // Blender & Fusion convention: plain scroll zooms toward mouse cursor; Shift+scroll pans. + if modifiers.shift_key() { + self.pan[0] -= delta[0] / self.zoom; + self.pan[1] -= delta[1] / self.zoom; + } else { + let factor = (1.0 + delta[1] * 0.0045).clamp(0.7, 1.4); + self.zoom_at(factor, self.pointer_local); + } + } + ui::Event::Pinch(delta) => { + let factor = (1.0 + delta).clamp(0.7, 1.4); + self.zoom_at(factor, self.pointer_local); + } + ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { + self.handle_key(comp, Some(physical), &key, kmod, &mut actions); + } + ui::Event::Key { key, modifiers: kmod, .. } => { + self.handle_key(comp, None, &key, kmod, &mut actions); + } + _ => {} + } + + actions + } + + fn zoom_at(&mut self, factor: f32, pivot_local: [f32; 2]) { + let before = self.local_to_world(pivot_local); + self.zoom = (self.zoom * factor).clamp(0.12, 3.5); + let after = self.local_to_world(pivot_local); + self.pan[0] += before[0] - after[0]; + self.pan[1] += before[1] - after[1]; + } + + pub fn prepare_labels(&mut self, comp: &Comp) { + let label_font = text::Font { + families: Arc::from([text::Family::Sans]), + size: 9.5, + weight: 500, + italic: false, + }; + let badge_font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.0, + weight: 500, + italic: false, + }; + let make_layout = |s: &str, font: &text::Font| { + let styles = [text::Style::new(font.clone())]; + text::Paragraph { + text: s, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }; + for n in &comp.nodes { + self.label_cache.entry(n.name.clone()).or_insert_with(|| make_layout(&n.name, &label_font)); + } + for key in [ + "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom", + "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + ] { + self.badge_cache.entry(key.to_owned()).or_insert_with(|| make_layout(key, &badge_font)); + } + } + + pub fn paint<'a>(&'a self, comp: &'a Comp) -> Vec> { + let mut out = Vec::with_capacity(comp.nodes.len() * 10 + 128); + let [w, h] = self.size; + + // 1. Subtle architectural grid aligned to Fusion's 110×33 flow cells + let mult = if self.zoom < 0.35 { 4.0 } else if self.zoom < 0.70 { 2.0 } else { 1.0 }; + let step_x = 110.0 * mult; + let step_y = 33.0 * mult * 2.0; + let tl = self.local_to_world([0.0, 0.0]); + let br = self.local_to_world([w, h]); + let gx0 = (tl[0] / step_x).floor() as i32; + let gx1 = (br[0] / step_x).ceil() as i32; + let gy0 = (tl[1] / step_y).floor() as i32; + let gy1 = (br[1] / step_y).ceil() as i32; + for gx in gx0..=gx1 { + let x = self.world_to_local([gx as f32 * step_x, 0.0])[0]; + let col = if gx % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; + out.push(Primitive::Segment { from: [x, 0.0], to: [x, h], width: 1.0, color: col }); + } + for gy in gy0..=gy1 { + let y = self.world_to_local([0.0, gy as f32 * step_y])[1]; + let col = if gy % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor }; + out.push(Primitive::Segment { from: [0.0, y], to: [w, y], width: 1.0, color: col }); + } + + // 2. Modal Blender axis-lock guide lines + if let Some(m) = &self.modal { + let piv = self.world_to_local(m.pivot_world); + match m.axis { + AxisLock::X => out.push(Primitive::Segment { + from: [0.0, piv[1]], + to: [w, piv[1]], + width: 1.5, + color: [0.95, 0.28, 0.34, 0.85], + }), + AxisLock::Y => out.push(Primitive::Segment { + from: [piv[0], 0.0], + to: [piv[0], h], + width: 1.5, + color: [0.28, 0.90, 0.42, 0.85], + }), + AxisLock::None => {} + } + } + + // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)! + let large_ports = self.zoom >= 0.72; + let tri_len = if large_ports { 6.5 } else { 4.5 }; + let out_half = if large_ports { 2.8 } else { 2.0 }; + let out_gap = if large_ports { 2.2 } else { 1.5 }; + let port_outline = [0.04, 0.04, 0.06, 0.92]; + + for dst in &comp.nodes { + if dst.internal { continue; } + // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping + let mut used_edges: HashMap = HashMap::new(); + let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect(); + sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) { + PortRole::Background => 0u8, + PortRole::Foreground => 1, + PortRole::Mask => 2, + PortRole::Scene3D => 3, + PortRole::Aux => 4, + }); + for (port, binding) in sorted_ports { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = comp.find_node(src_name) else { continue }; + let role = PortRole::from_input_name(port); + let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role); + let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 }; + let count = used_edges.entry(ekey(be)).or_insert(0); + if *count > 0 { + // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge + let dr = self.node_rect_local(dst.pos); + if matches!(be, Edge::Top | Edge::Bottom) { + let t = if *count == 1 { 0.25 } else { 0.75 }; + b = be.point_on_rect(dr, t); + } else if role == PortRole::Mask { + be = Edge::Bottom; + b = be.point_on_rect(dr, 0.5); + } else { + let t = if *count == 1 { 0.30 } else { 0.70 }; + b = be.point_on_rect(dr, t); + } + } + *count += 1; + + let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port); + let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id); + + let wire_col = if is_hot { + [0.98, 0.82, 0.24, 1.0] + } else if is_sel { + [0.92, 0.94, 0.98, 0.96] + } else { + [0.64, 0.66, 0.72, 0.76] + }; + let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 }; + let an = ae.normal(); + let bn = be.normal(); + let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)]; + let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len]; + + // Straight wire directly from output square center to input triangle base (exact Fusion look!) + out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col }); + + if self.zoom >= 0.36 { + // Output port: crisp Fusion white square `□` with thin dark outline + out.push(Primitive::RoundedRect { + rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], + radius: 0.6, + stroke: None, + color: [0.94, 0.95, 0.98, 0.98], + }); + out.push(Primitive::RoundedRect { + rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], + radius: 0.6, + stroke: Some(0.9), + color: port_outline, + }); + + // Input port: crisp Fusion colored triangle pointing INTO `dst`! + let pcol = port_color(role); + let tri = input_arrow_svg(be, large_ports); + out.push(Primitive::Path { + data: tri, + origin: b, + style: PathStyle::Fill, + color: pcol, + }); + out.push(Primitive::Path { + data: tri, + origin: b, + style: PathStyle::Stroke(0.9), + color: port_outline, + }); + } + } + } + + // Active wire drag preview + if let Some(wd) = &self.wire_drag { + let sr = self.node_rect_local(comp.node(wd.src).pos); + let edge = self.node_output_edge(comp, wd.src); + let a = edge.point_on_rect(sr, 0.5); + out.push(Primitive::Segment { from: a, to: wd.cursor_local, width: 2.0, color: [0.98, 0.84, 0.30, 1.0] }); + } + + // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!) + for n in &comp.nodes { + if n.internal { continue; } + let r = self.node_rect_local(n.pos); + if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 { + continue; + } + let sel = self.selected.contains(&n.id); + let primary = self.primary == Some(n.id); + let hovered = self.hovered_node == Some(n.id); + let v1 = self.viewed_nodes[0] == Some(n.id); + let v2 = self.viewed_nodes[1] == Some(n.id); + let accent = node_accent(&n.kind); + + let bg = if n.bypassed { + [self.palette.node_fill[0] * 0.6, self.palette.node_fill[1] * 0.6, self.palette.node_fill[2] * 0.6, 0.65] + } else if sel { + self.palette.node_selected + } else if hovered { + self.palette.node_hover + } else { + self.palette.node_fill + }; + + let radius = (3.5 * self.zoom).clamp(1.5, 5.0); + out.push(Primitive::RoundedRect { rect: r, radius, stroke: None, color: bg }); + + // Bottom category color line (exact Fusion look — thin sleek strip on bottom edge!) + let bar_h = (2.6 * self.zoom).clamp(1.4, 3.4); + out.push(Primitive::Rect { + rect: [r[0] + 1.5, (r[3] - bar_h).max(r[1]), r[2] - 1.5, r[3]], + color: if n.bypassed { [0.28, 0.28, 0.32, 0.6] } else { accent }, + }); + + // Crisp border + let border_col = if primary { + [0.98, 0.78, 0.30, 1.0] + } else if sel { + self.palette.accent + } else { + self.palette.node_border + }; + out.push(Primitive::RoundedRect { + rect: r, + radius, + stroke: Some(if sel || primary { 1.4 } else { 0.9 }), + color: border_col, + }); + + // Node label centered cleanly inside thin bar + if self.zoom >= 0.42 { + if let Some(layout) = self.label_cache.get(&n.name) { + let ink = if n.bypassed { self.palette.text_dim } else { self.palette.text }; + let pad_x = (6.0 * self.zoom).clamp(3.0, 8.0); + let text_y = (r[1] + r[3] - bar_h) * 0.5 - 6.0; + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [r[0] + pad_x, text_y], + clip: Some([r[0] + pad_x, r[1] + 1.0, r[2] - 4.0, r[3] - bar_h]), + ink, + }); + } + } + + // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!) + if v1 || v2 { + let pw = 22.0; + let ph = 9.0; + let px = r[0] + 4.0; + let py = r[3] + 1.5; + out.push(Primitive::RoundedRect { + rect: [px, py, px + pw, py + ph], + radius: 3.0, + stroke: None, + color: [0.02, 0.02, 0.03, 0.92], + }); + let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; + let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; + out.push(Primitive::RoundedRect { + rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0], + radius: 2.5, + stroke: None, + color: d1, + }); + out.push(Primitive::RoundedRect { + rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0], + radius: 2.5, + stroke: None, + color: d2, + }); + } + + if n.bypassed { + let ym = (r[1] + r[3]) * 0.5; + out.push(Primitive::Segment { + from: [r[0] + 3.0, ym], + to: [r[2] - 3.0, ym], + width: 1.4, + color: [0.95, 0.35, 0.35, 0.85], + }); + } + } + + // 5. Box select marquee + if let Some(bs) = &self.box_select { + let x0 = bs.start_local[0].min(bs.cur_local[0]); + let x1 = bs.start_local[0].max(bs.cur_local[0]); + let y0 = bs.start_local[1].min(bs.cur_local[1]); + let y1 = bs.start_local[1].max(bs.cur_local[1]); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], + }); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: Some(1.2), + color: self.palette.accent, + }); + } + + // 6. Status HUD strip + let hud_key = match self.modal.as_ref().map(|m| m.mode) { + Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + None => "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom", + }; + if let Some(l) = self.badge_cache.get(hud_key) { + let pill_h = 20.0; + out.push(Primitive::RoundedRect { + rect: [8.0, h - pill_h - 6.0, w - 8.0, h - 6.0], + radius: 4.0, + stroke: None, + color: [self.palette.bg[0] * 0.75, self.palette.bg[1] * 0.75, self.palette.bg[2] * 0.75, 0.86], + }); + out.push(Primitive::Text { + text: l as &dyn Glyphs, + origin: [14.0, h - pill_h - 2.5], + clip: Some([12.0, h - pill_h - 6.0, w - 12.0, h - 6.0]), + ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim }, + }); + } + + out + } +} + +/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border). +fn input_arrow_svg(edge: Edge, large: bool) -> &'static str { + match (edge, large) { + (Edge::Left, true) => "M 0 0 L -6.5 -3.6 L -6.5 3.6 Z", + (Edge::Left, false) => "M 0 0 L -4.5 -2.6 L -4.5 2.6 Z", + (Edge::Right, true) => "M 0 0 L 6.5 -3.6 L 6.5 3.6 Z", + (Edge::Right, false) => "M 0 0 L 4.5 -2.6 L 4.5 2.6 Z", + (Edge::Top, true) => "M 0 0 L -3.6 -6.5 L 3.6 -6.5 Z", + (Edge::Top, false) => "M 0 0 L -2.6 -4.5 L 2.6 -4.5 Z", + (Edge::Bottom, true) => "M 0 0 L -3.6 6.5 L 3.6 6.5 Z", + (Edge::Bottom, false) => "M 0 0 L -2.6 4.5 L 2.6 4.5 Z", + } +} + +/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect. +fn closest_edge(dx: f32, dy: f32) -> Edge { + // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right + // while vertical stacks naturally snap Top/Bottom! + if dx.abs() * 0.58 >= dy.abs() { + if dx >= 0.0 { Edge::Right } else { Edge::Left } + } else if dy >= 0.0 { + Edge::Bottom + } else { + Edge::Top + } +} + +/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed. +fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge { + let primary = closest_edge(dx_to_src, dy_to_src); + match role { + PortRole::Mask => { + // Masks prefer Top/Bottom unless directly horizontal + if dy_to_src.abs() >= dx_to_src.abs() * 0.35 { + if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top } + } else { + primary + } + } + _ => primary, + } +} + +fn port_color(role: PortRole) -> [f32; 4] { + match role { + PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold + PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green + PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue + PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan + PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet + } +} + +fn node_accent(kind: &str) -> [f32; 4] { + match kind { + "Loader" | "Saver" => [0.32, 0.72, 0.92, 1.0], + "Merge" | "Switch" | "Fuse.Switch" => [0.58, 0.60, 0.66, 1.0], + "Background" | "FastNoise" => [0.36, 0.80, 0.42, 1.0], + "TextPlus" | "Text3D" => [0.34, 0.86, 0.54, 1.0], + "ColorCorrector" | "BrightnessContrast" | "ColorCurves" | "HueCurves" | "LumaKeyer" | "UltraKeyer" => { + [0.92, 0.58, 0.22, 1.0] + } + "Blur" | "DirectionalBlur" | "Glow" | "SoftGlow" | "Displace" | "ErodeDilate" => { + [0.92, 0.52, 0.24, 1.0] + } + "Transform" | "Scale" | "Crop" | "TimeStretcher" | "TimeSpeed" => [0.84, 0.66, 0.28, 1.0], + "EllipseMask" | "RectangleMask" | "PolylineMask" | "BitmapMask" => [0.32, 0.62, 0.98, 1.0], + k if k.starts_with("Fuse.") => [0.88, 0.44, 0.76, 1.0], + _ => [0.54, 0.54, 0.60, 1.0], + } +} + +fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 { + let stub = (8.0 * zoom).clamp(4.0, 11.0); + let an = ae.normal(); + let bn = be.normal(); + let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub]; + let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub]; + dist_to_seg(pt, a, a_out) + .min(dist_to_seg(pt, a_out, b_out)) + .min(dist_to_seg(pt, b_out, b)) +} + +fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { + let ab = [b[0] - a[0], b[1] - a[1]]; + let len2 = ab[0] * ab[0] + ab[1] * ab[1]; + let t = if len2 < 1e-6 { + 0.0 + } else { + (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / len2).clamp(0.0, 1.0) + }; + let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; + ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() +} diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..7936f188d2ae34f13a6802b15a8f31191b8dcdba --- /dev/null +++ b/crates/model/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "model" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[dependencies] +mlua.workspace = true diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs new file mode 100644 index 0000000000000000000000000000000000000000..2466348134143d54a79953d098978ccd21dd6e07 --- /dev/null +++ b/crates/model/src/comp.rs @@ -0,0 +1,1246 @@ +//! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing. + +use crate::expr::ExprEngine; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; +use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2}; +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct NodeId(pub usize); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PortRole { + Background, // Gold / yellow (Fusion main input) + Foreground, // Green + Mask, // Blue (EffectMask) + Aux, // Purple / grey + Scene3D, // Cyan +} + +impl PortRole { + pub fn from_input_name(name: &str) -> Self { + match name { + "EffectMask" | "GarbageMatte" | "SolidMatte" | "Mask" => Self::Mask, + "Foreground" | "Image2" => Self::Foreground, + "SceneInput" | "SceneInput1" | "SceneInput2" | "SceneInput3" | "SceneInput4" => { + Self::Scene3D + } + "Background" | "Input" | "Image" | "Image1" => Self::Background, + _ => Self::Aux, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ParamValue { + Number(f64), + Point([f64; 2]), + Text(String), + FuId(String), + Gradient(Gradient), + Raw(LuaValue), +} + +impl ParamValue { + pub fn as_f64(&self) -> Option { + match self { + ParamValue::Number(n) => Some(*n), + _ => None, + } + } + + pub fn as_point(&self) -> Option<[f64; 2]> { + match self { + ParamValue::Point(p) => Some(*p), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + ParamValue::Text(s) | ParamValue::FuId(s) => Some(s.as_str()), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct InputBinding { + pub value: Option, + pub source_op: Option, + pub source_output: Option, + pub expression: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ClipSpec { + pub filename: String, + pub alternate_filename: Option, + pub start_frame: i64, + pub length: Option, + pub trim_in: i64, + pub trim_out: i64, + pub global_start: i64, + pub global_end: i64, + pub extend_first: i64, + pub extend_last: i64, + pub loop_clip: bool, + pub reverse: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Node { + pub id: NodeId, + pub name: String, + /// Original Fusion operator class name (e.g. `"Merge"`, `"Fuse.Colorize"`, `"TextPlus"`). + pub kind: String, + /// Position in Flow coordinates (Fusion `ViewInfo.Pos`). + pub pos: [f32; 2], + pub bypassed: bool, + /// True for internal tools unpacked from a MacroOperator/GroupOperator (hidden from top-level Flow). + pub internal: bool, + /// For MacroOperator / GroupOperator nodes, the internal tool that produces this macro's output. + pub macro_output: Option, + pub inputs: HashMap, + /// Ordered list of image/mask connection ports (`(input_name, source_node_name, source_port)`). + pub clips: Vec, + /// Preserved raw Lua table for lossless roundtrip / debugging. + pub raw: LuaTable, +} + +impl Node { + /// Returns all image/mask connections targeting another flow node. + pub fn image_connections(&self, node_names: &HashSet) -> Vec<(String, String, PortRole)> { + let mut out = Vec::new(); + for (port, binding) in &self.inputs { + if let Some(src) = &binding.source_op { + if node_names.contains(src) { + let role = PortRole::from_input_name(port); + out.push((port.clone(), src.clone(), role)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out + } + + /// Returns static number value if present. + pub fn static_number(&self, name: &str) -> Option { + self.inputs.get(name)?.value.as_ref()?.as_f64() + } + + pub fn static_str(&self, name: &str) -> Option<&str> { + self.inputs.get(name)?.value.as_ref()?.as_str() + } + + pub fn static_point(&self, name: &str) -> Option<[f64; 2]> { + self.inputs.get(name)?.value.as_ref()?.as_point() + } + + pub fn connected_node(&self, port: &str) -> Option<&str> { + self.inputs.get(port)?.source_op.as_deref() + } +} + +/// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`). +/// Common Fusion property IDs: `1350` = Character X offset, `1351` = Character Y offset. +#[derive(Clone, Debug, PartialEq)] +pub struct ClsEntry { + pub prop_id: u32, + pub start: usize, + pub end: usize, + pub value: f32, +} + +#[derive(Clone, Debug)] +pub struct Comp { + pub path: Option, + pub name: String, + pub width: u32, + pub height: u32, + pub fps: f64, + pub current_time: f64, + pub global_range: [i64; 2], + pub render_range: [i64; 2], + pub audio_filename: Option, + pub audio_offset: f64, + /// Flow operators (excludes BezierSpline / PolyPath / LUTBezier modifiers). + pub nodes: Vec, + pub node_by_name: HashMap, + /// Animation splines keyed by Fusion modifier tool name (e.g. `"Merge6Blend"`). + pub splines: HashMap, + /// 2D PolyPath animation modifiers keyed by name (e.g. `"Path5"`). + pub poly_paths: HashMap, + /// Animated gradients (stored as a spline-like modifier with keyframes of Gradients or static). + pub gradient_modifiers: HashMap>, + /// Text modifiers such as `StyledTextCLS` (`CharacterLevelStyling1`) keyed by name. + pub text_modifiers: HashMap, + /// Keyframed `StyledText` splines (`BezierSpline` with `Value = Text { Value = "..." }`). + pub text_splines: HashMap>, + /// Keyframed `Polyline` splines (`BezierSpline` with `Value = Polyline { Points = ... }`). + pub polyline_splines: HashMap)>)>, + /// Per-character styling overrides from `StyledTextCLS` keyed by modifier name. + pub text_cls: HashMap>, + /// Generation counter incremented whenever any node, wire, or spline mutates. + pub revision: u64, +} + +const MODIFIER_TYPES: &[&str] = &[ + "BezierSpline", + "LUTBezier", + "PolyPath", + "Path", + "XYPath", + "Shake", + "Perturb", + "Expression", + "StyledTextCLS", + "CharacterLevelStyling", + "Follower", + "TrackerModifier", + "PublishNumber", + "PublishPoint", + "Calculation", + "TimeCode", + "Offset", + "Probe", + "FromImage", + "AnimCurves", + "GradientModifier", +]; + +fn is_modifier_type(kind: &str) -> bool { + MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier") +} + +impl Comp { + pub fn from_fusion_file(path: impl AsRef) -> Result> { + let path = path.as_ref(); + let bytes = std::fs::read(path)?; + let text = String::from_utf8_lossy(&bytes); + let mut comp = Self::from_fusion_str(&text)?; + comp.path = Some(path.to_path_buf()); + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + comp.name = stem.to_owned(); + } + Ok(comp) + } + + pub fn from_fusion_str(text: &str) -> Result { + let root_val = parse_lua(text)?; + let root = root_val + .as_table() + .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?; + + let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); + let global_range = root + .get_table("GlobalRange") + .and_then(read_vec2) + .map(|[a, b]| [a as i64, b as i64]) + .unwrap_or([0, 1000]); + let render_range = root + .get_table("RenderRange") + .and_then(read_vec2) + .map(|[a, b]| [a as i64, b as i64]) + .unwrap_or(global_range); + let audio_filename = root.get_str("AudioFilename").map(str::to_owned); + let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0); + + // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps) + let mut width = 1920u32; + let mut height = 1080u32; + let mut fps = 30.0_f64; + if let Some(ff) = root + .get_table("Prefs") + .and_then(|p| p.get_table("Comp")) + .and_then(|c| c.get_table("FrameFormat")) + { + if let Some(w) = ff.get_f64("Width") { + width = w.round().max(1.0) as u32; + } + if let Some(h) = ff.get_f64("Height") { + height = h.round().max(1.0) as u32; + } + if let Some(r) = ff.get_f64("Rate") { + if r > 0.0 { + fps = r; + } + } + } + + let mut nodes = Vec::new(); + let mut node_by_name = HashMap::new(); + let mut splines = HashMap::new(); + let mut poly_paths = HashMap::new(); + let mut gradient_modifiers = HashMap::new(); + let mut text_modifiers = HashMap::new(); + let mut text_splines = HashMap::new(); + let mut polyline_splines = HashMap::new(); + let mut text_cls = HashMap::new(); + let mut tracker_aliases: Vec<(String, String)> = Vec::new(); + let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); + let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); + + if let Some(tools) = root.get_table("Tools") { + parse_tools_table( + tools, + false, + &mut nodes, + &mut node_by_name, + &mut splines, + &mut poly_paths, + &mut gradient_modifiers, + &mut text_modifiers, + &mut text_splines, + &mut polyline_splines, + &mut text_cls, + &mut tracker_aliases, + &mut macro_defaults, + &mut instanced_from, + ); + } + + // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths` + for (tracker_name, src_path) in tracker_aliases { + if let Some(pp) = poly_paths.get(&src_path).cloned() { + poly_paths.insert(tracker_name, pp); + } + } + + // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. + for (target_op, target_param, val) in macro_defaults { + if let Some(&nid) = node_by_name.get(&target_op) { + let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() { + entry.value = Some(val); + } + } + } + + // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets + // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. + let node_inputs_snapshot: Vec<(String, HashMap)> = nodes + .iter() + .map(|n| (n.name.clone(), n.inputs.clone())) + .collect(); + let snap_map: HashMap> = node_inputs_snapshot.into_iter().collect(); + for n in &mut nodes { + if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { + let mut flow_wires = HashMap::new(); + for (in_name, b) in &n.inputs { + if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) { + if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) { + if let Some(ext_src) = &inner_in.source_op { + // Only connect if ext_src is a visible (non-internal) flow node + if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) { + let port_name = if in_name.starts_with("MainInput") || in_name == "Input" { + "Input".to_owned() + } else { + in_name.clone() + }; + flow_wires.insert( + port_name, + InputBinding { + value: None, + source_op: Some(ext_src.clone()), + source_output: inner_in.source_output.clone(), + expression: None, + }, + ); + } + } + } + } + } + if !flow_wires.is_empty() { + n.inputs = flow_wires; + } + } + } + + // Resolve Fusion instanced tools (e.g. `Instance_ColorGain1 = ColorGain { SourceOp = "ColorGain1" }`) + for (nid, master_name) in instanced_from { + if let Some(&mid) = node_by_name.get(&master_name) { + if mid != nid { + let master_inputs = nodes[mid.0].inputs.clone(); + let inst_inputs = &mut nodes[nid.0].inputs; + for (k, mb) in master_inputs { + let empty = inst_inputs.get(&k).is_none_or(|b| { + b.value.is_none() && b.source_op.is_none() && b.expression.is_none() + }); + if empty { + inst_inputs.insert(k, mb); + } + } + } + } + } + + // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height + if width == 1920 && height == 1080 { + for n in &nodes { + if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") { + if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) { + if w >= 64.0 && h >= 64.0 { + width = w as u32; + height = h as u32; + break; + } + } + } + } + } + + Ok(Self { + path: None, + name: "Untitled".to_owned(), + width, + height, + fps, + current_time, + global_range, + render_range, + audio_filename, + audio_offset, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + revision: 1, + }) + } + + /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`). + pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option> { + let (spline, kfs) = self.polyline_splines.get(name)?; + if kfs.is_empty() { + return None; + } + if kfs.len() == 1 || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + if time >= kfs[kfs.len() - 1].0 { + return Some(kfs[kfs.len() - 1].1.clone()); + } + // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing. + let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64); + let idx = (u.floor() as usize).min(kfs.len() - 2); + let frac = (u - idx as f64).clamp(0.0, 1.0); + let a = &kfs[idx].1; + let b = &kfs[idx + 1].1; + if a.len() != b.len() || frac <= 1e-6 { + return Some(a.clone()); + } + if frac >= 1.0 - 1e-6 { + return Some(b.clone()); + } + let lerp = |x: f64, y: f64| x + (y - x) * frac; + Some( + a.iter() + .zip(b.iter()) + .map(|(pa, pb)| crate::spline::PolyPoint { + x: lerp(pa.x, pb.x), + y: lerp(pa.y, pb.y), + lx: lerp(pa.lx, pb.lx), + ly: lerp(pa.ly, pb.ly), + rx: lerp(pa.rx, pb.rx), + ry: lerp(pa.ry, pb.ry), + linear: pa.linear && pb.linear, + }) + .collect(), + ) + } + + pub fn node(&self, id: NodeId) -> &Node { + &self.nodes[id.0] + } + + pub fn node_mut(&mut self, id: NodeId) -> &mut Node { + self.revision += 1; + &mut self.nodes[id.0] + } + + pub fn find_node(&self, name: &str) -> Option { + self.node_by_name.get(name).copied() + } + + /// Picks the default output node to view (the input of `Saver1`/first `Saver`, or the last `Merge`). + pub fn default_output_node(&self) -> Option { + // Prefer the upstream input of the first Saver (or Saver itself) + for n in &self.nodes { + if n.kind == "Saver" { + if let Some(src) = n.connected_node("Input").and_then(|s| self.find_node(s)) { + return Some(src); + } + return Some(n.id); + } + } + // Fallback: non-internal node with no outgoing connections, preferring the last sink (ColorCorrector/Merge) + let mut has_consumer = HashSet::new(); + let names: HashSet = self.node_by_name.keys().cloned().collect(); + for n in &self.nodes { + for (_, src, _) in n.image_connections(&names) { + has_consumer.insert(src); + } + } + let non_internal_sinks = || { + self.nodes + .iter() + .rev() + .filter(|n| !n.internal && !has_consumer.contains(&n.name)) + }; + non_internal_sinks() + .find(|n| matches!(n.kind.as_str(), "ColorCorrector" | "BrightnessContrast" | "Merge")) + .or_else(|| non_internal_sinks().next()) + .or_else(|| self.nodes.iter().rev().find(|n| !n.internal)) + .or_else(|| self.nodes.last()) + .map(|n| n.id) + } + + /// Returns all `(param_label, spline_name)` animated channels attached to `node_id` + /// (including `PolyPath`'s `Displacement` spline!). + pub fn node_splines(&self, node_id: NodeId) -> Vec<(String, String)> { + let Some(node) = self.nodes.get(node_id.0) else { return Vec::new() }; + let mut out = Vec::new(); + for (param, binding) in &node.inputs { + if let Some(src) = &binding.source_op { + if self.splines.contains_key(src) { + out.push((param.clone(), src.clone())); + } else if let Some(pp) = self.poly_paths.get(src) { + if let Some(disp) = &pp.displacement_op { + if self.splines.contains_key(disp) { + out.push((format!("{param} (Path)"), disp.clone())); + } + } + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out + } + + /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`. + pub fn eval_number( + &self, + node: &Node, + param: &str, + time: f64, + default: f64, + expr_engine: &ExprEngine, + ) -> f64 { + let Some(binding) = node.inputs.get(param) else { + return default; + }; + if let Some(expr) = &binding.expression { + if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) { + if v.is_finite() { + return v; + } + } + } + if let Some(src) = &binding.source_op { + if let Some(sp) = self.splines.get(src) { + return sp.eval(time); + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_f64) + .unwrap_or(default) + } + + /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`. + pub fn eval_point( + &self, + node: &Node, + param: &str, + time: f64, + default: [f64; 2], + expr_engine: &ExprEngine, + ) -> [f64; 2] { + let Some(binding) = node.inputs.get(param) else { + return default; + }; + if let Some(expr) = &binding.expression { + if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) { + return p; + } + } + if let Some(src) = &binding.source_op { + if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + return pp.eval_center(disp); + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_point) + .unwrap_or(default) + } + + pub fn eval_text( + &self, + node: &Node, + param: &str, + time: f64, + default: &str, + expr_engine: &ExprEngine, + ) -> String { + let Some(binding) = node.inputs.get(param) else { + return default.to_owned(); + }; + if let Some(expr) = &binding.expression { + let (sp, spts, en) = self.collect_expr_env(node, time); + if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) { + return s; + } + } + if let Some(src) = &binding.source_op { + if let Some(kfs) = self.text_splines.get(src) { + if !kfs.is_empty() { + let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); + return kfs[idx].1.clone(); + } + } + if let Some(txt) = self.text_modifiers.get(src) { + return txt.clone(); + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_str) + .unwrap_or(default) + .to_owned() + } + + pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] { + node.inputs + .get(param) + .and_then(|b| b.source_op.as_deref()) + .and_then(|src| self.text_cls.get(src)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } + + pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option { + let binding = node.inputs.get(param)?; + if let Some(src) = &binding.source_op { + if let Some(kfs) = self.gradient_modifiers.get(src) { + if kfs.is_empty() { + return None; + } + if kfs.len() == 1 || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + let last = &kfs[kfs.len() - 1]; + if time >= last.0 { + return Some(last.1.clone()); + } + let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); + let (t0, g0) = &kfs[idx]; + let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)]; + let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32; + // Bake 17 blended stops across [0..1] + let mut stops = Vec::with_capacity(17); + for i in 0..=16 { + let p = i as f64 / 16.0; + let a = g0.sample(p); + let b = g1.sample(p); + stops.push(crate::spline::GradientStop { + pos: p, + rgba: [ + a[0] + (b[0] - a[0]) * f, + a[1] + (b[1] - a[1]) * f, + a[2] + (b[2] - a[2]) * f, + a[3] + (b[3] - a[3]) * f, + ], + }); + } + return Some(Gradient { stops }); + } + } + if let Some(ParamValue::Gradient(g)) = &binding.value { + return Some(g.clone()); + } + None + } + + fn collect_expr_env( + &self, + node: &Node, + time: f64, + ) -> ( + HashMap, + HashMap, + HashMap>, + ) { + let mut self_params = HashMap::new(); + let mut self_points = HashMap::new(); + for (k, b) in &node.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + self_params.insert(k.clone(), v); + } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) { + self_points.insert(k.clone(), pt); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + self_params.insert(k.clone(), sp.eval(time)); + } else if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + self_points.insert(k.clone(), pp.eval_center(disp)); + } + } + } + let mut env_nodes = HashMap::new(); + for n in &self.nodes { + let mut m = HashMap::new(); + for (k, b) in &n.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + m.insert(k.clone(), v); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + m.insert(k.clone(), sp.eval(time)); + } + } + } + if !m.is_empty() { + env_nodes.insert(n.name.clone(), m); + } + } + (self_params, self_points, env_nodes) + } + + fn eval_expr_number( + &self, + node: &Node, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + ) -> Option { + let needs_nodes = expr.contains('.') + || expr.trim_start().starts_with(':') + || expr + .split(|c: char| !c.is_alphanumeric() && c != '_') + .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok)); + if !needs_nodes { + let empty_self = HashMap::new(); + let empty_pts = HashMap::new(); + let empty_env = HashMap::new(); + return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env); + } + let (sp, spts, en) = self.collect_expr_env(node, time); + expr_engine.eval_number(expr, time, &sp, &spts, &en) + } + + fn eval_expr_point( + &self, + node: &Node, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + ) -> Option<[f64; 2]> { + let (sp, spts, en) = self.collect_expr_env(node, time); + expr_engine.eval_point(expr, time, &sp, &spts, &en) + } + + /// Connects `src` node's output to `dst` node's `port` input. + pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) { + if src == dst { + return; + } + let src_name = self.nodes[src.0].name.clone(); + let entry = self.nodes[dst.0] + .inputs + .entry(port.to_owned()) + .or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.source_op = Some(src_name); + entry.source_output = Some("Output".to_owned()); + self.revision += 1; + } + + /// Disconnects `dst` node's `port` input. + pub fn disconnect(&mut self, dst: NodeId, port: &str) { + if let Some(entry) = self.nodes[dst.0].inputs.get_mut(port) { + entry.source_op = None; + entry.source_output = None; + self.revision += 1; + } + } + + /// Inserts `mid` node cleanly onto the wire `src -> dst.dst_port`! + /// Wires `src -> mid.(default_input)` and `mid -> dst.dst_port`. + pub fn insert_on_wire(&mut self, mid: NodeId, src: NodeId, dst: NodeId, dst_port: &str) { + if mid == src || mid == dst { + return; + } + let mid_port = default_main_input_port(&self.nodes[mid.0].kind); + self.connect(src, mid, mid_port); + self.connect(mid, dst, dst_port); + } + + /// Toggles bypass (`PassThrough`) on a node. + pub fn toggle_bypass(&mut self, id: NodeId) { + self.nodes[id.0].bypassed = !self.nodes[id.0].bypassed; + self.revision += 1; + } +} + +pub fn default_main_input_port(kind: &str) -> &'static str { + match kind { + "Merge" => "Background", + "Fuse.Colorize" | "Fuse.Outline" => "Image", + "Custom" => "Image1", + _ => "Input", + } +} + +fn parse_input_binding(t: &LuaTable) -> InputBinding { + let source_op = t.get_str("SourceOp").map(str::to_owned); + let source_output = t.get_str("Source").map(str::to_owned); + let expression = t.get_str("Expression").map(str::to_owned); + + let value = t.get("Value").map(parse_param_value); + InputBinding { + value, + source_op, + source_output, + expression, + } +} + +fn parse_param_value(v: &LuaValue) -> ParamValue { + match v { + LuaValue::Number(n) => ParamValue::Number(*n), + LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }), + LuaValue::String(s) => ParamValue::Text(s.clone()), + LuaValue::Table(t) => match t.tag.as_deref() { + Some("FuID") => ParamValue::FuId( + t.get_index(1) + .and_then(LuaValue::as_str) + .unwrap_or("") + .to_owned(), + ), + Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)), + Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)), + _ => { + if let Some(p) = read_vec2(t) { + ParamValue::Point(p) + } else { + ParamValue::Raw(v.clone()) + } + } + }, + LuaValue::Nil => ParamValue::Raw(LuaValue::Nil), + } +} + +fn try_parse_gradient_keyframes(table: &LuaTable) -> Option> { + let kfs = table.get_table("KeyFrames")?; + let mut grads = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt + .get_table("Value") + .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?; + if val.tag.as_deref() == Some("Gradient") { + grads.push((time, Gradient::from_lua(val))); + } else { + return None; + } + } + if grads.is_empty() { + return None; + } + grads.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(grads) +} + +fn try_parse_text_keyframes(table: &LuaTable) -> Option> { + let kfs = table.get_table("KeyFrames")?; + let mut texts = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt.get_table("Value")?; + if val.tag.as_deref() == Some("Text") { + let s = val.get_str("Value").unwrap_or("").to_owned(); + texts.push((time, s)); + } else { + return None; + } + } + if texts.is_empty() { + return None; + } + texts.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(texts) +} + +fn try_parse_polyline_keyframes(table: &LuaTable) -> Option)>> { + let kfs = table.get_table("KeyFrames")?; + let mut shapes = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt.get_table("Value")?; + if val.tag.as_deref() == Some("Polyline") { + let (_, pts) = PolyPath::parse_polyline_table(val); + shapes.push((time, pts)); + } else { + return None; + } + } + if shapes.is_empty() { + return None; + } + shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(shapes) +} + +#[allow(clippy::too_many_arguments)] +fn parse_tools_table( + tools: &LuaTable, + is_internal: bool, + nodes: &mut Vec, + node_by_name: &mut HashMap, + splines: &mut HashMap, + poly_paths: &mut HashMap, + gradient_modifiers: &mut HashMap>, + text_modifiers: &mut HashMap, + text_splines: &mut HashMap>, + polyline_splines: &mut HashMap)>)>, + text_cls: &mut HashMap>, + tracker_aliases: &mut Vec<(String, String)>, + macro_defaults: &mut Vec<(String, String, ParamValue)>, + instanced_from: &mut Vec<(NodeId, String)>, +) { + for (key, val) in &tools.entries { + let LuaKey::Str(name) = key else { continue }; + let Some(tbl) = val.as_table() else { continue }; + let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned()); + + if kind == "BezierSpline" || kind == "LUTBezier" { + if let Some(grads) = try_parse_gradient_keyframes(tbl) { + gradient_modifiers.insert(name.clone(), grads); + } else if let Some(txts) = try_parse_text_keyframes(tbl) { + text_splines.insert(name.clone(), txts); + } else if let Some(polys) = try_parse_polyline_keyframes(tbl) { + polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys)); + } else { + splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); + } + continue; + } + if kind == "PolyPath" || kind == "Path" { + poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); + continue; + } + if kind == "TrackerModifier" { + if let Some(in_tbl) = tbl.get_table("Inputs") { + if let Some(src_op) = in_tbl + .get_table("TrackedCenter0") + .and_then(|c| c.get_str("SourceOp")) + { + tracker_aliases.push((name.clone(), src_op.to_owned())); + } else if let Some(p) = in_tbl + .get_table("PatternCenter0") + .and_then(|c| c.get_table("Value")) + .and_then(read_vec2) + { + poly_paths.insert( + name.clone(), + PolyPath { + name: name.clone(), + displacement_op: None, + displacement_value: 0.0, + closed: false, + points: vec![crate::spline::PolyPoint { + x: p[0] - 0.5, + y: p[1] - 0.5, + lx: 0.0, + ly: 0.0, + rx: 0.0, + ry: 0.0, + linear: true, + }], + }, + ); + } + } + continue; + } + if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { + if let Some(in_tbl) = tbl.get_table("Inputs") { + if let Some(txt) = in_tbl + .get_table("Text") + .or_else(|| in_tbl.get_table("StyledText")) + .and_then(|s| s.get_str("Value")) + { + text_modifiers.insert(name.clone(), txt.to_owned()); + } + if let Some(arr) = in_tbl + .get_table("CharacterLevelStyling") + .and_then(|c| c.get_table("Value")) + .and_then(|v| v.get_table("Array")) + { + let mut entries = Vec::new(); + for (_, ev) in &arr.entries { + let Some(et) = ev.as_table() else { continue }; + let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue }; + let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue }; + let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue }; + let Some(val) = et.get_f64("Value") else { continue }; + entries.push(ClsEntry { + prop_id: pid.round().max(0.0) as u32, + start: s.round().max(0.0) as usize, + end: e.round().max(0.0) as usize, + value: val as f32, + }); + } + if !entries.is_empty() { + text_cls.insert(name.clone(), entries); + } + } + } + continue; + } + if is_modifier_type(&kind) { + if tbl.get_table("KeyFrames").is_some() { + splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); + } + continue; + } + + let pos = tbl + .get_table("ViewInfo") + .and_then(|vi| vi.get_table("Pos")) + .and_then(read_vec2) + .map(|[x, y]| [x as f32, y as f32]) + .unwrap_or([0.0, 0.0]); + let bypassed = tbl.get_bool("PassThrough").unwrap_or(false); + + let mut inputs = HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (ik, iv) in &in_tbl.entries { + let LuaKey::Str(in_name) = ik else { continue }; + let Some(it) = iv.as_table() else { continue }; + let binding = parse_input_binding(it); + if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { + if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) { + if let Some(def_v) = it.get("Default") { + macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v))); + } + } + } + inputs.insert(in_name.clone(), binding); + } + } + + // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.) + if let Some(uc) = tbl.get_table("UserControls") { + for (uk, uv) in &uc.entries { + let LuaKey::Str(uname) = uk else { continue }; + let Some(ut) = uv.as_table() else { continue }; + let missing = inputs.get(uname).is_none_or(|b| { + b.value.is_none() && b.source_op.is_none() && b.expression.is_none() + }); + if missing { + let is_point = ut.get_str("LINKID_DataType") == Some("Point") + || ut.get_str("INPID_InputControl") == Some("OffsetControl"); + let def_val = if is_point { + let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); + let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); + Some(ParamValue::Point([dx, dy])) + } else { + ut.get("INP_Default").map(parse_param_value) + }; + if let Some(val) = def_val { + inputs.insert( + uname.clone(), + InputBinding { + value: Some(val), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + } + } + } + + let mut clips = Vec::new(); + if let Some(clips_tbl) = tbl.get_table("Clips") { + for (_, cv) in &clips_tbl.entries { + if let Some(ct) = cv.as_table() { + if let Some(filename) = ct.get_str("Filename") { + clips.push(ClipSpec { + filename: filename.to_owned(), + alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned), + start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64, + length: ct.get_f64("Length").map(|v| v as i64), + trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64, + trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64, + global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64, + global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64, + extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64, + extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64, + loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5, + reverse: ct.get_bool("Reverse").unwrap_or(false), + }); + } + } + } + } + + if kind == "Saver" && clips.is_empty() { + if let Some(c) = tbl + .get_table("Inputs") + .and_then(|i| i.get_table("Clip")) + .and_then(|c| c.get_table("Value")) + { + if let Some(filename) = c.get_str("Filename") { + clips.push(ClipSpec { + filename: filename.to_owned(), + alternate_filename: None, + start_frame: 0, + length: None, + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }); + } + } + } + + // ColorCurves embeds its R/G/B/A LUTBezier splines inside a nested `Tools` table! + if kind == "ColorCurves" { + if let Some(inner_tools) = tbl.get_table("Tools") { + parse_tools_table( + inner_tools, + true, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + tracker_aliases, + macro_defaults, + instanced_from, + ); + } + } + + let mut macro_output = None; + if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { + let mut out_name: Option = None; + if let Some(outs) = tbl.get_table("Outputs") { + for (_, ov) in &outs.entries { + if let Some(ot) = ov.as_table() { + if let Some(src_op) = ot.get_str("SourceOp") { + out_name = Some(src_op.to_owned()); + break; + } + } + } + } + let inner_start = nodes.len(); + if let Some(inner_tools) = tbl.get_table("Tools") { + parse_tools_table( + inner_tools, + true, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + tracker_aliases, + macro_defaults, + instanced_from, + ); + } + if let Some(oname) = out_name { + macro_output = nodes[inner_start..] + .iter() + .find(|n| n.name == oname) + .map(|n| n.id) + .or_else(|| node_by_name.get(&oname).copied()); + } + } + + let id = NodeId(nodes.len()); + // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name. + if !is_internal || !node_by_name.contains_key(name) { + node_by_name.insert(name.clone(), id); + } + if let Some(master) = tbl.get_str("SourceOp") { + instanced_from.push((id, master.to_owned())); + } + nodes.push(Node { + id, + name: name.clone(), + kind, + pos, + bypassed, + internal: is_internal, + macro_output, + inputs, + clips, + raw: tbl.clone(), + }); + } +} diff --git a/crates/model/src/expr.rs b/crates/model/src/expr.rs new file mode 100644 index 0000000000000000000000000000000000000000..11aec17fd156bb37b7352c6f9a35fc5710a413d4 --- /dev/null +++ b/crates/model/src/expr.rs @@ -0,0 +1,171 @@ +//! Fusion SimpleExpression evaluator backed by `mlua` (Lua 5.4). +//! +//! Supports Fusion globals (`time`, `iif`, `Point`, `Text`, `sin`/`cos`/`floor`/`ceil`/etc.) +//! and `NodeName.ParamName` lookups without requiring full Fusion runtime scripting. + +use mlua::{Lua, MultiValue, Value}; +use std::collections::HashMap; + +pub struct ExprEngine { + lua: Lua, +} + +impl Default for ExprEngine { + fn default() -> Self { + Self::new() + } +} + +impl ExprEngine { + pub fn new() -> Self { + let lua = Lua::new(); + // Install Fusion SimpleExpression standard library into global scope. + let init = r#" + abs = math.abs + acos = math.acos + asin = math.asin + atan = math.atan + atan2 = math.atan + ceil = math.ceil + cos = math.cos + cosh = function(x) return (math.exp(x) + math.exp(-x)) * 0.5 end + deg = math.deg + exp = math.exp + floor = math.floor + fmod = math.fmod + log = math.log + log10 = function(x) return math.log(x, 10) end + max = math.max + min = math.min + mod = math.fmod + pi = math.pi + pow = function(a, b) return a ^ b end + rad = math.rad + sin = math.sin + sinh = function(x) return (math.exp(x) - math.exp(-x)) * 0.5 end + sqrt = math.sqrt + tan = math.tan + tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end + iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end + Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end + Text = function(s) return tostring(s or "") end + clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end + mix = function(a, b, t) return a + (b - a) * t end + "#; + let _ = lua.load(init).exec(); + Self { lua } + } + + fn expr_chunk(expr: &str) -> String { + let trimmed = expr.trim_start(); + if let Some(body) = trimmed.strip_prefix(':') { + body.to_owned() + } else { + format!("return ({expr})") + } + } + + /// Evaluates a Fusion SimpleExpression returning a number. + /// `env_nodes` provides `node_name -> (param_name -> f64)` and `self_params` provides + /// unqualified parameter names on the current node. + pub fn eval_number( + &self, + expr: &str, + time: f64, + self_params: &HashMap, + self_points: &HashMap, + env_nodes: &HashMap>, + ) -> Option { + let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; + let chunk = Self::expr_chunk(expr); + let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?; + match val { + Value::Number(n) => Some(n), + Value::Integer(i) => Some(i as f64), + Value::Boolean(b) => Some(if b { 1.0 } else { 0.0 }), + Value::String(s) => s.to_str().ok()?.trim().parse::().ok(), + _ => None, + } + } + + /// Evaluates a Fusion SimpleExpression returning a 2D point `[x, y]`. + pub fn eval_point( + &self, + expr: &str, + time: f64, + self_params: &HashMap, + self_points: &HashMap, + env_nodes: &HashMap>, + ) -> Option<[f64; 2]> { + let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; + let chunk = Self::expr_chunk(expr); + let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?; + if let Value::Table(t) = val { + let x = t.get::("X").or_else(|_| t.get::(1)).ok()?; + let y = t.get::("Y").or_else(|_| t.get::(2)).ok()?; + return Some([x, y]); + } + None + } + + /// Evaluates a Fusion SimpleExpression returning a string. + pub fn eval_string( + &self, + expr: &str, + time: f64, + self_params: &HashMap, + self_points: &HashMap, + env_nodes: &HashMap>, + ) -> Option { + let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; + let chunk = Self::expr_chunk(expr); + let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?; + match val { + Value::String(s) => Some(s.to_str().ok()?.to_owned()), + Value::Number(n) => Some(format!("{n}")), + Value::Integer(i) => Some(format!("{i}")), + _ => None, + } + } + + fn build_env( + &self, + time: f64, + self_params: &HashMap, + self_points: &HashMap, + env_nodes: &HashMap>, + ) -> mlua::Result { + let env = self.lua.create_table()?; + let mt = self.lua.create_table()?; + mt.set("__index", self.lua.globals())?; + env.set_metatable(Some(mt)); + env.set("time", time)?; + env.set("comp", self.lua.create_table()?)?; + for (k, v) in self_params { + env.set(k.as_str(), *v)?; + } + for (k, p) in self_points { + let pt = self.lua.create_table()?; + pt.set("X", p[0])?; + pt.set("Y", p[1])?; + pt.set(1, p[0])?; + pt.set(2, p[1])?; + env.set(k.as_str(), pt)?; + } + for (node_name, params) in env_nodes { + let nt = self.lua.create_table()?; + for (pk, pv) in params { + nt.set(pk.as_str(), *pv)?; + } + // Also default missing fields to 0 so expressions don't nil-crash + let nmt = self.lua.create_table()?; + nmt.set( + "__index", + self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?, + )?; + nt.set_metatable(Some(nmt)); + env.set(node_name.as_str(), nt)?; + } + Ok(env) + } +} diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..4913115e2034cc764a2dfbbda1674a89e9ca322b --- /dev/null +++ b/crates/model/src/lib.rs @@ -0,0 +1,80 @@ +pub mod comp; +pub mod expr; +pub mod lua_value; +pub mod spline; + +pub use comp::{ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, default_main_input_port}; +pub use expr::ExprEngine; +pub use lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; +pub use spline::{BezierSpline, Gradient, GradientStop, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint}; + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + #[test] + fn parses_all_337_real_fusion_comps() { + let mut paths = Vec::new(); + fn collect(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { return }; + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + collect(&p, out); + } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("comp")) { + out.push(p); + } + } + } + collect(Path::new("/Users/clo/dev/compositor/private/samples"), &mut paths); + collect(Path::new("/Volumes/Project/trees/fusion"), &mut paths); + paths.sort(); + assert!(!paths.is_empty(), "expected sample .comp files"); + + let mut failures = Vec::new(); + let mut total_nodes = 0usize; + let mut total_splines = 0usize; + for p in &paths { + match Comp::from_fusion_file(p) { + Ok(comp) => { + total_nodes += comp.nodes.len(); + total_splines += comp.splines.len(); + } + Err(e) => failures.push(format!("{}: {e}", p.display())), + } + } + assert!( + failures.is_empty(), + "failed to parse {}/{} comps:\n{}", + failures.len(), + paths.len(), + failures.join("\n") + ); + eprintln!( + "Parsed {}/{} real .comp files ({total_nodes} nodes, {total_splines} splines) cleanly!", + paths.len(), + paths.len() + ); + } + + #[test] + fn evaluates_20_falling_splines_and_expressions() { + let comp = Comp::from_fusion_file("/Volumes/Project/trees/fusion/20_falling.comp") + .expect("load 20_falling.comp"); + let expr = ExprEngine::new(); + assert_eq!(comp.width, 1920); + assert_eq!(comp.height, 1080); + + let ts = comp.node(comp.find_node("TimeStretcher1_2").unwrap()); + assert_eq!(comp.eval_number(ts, "SourceTime", 2200.0, 0.0, &expr), 2199.0); + + let noise = comp.node(comp.find_node("Noise_3").unwrap()); + assert_eq!(comp.eval_number(noise, "Seethe", 2200.0, 0.0, &expr), 733.0 * 42.0); + + let merge19 = comp.node(comp.find_node("Merge19").unwrap()); + let p0 = comp.eval_point(merge19, "Center", 2318.0, [0.5, 0.5], &expr); + let p1 = comp.eval_point(merge19, "Center", 2361.0, [0.5, 0.5], &expr); + assert!((p0[0] - p1[0]).abs() + (p0[1] - p1[1]).abs() > 1e-4); + } +} diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f58106379f4c59e51d68553323f687aa75e369b --- /dev/null +++ b/crates/model/src/lua_value.rs @@ -0,0 +1,603 @@ +//! Recursive-descent parser for Fusion `.comp` / `.setting` Lua table literals. +//! +//! Handles Fusion's full table syntax including constructor tags (`Composition { ... }`, +//! `ordered() { ... }`, `Input { ... }`, `FuID { ... }`), string/numeric/positional keys, +//! Lua escape sequences, long bracket strings, and line/block comments without executing code. + +use std::fmt; + +#[derive(Clone, Debug, PartialEq)] +pub enum LuaValue { + Nil, + Bool(bool), + Number(f64), + String(String), + Table(LuaTable), +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LuaTable { + /// Optional Fusion constructor tag, e.g. `"Composition"`, `"Input"`, `"Merge"`, `"ordered"`. + pub tag: Option, + /// Ordered entries preserving insertion order (crucial for `ordered()` and `Tools`). + pub entries: Vec<(LuaKey, LuaValue)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum LuaKey { + Index(i64), + Number(f64), + Str(String), +} + +impl LuaTable { + pub fn get(&self, key: &str) -> Option<&LuaValue> { + self.entries.iter().find_map(|(k, v)| match k { + LuaKey::Str(s) if s == key => Some(v), + _ => None, + }) + } + + pub fn get_index(&self, idx: i64) -> Option<&LuaValue> { + self.entries.iter().find_map(|(k, v)| match k { + LuaKey::Index(i) if *i == idx => Some(v), + LuaKey::Number(n) if (*n - idx as f64).abs() < 1e-9 => Some(v), + _ => None, + }) + } + + pub fn get_table(&self, key: &str) -> Option<&LuaTable> { + self.get(key)?.as_table() + } + + pub fn get_str(&self, key: &str) -> Option<&str> { + self.get(key)?.as_str() + } + + pub fn get_f64(&self, key: &str) -> Option { + self.get(key)?.as_f64() + } + + pub fn get_bool(&self, key: &str) -> Option { + self.get(key)?.as_bool() + } + + pub fn positional_values(&self) -> impl Iterator { + self.entries.iter().filter_map(|(k, v)| match k { + LuaKey::Index(_) => Some(v), + _ => None, + }) + } +} + +impl LuaValue { + pub fn as_table(&self) -> Option<&LuaTable> { + match self { + LuaValue::Table(t) => Some(t), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + LuaValue::String(s) => Some(s.as_str()), + _ => None, + } + } + + pub fn as_f64(&self) -> Option { + match self { + LuaValue::Number(n) => Some(*n), + _ => None, + } + } + + pub fn as_bool(&self) -> Option { + match self { + LuaValue::Bool(b) => Some(*b), + _ => None, + } + } + + /// Extracts a Fusion `FuID { "Name" }` or plain string. + pub fn as_fuid(&self) -> Option<&str> { + match self { + LuaValue::String(s) => Some(s.as_str()), + LuaValue::Table(t) => t.get_index(1).and_then(LuaValue::as_str), + _ => None, + } + } +} + +#[derive(Clone, Debug)] +pub struct ParseError { + pub offset: usize, + pub line: usize, + pub message: String, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "line {} (byte {}): {}", self.line, self.offset, self.message) + } +} + +impl std::error::Error for ParseError {} + +pub fn parse_lua(input: &str) -> Result { + let mut parser = Parser::new(input); + parser.skip_ws_and_comments()?; + let val = parser.parse_value()?; + parser.skip_ws_and_comments()?; + Ok(val) +} + +struct Parser<'a> { + src: &'a [u8], + pos: usize, +} + +impl<'a> Parser<'a> { + fn new(input: &'a str) -> Self { + let mut pos = 0; + // Strip UTF-8 BOM if present + if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) { + pos = 3; + } + Self { src: input.as_bytes(), pos } + } + + fn err(&self, msg: impl Into) -> ParseError { + let line = self.src[..self.pos.min(self.src.len())] + .iter() + .filter(|&&b| b == b'\n') + .count() + + 1; + ParseError { + offset: self.pos, + line, + message: msg.into(), + } + } + + fn peek(&self) -> Option { + self.src.get(self.pos).copied() + } + + fn peek_at(&self, delta: usize) -> Option { + self.src.get(self.pos + delta).copied() + } + + fn bump(&mut self) -> Option { + let b = self.peek()?; + self.pos += 1; + Some(b) + } + + fn skip_ws_and_comments(&mut self) -> Result<(), ParseError> { + loop { + while let Some(b) = self.peek() { + if matches!(b, b' ' | b'\t' | b'\r' | b'\n') { + self.pos += 1; + } else { + break; + } + } + if self.peek() == Some(b'-') && self.peek_at(1) == Some(b'-') { + self.pos += 2; + if self.peek() == Some(b'[') { + if let Some(level) = self.try_open_long_bracket() { + self.skip_long_bracket(level)?; + continue; + } + } + while let Some(b) = self.bump() { + if b == b'\n' { + break; + } + } + continue; + } + break; + } + Ok(()) + } + + fn try_open_long_bracket(&mut self) -> Option { + if self.peek() != Some(b'[') { + return None; + } + let mut i = self.pos + 1; + while i < self.src.len() && self.src[i] == b'=' { + i += 1; + } + if i < self.src.len() && self.src[i] == b'[' { + let level = i - (self.pos + 1); + self.pos = i + 1; + Some(level) + } else { + None + } + } + + fn skip_long_bracket(&mut self, level: usize) -> Result { + let start = self.pos; + while self.pos < self.src.len() { + if self.src[self.pos] == b']' { + let mut i = self.pos + 1; + let mut eq = 0; + while i < self.src.len() && self.src[i] == b'=' && eq < level { + i += 1; + eq += 1; + } + if eq == level && i < self.src.len() && self.src[i] == b']' { + let s = String::from_utf8_lossy(&self.src[start..self.pos]).into_owned(); + self.pos = i + 1; + return Ok(s); + } + } + self.pos += 1; + } + Err(self.err("unterminated long bracket string/comment")) + } + + fn parse_value(&mut self) -> Result { + self.skip_ws_and_comments()?; + let Some(b) = self.peek() else { + return Err(self.err("unexpected EOF while parsing value")); + }; + match b { + b'{' => self.parse_table(None).map(LuaValue::Table), + b'"' | b'\'' => self.parse_quoted_string().map(LuaValue::String), + b'[' => { + if let Some(level) = self.try_open_long_bracket() { + // Lua drops a single immediate newline after opening long bracket + if self.peek() == Some(b'\r') && self.peek_at(1) == Some(b'\n') { + self.pos += 2; + } else if self.peek() == Some(b'\n') { + self.pos += 1; + } + let s = self.skip_long_bracket(level)?; + Ok(LuaValue::String(s)) + } else { + Err(self.err("unexpected '['")) + } + } + b'-' | b'+' | b'0'..=b'9' | b'.' => self.parse_number(), + _ if is_ident_start(b) => self.parse_ident_or_constructor(), + other => Err(self.err(format!("unexpected byte 0x{other:02x} ('{}')", other as char))), + } + } + + fn parse_ident_or_constructor(&mut self) -> Result { + let start = self.pos; + while let Some(b) = self.peek() { + if is_ident_cont(b) || b == b'.' { + self.pos += 1; + } else { + break; + } + } + let ident = std::str::from_utf8(&self.src[start..self.pos]) + .map_err(|_| self.err("invalid UTF-8 identifier"))? + .to_owned(); + + match ident.as_str() { + "true" => return Ok(LuaValue::Bool(true)), + "false" => return Ok(LuaValue::Bool(false)), + "nil" => return Ok(LuaValue::Nil), + "inf" | "INF" => return Ok(LuaValue::Number(f64::INFINITY)), + "nan" | "NaN" | "NAN" => return Ok(LuaValue::Number(f64::NAN)), + _ => {} + } + + self.skip_ws_and_comments()?; + + // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)` + if self.peek() == Some(b'(') { + self.pos += 1; + let mut args = Vec::new(); + self.skip_ws_and_comments()?; + if self.peek() != Some(b')') { + loop { + args.push(self.parse_value()?); + self.skip_ws_and_comments()?; + if self.peek() == Some(b',') { + self.pos += 1; + } else { + break; + } + } + } + if self.bump() != Some(b')') { + return Err(self.err(format!("expected ')' after {ident}(..."))); + } + self.skip_ws_and_comments()?; + if self.peek() == Some(b'{') { + let mut table = self.parse_table(Some(ident))?; + // Preserve any call arguments if non-empty + for (i, arg) in args.into_iter().enumerate() { + table.entries.insert(i, (LuaKey::Str(format!("__arg{i}")), arg)); + } + return Ok(LuaValue::Table(table)); + } + // Standalone call like `Point(0.5, 0.5)` or `FuID("Foo")` + let mut table = LuaTable { tag: Some(ident), entries: Vec::new() }; + for (i, arg) in args.into_iter().enumerate() { + table.entries.push((LuaKey::Index((i + 1) as i64), arg)); + } + return Ok(LuaValue::Table(table)); + } + + // Handle constructor `Tag { ... }` or `Tag "str"` + if self.peek() == Some(b'{') { + return self.parse_table(Some(ident)).map(LuaValue::Table); + } + if matches!(self.peek(), Some(b'"' | b'\'')) { + let s = self.parse_quoted_string()?; + let table = LuaTable { + tag: Some(ident), + entries: vec![(LuaKey::Index(1), LuaValue::String(s))], + }; + return Ok(LuaValue::Table(table)); + } + + // Bare identifier (rare, e.g., symbolic constants in old Fusion 9 files) + Ok(LuaValue::String(ident)) + } + + fn parse_table(&mut self, tag: Option) -> Result { + if self.bump() != Some(b'{') { + return Err(self.err("expected '{'")); + } + let mut entries = Vec::new(); + let mut next_index: i64 = 1; + + loop { + self.skip_ws_and_comments()?; + match self.peek() { + None => { + // Gracefully close open tables on truncated/export-clipped `.comp` files. + break; + } + Some(b'}') => { + self.pos += 1; + break; + } + Some(b',') | Some(b';') => { + self.pos += 1; + continue; + } + _ => {} + } + + // Decide between `[expr] = val`, `ident = val`, or positional `val` + if self.peek() == Some(b'[') && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') { + self.pos += 1; // consume '[' + self.skip_ws_and_comments()?; + let key_val = self.parse_value()?; + self.skip_ws_and_comments()?; + if self.bump() != Some(b']') { + return Err(self.err("expected ']' after table key")); + } + self.skip_ws_and_comments()?; + if self.bump() != Some(b'=') { + return Err(self.err("expected '=' after [key]")); + } + let val = self.parse_value()?; + let key = match key_val { + LuaValue::String(s) => LuaKey::Str(s), + LuaValue::Number(n) => { + if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) { + LuaKey::Index(n as i64) + } else { + LuaKey::Number(n) + } + } + other => LuaKey::Str(format!("{other:?}")), + }; + entries.push((key, val)); + } else if let Some((key, saved_pos)) = self.try_ident_equals() { + let _ = saved_pos; + let val = self.parse_value()?; + entries.push((LuaKey::Str(key), val)); + } else { + let val = self.parse_value()?; + entries.push((LuaKey::Index(next_index), val)); + next_index += 1; + } + + self.skip_ws_and_comments()?; + if matches!(self.peek(), Some(b',' | b';')) { + self.pos += 1; + } + } + + Ok(LuaTable { tag, entries }) + } + + fn try_ident_equals(&mut self) -> Option<(String, usize)> { + let saved = self.pos; + let b = self.peek()?; + if !is_ident_start(b) { + return None; + } + let start = self.pos; + while let Some(c) = self.peek() { + if is_ident_cont(c) { + self.pos += 1; + } else { + break; + } + } + let end = self.pos; + let _ = self.skip_ws_and_comments(); + if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') { + self.pos += 1; + let key = std::str::from_utf8(&self.src[start..end]).ok()?.to_owned(); + Some((key, saved)) + } else { + self.pos = saved; + None + } + } + + fn parse_quoted_string(&mut self) -> Result { + let quote = self.bump().ok_or_else(|| self.err("expected quote"))?; + let mut out = Vec::new(); + while let Some(b) = self.bump() { + if b == quote { + return Ok(String::from_utf8_lossy(&out).into_owned()); + } + if b == b'\\' { + let Some(esc) = self.bump() else { + return Err(self.err("unterminated escape sequence")); + }; + match esc { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'\\' => out.push(b'\\'), + b'"' => out.push(b'"'), + b'\'' => out.push(b'\''), + b'a' => out.push(0x07), + b'b' => out.push(0x08), + b'f' => out.push(0x0C), + b'v' => out.push(0x0B), + b'\n' => out.push(b'\n'), + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + out.push(b'\n'); + } + b'z' => { + while let Some(ws) = self.peek() { + if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') { + self.pos += 1; + } else { + break; + } + } + } + b'x' => { + let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; + let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; + let s = [h1, h2]; + let byte = u8::from_str_radix(std::str::from_utf8(&s).unwrap_or("00"), 16) + .map_err(|_| self.err("invalid hex escape"))?; + out.push(byte); + } + b'0'..=b'9' => { + let mut val = (esc - b'0') as u32; + for _ in 0..2 { + if let Some(d @ b'0'..=b'9') = self.peek() { + self.pos += 1; + val = val * 10 + (d - b'0') as u32; + } else { + break; + } + } + out.push((val & 0xFF) as u8); + } + other => out.push(other), + } + } else { + out.push(b); + } + } + Err(self.err("unterminated string literal")) + } + + fn parse_number(&mut self) -> Result { + let start = self.pos; + if matches!(self.peek(), Some(b'-' | b'+')) { + self.pos += 1; + } + // Check for -inf / -nan / -1.#INF / -1.#IND (Windows MSVC Fusion files!) + if self.src[self.pos..].starts_with(b"inf") || self.src[self.pos..].starts_with(b"INF") { + self.pos += 3; + let neg = self.src[start] == b'-'; + return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY })); + } + if self.src[self.pos..].starts_with(b"nan") || self.src[self.pos..].starts_with(b"NaN") || self.src[self.pos..].starts_with(b"NAN") { + self.pos += 3; + return Ok(LuaValue::Number(f64::NAN)); + } + + // Hex integer / float `0x...` + if self.peek() == Some(b'0') && matches!(self.peek_at(1), Some(b'x' | b'X')) { + self.pos += 2; + let hex_start = self.pos; + while let Some(b) = self.peek() { + if b.is_ascii_hexdigit() { + self.pos += 1; + } else { + break; + } + } + let s = std::str::from_utf8(&self.src[hex_start..self.pos]).unwrap_or("0"); + let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64; + let neg = self.src[start] == b'-'; + return Ok(LuaValue::Number(if neg { -v } else { v })); + } + + while let Some(b) = self.peek() { + if b.is_ascii_digit() { + self.pos += 1; + } else { + break; + } + } + if self.peek() == Some(b'.') { + self.pos += 1; + // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN` + if self.peek() == Some(b'#') { + while let Some(b) = self.peek() { + if b.is_ascii_alphanumeric() || b == b'#' { + self.pos += 1; + } else { + break; + } + } + let raw = std::str::from_utf8(&self.src[start..self.pos]).unwrap_or(""); + if raw.contains("INF") { + return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY })); + } + return Ok(LuaValue::Number(f64::NAN)); + } + while let Some(b) = self.peek() { + if b.is_ascii_digit() { + self.pos += 1; + } else { + break; + } + } + } + if matches!(self.peek(), Some(b'e' | b'E')) { + self.pos += 1; + if matches!(self.peek(), Some(b'+' | b'-')) { + self.pos += 1; + } + while let Some(b) = self.peek() { + if b.is_ascii_digit() { + self.pos += 1; + } else { + break; + } + } + } + let s = std::str::from_utf8(&self.src[start..self.pos]) + .map_err(|_| self.err("invalid UTF-8 in number"))?; + let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?; + Ok(LuaValue::Number(n)) + } +} + +fn is_ident_start(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' +} + +fn is_ident_cont(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} diff --git a/crates/model/src/spline.rs b/crates/model/src/spline.rs new file mode 100644 index 0000000000000000000000000000000000000000..056e04fd30fa9a7df2f469aa325e5bc109e000a2 --- /dev/null +++ b/crates/model/src/spline.rs @@ -0,0 +1,491 @@ +//! Fusion BezierSpline, PolyPath, LUTBezier, and Gradient animation data & evaluators. + +use crate::lua_value::{LuaKey, LuaTable, LuaValue}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum HandleMode { + #[default] + Free, + Aligned, + Vector, + Auto, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct KeyFlags { + pub linear: bool, + pub step_in: bool, + pub step_out: bool, + pub loop_after: bool, + pub loop_rel: bool, + pub ping_pong: bool, + pub locked_y: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Keyframe { + pub time: f64, + pub value: f64, + /// Left tangent handle in absolute `(time, value)` coordinates (Fusion convention). + pub lh: Option<[f64; 2]>, + /// Right tangent handle in absolute `(time, value)` coordinates (Fusion convention). + pub rh: Option<[f64; 2]>, + pub flags: KeyFlags, + pub handle_mode: HandleMode, +} + +impl Keyframe { + pub fn new(time: f64, value: f64) -> Self { + Self { + time, + value, + lh: None, + rh: None, + flags: KeyFlags { linear: true, ..Default::default() }, + handle_mode: HandleMode::Aligned, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BezierSpline { + pub name: String, + pub color: [u8; 3], + pub keyframes: Vec, +} + +impl BezierSpline { + pub fn from_lua(name: String, table: &LuaTable) -> Self { + let color = table + .get_table("SplineColor") + .map(|c| { + [ + c.get_f64("Red").unwrap_or(200.0) as u8, + c.get_f64("Green").unwrap_or(140.0) as u8, + c.get_f64("Blue").unwrap_or(255.0) as u8, + ] + }) + .unwrap_or([210, 140, 255]); + + let mut keyframes = Vec::new(); + // BezierSpline uses `KeyFrames`; LUTBezier uses `KeyColorSplines[0]` + let kf_table = table.get_table("KeyFrames").or_else(|| { + table + .get_table("KeyColorSplines") + .and_then(|kc| kc.get_index(0)) + .and_then(LuaValue::as_table) + }); + + if let Some(kfs) = kf_table { + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let Some(kt) = v.as_table() else { continue }; + let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0); + let lh = kt.get_table("LH").and_then(read_vec2); + let rh = kt.get_table("RH").and_then(read_vec2); + let mut flags = KeyFlags::default(); + if let Some(ft) = kt.get_table("Flags") { + flags.linear = ft.get_bool("Linear").unwrap_or(false); + flags.step_in = ft.get_bool("StepIn").unwrap_or(false); + flags.step_out = ft.get_bool("StepOut").unwrap_or(false); + flags.loop_after = ft.get_bool("Loop").unwrap_or(false); + flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false); + flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false); + flags.locked_y = ft.get_bool("LockedY").unwrap_or(false); + } + let handle_mode = if flags.linear { + HandleMode::Vector + } else { + HandleMode::Free + }; + keyframes.push(Keyframe { + time, + value, + lh, + rh, + flags, + handle_mode, + }); + } + } + keyframes.sort_by(|a, b| a.time.total_cmp(&b.time)); + Self { name, color, keyframes } + } + + pub fn sort(&mut self) { + self.keyframes.sort_by(|a, b| a.time.total_cmp(&b.time)); + } + + /// Evaluates the spline at arbitrary continuous time `t`. + pub fn eval(&self, t: f64) -> f64 { + let kfs = &self.keyframes; + if kfs.is_empty() { + return 0.0; + } + if kfs.len() == 1 { + return kfs[0].value; + } + let first = &kfs[0]; + let last = &kfs[kfs.len() - 1]; + + // Handle loop / relative-loop (`LoopRel`) / ping-pong if set on first or last keyframe + let mut t = t; + let mut value_offset = 0.0_f64; + let span = last.time - first.time; + let dv_cycle = last.value - first.value; + let do_loop_after = last.flags.loop_after || last.flags.loop_rel || last.flags.ping_pong; + let do_loop_before = first.flags.loop_after || first.flags.loop_rel || first.flags.ping_pong; + + if span > 1e-9 && ((t > last.time && do_loop_after) || (t < first.time && do_loop_before)) { + let offset = t - first.time; + let cycle = (offset / span).floor(); + let rem = offset - cycle * span; + if (t > last.time && last.flags.ping_pong) || (t < first.time && first.flags.ping_pong) { + t = if (cycle as i64) & 1 == 0 { + first.time + rem + } else { + last.time - rem + }; + } else { + t = first.time + rem; + if (t > last.time || offset >= span) && (last.flags.loop_rel || first.flags.loop_rel) { + value_offset = cycle * dv_cycle; + } else if offset < 0.0 && (first.flags.loop_rel || last.flags.loop_rel) { + value_offset = cycle * dv_cycle; + } + } + } + + if t <= first.time { + return first.value + value_offset; + } + if t >= last.time { + return last.value + value_offset; + } + + // Binary search segment [k0, k1] with k0.time <= t <= k1.time + let idx = kfs.partition_point(|k| k.time <= t).saturating_sub(1); + let k0 = &kfs[idx]; + let k1 = &kfs[(idx + 1).min(kfs.len() - 1)]; + eval_segment(k0, k1, t) + value_offset + } + + /// Returns the effective cubic Bezier control points `[p0, p1, p2, p3]` for segment `idx -> idx+1`. + pub fn segment_points(&self, idx: usize) -> Option<[[f64; 2]; 4]> { + let k0 = self.keyframes.get(idx)?; + let k1 = self.keyframes.get(idx + 1)?; + Some(segment_control_points(k0, k1)) + } +} + +pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] { + let p0 = [k0.time, k0.value]; + let p3 = [k1.time, k1.value]; + let dt = k1.time - k0.time; + let dv = k1.value - k0.value; + + let p1 = if k1.flags.linear && k0.rh.is_none() { + [k0.time + dt / 3.0, k0.value + dv / 3.0] + } else if let Some(rh) = k0.rh { + [rh[0].clamp(k0.time, k1.time), rh[1]] + } else { + [k0.time + dt / 3.0, k0.value + dv / 3.0] + }; + + let p2 = if k1.flags.linear && k1.lh.is_none() { + [k1.time - dt / 3.0, k1.value - dv / 3.0] + } else if let Some(lh) = k1.lh { + [lh[0].clamp(k0.time, k1.time), lh[1]] + } else { + [k1.time - dt / 3.0, k1.value - dv / 3.0] + }; + + [p0, p1, p2, p3] +} + +fn eval_segment(k0: &Keyframe, k1: &Keyframe, t: f64) -> f64 { + let dt = k1.time - k0.time; + if dt.abs() < 1e-12 { + return k1.value; + } + if k0.flags.step_out { + return k1.value; + } + if k1.flags.step_in { + return k0.value; + } + if k1.flags.linear && k0.rh.is_none() && k1.lh.is_none() { + let u = (t - k0.time) / dt; + return k0.value + (k1.value - k0.value) * u; + } + + let [p0, p1, p2, p3] = segment_control_points(k0, k1); + + // Solve cubic X(u) = t for u in [0, 1] using Newton-Raphson + bisection guard. + let mut lo = 0.0_f64; + let mut hi = 1.0_f64; + let mut u = ((t - p0[0]) / dt).clamp(0.0, 1.0); + for _ in 0..12 { + let x = cubic(p0[0], p1[0], p2[0], p3[0], u); + let err = x - t; + if err.abs() < 1e-7 { + break; + } + if err < 0.0 { + lo = u; + } else { + hi = u; + } + let dx = cubic_deriv(p0[0], p1[0], p2[0], p3[0], u); + let next = if dx.abs() > 1e-9 { u - err / dx } else { 0.5 * (lo + hi) }; + u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + cubic(p0[1], p1[1], p2[1], p3[1], u) +} + +#[inline] +pub fn cubic(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 { + let inv = 1.0 - u; + inv * inv * inv * a + 3.0 * inv * inv * u * b + 3.0 * inv * u * u * c + u * u * u * d +} + +#[inline] +fn cubic_deriv(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 { + let inv = 1.0 - u; + 3.0 * inv * inv * (b - a) + 6.0 * inv * u * (c - b) + 3.0 * u * u * (d - c) +} + +/// 2D Bezier path used by Fusion `PolyPath` (Point animation) and `PolylineMask`. +#[derive(Clone, Debug, PartialEq)] +pub struct PolyPoint { + pub x: f64, + pub y: f64, + /// Relative left tangent handle `(lx, ly)` from `(x, y)`. + pub lx: f64, + pub ly: f64, + /// Relative right tangent handle `(rx, ry)` from `(x, y)`. + pub rx: f64, + pub ry: f64, + pub linear: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PolyPath { + pub name: String, + pub displacement_op: Option, + pub displacement_value: f64, + pub closed: bool, + pub points: Vec, +} + +impl PolyPath { + pub fn parse_polyline_table(pl: &LuaTable) -> (bool, Vec) { + let closed = pl.get_bool("Closed").unwrap_or(false); + let mut points = Vec::new(); + if let Some(pts) = pl.get_table("Points") { + for (_, v) in &pts.entries { + if let Some(pt) = v.as_table() { + points.push(PolyPoint { + x: pt.get_f64("X").unwrap_or(0.0), + y: pt.get_f64("Y").unwrap_or(0.0), + lx: pt.get_f64("LX").unwrap_or(0.0), + ly: pt.get_f64("LY").unwrap_or(0.0), + rx: pt.get_f64("RX").unwrap_or(0.0), + ry: pt.get_f64("RY").unwrap_or(0.0), + linear: pt.get_bool("Linear").unwrap_or(false), + }); + } + } + } + (closed, points) + } + + pub fn from_lua(name: String, table: &LuaTable) -> Self { + let mut displacement_op = None; + let mut displacement_value = 0.0; + let mut closed = false; + let mut points = Vec::new(); + + if let Some(inputs) = table.get_table("Inputs") { + if let Some(disp) = inputs.get_table("Displacement") { + displacement_op = disp.get_str("SourceOp").map(str::to_owned); + displacement_value = disp.get_f64("Value").unwrap_or(0.0); + } + if let Some(pl_in) = inputs.get_table("PolyLine").or_else(|| inputs.get_table("Polyline")) { + if let Some(pl) = pl_in.get_table("Value") { + let (c, pts) = Self::parse_polyline_table(pl); + closed = c; + points = pts; + } + } + } + + Self { + name, + displacement_op, + displacement_value, + closed, + points, + } + } + + /// Evaluates the PolyPath at normalized arc-length `displacement ∈ [0, 1]`, + /// returning Fusion normalized `[x, y]` coordinates (with `(0.5, 0.5)` origin!). + pub fn eval_center(&self, displacement: f64) -> [f64; 2] { + let p = self.eval_raw(displacement); + [0.5 + p[0], 0.5 + p[1]] + } + + /// Evaluates raw Polyline coordinates centered around `(0, 0)`. + /// Supports extrapolation when `displacement` is outside `[0, 1]` (e.g. from `LoopRel`!). + pub fn eval_raw(&self, displacement: f64) -> [f64; 2] { + if self.points.is_empty() { + return [0.0, 0.0]; + } + if self.points.len() == 1 { + return [self.points[0].x, self.points[0].y]; + } + let seg_count = if self.closed { self.points.len() } else { self.points.len() - 1 }; + + // Sample arc lengths along segments for accurate constant-speed displacement. + const SUBS: usize = 16; + let mut samples = Vec::with_capacity(seg_count * SUBS + 1); + let mut cum_len = 0.0_f64; + let mut prev = [self.points[0].x, self.points[0].y]; + samples.push((0.0_f64, prev)); + + for s in 0..seg_count { + let a = &self.points[s]; + let b = &self.points[(s + 1) % self.points.len()]; + let p0 = [a.x, a.y]; + let p3 = [b.x, b.y]; + let p1 = [a.x + a.rx, a.y + a.ry]; + let p2 = [b.x + b.lx, b.y + b.ly]; + for step in 1..=SUBS { + let u = step as f64 / SUBS as f64; + let cur = if a.linear && b.linear { + [p0[0] + (p3[0] - p0[0]) * u, p0[1] + (p3[1] - p0[1]) * u] + } else { + [ + cubic(p0[0], p1[0], p2[0], p3[0], u), + cubic(p0[1], p1[1], p2[1], p3[1], u), + ] + }; + let dx = cur[0] - prev[0]; + let dy = cur[1] - prev[1]; + cum_len += (dx * dx + dy * dy).sqrt(); + samples.push((cum_len, cur)); + prev = cur; + } + } + + if cum_len <= 1e-12 { + return samples[0].1; + } + // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1] + if displacement > 1.0 && samples.len() >= 2 { + let (l0, v0) = samples[samples.len() - 2]; + let (l1, v1) = samples[samples.len() - 1]; + let seg = (l1 - l0).max(1e-12); + let extra = (displacement - 1.0) * cum_len; + return [ + v1[0] + (v1[0] - v0[0]) / seg * extra, + v1[1] + (v1[1] - v0[1]) / seg * extra, + ]; + } + if displacement < 0.0 && samples.len() >= 2 { + let (l0, v0) = samples[0]; + let (l1, v1) = samples[1]; + let seg = (l1 - l0).max(1e-12); + let extra = displacement * cum_len; + return [ + v0[0] + (v1[0] - v0[0]) / seg * extra, + v0[1] + (v1[1] - v0[1]) / seg * extra, + ]; + } + + let d = displacement.clamp(0.0, 1.0); + let target = d * cum_len; + let idx = samples.partition_point(|(l, _)| *l < target); + if idx == 0 { + return samples[0].1; + } + if idx >= samples.len() { + return samples[samples.len() - 1].1; + } + let (l0, v0) = samples[idx - 1]; + let (l1, v1) = samples[idx]; + let span = (l1 - l0).max(1e-12); + let frac = (target - l0) / span; + [v0[0] + (v1[0] - v0[0]) * frac, v0[1] + (v1[1] - v0[1]) * frac] + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct GradientStop { + pub pos: f64, + pub rgba: [f32; 4], +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Gradient { + pub stops: Vec, +} + +impl Gradient { + pub fn from_lua(table: &LuaTable) -> Self { + let mut stops = Vec::new(); + if let Some(colors) = table.get_table("Colors") { + for (k, v) in &colors.entries { + let pos = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + if let Some(ct) = v.as_table() { + let r = ct.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; + let g = ct.get_index(2).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; + let b = ct.get_index(3).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; + let a = ct.get_index(4).and_then(LuaValue::as_f64).unwrap_or(1.0) as f32; + stops.push(GradientStop { pos, rgba: [r, g, b, a] }); + } + } + } + stops.sort_by(|a, b| a.pos.total_cmp(&b.pos)); + Self { stops } + } + + pub fn sample(&self, t: f64) -> [f32; 4] { + if self.stops.is_empty() { + return [0.0, 0.0, 0.0, 1.0]; + } + if self.stops.len() == 1 || t <= self.stops[0].pos { + return self.stops[0].rgba; + } + let last = &self.stops[self.stops.len() - 1]; + if t >= last.pos { + return last.rgba; + } + let idx = self.stops.partition_point(|s| s.pos <= t).saturating_sub(1); + let a = &self.stops[idx]; + let b = &self.stops[(idx + 1).min(self.stops.len() - 1)]; + let span = (b.pos - a.pos).max(1e-9); + let f = ((t - a.pos) / span) as f32; + [ + a.rgba[0] + (b.rgba[0] - a.rgba[0]) * f, + a.rgba[1] + (b.rgba[1] - a.rgba[1]) * f, + a.rgba[2] + (b.rgba[2] - a.rgba[2]) * f, + a.rgba[3] + (b.rgba[3] - a.rgba[3]) * f, + ] + } +} + +pub fn read_vec2(t: &LuaTable) -> Option<[f64; 2]> { + let x = t.get_index(1)?.as_f64()?; + let y = t.get_index(2)?.as_f64()?; + Some([x, y]) +} diff --git a/crates/spline/Cargo.toml b/crates/spline/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..fed6034396ffb22447400e4e91cf6c491804dc83 --- /dev/null +++ b/crates/spline/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "spline" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[dependencies] +draw.workspace = true +model.workspace = true +text.workspace = true +theme.workspace = true +ui.workspace = true +winit.workspace = true diff --git a/crates/spline/src/lib.rs b/crates/spline/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..9e794e509a5206a31884f0a56e0079c3a9a30468 --- /dev/null +++ b/crates/spline/src/lib.rs @@ -0,0 +1,1282 @@ +//! Blender-style Bezier Spline Editor built on `draw` + `ui`. +//! +//! Features: +//! - Both direct LMB drag AND Blender `G` (Grab), `R` (Rotate), `S` (Scale) modal editing +//! - `X`/`Y` axis locks with red/green guides, integer-frame snapping (`Shift` for fine) +//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `T` Step, `I` Insert key, `Del/BS` Delete +//! - Crisp high-contrast curves (zero XOR!), generous hit targets, live GPU Viewer feedback. + +use draw::{Glyphs, Primitive}; +use model::spline::{cubic, segment_control_points}; +use model::{Comp, Keyframe, NodeId}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use winit::event::{ElementState, MouseButton}; +use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; + +const RULER_H: f32 = 24.0; +const SIDEBAR_W: f32 = 172.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum HandlePart { + Key, + LeftHandle, + RightHandle, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct PointRef { + pub spline: String, + pub key_idx: usize, + pub part: HandlePart, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TransformMode { + Grab, + Rotate, + Scale, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AxisLock { + None, + X, + Y, +} + +#[derive(Clone, Debug)] +struct ModalEdit { + mode: TransformMode, + axis: AxisLock, + pivot: [f64; 2], + start_pointer: [f64; 2], + saved_splines: HashMap>, +} + +#[derive(Clone, Debug)] +struct BoxSelect { + start_local: [f32; 2], + cur_local: [f32; 2], +} + +#[derive(Clone, Debug)] +pub enum SplineAction { + SplineEdited, + ScrubFrame(f64), +} + +#[derive(Clone, Copy, Debug)] +pub struct SplinePalette { + pub bg: [f32; 4], + pub sidebar: [f32; 4], + pub ruler: [f32; 4], + pub rule: [f32; 4], + pub grid: [f32; 4], + pub zero_line: [f32; 4], + pub text: [f32; 4], + pub text_dim: [f32; 4], + pub accent: [f32; 4], +} + +impl SplinePalette { + pub fn from_ui(theme: &ui::Theme) -> Self { + let b = theme.base; + let lift = |c: [f32; 4], d: f32| { + [(c[0] + d).clamp(0.0, 1.0), (c[1] + d).clamp(0.0, 1.0), (c[2] + d).clamp(0.0, 1.0), 1.0] + }; + Self { + bg: b, + sidebar: lift(b, 0.012), + ruler: lift(b, 0.018), + rule: theme.rule, + grid: lift(b, 0.022), + zero_line: lift(b, 0.065), + text: theme.text, + text_dim: theme.text_dim, + accent: theme.accent, + } + } +} + +pub struct SplineView { + pub t_range: [f64; 2], + pub v_range: [f64; 2], + pub size: [f32; 2], + pub channels: Vec<(String, String)>, + pub hidden_splines: HashSet, + pub selected: HashSet, + pub palette: SplinePalette, + hovered: Option, + modal: Option, + lmb_drag_point: Option<([f32; 2], bool)>, + box_select: Option, + panning: Option<([f32; 2], [f64; 2], [f64; 2])>, + scrubbing: bool, + pointer_local: [f32; 2], + current_node: Option, + text_cache: HashMap, +} + +impl SplineView { + pub fn new(theme: &ui::Theme) -> Self { + Self { + t_range: [0.0, 300.0], + v_range: [-0.2, 1.2], + size: [800.0, 360.0], + channels: Vec::new(), + hidden_splines: HashSet::new(), + selected: HashSet::new(), + palette: SplinePalette::from_ui(theme), + hovered: None, + modal: None, + lmb_drag_point: None, + box_select: None, + panning: None, + scrubbing: false, + pointer_local: [0.0, 0.0], + current_node: None, + text_cache: HashMap::new(), + } + } + + pub fn resize(&mut self, size: [f32; 2]) { + self.size = [size[0].max(1.0), size[1].max(1.0)]; + } + + pub fn background(&self) -> [f32; 4] { + self.palette.bg + } + + pub fn set_target_node(&mut self, comp: &Comp, selected_node: Option) { + if self.current_node == selected_node && !self.channels.is_empty() { + return; + } + self.current_node = selected_node; + self.selected.clear(); + self.modal = None; + self.lmb_drag_point = None; + + let mut ch = selected_node + .map(|id| comp.node_splines(id)) + .unwrap_or_default(); + + if ch.is_empty() { + // Skip 0..1 LUT splines (e.g. CustomTool LUTIn) so the frame timeline doesn't stretch to 0..2500. + let mut all: Vec = comp + .splines + .iter() + .filter(|(k, s)| s.keyframes.len() >= 2 && !k.contains("LUTIn")) + .map(|(k, _)| k.clone()) + .collect(); + all.sort(); + for s in all.into_iter().take(12) { + ch.push((s.clone(), s)); + } + } + self.channels = ch; + self.fit_all(comp); + } + + pub fn fit_all(&mut self, comp: &Comp) { + let mut t0 = f64::INFINITY; + let mut t1 = f64::NEG_INFINITY; + let mut v0 = f64::INFINITY; + let mut v1 = f64::NEG_INFINITY; + + // If keyframes are selected, frame them (Blender Numpad `.` behavior!); otherwise frame all visible curves! + let use_sel = !self.selected.is_empty(); + if use_sel { + for pref in &self.selected { + if let Some(sp) = comp.splines.get(&pref.spline) { + if let Some(kf) = sp.keyframes.get(pref.key_idx) { + t0 = t0.min(kf.time); + t1 = t1.max(kf.time); + v0 = v0.min(kf.value); + v1 = v1.max(kf.value); + } + } + } + } + if !t0.is_finite() { + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + let Some(sp) = comp.splines.get(sname) else { continue }; + for kf in &sp.keyframes { + t0 = t0.min(kf.time); + t1 = t1.max(kf.time); + v0 = v0.min(kf.value); + v1 = v1.max(kf.value); + if let Some(lh) = kf.lh { + v0 = v0.min(lh[1]); + v1 = v1.max(lh[1]); + } + if let Some(rh) = kf.rh { + v0 = v0.min(rh[1]); + v1 = v1.max(rh[1]); + } + } + } + } + + if !t0.is_finite() { + self.t_range = [comp.render_range[0] as f64, comp.render_range[1] as f64]; + self.v_range = [-0.2, 1.2]; + return; + } + let dt = (t1 - t0).max(20.0); + let dv = (v1 - v0).max(0.2); + self.t_range = [t0 - dt * 0.14, t1 + dt * 0.14]; + self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20]; + } + + fn plot_rect(&self) -> [f32; 4] { + [ + SIDEBAR_W, + RULER_H, + self.size[0].max(SIDEBAR_W + 40.0), + (self.size[1] - 24.0).max(RULER_H + 40.0), + ] + } + + fn data_to_local(&self, t: f64, v: f64) -> [f32; 2] { + let r = self.plot_rect(); + let tx = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6); + let ty = (v - self.v_range[0]) / (self.v_range[1] - self.v_range[0]).max(1e-6); + [ + r[0] + (tx as f32) * (r[2] - r[0]), + r[3] - (ty as f32) * (r[3] - r[1]), + ] + } + + fn local_to_data(&self, l: [f32; 2]) -> [f64; 2] { + let r = self.plot_rect(); + let tx = f64::from((l[0] - r[0]) / (r[2] - r[0]).max(1.0)); + let ty = f64::from((r[3] - l[1]) / (r[3] - r[1]).max(1.0)); + [ + self.t_range[0] + tx * (self.t_range[1] - self.t_range[0]), + self.v_range[0] + ty * (self.v_range[1] - self.v_range[0]), + ] + } + + fn hit_point(&self, comp: &Comp, local: [f32; 2]) -> Option { + let mut best_handle: Option<(f32, PointRef)> = None; + let mut best_key: Option<(f32, PointRef)> = None; + + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + let Some(sp) = comp.splines.get(sname) else { continue }; + for (ki, kf) in sp.keyframes.iter().enumerate() { + let kp = self.data_to_local(kf.time, kf.value); + let kd = hypot2(local, kp); + if kd < 15.0 && best_key.as_ref().is_none_or(|(d, _)| kd < *d) { + best_key = Some(( + kd, + PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key }, + )); + } + + if self.is_key_or_handle_selected(sname, ki) { + if let Some(lh) = kf.lh { + let lp = self.data_to_local(lh[0], lh[1]); + let ld = hypot2(local, lp); + if ld < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| ld < *d) { + best_handle = Some(( + ld, + PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::LeftHandle }, + )); + } + } + if let Some(rh) = kf.rh { + let rp = self.data_to_local(rh[0], rh[1]); + let rd = hypot2(local, rp); + if rd < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| rd < *d) { + best_handle = Some(( + rd, + PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::RightHandle }, + )); + } + } + } + } + } + best_handle.or(best_key).map(|(_, pr)| pr) + } + + fn is_key_or_handle_selected(&self, spline: &str, key_idx: usize) -> bool { + self.selected.iter().any(|p| p.spline == spline && p.key_idx == key_idx) + } + + fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) { + if self.selected.is_empty() { + return; + } + let mut sum_t = 0.0; + let mut sum_v = 0.0; + let mut count = 0usize; + let mut saved = HashMap::new(); + + for pref in &self.selected { + if let Some(sp) = comp.splines.get(&pref.spline) { + saved.entry(pref.spline.clone()).or_insert_with(|| sp.keyframes.clone()); + if let Some(kf) = sp.keyframes.get(pref.key_idx) { + let pt = match pref.part { + HandlePart::Key => [kf.time, kf.value], + HandlePart::LeftHandle => kf.lh.unwrap_or([kf.time, kf.value]), + HandlePart::RightHandle => kf.rh.unwrap_or([kf.time, kf.value]), + }; + let piv_pt = if self.selected.len() == 1 && pref.part != HandlePart::Key { + [kf.time, kf.value] + } else { + pt + }; + sum_t += piv_pt[0]; + sum_v += piv_pt[1]; + count += 1; + } + } + } + if count == 0 { + return; + } + self.modal = Some(ModalEdit { + mode, + axis: AxisLock::None, + pivot: [sum_t / count as f64, sum_v / count as f64], + start_pointer: self.local_to_data(self.pointer_local), + saved_splines: saved, + }); + } + + fn apply_modal(&mut self, comp: &mut Comp, fine: bool) -> bool { + let Some(m) = &self.modal else { return false }; + let cur = self.local_to_data(self.pointer_local); + let dt = cur[0] - m.start_pointer[0]; + let dv = cur[1] - m.start_pointer[1]; + let piv = m.pivot; + + for (sname, orig_kfs) in &m.saved_splines { + if let Some(sp) = comp.splines.get_mut(sname) { + sp.keyframes = orig_kfs.clone(); + } + } + + let snap_t = |t: f64| if fine { t } else { t.round() }; + + match m.mode { + TransformMode::Grab => { + let (mt, mv) = match m.axis { + AxisLock::None => (dt, dv), + AxisLock::X => (dt, 0.0), + AxisLock::Y => (0.0, dv), + }; + for pref in &self.selected { + let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; + match pref.part { + HandlePart::Key => { + let new_t = snap_t(kf.time + mt); + let actual_dt = new_t - kf.time; + kf.time = new_t; + kf.value += mv; + if let Some(lh) = &mut kf.lh { + lh[0] += actual_dt; + lh[1] += mv; + } + if let Some(rh) = &mut kf.rh { + rh[0] += actual_dt; + rh[1] += mv; + } + } + HandlePart::LeftHandle => { + let mut h = kf.lh.unwrap_or([kf.time - 5.0, kf.value]); + h[0] = (h[0] + mt).min(kf.time - 0.01); + h[1] += mv; + kf.lh = Some(h); + kf.flags.linear = false; + } + HandlePart::RightHandle => { + let mut h = kf.rh.unwrap_or([kf.time + 5.0, kf.value]); + h[0] = (h[0] + mt).max(kf.time + 0.01); + h[1] += mv; + kf.rh = Some(h); + kf.flags.linear = false; + } + } + } + } + TransformMode::Scale => { + let s0 = self.data_to_local(m.start_pointer[0], m.start_pointer[1]); + let s1 = self.pointer_local; + let sp = self.data_to_local(piv[0], piv[1]); + let d0 = hypot2(s0, sp).max(10.0); + let d1 = hypot2(s1, sp); + let f = f64::from((d1 / d0).clamp(0.05, 10.0)); + let (st, sv) = match m.axis { + AxisLock::None => (f, f), + AxisLock::X => (f, 1.0), + AxisLock::Y => (1.0, f), + }; + for pref in &self.selected { + let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; + match pref.part { + HandlePart::Key => { + kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st); + kf.value = piv[1] + (kf.value - piv[1]) * sv; + if let Some(lh) = &mut kf.lh { + lh[0] = piv[0] + (lh[0] - piv[0]) * st; + lh[1] = piv[1] + (lh[1] - piv[1]) * sv; + } + if let Some(rh) = &mut kf.rh { + rh[0] = piv[0] + (rh[0] - piv[0]) * st; + rh[1] = piv[1] + (rh[1] - piv[1]) * sv; + } + } + HandlePart::LeftHandle => { + if let Some(lh) = &mut kf.lh { + lh[0] = (kf.time + (lh[0] - kf.time) * st).min(kf.time - 0.01); + lh[1] = kf.value + (lh[1] - kf.value) * sv; + } + } + HandlePart::RightHandle => { + if let Some(rh) = &mut kf.rh { + rh[0] = (kf.time + (rh[0] - kf.time) * st).max(kf.time + 0.01); + rh[1] = kf.value + (rh[1] - kf.value) * sv; + } + } + } + } + } + TransformMode::Rotate => { + let sp_px = self.data_to_local(piv[0], piv[1]); + let s0_px = self.data_to_local(m.start_pointer[0], m.start_pointer[1]); + let a0 = (s0_px[1] - sp_px[1]).atan2(s0_px[0] - sp_px[0]); + let a1 = (self.pointer_local[1] - sp_px[1]).atan2(self.pointer_local[0] - sp_px[0]); + let da = a1 - a0; + let (c, s) = (da.cos(), da.sin()); + + let rot = |pt: [f64; 2], center_px: [f32; 2]| -> [f64; 2] { + let p = self.data_to_local(pt[0], pt[1]); + let rx = p[0] - center_px[0]; + let ry = p[1] - center_px[1]; + let np = [center_px[0] + rx * c - ry * s, center_px[1] + rx * s + ry * c]; + self.local_to_data(np) + }; + + for pref in &self.selected { + let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; + match pref.part { + HandlePart::Key => { + if self.selected.len() == 1 { + let kp = self.data_to_local(kf.time, kf.value); + ensure_handles(kf); + if let Some(lh) = kf.lh { + let nl = rot(lh, kp); + kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]); + } + if let Some(rh) = kf.rh { + let nr = rot(rh, kp); + kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]); + } + kf.flags.linear = false; + } else { + let nk = rot([kf.time, kf.value], sp_px); + kf.time = snap_t(nk[0]); + kf.value = nk[1]; + } + } + HandlePart::LeftHandle => { + let kp = self.data_to_local(kf.time, kf.value); + if let Some(lh) = kf.lh { + let nl = rot(lh, kp); + kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]); + kf.flags.linear = false; + } + } + HandlePart::RightHandle => { + let kp = self.data_to_local(kf.time, kf.value); + if let Some(rh) = kf.rh { + let nr = rot(rh, kp); + kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]); + kf.flags.linear = false; + } + } + } + } + } + } + comp.revision += 1; + true + } + + fn cancel_modal(&mut self, comp: &mut Comp) { + if let Some(m) = self.modal.take() { + for (sname, orig) in m.saved_splines { + if let Some(sp) = comp.splines.get_mut(&sname) { + sp.keyframes = orig; + } + } + comp.revision += 1; + } + } + + fn confirm_modal(&mut self, comp: &mut Comp) { + if let Some(m) = self.modal.take() { + for sname in m.saved_splines.keys() { + if let Some(sp) = comp.splines.get_mut(sname) { + sp.sort(); + } + } + comp.revision += 1; + } + } + + fn handle_key( + &mut self, + comp: &mut Comp, + current_frame: f64, + physical: Option, + key: &Key, + kmod: ModifiersState, + actions: &mut Vec, + ) { + if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { + self.fit_all(comp); + return; + } + match key { + Key::Named(NamedKey::Escape) => { + if self.modal.is_some() { + self.cancel_modal(comp); + actions.push(SplineAction::SplineEdited); + } + } + Key::Named(NamedKey::Enter) => { + if self.modal.is_some() { + self.confirm_modal(comp); + actions.push(SplineAction::SplineEdited); + } + } + Key::Named(NamedKey::Delete | NamedKey::Backspace) => { + if self.delete_selected(comp) { + actions.push(SplineAction::SplineEdited); + } + } + Key::Character(c) => match c.to_ascii_lowercase().as_str() { + "f" if kmod.super_key() => self.fit_all(comp), + "f" | "." if !kmod.super_key() => self.fit_all(comp), + "g" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Grab); + } + "r" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Rotate); + } + "s" if !kmod.super_key() && self.modal.is_none() => { + self.begin_modal(comp, TransformMode::Scale); + } + "x" if self.modal.is_some() => { + if let Some(m) = &mut self.modal { + m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X }; + } + if self.apply_modal(comp, kmod.shift_key()) { + actions.push(SplineAction::SplineEdited); + } + } + "x" if self.modal.is_none() && !kmod.super_key() => { + // Blender `X` deletes selected keys when not in a modal transform! + if self.delete_selected(comp) { + actions.push(SplineAction::SplineEdited); + } + } + "y" if self.modal.is_some() => { + if let Some(m) = &mut self.modal { + m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y }; + } + if self.apply_modal(comp, kmod.shift_key()) { + actions.push(SplineAction::SplineEdited); + } + } + "i" if !kmod.super_key() && self.modal.is_none() => { + // Blender `I` inserts keyframe at current integer frame on all visible channels + let t = current_frame.round(); + let mut inserted = false; + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + if let Some(sp) = comp.splines.get_mut(sname) { + if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) { + let v = sp.eval(t); + sp.keyframes.push(Keyframe::new(t, v)); + sp.sort(); + inserted = true; + } + } + } + if inserted { + comp.revision += 1; + actions.push(SplineAction::SplineEdited); + } + } + "a" if !kmod.super_key() => { + if !self.selected.is_empty() { + self.selected.clear(); + } else { + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + if let Some(sp) = comp.splines.get(sname) { + for ki in 0..sp.keyframes.len() { + self.selected.insert(PointRef { + spline: sname.clone(), + key_idx: ki, + part: HandlePart::Key, + }); + } + } + } + } + } + "l" => { + for pref in &self.selected { + if let Some(sp) = comp.splines.get_mut(&pref.spline) { + if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { + kf.flags.linear = !kf.flags.linear; + if kf.flags.linear { + kf.lh = None; + kf.rh = None; + } else { + ensure_handles(kf); + } + } + } + } + if !self.selected.is_empty() { + comp.revision += 1; + actions.push(SplineAction::SplineEdited); + } + } + "t" => { + for pref in &self.selected { + if let Some(sp) = comp.splines.get_mut(&pref.spline) { + if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { + kf.flags.step_in = !kf.flags.step_in; + } + } + } + if !self.selected.is_empty() { + comp.revision += 1; + actions.push(SplineAction::SplineEdited); + } + } + _ => {} + }, + _ => {} + } + } + + fn delete_selected(&mut self, comp: &mut Comp) -> bool { + let mut by_spline: HashMap> = HashMap::new(); + for pref in &self.selected { + if pref.part == HandlePart::Key { + by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx); + } + } + let mut changed = false; + for (sname, mut idxs) in by_spline { + idxs.sort_unstable(); + idxs.dedup(); + if let Some(sp) = comp.splines.get_mut(&sname) { + for &idx in idxs.iter().rev() { + if sp.keyframes.len() > 1 && idx < sp.keyframes.len() { + sp.keyframes.remove(idx); + changed = true; + } + } + } + } + if changed { + self.selected.clear(); + comp.revision += 1; + } + changed + } + + pub fn input( + &mut self, + comp: &mut Comp, + current_frame: f64, + event: ui::Event, + rect: [f32; 4], + pointer_window: [f32; 2], + modifiers: ModifiersState, + ) -> Vec { + let mut actions = Vec::new(); + self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; + let plot = self.plot_rect(); + + match event { + ui::Event::PointerMoved(p) => { + self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; + if self.scrubbing { + let t = self.local_to_data(self.pointer_local)[0].round(); + actions.push(SplineAction::ScrubFrame(t)); + } else if let Some((sp, tr, vr)) = self.panning { + let dx = f64::from((self.pointer_local[0] - sp[0]) / (plot[2] - plot[0]).max(1.0)); + let dy = f64::from((self.pointer_local[1] - sp[1]) / (plot[3] - plot[1]).max(1.0)); + let dt = dx * (tr[1] - tr[0]); + let dv = dy * (vr[1] - vr[0]); + self.t_range = [tr[0] - dt, tr[1] - dt]; + self.v_range = [vr[0] + dv, vr[1] + dv]; + } else if self.modal.is_some() { + if self.apply_modal(comp, modifiers.shift_key()) { + actions.push(SplineAction::SplineEdited); + } + } else if let Some((start_l, ref mut dragging)) = self.lmb_drag_point { + if !*dragging && hypot2(self.pointer_local, start_l) > 3.5 { + *dragging = true; + self.begin_modal(comp, TransformMode::Grab); + if self.apply_modal(comp, modifiers.shift_key()) { + actions.push(SplineAction::SplineEdited); + } + } + } else if let Some(bs) = &mut self.box_select { + bs.cur_local = self.pointer_local; + } else { + self.hovered = self.hit_point(comp, self.pointer_local); + } + } + ui::Event::Button { button, pressed, .. } => { + if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { + if pressed { + self.panning = Some((self.pointer_local, self.t_range, self.v_range)); + } else { + self.panning = None; + } + } else if button == MouseButton::Right { + if pressed && self.modal.is_some() { + self.cancel_modal(comp); + self.lmb_drag_point = None; + actions.push(SplineAction::SplineEdited); + } + } else if button == MouseButton::Left { + if pressed { + if self.modal.is_some() { + self.confirm_modal(comp); + self.lmb_drag_point = None; + actions.push(SplineAction::SplineEdited); + } else if self.pointer_local[0] < SIDEBAR_W { + let row = ((self.pointer_local[1] - RULER_H - 6.0) / 22.0).floor() as isize; + if row >= 0 && (row as usize) < self.channels.len() { + let sname = self.channels[row as usize].1.clone(); + if !self.hidden_splines.remove(&sname) { + self.hidden_splines.insert(sname); + } + } + } else if self.pointer_local[1] < RULER_H { + self.scrubbing = true; + let t = self.local_to_data(self.pointer_local)[0].round(); + actions.push(SplineAction::ScrubFrame(t)); + } else if let Some(hit) = self.hit_point(comp, self.pointer_local) { + if modifiers.shift_key() { + if !self.selected.remove(&hit) { + self.selected.insert(hit); + } + } else if !self.selected.contains(&hit) { + self.selected.clear(); + self.selected.insert(hit); + } + for pref in &self.selected { + if let Some(sp) = comp.splines.get_mut(&pref.spline) { + if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { + ensure_handles(kf); + } + } + } + // Allow direct drag right from mouse down! + self.lmb_drag_point = Some((self.pointer_local, false)); + } else { + if !modifiers.shift_key() { + self.selected.clear(); + } + self.box_select = Some(BoxSelect { + start_local: self.pointer_local, + cur_local: self.pointer_local, + }); + } + } else { + self.scrubbing = false; + if let Some((_start, dragging)) = self.lmb_drag_point.take() { + if dragging && self.modal.is_some() { + self.confirm_modal(comp); + actions.push(SplineAction::SplineEdited); + } + } + if let Some(bs) = self.box_select.take() { + let x0 = bs.start_local[0].min(bs.cur_local[0]); + let x1 = bs.start_local[0].max(bs.cur_local[0]); + let y0 = bs.start_local[1].min(bs.cur_local[1]); + let y1 = bs.start_local[1].max(bs.cur_local[1]); + if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 { + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + let Some(sp) = comp.splines.get(sname) else { continue }; + for (ki, kf) in sp.keyframes.iter().enumerate() { + let p = self.data_to_local(kf.time, kf.value); + if p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1 { + self.selected.insert(PointRef { + spline: sname.clone(), + key_idx: ki, + part: HandlePart::Key, + }); + } + } + } + } + } + } + } + } + ui::Event::Wheel(delta) => { + // Blender convention: plain scroll zooms toward mouse cursor; Shift zooms Y; Alt pans. + if modifiers.alt_key() { + let dx = f64::from(delta[0] / (plot[2] - plot[0]).max(1.0)); + let dy = f64::from(delta[1] / (plot[3] - plot[1]).max(1.0)); + let dt = dx * (self.t_range[1] - self.t_range[0]); + let dv = dy * (self.v_range[1] - self.v_range[0]); + self.t_range = [self.t_range[0] - dt, self.t_range[1] - dt]; + self.v_range = [self.v_range[0] + dv, self.v_range[1] + dv]; + } else if modifiers.shift_key() { + let f = f64::from((1.0 - delta[1] * 0.004).clamp(0.7, 1.4)); + self.zoom_at(1.0, f, self.pointer_local); + } else { + let f = f64::from((1.0 - delta[1] * 0.0045).clamp(0.7, 1.4)); + self.zoom_at(f, f, self.pointer_local); + } + } + ui::Event::Pinch(delta) => { + let f = f64::from((1.0 - delta).clamp(0.7, 1.4)); + self.zoom_at(f, f, self.pointer_local); + } + ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { + self.handle_key(comp, current_frame, Some(physical), &key, kmod, &mut actions); + } + ui::Event::Key { key, modifiers: kmod, .. } => { + self.handle_key(comp, current_frame, None, &key, kmod, &mut actions); + } + _ => {} + } + + actions + } + + fn zoom_at(&mut self, ft: f64, fv: f64, pivot_local: [f32; 2]) { + let p = self.local_to_data(pivot_local); + let t0 = p[0] - (p[0] - self.t_range[0]) * ft; + let t1 = p[0] + (self.t_range[1] - p[0]) * ft; + let v0 = p[1] - (p[1] - self.v_range[0]) * fv; + let v1 = p[1] + (self.v_range[1] - p[1]) * fv; + if (t1 - t0) > 2.0 && (t1 - t0) < 100_000.0 { + self.t_range = [t0, t1]; + } + if (v1 - v0) > 1e-4 && (v1 - v0) < 1_000_000.0 { + self.v_range = [v0, v1]; + } + } + + pub fn prepare_labels(&mut self, comp: &Comp) { + let font_sm = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.0, + weight: 500, + italic: false, + }; + let font_ch = text::Font { + families: Arc::from([text::Family::Sans]), + size: 11.0, + weight: 500, + italic: false, + }; + let make_layout = |s: &str, font: &text::Font| { + let styles = [text::Style::new(font.clone())]; + text::Paragraph { + text: s, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }; + for (label, _) in &self.channels { + self.text_cache.entry(label.clone()).or_insert_with(|| make_layout(label, &font_ch)); + } + let header = self + .current_node + .map(|id| format!("Splines: {}", comp.node(id).name)) + .unwrap_or_else(|| "Splines (Comp)".to_owned()); + self.text_cache.entry(header.clone()).or_insert_with(|| make_layout(&header, &font_ch)); + for hud in [ + "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit", + "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]", + "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]", + ] { + self.text_cache.entry(hud.to_owned()).or_insert_with(|| make_layout(hud, &font_sm)); + } + + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let key = format!("t:{}", (ti as f64 * t_step).round() as i64); + self.text_cache.entry(key.clone()).or_insert_with(|| make_layout(&key[2..], &font_sm)); + } + let v_step = nice_step((self.v_range[1] - self.v_range[0]) / 6.0); + let v_start = (self.v_range[0] / v_step).floor() as i64; + let v_end = (self.v_range[1] / v_step).ceil() as i64; + for vi in v_start..=v_end { + let val = vi as f64 * v_step; + let s = format!("{val:.2}"); + let key = format!("v:{s}"); + self.text_cache.entry(key).or_insert_with(|| make_layout(&s, &font_sm)); + } + } + + pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { + let mut out = Vec::with_capacity(512); + let [w, h] = self.size; + let plot = self.plot_rect(); + + out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar }); + out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule }); + out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler }); + out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule }); + + let header = self + .current_node + .map(|id| format!("Splines: {}", comp.node(id).name)) + .unwrap_or_else(|| "Splines (Comp)".to_owned()); + if let Some(hl) = self.text_cache.get(&header) { + out.push(Primitive::Text { + text: hl as &dyn Glyphs, + origin: [10.0, 5.0], + clip: Some([8.0, 0.0, SIDEBAR_W - 8.0, RULER_H]), + ink: self.palette.text, + }); + } + + for (i, (label, sname)) in self.channels.iter().enumerate() { + let y = RULER_H + 6.0 + i as f32 * 22.0; + if y > h - 24.0 { + break; + } + let hidden = self.hidden_splines.contains(sname); + let col = spline_color(comp, sname, i); + out.push(Primitive::RoundedRect { + rect: [10.0, y + 4.0, 20.0, y + 14.0], + radius: 3.0, + stroke: if hidden { Some(1.2) } else { None }, + color: if hidden { self.palette.text_dim } else { col }, + }); + if let Some(tl) = self.text_cache.get(label) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [26.0, y + 2.0], + clip: Some([26.0, y, SIDEBAR_W - 8.0, y + 20.0]), + ink: if hidden { self.palette.text_dim } else { self.palette.text }, + }); + } + } + + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let t = ti as f64 * t_step; + let x = self.data_to_local(t, 0.0)[0]; + if x < plot[0] || x > plot[2] { + continue; + } + out.push(Primitive::Segment { from: [x, plot[1]], to: [x, plot[3]], width: 1.0, color: self.palette.grid }); + let key = format!("t:{}", t.round() as i64); + if let Some(tl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [x + 3.0, 6.0], + clip: Some([plot[0], 0.0, plot[2], RULER_H]), + ink: self.palette.text_dim, + }); + } + } + + let v_step = nice_step((self.v_range[1] - self.v_range[0]) / 6.0); + let v_start = (self.v_range[0] / v_step).floor() as i64; + let v_end = (self.v_range[1] / v_step).ceil() as i64; + for vi in v_start..=v_end { + let v = vi as f64 * v_step; + let y = self.data_to_local(0.0, v)[1]; + if y < plot[1] || y > plot[3] { + continue; + } + let is_zero = v.abs() < 1e-6; + out.push(Primitive::Segment { + from: [plot[0], y], + to: [plot[2], y], + width: if is_zero { 1.3 } else { 1.0 }, + color: if is_zero { self.palette.zero_line } else { self.palette.grid }, + }); + let key = format!("v:{v:.2}"); + if let Some(vl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: vl as &dyn Glyphs, + origin: [plot[0] + 4.0, y - 12.0], + clip: Some(plot), + ink: self.palette.text_dim, + }); + } + } + + out.push(Primitive::PushClip { rect: plot, radius: 0.0 }); + + if let Some(m) = &self.modal { + let piv = self.data_to_local(m.pivot[0], m.pivot[1]); + match m.axis { + AxisLock::X => out.push(Primitive::Segment { + from: [plot[0], piv[1]], + to: [plot[2], piv[1]], + width: 1.5, + color: [0.95, 0.28, 0.34, 0.85], + }), + AxisLock::Y => out.push(Primitive::Segment { + from: [piv[0], plot[1]], + to: [piv[0], plot[3]], + width: 1.5, + color: [0.28, 0.90, 0.42, 0.85], + }), + AxisLock::None => {} + } + } + + let px = self.data_to_local(current_frame, 0.0)[0]; + if px >= plot[0] && px <= plot[2] { + out.push(Primitive::Segment { + from: [px, plot[1]], + to: [px, plot[3]], + width: 1.6, + color: [0.96, 0.36, 0.34, 0.90], + }); + } + + for (ci, (_, sname)) in self.channels.iter().enumerate() { + if self.hidden_splines.contains(sname) { + continue; + } + let Some(sp) = comp.splines.get(sname) else { continue }; + let col = spline_color(comp, sname, ci); + let any_sel = self.selected.iter().any(|p| p.spline == *sname); + let curve_w = if any_sel { 2.4 } else { 1.7 }; + let curve_col = if any_sel { + [(col[0] + 0.15).min(1.0), (col[1] + 0.15).min(1.0), (col[2] + 0.15).min(1.0), 1.0] + } else { + col + }; + + if let Some(first) = sp.keyframes.first() { + let p = self.data_to_local(first.time, first.value); + if p[0] > plot[0] { + out.push(Primitive::Segment { + from: [plot[0], p[1]], + to: p, + width: 1.1, + color: [curve_col[0], curve_col[1], curve_col[2], 0.35], + }); + } + } + if let Some(last) = sp.keyframes.last() { + let p = self.data_to_local(last.time, last.value); + if p[0] < plot[2] { + out.push(Primitive::Segment { + from: p, + to: [plot[2], p[1]], + width: 1.1, + color: [curve_col[0], curve_col[1], curve_col[2], 0.35], + }); + } + } + + let dense = sp.keyframes.len() > 250; + for seg in 0..sp.keyframes.len().saturating_sub(1) { + let k0 = &sp.keyframes[seg]; + let k1 = &sp.keyframes[seg + 1]; + if k1.time < self.t_range[0] || k0.time > self.t_range[1] { + continue; + } + if k1.flags.step_in { + let a = self.data_to_local(k0.time, k0.value); + let m = self.data_to_local(k1.time, k0.value); + let b = self.data_to_local(k1.time, k1.value); + out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col }); + out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col }); + } else if dense || (k1.flags.linear && k0.rh.is_none() && k1.lh.is_none()) { + let a = self.data_to_local(k0.time, k0.value); + let b = self.data_to_local(k1.time, k1.value); + out.push(Primitive::Segment { from: a, to: b, width: curve_w, color: curve_col }); + } else { + let [p0, p1, p2, p3] = segment_control_points(k0, k1); + const SUBS: usize = 20; + let mut prev = self.data_to_local(p0[0], p0[1]); + for s in 1..=SUBS { + let u = s as f64 / SUBS as f64; + let t = cubic(p0[0], p1[0], p2[0], p3[0], u); + let v = cubic(p0[1], p1[1], p2[1], p3[1], u); + let cur = self.data_to_local(t, v); + out.push(Primitive::Segment { from: prev, to: cur, width: curve_w, color: curve_col }); + prev = cur; + } + } + } + + if !dense || (self.t_range[1] - self.t_range[0]) < 180.0 { + for (ki, kf) in sp.keyframes.iter().enumerate() { + if kf.time < self.t_range[0] - 5.0 || kf.time > self.t_range[1] + 5.0 { + continue; + } + let kp = self.data_to_local(kf.time, kf.value); + let kref = PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key }; + let ksel = self.selected.contains(&kref); + let khov = self.hovered.as_ref() == Some(&kref); + let show_handles = self.is_key_or_handle_selected(sname, ki); + + if show_handles { + for (part, hopt) in [(HandlePart::LeftHandle, kf.lh), (HandlePart::RightHandle, kf.rh)] { + if let Some(h) = hopt { + let hp = self.data_to_local(h[0], h[1]); + let href = PointRef { spline: sname.clone(), key_idx: ki, part }; + let hsel = self.selected.contains(&href); + let hhov = self.hovered.as_ref() == Some(&href); + out.push(Primitive::Segment { + from: kp, + to: hp, + width: 1.4, + color: if hsel { [1.0, 0.85, 0.35, 1.0] } else { [0.75, 0.78, 0.86, 0.75] }, + }); + let hr = if hsel || hhov { 5.2 } else { 4.2 }; + out.push(Primitive::RoundedRect { + rect: [hp[0] - hr, hp[1] - hr, hp[0] + hr, hp[1] + hr], + radius: hr, + stroke: None, + color: if hsel { [1.0, 0.86, 0.28, 1.0] } else if hhov { [1.0, 1.0, 1.0, 1.0] } else { [0.85, 0.50, 0.95, 1.0] }, + }); + } + } + } + + let kr = if ksel || khov { 5.4 } else { 4.2 }; + out.push(Primitive::RoundedRect { + rect: [kp[0] - kr, kp[1] - kr, kp[0] + kr, kp[1] + kr], + radius: 1.5, + stroke: None, + color: if ksel { [1.0, 0.84, 0.24, 1.0] } else if khov { [1.0, 1.0, 1.0, 1.0] } else { curve_col }, + }); + out.push(Primitive::RoundedRect { + rect: [kp[0] - kr, kp[1] - kr, kp[0] + kr, kp[1] + kr], + radius: 1.5, + stroke: Some(1.2), + color: [0.02, 0.02, 0.03, 1.0], + }); + } + } + } + + if let Some(bs) = &self.box_select { + let x0 = bs.start_local[0].min(bs.cur_local[0]); + let x1 = bs.start_local[0].max(bs.cur_local[0]); + let y0 = bs.start_local[1].min(bs.cur_local[1]); + let y1 = bs.start_local[1].max(bs.cur_local[1]); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], + }); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: Some(1.2), + color: self.palette.accent, + }); + } + + out.push(Primitive::PopClip); + + let hud_key = match self.modal.as_ref().map(|m| m.mode) { + Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]", + Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", + Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]", + None => "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit", + }; + out.push(Primitive::Rect { rect: [SIDEBAR_W, h - 24.0, w, h], color: self.palette.ruler }); + if let Some(hl) = self.text_cache.get(hud_key) { + out.push(Primitive::Text { + text: hl as &dyn Glyphs, + origin: [SIDEBAR_W + 10.0, h - 18.0], + clip: Some([SIDEBAR_W + 6.0, h - 24.0, w - 6.0, h]), + ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim }, + }); + } + + out + } +} + +fn ensure_handles(kf: &mut Keyframe) { + if kf.lh.is_none() { + kf.lh = Some([kf.time - 8.0, kf.value]); + } + if kf.rh.is_none() { + kf.rh = Some([kf.time + 8.0, kf.value]); + } +} + +fn spline_color(comp: &Comp, name: &str, idx: usize) -> [f32; 4] { + if let Some(sp) = comp.splines.get(name) { + let [r, g, b] = sp.color; + if r as u16 + g as u16 + b as u16 > 120 { + return [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]; + } + } + const PALETTE: &[[f32; 4]] = &[ + [0.98, 0.44, 0.62, 1.0], + [0.36, 0.84, 0.96, 1.0], + [0.50, 0.92, 0.46, 1.0], + [0.98, 0.78, 0.28, 1.0], + [0.74, 0.56, 0.98, 1.0], + ]; + PALETTE[idx % PALETTE.len()] +} + +fn nice_step(raw: f64) -> f64 { + let raw = raw.max(1e-6); + let pow = 10.0_f64.powf(raw.log10().floor()); + let frac = raw / pow; + let nice = if frac < 1.5 { 1.0 } else if frac < 3.5 { 2.0 } else if frac < 7.5 { 5.0 } else { 10.0 }; + nice * pow +} + +fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt() +} diff --git a/crates/studio/Cargo.toml b/crates/studio/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..fe865de8bd0b91a4f5fd3a174d386a029b7373f9 --- /dev/null +++ b/crates/studio/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "studio" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[[bin]] +name = "compositor" +path = "src/main.rs" + +[dependencies] +accesskit.workspace = true +accesskit_winit.workspace = true +dock.workspace = true +draw.workspace = true +engine.workspace = true +flow.workspace = true +model.workspace = true +png.workspace = true +pollster.workspace = true +spline.workspace = true +state.workspace = true +text.workspace = true +theme.workspace = true +ui.workspace = true +viewer.workspace = true +wgpu.workspace = true +winit.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +objc2.workspace = true +objc2-app-kit = { workspace = true, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSResponder", "NSMenu", "NSMenuItem"] } +objc2-foundation = { workspace = true, features = ["std", "NSString"] } diff --git a/crates/studio/src/main.rs b/crates/studio/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..c846c0fe7199225c9bd7f4e69ec2483390a19ffe --- /dev/null +++ b/crates/studio/src/main.rs @@ -0,0 +1,872 @@ +//! Compositor Studio — docked zero-copy `wgpu` Multi-Viewer (`1`/`2`) + Flow + Blender-style Spline Editor +//! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris). + +use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab}; +use engine::{CacheMode, Engine}; +use flow::{FlowAction, FlowView}; +use model::Comp; +use spline::{SplineAction, SplineView}; +use std::collections::HashMap; +use std::error::Error; +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use ui::host::{Accessibility, Clipboard, Surface}; +use viewer::{PlaybackClock, SyncMode, ViewerAction, ViewerState}; +use winit::application::ApplicationHandler; +use winit::dpi::LogicalSize; +use winit::event::{ElementState, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy}; +use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey}; +use winit::window::{CursorIcon, Window, WindowId}; + +const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp"; +const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline"]; + +fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) } +fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) } +fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") } +fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") } + +struct Cli { + comp_path: PathBuf, + snapshot: Option, + frame: Option, + select_node: Option, + dual_viewer: bool, +} + +fn parse_cli() -> Cli { + let args: Vec = std::env::args().collect(); + let mut comp_path = PathBuf::from(DEFAULT_COMP); + let mut snapshot = None; + let mut frame = None; + let mut select_node = None; + let mut dual_viewer = false; + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--snapshot" if i + 1 < args.len() => { + snapshot = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--frame" if i + 1 < args.len() => { + frame = args[i + 1].parse().ok(); + i += 2; + } + "--select" if i + 1 < args.len() => { + select_node = Some(args[i + 1].clone()); + i += 2; + } + "--dual" => { + dual_viewer = true; + i += 1; + } + other if !other.starts_with("--") => { + comp_path = PathBuf::from(other); + i += 1; + } + _ => i += 1, + } + } + Cli { comp_path, snapshot, frame, select_node, dual_viewer } +} + +fn main() { + let cli = parse_cli(); + let res = match &cli.snapshot { + Some(out) => run_snapshot(&cli, out), + None => run_window(&cli), + }; + if let Err(e) = res { + eprintln!("compositor error: {e}"); + std::process::exit(1); + } +} + +struct Studio { + ui: ui::Ui, + dock: Dock, + layout: dock::Layout, + seen: dock::Seen, + renderer: draw::Renderer, + engine: Engine, + comp: Comp, + playback: PlaybackClock, + viewers: [ViewerState; 2], + flow: FlowView, + spline: SplineView, + size: [f32; 2], + scale: f32, + clock: Instant, +} + +impl Studio { + fn new(renderer: draw::Renderer, comp: Comp, init_frame: Option, select_node: Option<&str>, dual_viewer: bool) -> Self { + let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); + // Knife's soft toned Iris quiet-layered theme! + let ui_theme = ui::Theme::new(&theme::KNIFE, true); + let mut ui = ui::Ui::new(ui_theme.clone()); + ui.window_focused = true; + + let g_v1 = GroupId(1); + let g_flow = GroupId(2); + let g_spline = GroupId(3); + let g_v2 = GroupId(4); + + let top_node = if dual_viewer { + DockNode::Split { + id: SplitId(3), + axis: DockAxis::X, + parts: vec![ + DockPart { + share: 0.5, + node: DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + DockPart { + share: 0.5, + node: DockNode::Group { id: g_v2, tabs: vec!["Viewer 2".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + ], + rest: Default::default(), + } + } else { + DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() } + }; + + let layout = dock::Layout { + root: DockNode::Split { + id: SplitId(1), + axis: DockAxis::Y, + parts: vec![ + DockPart { share: 0.54, node: top_node, rest: Default::default() }, + DockPart { + share: 0.46, + node: DockNode::Split { + id: SplitId(2), + axis: DockAxis::X, + parts: vec![ + DockPart { + share: 0.52, + node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + DockPart { + share: 0.48, + node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + ], + rest: Default::default(), + }, + rest: Default::default(), + }, + ], + rest: Default::default(), + }, + issued: 5, + rest: Default::default(), + }; + let mut seen = dock::Seen::default(); + seen.active.insert(g_v1, "Viewer 1".to_owned()); + if dual_viewer { + seen.active.insert(g_v2, "Viewer 2".to_owned()); + } + seen.active.insert(g_flow, "Flow".to_owned()); + seen.active.insert(g_spline, "Spline".to_owned()); + seen.focused = Some(g_flow); + let dock = Dock::new(); + + let mut playback = PlaybackClock::new(); + playback.init_from_comp(&comp); + if let Some(f) = init_frame { + playback.set_frame(&comp, f, Instant::now()); + } + + let mut v1 = ViewerState::new(0, &ui_theme); + v1.viewed_node = comp.default_output_node(); + let mut v2 = ViewerState::new(1, &ui_theme); + v2.viewed_node = select_node.and_then(|n| comp.find_node(n)).or(v1.viewed_node); + + let mut flow = FlowView::new(&ui_theme); + flow.viewed_nodes = [v1.viewed_node, if dual_viewer { v2.viewed_node } else { None }]; + + let default_sel = select_node + .and_then(|n| comp.find_node(n)) + .or_else(|| comp.nodes.iter().find(|n| !comp.node_splines(n.id).is_empty()).map(|n| n.id)) + .or(v1.viewed_node); + if let Some(id) = default_sel { + flow.selected.insert(id); + flow.primary = Some(id); + } + + let mut spline = SplineView::new(&ui_theme); + spline.set_target_node(&comp, default_sel); + + Self { + ui, + dock, + layout, + seen, + renderer, + engine, + comp, + playback, + viewers: [v1, v2], + flow, + spline, + size: [1440.0, 900.0], + scale: 2.0, + clock: Instant::now(), + } + } + + fn ensure_viewer2_open(&mut self) { + if self.layout.group_of(&"Viewer 2".to_owned(), String::clone).is_some() { + return; + } + let target_group = self + .layout + .group_of(&"Viewer 1".to_owned(), String::clone) + .unwrap_or_else(|| self.dock.at(&mut self.layout, &mut self.seen, &String::clone).focused()); + self.dock + .at(&mut self.layout, &mut self.seen, &String::clone) + .open("Viewer 2".to_owned(), Place::Beside(target_group, Side::Right)); + } + + fn clear_viewers(&mut self) { + for v in &mut self.viewers { + v.clear(); + } + self.flow.viewed_nodes = [None, None]; + } + + fn frame(&mut self, now: Instant) -> bool { + self.clock = now; + let (animating, frame_changed) = self.playback.tick(&self.comp, now); + if frame_changed { + for v in &mut self.viewers { + v.dirty = true; + } + } + + let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown(); + for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] { + if shown.contains(&pane_name.to_owned()) { + self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale); + self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback); + } + } + self.flow.prepare_labels(&self.comp); + self.spline.prepare_labels(&self.comp); + + self.ui.begin(self.size, self.scale, now); + + let choices: Vec> = PANES + .iter() + .map(|&name| ui::popup::Item { text: name, ..Default::default() }) + .collect(); + + let Studio { + ui, + dock, + layout, + seen, + engine, + playback, + viewers, + flow, + spline, + size, + .. + } = self; + + let v1_bg = viewers[0].background(); + let v2_bg = viewers[1].background(); + let flow_bg = flow.background(); + let spline_bg = spline.background(); + let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new(); + + let mut d = dock.at(layout, seen, &String::clone); + let events = d.build( + ui, + "studio-dock", + *size, + |_| Plus::Menu("Open Pane", &choices), + &(), + |name: &String, _| { + let bg = match name.as_str() { + "Viewer 1" => v1_bg, + "Viewer 2" => v2_bg, + "Flow" => flow_bg, + "Spline" => spline_bg, + _ => flow_bg, + }; + Tab { + title: name, + icon: None, + unsaved: false, + closable: true, + action: None, + background: bg, + } + }, + |ui, name| { + let name = name?.as_str(); + match name { + "Viewer 1" => { + let acts = viewers[0].build_ui(ui, viewer_pane_id(0), viewer_canvas_id(0), engine, playback); + for a in acts { viewer_actions.push((0, a)); } + Some(viewer_canvas_id(0)) + } + "Viewer 2" => { + let acts = viewers[1].build_ui(ui, viewer_pane_id(1), viewer_canvas_id(1), engine, playback); + for a in acts { viewer_actions.push((1, a)); } + Some(viewer_canvas_id(1)) + } + "Flow" => { + let id = ui.open_as( + flow_canvas_id(), + ui::Spec { + flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, + size: [ui::fill(), ui::fill()], + ..ui::Spec::default() + }, + ); + ui.close(); + Some(id) + } + "Spline" => { + let id = ui.open_as( + spline_canvas_id(), + ui::Spec { + flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, + size: [ui::fill(), ui::fill()], + ..ui::Spec::default() + }, + ); + ui.close(); + Some(id) + } + _ => None, + } + }, + ); + self.ui.end(); + + for ev in events { + match ev { + Event::Close(name) => { + self.dock.at(&mut self.layout, &mut self.seen, &String::clone).close(&name); + } + Event::Plus { group, choice: Some(idx), .. } => { + if let Some(&name) = PANES.get(idx) { + self.dock.at(&mut self.layout, &mut self.seen, &String::clone).open(name.to_owned(), Place::Group(group)); + } + } + _ => {} + } + } + + self.route_viewer_actions(viewer_actions, now); + + for slot in [0usize, 1] { + let cid = viewer_canvas_id(slot); + if let Some(rect) = self.ui.laid_out(cid) { + self.viewers[slot].resize([rect[2] - rect[0], rect[3] - rect[1]]); + let sig = self.ui.signal(cid); + let ptr = self.ui.last_pointer(); + let mods = self.ui.modifiers(); + let mut acts = Vec::new(); + for ev in sig.events { + for a in self.viewers[slot].input(&self.comp, &self.playback, ev, rect, ptr, mods) { + acts.push((slot, a)); + } + } + self.route_viewer_actions(acts, now); + } + } + + if let Some(rect) = self.ui.laid_out(flow_canvas_id()) { + self.flow.resize([rect[2] - rect[0], rect[3] - rect[1]]); + self.flow.ensure_fitted(&self.comp); + let sig = self.ui.signal(flow_canvas_id()); + let ptr = self.ui.last_pointer(); + let mods = self.ui.modifiers(); + let mut acts = Vec::new(); + for ev in sig.events { + acts.extend(self.flow.input(&mut self.comp, ev, rect, ptr, mods)); + } + for a in acts { + match a { + FlowAction::SelectionChanged(sel) => { + self.spline.set_target_node(&self.comp, sel); + } + FlowAction::ViewNode(slot, id) => { + self.viewers[slot].viewed_node = Some(id); + self.viewers[slot].dirty = true; + self.flow.viewed_nodes[slot] = Some(id); + if slot == 1 { + self.ensure_viewer2_open(); + } + } + FlowAction::ClearViewers => { + self.clear_viewers(); + } + FlowAction::GraphMutated => { + for v in &mut self.viewers { + v.dirty = true; + } + } + } + } + } + + if let Some(rect) = self.ui.laid_out(spline_canvas_id()) { + self.spline.resize([rect[2] - rect[0], rect[3] - rect[1]]); + let sig = self.ui.signal(spline_canvas_id()); + let ptr = self.ui.last_pointer(); + let mods = self.ui.modifiers(); + let mut acts = Vec::new(); + for ev in sig.events { + acts.extend(self.spline.input(&mut self.comp, self.playback.current_frame, ev, rect, ptr, mods)); + } + for a in acts { + match a { + SplineAction::SplineEdited => { + if let Some(id) = self.flow.primary { + self.engine.bust_subtree(id); + } + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + SplineAction::ScrubFrame(f) => { + if self.playback.set_frame(&self.comp, f, now) { + for v in &mut self.viewers { + v.dirty = true; + } + } + } + } + } + } + + // Immediately re-render any dirty visible viewer before painting this frame! + let shown_now = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown(); + for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] { + if shown_now.contains(&pane_name.to_owned()) && self.viewers[slot].dirty { + self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale); + self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback); + } + } + + animating || self.ui.wants_frame() || self.dock.moving() + } + + fn route_viewer_actions(&mut self, actions: Vec<(usize, ViewerAction)>, now: Instant) { + for (slot, a) in actions { + match a { + ViewerAction::TogglePlay => self.playback.toggle_play(now), + ViewerAction::SetFrame(f) => { + if self.playback.set_frame(&self.comp, f, now) { + for v in &mut self.viewers { + v.dirty = true; + } + } + } + ViewerAction::ToggleSyncMode => { + self.playback.sync_mode = match self.playback.sync_mode { + SyncMode::RealtimeDrop => SyncMode::EveryFrame, + SyncMode::EveryFrame => SyncMode::RealtimeDrop, + }; + } + ViewerAction::NeedRender => { + self.viewers[slot].dirty = true; + } + ViewerAction::BustFrame(f) => { + self.engine.bust_frame(f); + for v in &mut self.viewers { + v.cached_frames.remove(&f); + v.dirty = true; + } + } + ViewerAction::BustSubtree => { + if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) { + self.engine.bust_subtree(id); + } + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + ViewerAction::BustGpu => { + self.engine.bust_gpu_cache(); + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + ViewerAction::BustAll => { + self.engine.bust_all_caches(); + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + ViewerAction::ToggleCacheBypass => { + let next = match self.engine.cache.mode { + CacheMode::Enabled => CacheMode::Bypass, + CacheMode::Bypass => CacheMode::Enabled, + }; + self.engine.set_cache_mode(next); + for v in &mut self.viewers { + v.dirty = true; + } + } + ViewerAction::SetProxy(scale) => { + if self.engine.proxy_scale != scale { + self.engine.proxy_scale = scale; + self.engine.bust_gpu_cache(); + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + } + ViewerAction::ToggleHiQ => { + self.engine.hiq = !self.engine.hiq; + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + ViewerAction::ClearViewers => { + self.clear_viewers(); + } + } + } + } + + fn paint(&mut self, target: &wgpu::TextureView, pixels: [u32; 2]) -> Result<(), Box> { + let scale = self.scale; + let cur_f = self.playback.current_frame; + let Studio { ui, renderer, comp, viewers, flow, spline, .. } = self; + + let mut custom_prims: HashMap>)> = HashMap::new(); + for slot in [0usize, 1] { + let cid = viewer_canvas_id(slot); + if let Some(r) = ui.laid_out(cid) { + custom_prims.insert(cid, (viewers[slot].background(), [r[0], r[1]], viewers[slot].paint(comp, cur_f))); + } + } + if let Some(r) = ui.laid_out(flow_canvas_id()) { + custom_prims.insert(flow_canvas_id(), (flow.background(), [r[0], r[1]], flow.paint(comp))); + } + if let Some(r) = ui.laid_out(spline_canvas_id()) { + custom_prims.insert(spline_canvas_id(), (spline.background(), [r[0], r[1]], spline.paint(comp, cur_f))); + } + + let interface = ui.layers(); + let layers: Vec = interface + .iter() + .filter_map(|layer| match layer { + ui::Layer::Primitives(prims) => Some(prims.layer(scale)), + ui::Layer::Custom { id, rect, .. } => { + let (bg, corner, prims) = custom_prims.get(id)?; + Some(draw::Layer { + scale, + origin: corner.map(|v| v * scale), + clip: Some(rect.map(|v| v * scale)), + backdrop: Some(*bg), + round: None, + motion: None, + primitives: prims, + }) + } + }) + .collect(); + + renderer + .draw(target, pixels, ui.theme.base, &layers) + .map_err(|e| format!("{e:?}"))?; + Ok(()) + } +} + +fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box> { + theme::fonts::register()?; + let comp = Comp::from_fusion_file(&cli.comp_path)?; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?; + let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?; + let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); + + let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer); + studio.size = [1440.0, 900.0]; + studio.scale = 2.0; + + let now = Instant::now(); + studio.frame(now); + studio.frame(now + Duration::from_millis(16)); + + let pixels = studio.size.map(|s| (s * studio.scale) as u32); + let tex = studio.renderer.offscreen(pixels); + let view = tex.create_view(&Default::default()); + studio.paint(&view, pixels)?; + let rgba = studio.renderer.read(&tex)?; + + let mut enc = png::Encoder::new(File::create(out_path)?, pixels[0], pixels[1]); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.write_header()?.write_image_data(&rgba)?; + eprintln!( + "Wrote docked Studio snapshot to {} ({}x{}) | eval={:.1}ms", + out_path.display(), + pixels[0], + pixels[1], + studio.viewers[0].last_stats.eval_ms + ); + Ok(()) +} + +#[allow(dead_code)] +enum UserEvent { + Redraw, + #[cfg(target_os = "macos")] + Quit, + Accessibility(accesskit_winit::Event), +} + +impl From for UserEvent { + fn from(event: accesskit_winit::Event) -> Self { + Self::Accessibility(event) + } +} + +struct WindowHost { + window: Arc, + surface: Surface, + studio: Studio, + access: Accessibility, + occluded: bool, +} + +struct App { + proxy: EventLoopProxy, + cli: Cli, + host: Option, + error: Option>, +} + +fn run_window(cli: &Cli) -> Result<(), Box> { + theme::fonts::register()?; + let mut builder = EventLoop::::with_user_event(); + #[cfg(target_os = "macos")] + { + use winit::platform::macos::EventLoopBuilderExtMacOS; + builder.with_activate_ignoring_other_apps(false); + } + let event_loop = builder.build()?; + let proxy = event_loop.create_proxy(); + let mut app = App { + proxy, + cli: Cli { + comp_path: cli.comp_path.clone(), + snapshot: None, + frame: cli.frame, + select_node: cli.select_node.clone(), + dual_viewer: cli.dual_viewer, + }, + host: None, + error: None, + }; + event_loop.run_app(&mut app)?; + match app.error { + Some(e) => Err(e), + None => Ok(()), + } +} + +impl WindowHost { + fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy, cli: &Cli) -> Result> { + let comp = Comp::from_fusion_file(&cli.comp_path)?; + let title = format!("Compositor — {}", comp.name); + let attrs = Window::default_attributes() + .with_title(title) + .with_inner_size(LogicalSize::new(1440.0, 900.0)); + let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?; + let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?; + let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer); + studio.ui.window_focused = window.has_focus(); + studio.ui.clipboard = Clipboard::system(); + window.request_redraw(); + #[cfg(target_os = "macos")] + { + let quit = proxy.clone(); + ui::host::macos::quit(move || { let _ = quit.send_event(UserEvent::Quit); }); + } + Ok(Self { window, surface, studio, access, occluded: false }) + } + + fn redraw(&mut self) -> Result<(), Box> { + let now = Instant::now(); + let wheel = self.surface.wheel.frame(now, self.studio.ui.reduces_motion()); + if wheel != [0.0; 2] { + self.studio.ui.event(ui::Event::Wheel(wheel)); + } + self.studio.scale = self.window.scale_factor() as f32; + let pixels = self.surface.fit(&self.studio.renderer); + if pixels.contains(&0) { + return Ok(()); + } + self.studio.size = pixels.map(|s| s as f32 / self.studio.scale); + let wants_more = self.studio.frame(now); + + self.window.set_cursor(self.studio.ui.cursor().unwrap_or(CursorIcon::Default)); + self.access.update_views(&mut self.studio.ui, "Compositor", f64::from(self.studio.scale), Vec::new); + + if !self.occluded && let Some(frame) = self.surface.frame(&self.studio.renderer, Some(&mut self.studio.ui))? { + self.studio.paint(&frame.target, pixels)?; + self.surface.present(&self.studio.renderer, frame); + } + if wants_more && !self.occluded { + self.window.request_redraw(); + } + Ok(()) + } + + fn input(&mut self, event: ui::Event) { + // Global Space toggles playback and `` ` `` clears both viewers from any focused pane! + let is_space = matches!( + &event, + ui::Event::KeyInput { key: Key::Named(NamedKey::Space), state: ElementState::Pressed, repeat: false, .. } + | ui::Event::Key { key: Key::Named(NamedKey::Space), .. } + ); + if is_space { + self.studio.playback.toggle_play(Instant::now()); + self.window.request_redraw(); + return; + } + let is_backquote = match &event { + ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true, + ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true, + _ => false, + }; + if is_backquote { + self.studio.clear_viewers(); + self.window.request_redraw(); + return; + } + if !self.studio.ui.popups_open() && let ui::Event::Key { key, modifiers, .. } = &event { + let cmd = match key { + Key::Named(NamedKey::Tab) if modifiers.control_key() => { + Some(if modifiers.shift_key() { Command::Previous } else { Command::Next }) + } + _ => None, + }; + if let Some(cmd) = cmd { + let _ = self.studio.dock.at(&mut self.studio.layout, &mut self.studio.seen, &String::clone).run(cmd); + self.window.request_redraw(); + return; + } + } + self.studio.ui.event(event); + self.window.request_redraw(); + } +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.host.is_some() { return; } + match WindowHost::new(event_loop, self.proxy.clone(), &self.cli) { + Ok(host) => self.host = Some(host), + Err(e) => { + self.error = Some(e); + event_loop.exit(); + } + } + } + + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) { + #[cfg(not(target_os = "macos"))] + let _ = event_loop; + let Some(host) = &mut self.host else { return }; + match event { + UserEvent::Redraw => host.window.request_redraw(), + #[cfg(target_os = "macos")] + UserEvent::Quit => { + ui::host::macos::finish_quit(true); + event_loop.exit(); + } + UserEvent::Accessibility(ev) => match ev.window_event { + accesskit_winit::WindowEvent::InitialTreeRequested => { + host.access.forget(&mut host.studio.ui); + host.window.request_redraw(); + } + accesskit_winit::WindowEvent::AccessibilityDeactivated => host.access.forget(&mut host.studio.ui), + accesskit_winit::WindowEvent::ActionRequested(req) => host.input(ui::Event::Access(req)), + }, + } + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) { + let Some(host) = &mut self.host else { return }; + host.access.adapter.process_event(&host.window, &event); + if let Some(Err(e)) = ui::host::draw(&event, || host.redraw()) { + self.error = Some(e); + event_loop.exit(); + return; + } + let page = host.surface.size[1] as f32 / host.window.scale_factor() as f32; + if let Some(wheel) = host.surface.wheel.input(&host.window, &event, page, host.studio.ui.reduces_motion(), Instant::now()) { + if wheel != [0.0; 2] { host.input(ui::Event::Wheel(wheel)); } + host.window.request_redraw(); + return; + } + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::Focused(focused) => { + ui::host::focus(&mut host.studio.ui, focused); + host.window.request_redraw(); + } + WindowEvent::ScaleFactorChanged { .. } => { + host.studio.renderer.clear_glyph_cache(); + host.window.request_redraw(); + } + WindowEvent::Occluded(occluded) => { + host.occluded = occluded; + if occluded { host.surface.wheel.cancel(); } + else { host.window.request_redraw(); } + } + // Route full physical + logical key events when a custom pane (Viewer/Flow/Spline) has focus! + WindowEvent::KeyboardInput { event: key_ev, is_synthetic: false, .. } + if host.studio.ui.full_key_input() => + { + let held = host.studio.ui.modifiers(); + host.input(ui::Event::from_key(key_ev, held)); + } + other => { + if let Some(input) = ui::Event::from_window(other, host.window.scale_factor() as f32, host.studio.ui.modifiers()) { + host.input(input); + } + } + } + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if let Some(host) = &self.host { + if host.studio.playback.playing && !host.occluded { + let wake = host.studio.playback.next_wake(&host.studio.comp); + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake)); + host.window.request_redraw(); + return; + } + } + event_loop.set_control_flow(ControlFlow::Wait); + } +} diff --git a/crates/viewer/Cargo.toml b/crates/viewer/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..62ed51d33cb724bd01b56a754f15589d55e57e59 --- /dev/null +++ b/crates/viewer/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "viewer" +edition.workspace = true +version.workspace = true +publish.workspace = true + +[dependencies] +draw.workspace = true +engine.workspace = true +model.workspace = true +text.workspace = true +theme.workspace = true +ui.workspace = true +wgpu.workspace = true +winit.workspace = true diff --git a/crates/viewer/src/lib.rs b/crates/viewer/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..d45025c2bc9e65bfa049f8f84d81a8b1614ab01d --- /dev/null +++ b/crates/viewer/src/lib.rs @@ -0,0 +1,803 @@ +//! Minimal zero-copy `wgpu` comp video player built on `draw` + `ui`. +//! +//! Features: +//! - Multi-viewer support (Viewer 1 & Viewer 2 sharing a synchronized timeline clock) +//! - Realtime (drop frames) AND Every-Frame (throttled to <= comp.fps — never faster than realtime!) +//! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions +//! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view. + +use draw::{Glyphs, Primitive, RasterImage}; +use engine::{CacheMode, DisplaySettings, Engine, EvalStats}; +use model::{Comp, NodeId}; +use std::collections::HashSet; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use winit::event::{ElementState, MouseButton}; +use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SyncMode { + /// Wall/audio clock master: skips frames to hold real-time FPS. + RealtimeDrop, + /// Steps exactly +1 integer frame, throttled so it never runs faster than `comp.fps`. + EveryFrame, +} + +/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline). +pub struct PlaybackClock { + pub current_frame: f64, + pub playing: bool, + pub sync_mode: SyncMode, + anchor_time: Instant, + anchor_frame: f64, + last_every_step: Instant, +} + +impl Default for PlaybackClock { + fn default() -> Self { + Self::new() + } +} + +impl PlaybackClock { + pub fn new() -> Self { + let now = Instant::now(); + Self { + current_frame: 0.0, + playing: false, + sync_mode: SyncMode::RealtimeDrop, + anchor_time: now, + anchor_frame: 0.0, + last_every_step: now, + } + } + + pub fn init_from_comp(&mut self, comp: &Comp) { + let cur = comp.current_time.round(); + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1] as f64; + self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 }; + self.anchor_frame = self.current_frame; + self.anchor_time = Instant::now(); + self.last_every_step = self.anchor_time; + } + + pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool { + let clamped = frame + .round() + .clamp(comp.global_range[0] as f64, comp.global_range[1] as f64); + let changed = (clamped - self.current_frame).abs() > 1e-6; + self.current_frame = clamped; + if self.playing { + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + changed + } + + pub fn toggle_play(&mut self, now: Instant) { + self.playing = !self.playing; + self.anchor_time = now; + self.anchor_frame = self.current_frame; + self.last_every_step = now; + } + + /// Advances the playback clock; returns `(still_playing, frame_changed)`. + /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime! + pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) { + if !self.playing { + return (false, false); + } + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; + let span = (r1 - r0 + 1.0).max(1.0); + let fps = comp.fps.max(1.0); + let frame_dur = Duration::from_secs_f64(1.0 / fps); + + let mut changed = false; + match self.sync_mode { + SyncMode::RealtimeDrop => { + let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64(); + let adv = (elapsed * fps).floor(); + let next = r0 + (self.anchor_frame - r0 + adv).rem_euclid(span); + if (next - self.current_frame).abs() >= 1.0 { + self.current_frame = next; + changed = true; + } + } + SyncMode::EveryFrame => { + if now.saturating_duration_since(self.last_every_step) >= frame_dur { + let next = if self.current_frame + 1.0 > r1 { + r0 + } else { + self.current_frame + 1.0 + }; + self.current_frame = next; + self.last_every_step = now; + changed = true; + } + } + } + (true, changed) + } + + pub fn next_wake(&self, comp: &Comp) -> Duration { + let fps = comp.fps.max(1.0); + Duration::from_secs_f64((0.5 / fps).min(0.016)) + } +} + +pub enum ViewerAction { + TogglePlay, + SetFrame(f64), + ToggleSyncMode, + NeedRender, + BustFrame(i64), + BustSubtree, + BustGpu, + BustAll, + ToggleCacheBypass, + SetProxy(u32), + ToggleHiQ, + ClearViewers, +} + +#[derive(Clone, Copy, Debug)] +pub struct ViewerPalette { + pub bg: [f32; 4], + pub bar: [f32; 4], + pub scrub_bg: [f32; 4], + pub border: [f32; 4], + pub text: [f32; 4], + pub accent: [f32; 4], +} + +impl ViewerPalette { + pub fn from_ui(theme: &ui::Theme) -> Self { + let b = theme.base; + let lift = |c: [f32; 4], d: f32| { + [(c[0] + d).clamp(0.0, 1.0), (c[1] + d).clamp(0.0, 1.0), (c[2] + d).clamp(0.0, 1.0), 1.0] + }; + Self { + bg: b, + bar: theme.strip, + scrub_bg: lift(b, 0.024), + border: theme.rule, + text: theme.text, + accent: theme.accent, + } + } +} + +pub struct ViewerState { + pub slot: usize, // 0 = Viewer 1, 1 = Viewer 2 + pub viewed_node: Option, + pub display: DisplaySettings, + pub zoom: f32, + pub pan: [f32; 2], + pub fit_mode: bool, + pub size: [f32; 2], + pub last_stats: EvalStats, + pub cached_frames: HashSet, + pub dirty: bool, + pub palette: ViewerPalette, + last_revision: u64, + last_rendered_frame: i64, + last_viewed_node: Option, + output_tex: Option, + output_image: Option, + output_size: [u32; 2], + last_uv_rect: [f32; 4], + panning: Option<([f32; 2], [f32; 2])>, + scrubbing: bool, + pointer_local: [f32; 2], + hud_layout: Option<(String, text::Layout)>, +} + +impl ViewerState { + pub fn new(slot: usize, theme: &ui::Theme) -> Self { + Self { + slot, + viewed_node: None, + display: DisplaySettings::default(), + zoom: 1.0, + pan: [0.0, 0.0], + fit_mode: true, + size: [800.0, 500.0], + last_stats: EvalStats::default(), + cached_frames: HashSet::new(), + dirty: true, + palette: ViewerPalette::from_ui(theme), + last_revision: 0, + last_rendered_frame: i64::MIN, + last_viewed_node: None, + output_tex: None, + output_image: None, + output_size: [0, 0], + last_uv_rect: [0.0, 0.0, 1.0, 1.0], + panning: None, + scrubbing: false, + pointer_local: [0.0, 0.0], + hud_layout: None, + } + } + + pub fn background(&self) -> [f32; 4] { + self.palette.bg + } + + pub fn resize(&mut self, size: [f32; 2]) { + let clamped = [size[0].max(1.0), size[1].max(1.0)]; + if (self.size[0] - clamped[0]).abs() > 0.5 || (self.size[1] - clamped[1]).abs() > 0.5 { + self.size = clamped; + self.dirty = true; + } + } + + pub fn fit(&mut self) { + self.fit_mode = true; + self.pan = [0.0, 0.0]; + self.dirty = true; + } + + pub fn clear(&mut self) { + self.viewed_node = None; + self.last_viewed_node = None; + self.output_tex = None; + self.output_image = None; + self.output_size = [0, 0]; + self.dirty = false; + } + + /// Computes `(full_img_rect, visible_rect, uv_rect, effective_scale)` in viewer-local coordinates. + fn image_layout(&self, comp: &Comp) -> ([f32; 4], [f32; 4], [f32; 4], f32) { + let [w, h] = self.size; + let top_pad = 30.0; + let view_h = (h - 34.0).max(20.0); + let avail_h = (view_h - top_pad - 6.0).max(20.0); + let iw = comp.width.max(1) as f32; + let ih = comp.height.max(1) as f32; + let scale = if self.fit_mode { + ((w - 24.0) / iw).min((avail_h - 4.0) / ih).max(0.05) + } else { + self.zoom + }; + let dw = iw * scale; + let dh = ih * scale; + let cx = w * 0.5 + if self.fit_mode { 0.0 } else { self.pan[0] }; + let cy = top_pad + avail_h * 0.5 + if self.fit_mode { 0.0 } else { self.pan[1] }; + let img = [cx - dw * 0.5, cy - dh * 0.5, cx + dw * 0.5, cy + dh * 0.5]; + let vp = [4.0, top_pad, (w - 4.0).max(8.0), (view_h - 2.0).max(top_pad + 4.0)]; + let vis = [ + img[0].max(vp[0]), + img[1].max(vp[1]), + img[2].min(vp[2]), + img[3].min(vp[3]), + ]; + let u0 = ((vis[0] - img[0]) / dw.max(1e-4)).clamp(0.0, 1.0); + let v0 = ((vis[1] - img[1]) / dh.max(1e-4)).clamp(0.0, 1.0); + let u1 = ((vis[2] - img[0]) / dw.max(1e-4)).clamp(0.0, 1.0); + let v1 = ((vis[3] - img[1]) / dh.max(1e-4)).clamp(0.0, 1.0); + (img, vis, [u0, v0, u1, v1], scale) + } + + fn zoom_at(&mut self, comp: &Comp, factor: f32, pivot_local: [f32; 2]) { + let (img, _, _, cur_scale) = self.image_layout(comp); + let [w, h] = self.size; + let top_pad = 30.0; + let view_h = (h - 34.0).max(20.0); + let avail_h = (view_h - top_pad - 6.0).max(20.0); + let iw = comp.width.max(1) as f32; + let ih = comp.height.max(1) as f32; + + // Image UV right underneath the mouse cursor stays fixed through zoom! + let u = (pivot_local[0] - img[0]) / (img[2] - img[0]).max(1e-4); + let v = (pivot_local[1] - img[1]) / (img[3] - img[1]).max(1e-4); + + let new_scale = (cur_scale * factor).clamp(0.05, 32.0); + let new_dw = iw * new_scale; + let new_dh = ih * new_scale; + let new_x0 = pivot_local[0] - u * new_dw; + let new_y0 = pivot_local[1] - v * new_dh; + let new_cx = new_x0 + new_dw * 0.5; + let new_cy = new_y0 + new_dh * 0.5; + + self.fit_mode = false; + self.zoom = new_scale; + self.pan = [new_cx - w * 0.5, new_cy - (top_pad + avail_h * 0.5)]; + self.dirty = true; + } + + pub fn ensure_rendered(&mut self, engine: &mut Engine, comp: &Comp, current_frame: f64, dpi_scale: f32) { + let Some(target) = self.viewed_node else { + return; + }; + let frame_i = current_frame.round() as i64; + let (_, vis, uv_rect, _) = self.image_layout(comp); + if vis[2] <= vis[0] + 1.0 || vis[3] <= vis[1] + 1.0 { + return; + } + // Viewport-exact physical pixel backing texture -> 1:1 display with ZERO bilinear blur when Smooth Resize is OFF! + let desired_size = [ + ((vis[2] - vis[0]) * dpi_scale).round().clamp(1.0, 2880.0) as u32, + ((vis[3] - vis[1]) * dpi_scale).round().clamp(1.0, 1800.0) as u32, + ]; + + if self.output_size != desired_size || self.output_tex.is_none() { + let tex = engine.device().create_texture(&wgpu::TextureDescriptor { + label: Some("viewer-output"), + size: wgpu::Extent3d { + width: desired_size[0], + height: desired_size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let tex_for_draw = tex.clone(); + let img = RasterImage::from_texture(desired_size, move |_| tex_for_draw.clone()); + self.output_tex = Some(tex); + self.output_image = Some(img); + self.output_size = desired_size; + self.dirty = true; + } + + let uv_changed = (0..4).any(|i| (uv_rect[i] - self.last_uv_rect[i]).abs() > 1e-5); + let needs_eval = self.dirty + || uv_changed + || self.last_revision != comp.revision + || self.last_rendered_frame != frame_i + || self.last_viewed_node != Some(target); + + if needs_eval { + if let Some(tex) = &self.output_tex { + let mut disp = self.display; + disp.uv_rect = uv_rect; + self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp); + if engine.cache.mode == CacheMode::Enabled { + self.cached_frames.insert(frame_i); + } + self.dirty = false; + self.last_uv_rect = uv_rect; + self.last_revision = comp.revision; + self.last_rendered_frame = frame_i; + self.last_viewed_node = Some(target); + } + } + } + + pub fn prepare_hud(&mut self, comp: &Comp, engine: &Engine, clock: &PlaybackClock) { + let node_name = self + .viewed_node + .map(|id| comp.node(id).name.as_str()) + .unwrap_or("(empty)"); + let cache_lbl = match engine.cache.mode { + CacheMode::Enabled => "CACHE", + CacheMode::Bypass => "BYPASS", + }; + let sync_lbl = match clock.sync_mode { + SyncMode::RealtimeDrop => "RT", + SyncMode::EveryFrame => "EVERY", + }; + let hiq_lbl = if engine.hiq { "HiQ" } else { "FAST" }; + let (_, _, _, eff_scale) = self.image_layout(comp); + let zoom_pct = (eff_scale * 100.0).round() as i32; + let s = &self.last_stats; + let line = format!( + "[V{}] {} · f{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}", + self.slot + 1, + node_name, + clock.current_frame.round() as i64, + zoom_pct, + s.eval_ms, + s.nodes_evaluated, + s.cache_hits, + s.cache_misses, + s.cached_vram_mb, + engine.proxy_scale, + hiq_lbl, + cache_lbl, + sync_lbl, + ); + if self.hud_layout.as_ref().is_none_or(|(prev, _)| prev != &line) { + let font = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.5, + weight: 500, + italic: false, + }; + let styles = [text::Style::new(font)]; + let layout = text::Paragraph { + text: &line, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout(); + self.hud_layout = Some((line, layout)); + } + } + + pub fn build_ui( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + canvas_id: ui::Id, + engine: &Engine, + clock: &PlaybackClock, + ) -> Vec { + let mut actions = Vec::new(); + ui.open_as( + pane_id, + ui::Spec { + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + fill: Some(self.background()), + ..ui::Spec::default() + }, + ); + + ui.open( + ("top_bar", self.slot), + ui::Spec { + size: [ui::fill(), ui::px(30.0)], + axis: ui::Axis::X, + pad: [6.0, 4.0], + gap: 4.0, + fill: Some(self.palette.bar), + ..ui::Spec::default() + }, + ); + + if self.slot == 0 { + let play_lbl = if clock.playing { "Pause" } else { "Play" }; + if tool_btn(ui, ("play", self.slot), play_lbl, clock.playing).clicked { + actions.push(ViewerAction::TogglePlay); + } + if tool_btn(ui, ("prev", self.slot), "<", false).clicked { + actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)); + } + if tool_btn(ui, ("next", self.slot), ">", false).clicked { + actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)); + } + let sync_lbl = match clock.sync_mode { + SyncMode::RealtimeDrop => "RT", + SyncMode::EveryFrame => "Every", + }; + if tool_btn(ui, ("sync", self.slot), sync_lbl, clock.sync_mode == SyncMode::EveryFrame).clicked { + actions.push(ViewerAction::ToggleSyncMode); + } + for scale in [1u32, 2, 4] { + let lbl = format!("1:{scale}"); + if tool_btn(ui, ("proxy", self.slot, scale), &lbl, engine.proxy_scale == scale).clicked { + actions.push(ViewerAction::SetProxy(scale)); + } + } + if tool_btn(ui, ("hiq", self.slot), "HiQ", engine.hiq).clicked { + actions.push(ViewerAction::ToggleHiQ); + } + } + + let ch_lbl = match self.display.channel { + 1 => "R", + 2 => "G", + 3 => "B", + 4 => "A", + _ => "RGBA", + }; + if tool_btn(ui, ("chan", self.slot), ch_lbl, self.display.channel != 0).clicked { + self.display.channel = (self.display.channel + 1) % 5; + self.dirty = true; + actions.push(ViewerAction::NeedRender); + } + let filt_lbl = if self.display.smooth_resize { "Smooth" } else { "Pixel" }; + if tool_btn(ui, ("smooth", self.slot), filt_lbl, self.display.smooth_resize).clicked { + self.display.smooth_resize = !self.display.smooth_resize; + self.dirty = true; + actions.push(ViewerAction::NeedRender); + } + if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked { + self.fit(); + } + + if self.slot == 0 { + let bypass_lbl = match engine.cache.mode { + CacheMode::Enabled => "Cache", + CacheMode::Bypass => "Bypass", + }; + if tool_btn(ui, ("cache_mode", self.slot), bypass_lbl, engine.cache.mode == CacheMode::Bypass).clicked { + actions.push(ViewerAction::ToggleCacheBypass); + } + if tool_btn(ui, ("bust_frame", self.slot), "Bust F", false).clicked { + let f = clock.current_frame.round() as i64; + self.cached_frames.remove(&f); + self.dirty = true; + actions.push(ViewerAction::BustFrame(f)); + } + if tool_btn(ui, ("bust_sub", self.slot), "Node", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustSubtree); + } + if tool_btn(ui, ("bust_gpu", self.slot), "GPU", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustGpu); + } + if tool_btn(ui, ("bust_all", self.slot), "All", false).clicked { + self.cached_frames.clear(); + self.dirty = true; + actions.push(ViewerAction::BustAll); + } + } + ui.close(); + + ui.open_as( + canvas_id, + ui::Spec { + flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, + size: [ui::fill(), ui::fill()], + ..ui::Spec::default() + }, + ); + ui.close(); + + ui.close(); + actions + } + + fn scrubber_rect(&self) -> [f32; 4] { + [ + 10.0, + (self.size[1] - 26.0).max(4.0), + (self.size[0] - 10.0).max(20.0), + (self.size[1] - 8.0).max(20.0), + ] + } + + fn frame_at_x(&self, comp: &Comp, local_x: f32) -> f64 { + let r = self.scrubber_rect(); + let frac = ((local_x - r[0]) / (r[2] - r[0]).max(1.0)).clamp(0.0, 1.0); + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; + (r0 + f64::from(frac) * (r1 - r0)).round() + } + + fn handle_key(&mut self, clock: &PlaybackClock, physical: Option, key: &Key, kmod: ModifiersState, actions: &mut Vec) { + if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { + self.fit(); + return; + } + if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) { + actions.push(ViewerAction::ClearViewers); + return; + } + match key { + Key::Named(NamedKey::Space) => actions.push(ViewerAction::TogglePlay), + Key::Named(NamedKey::ArrowLeft) => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), + Key::Named(NamedKey::ArrowRight) => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), + Key::Character(c) => match c.to_ascii_lowercase().as_str() { + "`" | "~" => actions.push(ViewerAction::ClearViewers), + "f" if kmod.super_key() => self.fit(), + "f" | "." if !kmod.super_key() => self.fit(), + "0" => { + self.fit_mode = false; + self.zoom = 1.0; + self.pan = [0.0, 0.0]; + self.dirty = true; + } + "[" => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), + "]" => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), + _ => {} + }, + _ => {} + } + } + + pub fn input( + &mut self, + comp: &Comp, + clock: &PlaybackClock, + event: ui::Event, + rect: [f32; 4], + pointer_window: [f32; 2], + modifiers: ModifiersState, + ) -> Vec { + let mut actions = Vec::new(); + self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; + let scrub = self.scrubber_rect(); + + match event { + ui::Event::PointerMoved(p) => { + self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; + if self.scrubbing { + actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); + } else if let Some((sp, span)) = self.panning { + self.fit_mode = false; + self.pan = [ + span[0] + (self.pointer_local[0] - sp[0]), + span[1] + (self.pointer_local[1] - sp[1]), + ]; + self.dirty = true; + } + } + ui::Event::Button { button, pressed, .. } => { + if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { + if pressed { + if self.fit_mode { + let (_, _, _, cur_scale) = self.image_layout(comp); + self.zoom = cur_scale; + self.pan = [0.0, 0.0]; + self.fit_mode = false; + } + self.panning = Some((self.pointer_local, self.pan)); + } else { + self.panning = None; + } + } else if button == MouseButton::Left { + if pressed { + if self.pointer_local[1] >= scrub[1] - 6.0 { + self.scrubbing = true; + actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); + } + } else { + self.scrubbing = false; + } + } + } + ui::Event::Wheel(delta) => { + // Blender & Fusion convention: plain scroll zooms toward mouse cursor; Shift+scroll pans. + if modifiers.shift_key() { + if self.fit_mode { + let (_, _, _, cur_scale) = self.image_layout(comp); + self.zoom = cur_scale; + self.pan = [0.0, 0.0]; + self.fit_mode = false; + } + self.pan[0] += delta[0]; + self.pan[1] += delta[1]; + self.dirty = true; + } else { + let factor = (1.0 + delta[1] * 0.0045).clamp(0.7, 1.4); + self.zoom_at(comp, factor, self.pointer_local); + } + } + ui::Event::Pinch(delta) => { + let factor = (1.0 + delta).clamp(0.7, 1.4); + self.zoom_at(comp, factor, self.pointer_local); + } + ui::Event::KeyInput { physical, key, state: ElementState::Pressed, .. } => { + self.handle_key(clock, Some(physical), &key, modifiers, &mut actions); + } + ui::Event::Key { key, modifiers: kmod, .. } => { + self.handle_key(clock, None, &key, kmod, &mut actions); + } + _ => {} + } + actions + } + + pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { + let mut out = Vec::with_capacity(64); + let [w, _h] = self.size; + + if self.viewed_node.is_some() { + if let Some(img) = &self.output_image { + let (full_rect, vis, _, _) = self.image_layout(comp); + if vis[2] > vis[0] + 0.5 && vis[3] > vis[1] + 0.5 { + out.push(Primitive::Image { image: img, rect: vis, radius: 0.0 }); + out.push(Primitive::RoundedRect { + rect: [ + full_rect[0].max(vis[0]), + full_rect[1].max(vis[1]), + full_rect[2].min(vis[2]), + full_rect[3].min(vis[3]), + ], + radius: 1.0, + stroke: Some(1.0), + color: self.palette.border, + }); + } + } + } + + if let Some((_, layout)) = &self.hud_layout { + out.push(Primitive::RoundedRect { + rect: [8.0, 5.0, (w - 8.0).max(20.0), 24.0], + radius: 4.0, + stroke: None, + color: [self.palette.bg[0] * 0.72, self.palette.bg[1] * 0.72, self.palette.bg[2] * 0.72, 0.82], + }); + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [14.0, 8.0], + clip: Some([12.0, 5.0, w - 12.0, 24.0]), + ink: self.palette.text, + }); + } + + let sr = self.scrubber_rect(); + out.push(Primitive::RoundedRect { rect: sr, radius: 4.0, stroke: None, color: self.palette.scrub_bg }); + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; + let span = (r1 - r0).max(1.0); + let bar_w = (sr[2] - sr[0]).max(1.0); + let tick_w = (bar_w / span as f32).max(2.0); + for &cf in &self.cached_frames { + if (cf as f64) >= r0 && (cf as f64) <= r1 { + let frac = ((cf as f64 - r0) / span) as f32; + let x = sr[0] + frac * bar_w; + out.push(Primitive::Rect { + rect: [x, sr[3] - 4.0, (x + tick_w).min(sr[2]), sr[3] - 1.0], + color: [0.24, 0.84, 0.50, 0.85], + }); + } + } + + let frac = ((current_frame - r0) / span).clamp(0.0, 1.0) as f32; + let px = sr[0] + frac * bar_w; + out.push(Primitive::RoundedRect { + rect: [sr[0], sr[1], px.max(sr[0] + 2.0), sr[3]], + radius: 4.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25], + }); + out.push(Primitive::RoundedRect { + rect: [px - 3.0, sr[1] - 2.0, px + 3.0, sr[3] + 2.0], + radius: 2.0, + stroke: None, + color: [0.98, 0.40, 0.36, 1.0], + }); + + out + } +} + +/// Sleek Knife-style compact toolbar control (soft tinted surface + hairline border, +/// accent tint when active — replaces the chunky generic `ui::button`). +fn tool_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal { + let t = &ui.theme; + let fill = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.24] + } else { + [t.base[0], t.base[1], t.base[2], 0.65] + }; + let border = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.65] + } else { + t.rule + }; + let ink = if active { t.text } else { t.text_dim }; + ui.leaf( + part, + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fit(), ui::px(22.0)], + text: Some(label), + font_size: Some(11.5), + medium: true, + color: Some(ink), + fill: Some(fill), + border: Some(border), + hover_fill: Some(t.ghost_soft), + hover_border: Some(t.accent), + radius: 5.0, + pad: [7.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ) +} diff --git a/scripts/fusion_probes.py b/scripts/fusion_probes.py new file mode 100644 index 0000000000000000000000000000000000000000..71151341b853cd9993c10d4bd734ef684a48ff00 --- /dev/null +++ b/scripts/fusion_probes.py @@ -0,0 +1,1033 @@ +#!/usr/bin/env python3 +"""Fusion Render Node (sg render) conformance probe generator & comparator. + +Generates compact multi-frame .comp files, renders ground truth on Snow Globe's RTX 3090 via +`sg render` (using /Volumes/clover directly if mounted, or sg upload/download to /srv/clover), +and compares every frame against our `target/release/render-check`. +""" + +import math +import os +import struct +import subprocess +import sys +import zlib +from pathlib import Path + +SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes") +REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes" +CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes" +LOCAL_FALLBACK = Path( + "/Users/clo/.knife/agent/gemini-roPs/antigravity-cli/brain/d42ef021-5bce-4812-b5e5-1e3ed7ce6c77/scratch/probes" +) +REPO = Path("/Users/clo/dev/compositor") +RENDER_CHECK = REPO / "target/release/render-check" + + +def use_smb() -> bool: + return SMB_ROOT.parent.exists() + + +def local_root() -> Path: + return SMB_ROOT if use_smb() else LOCAL_FALLBACK + + +def ensure_dirs(): + r = local_root() + for sub in ("comps", "assets", "gt", "ours"): + (r / sub).mkdir(parents=True, exist_ok=True) + + +def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes): + def chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + raw = bytearray() + stride = w * 4 + for y in range(h): + raw.append(0) + raw.extend(rgba_bytes[y * stride : (y + 1) * stride]) + + ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", ihdr) + + chunk(b"IDAT", zlib.compress(bytes(raw), level=6)) + + chunk(b"IEND", b"") + ) + path.write_bytes(png) + + +def hsv_to_rgb(h: float, s: float, v: float): + h = (h % 1.0) * 6.0 + i = int(h) + f = h - i + p = v * (1.0 - s) + q = v * (1.0 - s * f) + t = v * (1.0 - s * (1.0 - f)) + return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6] + + +def sync_asset(local_path: Path): + if not use_smb(): + subprocess.run(["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"], check=True) + + +def generate_color_chart() -> str: + """Straight-alpha PNG color chart (512x512).""" + p = local_root() / "assets" / "color_chart.png" + if p.exists() and p.stat().st_size > 1000: + return f"{CONTAINER_ROOT}/assets/color_chart.png" + w, h = 512, 512 + buf = bytearray(w * h * 4) + for y in range(h): + ny = y / (h - 1) + for x in range(w): + nx = x / (w - 1) + r, g, b, a = 0.0, 0.0, 0.0, 1.0 + if ny < 0.45: + r, g, b = hsv_to_rgb(nx, ny / 0.45, 0.85) + elif ny < 0.70: + t = (ny - 0.45) / 0.25 + wave = 0.5 + 0.5 * math.sin(nx * 25.0 + ny * 40.0) + r, g, b = hsv_to_rgb(0.62 + 0.08 * math.sin(nx * 6.0), 0.08 + 0.25 * t * (0.4 + 0.6 * wave), 0.78 + 0.20 * (1.0 - t)) + elif ny < 0.85: + if nx < 0.5: + g0 = nx * 2.0 + r, g, b = g0, g0, g0 + else: + r, g, b = hsv_to_rgb((nx - 0.5) * 2.0, 1.0, 0.35 + 0.65 * ((ny - 0.70) / 0.15)) + else: + r, g, b = hsv_to_rgb(nx, 0.9, 0.9) + a = 1.0 - (ny - 0.85) / 0.15 + idx = (y * w + x) * 4 + buf[idx] = max(0, min(255, int(round(r * 255)))) + buf[idx + 1] = max(0, min(255, int(round(g * 255)))) + buf[idx + 2] = max(0, min(255, int(round(b * 255)))) + buf[idx + 3] = max(0, min(255, int(round(a * 255)))) + write_png_rgba(p, w, h, bytes(buf)) + sync_asset(p) + return f"{CONTAINER_ROOT}/assets/color_chart.png" + + +def generate_grid_chart() -> str: + """512x512 crisp colored grid + asymmetric L-shape for 3D / Transform / Displace orientation tests.""" + p = local_root() / "assets" / "grid_chart.png" + if p.exists() and p.stat().st_size > 1000: + return f"{CONTAINER_ROOT}/assets/grid_chart.png" + w, h = 512, 512 + buf = bytearray(w * h * 4) + for y in range(h): + for x in range(w): + r, g, b, a = 24, 28, 36, 255 + # Colored quadrants + if x < 256 and y < 256: + r, g, b = 190, 60, 60 # top-left = red + elif x >= 256 and y < 256: + r, g, b = 60, 180, 75 # top-right = green + elif x < 256 and y >= 256: + r, g, b = 60, 95, 200 # bottom-left = blue + else: + r, g, b = 210, 180, 50 # bottom-right = yellow + # Grid lines every 64px + if x % 64 < 3 or y % 64 < 3: + r, g, b = 245, 245, 245 + # Asymmetric white arrow pointing UP-RIGHT in center + if 220 <= x <= 290 and 120 <= y <= 380 and abs(x - 256) < 12: + r, g, b = 255, 255, 255 + if 120 <= y <= 180 and abs(x - 256) < (y - 120): + r, g, b = 255, 255, 255 + # Small bright square at top-left (x=64..96, y=64..96) + if 64 <= x < 112 and 64 <= y < 112: + r, g, b = 255, 255, 0 + idx = (y * w + x) * 4 + buf[idx:idx+4] = bytes((r, g, b, a)) + write_png_rgba(p, w, h, bytes(buf)) + sync_asset(p) + return f"{CONTAINER_ROOT}/assets/grid_chart.png" + + +def step_spline(name: str, frame_values: dict) -> str: + kfs = [] + for f, v in sorted(frame_values.items()): + kfs.append(f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }},") + return f"""\t\t{name} = BezierSpline {{ +\t\t\tKeyFrames = {{ +{chr(10).join(kfs)} +\t\t\t}}, +\t\t}},""" + + +def make_loader(name: str, container_path: str, post_mult: int = 1) -> str: + return f"""\t\t{name} = Loader {{ +\t\t\tClips = {{ +\t\t\t\tClip {{ +\t\t\t\t\tID = "Clip1", +\t\t\t\t\tFilename = "{container_path}", +\t\t\t\t\tFormatID = "PNGFormat", +\t\t\t\t\tLength = 1, +\t\t\t\t\tLengthSetManually = true, +\t\t\t\t\tTrimIn = 0, +\t\t\t\t\tTrimOut = 0, +\t\t\t\t\tExtendFirst = 0, +\t\t\t\t\tExtendLast = 0, +\t\t\t\t\tLoop = 1, +\t\t\t\t\tStartFrame = -1, +\t\t\t\t\tGlobalStart = 0, +\t\t\t\t\tGlobalEnd = 100, +\t\t\t\t}}, +\t\t\t}}, +\t\t\tInputs = {{ +\t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }}, +\t\t\t}}, +\t\t}},""" + + +def make_saver(src_op: str, prefix: str) -> str: + return f"""\t\tSaver1 = Saver {{ +\t\t\tInputs = {{ +\t\t\t\tClip = Input {{ +\t\t\t\t\tValue = Clip {{ +\t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png", +\t\t\t\t\t\tFormatID = "PNGFormat", +\t\t\t\t\t\tLength = 0, +\t\t\t\t\t\tSaving = true, +\t\t\t\t\t\tTrimIn = 0, +\t\t\t\t\t\tExtendFirst = 0, +\t\t\t\t\t\tExtendLast = 0, +\t\t\t\t\t\tLoop = 1, +\t\t\t\t\t\tAspectMode = 0, +\t\t\t\t\t\tDepth = 0, +\t\t\t\t\t\tGlobalStart = -2000000000, +\t\t\t\t\t\tGlobalEnd = 0, +\t\t\t\t\t}}, +\t\t\t\t}}, +\t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }}, +\t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + + +def make_comp(tools_body: str, end_frame: int, w: int = 512, h: int = 512) -> str: + return f"""Composition {{ +\tCurrentTime = 0, +\tRenderRange = {{ 0, {end_frame} }}, +\tGlobalRange = {{ 0, {end_frame} }}, +\tCurrentID = 200, +\tHiQ = true, +\tPlaybackUpdateMode = 0, +\tVersion = "Fusion Studio 21.1 build 23", +\tTools = ordered() {{ +{tools_body} +\t}}, +\tPrefs = {{ +\t\tComp = {{ +\t\t\tFrameFormat = {{ +\t\t\t\tWidth = {w}, +\t\t\t\tHeight = {h}, +\t\t\t\tRate = 24, +\t\t\t}}, +\t\t}}, +\t}}, +}} +""" + + +def build_probe_merge(): + """Tests Merge ApplyModes + Gain (0, 0.5, 0.92, 1.0) + Operator=Under + BurnIn + SubtractiveAdditive!""" + chart = generate_color_chart() + grid = generate_grid_chart() + # Each case gets its own Merge node chained with Blend=1 on its frame and 0 on all other frames! + cases = [ + # (frame, label, apply_mode, operator, gain, sub_add, burn_in, extra_inputs) + (0, "Normal_gain1.0", "Normal", "Over", 1.0, 1.0, 0.0, ""), + (1, "Normal_gain0.5", "Normal", "Over", 0.5, 1.0, 0.0, ""), + (2, "Normal_gain0.0_add", "Normal", "Over", 0.0, 1.0, 0.0, ""), + (3, "Normal_sub0.0_add", "Normal", "Over", 1.0, 0.0, 0.0, ""), + (4, "Normal_Under", "Normal", "Under", 1.0, 1.0, 0.0, ""), + (5, "Difference_gain1.0", "Difference", "Over", 1.0, 1.0, 0.0, ""), + (6, "Difference_gain0.92", "Difference", "Over", 0.92, 1.0, 0.0, ""), + (7, "Difference_gain0.5", "Difference", "Over", 0.5, 1.0, 0.0, ""), + (8, "Difference_gain0.0", "Difference", "Over", 0.0, 1.0, 0.0, ""), + (9, "DarkerColor_gain1.0", "DarkerColor", "Over", 1.0, 1.0, 0.0, ""), + (10, "DarkerColor_gain0.5", "DarkerColor", "Over", 0.5, 1.0, 0.0, ""), + (11, "Darken_gain1.0", "Darken", "Over", 1.0, 1.0, 0.0, ""), + (12, "Multiply_gain1.0", "Multiply", "Over", 1.0, 1.0, 0.0, ""), + (13, "Screen_gain1.0", "Screen", "Over", 1.0, 1.0, 0.0, ""), + (14, "Screen_gain0.5", "Screen", "Over", 0.5, 1.0, 0.0, ""), + (15, "LinearDodge_gain1.0", "LinearDodge", "Over", 1.0, 1.0, 0.0, ""), + (16, "LinearLight_gain1.0", "LinearLight", "Over", 1.0, 1.0, 0.0, ""), + (17, "HardLight_gain1.0", "Hard Light", "Over", 1.0, 1.0, 0.0, ""), + (18, "SoftLight_gain1.0", "Soft Light", "Over", 1.0, 1.0, 0.0, ""), + (19, "Normal_BurnIn0.5", "Normal", "Over", 1.0, 1.0, 0.5, ""), + ] + + nodes = [ + make_loader("BG_Loader", chart, post_mult=1), + make_loader("FG_Loader", grid, post_mult=1), + # Also make a semi-transparent FG (alpha=0.75) by merging FG over transparent or multiplying? + # Even better: FG_Loader has alpha=1, BG_Loader has alpha ramp at bottom — let us scale FG down to 0.85 so edges + alpha ramp both show! + ] + splines = [] + # Chain merges on a clean BG_Loader -> Switch via Blend=1 on active frame + # Note: if we chain Merge_k(Background=prev, Foreground=FG_Loader, Blend=1 only on frame k), then on frame k only Merge_k runs! + prev = "BG_Loader" + for f, label, mode, op, gain, sub_add, burn_in, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"M{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tMerge_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "FG_Loader", Source = "Output", }}, +\t\t\t\tSize = Input {{ Value = 0.85, }}, +\t\t\t\tApplyMode = Input {{ Value = FuID {{ "{mode}" }}, }}, +\t\t\t\tOperator = Input {{ Value = FuID {{ "{op}" }}, }}, +\t\t\t\tGain = Input {{ Value = {gain}, }}, +\t\t\t\tSubtractiveAdditive = Input {{ Value = {sub_add}, }}, +\t\t\t\tBurnIn = Input {{ Value = {burn_in}, }}, +\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, +{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Merge_{f}" + + nodes.append(make_saver(prev, "merge")) + comp_path = local_root() / "comps" / "probe_merge.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "merge", [(c[0], c[1]) for c in cases] + + +def build_probe_cam3d(): + """Tests Camera3D RotOrder (all 6 orders!) + AoV + Shape3D Cylinder/Plane projection.""" + grid = generate_grid_chart() + # 12 frames at 640x360 (16:9!): + # f0..f5: All 6 RotOrder values on Camera3D with (RX=15, RY=-25, RZ=12) looking at ImagePlane3D at Z=-3! + # f6: Exact 60_moon_guide_u f5500 camera angles (XZY, RX=11.152, RY=-16.972, RZ=0.0004) looking at vertical Shape3D Cylinder! + # f7: Same cylinder with RotOrder=YXZ + # f8: Same cylinder with RotOrder=XYZ + # f9: Exact 21_ground001 f2760 camera angles (XZY, RX=13.05, RY=34.09, RZ=0) looking at grid plane! + # f10: AoVType=1 (Horizontal) vs AoVType=0 (Vertical) check + # f11: Nested Transform3D with RotOrder=XZY (RX=20, RY=30, RZ=15) + orders = ["XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"] + cases = [ + (0, "cam_RotOrder_XYZ"), + (1, "cam_RotOrder_XZY"), + (2, "cam_RotOrder_YXZ"), + (3, "cam_RotOrder_YZX"), + (4, "cam_RotOrder_ZXY"), + (5, "cam_RotOrder_ZYX"), + (6, "moon5500_cyl_XZY"), + (7, "moon5500_cyl_YXZ"), + (8, "moon5500_cyl_XYZ"), + (9, "ground2760_plane_XZY"), + (10, "cam_AoV_horiz_45"), + (11, "xf3d_RotOrder_XZY"), + ] + nodes = [make_loader("GridLoader", grid, post_mult=1)] + splines = [] + # Build one Renderer3D per frame (so static RotOrder/Shape dropdowns are exact!) and switch via Merge Blend! + nodes.append("""\t\tBlackBG = Background { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 640, }, +\t\t\t\tHeight = Input { Value = 360, }, +\t\t\t\tTopLeftAlpha = Input { Value = 1, }, +\t\t\t}, +\t\t},""") + prev = "BlackBG" + for f, label in cases: + if f < 6: + ro = orders[f] + cam_rx, cam_ry, cam_rz = 15.0, -25.0, 12.0 + cam_tz = 3.0 + aov, aov_type = 35.0, 0 + shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -1.2, }}, +\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.7, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + scene_in = f"Plane_{f}" + elif f in (6, 7, 8): + ro = {6: "XZY", 7: "YXZ", 8: "XYZ"}[f] + cam_rx, cam_ry, cam_rz = 11.152, -16.972, 0.0004 + cam_tz = 0.0 + aov, aov_type = 27.99, 0 + shape_blk = f"""\t\tCyl_{f} = Shape3D {{ +\t\t\tInputs = {{ +\t\t\t\t["SurfaceCylinderInputs.Radius"] = Input {{ Value = 100.0, }}, +\t\t\t\t["SurfaceCylinderInputs.Height"] = Input {{ Value = 150.0, }}, +\t\t\t\t["SurfaceCylinderInputs.SubdivisionLevelBase"] = Input {{ Value = 32, }}, +\t\t\t\t["SurfaceCylinderInputs.SubdivisionLevelHeight"] = Input {{ Value = 16, }}, +\t\t\t\tShape = Input {{ Value = FuID {{ "SurfaceCylinderInputs" }}, }}, +\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 30.0, }}, +\t\t\t\t["MtlStdInputs.MaterialID"] = Input {{ Value = 1, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + scene_in = f"Cyl_{f}" + elif f == 9: + ro = "XZY" + cam_rx, cam_ry, cam_rz = 13.05, 34.09, 0.0 + cam_tz = 0.0 + aov, aov_type = 35.0, 0 + shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -2.2, }}, +\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.8, }}, +\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -3.0, }}, +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + scene_in = f"Plane_{f}" + elif f == 10: + ro = "XYZ" + cam_rx, cam_ry, cam_rz = 0.0, 0.0, 0.0 + cam_tz = 3.0 + aov, aov_type = 45.0, 1 + shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + scene_in = f"Plane_{f}" + else: + ro = "XYZ" + cam_rx, cam_ry, cam_rz = 0.0, 0.0, 0.0 + cam_tz = 4.0 + aov, aov_type = 35.0, 0 + shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tXf3D_{f} = Transform3D {{ +\t\t\tInputs = {{ +\t\t\t\tSceneInput = Input {{ SourceOp = "Plane_{f}", Source = "Output", }}, +\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "XZY" }}, }}, +\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 20.0, }}, +\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 35.0, }}, +\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 15.0, }}, +\t\t\t}}, +\t\t}},""" + scene_in = f"Xf3D_{f}" + + nodes.append(shape_blk) + nodes.append(f"""\t\tCam_{f} = Camera3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = {cam_tz}, }}, +\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }}, +\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = {cam_rx}, }}, +\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = {cam_ry}, }}, +\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = {cam_rz}, }}, +\t\t\t\tAoV = Input {{ Value = {aov}, }}, +\t\t\t\tAoVType = Input {{ Value = {aov_type}, }}, +\t\t\t}}, +\t\t}}, +\t\tM3D_{f} = Merge3D {{ +\t\t\tInputs = {{ +\t\t\t\tSceneInput1 = Input {{ SourceOp = "{scene_in}", Source = "Output", }}, +\t\t\t\tSceneInput2 = Input {{ SourceOp = "Cam_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tRen_{f} = Renderer3D {{ +\t\t\tInputs = {{ +\t\t\t\tWidth = Input {{ Value = 640, }}, +\t\t\t\tHeight = Input {{ Value = 360, }}, +\t\t\t\tSceneInput = Input {{ SourceOp = "M3D_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Sw3D_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw3D_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Ren_{f}", Source = "Output", }}, +\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw3D_{f}" + + nodes.append(make_saver(prev, "cam3d")) + comp_path = local_root() / "comps" / "probe_cam3d.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360)) + return comp_path, "cam3d", cases + + +def build_probe_mask(): + """Tests EllipseMask & RectangleMask aspect, SoftEdge, CornerRadius, Angle, PaintModes on 16:9 640x360.""" + cases = [ + (0, "ellipse_0.5x0.5_circle"), + (1, "ellipse_0.5x0.3_rot35"), + (2, "ellipse_soft0.1_fastgauss"), + (3, "ellipse_soft0.2_gauss"), + (4, "rect_0.5x0.5_16x9"), + (5, "rect_0.5x0.5_corner0.3"), + (6, "rect_0.6x0.4_rot30_soft0.05"), + (7, "chain_ellipse_sub_rect"), + (8, "chain_ellipse_mul_rect"), + (9, "chain_ellipse_inv_rect"), + ] + nodes = ["""\t\tWhiteBG = Background { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 640, }, +\t\t\t\tHeight = Input { Value = 360, }, +\t\t\t\tTopLeftRed = Input { Value = 1, }, +\t\t\t\tTopLeftGreen = Input { Value = 1, }, +\t\t\t\tTopLeftBlue = Input { Value = 1, }, +\t\t\t\tTopLeftAlpha = Input { Value = 1, }, +\t\t\t}, +\t\t}, +\t\tBlackBG = Background { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 640, }, +\t\t\t\tHeight = Input { Value = 360, }, +\t\t\t\tTopLeftAlpha = Input { Value = 1, }, +\t\t\t}, +\t\t},"""] + splines = [] + prev = "BlackBG" + for f, label in cases: + if f == 0: + mblk = f"""\t\tMask_{f} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.5, }}, }}, }},""" + elif f == 1: + mblk = f"""\t\tMask_{f} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.3, }}, Angle = Input {{ Value = 35.0, }}, }}, }},""" + elif f == 2: + mblk = f"""\t\tMask_{f} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.4, }}, Height = Input {{ Value = 0.4, }}, SoftEdge = Input {{ Value = 0.1, }}, Filter = Input {{ Value = FuID {{ "Fast Gaussian" }}, }}, }}, }},""" + elif f == 3: + mblk = f"""\t\tMask_{f} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.4, }}, Height = Input {{ Value = 0.4, }}, SoftEdge = Input {{ Value = 0.2, }}, Filter = Input {{ Value = FuID {{ "Gaussian" }}, }}, }}, }},""" + elif f == 4: + mblk = f"""\t\tMask_{f} = RectangleMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.5, }}, }}, }},""" + elif f == 5: + mblk = f"""\t\tMask_{f} = RectangleMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.5, }}, CornerRadius = Input {{ Value = 0.3, }}, }}, }},""" + elif f == 6: + mblk = f"""\t\tMask_{f} = RectangleMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.6, }}, Height = Input {{ Value = 0.4, }}, Angle = Input {{ Value = 30.0, }}, SoftEdge = Input {{ Value = 0.05, }}, }}, }},""" + else: + pm = {7: "Subtract", 8: "Multiply", 9: "Invert"}[f] + mblk = f"""\t\tBaseM_{f} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.5, }}, }}, }}, +\t\tMask_{f} = RectangleMask {{ Inputs = {{ EffectMask = Input {{ SourceOp = "BaseM_{f}", Source = "Mask", }}, PaintMode = Input {{ Value = FuID {{ "{pm}" }}, }}, MaskWidth = Input {{ Value = 640, }}, MaskHeight = Input {{ Value = 360, }}, Center = Input {{ Value = {{ 0.6, 0.55 }}, }}, Width = Input {{ Value = 0.35, }}, Height = Input {{ Value = 0.45, }}, }}, }},""" + nodes.append(mblk) + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"SwM_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSwM_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tEffectMask = Input {{ SourceOp = "Mask_{f}", Source = "Mask", }}, +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "WhiteBG", Source = "Output", }}, +\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, +\t\t\t}}, +\t\t}},""") + prev = f"SwM_{f}" + + nodes.append(make_saver(prev, "mask")) + comp_path = local_root() / "comps" / "probe_mask.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360)) + return comp_path, "mask", cases + + +def run_probe(comp_path: Path, prefix: str, cases: list, render_gt: bool = True): + end_f = max(f for f, _ in cases) + if render_gt: + if use_smb(): + target_comp = str(comp_path) + else: + remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}" + subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True) + target_comp = remote_comp + print(f"=== sg render {comp_path.name} (0..{end_f}) ===") + subprocess.run(["sg", "render", target_comp, "--start", "0", "--end", str(end_f)], check=True) + if not use_smb(): + # Download rendered GT frames in one tar stream! + gt_dir = local_root() / "gt" + files = " ".join(f"{prefix}_{f:04d}.png" for f, _ in cases) + subprocess.run( + f'ssh root@10.0.0.1 "tar -C {REMOTE_ROOT}/gt -cf - {files}" | tar -C "{gt_dir}" -xf -', + shell=True, check=True, + ) + + # Also write a local-paths copy of the comp for render-check if SMB isn't mounted + eval_comp = comp_path + if not use_smb(): + txt = comp_path.read_text().replace(CONTAINER_ROOT, str(local_root())) + eval_comp = comp_path.with_suffix(".local.comp") + eval_comp.write_text(txt) + + print(f"\n=== Comparing {comp_path.name} ===") + for f, label in cases: + gt_p = local_root() / "gt" / f"{prefix}_{f:04d}.png" + out_p = local_root() / "ours" / f"{prefix}_{f:04d}.png" + res = subprocess.run( + [str(RENDER_CHECK), str(eval_comp), str(f), "--out", str(out_p), "--ref", str(gt_p)], + capture_output=True, text=True, check=True, + ) + out_all = res.stdout + "\n" + res.stderr + diff_line = [ln for ln in out_all.splitlines() if ln.startswith("Diff vs")] + summary = diff_line[-1].split(": ", 1)[-1] if diff_line else out_all.strip() + print(f" f{f:02d} {label:<30s} | {summary}") + + +def build_probe_cam3d_fov(): + """Pinpoints exact Camera3D FilmGate/ResolutionGateFit/AoV/FLength + 60_moon_guide_u f5500 cylinder + all RotOrders IN-FRAME!""" + grid = generate_grid_chart() + cases = [ + (0, "cam_default_no_aov"), + (1, "exportCam_Inside_37.85"), + (2, "exportCam_Width_37.85"), + (3, "exportCam_Height_37.85"), + (4, "exportCam_Outside_37.85"), + (5, "exportCam_AoVType_Horiz"), + (6, "exportCam_FLength_24mm"), + (7, "moon5500_exact_XZY"), + (8, "moon5500_exact_XYZ"), + (9, "moon5500_exact_YXZ"), + (10, "inframe_cam_XZY_15_20_10"), + (11, "inframe_cam_YXZ_15_20_10"), + ] + nodes = [make_loader("GridLoader", grid, post_mult=1), """\t\tBlackBG = Background { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 640, }, +\t\t\t\tHeight = Input { Value = 360, }, +\t\t\t\tTopLeftAlpha = Input { Value = 1, }, +\t\t\t}, +\t\t},"""] + splines = [] + prev = "BlackBG" + for f, label in cases: + if f in (0, 1, 2, 3, 4, 5, 6): + extra_cam = { + 0: "", + 1: '\t\t\t\tAoV = Input { Value = 37.8493078162983, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },', + 2: '\t\t\t\tAoV = Input { Value = 37.8493078162983, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },\n\t\t\t\tResolutionGateFit = Input { Value = FuID { "Width" }, },', + 3: '\t\t\t\tAoV = Input { Value = 37.8493078162983, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },\n\t\t\t\tResolutionGateFit = Input { Value = FuID { "Height" }, },', + 4: '\t\t\t\tAoV = Input { Value = 37.8493078162983, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },\n\t\t\t\tResolutionGateFit = Input { Value = FuID { "Outside" }, },', + 5: '\t\t\t\tAoV = Input { Value = 37.8493078162983, },\n\t\t\t\tAoVType = Input { Value = FuID { "Horizontal" }, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },', + 6: '\t\t\t\tFLength = Input { Value = 24.0, },\n\t\t\t\tFilmBack = Input { Value = 1, },\n\t\t\t\tFilmGate = Input { Value = FuID { "User" }, },\n\t\t\t\tApertureW = Input { Value = 1.4173236, },\n\t\t\t\tApertureH = Input { Value = 0.9448824, },', + }[f] + nodes.append(f"""\t\tObj_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tCam_{f} = Camera3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = 4.0, }}, +{extra_cam} +\t\t\t}}, +\t\t}},""") + elif f in (7, 8, 9): + ro = {7: "XZY", 8: "XYZ", 9: "YXZ"}[f] + nodes.append(f"""\t\tObj_{f} = Shape3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 62.087, }}, +\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -44.83, }}, +\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 362.6, }}, +\t\t\t\tShape = Input {{ Value = FuID {{ "SurfaceCylinderInputs" }}, }}, +\t\t\t\t["SurfaceCylinderInputs.Radius"] = Input {{ Value = 200, }}, +\t\t\t\t["SurfaceCylinderInputs.Height"] = Input {{ Value = 200, }}, +\t\t\t\t["SurfaceCylinderInputs.StartSweep"] = Input {{ Value = 196, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tCam_{f} = Camera3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }}, +\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 11.152, }}, +\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = -16.972, }}, +\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 0.0004, }}, +\t\t\t\tAoV = Input {{ Value = 37.8493078162983, }}, +\t\t\t\tFilmBack = Input {{ Value = 1, }}, +\t\t\t\tFilmGate = Input {{ Value = FuID {{ "User" }}, }}, +\t\t\t\tApertureW = Input {{ Value = 1.4173236, }}, +\t\t\t\tApertureH = Input {{ Value = 0.9448824, }}, +\t\t\t}}, +\t\t}},""") + else: + ro = "XZY" if f == 10 else "YXZ" + nodes.append(f"""\t\tObj_{f} = ImagePlane3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -1.2, }}, +\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.9, }}, +\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -3.5, }}, +\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }}, +\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tCam_{f} = Camera3D {{ +\t\t\tInputs = {{ +\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }}, +\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 15.0, }}, +\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 20.0, }}, +\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 10.0, }}, +\t\t\t\tAoV = Input {{ Value = 37.8493078162983, }}, +\t\t\t\tFilmBack = Input {{ Value = 1, }}, +\t\t\t\tFilmGate = Input {{ Value = FuID {{ "User" }}, }}, +\t\t\t\tApertureW = Input {{ Value = 1.4173236, }}, +\t\t\t\tApertureH = Input {{ Value = 0.9448824, }}, +\t\t\t}}, +\t\t}},""") + nodes.append(f"""\t\tM3D_{f} = Merge3D {{ +\t\t\tInputs = {{ +\t\t\t\tSceneInput1 = Input {{ SourceOp = "Obj_{f}", Source = "Output", }}, +\t\t\t\tSceneInput2 = Input {{ SourceOp = "Cam_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}}, +\t\tRen_{f} = Renderer3D {{ +\t\t\tInputs = {{ +\t\t\t\tWidth = Input {{ Value = 640, }}, +\t\t\t\tHeight = Input {{ Value = 360, }}, +\t\t\t\tSceneInput = Input {{ SourceOp = "M3D_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"SwF_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSwF_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Ren_{f}", Source = "Output", }}, +\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, +\t\t\t}}, +\t\t}},""") + prev = f"SwF_{f}" + nodes.append(make_saver(prev, "cam3d_fov")) + comp_path = local_root() / "comps" / "probe_cam3d_fov.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360)) + return comp_path, "cam3d_fov", cases + + +def build_probe_transform(): + """Tests Transform FilterMethod (Nearest/Box/Linear/Catmull), Edges (Canvas/Wrap/Dup/Mirror), Pivot+Angle+Aspect+Flip.""" + grid = generate_grid_chart() + cases = [ + (0, "xf_nearest_zoom4x", 'Size = Input { Value = 4.0, }, FilterMethod = Input { Value = 0, },'), + (1, "xf_linear_zoom4x", 'Size = Input { Value = 4.0, }, FilterMethod = Input { Value = 2, },'), + (2, "xf_edges_canvas", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 0, },'), + (3, "xf_edges_wrap", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 1, },'), + (4, "xf_edges_duplicate", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 2, },'), + (5, "xf_edges_mirror", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 3, },'), + (6, "xf_pivot_angle37", 'Pivot = Input { Value = { 0.25, 0.75 }, }, Angle = Input { Value = 37.0, }, Size = Input { Value = 0.85, },'), + (7, "xf_nonuniform_xy", 'UseSizeAndAspect = Input { Value = 0, }, XSize = Input { Value = 1.35, }, YSize = Input { Value = 0.65, }, Angle = Input { Value = 20.0, },'), + (8, "xf_aspect_1.6", 'Size = Input { Value = 0.8, }, Aspect = Input { Value = 1.6, }, Angle = Input { Value = -25.0, },'), + (9, "xf_flip_hv", 'FlipHoriz = Input { Value = 1, }, FlipVert = Input { Value = 1, }, Size = Input { Value = 0.8, },'), + (10, "xf_center_offset_rot", 'Center = Input { Value = { 0.35, 0.65 }, }, Pivot = Input { Value = { 0.7, 0.3 }, }, Angle = Input { Value = -42.0, }, Size = Input { Value = 0.75, },'), + (11, "xf_nearest_rot15_zoom3", 'Size = Input { Value = 3.0, }, Angle = Input { Value = 15.0, }, FilterMethod = Input { Value = 0, },'), + ] + nodes = [make_loader("GridLoader", grid, post_mult=1)] + splines = [] + prev = "GridLoader" + for f, label, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Xf_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tXf_{f} = Transform {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Xf_{f}" + nodes.append(make_saver(prev, "xf")) + comp_path = local_root() / "comps" / "probe_xf.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "xf", [(c[0], c[1]) for c in cases] + + +def build_probe_blur(): + """Tests Blur (FastGauss/Gauss/Box + ClippingMode), DirectionalBlur (Linear/Centered/Radial/Zoom+Glow), ErodeDilate (+/-/Box/Circle).""" + grid = generate_grid_chart() + cases = [ + (0, "blur_fgauss_5", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 5.0, },'), + (1, "blur_fgauss_20", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 20.0, },'), + (2, "blur_gauss_10", "Blur", 'Filter = Input { Value = FuID { "Gaussian" }, }, XBlurSize = Input { Value = 10.0, },'), + (3, "blur_box_10", "Blur", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 10.0, },'), + (4, "blur_clip_none_15", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 15.0, }, ClippingMode = Input { Value = FuID { "None" }, },'), + (5, "dirblur_linear_0.08", "DirectionalBlur", 'Type = Input { Value = 0, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 30.0, },'), + (6, "dirblur_radial_0.08", "DirectionalBlur", 'Type = Input { Value = 1, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 30.0, },'), + (7, "dirblur_centered_0.08", "DirectionalBlur", 'Type = Input { Value = 2, }, Length = Input { Value = 0.08, }, Center = Input { Value = { 0.4, 0.6 }, },'), + (8, "dirblur_zoom_0.1_glow", "DirectionalBlur", 'Type = Input { Value = 3, }, Length = Input { Value = 0.10, }, Glow = Input { Value = 0.15, }, Center = Input { Value = { 0.6, 0.4 }, },'), + (9, "erode_box_+0.02", "ErodeDilate", 'XAmount = Input { Value = 0.02, },'), + (10, "erode_box_-0.02", "ErodeDilate", 'XAmount = Input { Value = -0.02, },'), + (11, "erode_circle_+0.02", "ErodeDilate", 'Filter = Input { Value = 3, }, XAmount = Input { Value = 0.02, },'), + ] + nodes = [make_loader("GridLoader", grid, post_mult=1)] + splines = [] + prev = "GridLoader" + for f, label, kind, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Bl_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tOp_{f} = {kind} {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Op_{f}" + nodes.append(make_saver(prev, "blur")) + comp_path = local_root() / "comps" / "probe_blur.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "blur", [(c[0], c[1]) for c in cases] + + +def build_probe_color_ops(): + """Tests BrightnessContrast, ColorGain, and ChannelBoolean edge cases.""" + chart = generate_color_chart() + grid = generate_grid_chart() + cases = [ + (0, "bc_gain1.4_lift0.1", "BrightnessContrast", 'Gain = Input { Value = 1.4, }, Lift = Input { Value = 0.1, },'), + (1, "bc_gamma0.6_con0.4", "BrightnessContrast", 'Gamma = Input { Value = 0.6, }, Contrast = Input { Value = 0.4, }, Brightness = Input { Value = 0.05, },'), + (2, "bc_low0.2_high0.8", "BrightnessContrast", 'Low = Input { Value = 0.2, }, High = Input { Value = 0.8, },'), + (3, "bc_sat0.3_prediv1", "BrightnessContrast", 'Saturation = Input { Value = 0.3, }, Brightness = Input { Value = 0.15, }, PreDividePostMultiply = Input { Value = 1, },'), + (4, "cg_midhigh_hue0.58", "ColorGain", 'MidHue = Input { Value = 0.583, }, HighHue = Input { Value = 0.583, },'), + (5, "cg_dark0.2_mid0.6_hi0.9", "ColorGain", 'DarkHue = Input { Value = 0.2, }, MidHue = Input { Value = 0.6, }, HighHue = Input { Value = 0.9, },'), + (6, "cg_gain_lift_gamma_rgb", "ColorGain", 'GainRed = Input { Value = 1.3, }, LiftGreen = Input { Value = 0.15, }, GammaBlue = Input { Value = 0.7, },'), + (7, "cg_sat_bands", "ColorGain", 'SaturationLow = Input { Value = 0.3, }, SaturationMid = Input { Value = 1.6, }, SaturationHigh = Input { Value = 0.5, },'), + (8, "cb_copy_swizzle_gbr", "ChannelBoolean", 'Operation = Input { Value = 0, }, ToRed = Input { Value = 1, }, ToGreen = Input { Value = 2, }, ToBlue = Input { Value = 0, },'), + (9, "cb_add_fg", "ChannelBoolean", 'Operation = Input { Value = 1, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'), + (10, "cb_mul_fg", "ChannelBoolean", 'Operation = Input { Value = 6, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'), + (11, "cb_diff_fg", "ChannelBoolean", 'Operation = Input { Value = 8, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'), + ] + nodes = [ + make_loader("ChartLoader", chart, post_mult=1), + make_loader("GridLoader", grid, post_mult=1), + ] + splines = [] + prev = "ChartLoader" + for f, label, kind, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Co_{f}_Blend" + splines.append(step_spline(sname, bl)) + in_port = "Background" if kind == "ChannelBoolean" else "Input" + nodes.append(f"""\t\tCo_{f} = {kind} {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\t{in_port} = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Co_{f}" + nodes.append(make_saver(prev, "color_ops")) + comp_path = local_root() / "comps" / "probe_color_ops.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "color_ops", [(c[0], c[1]) for c in cases] + + +def build_probe_displace(): + """Tests Displace XY (sign, offsets, channels) + Radial/Bump (strength, spread, light).""" + grid = generate_grid_chart() + chart = generate_color_chart() + cases = [ + (0, "disp_xy_default_off", 'Type = Input { Value = 1, }, XRefraction = Input { Value = 0.08, }, YRefraction = Input { Value = 0.04, },'), + (1, "disp_xy_off-0.5_ch_rg", 'Type = Input { Value = 1, }, XChannel = Input { Value = 0, }, YChannel = Input { Value = 1, }, XOffset = Input { Value = -0.5, }, YOffset = Input { Value = -0.5, }, XRefraction = Input { Value = 0.08, }, YRefraction = Input { Value = 0.08, },'), + (2, "disp_xy_ch_g_only", 'Type = Input { Value = 1, }, XChannel = Input { Value = 1, }, XOffset = Input { Value = -0.5, }, XRefraction = Input { Value = 0.12, },'), + (3, "disp_xy_neg_refract", 'Type = Input { Value = 1, }, XChannel = Input { Value = 0, }, XOffset = Input { Value = -0.5, }, XRefraction = Input { Value = -0.10, },'), + (4, "disp_radial_0.15", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, },'), + (5, "disp_radial_spread0.4", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, }, Spread = Input { Value = 0.4, },'), + (6, "disp_radial_light0.5", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, }, LightPower = Input { Value = 0.5, },'), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + make_loader("ChartLoader", chart, post_mult=1), + ] + splines = [] + prev = "GridLoader" + for f, label, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Dp_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tDp_{f} = Displace {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "ChartLoader", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Dp_{f}" + nodes.append(make_saver(prev, "displace")) + comp_path = local_root() / "comps" / "probe_displace.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "displace", [(c[0], c[1]) for c in cases] + + +def build_probe_glow(): + """Tests SoftGlow and Glow edge cases (Gain, XGlowSize=0, Threshold, GlowOnly, GlowSize).""" + grid = generate_grid_chart() + cases = [ + (0, "sg_default", "SoftGlow", ''), + (1, "sg_size0_gain1.38", "SoftGlow", 'XGlowSize = Input { Value = 0.0, }, Gain = Input { Value = 1.378, },'), + (2, "sg_size21_gain1.06", "SoftGlow", 'XGlowSize = Input { Value = 21.3, }, Gain = Input { Value = 1.063, },'), + (3, "sg_size6_gain2.0", "SoftGlow", 'XGlowSize = Input { Value = 6.3, }, Gain = Input { Value = 2.0, },'), + (4, "sg_thresh0.6_size12", "SoftGlow", 'Threshold = Input { Value = 0.6, }, XGlowSize = Input { Value = 12.0, }, Gain = Input { Value = 1.5, },'), + (5, "sg_glow_only", "SoftGlow", 'GlowOnly = Input { Value = 1, }, XGlowSize = Input { Value = 10.0, }, Gain = Input { Value = 1.2, },'), + (6, "glow_default", "Glow", ''), + (7, "glow_0.58_size12", "Glow", 'Glow = Input { Value = 0.583, }, GlowSize = Input { Value = 12.0, },'), + ] + nodes = [make_loader("GridLoader", grid, post_mult=1)] + splines = [] + prev = "GridLoader" + for f, label, kind, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Gl_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tGl_{f} = {kind} {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""") + prev = f"Gl_{f}" + nodes.append(make_saver(prev, "glow")) + comp_path = local_root() / "comps" / "probe_glow.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "glow", [(c[0], c[1]) for c in cases] + + +def build_probe_text(): + """Tests TextPlus size, alignment, tracking, and outline shading (Liberation Sans).""" + cases = [ + (0, "txt_center_0.12", 'StyledText = Input { Value = "Hello 123", }, Size = Input { Value = 0.12, },'), + (1, "txt_left_top", 'StyledText = Input { Value = "TopLeft", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.2, 0.7 }, }, HorizontalLeftCenterRight = Input { Value = -1, }, VerticalTopCenterBottom = Input { Value = -1, },'), + (2, "txt_right_bottom", 'StyledText = Input { Value = "BotRight", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.8, 0.3 }, }, HorizontalLeftCenterRight = Input { Value = 1, }, VerticalTopCenterBottom = Input { Value = 1, },'), + (3, "txt_tracking_1.3", 'StyledText = Input { Value = "WIDE", }, Size = Input { Value = 0.12, }, CharacterSpacing = Input { Value = 1.3, },'), + (4, "txt_outline_round", 'StyledText = Input { Value = "the", }, Size = Input { Value = 0.18, }, Enabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 2, }, Thickness2 = Input { Value = 0.04, }, Red2 = Input { Value = 0.9, }, Green2 = Input { Value = 0.2, }, Blue2 = Input { Value = 0.2, },'), + ] + nodes = ["""\t\tBlackBG = Background { +\t\t\tInputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, +\t\t},"""] + splines = [] + prev = "BlackBG" + for f, label, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Tx_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tTxt_{f} = TextPlus {{ +\t\t\tInputs = {{ +\t\t\t\tWidth = Input {{ Value = 512, }}, +\t\t\t\tHeight = Input {{ Value = 512, }}, +\t\t\t\tFont = Input {{ Value = "Liberation Sans", }}, +\t\t\t\tStyle = Input {{ Value = "Regular", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}}, +\t\tM_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Txt_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"M_{f}" + nodes.append(make_saver(prev, "text")) + comp_path = local_root() / "comps" / "probe_text.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "text", [(c[0], c[1]) for c in cases] + + +def build_probe_noise_text(): + """Dissects Fusion 21.1 FastNoise exact lattice/seed/fBm AND TextPlus red-outline + ColorGain outer edge.""" + cases = [ + (0, "fn_d1_s4_z0", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Seethe = Input { Value = 0, }, Color1Alpha = Input { Value = 1, },'), + (1, "fn_d1_s8_z0", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 8, }, Seethe = Input { Value = 0, }, Color1Alpha = Input { Value = 1, },'), + (2, "fn_d1_s4_z0.5", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Seethe = Input { Value = 0.5, }, Color1Alpha = Input { Value = 1, },'), + (3, "fn_d1_s4_z1.0", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Seethe = Input { Value = 1.0, }, Color1Alpha = Input { Value = 1, },'), + (4, "fn_d4_s4_z0", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 4, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Seethe = Input { Value = 0, }, Color1Alpha = Input { Value = 1, },'), + (5, "fn_d1_s4_discont", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Discontinuous = Input { Value = 1, }, Color1Alpha = Input { Value = 1, },'), + (6, "fn_d1_s4_ctr2575", "FastNoise", 'Width = Input { Value = 512, }, Height = Input { Value = 512, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, Center = Input { Value = { 0.25, 0.75 }, }, Color1Alpha = Input { Value = 1, },'), + (7, "fn_d1_16x9_s4", "FastNoise", 'Width = Input { Value = 640, }, Height = Input { Value = 360, }, Detail = Input { Value = 1, }, Contrast = Input { Value = 1, }, Brightness = Input { Value = 0, }, XScale = Input { Value = 4, }, YScale = Input { Value = 10, }, Color1Alpha = Input { Value = 1, },'), + (8, "txt_red_outline", "TextCG", 'cg=0'), + (9, "txt_red_cg_blue", "TextCG", 'cg=1'), + (10, "txt_red_cg_prediv","TextCG", 'cg=2'), + ] + nodes = ["""\t\tDarkBG = Background { +\t\t\tInputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.10, }, TopLeftBlue = Input { Value = 0.22, }, TopLeftAlpha = Input { Value = 1, }, }, +\t\t}, +\t\tTxtW = TextPlus { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tFont = Input { Value = "Liberation Sans", }, Style = Input { Value = "Bold", }, +\t\t\t\tStyledText = Input { Value = "W", }, Size = Input { Value = 0.55, }, +\t\t\t\tRed1 = Input { Value = 0, }, Green1 = Input { Value = 0, }, Blue1 = Input { Value = 0, }, +\t\t\t\tEnabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 1, }, +\t\t\t\tThickness2 = Input { Value = 0.05, }, Round2 = Input { Value = 1, }, +\t\t\t\tRed2 = Input { Value = 1, }, Green2 = Input { Value = 0, }, Blue2 = Input { Value = 0, }, +\t\t\t}, +\t\t}, +\t\tCG_Blue = ColorGain { +\t\t\tInputs = { MidHue = Input { Value = 0.62, }, HighHue = Input { Value = 0.62, }, Input = Input { SourceOp = "TxtW", Source = "Output", }, }, +\t\t}, +\t\tCG_Blue_PD = ColorGain { +\t\t\tInputs = { MidHue = Input { Value = 0.62, }, HighHue = Input { Value = 0.62, }, PreDividePostMultiply = Input { Value = 1, }, Input = Input { SourceOp = "TxtW", Source = "Output", }, }, +\t\t},"""] + splines = [] + prev = "DarkBG" + for f, label, kind, extra in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Nt_{f}_Blend" + splines.append(step_spline(sname, bl)) + if kind == "FastNoise": + nodes.append(f"""\t\tFn_{f} = FastNoise {{ +\t\t\tInputs = {{ {extra} }}, +\t\t}}, +\t\tM_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Fn_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + else: + src_op = {"cg=0": "TxtW", "cg=1": "CG_Blue", "cg=2": "CG_Blue_PD"}[extra] + nodes.append(f"""\t\tM_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "{src_op}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"M_{f}" + nodes.append(make_saver(prev, "noise_text")) + comp_path = local_root() / "comps" / "probe_noise_text.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "noise_text", [(c[0], c[1]) for c in cases] + + +def main(): + ensure_dirs() + which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"] + skip_gt = "--no-gt" in sys.argv + builders = { + "merge": build_probe_merge, + "cam3d": build_probe_cam3d, + "cam3d_fov": build_probe_cam3d_fov, + "mask": build_probe_mask, + "xf": build_probe_transform, + "blur": build_probe_blur, + "color_ops": build_probe_color_ops, + "displace": build_probe_displace, + "glow": build_probe_glow, + "text": build_probe_text, + "noise_text": build_probe_noise_text, + } + for w in which: + comp_path, prefix, cases = builders[w]() + run_probe(comp_path, prefix, cases, render_gt=not skip_gt) + + +if __name__ == "__main__": + main() -- 2.54.1