authoravatarclover caruso<git@paperclover.net>2026-11-29 23:43:54-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 00:08:42-08:00
log3e8af8b7da0e1971a20866eb7457b1c5b8bc110d
tree93803f515ed87524955ec03ca4ef28d23f90bf39
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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)

27 files changed, 19626 insertions(+), 0 deletions(-)

.gitignore created+5
...@@ -0,0 +1,5 @@
1/target
2/private
3.DS_Store
4*.png
5!docs/**/*.png
Cargo.lock created+4689
...@@ -0,0 +1,4689 @@
1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "ab_glyph"
7version = "0.2.32"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"
10dependencies = [
11 "ab_glyph_rasterizer",
12 "owned_ttf_parser",
13]
14
15[[package]]
16name = "ab_glyph_rasterizer"
17version = "0.1.10"
18source = "registry+https://github.com/rust-lang/crates.io-index"
19checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
20
21[[package]]
22name = "accesskit"
23version = "0.25.1"
24source = "registry+https://github.com/rust-lang/crates.io-index"
25checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932"
26dependencies = [
27 "enumn",
28 "serde",
29 "uuid",
30]
31
32[[package]]
33name = "accesskit_consumer"
34version = "0.39.1"
35dependencies = [
36 "accesskit",
37 "hashbrown 0.17.2",
38]
39
40[[package]]
41name = "accesskit_ios"
42version = "0.2.1"
43source = "registry+https://github.com/rust-lang/crates.io-index"
44checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937"
45dependencies = [
46 "accesskit",
47 "accesskit_consumer",
48 "hashbrown 0.17.2",
49 "objc2 0.5.3",
50 "objc2-foundation 0.2.2",
51 "objc2-ui-kit",
52]
53
54[[package]]
55name = "accesskit_macos"
56version = "0.27.1"
57source = "registry+https://github.com/rust-lang/crates.io-index"
58checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4"
59dependencies = [
60 "accesskit",
61 "accesskit_consumer",
62 "hashbrown 0.17.2",
63 "objc2 0.5.3",
64 "objc2-app-kit 0.2.2",
65 "objc2-foundation 0.2.2",
66]
67
68[[package]]
69name = "accesskit_windows"
70version = "0.35.1"
71source = "registry+https://github.com/rust-lang/crates.io-index"
72checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb"
73dependencies = [
74 "accesskit",
75 "accesskit_consumer",
76 "hashbrown 0.17.2",
77 "static_assertions",
78 "windows",
79 "windows-core",
80]
81
82[[package]]
83name = "accesskit_winit"
84version = "0.34.1"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77"
87dependencies = [
88 "accesskit",
89 "accesskit_ios",
90 "accesskit_macos",
91 "accesskit_windows",
92 "raw-window-handle",
93 "winit",
94]
95
96[[package]]
97name = "adler2"
98version = "2.0.1"
99source = "registry+https://github.com/rust-lang/crates.io-index"
100checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
101
102[[package]]
103name = "ahash"
104version = "0.8.15"
105source = "registry+https://github.com/rust-lang/crates.io-index"
106checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"
107dependencies = [
108 "cfg-if",
109 "getrandom",
110 "once_cell",
111 "serde",
112 "version_check",
113 "zerocopy",
114]
115
116[[package]]
117name = "aho-corasick"
118version = "1.1.5"
119source = "registry+https://github.com/rust-lang/crates.io-index"
120checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
121dependencies = [
122 "memchr",
123]
124
125[[package]]
126name = "alloc-no-stdlib"
127version = "3.0.0"
128source = "registry+https://github.com/rust-lang/crates.io-index"
129checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
130
131[[package]]
132name = "allocator-api2"
133version = "0.2.22"
134source = "registry+https://github.com/rust-lang/crates.io-index"
135checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014"
136
137[[package]]
138name = "android-activity"
139version = "0.6.1"
140source = "registry+https://github.com/rust-lang/crates.io-index"
141checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"
142dependencies = [
143 "android-properties",
144 "bitflags 2.13.2",
145 "cc",
146 "jni",
147 "libc",
148 "log",
149 "ndk",
150 "ndk-context",
151 "ndk-sys",
152 "num_enum",
153 "thiserror 2.0.21",
154]
155
156[[package]]
157name = "android-properties"
158version = "0.2.2"
159source = "registry+https://github.com/rust-lang/crates.io-index"
160checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
161
162[[package]]
163name = "android_system_properties"
164version = "0.1.6"
165source = "registry+https://github.com/rust-lang/crates.io-index"
166checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
167dependencies = [
168 "libc",
169]
170
171[[package]]
172name = "arboard"
173version = "3.7.0"
174source = "registry+https://github.com/rust-lang/crates.io-index"
175checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917"
176dependencies = [
177 "clipboard-win",
178 "log",
179 "objc2 0.6.5",
180 "objc2-app-kit 0.3.2",
181 "objc2-foundation 0.3.2",
182 "parking_lot",
183 "percent-encoding",
184 "windows-sys 0.61.2",
185 "wl-clipboard-rs",
186 "x11rb",
187]
188
189[[package]]
190name = "arrayref"
191version = "0.3.9"
192source = "registry+https://github.com/rust-lang/crates.io-index"
193checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
194
195[[package]]
196name = "arrayvec"
197version = "0.7.9"
198source = "registry+https://github.com/rust-lang/crates.io-index"
199checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d"
200
201[[package]]
202name = "as-raw-xcb-connection"
203version = "1.0.1"
204source = "registry+https://github.com/rust-lang/crates.io-index"
205checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
206
207[[package]]
208name = "ash"
209version = "0.38.0+1.3.281"
210source = "registry+https://github.com/rust-lang/crates.io-index"
211checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
212dependencies = [
213 "libloading",
214]
215
216[[package]]
217name = "async-broadcast"
218version = "0.7.2"
219source = "registry+https://github.com/rust-lang/crates.io-index"
220checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
221dependencies = [
222 "event-listener",
223 "event-listener-strategy",
224 "futures-core",
225 "pin-project-lite",
226]
227
228[[package]]
229name = "async-channel"
230version = "2.5.0"
231source = "registry+https://github.com/rust-lang/crates.io-index"
232checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
233dependencies = [
234 "concurrent-queue",
235 "event-listener-strategy",
236 "futures-core",
237 "pin-project-lite",
238]
239
240[[package]]
241name = "async-executor"
242version = "1.14.1"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
245dependencies = [
246 "async-task",
247 "concurrent-queue",
248 "fastrand",
249 "futures-lite",
250 "pin-project-lite",
251 "slab",
252]
253
254[[package]]
255name = "async-io"
256version = "2.6.0"
257source = "registry+https://github.com/rust-lang/crates.io-index"
258checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
259dependencies = [
260 "autocfg",
261 "cfg-if",
262 "concurrent-queue",
263 "futures-io",
264 "futures-lite",
265 "parking",
266 "polling",
267 "rustix 1.1.6",
268 "slab",
269 "windows-sys 0.61.2",
270]
271
272[[package]]
273name = "async-lock"
274version = "3.5.0"
275source = "registry+https://github.com/rust-lang/crates.io-index"
276checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"
277dependencies = [
278 "event-listener",
279 "event-listener-strategy",
280 "pin-project-lite",
281]
282
283[[package]]
284name = "async-process"
285version = "2.5.0"
286source = "registry+https://github.com/rust-lang/crates.io-index"
287checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
288dependencies = [
289 "async-channel",
290 "async-io",
291 "async-lock",
292 "async-signal",
293 "async-task",
294 "blocking",
295 "cfg-if",
296 "event-listener",
297 "futures-lite",
298 "rustix 1.1.6",
299]
300
301[[package]]
302name = "async-recursion"
303version = "1.2.0"
304source = "registry+https://github.com/rust-lang/crates.io-index"
305checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
306dependencies = [
307 "proc-macro2",
308 "quote",
309 "syn 3.0.10",
310]
311
312[[package]]
313name = "async-signal"
314version = "0.2.14"
315source = "registry+https://github.com/rust-lang/crates.io-index"
316checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
317dependencies = [
318 "async-io",
319 "async-lock",
320 "atomic-waker",
321 "cfg-if",
322 "futures-core",
323 "futures-io",
324 "rustix 1.1.6",
325 "signal-hook-registry",
326 "slab",
327 "windows-sys 0.61.2",
328]
329
330[[package]]
331name = "async-task"
332version = "4.7.1"
333source = "registry+https://github.com/rust-lang/crates.io-index"
334checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
335
336[[package]]
337name = "async-trait"
338version = "0.1.92"
339source = "registry+https://github.com/rust-lang/crates.io-index"
340checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
341dependencies = [
342 "proc-macro2",
343 "quote",
344 "syn 3.0.10",
345]
346
347[[package]]
348name = "atomic-waker"
349version = "1.1.2"
350source = "registry+https://github.com/rust-lang/crates.io-index"
351checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
352
353[[package]]
354name = "autocfg"
355version = "1.5.1"
356source = "registry+https://github.com/rust-lang/crates.io-index"
357checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
358
359[[package]]
360name = "base64"
361version = "0.23.1"
362source = "registry+https://github.com/rust-lang/crates.io-index"
363checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
364
365[[package]]
366name = "bit-set"
367version = "0.10.0"
368source = "registry+https://github.com/rust-lang/crates.io-index"
369checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
370dependencies = [
371 "bit-vec",
372]
373
374[[package]]
375name = "bit-vec"
376version = "0.9.1"
377source = "registry+https://github.com/rust-lang/crates.io-index"
378checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
379
380[[package]]
381name = "bit_field"
382version = "0.10.4"
383source = "registry+https://github.com/rust-lang/crates.io-index"
384checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
385
386[[package]]
387name = "bitflags"
388version = "1.3.2"
389source = "registry+https://github.com/rust-lang/crates.io-index"
390checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
391
392[[package]]
393name = "bitflags"
394version = "2.13.2"
395source = "registry+https://github.com/rust-lang/crates.io-index"
396checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
397
398[[package]]
399name = "block-buffer"
400version = "0.12.1"
401source = "registry+https://github.com/rust-lang/crates.io-index"
402checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
403dependencies = [
404 "hybrid-array",
405]
406
407[[package]]
408name = "block2"
409version = "0.5.1"
410source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
412dependencies = [
413 "objc2 0.5.3",
414]
415
416[[package]]
417name = "block2"
418version = "0.6.2"
419source = "registry+https://github.com/rust-lang/crates.io-index"
420checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
421dependencies = [
422 "objc2 0.6.5",
423]
424
425[[package]]
426name = "blocking"
427version = "1.7.0"
428source = "registry+https://github.com/rust-lang/crates.io-index"
429checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
430dependencies = [
431 "async-channel",
432 "async-task",
433 "futures-io",
434 "futures-lite",
435 "piper",
436]
437
438[[package]]
439name = "brotli-decompressor"
440version = "6.4.0"
441source = "registry+https://github.com/rust-lang/crates.io-index"
442checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb"
443dependencies = [
444 "alloc-no-stdlib",
445]
446
447[[package]]
448name = "bstr"
449version = "1.14.0"
450source = "registry+https://github.com/rust-lang/crates.io-index"
451checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
452dependencies = [
453 "memchr",
454 "serde_core",
455]
456
457[[package]]
458name = "bumpalo"
459version = "3.20.4"
460source = "registry+https://github.com/rust-lang/crates.io-index"
461checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
462
463[[package]]
464name = "bytemuck"
465version = "1.25.2"
466source = "registry+https://github.com/rust-lang/crates.io-index"
467checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
468dependencies = [
469 "bytemuck_derive",
470]
471
472[[package]]
473name = "bytemuck_derive"
474version = "1.12.1"
475source = "registry+https://github.com/rust-lang/crates.io-index"
476checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
477dependencies = [
478 "proc-macro2",
479 "quote",
480 "syn 3.0.10",
481]
482
483[[package]]
484name = "byteorder-lite"
485version = "0.1.0"
486source = "registry+https://github.com/rust-lang/crates.io-index"
487checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
488
489[[package]]
490name = "bytes"
491version = "1.12.2"
492source = "registry+https://github.com/rust-lang/crates.io-index"
493checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
494
495[[package]]
496name = "calloop"
497version = "0.13.0"
498source = "registry+https://github.com/rust-lang/crates.io-index"
499checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
500dependencies = [
501 "bitflags 2.13.2",
502 "log",
503 "polling",
504 "rustix 0.38.44",
505 "slab",
506 "thiserror 1.0.69",
507]
508
509[[package]]
510name = "calloop-wayland-source"
511version = "0.3.0"
512source = "registry+https://github.com/rust-lang/crates.io-index"
513checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
514dependencies = [
515 "calloop",
516 "rustix 0.38.44",
517 "wayland-backend",
518 "wayland-client",
519]
520
521[[package]]
522name = "cc"
523version = "1.12.0"
524source = "registry+https://github.com/rust-lang/crates.io-index"
525checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"
526dependencies = [
527 "find-msvc-tools",
528 "jobserver",
529 "libc",
530 "shlex",
531]
532
533[[package]]
534name = "cfg-if"
535version = "1.0.5"
536source = "registry+https://github.com/rust-lang/crates.io-index"
537checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
538
539[[package]]
540name = "cfg_aliases"
541version = "0.2.2"
542source = "registry+https://github.com/rust-lang/crates.io-index"
543checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
544
545[[package]]
546name = "clipboard-win"
547version = "5.4.3"
548source = "registry+https://github.com/rust-lang/crates.io-index"
549checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
550dependencies = [
551 "error-code",
552]
553
554[[package]]
555name = "codespan-reporting"
556version = "0.13.1"
557source = "registry+https://github.com/rust-lang/crates.io-index"
558checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
559dependencies = [
560 "serde",
561 "termcolor",
562 "unicode-width",
563]
564
565[[package]]
566name = "color_quant"
567version = "1.1.0"
568source = "registry+https://github.com/rust-lang/crates.io-index"
569checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
570
571[[package]]
572name = "combine"
573version = "4.6.9"
574source = "registry+https://github.com/rust-lang/crates.io-index"
575checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
576dependencies = [
577 "bytes",
578 "memchr",
579]
580
581[[package]]
582name = "concurrent-queue"
583version = "2.5.0"
584source = "registry+https://github.com/rust-lang/crates.io-index"
585checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
586dependencies = [
587 "crossbeam-utils",
588]
589
590[[package]]
591name = "const-oid"
592version = "0.10.3"
593source = "registry+https://github.com/rust-lang/crates.io-index"
594checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
595
596[[package]]
597name = "core-foundation"
598version = "0.9.4"
599source = "registry+https://github.com/rust-lang/crates.io-index"
600checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
601dependencies = [
602 "core-foundation-sys",
603 "libc",
604]
605
606[[package]]
607name = "core-foundation-sys"
608version = "0.8.7"
609source = "registry+https://github.com/rust-lang/crates.io-index"
610checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
611
612[[package]]
613name = "core-graphics"
614version = "0.23.2"
615source = "registry+https://github.com/rust-lang/crates.io-index"
616checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
617dependencies = [
618 "bitflags 1.3.2",
619 "core-foundation",
620 "core-graphics-types",
621 "foreign-types",
622 "libc",
623]
624
625[[package]]
626name = "core-graphics-types"
627version = "0.1.3"
628source = "registry+https://github.com/rust-lang/crates.io-index"
629checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
630dependencies = [
631 "bitflags 1.3.2",
632 "core-foundation",
633 "libc",
634]
635
636[[package]]
637name = "cpufeatures"
638version = "0.3.1"
639source = "registry+https://github.com/rust-lang/crates.io-index"
640checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
641dependencies = [
642 "libc",
643]
644
645[[package]]
646name = "crc32fast"
647version = "1.5.6"
648source = "registry+https://github.com/rust-lang/crates.io-index"
649checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
650dependencies = [
651 "cfg-if",
652]
653
654[[package]]
655name = "crossbeam-deque"
656version = "0.8.8"
657source = "registry+https://github.com/rust-lang/crates.io-index"
658checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
659dependencies = [
660 "crossbeam-epoch",
661 "crossbeam-utils",
662]
663
664[[package]]
665name = "crossbeam-epoch"
666version = "0.9.21"
667source = "registry+https://github.com/rust-lang/crates.io-index"
668checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
669dependencies = [
670 "crossbeam-utils",
671]
672
673[[package]]
674name = "crossbeam-utils"
675version = "0.8.23"
676source = "registry+https://github.com/rust-lang/crates.io-index"
677checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
678
679[[package]]
680name = "crunchy"
681version = "0.2.4"
682source = "registry+https://github.com/rust-lang/crates.io-index"
683checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
684
685[[package]]
686name = "crypto-common"
687version = "0.2.2"
688source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
690dependencies = [
691 "hybrid-array",
692]
693
694[[package]]
695name = "cursor-icon"
696version = "1.2.0"
697source = "registry+https://github.com/rust-lang/crates.io-index"
698checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
699dependencies = [
700 "serde",
701]
702
703[[package]]
704name = "data-url"
705version = "0.3.2"
706source = "registry+https://github.com/rust-lang/crates.io-index"
707checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
708
709[[package]]
710name = "deranged"
711version = "0.5.9"
712source = "registry+https://github.com/rust-lang/crates.io-index"
713checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
714
715[[package]]
716name = "diff"
717version = "0.1.0"
718dependencies = [
719 "highlight",
720 "tree-sitter",
721]
722
723[[package]]
724name = "digest"
725version = "0.11.3"
726source = "registry+https://github.com/rust-lang/crates.io-index"
727checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
728dependencies = [
729 "block-buffer",
730 "const-oid",
731 "crypto-common",
732]
733
734[[package]]
735name = "dispatch"
736version = "0.2.0"
737source = "registry+https://github.com/rust-lang/crates.io-index"
738checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
739
740[[package]]
741name = "dispatch2"
742version = "0.3.1"
743source = "registry+https://github.com/rust-lang/crates.io-index"
744checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
745dependencies = [
746 "bitflags 2.13.2",
747 "objc2 0.6.5",
748]
749
750[[package]]
751name = "dlib"
752version = "0.5.3"
753source = "registry+https://github.com/rust-lang/crates.io-index"
754checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
755dependencies = [
756 "libloading",
757]
758
759[[package]]
760name = "dock"
761version = "0.1.0"
762dependencies = [
763 "accesskit",
764 "draw",
765 "edit",
766 "state",
767 "theme",
768 "ui",
769 "winit",
770]
771
772[[package]]
773name = "document-features"
774version = "0.2.12"
775source = "registry+https://github.com/rust-lang/crates.io-index"
776checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
777dependencies = [
778 "litrs",
779]
780
781[[package]]
782name = "downcast-rs"
783version = "1.2.1"
784source = "registry+https://github.com/rust-lang/crates.io-index"
785checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
786
787[[package]]
788name = "dpi"
789version = "0.1.2"
790source = "registry+https://github.com/rust-lang/crates.io-index"
791checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
792dependencies = [
793 "serde",
794]
795
796[[package]]
797name = "draw"
798version = "0.1.0"
799dependencies = [
800 "bytemuck",
801 "image",
802 "resvg",
803 "roxmltree 0.21.2",
804 "serde_json",
805 "state",
806 "text",
807 "wgpu",
808 "zeno",
809]
810
811[[package]]
812name = "edit"
813version = "0.1.0"
814dependencies = [
815 "accesskit",
816 "block2 0.6.2",
817 "objc2 0.6.5",
818 "objc2-app-kit 0.3.2",
819 "objc2-foundation 0.3.2",
820 "text",
821 "unicode-segmentation",
822 "windows-sys 0.61.2",
823]
824
825[[package]]
826name = "either"
827version = "1.19.0"
828source = "registry+https://github.com/rust-lang/crates.io-index"
829checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
830
831[[package]]
832name = "endi"
833version = "1.1.1"
834source = "registry+https://github.com/rust-lang/crates.io-index"
835checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
836
837[[package]]
838name = "engine"
839version = "0.1.0"
840dependencies = [
841 "bytemuck",
842 "exr",
843 "image",
844 "model",
845 "png",
846 "pollster",
847 "text",
848 "theme",
849 "wgpu",
850 "zeno",
851]
852
853[[package]]
854name = "enumflags2"
855version = "0.7.12"
856source = "registry+https://github.com/rust-lang/crates.io-index"
857checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
858dependencies = [
859 "enumflags2_derive",
860 "serde",
861]
862
863[[package]]
864name = "enumflags2_derive"
865version = "0.7.12"
866source = "registry+https://github.com/rust-lang/crates.io-index"
867checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
868dependencies = [
869 "proc-macro2",
870 "quote",
871 "syn 2.0.119",
872]
873
874[[package]]
875name = "enumn"
876version = "0.1.14"
877source = "registry+https://github.com/rust-lang/crates.io-index"
878checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
879dependencies = [
880 "proc-macro2",
881 "quote",
882 "syn 2.0.119",
883]
884
885[[package]]
886name = "env_home"
887version = "0.1.0"
888source = "registry+https://github.com/rust-lang/crates.io-index"
889checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
890
891[[package]]
892name = "equivalent"
893version = "1.0.3"
894source = "registry+https://github.com/rust-lang/crates.io-index"
895checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
896
897[[package]]
898name = "errno"
899version = "0.3.15"
900source = "registry+https://github.com/rust-lang/crates.io-index"
901checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
902dependencies = [
903 "libc",
904 "windows-sys 0.61.2",
905]
906
907[[package]]
908name = "error-code"
909version = "3.4.0"
910source = "registry+https://github.com/rust-lang/crates.io-index"
911checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
912
913[[package]]
914name = "euclid"
915version = "0.22.14"
916source = "registry+https://github.com/rust-lang/crates.io-index"
917checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
918dependencies = [
919 "num-traits",
920]
921
922[[package]]
923name = "event-listener"
924version = "5.4.2"
925source = "registry+https://github.com/rust-lang/crates.io-index"
926checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
927dependencies = [
928 "parking",
929 "pin-project-lite",
930]
931
932[[package]]
933name = "event-listener-strategy"
934version = "0.5.4"
935source = "registry+https://github.com/rust-lang/crates.io-index"
936checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
937dependencies = [
938 "event-listener",
939 "pin-project-lite",
940]
941
942[[package]]
943name = "exr"
944version = "1.74.3"
945source = "registry+https://github.com/rust-lang/crates.io-index"
946checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
947dependencies = [
948 "bit_field",
949 "half",
950 "lebe",
951 "miniz_oxide 0.8.9",
952 "multiversion",
953 "rayon-core",
954 "smallvec",
955 "zune-inflate",
956]
957
958[[package]]
959name = "fastrand"
960version = "2.5.0"
961source = "registry+https://github.com/rust-lang/crates.io-index"
962checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
963
964[[package]]
965name = "fax"
966version = "0.2.7"
967source = "registry+https://github.com/rust-lang/crates.io-index"
968checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
969
970[[package]]
971name = "fdeflate"
972version = "0.3.7"
973source = "registry+https://github.com/rust-lang/crates.io-index"
974checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
975dependencies = [
976 "simd-adler32",
977]
978
979[[package]]
980name = "find-msvc-tools"
981version = "0.1.16"
982source = "registry+https://github.com/rust-lang/crates.io-index"
983checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
984
985[[package]]
986name = "fixedbitset"
987version = "0.5.9"
988source = "registry+https://github.com/rust-lang/crates.io-index"
989checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
990
991[[package]]
992name = "flate2"
993version = "1.1.11"
994source = "registry+https://github.com/rust-lang/crates.io-index"
995checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
996dependencies = [
997 "crc32fast",
998 "miniz_oxide 0.9.1",
999 "zlib-rs",
1000]
1001
1002[[package]]
1003name = "float-cmp"
1004version = "0.9.0"
1005source = "registry+https://github.com/rust-lang/crates.io-index"
1006checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
1007
1008[[package]]
1009name = "flow"
1010version = "0.1.0"
1011dependencies = [
1012 "draw",
1013 "model",
1014 "text",
1015 "theme",
1016 "ui",
1017 "winit",
1018]
1019
1020[[package]]
1021name = "foldhash"
1022version = "0.1.5"
1023source = "registry+https://github.com/rust-lang/crates.io-index"
1024checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
1025
1026[[package]]
1027name = "foldhash"
1028version = "0.2.0"
1029source = "registry+https://github.com/rust-lang/crates.io-index"
1030checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
1031
1032[[package]]
1033name = "font-types"
1034version = "0.12.7"
1035source = "registry+https://github.com/rust-lang/crates.io-index"
1036checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
1037dependencies = [
1038 "bytemuck",
1039]
1040
1041[[package]]
1042name = "fontconfig-parser"
1043version = "0.5.8"
1044source = "registry+https://github.com/rust-lang/crates.io-index"
1045checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
1046dependencies = [
1047 "roxmltree 0.20.0",
1048]
1049
1050[[package]]
1051name = "fontdb"
1052version = "0.24.0"
1053source = "registry+https://github.com/rust-lang/crates.io-index"
1054checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"
1055dependencies = [
1056 "fontconfig-parser",
1057 "log",
1058 "memmap2",
1059 "slotmap",
1060 "tinyvec",
1061]
1062
1063[[package]]
1064name = "foreign-types"
1065version = "0.5.0"
1066source = "registry+https://github.com/rust-lang/crates.io-index"
1067checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
1068dependencies = [
1069 "foreign-types-macros",
1070 "foreign-types-shared",
1071]
1072
1073[[package]]
1074name = "foreign-types-macros"
1075version = "0.2.4"
1076source = "registry+https://github.com/rust-lang/crates.io-index"
1077checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
1078dependencies = [
1079 "proc-macro2",
1080 "quote",
1081 "syn 3.0.10",
1082]
1083
1084[[package]]
1085name = "foreign-types-shared"
1086version = "0.3.1"
1087source = "registry+https://github.com/rust-lang/crates.io-index"
1088checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
1089
1090[[package]]
1091name = "futures-core"
1092version = "0.3.34"
1093source = "registry+https://github.com/rust-lang/crates.io-index"
1094checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
1095
1096[[package]]
1097name = "futures-io"
1098version = "0.3.34"
1099source = "registry+https://github.com/rust-lang/crates.io-index"
1100checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
1101
1102[[package]]
1103name = "futures-lite"
1104version = "2.6.1"
1105source = "registry+https://github.com/rust-lang/crates.io-index"
1106checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
1107dependencies = [
1108 "fastrand",
1109 "futures-core",
1110 "futures-io",
1111 "parking",
1112 "pin-project-lite",
1113]
1114
1115[[package]]
1116name = "futures-task"
1117version = "0.3.34"
1118source = "registry+https://github.com/rust-lang/crates.io-index"
1119checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
1120
1121[[package]]
1122name = "futures-util"
1123version = "0.3.34"
1124source = "registry+https://github.com/rust-lang/crates.io-index"
1125checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
1126dependencies = [
1127 "futures-core",
1128 "futures-task",
1129 "pin-project-lite",
1130 "slab",
1131]
1132
1133[[package]]
1134name = "gethostname"
1135version = "1.1.0"
1136source = "registry+https://github.com/rust-lang/crates.io-index"
1137checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
1138dependencies = [
1139 "rustix 1.1.6",
1140 "windows-link",
1141]
1142
1143[[package]]
1144name = "getrandom"
1145version = "0.4.3"
1146source = "registry+https://github.com/rust-lang/crates.io-index"
1147checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
1148dependencies = [
1149 "cfg-if",
1150 "js-sys",
1151 "libc",
1152 "r-efi",
1153 "wasm-bindgen",
1154]
1155
1156[[package]]
1157name = "gif"
1158version = "0.14.2"
1159source = "registry+https://github.com/rust-lang/crates.io-index"
1160checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
1161dependencies = [
1162 "color_quant",
1163 "weezl",
1164]
1165
1166[[package]]
1167name = "gl_generator"
1168version = "0.14.0"
1169source = "registry+https://github.com/rust-lang/crates.io-index"
1170checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
1171dependencies = [
1172 "khronos_api",
1173 "log",
1174 "xml-rs",
1175]
1176
1177[[package]]
1178name = "glow"
1179version = "0.17.0"
1180source = "registry+https://github.com/rust-lang/crates.io-index"
1181checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"
1182dependencies = [
1183 "js-sys",
1184 "slotmap",
1185 "wasm-bindgen",
1186 "web-sys",
1187]
1188
1189[[package]]
1190name = "glutin_wgl_sys"
1191version = "0.6.1"
1192source = "registry+https://github.com/rust-lang/crates.io-index"
1193checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
1194dependencies = [
1195 "gl_generator",
1196]
1197
1198[[package]]
1199name = "gpu-allocator"
1200version = "0.28.0"
1201source = "registry+https://github.com/rust-lang/crates.io-index"
1202checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
1203dependencies = [
1204 "ash",
1205 "hashbrown 0.16.1",
1206 "log",
1207 "presser",
1208 "thiserror 2.0.21",
1209 "windows",
1210]
1211
1212[[package]]
1213name = "half"
1214version = "2.7.1"
1215source = "registry+https://github.com/rust-lang/crates.io-index"
1216checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
1217dependencies = [
1218 "cfg-if",
1219 "crunchy",
1220 "num-traits",
1221 "zerocopy",
1222]
1223
1224[[package]]
1225name = "harfrust"
1226version = "0.12.0"
1227source = "registry+https://github.com/rust-lang/crates.io-index"
1228checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
1229dependencies = [
1230 "bitflags 2.13.2",
1231 "bytemuck",
1232 "read-fonts 0.41.0",
1233 "smallvec",
1234]
1235
1236[[package]]
1237name = "harfrust"
1238version = "0.15.0"
1239source = "registry+https://github.com/rust-lang/crates.io-index"
1240checksum = "865dcc4105d51c323d8fedbb2d75b5e9c8ecddf5613f74c82f851d0afbc97114"
1241dependencies = [
1242 "bitflags 2.13.2",
1243 "bytemuck",
1244 "read-fonts 0.46.0",
1245 "smallvec",
1246 "yoke",
1247]
1248
1249[[package]]
1250name = "hashbrown"
1251version = "0.15.5"
1252source = "registry+https://github.com/rust-lang/crates.io-index"
1253checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
1254dependencies = [
1255 "foldhash 0.1.5",
1256]
1257
1258[[package]]
1259name = "hashbrown"
1260version = "0.16.1"
1261source = "registry+https://github.com/rust-lang/crates.io-index"
1262checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1263dependencies = [
1264 "allocator-api2",
1265 "equivalent",
1266 "foldhash 0.2.0",
1267]
1268
1269[[package]]
1270name = "hashbrown"
1271version = "0.17.2"
1272source = "registry+https://github.com/rust-lang/crates.io-index"
1273checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
1274dependencies = [
1275 "foldhash 0.2.0",
1276]
1277
1278[[package]]
1279name = "hermit-abi"
1280version = "0.5.3"
1281source = "registry+https://github.com/rust-lang/crates.io-index"
1282checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
1283
1284[[package]]
1285name = "hex"
1286version = "0.4.3"
1287source = "registry+https://github.com/rust-lang/crates.io-index"
1288checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1289
1290[[package]]
1291name = "highlight"
1292version = "0.1.0"
1293dependencies = [
1294 "streaming-iterator",
1295 "tree-sitter",
1296 "tree-sitter-bash",
1297 "tree-sitter-c",
1298 "tree-sitter-cpp",
1299 "tree-sitter-css",
1300 "tree-sitter-diff",
1301 "tree-sitter-go",
1302 "tree-sitter-html",
1303 "tree-sitter-java",
1304 "tree-sitter-javascript",
1305 "tree-sitter-json",
1306 "tree-sitter-lua",
1307 "tree-sitter-md",
1308 "tree-sitter-python",
1309 "tree-sitter-ruby",
1310 "tree-sitter-rust",
1311 "tree-sitter-sequel",
1312 "tree-sitter-swift",
1313 "tree-sitter-toml-ng",
1314 "tree-sitter-typescript",
1315 "tree-sitter-yaml",
1316 "tree-sitter-zig",
1317]
1318
1319[[package]]
1320name = "hybrid-array"
1321version = "0.4.15"
1322source = "registry+https://github.com/rust-lang/crates.io-index"
1323checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
1324dependencies = [
1325 "typenum",
1326]
1327
1328[[package]]
1329name = "image"
1330version = "0.25.10"
1331source = "registry+https://github.com/rust-lang/crates.io-index"
1332checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
1333dependencies = [
1334 "bytemuck",
1335 "byteorder-lite",
1336 "color_quant",
1337 "exr",
1338 "gif",
1339 "image-webp",
1340 "moxcms",
1341 "num-traits",
1342 "png",
1343 "tiff",
1344 "zune-core",
1345 "zune-jpeg",
1346]
1347
1348[[package]]
1349name = "image-webp"
1350version = "0.2.4"
1351source = "registry+https://github.com/rust-lang/crates.io-index"
1352checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
1353dependencies = [
1354 "byteorder-lite",
1355 "quick-error",
1356]
1357
1358[[package]]
1359name = "imagesize"
1360version = "0.15.0"
1361source = "registry+https://github.com/rust-lang/crates.io-index"
1362checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"
1363
1364[[package]]
1365name = "indexmap"
1366version = "2.14.2"
1367source = "registry+https://github.com/rust-lang/crates.io-index"
1368checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
1369dependencies = [
1370 "equivalent",
1371 "hashbrown 0.17.2",
1372]
1373
1374[[package]]
1375name = "itoa"
1376version = "1.0.19"
1377source = "registry+https://github.com/rust-lang/crates.io-index"
1378checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
1379
1380[[package]]
1381name = "jni"
1382version = "0.22.4"
1383source = "registry+https://github.com/rust-lang/crates.io-index"
1384checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
1385dependencies = [
1386 "cfg-if",
1387 "combine",
1388 "jni-macros",
1389 "jni-sys 0.4.1",
1390 "log",
1391 "simd_cesu8",
1392 "thiserror 2.0.21",
1393 "walkdir",
1394 "windows-link",
1395]
1396
1397[[package]]
1398name = "jni-macros"
1399version = "0.22.4"
1400source = "registry+https://github.com/rust-lang/crates.io-index"
1401checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
1402dependencies = [
1403 "proc-macro2",
1404 "quote",
1405 "rustc_version",
1406 "simd_cesu8",
1407 "syn 2.0.119",
1408]
1409
1410[[package]]
1411name = "jni-sys"
1412version = "0.3.1"
1413source = "registry+https://github.com/rust-lang/crates.io-index"
1414checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
1415dependencies = [
1416 "jni-sys 0.4.1",
1417]
1418
1419[[package]]
1420name = "jni-sys"
1421version = "0.4.1"
1422source = "registry+https://github.com/rust-lang/crates.io-index"
1423checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
1424dependencies = [
1425 "jni-sys-macros",
1426]
1427
1428[[package]]
1429name = "jni-sys-macros"
1430version = "0.4.1"
1431source = "registry+https://github.com/rust-lang/crates.io-index"
1432checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
1433dependencies = [
1434 "quote",
1435 "syn 2.0.119",
1436]
1437
1438[[package]]
1439name = "jobserver"
1440version = "0.1.35"
1441source = "registry+https://github.com/rust-lang/crates.io-index"
1442checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1443dependencies = [
1444 "getrandom",
1445 "libc",
1446]
1447
1448[[package]]
1449name = "js-sys"
1450version = "0.3.107"
1451source = "registry+https://github.com/rust-lang/crates.io-index"
1452checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
1453dependencies = [
1454 "cfg-if",
1455 "futures-util",
1456 "wasm-bindgen",
1457]
1458
1459[[package]]
1460name = "khronos-egl"
1461version = "6.0.0"
1462source = "registry+https://github.com/rust-lang/crates.io-index"
1463checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"
1464dependencies = [
1465 "libc",
1466 "libloading",
1467 "pkg-config",
1468]
1469
1470[[package]]
1471name = "khronos_api"
1472version = "3.1.0"
1473source = "registry+https://github.com/rust-lang/crates.io-index"
1474checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
1475
1476[[package]]
1477name = "knife-window-host"
1478version = "0.1.0"
1479dependencies = [
1480 "accesskit",
1481 "accesskit_winit",
1482 "block2 0.6.2",
1483 "libc",
1484 "objc2 0.6.5",
1485 "objc2-app-kit 0.3.2",
1486 "objc2-core-foundation",
1487 "objc2-core-graphics",
1488 "objc2-foundation 0.3.2",
1489 "objc2-quartz-core 0.3.2",
1490 "serde",
1491 "serde_json",
1492 "winit",
1493]
1494
1495[[package]]
1496name = "kurbo"
1497version = "0.13.1"
1498source = "registry+https://github.com/rust-lang/crates.io-index"
1499checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
1500dependencies = [
1501 "arrayvec",
1502 "euclid",
1503 "polycool",
1504 "smallvec",
1505]
1506
1507[[package]]
1508name = "lebe"
1509version = "0.5.3"
1510source = "registry+https://github.com/rust-lang/crates.io-index"
1511checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
1512
1513[[package]]
1514name = "libc"
1515version = "0.2.191"
1516source = "registry+https://github.com/rust-lang/crates.io-index"
1517checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
1518
1519[[package]]
1520name = "libloading"
1521version = "0.8.9"
1522source = "registry+https://github.com/rust-lang/crates.io-index"
1523checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1524dependencies = [
1525 "cfg-if",
1526 "windows-link",
1527]
1528
1529[[package]]
1530name = "libm"
1531version = "0.2.16"
1532source = "registry+https://github.com/rust-lang/crates.io-index"
1533checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
1534
1535[[package]]
1536name = "libredox"
1537version = "0.1.25"
1538source = "registry+https://github.com/rust-lang/crates.io-index"
1539checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
1540dependencies = [
1541 "bitflags 2.13.2",
1542 "libc",
1543 "plain",
1544 "redox_syscall 0.9.5",
1545]
1546
1547[[package]]
1548name = "linux-raw-sys"
1549version = "0.4.15"
1550source = "registry+https://github.com/rust-lang/crates.io-index"
1551checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
1552
1553[[package]]
1554name = "linux-raw-sys"
1555version = "0.12.1"
1556source = "registry+https://github.com/rust-lang/crates.io-index"
1557checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1558
1559[[package]]
1560name = "litrs"
1561version = "1.1.0"
1562source = "registry+https://github.com/rust-lang/crates.io-index"
1563checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"
1564
1565[[package]]
1566name = "lock_api"
1567version = "0.4.14"
1568source = "registry+https://github.com/rust-lang/crates.io-index"
1569checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
1570dependencies = [
1571 "scopeguard",
1572]
1573
1574[[package]]
1575name = "log"
1576version = "0.4.35"
1577source = "registry+https://github.com/rust-lang/crates.io-index"
1578checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
1579
1580[[package]]
1581name = "lua-src"
1582version = "547.0.0"
1583source = "registry+https://github.com/rust-lang/crates.io-index"
1584checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
1585dependencies = [
1586 "cc",
1587]
1588
1589[[package]]
1590name = "luajit-src"
1591version = "210.5.12+a4f56a4"
1592source = "registry+https://github.com/rust-lang/crates.io-index"
1593checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
1594dependencies = [
1595 "cc",
1596 "which",
1597]
1598
1599[[package]]
1600name = "memchr"
1601version = "2.8.3"
1602source = "registry+https://github.com/rust-lang/crates.io-index"
1603checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
1604
1605[[package]]
1606name = "memmap2"
1607version = "0.9.12"
1608source = "registry+https://github.com/rust-lang/crates.io-index"
1609checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
1610dependencies = [
1611 "libc",
1612]
1613
1614[[package]]
1615name = "memoffset"
1616version = "0.9.1"
1617source = "registry+https://github.com/rust-lang/crates.io-index"
1618checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
1619dependencies = [
1620 "autocfg",
1621]
1622
1623[[package]]
1624name = "miniz_oxide"
1625version = "0.8.9"
1626source = "registry+https://github.com/rust-lang/crates.io-index"
1627checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
1628dependencies = [
1629 "adler2",
1630 "simd-adler32",
1631]
1632
1633[[package]]
1634name = "miniz_oxide"
1635version = "0.9.1"
1636source = "registry+https://github.com/rust-lang/crates.io-index"
1637checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
1638dependencies = [
1639 "adler2",
1640 "simd-adler32",
1641]
1642
1643[[package]]
1644name = "mlua"
1645version = "0.10.5"
1646source = "registry+https://github.com/rust-lang/crates.io-index"
1647checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
1648dependencies = [
1649 "bstr",
1650 "either",
1651 "mlua-sys",
1652 "num-traits",
1653 "parking_lot",
1654 "rustc-hash 2.1.3",
1655 "rustversion",
1656]
1657
1658[[package]]
1659name = "mlua-sys"
1660version = "0.6.8"
1661source = "registry+https://github.com/rust-lang/crates.io-index"
1662checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
1663dependencies = [
1664 "cc",
1665 "cfg-if",
1666 "lua-src",
1667 "luajit-src",
1668 "pkg-config",
1669]
1670
1671[[package]]
1672name = "model"
1673version = "0.1.0"
1674dependencies = [
1675 "mlua",
1676]
1677
1678[[package]]
1679name = "moxcms"
1680version = "0.8.1"
1681source = "registry+https://github.com/rust-lang/crates.io-index"
1682checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
1683dependencies = [
1684 "num-traits",
1685 "pxfm",
1686]
1687
1688[[package]]
1689name = "multiversion"
1690version = "0.8.1"
1691source = "registry+https://github.com/rust-lang/crates.io-index"
1692checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
1693dependencies = [
1694 "multiversion-macros",
1695 "target-features",
1696]
1697
1698[[package]]
1699name = "multiversion-macros"
1700version = "0.8.1"
1701source = "registry+https://github.com/rust-lang/crates.io-index"
1702checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
1703dependencies = [
1704 "proc-macro2",
1705 "quote",
1706 "syn 2.0.119",
1707 "target-features",
1708]
1709
1710[[package]]
1711name = "naga"
1712version = "30.0.2"
1713source = "registry+https://github.com/rust-lang/crates.io-index"
1714checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163"
1715dependencies = [
1716 "arrayvec",
1717 "bit-set",
1718 "bitflags 2.13.2",
1719 "cfg-if",
1720 "cfg_aliases",
1721 "codespan-reporting",
1722 "half",
1723 "hashbrown 0.17.2",
1724 "indexmap",
1725 "libm",
1726 "log",
1727 "naga-types",
1728 "num-traits",
1729 "once_cell",
1730 "rustc-hash 1.1.0",
1731 "spirv",
1732 "thiserror 2.0.21",
1733 "unicode-ident",
1734]
1735
1736[[package]]
1737name = "naga-types"
1738version = "30.0.2"
1739source = "registry+https://github.com/rust-lang/crates.io-index"
1740checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d"
1741dependencies = [
1742 "hashbrown 0.17.2",
1743 "indexmap",
1744 "rustc-hash 1.1.0",
1745 "thiserror 2.0.21",
1746]
1747
1748[[package]]
1749name = "ndk"
1750version = "0.9.0"
1751source = "registry+https://github.com/rust-lang/crates.io-index"
1752checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
1753dependencies = [
1754 "bitflags 2.13.2",
1755 "jni-sys 0.3.1",
1756 "log",
1757 "ndk-sys",
1758 "num_enum",
1759 "raw-window-handle",
1760 "thiserror 1.0.69",
1761]
1762
1763[[package]]
1764name = "ndk-context"
1765version = "0.1.1"
1766source = "registry+https://github.com/rust-lang/crates.io-index"
1767checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
1768
1769[[package]]
1770name = "ndk-sys"
1771version = "0.6.0+11769913"
1772source = "registry+https://github.com/rust-lang/crates.io-index"
1773checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
1774dependencies = [
1775 "jni-sys 0.3.1",
1776]
1777
1778[[package]]
1779name = "nom"
1780version = "8.0.0"
1781source = "registry+https://github.com/rust-lang/crates.io-index"
1782checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
1783dependencies = [
1784 "memchr",
1785]
1786
1787[[package]]
1788name = "nucleo-matcher"
1789version = "0.3.1"
1790source = "registry+https://github.com/rust-lang/crates.io-index"
1791checksum = "bf33f538733d1a5a3494b836ba913207f14d9d4a1d3cd67030c5061bdd2cac85"
1792dependencies = [
1793 "memchr",
1794 "unicode-segmentation",
1795]
1796
1797[[package]]
1798name = "num-conv"
1799version = "0.2.2"
1800source = "registry+https://github.com/rust-lang/crates.io-index"
1801checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
1802
1803[[package]]
1804name = "num-traits"
1805version = "0.2.19"
1806source = "registry+https://github.com/rust-lang/crates.io-index"
1807checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
1808dependencies = [
1809 "autocfg",
1810 "libm",
1811]
1812
1813[[package]]
1814name = "num_enum"
1815version = "0.7.6"
1816source = "registry+https://github.com/rust-lang/crates.io-index"
1817checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
1818dependencies = [
1819 "num_enum_derive",
1820 "rustversion",
1821]
1822
1823[[package]]
1824name = "num_enum_derive"
1825version = "0.7.6"
1826source = "registry+https://github.com/rust-lang/crates.io-index"
1827checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
1828dependencies = [
1829 "proc-macro-crate",
1830 "proc-macro2",
1831 "quote",
1832 "syn 2.0.119",
1833]
1834
1835[[package]]
1836name = "objc-sys"
1837version = "0.3.5"
1838source = "registry+https://github.com/rust-lang/crates.io-index"
1839checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
1840
1841[[package]]
1842name = "objc2"
1843version = "0.5.3"
1844source = "registry+https://github.com/rust-lang/crates.io-index"
1845checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b"
1846dependencies = [
1847 "objc-sys",
1848 "objc2-encode",
1849]
1850
1851[[package]]
1852name = "objc2"
1853version = "0.6.5"
1854source = "registry+https://github.com/rust-lang/crates.io-index"
1855checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
1856dependencies = [
1857 "objc2-encode",
1858]
1859
1860[[package]]
1861name = "objc2-app-kit"
1862version = "0.2.2"
1863source = "registry+https://github.com/rust-lang/crates.io-index"
1864checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
1865dependencies = [
1866 "bitflags 2.13.2",
1867 "block2 0.5.1",
1868 "libc",
1869 "objc2 0.5.3",
1870 "objc2-core-data",
1871 "objc2-core-image",
1872 "objc2-foundation 0.2.2",
1873 "objc2-quartz-core 0.2.2",
1874]
1875
1876[[package]]
1877name = "objc2-app-kit"
1878version = "0.3.2"
1879source = "registry+https://github.com/rust-lang/crates.io-index"
1880checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
1881dependencies = [
1882 "bitflags 2.13.2",
1883 "block2 0.6.2",
1884 "objc2 0.6.5",
1885 "objc2-core-foundation",
1886 "objc2-core-graphics",
1887 "objc2-foundation 0.3.2",
1888 "objc2-quartz-core 0.3.2",
1889]
1890
1891[[package]]
1892name = "objc2-cloud-kit"
1893version = "0.2.2"
1894source = "registry+https://github.com/rust-lang/crates.io-index"
1895checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"
1896dependencies = [
1897 "bitflags 2.13.2",
1898 "block2 0.5.1",
1899 "objc2 0.5.3",
1900 "objc2-core-location",
1901 "objc2-foundation 0.2.2",
1902]
1903
1904[[package]]
1905name = "objc2-contacts"
1906version = "0.2.2"
1907source = "registry+https://github.com/rust-lang/crates.io-index"
1908checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"
1909dependencies = [
1910 "block2 0.5.1",
1911 "objc2 0.5.3",
1912 "objc2-foundation 0.2.2",
1913]
1914
1915[[package]]
1916name = "objc2-core-data"
1917version = "0.2.2"
1918source = "registry+https://github.com/rust-lang/crates.io-index"
1919checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
1920dependencies = [
1921 "bitflags 2.13.2",
1922 "block2 0.5.1",
1923 "objc2 0.5.3",
1924 "objc2-foundation 0.2.2",
1925]
1926
1927[[package]]
1928name = "objc2-core-foundation"
1929version = "0.3.2"
1930source = "registry+https://github.com/rust-lang/crates.io-index"
1931checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
1932dependencies = [
1933 "bitflags 2.13.2",
1934 "dispatch2",
1935 "objc2 0.6.5",
1936]
1937
1938[[package]]
1939name = "objc2-core-graphics"
1940version = "0.3.2"
1941source = "registry+https://github.com/rust-lang/crates.io-index"
1942checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
1943dependencies = [
1944 "bitflags 2.13.2",
1945 "dispatch2",
1946 "objc2 0.6.5",
1947 "objc2-core-foundation",
1948 "objc2-io-surface",
1949]
1950
1951[[package]]
1952name = "objc2-core-image"
1953version = "0.2.2"
1954source = "registry+https://github.com/rust-lang/crates.io-index"
1955checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"
1956dependencies = [
1957 "block2 0.5.1",
1958 "objc2 0.5.3",
1959 "objc2-foundation 0.2.2",
1960 "objc2-metal 0.2.2",
1961]
1962
1963[[package]]
1964name = "objc2-core-location"
1965version = "0.2.2"
1966source = "registry+https://github.com/rust-lang/crates.io-index"
1967checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"
1968dependencies = [
1969 "block2 0.5.1",
1970 "objc2 0.5.3",
1971 "objc2-contacts",
1972 "objc2-foundation 0.2.2",
1973]
1974
1975[[package]]
1976name = "objc2-core-text"
1977version = "0.3.2"
1978source = "registry+https://github.com/rust-lang/crates.io-index"
1979checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
1980dependencies = [
1981 "bitflags 2.13.2",
1982 "objc2-core-foundation",
1983 "objc2-core-graphics",
1984]
1985
1986[[package]]
1987name = "objc2-core-video"
1988version = "0.3.2"
1989source = "registry+https://github.com/rust-lang/crates.io-index"
1990checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
1991dependencies = [
1992 "bitflags 2.13.2",
1993 "block2 0.6.2",
1994 "objc2 0.6.5",
1995 "objc2-core-foundation",
1996 "objc2-core-graphics",
1997 "objc2-io-surface",
1998]
1999
2000[[package]]
2001name = "objc2-encode"
2002version = "4.1.0"
2003source = "registry+https://github.com/rust-lang/crates.io-index"
2004checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
2005
2006[[package]]
2007name = "objc2-foundation"
2008version = "0.2.2"
2009source = "registry+https://github.com/rust-lang/crates.io-index"
2010checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
2011dependencies = [
2012 "bitflags 2.13.2",
2013 "block2 0.5.1",
2014 "dispatch",
2015 "libc",
2016 "objc2 0.5.3",
2017]
2018
2019[[package]]
2020name = "objc2-foundation"
2021version = "0.3.2"
2022source = "registry+https://github.com/rust-lang/crates.io-index"
2023checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
2024dependencies = [
2025 "bitflags 2.13.2",
2026 "block2 0.6.2",
2027 "objc2 0.6.5",
2028 "objc2-core-foundation",
2029]
2030
2031[[package]]
2032name = "objc2-io-surface"
2033version = "0.3.2"
2034source = "registry+https://github.com/rust-lang/crates.io-index"
2035checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
2036dependencies = [
2037 "bitflags 2.13.2",
2038 "objc2 0.6.5",
2039 "objc2-core-foundation",
2040]
2041
2042[[package]]
2043name = "objc2-link-presentation"
2044version = "0.2.2"
2045source = "registry+https://github.com/rust-lang/crates.io-index"
2046checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
2047dependencies = [
2048 "block2 0.5.1",
2049 "objc2 0.5.3",
2050 "objc2-app-kit 0.2.2",
2051 "objc2-foundation 0.2.2",
2052]
2053
2054[[package]]
2055name = "objc2-metal"
2056version = "0.2.2"
2057source = "registry+https://github.com/rust-lang/crates.io-index"
2058checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
2059dependencies = [
2060 "bitflags 2.13.2",
2061 "block2 0.5.1",
2062 "objc2 0.5.3",
2063 "objc2-foundation 0.2.2",
2064]
2065
2066[[package]]
2067name = "objc2-metal"
2068version = "0.3.2"
2069source = "registry+https://github.com/rust-lang/crates.io-index"
2070checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
2071dependencies = [
2072 "bitflags 2.13.2",
2073 "block2 0.6.2",
2074 "objc2 0.6.5",
2075 "objc2-core-foundation",
2076 "objc2-foundation 0.3.2",
2077]
2078
2079[[package]]
2080name = "objc2-quartz-core"
2081version = "0.2.2"
2082source = "registry+https://github.com/rust-lang/crates.io-index"
2083checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
2084dependencies = [
2085 "bitflags 2.13.2",
2086 "block2 0.5.1",
2087 "objc2 0.5.3",
2088 "objc2-foundation 0.2.2",
2089 "objc2-metal 0.2.2",
2090]
2091
2092[[package]]
2093name = "objc2-quartz-core"
2094version = "0.3.2"
2095source = "registry+https://github.com/rust-lang/crates.io-index"
2096checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
2097dependencies = [
2098 "bitflags 2.13.2",
2099 "objc2 0.6.5",
2100 "objc2-core-foundation",
2101 "objc2-core-graphics",
2102 "objc2-foundation 0.3.2",
2103 "objc2-metal 0.3.2",
2104]
2105
2106[[package]]
2107name = "objc2-symbols"
2108version = "0.2.2"
2109source = "registry+https://github.com/rust-lang/crates.io-index"
2110checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"
2111dependencies = [
2112 "objc2 0.5.3",
2113 "objc2-foundation 0.2.2",
2114]
2115
2116[[package]]
2117name = "objc2-ui-kit"
2118version = "0.2.2"
2119source = "registry+https://github.com/rust-lang/crates.io-index"
2120checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"
2121dependencies = [
2122 "bitflags 2.13.2",
2123 "block2 0.5.1",
2124 "objc2 0.5.3",
2125 "objc2-cloud-kit",
2126 "objc2-core-data",
2127 "objc2-core-image",
2128 "objc2-core-location",
2129 "objc2-foundation 0.2.2",
2130 "objc2-link-presentation",
2131 "objc2-quartz-core 0.2.2",
2132 "objc2-symbols",
2133 "objc2-uniform-type-identifiers",
2134 "objc2-user-notifications",
2135]
2136
2137[[package]]
2138name = "objc2-uniform-type-identifiers"
2139version = "0.2.2"
2140source = "registry+https://github.com/rust-lang/crates.io-index"
2141checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"
2142dependencies = [
2143 "block2 0.5.1",
2144 "objc2 0.5.3",
2145 "objc2-foundation 0.2.2",
2146]
2147
2148[[package]]
2149name = "objc2-user-notifications"
2150version = "0.2.2"
2151source = "registry+https://github.com/rust-lang/crates.io-index"
2152checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"
2153dependencies = [
2154 "bitflags 2.13.2",
2155 "block2 0.5.1",
2156 "objc2 0.5.3",
2157 "objc2-core-location",
2158 "objc2-foundation 0.2.2",
2159]
2160
2161[[package]]
2162name = "once_cell"
2163version = "1.21.4"
2164source = "registry+https://github.com/rust-lang/crates.io-index"
2165checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
2166
2167[[package]]
2168name = "orbclient"
2169version = "0.3.55"
2170source = "registry+https://github.com/rust-lang/crates.io-index"
2171checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"
2172dependencies = [
2173 "libc",
2174 "libredox",
2175]
2176
2177[[package]]
2178name = "ordered-float"
2179version = "5.5.1"
2180source = "registry+https://github.com/rust-lang/crates.io-index"
2181checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
2182dependencies = [
2183 "num-traits",
2184]
2185
2186[[package]]
2187name = "ordered-stream"
2188version = "0.2.0"
2189source = "registry+https://github.com/rust-lang/crates.io-index"
2190checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
2191dependencies = [
2192 "futures-core",
2193 "pin-project-lite",
2194]
2195
2196[[package]]
2197name = "os_pipe"
2198version = "1.2.3"
2199source = "registry+https://github.com/rust-lang/crates.io-index"
2200checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
2201dependencies = [
2202 "libc",
2203 "windows-sys 0.61.2",
2204]
2205
2206[[package]]
2207name = "owned_ttf_parser"
2208version = "0.25.1"
2209source = "registry+https://github.com/rust-lang/crates.io-index"
2210checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"
2211dependencies = [
2212 "ttf-parser",
2213]
2214
2215[[package]]
2216name = "parking"
2217version = "2.2.1"
2218source = "registry+https://github.com/rust-lang/crates.io-index"
2219checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
2220
2221[[package]]
2222name = "parking_lot"
2223version = "0.12.5"
2224source = "registry+https://github.com/rust-lang/crates.io-index"
2225checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
2226dependencies = [
2227 "lock_api",
2228 "parking_lot_core",
2229]
2230
2231[[package]]
2232name = "parking_lot_core"
2233version = "0.9.12"
2234source = "registry+https://github.com/rust-lang/crates.io-index"
2235checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
2236dependencies = [
2237 "cfg-if",
2238 "libc",
2239 "redox_syscall 0.5.18",
2240 "smallvec",
2241 "windows-link",
2242]
2243
2244[[package]]
2245name = "percent-encoding"
2246version = "2.3.2"
2247source = "registry+https://github.com/rust-lang/crates.io-index"
2248checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
2249
2250[[package]]
2251name = "petgraph"
2252version = "0.8.3"
2253source = "registry+https://github.com/rust-lang/crates.io-index"
2254checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
2255dependencies = [
2256 "fixedbitset",
2257 "hashbrown 0.15.5",
2258 "indexmap",
2259]
2260
2261[[package]]
2262name = "pico-args"
2263version = "0.5.0"
2264source = "registry+https://github.com/rust-lang/crates.io-index"
2265checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
2266
2267[[package]]
2268name = "pin-project"
2269version = "1.2.0"
2270source = "registry+https://github.com/rust-lang/crates.io-index"
2271checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9"
2272dependencies = [
2273 "pin-project-internal",
2274]
2275
2276[[package]]
2277name = "pin-project-internal"
2278version = "1.2.0"
2279source = "registry+https://github.com/rust-lang/crates.io-index"
2280checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756"
2281dependencies = [
2282 "proc-macro2",
2283 "quote",
2284 "syn 3.0.10",
2285]
2286
2287[[package]]
2288name = "pin-project-lite"
2289version = "0.2.18"
2290source = "registry+https://github.com/rust-lang/crates.io-index"
2291checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
2292
2293[[package]]
2294name = "piper"
2295version = "0.2.5"
2296source = "registry+https://github.com/rust-lang/crates.io-index"
2297checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
2298dependencies = [
2299 "atomic-waker",
2300 "fastrand",
2301 "futures-io",
2302]
2303
2304[[package]]
2305name = "pkg-config"
2306version = "0.3.34"
2307source = "registry+https://github.com/rust-lang/crates.io-index"
2308checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
2309
2310[[package]]
2311name = "plain"
2312version = "0.2.3"
2313source = "registry+https://github.com/rust-lang/crates.io-index"
2314checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
2315
2316[[package]]
2317name = "png"
2318version = "0.18.1"
2319source = "registry+https://github.com/rust-lang/crates.io-index"
2320checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
2321dependencies = [
2322 "bitflags 2.13.2",
2323 "crc32fast",
2324 "fdeflate",
2325 "flate2",
2326 "miniz_oxide 0.8.9",
2327]
2328
2329[[package]]
2330name = "polling"
2331version = "3.11.0"
2332source = "registry+https://github.com/rust-lang/crates.io-index"
2333checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
2334dependencies = [
2335 "cfg-if",
2336 "concurrent-queue",
2337 "hermit-abi",
2338 "pin-project-lite",
2339 "rustix 1.1.6",
2340 "windows-sys 0.61.2",
2341]
2342
2343[[package]]
2344name = "pollster"
2345version = "0.4.0"
2346source = "registry+https://github.com/rust-lang/crates.io-index"
2347checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
2348
2349[[package]]
2350name = "polycool"
2351version = "0.4.0"
2352source = "registry+https://github.com/rust-lang/crates.io-index"
2353checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
2354dependencies = [
2355 "arrayvec",
2356]
2357
2358[[package]]
2359name = "portable-atomic"
2360version = "1.15.0"
2361source = "registry+https://github.com/rust-lang/crates.io-index"
2362checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
2363
2364[[package]]
2365name = "portable-atomic-util"
2366version = "0.2.8"
2367source = "registry+https://github.com/rust-lang/crates.io-index"
2368checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
2369dependencies = [
2370 "portable-atomic",
2371]
2372
2373[[package]]
2374name = "powerfmt"
2375version = "0.2.1"
2376source = "registry+https://github.com/rust-lang/crates.io-index"
2377checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
2378
2379[[package]]
2380name = "presser"
2381version = "0.3.1"
2382source = "registry+https://github.com/rust-lang/crates.io-index"
2383checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
2384
2385[[package]]
2386name = "proc-macro-crate"
2387version = "3.5.0"
2388source = "registry+https://github.com/rust-lang/crates.io-index"
2389checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
2390dependencies = [
2391 "toml_edit",
2392]
2393
2394[[package]]
2395name = "proc-macro2"
2396version = "1.0.107"
2397source = "registry+https://github.com/rust-lang/crates.io-index"
2398checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
2399dependencies = [
2400 "unicode-ident",
2401]
2402
2403[[package]]
2404name = "profiling"
2405version = "1.0.18"
2406source = "registry+https://github.com/rust-lang/crates.io-index"
2407checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
2408
2409[[package]]
2410name = "pxfm"
2411version = "0.1.30"
2412source = "registry+https://github.com/rust-lang/crates.io-index"
2413checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
2414
2415[[package]]
2416name = "qrcodegen"
2417version = "1.8.0"
2418source = "registry+https://github.com/rust-lang/crates.io-index"
2419checksum = "4339fc7a1021c9c1621d87f5e3505f2805c8c105420ba2f2a4df86814590c142"
2420
2421[[package]]
2422name = "quick-error"
2423version = "2.0.1"
2424source = "registry+https://github.com/rust-lang/crates.io-index"
2425checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
2426
2427[[package]]
2428name = "quick-xml"
2429version = "0.41.0"
2430source = "registry+https://github.com/rust-lang/crates.io-index"
2431checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
2432dependencies = [
2433 "memchr",
2434]
2435
2436[[package]]
2437name = "quote"
2438version = "1.0.47"
2439source = "registry+https://github.com/rust-lang/crates.io-index"
2440checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
2441dependencies = [
2442 "proc-macro2",
2443]
2444
2445[[package]]
2446name = "r-efi"
2447version = "6.0.0"
2448source = "registry+https://github.com/rust-lang/crates.io-index"
2449checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
2450
2451[[package]]
2452name = "range-alloc"
2453version = "0.1.5"
2454source = "registry+https://github.com/rust-lang/crates.io-index"
2455checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
2456
2457[[package]]
2458name = "raw-window-handle"
2459version = "0.6.2"
2460source = "registry+https://github.com/rust-lang/crates.io-index"
2461checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
2462
2463[[package]]
2464name = "raw-window-metal"
2465version = "1.1.0"
2466source = "registry+https://github.com/rust-lang/crates.io-index"
2467checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
2468dependencies = [
2469 "objc2 0.6.5",
2470 "objc2-core-foundation",
2471 "objc2-foundation 0.3.2",
2472 "objc2-quartz-core 0.3.2",
2473]
2474
2475[[package]]
2476name = "rayon-core"
2477version = "1.13.0"
2478source = "registry+https://github.com/rust-lang/crates.io-index"
2479checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
2480dependencies = [
2481 "crossbeam-deque",
2482 "crossbeam-utils",
2483]
2484
2485[[package]]
2486name = "read-fonts"
2487version = "0.41.0"
2488source = "registry+https://github.com/rust-lang/crates.io-index"
2489checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
2490dependencies = [
2491 "bytemuck",
2492 "font-types",
2493 "once_cell",
2494]
2495
2496[[package]]
2497name = "read-fonts"
2498version = "0.46.0"
2499source = "registry+https://github.com/rust-lang/crates.io-index"
2500checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330"
2501dependencies = [
2502 "bytemuck",
2503 "foldhash 0.2.0",
2504 "font-types",
2505 "once_cell",
2506 "smallvec",
2507 "yoke",
2508]
2509
2510[[package]]
2511name = "redox_syscall"
2512version = "0.4.1"
2513source = "registry+https://github.com/rust-lang/crates.io-index"
2514checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
2515dependencies = [
2516 "bitflags 1.3.2",
2517]
2518
2519[[package]]
2520name = "redox_syscall"
2521version = "0.5.18"
2522source = "registry+https://github.com/rust-lang/crates.io-index"
2523checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
2524dependencies = [
2525 "bitflags 2.13.2",
2526]
2527
2528[[package]]
2529name = "redox_syscall"
2530version = "0.9.5"
2531source = "registry+https://github.com/rust-lang/crates.io-index"
2532checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
2533dependencies = [
2534 "bitflags 2.13.2",
2535]
2536
2537[[package]]
2538name = "regex"
2539version = "1.13.2"
2540source = "registry+https://github.com/rust-lang/crates.io-index"
2541checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
2542dependencies = [
2543 "aho-corasick",
2544 "memchr",
2545 "regex-automata",
2546 "regex-syntax",
2547]
2548
2549[[package]]
2550name = "regex-automata"
2551version = "0.4.19"
2552source = "registry+https://github.com/rust-lang/crates.io-index"
2553checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
2554dependencies = [
2555 "aho-corasick",
2556 "memchr",
2557 "regex-syntax",
2558]
2559
2560[[package]]
2561name = "regex-syntax"
2562version = "0.8.12"
2563source = "registry+https://github.com/rust-lang/crates.io-index"
2564checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
2565
2566[[package]]
2567name = "renderdoc-sys"
2568version = "1.1.0"
2569source = "registry+https://github.com/rust-lang/crates.io-index"
2570checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
2571
2572[[package]]
2573name = "resvg"
2574version = "0.48.1"
2575source = "registry+https://github.com/rust-lang/crates.io-index"
2576checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
2577dependencies = [
2578 "bytemuck",
2579 "log",
2580 "pico-args",
2581 "rgb",
2582 "svgtypes",
2583 "tiny-skia 0.12.0",
2584 "usvg",
2585]
2586
2587[[package]]
2588name = "rgb"
2589version = "0.8.53"
2590source = "registry+https://github.com/rust-lang/crates.io-index"
2591checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
2592dependencies = [
2593 "bytemuck",
2594]
2595
2596[[package]]
2597name = "roxmltree"
2598version = "0.20.0"
2599source = "registry+https://github.com/rust-lang/crates.io-index"
2600checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
2601
2602[[package]]
2603name = "roxmltree"
2604version = "0.21.2"
2605source = "registry+https://github.com/rust-lang/crates.io-index"
2606checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
2607dependencies = [
2608 "memchr",
2609]
2610
2611[[package]]
2612name = "rustc-hash"
2613version = "1.1.0"
2614source = "registry+https://github.com/rust-lang/crates.io-index"
2615checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
2616
2617[[package]]
2618name = "rustc-hash"
2619version = "2.1.3"
2620source = "registry+https://github.com/rust-lang/crates.io-index"
2621checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
2622
2623[[package]]
2624name = "rustc_version"
2625version = "0.4.1"
2626source = "registry+https://github.com/rust-lang/crates.io-index"
2627checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
2628dependencies = [
2629 "semver",
2630]
2631
2632[[package]]
2633name = "rustix"
2634version = "0.38.44"
2635source = "registry+https://github.com/rust-lang/crates.io-index"
2636checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
2637dependencies = [
2638 "bitflags 2.13.2",
2639 "errno",
2640 "libc",
2641 "linux-raw-sys 0.4.15",
2642 "windows-sys 0.59.0",
2643]
2644
2645[[package]]
2646name = "rustix"
2647version = "1.1.6"
2648source = "registry+https://github.com/rust-lang/crates.io-index"
2649checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
2650dependencies = [
2651 "bitflags 2.13.2",
2652 "errno",
2653 "libc",
2654 "linux-raw-sys 0.12.1",
2655 "windows-sys 0.61.2",
2656]
2657
2658[[package]]
2659name = "rustversion"
2660version = "1.0.23"
2661source = "registry+https://github.com/rust-lang/crates.io-index"
2662checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
2663
2664[[package]]
2665name = "same-file"
2666version = "1.0.6"
2667source = "registry+https://github.com/rust-lang/crates.io-index"
2668checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
2669dependencies = [
2670 "winapi-util",
2671]
2672
2673[[package]]
2674name = "scoped-tls"
2675version = "1.0.1"
2676source = "registry+https://github.com/rust-lang/crates.io-index"
2677checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
2678
2679[[package]]
2680name = "scopeguard"
2681version = "1.2.0"
2682source = "registry+https://github.com/rust-lang/crates.io-index"
2683checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
2684
2685[[package]]
2686name = "sctk-adwaita"
2687version = "0.10.1"
2688source = "registry+https://github.com/rust-lang/crates.io-index"
2689checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
2690dependencies = [
2691 "ab_glyph",
2692 "log",
2693 "memmap2",
2694 "smithay-client-toolkit",
2695 "tiny-skia 0.11.4",
2696]
2697
2698[[package]]
2699name = "semver"
2700version = "1.0.28"
2701source = "registry+https://github.com/rust-lang/crates.io-index"
2702checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
2703
2704[[package]]
2705name = "serde"
2706version = "1.0.229"
2707source = "registry+https://github.com/rust-lang/crates.io-index"
2708checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
2709dependencies = [
2710 "serde_core",
2711 "serde_derive",
2712]
2713
2714[[package]]
2715name = "serde_core"
2716version = "1.0.229"
2717source = "registry+https://github.com/rust-lang/crates.io-index"
2718checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
2719dependencies = [
2720 "serde_derive",
2721]
2722
2723[[package]]
2724name = "serde_derive"
2725version = "1.0.229"
2726source = "registry+https://github.com/rust-lang/crates.io-index"
2727checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
2728dependencies = [
2729 "proc-macro2",
2730 "quote",
2731 "syn 3.0.10",
2732]
2733
2734[[package]]
2735name = "serde_json"
2736version = "1.0.154"
2737source = "registry+https://github.com/rust-lang/crates.io-index"
2738checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
2739dependencies = [
2740 "foldhash 0.2.0",
2741 "indexmap",
2742 "itoa",
2743 "memchr",
2744 "serde",
2745 "serde_core",
2746 "zmij",
2747]
2748
2749[[package]]
2750name = "serde_repr"
2751version = "0.1.21"
2752source = "registry+https://github.com/rust-lang/crates.io-index"
2753checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
2754dependencies = [
2755 "proc-macro2",
2756 "quote",
2757 "syn 3.0.10",
2758]
2759
2760[[package]]
2761name = "sha2"
2762version = "0.11.2"
2763source = "registry+https://github.com/rust-lang/crates.io-index"
2764checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
2765dependencies = [
2766 "cfg-if",
2767 "cpufeatures",
2768 "digest",
2769]
2770
2771[[package]]
2772name = "shlex"
2773version = "2.0.1"
2774source = "registry+https://github.com/rust-lang/crates.io-index"
2775checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
2776
2777[[package]]
2778name = "signal-hook-registry"
2779version = "1.4.8"
2780source = "registry+https://github.com/rust-lang/crates.io-index"
2781checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
2782dependencies = [
2783 "errno",
2784 "libc",
2785]
2786
2787[[package]]
2788name = "simd-adler32"
2789version = "0.3.10"
2790source = "registry+https://github.com/rust-lang/crates.io-index"
2791checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
2792
2793[[package]]
2794name = "simd_cesu8"
2795version = "1.2.0"
2796source = "registry+https://github.com/rust-lang/crates.io-index"
2797checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
2798dependencies = [
2799 "rustc_version",
2800 "simdutf8",
2801]
2802
2803[[package]]
2804name = "simdutf8"
2805version = "0.1.5"
2806source = "registry+https://github.com/rust-lang/crates.io-index"
2807checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
2808
2809[[package]]
2810name = "simplecss"
2811version = "0.2.2"
2812source = "registry+https://github.com/rust-lang/crates.io-index"
2813checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
2814dependencies = [
2815 "log",
2816]
2817
2818[[package]]
2819name = "siphasher"
2820version = "1.0.4"
2821source = "registry+https://github.com/rust-lang/crates.io-index"
2822checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
2823
2824[[package]]
2825name = "skrifa"
2826version = "0.44.0"
2827source = "registry+https://github.com/rust-lang/crates.io-index"
2828checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
2829dependencies = [
2830 "bytemuck",
2831 "read-fonts 0.41.0",
2832]
2833
2834[[package]]
2835name = "skrifa"
2836version = "0.49.0"
2837source = "registry+https://github.com/rust-lang/crates.io-index"
2838checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d"
2839dependencies = [
2840 "bytemuck",
2841 "once_cell",
2842 "read-fonts 0.46.0",
2843 "smallvec",
2844 "yoke",
2845]
2846
2847[[package]]
2848name = "slab"
2849version = "0.4.12"
2850source = "registry+https://github.com/rust-lang/crates.io-index"
2851checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
2852
2853[[package]]
2854name = "slotmap"
2855version = "1.1.1"
2856source = "registry+https://github.com/rust-lang/crates.io-index"
2857checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
2858dependencies = [
2859 "version_check",
2860]
2861
2862[[package]]
2863name = "smallvec"
2864version = "1.16.6"
2865source = "registry+https://github.com/rust-lang/crates.io-index"
2866checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
2867
2868[[package]]
2869name = "smithay-client-toolkit"
2870version = "0.19.2"
2871source = "registry+https://github.com/rust-lang/crates.io-index"
2872checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
2873dependencies = [
2874 "bitflags 2.13.2",
2875 "calloop",
2876 "calloop-wayland-source",
2877 "cursor-icon",
2878 "libc",
2879 "log",
2880 "memmap2",
2881 "rustix 0.38.44",
2882 "thiserror 1.0.69",
2883 "wayland-backend",
2884 "wayland-client",
2885 "wayland-csd-frame",
2886 "wayland-cursor",
2887 "wayland-protocols",
2888 "wayland-protocols-wlr",
2889 "wayland-scanner",
2890 "xkeysym",
2891]
2892
2893[[package]]
2894name = "smol_str"
2895version = "0.2.2"
2896source = "registry+https://github.com/rust-lang/crates.io-index"
2897checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"
2898dependencies = [
2899 "serde",
2900]
2901
2902[[package]]
2903name = "spirv"
2904version = "0.4.0+sdk-1.4.341.0"
2905source = "registry+https://github.com/rust-lang/crates.io-index"
2906checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
2907dependencies = [
2908 "bitflags 2.13.2",
2909]
2910
2911[[package]]
2912name = "spline"
2913version = "0.1.0"
2914dependencies = [
2915 "draw",
2916 "model",
2917 "text",
2918 "theme",
2919 "ui",
2920 "winit",
2921]
2922
2923[[package]]
2924name = "stable_deref_trait"
2925version = "1.2.1"
2926source = "registry+https://github.com/rust-lang/crates.io-index"
2927checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
2928
2929[[package]]
2930name = "state"
2931version = "0.1.0"
2932dependencies = [
2933 "libc",
2934 "serde_json",
2935 "sha2",
2936 "state-derive",
2937 "windows-sys 0.61.2",
2938]
2939
2940[[package]]
2941name = "state-derive"
2942version = "0.1.0"
2943dependencies = [
2944 "proc-macro2",
2945 "quote",
2946 "syn 2.0.119",
2947]
2948
2949[[package]]
2950name = "static_assertions"
2951version = "1.1.0"
2952source = "registry+https://github.com/rust-lang/crates.io-index"
2953checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
2954
2955[[package]]
2956name = "streaming-iterator"
2957version = "0.1.9"
2958source = "registry+https://github.com/rust-lang/crates.io-index"
2959checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"
2960
2961[[package]]
2962name = "strict-num"
2963version = "0.1.1"
2964source = "registry+https://github.com/rust-lang/crates.io-index"
2965checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
2966dependencies = [
2967 "float-cmp",
2968]
2969
2970[[package]]
2971name = "studio"
2972version = "0.1.0"
2973dependencies = [
2974 "accesskit",
2975 "accesskit_winit",
2976 "dock",
2977 "draw",
2978 "engine",
2979 "flow",
2980 "model",
2981 "objc2 0.6.5",
2982 "objc2-app-kit 0.3.2",
2983 "objc2-foundation 0.3.2",
2984 "png",
2985 "pollster",
2986 "spline",
2987 "state",
2988 "text",
2989 "theme",
2990 "ui",
2991 "viewer",
2992 "wgpu",
2993 "winit",
2994]
2995
2996[[package]]
2997name = "svgtypes"
2998version = "0.16.2"
2999source = "registry+https://github.com/rust-lang/crates.io-index"
3000checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
3001dependencies = [
3002 "kurbo",
3003 "siphasher",
3004]
3005
3006[[package]]
3007name = "syn"
3008version = "2.0.119"
3009source = "registry+https://github.com/rust-lang/crates.io-index"
3010checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
3011dependencies = [
3012 "proc-macro2",
3013 "quote",
3014 "unicode-ident",
3015]
3016
3017[[package]]
3018name = "syn"
3019version = "3.0.10"
3020source = "registry+https://github.com/rust-lang/crates.io-index"
3021checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
3022dependencies = [
3023 "proc-macro2",
3024 "quote",
3025 "unicode-ident",
3026]
3027
3028[[package]]
3029name = "synstructure"
3030version = "0.14.0"
3031source = "registry+https://github.com/rust-lang/crates.io-index"
3032checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
3033dependencies = [
3034 "proc-macro2",
3035 "quote",
3036 "syn 3.0.10",
3037]
3038
3039[[package]]
3040name = "target-features"
3041version = "0.1.6"
3042source = "registry+https://github.com/rust-lang/crates.io-index"
3043checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
3044
3045[[package]]
3046name = "tempfile"
3047version = "3.27.0"
3048source = "registry+https://github.com/rust-lang/crates.io-index"
3049checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
3050dependencies = [
3051 "fastrand",
3052 "getrandom",
3053 "once_cell",
3054 "rustix 1.1.6",
3055 "windows-sys 0.61.2",
3056]
3057
3058[[package]]
3059name = "termcolor"
3060version = "1.4.1"
3061source = "registry+https://github.com/rust-lang/crates.io-index"
3062checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
3063dependencies = [
3064 "winapi-util",
3065]
3066
3067[[package]]
3068name = "text"
3069version = "0.1.0"
3070dependencies = [
3071 "harfrust 0.15.0",
3072 "objc2 0.6.5",
3073 "objc2-app-kit 0.3.2",
3074 "objc2-core-foundation",
3075 "objc2-core-graphics",
3076 "objc2-core-text",
3077 "objc2-foundation 0.3.2",
3078 "png",
3079 "skrifa 0.49.0",
3080 "unicode-bidi",
3081 "unicode-general-category",
3082 "unicode-linebreak",
3083 "unicode-normalization",
3084 "unicode-script",
3085 "unicode-segmentation",
3086 "wuff",
3087 "zeno",
3088]
3089
3090[[package]]
3091name = "theme"
3092version = "0.1.0"
3093dependencies = [
3094 "diff",
3095 "draw",
3096 "highlight",
3097 "memmap2",
3098 "text",
3099]
3100
3101[[package]]
3102name = "thiserror"
3103version = "1.0.69"
3104source = "registry+https://github.com/rust-lang/crates.io-index"
3105checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
3106dependencies = [
3107 "thiserror-impl 1.0.69",
3108]
3109
3110[[package]]
3111name = "thiserror"
3112version = "2.0.21"
3113source = "registry+https://github.com/rust-lang/crates.io-index"
3114checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
3115dependencies = [
3116 "thiserror-impl 2.0.21",
3117]
3118
3119[[package]]
3120name = "thiserror-impl"
3121version = "1.0.69"
3122source = "registry+https://github.com/rust-lang/crates.io-index"
3123checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
3124dependencies = [
3125 "proc-macro2",
3126 "quote",
3127 "syn 2.0.119",
3128]
3129
3130[[package]]
3131name = "thiserror-impl"
3132version = "2.0.21"
3133source = "registry+https://github.com/rust-lang/crates.io-index"
3134checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
3135dependencies = [
3136 "proc-macro2",
3137 "quote",
3138 "syn 3.0.10",
3139]
3140
3141[[package]]
3142name = "tiff"
3143version = "0.11.3"
3144source = "registry+https://github.com/rust-lang/crates.io-index"
3145checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
3146dependencies = [
3147 "fax",
3148 "flate2",
3149 "half",
3150 "quick-error",
3151 "weezl",
3152 "zune-jpeg",
3153]
3154
3155[[package]]
3156name = "time"
3157version = "0.3.55"
3158source = "registry+https://github.com/rust-lang/crates.io-index"
3159checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
3160dependencies = [
3161 "deranged",
3162 "num-conv",
3163 "powerfmt",
3164 "serde_core",
3165 "time-core",
3166]
3167
3168[[package]]
3169name = "time-core"
3170version = "0.1.9"
3171source = "registry+https://github.com/rust-lang/crates.io-index"
3172checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
3173
3174[[package]]
3175name = "tiny-skia"
3176version = "0.11.4"
3177source = "registry+https://github.com/rust-lang/crates.io-index"
3178checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
3179dependencies = [
3180 "arrayref",
3181 "arrayvec",
3182 "bytemuck",
3183 "cfg-if",
3184 "log",
3185 "tiny-skia-path 0.11.4",
3186]
3187
3188[[package]]
3189name = "tiny-skia"
3190version = "0.12.0"
3191source = "registry+https://github.com/rust-lang/crates.io-index"
3192checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
3193dependencies = [
3194 "arrayref",
3195 "arrayvec",
3196 "bytemuck",
3197 "cfg-if",
3198 "log",
3199 "png",
3200 "tiny-skia-path 0.12.0",
3201]
3202
3203[[package]]
3204name = "tiny-skia-path"
3205version = "0.11.4"
3206source = "registry+https://github.com/rust-lang/crates.io-index"
3207checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
3208dependencies = [
3209 "arrayref",
3210 "bytemuck",
3211 "strict-num",
3212]
3213
3214[[package]]
3215name = "tiny-skia-path"
3216version = "0.12.0"
3217source = "registry+https://github.com/rust-lang/crates.io-index"
3218checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
3219dependencies = [
3220 "arrayref",
3221 "bytemuck",
3222 "strict-num",
3223]
3224
3225[[package]]
3226name = "tinyvec"
3227version = "1.13.3"
3228source = "registry+https://github.com/rust-lang/crates.io-index"
3229checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
3230
3231[[package]]
3232name = "tokio"
3233version = "1.54.1"
3234source = "registry+https://github.com/rust-lang/crates.io-index"
3235checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
3236dependencies = [
3237 "pin-project-lite",
3238]
3239
3240[[package]]
3241name = "toml_datetime"
3242version = "1.1.3+spec-1.1.0"
3243source = "registry+https://github.com/rust-lang/crates.io-index"
3244checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
3245dependencies = [
3246 "serde_core",
3247]
3248
3249[[package]]
3250name = "toml_edit"
3251version = "0.25.21+spec-1.1.0"
3252source = "registry+https://github.com/rust-lang/crates.io-index"
3253checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4"
3254dependencies = [
3255 "indexmap",
3256 "toml_datetime",
3257 "toml_parser",
3258 "winnow",
3259]
3260
3261[[package]]
3262name = "toml_parser"
3263version = "1.1.7+spec-1.1.0"
3264source = "registry+https://github.com/rust-lang/crates.io-index"
3265checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
3266dependencies = [
3267 "winnow",
3268]
3269
3270[[package]]
3271name = "tracing"
3272version = "0.1.44"
3273source = "registry+https://github.com/rust-lang/crates.io-index"
3274checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
3275dependencies = [
3276 "pin-project-lite",
3277 "tracing-attributes",
3278 "tracing-core",
3279]
3280
3281[[package]]
3282name = "tracing-attributes"
3283version = "0.1.31"
3284source = "registry+https://github.com/rust-lang/crates.io-index"
3285checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
3286dependencies = [
3287 "proc-macro2",
3288 "quote",
3289 "syn 2.0.119",
3290]
3291
3292[[package]]
3293name = "tracing-core"
3294version = "0.1.36"
3295source = "registry+https://github.com/rust-lang/crates.io-index"
3296checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
3297dependencies = [
3298 "once_cell",
3299]
3300
3301[[package]]
3302name = "tree-sitter"
3303version = "0.27.2"
3304source = "registry+https://github.com/rust-lang/crates.io-index"
3305checksum = "37b2bed8f39a73439f3b0b7ed8f452be5d2911b5e9da69d352ef113bb7448fb8"
3306dependencies = [
3307 "cc",
3308 "regex",
3309 "serde_json",
3310 "streaming-iterator",
3311 "tree-sitter-language",
3312]
3313
3314[[package]]
3315name = "tree-sitter-bash"
3316version = "0.25.1"
3317source = "registry+https://github.com/rust-lang/crates.io-index"
3318checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062"
3319dependencies = [
3320 "cc",
3321 "tree-sitter-language",
3322]
3323
3324[[package]]
3325name = "tree-sitter-c"
3326version = "0.24.2"
3327source = "registry+https://github.com/rust-lang/crates.io-index"
3328checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728"
3329dependencies = [
3330 "cc",
3331 "tree-sitter-language",
3332]
3333
3334[[package]]
3335name = "tree-sitter-cpp"
3336version = "0.23.4"
3337source = "registry+https://github.com/rust-lang/crates.io-index"
3338checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743"
3339dependencies = [
3340 "cc",
3341 "tree-sitter-language",
3342]
3343
3344[[package]]
3345name = "tree-sitter-css"
3346version = "0.25.0"
3347source = "registry+https://github.com/rust-lang/crates.io-index"
3348checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f"
3349dependencies = [
3350 "cc",
3351 "tree-sitter-language",
3352]
3353
3354[[package]]
3355name = "tree-sitter-diff"
3356version = "0.1.0"
3357source = "registry+https://github.com/rust-lang/crates.io-index"
3358checksum = "dfe1e5ca280a65dfe5ba4205c1bcc84edf486464fed315db53dee6da9a335889"
3359dependencies = [
3360 "cc",
3361 "tree-sitter-language",
3362]
3363
3364[[package]]
3365name = "tree-sitter-go"
3366version = "0.25.0"
3367source = "registry+https://github.com/rust-lang/crates.io-index"
3368checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea"
3369dependencies = [
3370 "cc",
3371 "tree-sitter-language",
3372]
3373
3374[[package]]
3375name = "tree-sitter-html"
3376version = "0.23.2"
3377source = "registry+https://github.com/rust-lang/crates.io-index"
3378checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee"
3379dependencies = [
3380 "cc",
3381 "tree-sitter-language",
3382]
3383
3384[[package]]
3385name = "tree-sitter-java"
3386version = "0.23.5"
3387source = "registry+https://github.com/rust-lang/crates.io-index"
3388checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"
3389dependencies = [
3390 "cc",
3391 "tree-sitter-language",
3392]
3393
3394[[package]]
3395name = "tree-sitter-javascript"
3396version = "0.25.0"
3397source = "registry+https://github.com/rust-lang/crates.io-index"
3398checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5"
3399dependencies = [
3400 "cc",
3401 "tree-sitter-language",
3402]
3403
3404[[package]]
3405name = "tree-sitter-json"
3406version = "0.24.8"
3407source = "registry+https://github.com/rust-lang/crates.io-index"
3408checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471"
3409dependencies = [
3410 "cc",
3411 "tree-sitter-language",
3412]
3413
3414[[package]]
3415name = "tree-sitter-language"
3416version = "0.1.9"
3417source = "registry+https://github.com/rust-lang/crates.io-index"
3418checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a"
3419
3420[[package]]
3421name = "tree-sitter-lua"
3422version = "0.5.0"
3423source = "registry+https://github.com/rust-lang/crates.io-index"
3424checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c"
3425dependencies = [
3426 "cc",
3427 "tree-sitter-language",
3428]
3429
3430[[package]]
3431name = "tree-sitter-md"
3432version = "0.5.4"
3433source = "registry+https://github.com/rust-lang/crates.io-index"
3434checksum = "8ed661bfe3c264961425f77cd89ad2998bf5d629e71ce8bab1e5d7e940d6246e"
3435dependencies = [
3436 "cc",
3437 "tree-sitter-language",
3438]
3439
3440[[package]]
3441name = "tree-sitter-python"
3442version = "0.25.0"
3443source = "registry+https://github.com/rust-lang/crates.io-index"
3444checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c"
3445dependencies = [
3446 "cc",
3447 "tree-sitter-language",
3448]
3449
3450[[package]]
3451name = "tree-sitter-ruby"
3452version = "0.23.1"
3453source = "registry+https://github.com/rust-lang/crates.io-index"
3454checksum = "be0484ea4ef6bb9c575b4fdabde7e31340a8d2dbc7d52b321ac83da703249f95"
3455dependencies = [
3456 "cc",
3457 "tree-sitter-language",
3458]
3459
3460[[package]]
3461name = "tree-sitter-rust"
3462version = "0.24.2"
3463source = "registry+https://github.com/rust-lang/crates.io-index"
3464checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"
3465dependencies = [
3466 "cc",
3467 "tree-sitter-language",
3468]
3469
3470[[package]]
3471name = "tree-sitter-sequel"
3472version = "0.3.13"
3473source = "registry+https://github.com/rust-lang/crates.io-index"
3474checksum = "711e236e1ae0708f911d8413c3b5656f522416cba683ea91589aebc49eda1b5a"
3475dependencies = [
3476 "cc",
3477 "tree-sitter-language",
3478]
3479
3480[[package]]
3481name = "tree-sitter-swift"
3482version = "0.7.4"
3483source = "registry+https://github.com/rust-lang/crates.io-index"
3484checksum = "2688c06564afa397313e0db17d140a73e2c6a47f3884794614246167c9dd5dfd"
3485dependencies = [
3486 "cc",
3487 "tree-sitter-language",
3488]
3489
3490[[package]]
3491name = "tree-sitter-toml-ng"
3492version = "0.7.0"
3493source = "registry+https://github.com/rust-lang/crates.io-index"
3494checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1"
3495dependencies = [
3496 "cc",
3497 "tree-sitter-language",
3498]
3499
3500[[package]]
3501name = "tree-sitter-typescript"
3502version = "0.23.2"
3503source = "registry+https://github.com/rust-lang/crates.io-index"
3504checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff"
3505dependencies = [
3506 "cc",
3507 "tree-sitter-language",
3508]
3509
3510[[package]]
3511name = "tree-sitter-yaml"
3512version = "0.7.2"
3513source = "registry+https://github.com/rust-lang/crates.io-index"
3514checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97"
3515dependencies = [
3516 "cc",
3517 "tree-sitter-language",
3518]
3519
3520[[package]]
3521name = "tree-sitter-zig"
3522version = "1.1.2"
3523source = "registry+https://github.com/rust-lang/crates.io-index"
3524checksum = "ab11fc124851b0db4dd5e55983bbd9631192e93238389dcd44521715e5d53e28"
3525dependencies = [
3526 "cc",
3527 "tree-sitter-language",
3528]
3529
3530[[package]]
3531name = "tree_magic_mini"
3532version = "3.2.2"
3533source = "registry+https://github.com/rust-lang/crates.io-index"
3534checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
3535dependencies = [
3536 "memchr",
3537 "nom",
3538 "petgraph",
3539]
3540
3541[[package]]
3542name = "ttf-parser"
3543version = "0.25.1"
3544source = "registry+https://github.com/rust-lang/crates.io-index"
3545checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
3546
3547[[package]]
3548name = "typenum"
3549version = "1.20.1"
3550source = "registry+https://github.com/rust-lang/crates.io-index"
3551checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
3552
3553[[package]]
3554name = "uds_windows"
3555version = "1.2.1"
3556source = "registry+https://github.com/rust-lang/crates.io-index"
3557checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
3558dependencies = [
3559 "memoffset",
3560 "tempfile",
3561 "windows-sys 0.61.2",
3562]
3563
3564[[package]]
3565name = "ui"
3566version = "0.1.0"
3567dependencies = [
3568 "accesskit",
3569 "accesskit_consumer",
3570 "accesskit_winit",
3571 "arboard",
3572 "block2 0.6.2",
3573 "draw",
3574 "edit",
3575 "fontdb",
3576 "knife-window-host",
3577 "libc",
3578 "nucleo-matcher",
3579 "objc2 0.6.5",
3580 "objc2-app-kit 0.3.2",
3581 "objc2-core-foundation",
3582 "objc2-core-video",
3583 "objc2-foundation 0.3.2",
3584 "objc2-metal 0.3.2",
3585 "objc2-quartz-core 0.3.2",
3586 "qrcodegen",
3587 "serde_json",
3588 "siphasher",
3589 "text",
3590 "theme",
3591 "time",
3592 "wgpu",
3593 "windows-sys 0.61.2",
3594 "winit",
3595 "x11rb",
3596 "zbus",
3597]
3598
3599[[package]]
3600name = "unicode-bidi"
3601version = "0.3.18"
3602source = "registry+https://github.com/rust-lang/crates.io-index"
3603checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
3604
3605[[package]]
3606name = "unicode-general-category"
3607version = "1.1.0"
3608source = "registry+https://github.com/rust-lang/crates.io-index"
3609checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
3610
3611[[package]]
3612name = "unicode-ident"
3613version = "1.0.27"
3614source = "registry+https://github.com/rust-lang/crates.io-index"
3615checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
3616
3617[[package]]
3618name = "unicode-linebreak"
3619version = "0.1.5"
3620source = "registry+https://github.com/rust-lang/crates.io-index"
3621checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
3622
3623[[package]]
3624name = "unicode-normalization"
3625version = "0.1.26"
3626source = "registry+https://github.com/rust-lang/crates.io-index"
3627checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
3628dependencies = [
3629 "tinyvec",
3630]
3631
3632[[package]]
3633name = "unicode-script"
3634version = "0.5.9"
3635source = "registry+https://github.com/rust-lang/crates.io-index"
3636checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"
3637
3638[[package]]
3639name = "unicode-segmentation"
3640version = "1.13.3"
3641source = "registry+https://github.com/rust-lang/crates.io-index"
3642checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
3643
3644[[package]]
3645name = "unicode-vo"
3646version = "0.1.0"
3647source = "registry+https://github.com/rust-lang/crates.io-index"
3648checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
3649
3650[[package]]
3651name = "unicode-width"
3652version = "0.2.3"
3653source = "registry+https://github.com/rust-lang/crates.io-index"
3654checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
3655
3656[[package]]
3657name = "usvg"
3658version = "0.48.1"
3659source = "registry+https://github.com/rust-lang/crates.io-index"
3660checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
3661dependencies = [
3662 "base64",
3663 "data-url",
3664 "fontdb",
3665 "harfrust 0.12.0",
3666 "imagesize",
3667 "kurbo",
3668 "log",
3669 "pico-args",
3670 "roxmltree 0.21.2",
3671 "simplecss",
3672 "siphasher",
3673 "skrifa 0.44.0",
3674 "strict-num",
3675 "svgtypes",
3676 "tiny-skia-path 0.12.0",
3677 "unicode-bidi",
3678 "unicode-script",
3679 "unicode-vo",
3680 "xmlwriter",
3681]
3682
3683[[package]]
3684name = "uuid"
3685version = "1.29.3"
3686source = "registry+https://github.com/rust-lang/crates.io-index"
3687checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
3688dependencies = [
3689 "js-sys",
3690 "serde_core",
3691 "wasm-bindgen",
3692]
3693
3694[[package]]
3695name = "version_check"
3696version = "0.9.5"
3697source = "registry+https://github.com/rust-lang/crates.io-index"
3698checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
3699
3700[[package]]
3701name = "viewer"
3702version = "0.1.0"
3703dependencies = [
3704 "draw",
3705 "engine",
3706 "model",
3707 "text",
3708 "theme",
3709 "ui",
3710 "wgpu",
3711 "winit",
3712]
3713
3714[[package]]
3715name = "walkdir"
3716version = "2.5.1"
3717source = "registry+https://github.com/rust-lang/crates.io-index"
3718checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403"
3719dependencies = [
3720 "same-file",
3721 "winapi-util",
3722]
3723
3724[[package]]
3725name = "wasm-bindgen"
3726version = "0.2.130"
3727source = "registry+https://github.com/rust-lang/crates.io-index"
3728checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
3729dependencies = [
3730 "cfg-if",
3731 "rustversion",
3732 "wasm-bindgen-macro",
3733 "wasm-bindgen-shared",
3734]
3735
3736[[package]]
3737name = "wasm-bindgen-futures"
3738version = "0.4.80"
3739source = "registry+https://github.com/rust-lang/crates.io-index"
3740checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
3741dependencies = [
3742 "js-sys",
3743 "tokio",
3744 "wasm-bindgen",
3745]
3746
3747[[package]]
3748name = "wasm-bindgen-macro"
3749version = "0.2.130"
3750source = "registry+https://github.com/rust-lang/crates.io-index"
3751checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
3752dependencies = [
3753 "quote",
3754 "wasm-bindgen-macro-support",
3755]
3756
3757[[package]]
3758name = "wasm-bindgen-macro-support"
3759version = "0.2.130"
3760source = "registry+https://github.com/rust-lang/crates.io-index"
3761checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
3762dependencies = [
3763 "bumpalo",
3764 "proc-macro2",
3765 "quote",
3766 "syn 3.0.10",
3767 "wasm-bindgen-shared",
3768]
3769
3770[[package]]
3771name = "wasm-bindgen-shared"
3772version = "0.2.130"
3773source = "registry+https://github.com/rust-lang/crates.io-index"
3774checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
3775dependencies = [
3776 "unicode-ident",
3777]
3778
3779[[package]]
3780name = "wayland-backend"
3781version = "0.3.17"
3782source = "registry+https://github.com/rust-lang/crates.io-index"
3783checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
3784dependencies = [
3785 "cc",
3786 "downcast-rs",
3787 "rustix 1.1.6",
3788 "scoped-tls",
3789 "smallvec",
3790 "wayland-sys",
3791]
3792
3793[[package]]
3794name = "wayland-client"
3795version = "0.31.15"
3796source = "registry+https://github.com/rust-lang/crates.io-index"
3797checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
3798dependencies = [
3799 "bitflags 2.13.2",
3800 "rustix 1.1.6",
3801 "wayland-backend",
3802 "wayland-scanner",
3803]
3804
3805[[package]]
3806name = "wayland-csd-frame"
3807version = "0.3.0"
3808source = "registry+https://github.com/rust-lang/crates.io-index"
3809checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
3810dependencies = [
3811 "bitflags 2.13.2",
3812 "cursor-icon",
3813 "wayland-backend",
3814]
3815
3816[[package]]
3817name = "wayland-cursor"
3818version = "0.31.14"
3819source = "registry+https://github.com/rust-lang/crates.io-index"
3820checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
3821dependencies = [
3822 "rustix 1.1.6",
3823 "wayland-client",
3824 "xcursor",
3825]
3826
3827[[package]]
3828name = "wayland-protocols"
3829version = "0.32.13"
3830source = "registry+https://github.com/rust-lang/crates.io-index"
3831checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
3832dependencies = [
3833 "bitflags 2.13.2",
3834 "wayland-backend",
3835 "wayland-client",
3836 "wayland-scanner",
3837]
3838
3839[[package]]
3840name = "wayland-protocols-plasma"
3841version = "0.3.12"
3842source = "registry+https://github.com/rust-lang/crates.io-index"
3843checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
3844dependencies = [
3845 "bitflags 2.13.2",
3846 "wayland-backend",
3847 "wayland-client",
3848 "wayland-protocols",
3849 "wayland-scanner",
3850]
3851
3852[[package]]
3853name = "wayland-protocols-wlr"
3854version = "0.3.12"
3855source = "registry+https://github.com/rust-lang/crates.io-index"
3856checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
3857dependencies = [
3858 "bitflags 2.13.2",
3859 "wayland-backend",
3860 "wayland-client",
3861 "wayland-protocols",
3862 "wayland-scanner",
3863]
3864
3865[[package]]
3866name = "wayland-scanner"
3867version = "0.31.11"
3868source = "registry+https://github.com/rust-lang/crates.io-index"
3869checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
3870dependencies = [
3871 "proc-macro2",
3872 "quick-xml",
3873 "quote",
3874]
3875
3876[[package]]
3877name = "wayland-sys"
3878version = "0.31.11"
3879source = "registry+https://github.com/rust-lang/crates.io-index"
3880checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
3881dependencies = [
3882 "dlib",
3883 "log",
3884 "once_cell",
3885 "pkg-config",
3886]
3887
3888[[package]]
3889name = "web-sys"
3890version = "0.3.107"
3891source = "registry+https://github.com/rust-lang/crates.io-index"
3892checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
3893dependencies = [
3894 "js-sys",
3895 "wasm-bindgen",
3896]
3897
3898[[package]]
3899name = "web-time"
3900version = "1.1.0"
3901source = "registry+https://github.com/rust-lang/crates.io-index"
3902checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
3903dependencies = [
3904 "js-sys",
3905 "wasm-bindgen",
3906]
3907
3908[[package]]
3909name = "weezl"
3910version = "0.1.12"
3911source = "registry+https://github.com/rust-lang/crates.io-index"
3912checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
3913
3914[[package]]
3915name = "wgpu"
3916version = "30.0.2"
3917source = "registry+https://github.com/rust-lang/crates.io-index"
3918checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e"
3919dependencies = [
3920 "arrayvec",
3921 "bitflags 2.13.2",
3922 "bytemuck",
3923 "cfg-if",
3924 "cfg_aliases",
3925 "document-features",
3926 "hashbrown 0.17.2",
3927 "js-sys",
3928 "log",
3929 "naga",
3930 "parking_lot",
3931 "portable-atomic",
3932 "profiling",
3933 "raw-window-handle",
3934 "smallvec",
3935 "static_assertions",
3936 "wasm-bindgen",
3937 "wasm-bindgen-futures",
3938 "web-sys",
3939 "wgpu-core",
3940 "wgpu-hal",
3941 "wgpu-types",
3942]
3943
3944[[package]]
3945name = "wgpu-core"
3946version = "30.0.2"
3947source = "registry+https://github.com/rust-lang/crates.io-index"
3948checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a"
3949dependencies = [
3950 "arrayvec",
3951 "bit-set",
3952 "bit-vec",
3953 "bitflags 2.13.2",
3954 "bytemuck",
3955 "cfg_aliases",
3956 "document-features",
3957 "hashbrown 0.17.2",
3958 "indexmap",
3959 "log",
3960 "naga",
3961 "naga-types",
3962 "once_cell",
3963 "parking_lot",
3964 "portable-atomic",
3965 "profiling",
3966 "raw-window-handle",
3967 "rustc-hash 1.1.0",
3968 "smallvec",
3969 "thiserror 2.0.21",
3970 "wgpu-core-deps-apple",
3971 "wgpu-core-deps-emscripten",
3972 "wgpu-core-deps-windows-linux-android",
3973 "wgpu-hal",
3974 "wgpu-naga-bridge",
3975 "wgpu-types",
3976]
3977
3978[[package]]
3979name = "wgpu-core-deps-apple"
3980version = "30.0.2"
3981source = "registry+https://github.com/rust-lang/crates.io-index"
3982checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16"
3983dependencies = [
3984 "wgpu-hal",
3985]
3986
3987[[package]]
3988name = "wgpu-core-deps-emscripten"
3989version = "30.0.2"
3990source = "registry+https://github.com/rust-lang/crates.io-index"
3991checksum = "55ccf093bd215ae9dc4f96df293e675513ac1f2569f8293a2911cc34ca3505d1"
3992dependencies = [
3993 "wgpu-hal",
3994]
3995
3996[[package]]
3997name = "wgpu-core-deps-windows-linux-android"
3998version = "30.0.2"
3999source = "registry+https://github.com/rust-lang/crates.io-index"
4000checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc"
4001dependencies = [
4002 "wgpu-hal",
4003]
4004
4005[[package]]
4006name = "wgpu-hal"
4007version = "30.0.2"
4008source = "registry+https://github.com/rust-lang/crates.io-index"
4009checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff"
4010dependencies = [
4011 "android_system_properties",
4012 "arrayvec",
4013 "ash",
4014 "bit-set",
4015 "bitflags 2.13.2",
4016 "block2 0.6.2",
4017 "bytemuck",
4018 "cfg-if",
4019 "cfg_aliases",
4020 "glow",
4021 "glutin_wgl_sys",
4022 "gpu-allocator",
4023 "hashbrown 0.17.2",
4024 "js-sys",
4025 "khronos-egl",
4026 "libc",
4027 "libloading",
4028 "log",
4029 "naga",
4030 "naga-types",
4031 "ndk-sys",
4032 "objc2 0.6.5",
4033 "objc2-core-foundation",
4034 "objc2-core-graphics",
4035 "objc2-foundation 0.3.2",
4036 "objc2-metal 0.3.2",
4037 "objc2-quartz-core 0.3.2",
4038 "once_cell",
4039 "ordered-float",
4040 "parking_lot",
4041 "portable-atomic",
4042 "portable-atomic-util",
4043 "profiling",
4044 "range-alloc",
4045 "raw-window-handle",
4046 "raw-window-metal",
4047 "renderdoc-sys",
4048 "smallvec",
4049 "static_assertions",
4050 "thiserror 2.0.21",
4051 "wasm-bindgen",
4052 "wayland-sys",
4053 "web-sys",
4054 "wgpu-naga-bridge",
4055 "wgpu-types",
4056 "windows",
4057 "windows-core",
4058 "windows-result",
4059]
4060
4061[[package]]
4062name = "wgpu-naga-bridge"
4063version = "30.0.2"
4064source = "registry+https://github.com/rust-lang/crates.io-index"
4065checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f"
4066dependencies = [
4067 "naga",
4068 "wgpu-types",
4069]
4070
4071[[package]]
4072name = "wgpu-types"
4073version = "30.0.2"
4074source = "registry+https://github.com/rust-lang/crates.io-index"
4075checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6"
4076dependencies = [
4077 "bitflags 2.13.2",
4078 "bytemuck",
4079 "js-sys",
4080 "log",
4081 "naga-types",
4082 "raw-window-handle",
4083 "static_assertions",
4084 "web-sys",
4085]
4086
4087[[package]]
4088name = "which"
4089version = "7.0.3"
4090source = "registry+https://github.com/rust-lang/crates.io-index"
4091checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
4092dependencies = [
4093 "either",
4094 "env_home",
4095 "rustix 1.1.6",
4096 "winsafe",
4097]
4098
4099[[package]]
4100name = "winapi-util"
4101version = "0.1.11"
4102source = "registry+https://github.com/rust-lang/crates.io-index"
4103checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
4104dependencies = [
4105 "windows-sys 0.61.2",
4106]
4107
4108[[package]]
4109name = "windows"
4110version = "0.62.2"
4111source = "registry+https://github.com/rust-lang/crates.io-index"
4112checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
4113dependencies = [
4114 "windows-collections",
4115 "windows-core",
4116 "windows-future",
4117 "windows-numerics",
4118]
4119
4120[[package]]
4121name = "windows-collections"
4122version = "0.3.2"
4123source = "registry+https://github.com/rust-lang/crates.io-index"
4124checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
4125dependencies = [
4126 "windows-core",
4127]
4128
4129[[package]]
4130name = "windows-core"
4131version = "0.62.2"
4132source = "registry+https://github.com/rust-lang/crates.io-index"
4133checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
4134dependencies = [
4135 "windows-implement",
4136 "windows-interface",
4137 "windows-link",
4138 "windows-result",
4139 "windows-strings",
4140]
4141
4142[[package]]
4143name = "windows-future"
4144version = "0.3.2"
4145source = "registry+https://github.com/rust-lang/crates.io-index"
4146checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
4147dependencies = [
4148 "windows-core",
4149 "windows-link",
4150 "windows-threading",
4151]
4152
4153[[package]]
4154name = "windows-implement"
4155version = "0.60.2"
4156source = "registry+https://github.com/rust-lang/crates.io-index"
4157checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
4158dependencies = [
4159 "proc-macro2",
4160 "quote",
4161 "syn 2.0.119",
4162]
4163
4164[[package]]
4165name = "windows-interface"
4166version = "0.59.3"
4167source = "registry+https://github.com/rust-lang/crates.io-index"
4168checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
4169dependencies = [
4170 "proc-macro2",
4171 "quote",
4172 "syn 2.0.119",
4173]
4174
4175[[package]]
4176name = "windows-link"
4177version = "0.2.1"
4178source = "registry+https://github.com/rust-lang/crates.io-index"
4179checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
4180
4181[[package]]
4182name = "windows-numerics"
4183version = "0.3.1"
4184source = "registry+https://github.com/rust-lang/crates.io-index"
4185checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
4186dependencies = [
4187 "windows-core",
4188 "windows-link",
4189]
4190
4191[[package]]
4192name = "windows-result"
4193version = "0.4.1"
4194source = "registry+https://github.com/rust-lang/crates.io-index"
4195checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
4196dependencies = [
4197 "windows-link",
4198]
4199
4200[[package]]
4201name = "windows-strings"
4202version = "0.5.1"
4203source = "registry+https://github.com/rust-lang/crates.io-index"
4204checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
4205dependencies = [
4206 "windows-link",
4207]
4208
4209[[package]]
4210name = "windows-sys"
4211version = "0.52.0"
4212source = "registry+https://github.com/rust-lang/crates.io-index"
4213checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
4214dependencies = [
4215 "windows-targets",
4216]
4217
4218[[package]]
4219name = "windows-sys"
4220version = "0.59.0"
4221source = "registry+https://github.com/rust-lang/crates.io-index"
4222checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
4223dependencies = [
4224 "windows-targets",
4225]
4226
4227[[package]]
4228name = "windows-sys"
4229version = "0.61.2"
4230source = "registry+https://github.com/rust-lang/crates.io-index"
4231checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
4232dependencies = [
4233 "windows-link",
4234]
4235
4236[[package]]
4237name = "windows-targets"
4238version = "0.52.6"
4239source = "registry+https://github.com/rust-lang/crates.io-index"
4240checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
4241dependencies = [
4242 "windows_aarch64_gnullvm",
4243 "windows_aarch64_msvc",
4244 "windows_i686_gnu",
4245 "windows_i686_gnullvm",
4246 "windows_i686_msvc",
4247 "windows_x86_64_gnu",
4248 "windows_x86_64_gnullvm",
4249 "windows_x86_64_msvc",
4250]
4251
4252[[package]]
4253name = "windows-threading"
4254version = "0.2.1"
4255source = "registry+https://github.com/rust-lang/crates.io-index"
4256checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
4257dependencies = [
4258 "windows-link",
4259]
4260
4261[[package]]
4262name = "windows_aarch64_gnullvm"
4263version = "0.52.6"
4264source = "registry+https://github.com/rust-lang/crates.io-index"
4265checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
4266
4267[[package]]
4268name = "windows_aarch64_msvc"
4269version = "0.52.6"
4270source = "registry+https://github.com/rust-lang/crates.io-index"
4271checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
4272
4273[[package]]
4274name = "windows_i686_gnu"
4275version = "0.52.6"
4276source = "registry+https://github.com/rust-lang/crates.io-index"
4277checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
4278
4279[[package]]
4280name = "windows_i686_gnullvm"
4281version = "0.52.6"
4282source = "registry+https://github.com/rust-lang/crates.io-index"
4283checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
4284
4285[[package]]
4286name = "windows_i686_msvc"
4287version = "0.52.6"
4288source = "registry+https://github.com/rust-lang/crates.io-index"
4289checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
4290
4291[[package]]
4292name = "windows_x86_64_gnu"
4293version = "0.52.6"
4294source = "registry+https://github.com/rust-lang/crates.io-index"
4295checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
4296
4297[[package]]
4298name = "windows_x86_64_gnullvm"
4299version = "0.52.6"
4300source = "registry+https://github.com/rust-lang/crates.io-index"
4301checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
4302
4303[[package]]
4304name = "windows_x86_64_msvc"
4305version = "0.52.6"
4306source = "registry+https://github.com/rust-lang/crates.io-index"
4307checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
4308
4309[[package]]
4310name = "winit"
4311version = "0.30.13"
4312source = "registry+https://github.com/rust-lang/crates.io-index"
4313checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
4314dependencies = [
4315 "ahash",
4316 "android-activity",
4317 "atomic-waker",
4318 "bitflags 2.13.2",
4319 "block2 0.5.1",
4320 "bytemuck",
4321 "calloop",
4322 "cfg_aliases",
4323 "concurrent-queue",
4324 "core-foundation",
4325 "core-graphics",
4326 "cursor-icon",
4327 "dpi",
4328 "js-sys",
4329 "libc",
4330 "memmap2",
4331 "ndk",
4332 "objc2 0.5.3",
4333 "objc2-app-kit 0.2.2",
4334 "objc2-foundation 0.2.2",
4335 "objc2-ui-kit",
4336 "orbclient",
4337 "percent-encoding",
4338 "pin-project",
4339 "raw-window-handle",
4340 "redox_syscall 0.4.1",
4341 "rustix 0.38.44",
4342 "sctk-adwaita",
4343 "serde",
4344 "smithay-client-toolkit",
4345 "smol_str",
4346 "tracing",
4347 "unicode-segmentation",
4348 "wasm-bindgen",
4349 "wasm-bindgen-futures",
4350 "wayland-backend",
4351 "wayland-client",
4352 "wayland-protocols",
4353 "wayland-protocols-plasma",
4354 "web-sys",
4355 "web-time",
4356 "windows-sys 0.52.0",
4357 "x11-dl",
4358 "x11rb",
4359 "xkbcommon-dl",
4360]
4361
4362[[package]]
4363name = "winnow"
4364version = "1.0.5"
4365source = "registry+https://github.com/rust-lang/crates.io-index"
4366checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
4367dependencies = [
4368 "memchr",
4369]
4370
4371[[package]]
4372name = "winsafe"
4373version = "0.0.19"
4374source = "registry+https://github.com/rust-lang/crates.io-index"
4375checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
4376
4377[[package]]
4378name = "wl-clipboard-rs"
4379version = "0.9.5"
4380source = "registry+https://github.com/rust-lang/crates.io-index"
4381checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848"
4382dependencies = [
4383 "libc",
4384 "log",
4385 "os_pipe",
4386 "rustix 1.1.6",
4387 "thiserror 2.0.21",
4388 "tree_magic_mini",
4389 "wayland-backend",
4390 "wayland-client",
4391 "wayland-protocols",
4392 "wayland-protocols-wlr",
4393]
4394
4395[[package]]
4396name = "wuff"
4397version = "0.2.10"
4398source = "registry+https://github.com/rust-lang/crates.io-index"
4399checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd"
4400dependencies = [
4401 "brotli-decompressor",
4402 "bytes",
4403]
4404
4405[[package]]
4406name = "x11-dl"
4407version = "2.21.0"
4408source = "registry+https://github.com/rust-lang/crates.io-index"
4409checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
4410dependencies = [
4411 "libc",
4412 "once_cell",
4413 "pkg-config",
4414]
4415
4416[[package]]
4417name = "x11rb"
4418version = "0.13.2"
4419source = "registry+https://github.com/rust-lang/crates.io-index"
4420checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
4421dependencies = [
4422 "as-raw-xcb-connection",
4423 "gethostname",
4424 "libc",
4425 "libloading",
4426 "once_cell",
4427 "rustix 1.1.6",
4428 "x11rb-protocol",
4429]
4430
4431[[package]]
4432name = "x11rb-protocol"
4433version = "0.13.2"
4434source = "registry+https://github.com/rust-lang/crates.io-index"
4435checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
4436
4437[[package]]
4438name = "xcursor"
4439version = "0.3.11"
4440source = "registry+https://github.com/rust-lang/crates.io-index"
4441checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
4442
4443[[package]]
4444name = "xkbcommon-dl"
4445version = "0.4.2"
4446source = "registry+https://github.com/rust-lang/crates.io-index"
4447checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"
4448dependencies = [
4449 "bitflags 2.13.2",
4450 "dlib",
4451 "log",
4452 "once_cell",
4453 "xkeysym",
4454]
4455
4456[[package]]
4457name = "xkeysym"
4458version = "0.2.1"
4459source = "registry+https://github.com/rust-lang/crates.io-index"
4460checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
4461
4462[[package]]
4463name = "xml-rs"
4464version = "0.8.29"
4465source = "registry+https://github.com/rust-lang/crates.io-index"
4466checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
4467
4468[[package]]
4469name = "xmlwriter"
4470version = "0.1.0"
4471source = "registry+https://github.com/rust-lang/crates.io-index"
4472checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
4473
4474[[package]]
4475name = "yoke"
4476version = "0.8.4"
4477source = "registry+https://github.com/rust-lang/crates.io-index"
4478checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
4479dependencies = [
4480 "stable_deref_trait",
4481 "yoke-derive",
4482 "zerofrom",
4483]
4484
4485[[package]]
4486name = "yoke-derive"
4487version = "0.8.4"
4488source = "registry+https://github.com/rust-lang/crates.io-index"
4489checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
4490dependencies = [
4491 "proc-macro2",
4492 "quote",
4493 "syn 3.0.10",
4494 "synstructure",
4495]
4496
4497[[package]]
4498name = "zbus"
4499version = "5.19.0"
4500source = "registry+https://github.com/rust-lang/crates.io-index"
4501checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
4502dependencies = [
4503 "async-broadcast",
4504 "async-executor",
4505 "async-io",
4506 "async-lock",
4507 "async-process",
4508 "async-recursion",
4509 "async-task",
4510 "async-trait",
4511 "blocking",
4512 "enumflags2",
4513 "event-listener",
4514 "futures-core",
4515 "futures-lite",
4516 "hex",
4517 "libc",
4518 "ordered-stream",
4519 "rustix 1.1.6",
4520 "serde",
4521 "serde_repr",
4522 "tracing",
4523 "uds_windows",
4524 "uuid",
4525 "windows-sys 0.61.2",
4526 "winnow",
4527 "zbus_macros",
4528 "zbus_names",
4529 "zvariant",
4530]
4531
4532[[package]]
4533name = "zbus_macros"
4534version = "5.19.0"
4535source = "registry+https://github.com/rust-lang/crates.io-index"
4536checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
4537dependencies = [
4538 "proc-macro-crate",
4539 "proc-macro2",
4540 "quote",
4541 "syn 3.0.10",
4542 "zbus_names",
4543 "zvariant",
4544 "zvariant_utils",
4545]
4546
4547[[package]]
4548name = "zbus_names"
4549version = "4.3.5"
4550source = "registry+https://github.com/rust-lang/crates.io-index"
4551checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
4552dependencies = [
4553 "serde",
4554 "winnow",
4555 "zvariant",
4556]
4557
4558[[package]]
4559name = "zcheapstr"
4560version = "1.4.0"
4561source = "registry+https://github.com/rust-lang/crates.io-index"
4562checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907"
4563dependencies = [
4564 "serde",
4565]
4566
4567[[package]]
4568name = "zeno"
4569version = "0.3.3"
4570source = "registry+https://github.com/rust-lang/crates.io-index"
4571checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524"
4572
4573[[package]]
4574name = "zerocopy"
4575version = "0.8.66"
4576source = "registry+https://github.com/rust-lang/crates.io-index"
4577checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
4578dependencies = [
4579 "zerocopy-derive",
4580]
4581
4582[[package]]
4583name = "zerocopy-derive"
4584version = "0.8.66"
4585source = "registry+https://github.com/rust-lang/crates.io-index"
4586checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
4587dependencies = [
4588 "proc-macro2",
4589 "quote",
4590 "syn 2.0.119",
4591]
4592
4593[[package]]
4594name = "zerofrom"
4595version = "0.1.8"
4596source = "registry+https://github.com/rust-lang/crates.io-index"
4597checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
4598dependencies = [
4599 "zerofrom-derive",
4600]
4601
4602[[package]]
4603name = "zerofrom-derive"
4604version = "0.1.8"
4605source = "registry+https://github.com/rust-lang/crates.io-index"
4606checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
4607dependencies = [
4608 "proc-macro2",
4609 "quote",
4610 "syn 3.0.10",
4611 "synstructure",
4612]
4613
4614[[package]]
4615name = "zlib-rs"
4616version = "0.6.9"
4617source = "registry+https://github.com/rust-lang/crates.io-index"
4618checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
4619
4620[[package]]
4621name = "zmij"
4622version = "1.0.23"
4623source = "registry+https://github.com/rust-lang/crates.io-index"
4624checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
4625
4626[[package]]
4627name = "zune-core"
4628version = "0.5.4"
4629source = "registry+https://github.com/rust-lang/crates.io-index"
4630checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18"
4631
4632[[package]]
4633name = "zune-inflate"
4634version = "0.2.54"
4635source = "registry+https://github.com/rust-lang/crates.io-index"
4636checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
4637dependencies = [
4638 "simd-adler32",
4639]
4640
4641[[package]]
4642name = "zune-jpeg"
4643version = "0.5.15"
4644source = "registry+https://github.com/rust-lang/crates.io-index"
4645checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
4646dependencies = [
4647 "zune-core",
4648]
4649
4650[[package]]
4651name = "zvariant"
4652version = "5.15.1"
4653source = "registry+https://github.com/rust-lang/crates.io-index"
4654checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
4655dependencies = [
4656 "endi",
4657 "enumflags2",
4658 "serde",
4659 "winnow",
4660 "zcheapstr",
4661 "zvariant_derive",
4662 "zvariant_utils",
4663]
4664
4665[[package]]
4666name = "zvariant_derive"
4667version = "5.15.1"
4668source = "registry+https://github.com/rust-lang/crates.io-index"
4669checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
4670dependencies = [
4671 "proc-macro-crate",
4672 "proc-macro2",
4673 "quote",
4674 "syn 3.0.10",
4675 "zvariant_utils",
4676]
4677
4678[[package]]
4679name = "zvariant_utils"
4680version = "4.2.0"
4681source = "registry+https://github.com/rust-lang/crates.io-index"
4682checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
4683dependencies = [
4684 "proc-macro2",
4685 "quote",
4686 "serde",
4687 "syn 3.0.10",
4688 "winnow",
4689]
Cargo.toml created+57
...@@ -0,0 +1,57 @@
1[workspace]
2members = [
3 "crates/model",
4 "crates/engine",
5 "crates/flow",
6 "crates/spline",
7 "crates/viewer",
8 "crates/studio",
9]
10resolver = "3"
11
12[workspace.package]
13edition = "2024"
14version = "0.1.0"
15publish = false
16
17[workspace.dependencies]
18# Local workspace crates
19model = { path = "crates/model" }
20engine = { path = "crates/engine" }
21flow = { path = "crates/flow" }
22spline = { path = "crates/spline" }
23viewer = { path = "crates/viewer" }
24
25# Knife toolkit (sibling checkout)
26draw = { path = "../the-knife/knife/draw" }
27ui = { path = "../the-knife/knife/ui" }
28dock = { path = "../the-knife/knife/dock" }
29state = { path = "../the-knife/knife/state" }
30text = { path = "../the-knife/knife/text" }
31theme = { path = "../the-knife/knife/theme" }
32
33# Shared versions aligned with the-knife
34accesskit = "0.25.1"
35accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] }
36bytemuck = { version = "1.25", features = ["derive"] }
37image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] }
38mlua = { version = "0.10", features = ["lua54", "vendored"] }
39png = "0.18"
40pollster = "0.4"
41wgpu = "30.0.1"
42winit = "0.30.13"
43zeno = "0.3.3"
44
45objc2 = "0.6.5"
46objc2-app-kit = { version = "0.3.2", default-features = false }
47objc2-foundation = { version = "0.3.2", default-features = false }
48
49[patch.crates-io]
50accesskit_consumer = { path = "../the-knife/knife/vendor/accesskit_consumer" }
51
52[profile.dev]
53debug = "line-tables-only"
54
55[profile.dev.package."*"]
56opt-level = 3
57debug = false
KNOWN_GAPS.md created+42
...@@ -0,0 +1,42 @@
1# Known Gaps & Roadmap
2
3Tracked rendering and architecture gaps compared to Blackmagic Fusion Studio 21.1.
4Items listed here are **tracked bugs / missing subsystems**, never permanent exclusions.
5
6---
7
8## 1. Cryptomatte (`Fuse.Cryptomatte` — e.g. `01_intro.comp` human character matte)
9- **Status:** Tracked known gap (not an intentional exclusion).
10- **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.
11- **Planned fix:** Add multi-channel EXR Cryptomatte layer decoding (`exr` crate already in workspace), parse `cryptomatte/<hash>/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.
12
13## 2. 3D Particle System (`pEmitter`, `pRender`, `pPointForce`)
14- **Status:** Tracked missing subsystem (currently reported in `unsupported` on `01_intro.comp`).
15- **Symptom:** Particle layers driven by `pEmitter` / `pPointForce` / `pRender` are skipped.
16- **Planned fix:** Deterministic frame-stepped particle simulator (seeded per-frame/cached state) feeding into `Scene3D` billboard/point-sprite instancing inside `Renderer3D` / `pRender`.
17
18## 3. Optical Flow & Retime Vectors (`Dimension.OpticalFlow`, `OpticalFlow`)
19- **Status:** Tracked missing subsystem (reported in `unsupported` on `01_intro.comp`).
20- **Symptom:** Motion-vector-interpolated retiming falls back to nearest/frame-blended source frames.
21- **Planned fix:** GPU dense optical-flow pass (hierarchical Lucas-Kanade / TV-L1 compute shader) writing forward/backward motion vectors for downstream `TimeStretcher` / `VectorMotionBlur`.
22
23## 4. Project-Defined Bit Depth (`DepthFull` / `DepthInteractive` / `ChangeDepth`)
24- **Status:** Planned engine upgrade.
25- **Current behavior:** Intermediate render targets currently use `Rgba8Unorm` (8-bit) in both `HiQ` and `Fast` modes.
26- **Target design (per user preference):**
27 - **`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`.
28 - **`Fast` mode:** Collapse working targets to `Rgba8Unorm` (and downsampled blurs / capped `XGlow` octaves) for maximum interactive throughput.
29
30## 5. Video Decode Backend (`AVFoundation` / `VideoToolbox` + `ffmpeg` fallback)
31- **Status:** Planned media layer upgrade.
32- **Current behavior:** Video clips decode via `ffmpeg` subprocesses with LRU frame caching.
33- **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.
34
35## 6. Procedural `FastNoise` Internal Permutation Seed
36- **Status:** Known inherent difference vs closed-source Fusion noise table.
37- **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`.
38
39## 7. Minor Tool Edge Cases Remaining
40- `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).
41- `Displace` `Type = 0` (`Radial`) `LightPower` specular/bump lighting exact angle & color model (`0.7% MAE` vs `0.1%` without `LightPower`).
42- `Glow` tool (`Glow = 0.583, GlowSize = 12`) slight Gaussian tail roll-off (`1.3% MAE`; `SoftGlow` is `0.0%–0.8%`).
crates/engine/Cargo.toml created+21
...@@ -0,0 +1,21 @@
1[package]
2name = "engine"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[[bin]]
8name = "render-check"
9path = "src/bin/render_check.rs"
10
11[dependencies]
12bytemuck.workspace = true
13exr = "1.74"
14image.workspace = true
15model.workspace = true
16png.workspace = true
17pollster.workspace = true
18text.workspace = true
19theme.workspace = true
20wgpu.workspace = true
21zeno.workspace = true
crates/engine/src/bin/render_check.rs created+356
...@@ -0,0 +1,356 @@
1//! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`.
2
3use engine::{CacheMode, Engine};
4use model::Comp;
5use std::collections::HashMap;
6use std::fs::File;
7use std::path::{Path, PathBuf};
8use std::time::Instant;
9
10fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64), Box<dyn std::error::Error>> {
11 let mut ref_img = image::open(ref_path)?.to_rgba8();
12 if [ref_img.width(), ref_img.height()] != tex_size {
13 ref_img = image::imageops::resize(
14 &ref_img,
15 tex_size[0],
16 tex_size[1],
17 image::imageops::FilterType::Triangle,
18 );
19 }
20 let rraw = ref_img.into_raw();
21 let mut sum_abs = 0u64;
22 let mut sum_sq = 0u64;
23 let n = (tex_size[0] as u64) * (tex_size[1] as u64) * 3;
24 for (a, b) in pixels.chunks_exact(4).zip(rraw.chunks_exact(4)) {
25 for c in 0..3 {
26 let d = (a[c] as i32 - b[c] as i32).unsigned_abs() as u64;
27 sum_abs += d;
28 sum_sq += d * d;
29 }
30 }
31 let mae = sum_abs as f64 / n as f64;
32 let rmse = (sum_sq as f64 / n as f64).sqrt();
33 Ok((mae, rmse))
34}
35
36fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
37 if let Some(parent) = path.parent() {
38 std::fs::create_dir_all(parent)?;
39 }
40 let mut enc = png::Encoder::new(File::create(path)?, size[0], size[1]);
41 enc.set_color(png::ColorType::Rgba);
42 enc.set_depth(png::BitDepth::Eight);
43 enc.write_header()?.write_image_data(pixels)?;
44 Ok(())
45}
46
47fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box<dyn std::error::Error>> {
48 let text = std::fs::read_to_string(manifest_path)?;
49 let mut engine = Engine::new_headless()?;
50 engine.hiq = hiq;
51 let mut comps: HashMap<PathBuf, Comp> = HashMap::new();
52 let mut passed = 0usize;
53 let mut failed = 0usize;
54
55 eprintln!(
56 "Quality mode: {} | Manifest: {}",
57 if hiq { "HiQ (bar-for-bar)" } else { "Fast (perfmaxxed)" },
58 manifest_path.display()
59 );
60 eprintln!(
61 "{:<6} {:<20} {:>6} {:>7} {:>7} {:>8} {:>8} {:>7} {}",
62 "STATUS", "CASE", "FRAME", "MAE%", "RMSE", "WARM_MS", "BUST_MS", "VRAM", "UNSUPPORTED"
63 );
64 eprintln!("{}", "-".repeat(94));
65
66 for (lineno, raw) in text.lines().enumerate() {
67 let line = raw.trim();
68 if line.is_empty() || line.starts_with('#') {
69 continue;
70 }
71 let cols: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
72 if cols.len() < 6 {
73 return Err(format!("suite line {}: expected 6 pipe-separated columns", lineno + 1).into());
74 }
75 let case_name = cols[0];
76 let comp_path = PathBuf::from(cols[1]);
77 let frame: f64 = cols[2].parse()?;
78 let ref_path = PathBuf::from(cols[3]);
79 let max_mae_pct: f64 = cols[4].parse()?;
80 let max_bust_ms: f64 = cols[5].parse()?;
81 let node_opt = cols.get(6).copied().filter(|s| !s.is_empty() && *s != "-");
82
83 if !comps.contains_key(&comp_path) {
84 comps.insert(comp_path.clone(), Comp::from_fusion_file(&comp_path)?);
85 }
86 let comp = &comps[&comp_path];
87 let target = match node_opt {
88 Some(n) => comp.find_node(n).ok_or_else(|| format!("{case_name}: no node {n}"))?,
89 None => comp.default_output_node().ok_or("comp has no nodes")?,
90 };
91
92 engine.set_cache_mode(CacheMode::Enabled);
93 let (tex, cold) = engine.evaluate(comp, target, frame);
94 let (_, warm) = engine.evaluate(comp, target, frame);
95 engine.bust_gpu_cache();
96 let (_, bust) = engine.evaluate(comp, target, frame);
97
98 let pixels = engine.readback_rgba(&tex)?;
99 let (mae, rmse) = compute_diff(&pixels, tex.size, &ref_path)?;
100 let mae_pct = mae / 2.55;
101
102 let ok = mae_pct <= max_mae_pct && bust.eval_ms <= max_bust_ms;
103 if ok {
104 passed += 1;
105 } else {
106 failed += 1;
107 }
108 eprintln!(
109 "{:<6} {:<20} {:>6} {:>6.2}% {:>7.2} {:>7.2}ms {:>7.2}ms {:>5.0}MB {:?}",
110 if ok { "PASS" } else { "FAIL" },
111 case_name,
112 frame as i64,
113 mae_pct,
114 rmse,
115 warm.eval_ms,
116 bust.eval_ms,
117 cold.cached_vram_mb,
118 cold.unsupported_nodes,
119 );
120 if !ok {
121 eprintln!(
122 " budget: MAE <= {max_mae_pct:.2}% (got {mae_pct:.2}%), bust <= {max_bust_ms:.1}ms (got {:.1}ms)",
123 bust.eval_ms
124 );
125 }
126 }
127
128 eprintln!("{}", "-".repeat(94));
129 eprintln!("Suite summary: {passed} passed, {failed} failed");
130 if failed > 0 {
131 std::process::exit(1);
132 }
133 Ok(())
134}
135
136fn run_batch_render(
137 comp_path: &Path,
138 range_str: &str,
139 out_dir: &Path,
140 node_name: Option<&str>,
141 proxy_scale: u32,
142) -> Result<(), Box<dyn std::error::Error>> {
143 let comp = Comp::from_fusion_file(comp_path)?;
144 let (start, end) = if let Some((a, b)) = range_str.split_once("..") {
145 (a.parse::<i64>()?, b.parse::<i64>()?)
146 } else {
147 (comp.render_range[0], comp.render_range[1])
148 };
149 let target = match node_name {
150 Some(n) => comp.find_node(n).ok_or_else(|| format!("no such node {n}"))?,
151 None => comp.default_output_node().ok_or("comp has no nodes")?,
152 };
153 std::fs::create_dir_all(out_dir)?;
154 let mut engine = Engine::new_headless()?;
155 engine.proxy_scale = proxy_scale;
156
157 let total = (end - start + 1).max(0) as usize;
158 let t_all = Instant::now();
159 eprintln!(
160 "Rendering {} ({}x{}, proxy 1:{}) node={} frames {}..{} ({total} frames) -> {}",
161 comp.name,
162 comp.width,
163 comp.height,
164 proxy_scale,
165 comp.node(target).name,
166 start,
167 end,
168 out_dir.display()
169 );
170 for (idx, f) in (start..=end).enumerate() {
171 let (tex, stats) = engine.evaluate(&comp, target, f as f64);
172 let pixels = engine.readback_rgba(&tex)?;
173 let out_file = out_dir.join(format!("{f:04}.png"));
174 write_png(&out_file, tex.size, &pixels)?;
175 if idx == 0 || (idx + 1) % 10 == 0 || idx + 1 == total {
176 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
177 let fps = (idx + 1) as f64 / elapsed;
178 eprintln!(
179 " [{:>4}/{total}] f{f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
180 idx + 1,
181 stats.eval_ms,
182 stats.cached_vram_mb,
183 stats.unsupported_nodes,
184 );
185 }
186 }
187 eprintln!(
188 "Finished {total} frames in {:.2}s ({:.1} fps)",
189 t_all.elapsed().as_secs_f64(),
190 total as f64 / t_all.elapsed().as_secs_f64().max(1e-6)
191 );
192 Ok(())
193}
194
195fn main() -> Result<(), Box<dyn std::error::Error>> {
196 let args: Vec<String> = std::env::args().collect();
197 if args.len() >= 3 && args[1] == "--suite" {
198 let hiq = !args.iter().any(|a| a == "--fast");
199 return run_suite(Path::new(&args[2]), hiq);
200 }
201 if args.len() < 3 {
202 eprintln!(
203 "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check --suite <private/suite.txt> [--fast]"
204 );
205 std::process::exit(2);
206 }
207
208 let comp_path = PathBuf::from(&args[1]);
209 if args[2] == "--render" {
210 let mut range = String::new();
211 let mut out_dir: Option<PathBuf> = None;
212 let mut node_name: Option<String> = None;
213 let mut proxy_scale = 1u32;
214 let mut i = 2;
215 while i < args.len() {
216 match args[i].as_str() {
217 "--render" if i + 1 < args.len() => {
218 range = args[i + 1].clone();
219 i += 2;
220 }
221 "--out-dir" if i + 1 < args.len() => {
222 out_dir = Some(PathBuf::from(&args[i + 1]));
223 i += 2;
224 }
225 "--node" if i + 1 < args.len() => {
226 node_name = Some(args[i + 1].clone());
227 i += 2;
228 }
229 "--proxy" if i + 1 < args.len() => {
230 proxy_scale = args[i + 1].parse().unwrap_or(1).max(1);
231 i += 2;
232 }
233 other => {
234 eprintln!("unexpected argument '{other}'");
235 std::process::exit(2);
236 }
237 }
238 }
239 let out_dir = out_dir.ok_or("--out-dir is required with --render")?;
240 return run_batch_render(&comp_path, &range, &out_dir, node_name.as_deref(), proxy_scale);
241 }
242
243 let frame: f64 = args[2].parse()?;
244 let mut out_path: Option<PathBuf> = None;
245 let mut ref_path: Option<PathBuf> = None;
246 let mut node_name: Option<String> = None;
247 let mut proxy_scale: u32 = 1;
248 let mut hiq = true;
249 let mut bench = false;
250 let mut i = 3;
251 while i < args.len() {
252 match args[i].as_str() {
253 "--out" if i + 1 < args.len() => {
254 out_path = Some(PathBuf::from(&args[i + 1]));
255 i += 2;
256 }
257 "--ref" if i + 1 < args.len() => {
258 ref_path = Some(PathBuf::from(&args[i + 1]));
259 i += 2;
260 }
261 "--node" if i + 1 < args.len() => {
262 node_name = Some(args[i + 1].clone());
263 i += 2;
264 }
265 "--proxy" if i + 1 < args.len() => {
266 proxy_scale = args[i + 1].parse().unwrap_or(1).max(1);
267 i += 2;
268 }
269 "--fast" => {
270 hiq = false;
271 i += 1;
272 }
273 "--bench" => {
274 bench = true;
275 i += 1;
276 }
277 other => {
278 eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --fast, --bench)");
279 std::process::exit(2);
280 }
281 }
282 }
283
284 let comp = Comp::from_fusion_file(&comp_path)?;
285 let target = match node_name {
286 Some(n) => comp.find_node(&n).ok_or_else(|| format!("no such node {n}"))?,
287 None => comp.default_output_node().ok_or("comp has no nodes")?,
288 };
289 eprintln!(
290 "Loaded {} ({}x{}, proxy 1:{}, {}, {} nodes, {} splines) -> viewing {} at frame {frame}",
291 comp.name,
292 comp.width,
293 comp.height,
294 proxy_scale,
295 if hiq { "HiQ" } else { "Fast" },
296 comp.nodes.len(),
297 comp.splines.len(),
298 comp.node(target).name
299 );
300
301 let mut engine = Engine::new_headless()?;
302 engine.proxy_scale = proxy_scale;
303 engine.hiq = hiq;
304
305 let (tex, cold) = engine.evaluate(&comp, target, frame);
306 eprintln!(
307 "[cold] {:.2} ms | eval={} hits={} misses={} loads={} pruned={} vram={:.1}MB unsupported={:?}",
308 cold.eval_ms,
309 cold.nodes_evaluated,
310 cold.cache_hits,
311 cold.cache_misses,
312 cold.source_loads,
313 cold.pruned_branches,
314 cold.cached_vram_mb,
315 cold.unsupported_nodes
316 );
317
318 if bench {
319 let (_, warm) = engine.evaluate(&comp, target, frame);
320 eprintln!(
321 "[warm] {:.2} ms | eval={} hits={} misses={}",
322 warm.eval_ms, warm.nodes_evaluated, warm.cache_hits, warm.cache_misses
323 );
324
325 engine.bust_gpu_cache();
326 let (_, gpu_bust) = engine.evaluate(&comp, target, frame);
327 eprintln!(
328 "[bust] {:.2} ms | eval={} hits={} misses={} loads={}",
329 gpu_bust.eval_ms, gpu_bust.nodes_evaluated, gpu_bust.cache_hits, gpu_bust.cache_misses, gpu_bust.source_loads
330 );
331
332 engine.set_cache_mode(CacheMode::Bypass);
333 let (_, bypass) = engine.evaluate(&comp, target, frame);
334 eprintln!(
335 "[bypass] {:.2} ms | eval={} pruned={}",
336 bypass.eval_ms, bypass.nodes_evaluated, bypass.pruned_branches
337 );
338 }
339
340 let pixels = engine.readback_rgba(&tex)?;
341 if let Some(out_path) = out_path {
342 write_png(&out_path, tex.size, &pixels)?;
343 eprintln!("Wrote {} ({}x{})", out_path.display(), tex.size[0], tex.size[1]);
344 }
345 if let Some(rp) = ref_path {
346 let (mae, rmse) = compute_diff(&pixels, tex.size, &rp)?;
347 eprintln!(
348 "Diff vs {} ({}x{}): MAE={mae:.2}/255 ({:.1}%), RMSE={rmse:.2}/255",
349 rp.display(),
350 tex.size[0],
351 tex.size[1],
352 mae / 2.55
353 );
354 }
355 Ok(())
356}
crates/engine/src/cache.rs created+210
...@@ -0,0 +1,210 @@
1//! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction,
2//! and surgical cache-busting modes for profiling and playback verification.
3
4use model::NodeId;
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum CacheMode {
10 /// Content-hashed cache across all nodes up to `budget_bytes`.
11 Enabled,
12 /// Forces full re-evaluation every frame (zero reads/writes to node cache).
13 Bypass,
14}
15
16#[derive(Clone, Debug)]
17pub struct CachedTexture {
18 pub texture: Arc<wgpu::Texture>,
19 pub view: Arc<wgpu::TextureView>,
20 /// Actual allocated GPU texture dimensions `[w, h]`.
21 pub size: [u32; 2],
22 /// Domain of Definition (DoD) top-left offset in logical canvas pixels (`[0, 0]` for standard frames).
23 pub origin: [i32; 2],
24 /// Logical frame canvas dimensions (e.g. `[1920, 1080]`, matching `size` when DoD == canvas).
25 pub canvas_size: [u32; 2],
26 pub content_hash: u64,
27 pub bytes: u64,
28}
29
30impl CachedTexture {
31 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {
32 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)
33 }
34
35 pub fn from_texture_dod(
36 texture: wgpu::Texture,
37 size: [u32; 2],
38 origin: [i32; 2],
39 canvas_size: [u32; 2],
40 content_hash: u64,
41 ) -> Self {
42 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
43 let bytes = u64::from(size[0]) * u64::from(size[1]) * 4;
44 Self {
45 texture: Arc::new(texture),
46 view: Arc::new(view),
47 size,
48 origin,
49 canvas_size,
50 content_hash,
51 bytes,
52 }
53 }
54
55 pub fn has_dod(&self) -> bool {
56 self.origin != [0, 0] || self.size != self.canvas_size
57 }
58}
59
60#[derive(Clone, Debug, Default)]
61pub struct EvalStats {
62 pub eval_ms: f64,
63 pub nodes_evaluated: usize,
64 pub cache_hits: usize,
65 pub cache_misses: usize,
66 pub source_loads: usize,
67 pub pruned_branches: usize,
68 pub cached_entries: usize,
69 pub cached_vram_mb: f64,
70 pub media_entries: usize,
71 pub media_mb: f64,
72 pub unsupported_nodes: Vec<String>,
73}
74
75struct Entry {
76 tex: CachedTexture,
77 last_used: u64,
78 producers: HashSet<NodeId>,
79 frames: HashSet<i64>,
80}
81
82pub struct NodeCache {
83 pub mode: CacheMode,
84 pub budget_bytes: u64,
85 entries: HashMap<u64, Entry>,
86 total_bytes: u64,
87 tick: u64,
88 /// Monotonic salt bumped when busting GPU cache globally.
89 pub gpu_salt: u64,
90 /// Per-node salt bumped when surgically busting a subtree.
91 node_salts: HashMap<NodeId, u64>,
92}
93
94impl NodeCache {
95 pub fn new(budget_mb: u64) -> Self {
96 Self {
97 mode: CacheMode::Enabled,
98 budget_bytes: budget_mb * 1024 * 1024,
99 entries: HashMap::new(),
100 total_bytes: 0,
101 tick: 0,
102 gpu_salt: 0,
103 node_salts: HashMap::new(),
104 }
105 }
106
107 pub fn node_salt(&self, id: NodeId) -> u64 {
108 self.node_salts.get(&id).copied().unwrap_or(0)
109 }
110
111 pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> {
112 if self.mode == CacheMode::Bypass {
113 return None;
114 }
115 self.tick += 1;
116 let e = self.entries.get_mut(&key)?;
117 e.last_used = self.tick;
118 e.producers.insert(node);
119 e.frames.insert(frame);
120 Some(e.tex.clone())
121 }
122
123 pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) {
124 if self.mode == CacheMode::Bypass {
125 return;
126 }
127 self.tick += 1;
128 if let Some(old) = self.entries.remove(&key) {
129 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);
130 }
131 self.total_bytes += tex.bytes;
132 let mut producers = HashSet::new();
133 producers.insert(node);
134 let mut frames = HashSet::new();
135 frames.insert(frame);
136 self.entries.insert(
137 key,
138 Entry {
139 tex,
140 last_used: self.tick,
141 producers,
142 frames,
143 },
144 );
145 self.evict_over_budget();
146 }
147
148 fn evict_over_budget(&mut self) {
149 while self.total_bytes > self.budget_bytes && self.entries.len() > 2 {
150 let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used)
151 else {
152 break;
153 };
154 if let Some(removed) = self.entries.remove(&oldest_key) {
155 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
156 }
157 }
158 }
159
160 /// Wipes every cached GPU node texture and bumps global salt.
161 pub fn bust_all(&mut self) {
162 self.entries.clear();
163 self.total_bytes = 0;
164 self.gpu_salt += 1;
165 }
166
167 /// Removes cached entries produced for a specific integer frame.
168 pub fn bust_frame(&mut self, frame: i64) -> usize {
169 let keys: Vec<u64> = self
170 .entries
171 .iter()
172 .filter(|(_, e)| e.frames.contains(&frame))
173 .map(|(k, _)| *k)
174 .collect();
175 let count = keys.len();
176 for k in keys {
177 if let Some(removed) = self.entries.remove(&k) {
178 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
179 }
180 }
181 count
182 }
183
184 /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream
185 /// via Merkle hashing!) and evicts its existing entries.
186 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
187 *self.node_salts.entry(node).or_insert(0) += 1;
188 let keys: Vec<u64> = self
189 .entries
190 .iter()
191 .filter(|(_, e)| e.producers.contains(&node))
192 .map(|(k, _)| *k)
193 .collect();
194 let count = keys.len();
195 for k in keys {
196 if let Some(removed) = self.entries.remove(&k) {
197 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
198 }
199 }
200 count
201 }
202
203 pub fn entry_count(&self) -> usize {
204 self.entries.len()
205 }
206
207 pub fn total_mb(&self) -> f64 {
208 self.total_bytes as f64 / (1024.0 * 1024.0)
209 }
210}
crates/engine/src/eval.rs created+3112
...@@ -0,0 +1,3112 @@
1//! Headless `wgpu` 2D compositor evaluator with Merkle content-hash caching,
2//! branch pruning, and surgical cache-busting.
3
4use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache};
5use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
6use bytemuck::{Pod, Zeroable};
7use model::{Comp, ExprEngine, Node, NodeId, ParamValue, default_main_input_port};
8use std::collections::{HashMap, HashSet};
9use std::collections::hash_map::DefaultHasher;
10use std::hash::{Hash, Hasher};
11use std::time::Instant;
12
13#[repr(C)]
14#[derive(Clone, Copy, Pod, Zeroable)]
15struct UniformParams {
16 p: [[f32; 4]; 16],
17}
18
19impl Default for UniformParams {
20 fn default() -> Self {
21 Self { p: [[0.0; 4]; 16] }
22 }
23}
24
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct DisplaySettings {
27 pub exposure: f32, // stops (0.0 = 1x)
28 pub gamma: f32, // default 1.0
29 pub channel: u32, // 0=RGBA, 1=R, 2=G, 3=B, 4=A
30 pub checker_bg: bool,
31 /// False (default) = exact nearest-neighbor pixels ("raw truth" when zooming in);
32 /// True = bilinear "Smooth Resize".
33 pub smooth_resize: bool,
34 /// Visible normalized UV rectangle `[u0, v0, u1, v1]` sampled into the viewer output texture.
35 pub uv_rect: [f32; 4],
36}
37
38impl Default for DisplaySettings {
39 fn default() -> Self {
40 Self {
41 exposure: 0.0,
42 gamma: 1.0,
43 channel: 0,
44 checker_bg: true,
45 smooth_resize: false,
46 uv_rect: [0.0, 0.0, 1.0, 1.0],
47 }
48 }
49}
50
51struct Pipelines {
52 bgl: wgpu::BindGroupLayout,
53 sampler: wgpu::Sampler,
54 bg: wgpu::ComputePipeline,
55 merge: wgpu::ComputePipeline,
56 transform: wgpu::ComputePipeline,
57 bc: wgpu::ComputePipeline,
58 cc: wgpu::ComputePipeline,
59 color_gain: wgpu::ComputePipeline,
60 luma_key: wgpu::ComputePipeline,
61 blur: wgpu::ComputePipeline,
62 dir_blur: wgpu::ComputePipeline,
63 fast_noise: wgpu::ComputePipeline,
64 displace: wgpu::ComputePipeline,
65 mask_shape: wgpu::ComputePipeline,
66 mask_combine: wgpu::ComputePipeline,
67 mask_apply: wgpu::ComputePipeline,
68 colorize: wgpu::ComputePipeline,
69 color_curves: wgpu::ComputePipeline,
70 xf_chroma: wgpu::ComputePipeline,
71 gamut_convert: wgpu::ComputePipeline,
72 vari_blur: wgpu::ComputePipeline,
73 outline_tint: wgpu::ComputePipeline,
74 outline_composite: wgpu::ComputePipeline,
75 text_outline: wgpu::ComputePipeline,
76 custom_wave: wgpu::ComputePipeline,
77 crop: wgpu::ComputePipeline,
78 glow_add: wgpu::ComputePipeline,
79 xglow_prep: wgpu::ComputePipeline,
80 xglow_accum: wgpu::ComputePipeline,
81 display_blit: wgpu::ComputePipeline,
82 invert: wgpu::ComputePipeline,
83 channel_boolean: wgpu::ComputePipeline,
84}
85
86impl Pipelines {
87 fn new(device: &wgpu::Device) -> Self {
88 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
89 label: Some("compositor-shaders"),
90 source: wgpu::ShaderSource::Wgsl(include_str!("shaders.wgsl").into()),
91 });
92
93 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
94 binding,
95 visibility: wgpu::ShaderStages::COMPUTE,
96 ty: wgpu::BindingType::Texture {
97 sample_type: wgpu::TextureSampleType::Float { filterable: true },
98 view_dimension: wgpu::TextureViewDimension::D2,
99 multisampled: false,
100 },
101 count: None,
102 };
103 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
104 label: Some("compositor-bgl"),
105 entries: &[
106 tex_entry(0),
107 tex_entry(1),
108 tex_entry(2),
109 wgpu::BindGroupLayoutEntry {
110 binding: 3,
111 visibility: wgpu::ShaderStages::COMPUTE,
112 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
113 count: None,
114 },
115 wgpu::BindGroupLayoutEntry {
116 binding: 4,
117 visibility: wgpu::ShaderStages::COMPUTE,
118 ty: wgpu::BindingType::StorageTexture {
119 access: wgpu::StorageTextureAccess::WriteOnly,
120 format: wgpu::TextureFormat::Rgba8Unorm,
121 view_dimension: wgpu::TextureViewDimension::D2,
122 },
123 count: None,
124 },
125 wgpu::BindGroupLayoutEntry {
126 binding: 5,
127 visibility: wgpu::ShaderStages::COMPUTE,
128 ty: wgpu::BindingType::Buffer {
129 ty: wgpu::BufferBindingType::Uniform,
130 has_dynamic_offset: false,
131 min_binding_size: None,
132 },
133 count: None,
134 },
135 ],
136 });
137
138 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
139 label: Some("compositor-pl"),
140 bind_group_layouts: &[Some(&bgl)],
141 immediate_size: 0,
142 });
143
144 let make = |entry: &str| {
145 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
146 label: Some(entry),
147 layout: Some(&layout),
148 module: &shader,
149 entry_point: Some(entry),
150 compilation_options: Default::default(),
151 cache: None,
152 })
153 };
154
155 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
156 label: Some("compositor-linear"),
157 address_mode_u: wgpu::AddressMode::ClampToEdge,
158 address_mode_v: wgpu::AddressMode::ClampToEdge,
159 mag_filter: wgpu::FilterMode::Linear,
160 min_filter: wgpu::FilterMode::Linear,
161 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
162 ..Default::default()
163 });
164
165 Self {
166 bgl,
167 sampler,
168 bg: make("bg_op"),
169 merge: make("merge_op"),
170 transform: make("transform_op"),
171 bc: make("bc_op"),
172 cc: make("cc_op"),
173 color_gain: make("color_gain_op"),
174 luma_key: make("luma_key_op"),
175 blur: make("blur_op"),
176 dir_blur: make("dir_blur_op"),
177 fast_noise: make("fast_noise_op"),
178 displace: make("displace_op"),
179 mask_shape: make("mask_shape_op"),
180 mask_combine: make("mask_combine_op"),
181 mask_apply: make("mask_apply_op"),
182 colorize: make("colorize_op"),
183 color_curves: make("color_curves_op"),
184 xf_chroma: make("xf_chroma_op"),
185 gamut_convert: make("gamut_convert_op"),
186 vari_blur: make("vari_blur_op"),
187 outline_tint: make("outline_tint"),
188 outline_composite: make("outline_composite"),
189 text_outline: make("text_outline_op"),
190 custom_wave: make("custom_wave_op"),
191 crop: make("crop_op"),
192 glow_add: make("glow_add_op"),
193 xglow_prep: make("xglow_prep_op"),
194 xglow_accum: make("xglow_accum_op"),
195 display_blit: make("display_blit_op"),
196 invert: make("invert_op"),
197 channel_boolean: make("channel_boolean_op"),
198 }
199 }
200}
201
202pub struct Engine {
203 device: wgpu::Device,
204 queue: wgpu::Queue,
205 pipelines: Pipelines,
206 scene3d: crate::scene3d::Scene3DRenderer,
207 dummy: CachedTexture,
208 pub cache: NodeCache,
209 pub media: MediaCache,
210 pub expr: ExprEngine,
211 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.
212 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,
213 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default
214 /// to matching the dimensions & aspect ratio of the node they mask!).
215 mask_target_size: Option<[u32; 2]>,
216 /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res.
217 pub proxy_scale: u32,
218 /// High-Quality mode (`true` = exact Fusion bar-for-bar passes; `false` = perfmaxxed pyramid blur/glow & fast taps).
219 pub hiq: bool,
220}
221
222impl Engine {
223 pub fn new(device: wgpu::Device, queue: wgpu::Queue) -> Self {
224 let pipelines = Pipelines::new(&device);
225 let scene3d = crate::scene3d::Scene3DRenderer::new(&device);
226 let dummy = create_texture(&device, [1, 1], 0);
227 queue.write_texture(
228 dummy.texture.as_image_copy(),
229 &[0, 0, 0, 0],
230 wgpu::TexelCopyBufferLayout {
231 offset: 0,
232 bytes_per_row: Some(4),
233 rows_per_image: Some(1),
234 },
235 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
236 );
237 Self {
238 device,
239 queue,
240 pipelines,
241 scene3d,
242 dummy,
243 cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs)
244 media: MediaCache::new(1024),
245 expr: ExprEngine::new(),
246 frame_memo: HashMap::new(),
247 mask_target_size: None,
248 proxy_scale: 1,
249 hiq: true,
250 }
251 }
252
253 pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> {
254 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
255 let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?;
256 let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?;
257 Ok(Self::new(device, queue))
258 }
259
260 pub fn device(&self) -> &wgpu::Device {
261 &self.device
262 }
263
264 pub fn queue(&self) -> &wgpu::Queue {
265 &self.queue
266 }
267
268 pub fn set_cache_mode(&mut self, mode: CacheMode) {
269 self.cache.mode = mode;
270 }
271
272 pub fn bust_all_caches(&mut self) {
273 self.cache.bust_all();
274 self.media.clear();
275 }
276
277 pub fn bust_gpu_cache(&mut self) {
278 self.cache.bust_all();
279 }
280
281 pub fn bust_frame(&mut self, frame: i64) -> usize {
282 self.cache.bust_frame(frame)
283 }
284
285 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
286 self.cache.bust_subtree(node)
287 }
288
289 /// Evaluates `target` node at `time` and returns its GPU texture + telemetry.
290 pub fn evaluate(
291 &mut self,
292 comp: &Comp,
293 target: NodeId,
294 time: f64,
295 ) -> (CachedTexture, EvalStats) {
296 let t0 = Instant::now();
297 let mut stats = EvalStats::default();
298 let mut visiting = HashSet::new();
299 self.frame_memo.clear();
300 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
301 label: Some("comp-eval"),
302 });
303
304 let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
305 if tex.has_dod() {
306 // Crop expanded DoD cleanly back to logical canvas_size for final readback/export
307 let cropped = create_texture(&self.device, tex.canvas_size, tex.content_hash ^ 0xD0D0);
308 let mut params = UniformParams::default();
309 params.p[0] = [1.0, 1.0, 0.0, 0.0];
310 params.p[4] = [
311 tex.origin[0] as f32,
312 tex.origin[1] as f32,
313 tex.canvas_size[0] as f32,
314 tex.canvas_size[1] as f32,
315 ];
316 self.dispatch(&mut encoder, &self.pipelines.display_blit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, &params);
317 tex = cropped;
318 }
319 self.queue.submit(Some(encoder.finish()));
320
321 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
322 stats.cached_entries = self.cache.entry_count();
323 stats.cached_vram_mb = self.cache.total_mb();
324 stats.media_entries = self.media.entry_count();
325 stats.media_mb = self.media.total_mb();
326 (tex, stats)
327 }
328
329 /// Zero-copy render straight into a persistent viewer `wgpu::Texture` (premultiplied Rgba8Unorm).
330 pub fn render_into_viewer(
331 &mut self,
332 comp: &Comp,
333 target: NodeId,
334 time: f64,
335 dst_texture: &wgpu::Texture,
336 display: DisplaySettings,
337 ) -> EvalStats {
338 let t0 = Instant::now();
339 let mut stats = EvalStats::default();
340 let mut visiting = HashSet::new();
341 self.frame_memo.clear();
342 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
343 label: Some("comp-viewer-eval"),
344 });
345
346 let tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
347
348 let dst_size = [dst_texture.width(), dst_texture.height()];
349 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
350 let mut params = UniformParams::default();
351 params.p[0] = [
352 2.0_f32.powf(display.exposure),
353 display.gamma,
354 display.channel as f32,
355 if display.checker_bg { 1.0 } else { 0.0 },
356 ];
357 params.p[1] = display.uv_rect;
358 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
359 if tex.has_dod() {
360 params.p[4] = [
361 tex.origin[0] as f32,
362 tex.origin[1] as f32,
363 tex.canvas_size[0] as f32,
364 tex.canvas_size[1] as f32,
365 ];
366 }
367 self.dispatch_to_view(
368 &mut encoder,
369 &self.pipelines.display_blit,
370 &tex.view,
371 &self.dummy.view,
372 &self.dummy.view,
373 &dst_view,
374 dst_size,
375 &params,
376 );
377
378 self.queue.submit(Some(encoder.finish()));
379
380 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
381 stats.cached_entries = self.cache.entry_count();
382 stats.cached_vram_mb = self.cache.total_mb();
383 stats.media_entries = self.media.entry_count();
384 stats.media_mb = self.media.total_mb();
385 stats
386 }
387
388 /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export).
389 pub fn readback_rgba(&self, tex: &CachedTexture) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
390 let [w, h] = tex.size;
391 let bpp = 4u32;
392 let unpadded_bpr = w * bpp;
393 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
394 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
395 let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
396 label: Some("readback"),
397 size: u64::from(padded_bpr) * u64::from(h),
398 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
399 mapped_at_creation: false,
400 });
401 let mut enc = self.device.create_command_encoder(&Default::default());
402 enc.copy_texture_to_buffer(
403 tex.texture.as_image_copy(),
404 wgpu::TexelCopyBufferInfo {
405 buffer: &buf,
406 layout: wgpu::TexelCopyBufferLayout {
407 offset: 0,
408 bytes_per_row: Some(padded_bpr),
409 rows_per_image: Some(h),
410 },
411 },
412 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
413 );
414 self.queue.submit(Some(enc.finish()));
415
416 let slice = buf.slice(..);
417 let (tx, rx) = std::sync::mpsc::channel();
418 slice.map_async(wgpu::MapMode::Read, move |res| {
419 let _ = tx.send(res);
420 });
421 self.device.poll(wgpu::PollType::Wait {
422 submission_index: None,
423 timeout: Some(std::time::Duration::from_secs(10)),
424 })?;
425 rx.recv()??;
426 let data = slice.get_mapped_range()?;
427 let mut out = Vec::with_capacity((w * h * 4) as usize);
428 for row in 0..h as usize {
429 let start = row * padded_bpr as usize;
430 out.extend_from_slice(&data[start..start + unpadded_bpr as usize]);
431 }
432 drop(data);
433 buf.unmap();
434 Ok(out)
435 }
436
437 fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] {
438 let s = self.proxy_scale.max(1);
439 [(w / s).max(1), (h / s).max(1)]
440 }
441
442 fn eval_node(
443 &mut self,
444 comp: &Comp,
445 id: NodeId,
446 time: f64,
447 enc: &mut wgpu::CommandEncoder,
448 visiting: &mut HashSet<(NodeId, i64)>,
449 stats: &mut EvalStats,
450 ) -> CachedTexture {
451 let frame_i = time.round() as i64;
452 let is_mask_node = matches!(
453 comp.node(id).kind.as_str(),
454 "EllipseMask" | "RectangleMask" | "PolylineMask"
455 );
456 let memo_sz = if is_mask_node { self.mask_target_size } else { None };
457 // Always memoize within a single frame's DAG pass so diamond graphs never explode
458 // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache).
459 if let Some(hit) = self.frame_memo.get(&(id, frame_i, memo_sz)).cloned() {
460 stats.cache_hits += 1;
461 return hit;
462 }
463 if !visiting.insert((id, frame_i)) {
464 return self.dummy.clone();
465 }
466 let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats);
467 visiting.remove(&(id, frame_i));
468 self.frame_memo.insert((id, frame_i, memo_sz), res.clone());
469 res
470 }
471
472 fn eval_node_inner(
473 &mut self,
474 comp: &Comp,
475 id: NodeId,
476 time: f64,
477 frame_i: i64,
478 enc: &mut wgpu::CommandEncoder,
479 visiting: &mut HashSet<(NodeId, i64)>,
480 stats: &mut EvalStats,
481 ) -> CachedTexture {
482 let node = comp.node(id);
483 let comp_dims = self.scaled_dims(comp.width, comp.height);
484
485 // Bypass (`PassThrough`) or passthrough utility nodes
486 if node.bypassed || matches!(node.kind.as_str(), "Saver" | "PipeRouter" | "Fuse.Wireless" | "Tracker") {
487 let port = default_main_input_port(&node.kind);
488 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
489 return self.eval_node(comp, src_id, time, enc, visiting, stats);
490 }
491 return self.dummy.clone();
492 }
493
494 // MacroOperator / GroupOperator: seamlessly evaluate the unpacked internal output tool!
495 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
496 if let Some(out_id) = node.macro_output {
497 return self.eval_node(comp, out_id, time, enc, visiting, stats);
498 }
499 if let Some(src_id) = node
500 .connected_node("Input")
501 .or_else(|| node.connected_node("MainInput1"))
502 .and_then(|s| comp.find_node(s))
503 {
504 return self.eval_node(comp, src_id, time, enc, visiting, stats);
505 }
506 return self.dummy.clone();
507 }
508
509 // TimeStretcher / TimeSpeed: remap time BEFORE evaluating upstream!
510 if node.kind == "TimeStretcher" {
511 let remapped = comp.eval_number(node, "SourceTime", time, time, &self.expr);
512 if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
513 return self.eval_node(comp, src_id, remapped, enc, visiting, stats);
514 }
515 return self.dummy.clone();
516 }
517 if node.kind == "TimeSpeed" {
518 let speed = comp.eval_number(node, "Speed", time, 1.0, &self.expr);
519 let delay = comp.eval_number(node, "Delay", time, 0.0, &self.expr);
520 let remapped = (time - delay) * speed;
521 if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
522 return self.eval_node(comp, src_id, remapped, enc, visiting, stats);
523 }
524 return self.dummy.clone();
525 }
526 if node.kind == "Switch" || node.kind == "Fuse.Switch" {
527 let which = comp.eval_number(node, "Which", time, 1.0, &self.expr).round().max(1.0) as usize;
528 let port = format!("Input{which}");
529 let src_name = node.connected_node(&port).or_else(|| node.connected_node("Input1"));
530 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
531 return self.eval_node(comp, src_id, time, enc, visiting, stats);
532 }
533 return self.dummy.clone();
534 }
535
536 match node.kind.as_str() {
537 "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats),
538 "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
539 "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats),
540 "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats),
541 "Scale" | "BetterResize" => self.eval_scale(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
542 "Crop" => self.eval_crop(comp, node, time, frame_i, enc, visiting, stats),
543 "BrightnessContrast" => self.eval_bc(comp, node, time, frame_i, enc, visiting, stats),
544 "ColorCorrector" => self.eval_cc(comp, node, time, frame_i, enc, visiting, stats),
545 "ColorGain" => self.eval_color_gain(comp, node, time, frame_i, enc, visiting, stats),
546 "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats),
547 "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats),
548 "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats),
549 "ChannelBoolean" => self.eval_channel_boolean(comp, node, time, frame_i, enc, visiting, stats),
550 "LumaKeyer" => self.eval_luma_key(comp, node, time, frame_i, enc, visiting, stats),
551 "Blur" => self.eval_blur(comp, node, time, frame_i, enc, visiting, stats),
552 "VariBlur" => self.eval_vari_blur(comp, node, time, frame_i, enc, visiting, stats),
553 "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats),
554 "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats),
555 "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats),
556 "ErodeDilate" => self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats),
557 "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats),
558 "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats),
559 "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats),
560 "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats),
561 "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
562 "BitmapMask" => self.eval_bitmap_mask(comp, node, time, enc, visiting, stats),
563 "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats),
564 "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats),
565 "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats),
566 "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats),
567 "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
568 "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
569 other => {
570 // Graceful passthrough for unsupported nodes (e.g. MacroOperator, 3D, etc.)
571 if !stats.unsupported_nodes.iter().any(|s| s == other) {
572 stats.unsupported_nodes.push(other.to_owned());
573 }
574 let port = default_main_input_port(other);
575 if let Some(src_id) = node.connected_node(port)
576 .or_else(|| node.connected_node("MainInput1"))
577 .or_else(|| node.connected_node("Input"))
578 .or_else(|| node.connected_node("Background"))
579 .and_then(|s| comp.find_node(s))
580 {
581 self.eval_node(comp, src_id, time, enc, visiting, stats)
582 } else {
583 self.dummy.clone()
584 }
585 }
586 }
587 }
588
589 #[allow(clippy::too_many_arguments)]
590 fn eval_mask_input_sized(
591 &mut self,
592 comp: &Comp,
593 node: &Node,
594 time: f64,
595 target_size: Option<[u32; 2]>,
596 enc: &mut wgpu::CommandEncoder,
597 visiting: &mut HashSet<(NodeId, i64)>,
598 stats: &mut EvalStats,
599 ) -> (Option<CachedTexture>, bool) {
600 let invert = comp.eval_number(node, "ApplyMaskInverted", time, 0.0, &self.expr) > 0.5;
601 let prev_sz = self.mask_target_size;
602 if target_size.is_some() {
603 self.mask_target_size = target_size;
604 }
605 let tex = node
606 .connected_node("EffectMask")
607 .and_then(|s| comp.find_node(s))
608 .map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats));
609 self.mask_target_size = prev_sz;
610 (tex, invert)
611 }
612
613 fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 {
614 let mut h = DefaultHasher::new();
615 self.cache.gpu_salt.hash(&mut h);
616 self.hiq.hash(&mut h);
617 self.cache.node_salt(node.id).hash(&mut h);
618 tag.hash(&mut h);
619 size.hash(&mut h);
620 upstream.hash(&mut h);
621 for &v in params {
622 v.to_bits().hash(&mut h);
623 }
624 h.finish()
625 }
626
627 fn eval_loader(
628 &mut self,
629 comp: &Comp,
630 node: &Node,
631 time: f64,
632 frame_i: i64,
633 enc: &mut wgpu::CommandEncoder,
634 visiting: &mut HashSet<(NodeId, i64)>,
635 stats: &mut EvalStats,
636 ) -> CachedTexture {
637 let Some(clip) = node.clips.first() else {
638 return self.dummy.clone();
639 };
640 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(1.0) > 0.5;
641 let exr_channels = [
642 node.static_str("Clip1.OpenEXRFormat.RedName"),
643 node.static_str("Clip1.OpenEXRFormat.GreenName"),
644 node.static_str("Clip1.OpenEXRFormat.BlueName"),
645 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
646 ];
647 let Some((resolved, local_idx, img, loaded_from_disk)) =
648 self.media.load_clip(clip, frame_i, post_mult, exr_channels)
649 else {
650 return self.dummy.clone();
651 };
652 if loaded_from_disk {
653 stats.source_loads += 1;
654 }
655 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);
656 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
657 let target_size = self.scaled_dims(img.size[0], img.size[1]);
658 let mut h = DefaultHasher::new();
659 self.cache.gpu_salt.hash(&mut h);
660 self.cache.node_salt(node.id).hash(&mut h);
661 "Loader".hash(&mut h);
662 resolved.hash(&mut h);
663 local_idx.hash(&mut h);
664 post_mult.hash(&mut h);
665 target_size.hash(&mut h);
666 mask_hash.hash(&mut h);
667 mask_inv.hash(&mut h);
668 let key = h.finish();
669
670 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
671 stats.cache_hits += 1;
672 return hit;
673 }
674 stats.cache_misses += 1;
675 stats.nodes_evaluated += 1;
676
677 let need_post = target_size != img.size || mask.is_some();
678 let full_tex = create_texture(&self.device, img.size, if need_post { 0 } else { key });
679 self.queue.write_texture(
680 full_tex.texture.as_image_copy(),
681 &img.rgba,
682 wgpu::TexelCopyBufferLayout {
683 offset: 0,
684 bytes_per_row: Some(img.size[0] * 4),
685 rows_per_image: Some(img.size[1]),
686 },
687 wgpu::Extent3d {
688 width: img.size[0],
689 height: img.size[1],
690 depth_or_array_layers: 1,
691 },
692 );
693 let base_tex = if target_size != img.size {
694 let scaled = create_texture(&self.device, target_size, if mask.is_some() { 0 } else { key });
695 let mut u = UniformParams::default();
696 u.p[0] = [1.0, 1.0, 0.0, 0.0];
697 self.dispatch(enc, &self.pipelines.display_blit, &full_tex.view, &self.dummy.view, &self.dummy.view, &scaled, &u);
698 scaled
699 } else {
700 full_tex
701 };
702 let tex = if let Some(m) = mask {
703 let masked = create_texture(&self.device, target_size, key);
704 let mut u = UniformParams::default();
705 u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
706 self.dispatch(enc, &self.pipelines.mask_apply, &base_tex.view, &self.dummy.view, &m.view, &masked, &u);
707 masked
708 } else {
709 base_tex
710 };
711 self.cache.insert(key, tex.clone(), node.id, frame_i);
712 tex
713 }
714
715 fn eval_background(
716 &mut self,
717 comp: &Comp,
718 node: &Node,
719 time: f64,
720 frame_i: i64,
721 comp_dims: [u32; 2],
722 enc: &mut wgpu::CommandEncoder,
723 visiting: &mut HashSet<(NodeId, i64)>,
724 stats: &mut EvalStats,
725 ) -> CachedTexture {
726 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
727 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;
728 let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims };
729
730 let tl = [
731 comp.eval_number(node, "TopLeftRed", time, 0.0, &self.expr) as f32,
732 comp.eval_number(node, "TopLeftGreen", time, 0.0, &self.expr) as f32,
733 comp.eval_number(node, "TopLeftBlue", time, 0.0, &self.expr) as f32,
734 comp.eval_number(node, "TopLeftAlpha", time, 1.0, &self.expr) as f32,
735 ];
736 let tr = [
737 comp.eval_number(node, "TopRightRed", time, tl[0] as f64, &self.expr) as f32,
738 comp.eval_number(node, "TopRightGreen", time, tl[1] as f64, &self.expr) as f32,
739 comp.eval_number(node, "TopRightBlue", time, tl[2] as f64, &self.expr) as f32,
740 comp.eval_number(node, "TopRightAlpha", time, tl[3] as f64, &self.expr) as f32,
741 ];
742 let bl = [
743 comp.eval_number(node, "BottomLeftRed", time, tl[0] as f64, &self.expr) as f32,
744 comp.eval_number(node, "BottomLeftGreen", time, tl[1] as f64, &self.expr) as f32,
745 comp.eval_number(node, "BottomLeftBlue", time, tl[2] as f64, &self.expr) as f32,
746 comp.eval_number(node, "BottomLeftAlpha", time, tl[3] as f64, &self.expr) as f32,
747 ];
748 let br = [
749 comp.eval_number(node, "BottomRightRed", time, tr[0] as f64, &self.expr) as f32,
750 comp.eval_number(node, "BottomRightGreen", time, tr[1] as f64, &self.expr) as f32,
751 comp.eval_number(node, "BottomRightBlue", time, tr[2] as f64, &self.expr) as f32,
752 comp.eval_number(node, "BottomRightAlpha", time, tr[3] as f64, &self.expr) as f32,
753 ];
754
755 let mut kind = match node.static_str("Type").unwrap_or("Solid") {
756 "Horizontal" => 1.0,
757 "Vertical" => 2.0,
758 "Corner" => 3.0,
759 "Gradient" => match node.static_str("GradientType").unwrap_or("Linear") {
760 "Radial" => 5.0,
761 _ => 4.0,
762 },
763 _ => 0.0,
764 };
765 let mut c0 = tl;
766 let mut c1 = tr;
767 if kind >= 4.0 {
768 if let Some(grad) = comp.eval_gradient(node, "Gradient", time) {
769 c0 = grad.sample(0.0);
770 c1 = grad.sample(1.0);
771 } else {
772 kind = 0.0;
773 }
774 }
775 let start = comp.eval_point(node, "Start", time, [0.0, 0.5], &self.expr);
776 let end = comp.eval_point(node, "End", time, [1.0, 0.5], &self.expr);
777 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
778 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
779
780 let mut u = UniformParams::default();
781 u.p[0] = c0;
782 u.p[1] = c1;
783 u.p[2] = bl;
784 u.p[3] = br;
785 u.p[4] = [kind, 0.0, start[0] as f32, start[1] as f32];
786 u.p[5] = [
787 end[0] as f32,
788 end[1] as f32,
789 if mask.is_some() { 1.0 } else { 0.0 },
790 if mask_inv { 1.0 } else { 0.0 },
791 ];
792
793 let key = self.make_key(node, "Background", size, &[mask_hash], bytemuck::cast_slice(&u.p[..6]));
794 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
795 stats.cache_hits += 1;
796 return hit;
797 }
798 stats.cache_misses += 1;
799 stats.nodes_evaluated += 1;
800
801 let dst = create_texture(&self.device, size, key);
802 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
803 self.dispatch(enc, &self.pipelines.bg, &self.dummy.view, &self.dummy.view, mv, &dst, &u);
804 self.cache.insert(key, dst.clone(), node.id, frame_i);
805 dst
806 }
807
808 fn eval_merge(
809 &mut self,
810 comp: &Comp,
811 node: &Node,
812 time: f64,
813 frame_i: i64,
814 enc: &mut wgpu::CommandEncoder,
815 visiting: &mut HashSet<(NodeId, i64)>,
816 stats: &mut EvalStats,
817 ) -> CachedTexture {
818 let bg = match node.connected_node("Background").and_then(|s| comp.find_node(s)) {
819 Some(bid) => self.eval_node(comp, bid, time, enc, visiting, stats),
820 None => return self.dummy.clone(),
821 };
822
823 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
824 if blend <= 1e-6 {
825 // Temporal liveness pruning — don't even evaluate Foreground!
826 stats.pruned_branches += 1;
827 return bg;
828 }
829
830 let fg = match node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
831 Some(fid) => self.eval_node(comp, fid, time, enc, visiting, stats),
832 None => return bg,
833 };
834
835 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
836 let size_s = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32;
837 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
838 let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32;
839 let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32;
840 let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32;
841 let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32;
842 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, &self.expr) as f32;
843 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, &self.expr) as f32;
844
845 let mode_str = node.static_str("ApplyMode").unwrap_or("Normal");
846 let mode_id = match mode_str {
847 "Screen" => 1.0,
848 "Multiply" => 2.0,
849 "Darken" => 3.0,
850 "Lighten" => 4.0,
851 "Difference" => 5.0,
852 "Exclusion" => 6.0,
853 "Overlay" => 7.0,
854 "Hard Light" | "HardLight" => 8.0,
855 "Soft Light" | "SoftLight" => 9.0,
856 "LinearLight" | "Linear Light" => 10.0,
857 "Color Dodge" | "ColorDodge" => 11.0,
858 "LinearDodge" | "Linear Dodge" | "Add" => 12.0,
859 "VividLight" | "Vivid Light" => 13.0,
860 "Hypotenuse" => 14.0,
861 "DarkerColor" | "Darker Color" => 15.0,
862 "LighterColor" | "Lighter Color" => 16.0,
863 "PinLight" | "Pin Light" => 17.0,
864 "ColorBurn" | "Color Burn" => 18.0,
865 "LinearBurn" | "Linear Burn" => 19.0,
866 "Geometric" => 20.0,
867 "Hue" => 21.0,
868 "Saturation" => 22.0,
869 "Color" => 23.0,
870 "Luminosity" => 24.0,
871 _ => 0.0,
872 };
873 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };
874 let op_id = match node.static_str("Operator").unwrap_or("Over") {
875 "Under" => 1.0,
876 "In" => 2.0,
877 "Held Out" | "HeldOut" => 3.0,
878 "Atop" => 4.0,
879 "XOr" => 5.0,
880 _ => 0.0, // Over
881 };
882
883 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats);
884 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
885
886 let mut u = UniformParams::default();
887 u.p[0] = [center[0] as f32, center[1] as f32, size_s, angle_deg.to_radians()];
888 u.p[1] = [blend, gain, mode_id, edges];
889 u.p[2] = [flip_h, flip_v, nearest, op_id];
890 u.p[3] = [
891 if mask.is_some() { 1.0 } else { 0.0 },
892 if mask_inv { 1.0 } else { 0.0 },
893 fg.canvas_size[0] as f32,
894 fg.canvas_size[1] as f32,
895 ];
896 if fg.has_dod() {
897 u.p[4] = [
898 fg.origin[0] as f32,
899 fg.origin[1] as f32,
900 fg.canvas_size[0] as f32,
901 fg.canvas_size[1] as f32,
902 ];
903 }
904 if bg.has_dod() {
905 u.p[5] = [
906 bg.origin[0] as f32,
907 bg.origin[1] as f32,
908 bg.canvas_size[0] as f32,
909 bg.canvas_size[1] as f32,
910 ];
911 }
912 u.p[6] = [burn_in, sub_add, 0.0, 0.0];
913
914 let key = self.make_key(
915 node,
916 "Merge",
917 bg.size,
918 &[bg.content_hash, fg.content_hash, mask_hash],
919 bytemuck::cast_slice(&u.p[..7]),
920 );
921 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
922 stats.cache_hits += 1;
923 return hit;
924 }
925 stats.cache_misses += 1;
926 stats.nodes_evaluated += 1;
927
928 let dst = create_texture_dod(&self.device, bg.size, bg.origin, bg.canvas_size, key);
929 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
930 self.dispatch(enc, &self.pipelines.merge, &bg.view, &fg.view, mv, &dst, &u);
931 self.cache.insert(key, dst.clone(), node.id, frame_i);
932 dst
933 }
934
935 fn eval_transform(
936 &mut self,
937 comp: &Comp,
938 node: &Node,
939 time: f64,
940 frame_i: i64,
941 enc: &mut wgpu::CommandEncoder,
942 visiting: &mut HashSet<(NodeId, i64)>,
943 stats: &mut EvalStats,
944 ) -> CachedTexture {
945 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
946 return self.dummy.clone();
947 };
948 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
949 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
950 if blend <= 1e-6 {
951 return src;
952 }
953 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
954 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
955 let use_xy = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, &self.expr) < 0.5;
956 let (sx, sy) = if use_xy {
957 (
958 comp.eval_number(node, "XSize", time, 1.0, &self.expr) as f32,
959 comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32,
960 )
961 } else {
962 let s = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32;
963 let asp = comp.eval_number(node, "Aspect", time, 1.0, &self.expr) as f32;
964 (s, s * asp)
965 };
966 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
967 let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32;
968 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, &self.expr) as f32;
969 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, &self.expr) as f32;
970 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };
971 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
972 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
973
974 let mut u = UniformParams::default();
975 u.p[0] = [center[0] as f32, center[1] as f32, pivot[0] as f32, pivot[1] as f32];
976 u.p[1] = [sx, sy, angle, edges];
977 u.p[2] = [flip_h, flip_v, blend, if mask.is_some() { 1.0 } else { 0.0 }];
978 u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, 0.0, 0.0];
979 if src.has_dod() {
980 u.p[4] = [
981 src.origin[0] as f32,
982 src.origin[1] as f32,
983 src.canvas_size[0] as f32,
984 src.canvas_size[1] as f32,
985 ];
986 }
987
988 let out_size = src.canvas_size;
989 let key = self.make_key(node, "Transform", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
990 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
991 stats.cache_hits += 1;
992 return hit;
993 }
994 stats.cache_misses += 1;
995 stats.nodes_evaluated += 1;
996
997 let dst = create_texture(&self.device, out_size, key);
998 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
999 self.dispatch(enc, &self.pipelines.transform, &src.view, &self.dummy.view, mv, &dst, &u);
1000 self.cache.insert(key, dst.clone(), node.id, frame_i);
1001 dst
1002 }
1003
1004 fn eval_scale(
1005 &mut self,
1006 comp: &Comp,
1007 node: &Node,
1008 time: f64,
1009 frame_i: i64,
1010 comp_dims: [u32; 2],
1011 enc: &mut wgpu::CommandEncoder,
1012 visiting: &mut HashSet<(NodeId, i64)>,
1013 stats: &mut EvalStats,
1014 ) -> CachedTexture {
1015 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1016 return self.dummy.clone();
1017 };
1018 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1019 let hiq_only = comp.eval_number(node, "HiQOnly", time, 0.0, &self.expr) > 0.5;
1020 if !self.hiq && hiq_only && node.kind == "Scale" {
1021 return src;
1022 }
1023 let dst_size = if node.kind == "BetterResize" {
1024 let w = comp.eval_number(node, "Width", time, comp_dims[0] as f64, &self.expr) as u32;
1025 let h = comp.eval_number(node, "Height", time, comp_dims[1] as f64, &self.expr) as u32;
1026 self.scaled_dims(w, h)
1027 } else {
1028 let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr);
1029 let sy = comp.eval_number(node, "YSize", time, sx, &self.expr);
1030 [
1031 ((src.size[0] as f64 * sx).round() as u32).clamp(1, 8192),
1032 ((src.size[1] as f64 * sy).round() as u32).clamp(1, 8192),
1033 ]
1034 };
1035 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };
1036 let mut u = UniformParams::default();
1037 u.p[0] = [1.0, 1.0, 0.0, 0.0];
1038 u.p[2] = [nearest, 0.0, 0.0, 0.0];
1039 let key = self.make_key(node, "Scale", dst_size, &[src.content_hash], &[nearest]);
1040 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1041 stats.cache_hits += 1;
1042 return hit;
1043 }
1044 stats.cache_misses += 1;
1045 stats.nodes_evaluated += 1;
1046 let dst = create_texture(&self.device, dst_size, key);
1047 self.dispatch(enc, &self.pipelines.display_blit, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u);
1048 self.cache.insert(key, dst.clone(), node.id, frame_i);
1049 dst
1050 }
1051
1052 fn eval_crop(
1053 &mut self,
1054 comp: &Comp,
1055 node: &Node,
1056 time: f64,
1057 frame_i: i64,
1058 enc: &mut wgpu::CommandEncoder,
1059 visiting: &mut HashSet<(NodeId, i64)>,
1060 stats: &mut EvalStats,
1061 ) -> CachedTexture {
1062 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1063 return self.dummy.clone();
1064 };
1065 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1066 let x_size = comp.eval_number(node, "XSize", time, src.size[0] as f64, &self.expr).round().max(1.0) as u32;
1067 let y_size = comp.eval_number(node, "YSize", time, src.size[1] as f64, &self.expr).round().max(1.0) as u32;
1068 let dst_size = self.scaled_dims(x_size, y_size);
1069 let x_off = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32 / self.proxy_scale.max(1) as f32;
1070 let y_off = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32 / self.proxy_scale.max(1) as f32;
1071
1072 let mut u = UniformParams::default();
1073 u.p[0] = [x_off, y_off, 1.0, 1.0];
1074 let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1]));
1075 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1076 stats.cache_hits += 1;
1077 return hit;
1078 }
1079 stats.cache_misses += 1;
1080 stats.nodes_evaluated += 1;
1081 let dst = create_texture(&self.device, dst_size, key);
1082 self.dispatch(enc, &self.pipelines.crop, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u);
1083 self.cache.insert(key, dst.clone(), node.id, frame_i);
1084 dst
1085 }
1086
1087 fn eval_bc(
1088 &mut self,
1089 comp: &Comp,
1090 node: &Node,
1091 time: f64,
1092 frame_i: i64,
1093 enc: &mut wgpu::CommandEncoder,
1094 visiting: &mut HashSet<(NodeId, i64)>,
1095 stats: &mut EvalStats,
1096 ) -> CachedTexture {
1097 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1098 return self.dummy.clone();
1099 };
1100 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1101 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1102 if blend <= 1e-6 {
1103 return src;
1104 }
1105 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1106 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1107
1108 let mut u = UniformParams::default();
1109 u.p[0] = [
1110 comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32,
1111 comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32,
1112 comp.eval_number(node, "Gamma", time, 1.0, &self.expr) as f32,
1113 comp.eval_number(node, "Contrast", time, 0.0, &self.expr) as f32,
1114 ];
1115 u.p[1] = [
1116 comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32,
1117 comp.eval_number(node, "Saturation", time, 1.0, &self.expr) as f32,
1118 comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32,
1119 blend,
1120 ];
1121 u.p[2] = [
1122 if mask.is_some() { 1.0 } else { 0.0 },
1123 if mask_inv { 1.0 } else { 0.0 },
1124 comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32,
1125 comp.eval_number(node, "High", time, 1.0, &self.expr) as f32,
1126 ];
1127 u.p[3] = [
1128 comp.eval_number(node, "Red", time, 1.0, &self.expr) as f32,
1129 comp.eval_number(node, "Green", time, 1.0, &self.expr) as f32,
1130 comp.eval_number(node, "Blue", time, 1.0, &self.expr) as f32,
1131 comp.eval_number(node, "Alpha", time, 0.0, &self.expr) as f32,
1132 ];
1133
1134 let key = self.make_key(node, "BC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
1135 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1136 stats.cache_hits += 1;
1137 return hit;
1138 }
1139 stats.cache_misses += 1;
1140 stats.nodes_evaluated += 1;
1141 let dst = create_texture(&self.device, src.size, key);
1142 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1143 self.dispatch(enc, &self.pipelines.bc, &src.view, &self.dummy.view, mv, &dst, &u);
1144 self.cache.insert(key, dst.clone(), node.id, frame_i);
1145 dst
1146 }
1147
1148 fn eval_cc(
1149 &mut self,
1150 comp: &Comp,
1151 node: &Node,
1152 time: f64,
1153 frame_i: i64,
1154 enc: &mut wgpu::CommandEncoder,
1155 visiting: &mut HashSet<(NodeId, i64)>,
1156 stats: &mut EvalStats,
1157 ) -> CachedTexture {
1158 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1159 return self.dummy.clone();
1160 };
1161 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1162 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1163 if blend <= 1e-6 {
1164 return src;
1165 }
1166 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1167 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1168
1169 let mut u = UniformParams::default();
1170 u.p[0] = [
1171 comp.eval_number(node, "WheelHue1", time, 0.0, &self.expr) as f32,
1172 comp.eval_number(node, "WheelSaturation1", time, 1.0, &self.expr) as f32,
1173 comp.eval_number(node, "WheelTintAngle1", time, 0.0, &self.expr) as f32,
1174 comp.eval_number(node, "WheelTintLength1", time, 0.0, &self.expr) as f32,
1175 ];
1176 u.p[1] = [
1177 comp.eval_number(node, "MasterRGBGain", time, 1.0, &self.expr) as f32,
1178 comp.eval_number(node, "MasterRGBLift", time, 0.0, &self.expr) as f32,
1179 comp.eval_number(node, "MasterRGBGamma", time, 1.0, &self.expr) as f32,
1180 comp.eval_number(node, "MasterRGBContrast", time, 1.0, &self.expr) as f32,
1181 ];
1182 u.p[2] = [
1183 comp.eval_number(node, "MasterRGBBrightness", time, 0.0, &self.expr) as f32,
1184 comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32,
1185 blend,
1186 if mask.is_some() { 1.0 } else { 0.0 },
1187 ];
1188 u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1189
1190 let key = self.make_key(node, "CC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
1191 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1192 stats.cache_hits += 1;
1193 return hit;
1194 }
1195 stats.cache_misses += 1;
1196 stats.nodes_evaluated += 1;
1197 let dst = create_texture(&self.device, src.size, key);
1198 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1199 self.dispatch(enc, &self.pipelines.cc, &src.view, &self.dummy.view, mv, &dst, &u);
1200 self.cache.insert(key, dst.clone(), node.id, frame_i);
1201 dst
1202 }
1203
1204 fn eval_luma_key(
1205 &mut self,
1206 comp: &Comp,
1207 node: &Node,
1208 time: f64,
1209 frame_i: i64,
1210 enc: &mut wgpu::CommandEncoder,
1211 visiting: &mut HashSet<(NodeId, i64)>,
1212 stats: &mut EvalStats,
1213 ) -> CachedTexture {
1214 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1215 return self.dummy.clone();
1216 };
1217 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1218 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1219 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1220
1221 let mut u = UniformParams::default();
1222 u.p[0] = [
1223 comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32,
1224 comp.eval_number(node, "High", time, 1.0, &self.expr) as f32,
1225 comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32,
1226 comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32,
1227 ];
1228 u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0];
1229
1230 let key = self.make_key(node, "LumaKeyer", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2]));
1231 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1232 stats.cache_hits += 1;
1233 return hit;
1234 }
1235 stats.cache_misses += 1;
1236 stats.nodes_evaluated += 1;
1237 let dst = create_texture(&self.device, src.size, key);
1238 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1239 self.dispatch(enc, &self.pipelines.luma_key, &src.view, &self.dummy.view, mv, &dst, &u);
1240 self.cache.insert(key, dst.clone(), node.id, frame_i);
1241 dst
1242 }
1243
1244 fn eval_blur(
1245 &mut self,
1246 comp: &Comp,
1247 node: &Node,
1248 time: f64,
1249 frame_i: i64,
1250 enc: &mut wgpu::CommandEncoder,
1251 visiting: &mut HashSet<(NodeId, i64)>,
1252 stats: &mut EvalStats,
1253 ) -> CachedTexture {
1254 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1255 return self.dummy.clone();
1256 };
1257 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1258 let lock_xy = comp.eval_number(node, "LockBlurXY", time, 1.0, &self.expr) > 0.5;
1259 let mode = if node.static_str("Filter").unwrap_or("Fast Gaussian") == "Box" { 1.0 } else { 0.0 };
1260 // Fusion XBlurSize is in 720px-reference pixels (blur_norm = XBlurSize / 720.0).
1261 // Gaussian blur_op uses sigma = radius * 0.45 while Fusion Gaussian has sigma ~= 0.553 * blur_px -> * 1.23.
1262 let scale_ref = src.size[0] as f32 / 720.0;
1263 let gauss_k = if mode < 0.5 { 1.14 } else { 1.0 };
1264 let x_raw = comp.eval_number(node, "XBlurSize", time, 1.0, &self.expr) as f32;
1265 let y_raw = if lock_xy {
1266 x_raw
1267 } else {
1268 comp.eval_number(node, "YBlurSize", time, x_raw as f64, &self.expr) as f32
1269 };
1270 let rx = x_raw * scale_ref * gauss_k;
1271 let ry = y_raw * scale_ref * gauss_k;
1272 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1273 let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 };
1274 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1275 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1276
1277 let max_r = rx.max(ry);
1278 if max_r < 0.25 || blend <= 1e-6 {
1279 return src;
1280 }
1281
1282 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 }]);
1283 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1284 stats.cache_hits += 1;
1285 return hit;
1286 }
1287 stats.cache_misses += 1;
1288 stats.nodes_evaluated += 1;
1289
1290 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
1291 // Fast mode (`!self.hiq`): downsample large blurs to 1/2 or 1/4 pyramid level for 4-16x speedup!
1292 let down = if self.hiq {
1293 1u32
1294 } else if max_r >= 16.0 {
1295 4u32
1296 } else if max_r >= 5.0 {
1297 2u32
1298 } else {
1299 1u32
1300 };
1301
1302 if down > 1 {
1303 let work_size = [(src.size[0] / down).max(1), (src.size[1] / down).max(1)];
1304 let small = create_texture(&self.device, work_size, 0);
1305 let tmp = create_texture(&self.device, work_size, 0);
1306 let small_blur = create_texture(&self.device, work_size, 0);
1307
1308 let mut u_blit = UniformParams::default();
1309 u_blit.p[0] = [1.0, 1.0, 0.0, 0.0];
1310 self.dispatch(enc, &self.pipelines.display_blit, &src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit);
1311
1312 let mut uh = UniformParams::default();
1313 uh.p[0] = [1.0, 0.0, rx / down as f32, mode];
1314 uh.p[1] = [1.0, 0.0, 0.0, clamp_edges];
1315 self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp, &uh);
1316
1317 let mut uv = UniformParams::default();
1318 uv.p[0] = [0.0, 1.0, ry / down as f32, mode];
1319 uv.p[1] = [1.0, 0.0, 0.0, clamp_edges];
1320 self.dispatch(enc, &self.pipelines.blur, &tmp.view, &self.dummy.view, &self.dummy.view, &small_blur, &uv);
1321
1322 if blend >= 0.999 && mask.is_none() {
1323 self.dispatch(enc, &self.pipelines.display_blit, &small_blur.view, &self.dummy.view, &self.dummy.view, &dst, &u_blit);
1324 } else {
1325 let mut um = UniformParams::default();
1326 um.p[0] = [0.5, 0.5, 1.0, 0.0];
1327 um.p[1] = [blend, 1.0, 0.0, 0.0];
1328 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];
1329 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1330 self.dispatch(enc, &self.pipelines.merge, &src.view, &small_blur.view, mv, &dst, &um);
1331 }
1332 } else {
1333 let tmp = create_texture(&self.device, src.size, 0);
1334 let mut uh = UniformParams::default();
1335 uh.p[0] = [1.0, 0.0, rx, mode];
1336 uh.p[1] = [1.0, 0.0, 0.0, clamp_edges];
1337 self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh);
1338
1339 let mut uv = UniformParams::default();
1340 uv.p[0] = [0.0, 1.0, ry, mode];
1341 uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, clamp_edges];
1342 uv.p[2] = [1.0, 0.0, 0.0, 0.0]; // blend against original unblurred src in src_b!
1343 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1344 self.dispatch(enc, &self.pipelines.blur, &tmp.view, &src.view, mv, &dst, &uv);
1345 }
1346
1347 self.cache.insert(key, dst.clone(), node.id, frame_i);
1348 dst
1349 }
1350
1351 fn eval_dir_blur(
1352 &mut self,
1353 comp: &Comp,
1354 node: &Node,
1355 time: f64,
1356 frame_i: i64,
1357 enc: &mut wgpu::CommandEncoder,
1358 visiting: &mut HashSet<(NodeId, i64)>,
1359 stats: &mut EvalStats,
1360 ) -> CachedTexture {
1361 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1362 return self.dummy.clone();
1363 };
1364 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1365 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1366 if blend <= 1e-6 {
1367 return src;
1368 }
1369 let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32;
1370 let len = comp.eval_number(node, "Length", time, 0.02, &self.expr) as f32;
1371 let ang = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
1372 let glow = comp.eval_number(node, "Glow", time, 0.0, &self.expr) as f32;
1373 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1374 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1375 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1376
1377 let samples = if self.hiq {
1378 ((len.abs() * 320.0).clamp(16.0, 48.0)).round()
1379 } else {
1380 ((len.abs() * 120.0).clamp(8.0, 12.0)).round()
1381 };
1382 let mut u = UniformParams::default();
1383 u.p[0] = [kind, len, ang, glow];
1384 u.p[1] = [center[0] as f32, center[1] as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }];
1385 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, samples, 0.0, 0.0];
1386 let key = self.make_key(node, "DirBlur", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
1387 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1388 stats.cache_hits += 1;
1389 return hit;
1390 }
1391 stats.cache_misses += 1;
1392 stats.nodes_evaluated += 1;
1393 let dst = create_texture(&self.device, src.size, key);
1394 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1395 self.dispatch(enc, &self.pipelines.dir_blur, &src.view, &self.dummy.view, mv, &dst, &u);
1396 self.cache.insert(key, dst.clone(), node.id, frame_i);
1397 dst
1398 }
1399
1400 fn eval_glow(
1401 &mut self,
1402 comp: &Comp,
1403 node: &Node,
1404 time: f64,
1405 frame_i: i64,
1406 enc: &mut wgpu::CommandEncoder,
1407 visiting: &mut HashSet<(NodeId, i64)>,
1408 stats: &mut EvalStats,
1409 ) -> CachedTexture {
1410 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1411 return self.dummy.clone();
1412 };
1413 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1414 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1415 if blend <= 1e-6 {
1416 return src;
1417 }
1418 let is_soft_glow = node.kind == "SoftGlow";
1419 // Fusion SoftGlow/Glow sizes are in 720px-reference pixels (same as Blur).
1420 let scale_ref = src.size[0] as f32 / 720.0 * 1.14;
1421 let (raw_size, gain, thresh, combine_mode) = if is_soft_glow {
1422 let sz = comp.eval_number(node, "XGlowSize", time, 10.0, &self.expr) as f32;
1423 let g = comp.eval_number(node, "Gain", time, 2.0, &self.expr) as f32;
1424 let th = comp.eval_number(node, "Threshold", time, 0.0, &self.expr).clamp(0.0, 0.999) as f32;
1425 (sz, g, th, 0.0f32) // Screen blend
1426 } else {
1427 let sz = comp.eval_number(node, "GlowSize", time, 10.0, &self.expr) as f32;
1428 let glow_p = comp.eval_number(node, "Glow", time, 0.8, &self.expr).clamp(0.0, 0.999) as f32;
1429 let g = 1.0 / (1.0 - glow_p).max(1e-3);
1430 (sz, g, 0.0f32, 1.0f32) // Replace with blurred / (1 - Glow)
1431 };
1432 let size = (raw_size * scale_ref).max(0.0);
1433 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1434 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1435 let prev_sz = self.mask_target_size;
1436 self.mask_target_size = Some(src.size);
1437 let glow_mask = node
1438 .connected_node("GlowMask")
1439 .and_then(|s| comp.find_node(s))
1440 .map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats));
1441 self.mask_target_size = prev_sz;
1442 let gm_hash = glow_mask.as_ref().map_or(0, |m| m.content_hash);
1443
1444 let key = self.make_key(
1445 node,
1446 if is_soft_glow { "SoftGlow" } else { "Glow" },
1447 src.size,
1448 &[src.content_hash, mask_hash, gm_hash],
1449 &[size, gain, thresh, blend, combine_mode, if mask_inv { 1.0 } else { 0.0 }],
1450 );
1451 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1452 stats.cache_hits += 1;
1453 return hit;
1454 }
1455 stats.cache_misses += 1;
1456 stats.nodes_evaluated += 1;
1457
1458 // Pre-threshold and/or pre-mask the glow source before blurring
1459 let glow_src = if thresh > 1e-5 || glow_mask.is_some() {
1460 let prepped = create_texture(&self.device, src.size, 0);
1461 let mut up = UniformParams::default();
1462 up.p[0] = [thresh, 1.0, 1.0, if glow_mask.is_some() { 1.0 } else { 0.0 }];
1463 up.p[1] = [1.0, 0.0, 0.0, 0.0];
1464 let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1465 self.dispatch(enc, &self.pipelines.xglow_prep, &src.view, &self.dummy.view, gmv, &prepped, &up);
1466 prepped
1467 } else {
1468 src.clone()
1469 };
1470
1471 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
1472 let down = if self.hiq { 1u32 } else if size >= 14.0 { 4u32 } else if size >= 4.0 { 2u32 } else { 1u32 };
1473 let work_size = [(src.size[0] / down).max(1), (src.size[1] / down).max(1)];
1474
1475 let blurred_tex = if size < 0.25 {
1476 glow_src
1477 } else if down > 1 {
1478 let small = create_texture(&self.device, work_size, 0);
1479 let tmp1 = create_texture(&self.device, work_size, 0);
1480 let tmp2 = create_texture(&self.device, work_size, 0);
1481 let upscaled = create_texture(&self.device, src.size, 0);
1482 let mut u_blit = UniformParams::default();
1483 u_blit.p[0] = [1.0, 1.0, 0.0, 0.0];
1484 self.dispatch(enc, &self.pipelines.display_blit, &glow_src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit);
1485
1486 let mut uh = UniformParams::default();
1487 uh.p[0] = [1.0, 0.0, size / down as f32, 0.0];
1488 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1489 self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
1490
1491 let mut uv = UniformParams::default();
1492 uv.p[0] = [0.0, 1.0, size / down as f32, 0.0];
1493 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
1494 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
1495 self.dispatch(enc, &self.pipelines.display_blit, &tmp2.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit);
1496 upscaled
1497 } else {
1498 let tmp1 = create_texture(&self.device, src.size, 0);
1499 let tmp2 = create_texture(&self.device, src.size, 0);
1500 let mut uh = UniformParams::default();
1501 uh.p[0] = [1.0, 0.0, size, 0.0];
1502 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1503 self.dispatch(enc, &self.pipelines.blur, &glow_src.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
1504
1505 let mut uv = UniformParams::default();
1506 uv.p[0] = [0.0, 1.0, size, 0.0];
1507 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
1508 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
1509 tmp2
1510 };
1511
1512 let mut ug = UniformParams::default();
1513 ug.p[0] = [gain, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1514 ug.p[1] = [combine_mode, 0.0, 0.0, 0.0];
1515 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1516 self.dispatch(enc, &self.pipelines.glow_add, &src.view, &blurred_tex.view, mv, &dst, &ug);
1517 self.cache.insert(key, dst.clone(), node.id, frame_i);
1518 dst
1519 }
1520
1521 fn eval_xglow(
1522 &mut self,
1523 comp: &Comp,
1524 node: &Node,
1525 time: f64,
1526 frame_i: i64,
1527 enc: &mut wgpu::CommandEncoder,
1528 visiting: &mut HashSet<(NodeId, i64)>,
1529 stats: &mut EvalStats,
1530 ) -> CachedTexture {
1531 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1532 return self.dummy.clone();
1533 };
1534 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1535 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1536 if blend <= 1e-6 {
1537 return src;
1538 }
1539 let prev_sz = self.mask_target_size;
1540 self.mask_target_size = Some(src.size);
1541 let glow_mask = node
1542 .connected_node("GlowMask")
1543 .and_then(|s| comp.find_node(s))
1544 .map(|gid| self.eval_node(comp, gid, time, enc, visiting, stats));
1545 self.mask_target_size = prev_sz;
1546 let gm_hash = glow_mask.as_ref().map_or(0, |m| m.content_hash);
1547 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1548 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1549
1550 let mode = comp.eval_number(node, "Mode", time, 1.0, &self.expr).round() as i32; // 0=Expo, 1=Fib (default)
1551 let t_lo = comp.eval_number(node, "ThresholdLow", time, 0.0, &self.expr) as f32;
1552 let t_hi = comp.eval_number(node, "ThresholdHigh", time, 0.0, &self.expr) as f32;
1553 let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32;
1554 let src_sat = comp.eval_number(node, "SrcSat", time, 1.0, &self.expr) as f32;
1555 let glow_sat = comp.eval_number(node, "GlowSat", time, 1.0, &self.expr) as f32;
1556 let lock_xy = comp.eval_number(node, "LockXY", time, 1.0, &self.expr) > 0.5;
1557 let x_glow = comp.eval_number(node, "XGlowSize", time, 1.0, &self.expr) as f32;
1558 let y_glow = if lock_xy {
1559 x_glow
1560 } else {
1561 comp.eval_number(node, "YGlowSize", time, x_glow as f64, &self.expr) as f32
1562 };
1563 let raw_iters = (comp.eval_number(node, "Iterations", time, 12.0, &self.expr).round() as usize).clamp(1, 16);
1564 let iters = if self.hiq { raw_iters } else { raw_iters.min(5) };
1565 let falloff = (comp.eval_number(node, "Falloff", time, 1.0, &self.expr) as f32).max(0.05);
1566 let glow_only = comp.eval_number(node, "GlowOnly", time, 0.0, &self.expr) > 0.5;
1567 let grad = comp.eval_gradient(node, "Gradient", time);
1568
1569 let key = self.make_key(
1570 node,
1571 "MT_XGlow",
1572 src.size,
1573 &[src.content_hash, gm_hash, mask_hash],
1574 &[
1575 mode as f32, t_lo, t_hi, gain, src_sat, glow_sat, x_glow, y_glow,
1576 iters as f32, falloff, blend,
1577 if glow_only { 1.0 } else { 0.0 },
1578 if mask_inv { 1.0 } else { 0.0 },
1579 ],
1580 );
1581 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1582 stats.cache_hits += 1;
1583 return hit;
1584 }
1585 stats.cache_misses += 1;
1586 stats.nodes_evaluated += 1;
1587
1588 // 1. Preprocess glow source: Threshold -> Gain -> SrcSat -> GlowMask RGB multiply (verbatim MT_XGlow.fuse!)
1589 let prep = create_texture(&self.device, src.size, 0);
1590 let mut up = UniformParams::default();
1591 up.p[0] = [t_lo, t_hi, src_sat, if glow_mask.is_some() { 1.0 } else { 0.0 }];
1592 up.p[1] = [gain, 0.0, 0.0, 0.0];
1593 let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1594 self.dispatch(enc, &self.pipelines.xglow_prep, &src.view, &self.dummy.view, gmv, &prep, &up);
1595
1596 // 2. Build mip pyramid matching MT_XGlow.fuse (1x, 1/2, 1/4, 1/8, 1/16)
1597 let mut ub = UniformParams::default();
1598 ub.p[0] = [1.0, 1.0, 0.0, 0.0];
1599 let make_mip = |engine: &Self, enc: &mut wgpu::CommandEncoder, div: u32| -> CachedTexture {
1600 let ws = [(src.size[0] / div).max(1), (src.size[1] / div).max(1)];
1601 let t = create_texture(&engine.device, ws, 0);
1602 engine.dispatch(enc, &engine.pipelines.display_blit, &prep.view, &engine.dummy.view, &engine.dummy.view, &t, &ub);
1603 t
1604 };
1605 let half = if iters > 2 || !self.hiq { Some(make_mip(self, enc, 2)) } else { None };
1606 let quarter = if iters > 4 { Some(make_mip(self, enc, 4)) } else { None };
1607 let eighth = if iters > 8 { Some(make_mip(self, enc, 8)) } else { None };
1608 let sixteenth = if iters > 12 { Some(make_mip(self, enc, 16)) } else { None };
1609
1610 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];
1611 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];
1612
1613 // Fusion MT_XGlow: blur_x = XGlowSize / 720 (normalized to width -> * src.size[0] px)
1614 // Note: Fusion Gaussian BLUR_XSize=b has sigma ~= b * width * 0.45, matching blur_op directly!
1615 let base_rx = (x_glow / 720.0) * src.size[0] as f32;
1616 let base_ry = (y_glow / 720.0) * src.size[0] as f32;
1617
1618 let mut running: Option<CachedTexture> = if glow_only { None } else { Some(src.clone()) };
1619 for i in 1..=iters {
1620 let var = i as f32 / iters as f32;
1621 let mult = if mode == 1 { FIB[i - 1] } else { EXPO[i - 1] };
1622 let (mip_tex, div) = if i <= 2 && self.hiq {
1623 (&prep, 1.0_f32)
1624 } else if i <= 4 {
1625 (half.as_ref().unwrap_or(&prep), 2.0_f32)
1626 } else if i <= 8 {
1627 (quarter.as_ref().unwrap_or(&prep), 4.0_f32)
1628 } else if i <= 12 {
1629 (eighth.as_ref().unwrap_or(&prep), 8.0_f32)
1630 } else {
1631 (sixteenth.as_ref().unwrap_or(&prep), 16.0_f32)
1632 };
1633
1634 // MT_XGlow passes BLUR_XSize = blur_x * mult to the mip image (which is `div` times smaller,
1635 // so in mip pixels the radius is base_rx * mult / div!).
1636 let rx_mip = (base_rx * mult / div).max(0.0);
1637 let ry_mip = (base_ry * mult / div).max(0.0);
1638 let tmp1 = create_texture(&self.device, mip_tex.size, 0);
1639 let tmp2 = create_texture(&self.device, mip_tex.size, 0);
1640 let mut uh = UniformParams::default();
1641 uh.p[0] = [1.0, 0.0, rx_mip, 0.0];
1642 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1643 self.dispatch(enc, &self.pipelines.blur, &mip_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
1644 let mut uv = UniformParams::default();
1645 uv.p[0] = [0.0, 1.0, ry_mip, 0.0];
1646 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
1647 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
1648
1649 let gc = grad.as_ref().map_or([1.0, 1.0, 1.0, 1.0], |g| g.sample(var as f64));
1650 let falloff_scale = 1.0 / falloff.powi(i as i32);
1651 // Verbatim MT_XGlow.fuse line 422: m:Scale(1/(falloff^i), glowSat*var, glowSat*var, 1)
1652 let y_scale = falloff_scale;
1653 let uv_scale = glow_sat * var;
1654
1655 let is_last = i == iters && mask.is_none() && (blend - 1.0).abs() <= 1e-4;
1656 let next = create_texture_dod(
1657 &self.device,
1658 src.size,
1659 src.origin,
1660 src.canvas_size,
1661 if is_last { key } else { 0 },
1662 );
1663 let mut ua = UniformParams::default();
1664 ua.p[0] = [gc[0], gc[1], gc[2], y_scale];
1665 ua.p[1] = [uv_scale, if running.is_some() { 1.0 } else { 0.0 }, falloff_scale * 0.5, 0.0];
1666 let base_v = running.as_ref().map_or(&self.dummy.view, |r| &r.view);
1667 self.dispatch(enc, &self.pipelines.xglow_accum, base_v, &tmp2.view, &self.dummy.view, &next, &ua);
1668 running = Some(next);
1669 }
1670
1671 let glowed = running.unwrap_or_else(|| src.clone());
1672 let dst = if mask.is_some() || (blend - 1.0).abs() > 1e-4 {
1673 let final_dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
1674 let mut ug = UniformParams::default();
1675 ug.p[0] = [1.0, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1676 ug.p[1] = [1.0, 0.0, 0.0, 0.0];
1677 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1678 self.dispatch(enc, &self.pipelines.glow_add, &src.view, &glowed.view, mv, &final_dst, &ug);
1679 final_dst
1680 } else {
1681 glowed
1682 };
1683 self.cache.insert(key, dst.clone(), node.id, frame_i);
1684 dst
1685 }
1686
1687 fn eval_erode_dilate(
1688 &mut self,
1689 comp: &Comp,
1690 node: &Node,
1691 time: f64,
1692 frame_i: i64,
1693 enc: &mut wgpu::CommandEncoder,
1694 visiting: &mut HashSet<(NodeId, i64)>,
1695 stats: &mut EvalStats,
1696 ) -> CachedTexture {
1697 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1698 return self.dummy.clone();
1699 };
1700 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1701 let amt = comp.eval_number(node, "XAmount", time, 0.0, &self.expr) as f32;
1702 let radius = amt.abs() * src.size[0] as f32;
1703 let mode = if amt < 0.0 { 2.0 } else { 3.0 };
1704 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1705 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1706 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1707 let key = self.make_key(node, "ErodeDilate", src.size, &[src.content_hash, mask_hash], &[amt, blend, if mask_inv { 1.0 } else { 0.0 }]);
1708 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1709 stats.cache_hits += 1;
1710 return hit;
1711 }
1712 stats.cache_misses += 1;
1713 stats.nodes_evaluated += 1;
1714 let tmp = create_texture(&self.device, src.size, 0);
1715 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
1716 let mut uh = UniformParams::default();
1717 uh.p[0] = [1.0, 0.0, radius, mode];
1718 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1719 self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh);
1720 let mut uv = UniformParams::default();
1721 uv.p[0] = [0.0, 1.0, radius, mode];
1722 uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
1723 uv.p[2] = [1.0, 0.0, 0.0, 0.0]; // blend against original src in src_b!
1724 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1725 self.dispatch(enc, &self.pipelines.blur, &tmp.view, &src.view, mv, &dst, &uv);
1726 self.cache.insert(key, dst.clone(), node.id, frame_i);
1727 dst
1728 }
1729
1730 fn eval_fast_noise(
1731 &mut self,
1732 comp: &Comp,
1733 node: &Node,
1734 time: f64,
1735 frame_i: i64,
1736 comp_dims: [u32; 2],
1737 enc: &mut wgpu::CommandEncoder,
1738 stats: &mut EvalStats,
1739 ) -> CachedTexture {
1740 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
1741 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;
1742 let mut size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims };
1743 // Cap giant procedural sky-dome FastNoise textures (e.g. 11520x4000) to 4096 max dim keeping aspect!
1744 let max_dim = size[0].max(size[1]);
1745 if max_dim > 4096 {
1746 let scale = 4096.0 / max_dim as f32;
1747 size = [((size[0] as f32 * scale).round() as u32).max(1), ((size[1] as f32 * scale).round() as u32).max(1)];
1748 }
1749
1750 let lock_scale = comp.eval_number(node, "LockScale", time, 1.0, &self.expr) > 0.5;
1751 let x_scale = comp.eval_number(node, "XScale", time, 2.0, &self.expr) as f32;
1752 let y_scale = if lock_scale {
1753 x_scale
1754 } else {
1755 comp.eval_number(node, "YScale", time, x_scale as f64, &self.expr) as f32
1756 };
1757 let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32;
1758 let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32;
1759 let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32;
1760 let seethe = comp.eval_number(node, "Seethe", time, 0.0, &self.expr) as f32
1761 + (comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) as f32) * (time as f32) * 0.02;
1762 let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32;
1763 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1764 let inverted = comp.eval_number(node, "Inverted", time, 0.0, &self.expr) as f32;
1765
1766 let c1 = [
1767 comp.eval_number(node, "Color1Red", time, 0.0, &self.expr) as f32,
1768 comp.eval_number(node, "Color1Green", time, 0.0, &self.expr) as f32,
1769 comp.eval_number(node, "Color1Blue", time, 0.0, &self.expr) as f32,
1770 comp.eval_number(node, "Color1Alpha", time, 0.0, &self.expr) as f32,
1771 ];
1772 let c2 = [
1773 comp.eval_number(node, "Color2Red", time, 1.0, &self.expr) as f32,
1774 comp.eval_number(node, "Color2Green", time, 1.0, &self.expr) as f32,
1775 comp.eval_number(node, "Color2Blue", time, 1.0, &self.expr) as f32,
1776 comp.eval_number(node, "Color2Alpha", time, 1.0, &self.expr) as f32,
1777 ];
1778 let grad = comp.eval_gradient(node, "Gradient", time);
1779
1780 // Bake high-precision 256x1 RGBA gradient LUT so sharp thresholds (e.g. 0.95..0.96 stars) are exact!
1781 let mut grad_bytes = [0u8; 256 * 4];
1782 for i in 0..256 {
1783 let t = i as f64 / 255.0;
1784 let c = if let Some(g) = &grad {
1785 g.sample(t)
1786 } else {
1787 let tf = t as f32;
1788 [
1789 c1[0] + (c2[0] - c1[0]) * tf,
1790 c1[1] + (c2[1] - c1[1]) * tf,
1791 c1[2] + (c2[2] - c1[2]) * tf,
1792 c1[3] + (c2[3] - c1[3]) * tf,
1793 ]
1794 };
1795 grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8;
1796 grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8;
1797 grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8;
1798 grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8;
1799 }
1800 let mut gh = DefaultHasher::new();
1801 grad_bytes.hash(&mut gh);
1802 let grad_hash = gh.finish();
1803
1804 let mut u = UniformParams::default();
1805 u.p[0] = [x_scale, y_scale, detail, contrast];
1806 u.p[1] = [brightness, seethe, disc, center[0] as f32];
1807 u.p[2] = [center[1] as f32, 0.0, inverted, 1.0];
1808
1809 let key = self.make_key(node, "FastNoise", size, &[grad_hash], bytemuck::cast_slice(&u.p[..3]));
1810 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1811 stats.cache_hits += 1;
1812 return hit;
1813 }
1814 stats.cache_misses += 1;
1815 stats.nodes_evaluated += 1;
1816 let lut_tex = create_texture(&self.device, [256, 1], 0);
1817 self.queue.write_texture(
1818 lut_tex.texture.as_image_copy(),
1819 &grad_bytes,
1820 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
1821 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
1822 );
1823 let dst = create_texture(&self.device, size, key);
1824 self.dispatch(enc, &self.pipelines.fast_noise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u);
1825 self.cache.insert(key, dst.clone(), node.id, frame_i);
1826 dst
1827 }
1828
1829 fn eval_displace(
1830 &mut self,
1831 comp: &Comp,
1832 node: &Node,
1833 time: f64,
1834 frame_i: i64,
1835 enc: &mut wgpu::CommandEncoder,
1836 visiting: &mut HashSet<(NodeId, i64)>,
1837 stats: &mut EvalStats,
1838 ) -> CachedTexture {
1839 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1840 return self.dummy.clone();
1841 };
1842 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1843 let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else {
1844 return src;
1845 };
1846 let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats);
1847 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1848 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1849
1850 let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32;
1851 let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32;
1852 let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32;
1853 let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32;
1854 let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32;
1855 let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32;
1856 let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32;
1857 let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32;
1858 let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32;
1859 let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32;
1860 let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32;
1861 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1862 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1863
1864 let mut u = UniformParams::default();
1865 u.p[0] = [kind, xr, yr, xo];
1866 u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }];
1867 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset];
1868 u.p[3] = [center[0] as f32, center[1] as f32, xch, ych];
1869
1870 let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
1871 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1872 stats.cache_hits += 1;
1873 return hit;
1874 }
1875 stats.cache_misses += 1;
1876 stats.nodes_evaluated += 1;
1877 let dst = create_texture(&self.device, src.size, key);
1878 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1879 self.dispatch(enc, &self.pipelines.displace, &src.view, &fg.view, mv, &dst, &u);
1880 self.cache.insert(key, dst.clone(), node.id, frame_i);
1881 dst
1882 }
1883
1884 fn paint_mode_id(node: &Node) -> f32 {
1885 match node.static_str("PaintMode").unwrap_or("Merge") {
1886 "Add" => 1.0,
1887 "Subtract" => 2.0,
1888 "Multiply" => 3.0,
1889 "Minimum" => 4.0,
1890 "Maximum" => 5.0,
1891 "Invert" => 6.0,
1892 "Replace" => 7.0,
1893 _ => 0.0, // Merge
1894 }
1895 }
1896
1897 #[allow(clippy::too_many_arguments)]
1898 fn eval_mask_shape(
1899 &mut self,
1900 comp: &Comp,
1901 node: &Node,
1902 time: f64,
1903 frame_i: i64,
1904 comp_dims: [u32; 2],
1905 shape: u32,
1906 enc: &mut wgpu::CommandEncoder,
1907 visiting: &mut HashSet<(NodeId, i64)>,
1908 stats: &mut EvalStats,
1909 ) -> CachedTexture {
1910 let output_size_mode = node.static_str("OutputSize").unwrap_or("Default");
1911 let size = if output_size_mode != "Custom" {
1912 if let Some(ts) = self.mask_target_size {
1913 ts
1914 } else {
1915 let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32;
1916 let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32;
1917 if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }
1918 }
1919 } else {
1920 let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32;
1921 let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32;
1922 if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }
1923 };
1924 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1925 let mw = comp.eval_number(node, "Width", time, 0.5, &self.expr) as f32;
1926 let mh = comp.eval_number(node, "Height", time, 0.5, &self.expr) as f32;
1927 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
1928 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr) as f32;
1929 let corner = comp.eval_number(node, "CornerRadius", time, 0.0, &self.expr) as f32;
1930 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32;
1931 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;
1932 let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
1933 let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash);
1934 let paint_mode = Self::paint_mode_id(node);
1935
1936 let mut u = UniformParams::default();
1937 u.p[0] = [center[0] as f32, center[1] as f32, mw, mh];
1938 u.p[1] = [angle, soft, corner, invert];
1939 u.p[2] = [shape as f32, level, if prev_mask.is_some() { 1.0 } else { 0.0 }, paint_mode];
1940
1941 let key = self.make_key(node, "MaskShape", size, &[prev_hash], bytemuck::cast_slice(&u.p[..3]));
1942 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1943 stats.cache_hits += 1;
1944 return hit;
1945 }
1946 stats.cache_misses += 1;
1947 stats.nodes_evaluated += 1;
1948 let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1949 let soft_px = soft * size[0] as f32;
1950 let dst = if soft_px >= 0.75 {
1951 // Fusion Mask SoftEdge runs a true 2D Gaussian blur (sigma ~ 0.45 * SoftEdge * width)
1952 // over the sharp shape before Invert/Level/PaintMode combine!
1953 let raw = create_texture(&self.device, size, 0);
1954 let mut u_raw = u;
1955 u_raw.p[1] = [angle, 0.0, corner, 0.0];
1956 u_raw.p[2] = [shape as f32, 1.0, 0.0, 0.0];
1957 self.dispatch(enc, &self.pipelines.mask_shape, &self.dummy.view, &self.dummy.view, &self.dummy.view, &raw, &u_raw);
1958
1959 // Downsample for large SoftEdge radii (>24px or Fast mode) so 2048x2048 soft masks stay <0.5ms!
1960 let down = if !self.hiq && soft_px >= 12.0 {
1961 4u32
1962 } else if soft_px >= 48.0 {
1963 4u32
1964 } else if soft_px >= 20.0 {
1965 2u32
1966 } else {
1967 1u32
1968 };
1969 let blurred = if down > 1 {
1970 let ws = [(size[0] / down).max(1), (size[1] / down).max(1)];
1971 let small = create_texture(&self.device, ws, 0);
1972 let tmp1 = create_texture(&self.device, ws, 0);
1973 let tmp2 = create_texture(&self.device, ws, 0);
1974 let up = create_texture(&self.device, size, 0);
1975 let mut ub = UniformParams::default();
1976 ub.p[0] = [1.0, 1.0, 0.0, 0.0];
1977 self.dispatch(enc, &self.pipelines.display_blit, &raw.view, &self.dummy.view, &self.dummy.view, &small, &ub);
1978 let r_s = soft_px / down as f32;
1979 let mut uh = UniformParams::default();
1980 uh.p[0] = [1.0, 0.0, r_s, 0.0];
1981 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1982 self.dispatch(enc, &self.pipelines.blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
1983 let mut uv = UniformParams::default();
1984 uv.p[0] = [0.0, 1.0, r_s, 0.0];
1985 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
1986 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
1987 self.dispatch(enc, &self.pipelines.display_blit, &tmp2.view, &self.dummy.view, &self.dummy.view, &up, &ub);
1988 up
1989 } else {
1990 let tmp1 = create_texture(&self.device, size, 0);
1991 let tmp2 = create_texture(&self.device, size, 0);
1992 let mut uh = UniformParams::default();
1993 uh.p[0] = [1.0, 0.0, soft_px, 0.0];
1994 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
1995 self.dispatch(enc, &self.pipelines.blur, &raw.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
1996 let mut uv = UniformParams::default();
1997 uv.p[0] = [0.0, 1.0, soft_px, 0.0];
1998 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
1999 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
2000 tmp2
2001 };
2002
2003 let out_tex = create_texture(&self.device, size, key);
2004 let mut uc = UniformParams::default();
2005 uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }];
2006 self.dispatch(enc, &self.pipelines.mask_combine, &blurred.view, &self.dummy.view, mv, &out_tex, &uc);
2007 out_tex
2008 } else {
2009 let out_tex = create_texture(&self.device, size, key);
2010 self.dispatch(enc, &self.pipelines.mask_shape, &self.dummy.view, &self.dummy.view, mv, &out_tex, &u);
2011 out_tex
2012 };
2013 self.cache.insert(key, dst.clone(), node.id, frame_i);
2014 dst
2015 }
2016
2017 #[allow(clippy::too_many_arguments)]
2018 fn eval_polyline_mask(
2019 &mut self,
2020 comp: &Comp,
2021 node: &Node,
2022 time: f64,
2023 frame_i: i64,
2024 comp_dims: [u32; 2],
2025 enc: &mut wgpu::CommandEncoder,
2026 visiting: &mut HashSet<(NodeId, i64)>,
2027 stats: &mut EvalStats,
2028 ) -> CachedTexture {
2029 let has_explicit_w = node.inputs.contains_key("MaskWidth");
2030 let has_explicit_h = node.inputs.contains_key("MaskHeight");
2031 let size = if has_explicit_w || has_explicit_h {
2032 let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32;
2033 let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32;
2034 if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }
2035 } else {
2036 self.mask_target_size.unwrap_or(comp_dims)
2037 };
2038 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
2039 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;
2040 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;
2041 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;
2042 let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
2043 let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash);
2044 let paint_mode = Self::paint_mode_id(node);
2045
2046 let evaluated_pts: Vec<model::PolyPoint>;
2047 let points: &[model::PolyPoint] = if let Some(src) = node.connected_node("Polyline") {
2048 if let Some(pts) = comp.eval_polyline_spline(src, time) {
2049 evaluated_pts = pts;
2050 &evaluated_pts
2051 } else if let Some(pp) = comp.poly_paths.get(src) {
2052 pp.points.as_slice()
2053 } else {
2054 &[]
2055 }
2056 } else if let Some(pl_tbl) = node
2057 .raw
2058 .get_table("Inputs")
2059 .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine")))
2060 .and_then(|p| p.get_table("Value"))
2061 {
2062 evaluated_pts = model::PolyPath::parse_polyline_table(pl_tbl).1;
2063 &evaluated_pts
2064 } else {
2065 &[]
2066 };
2067
2068 let mut hash_floats = Vec::with_capacity(6 + points.len() * 6);
2069 hash_floats.extend_from_slice(&[
2070 center[0] as f32,
2071 center[1] as f32,
2072 soft,
2073 if invert { 1.0 } else { 0.0 },
2074 level,
2075 paint_mode,
2076 ]);
2077 for p in points {
2078 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]);
2079 }
2080 let key = self.make_key(node, "PolylineMask", size, &[prev_hash], &hash_floats);
2081 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2082 stats.cache_hits += 1;
2083 return hit;
2084 }
2085 stats.cache_misses += 1;
2086 stats.nodes_evaluated += 1;
2087
2088 let soft_px = soft * size[0] as f32 * 1.14;
2089 let need_post = soft_px >= 0.35 || prev_mask.is_some();
2090 let pixels = rasterize_polyline_mask(
2091 size,
2092 points,
2093 [center[0] as f32, center[1] as f32],
2094 if need_post { false } else { invert },
2095 if need_post { 1.0 } else { level },
2096 );
2097 let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key });
2098 self.queue.write_texture(
2099 raw_tex.texture.as_image_copy(),
2100 &pixels,
2101 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size[0] * 4), rows_per_image: Some(size[1]) },
2102 wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
2103 );
2104 let tex = if need_post {
2105 let blurred = if soft_px >= 0.35 {
2106 let tmp1 = create_texture(&self.device, size, 0);
2107 let tmp2 = create_texture(&self.device, size, 0);
2108 let mut uh = UniformParams::default();
2109 uh.p[0] = [1.0, 0.0, soft_px, 0.0];
2110 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
2111 self.dispatch(enc, &self.pipelines.blur, &raw_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
2112 let mut uv = UniformParams::default();
2113 uv.p[0] = [0.0, 1.0, soft_px, 0.0];
2114 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
2115 self.dispatch(enc, &self.pipelines.blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
2116 tmp2
2117 } else {
2118 raw_tex
2119 };
2120 let combined = create_texture(&self.device, size, key);
2121 let mut u = UniformParams::default();
2122 u.p[0] = [
2123 paint_mode,
2124 if invert { 1.0 } else { 0.0 },
2125 level,
2126 if prev_mask.is_some() { 1.0 } else { 0.0 },
2127 ];
2128 let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2129 self.dispatch(enc, &self.pipelines.mask_combine, &blurred.view, &self.dummy.view, mv, &combined, &u);
2130 combined
2131 } else {
2132 raw_tex
2133 };
2134 self.cache.insert(key, tex.clone(), node.id, frame_i);
2135 tex
2136 }
2137
2138 fn eval_bitmap_mask(
2139 &mut self,
2140 comp: &Comp,
2141 node: &Node,
2142 time: f64,
2143 enc: &mut wgpu::CommandEncoder,
2144 visiting: &mut HashSet<(NodeId, i64)>,
2145 stats: &mut EvalStats,
2146 ) -> CachedTexture {
2147 if let Some(src_id) = node.connected_node("Image").and_then(|s| comp.find_node(s)) {
2148 self.eval_node(comp, src_id, time, enc, visiting, stats)
2149 } else {
2150 self.dummy.clone()
2151 }
2152 }
2153
2154 fn eval_text_plus(
2155 &mut self,
2156 comp: &Comp,
2157 node: &Node,
2158 time: f64,
2159 frame_i: i64,
2160 comp_dims: [u32; 2],
2161 enc: &mut wgpu::CommandEncoder,
2162 stats: &mut EvalStats,
2163 ) -> CachedTexture {
2164 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
2165 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;
2166 let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims };
2167
2168 let text_str = comp.eval_text(node, "StyledText", time, "", &self.expr);
2169 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue");
2170 let font_style = node.static_str("Style").unwrap_or("Regular");
2171 let size_norm = comp.eval_number(node, "Size", time, 0.08, &self.expr) as f32;
2172 let tracking = comp.eval_number(node, "CharacterSpacing", time, 1.0, &self.expr) as f32;
2173 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
2174 // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center (default), +1=Right
2175 let h_lcr = comp.eval_number(node, "HorizontalLeftCenterRight", time, 0.0, &self.expr) as f32;
2176 let v_tcb = comp.eval_number(node, "VerticalTopCenterBottom", time, 0.0, &self.expr) as f32;
2177
2178 let fill_rgba = [
2179 comp.eval_number(node, "Red1", time, 1.0, &self.expr) as f32,
2180 comp.eval_number(node, "Green1", time, 1.0, &self.expr) as f32,
2181 comp.eval_number(node, "Blue1", time, 1.0, &self.expr) as f32,
2182 comp.eval_number(node, "Alpha1", time, 1.0, &self.expr) as f32,
2183 ];
2184 let outline_enabled = comp.eval_number(node, "Enabled2", time, 0.0, &self.expr) > 0.5;
2185 let outline_rgba = [
2186 comp.eval_number(node, "Red2", time, 1.0, &self.expr) as f32,
2187 comp.eval_number(node, "Green2", time, 0.0, &self.expr) as f32,
2188 comp.eval_number(node, "Blue2", time, 0.0, &self.expr) as f32,
2189 comp.eval_number(node, "Alpha2", time, 1.0, &self.expr) as f32,
2190 ];
2191 let outline_thickness = comp.eval_number(node, "Thickness2", time, 0.02, &self.expr) as f32;
2192 let write_start = comp.eval_number(node, "Start", time, 0.0, &self.expr) as f32;
2193 let write_end = comp.eval_number(node, "End", time, 1.0, &self.expr) as f32;
2194 let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, &self.expr) as f32;
2195 let cls_entries = comp.text_cls_entries(node, "StyledText");
2196
2197 let mut kh = DefaultHasher::new();
2198 self.cache.gpu_salt.hash(&mut kh);
2199 self.cache.node_salt(node.id).hash(&mut kh);
2200 "TextPlus".hash(&mut kh);
2201 size.hash(&mut kh);
2202 text_str.hash(&mut kh);
2203 font_family.hash(&mut kh);
2204 font_style.hash(&mut kh);
2205 outline_enabled.hash(&mut kh);
2206 cls_entries.len().hash(&mut kh);
2207 for v in [
2208 size_norm, tracking, center[0] as f32, center[1] as f32, h_lcr, v_tcb,
2209 fill_rgba[0], fill_rgba[1], fill_rgba[2], fill_rgba[3],
2210 outline_rgba[0], outline_rgba[1], outline_rgba[2], outline_rgba[3],
2211 outline_thickness, write_start, write_end, shear_x,
2212 ] {
2213 v.to_bits().hash(&mut kh);
2214 }
2215 let key = kh.finish();
2216
2217 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2218 stats.cache_hits += 1;
2219 return hit;
2220 }
2221 stats.cache_misses += 1;
2222 stats.nodes_evaluated += 1;
2223
2224 let outline_radius = if outline_enabled && outline_thickness > 1e-4 {
2225 (outline_thickness * size_norm * size[0] as f32 * 0.50).clamp(1.0, 28.0)
2226 } else {
2227 0.0
2228 };
2229 let (tex_size, origin, pixels) = rasterize_text_plus(
2230 size,
2231 &TextPlusParams {
2232 text: &text_str,
2233 font_family,
2234 font_style,
2235 size_norm,
2236 tracking,
2237 center: [center[0] as f32, center[1] as f32],
2238 h_lcr,
2239 v_tcb,
2240 fill_rgba,
2241 write_on_start: write_start,
2242 write_on_end: write_end,
2243 shear_x,
2244 cls: cls_entries,
2245 },
2246 outline_radius.ceil() as i32 + 2,
2247 );
2248 let fill_tex = create_texture_dod(
2249 &self.device,
2250 tex_size,
2251 origin,
2252 size,
2253 if outline_enabled { 0 } else { key },
2254 );
2255 self.queue.write_texture(
2256 fill_tex.texture.as_image_copy(),
2257 &pixels,
2258 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) },
2259 wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 },
2260 );
2261
2262 let final_tex = if outline_radius > 0.0 {
2263 // Single-pass circular Euclidean L2 outline + fill-over-outline composite across DoD!
2264 let dst = create_texture_dod(&self.device, tex_size, origin, size, key);
2265 let mut u = UniformParams::default();
2266 u.p[0] = outline_rgba;
2267 u.p[1] = [outline_radius, 0.0, 0.0, 0.0];
2268 self.dispatch(enc, &self.pipelines.text_outline, &fill_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u);
2269 dst
2270 } else {
2271 fill_tex
2272 };
2273
2274 self.cache.insert(key, final_tex.clone(), node.id, frame_i);
2275 final_tex
2276 }
2277
2278 fn eval_colorize(
2279 &mut self,
2280 comp: &Comp,
2281 node: &Node,
2282 time: f64,
2283 frame_i: i64,
2284 enc: &mut wgpu::CommandEncoder,
2285 visiting: &mut HashSet<(NodeId, i64)>,
2286 stats: &mut EvalStats,
2287 ) -> CachedTexture {
2288 let Some(src_id) = node.connected_node("Image").or_else(|| node.connected_node("Input")).and_then(|s| comp.find_node(s)) else {
2289 return self.dummy.clone();
2290 };
2291 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2292 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2293 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2294
2295 let mut u = UniformParams::default();
2296 // Colorize.fuse defaults: Color 1 = (0,0,0,0), Color 2 = (1,1,1,1)
2297 u.p[0] = [
2298 comp.eval_number(node, "R1", time, 0.0, &self.expr) as f32,
2299 comp.eval_number(node, "G1", time, 0.0, &self.expr) as f32,
2300 comp.eval_number(node, "B1", time, 0.0, &self.expr) as f32,
2301 comp.eval_number(node, "A1", time, 0.0, &self.expr) as f32,
2302 ];
2303 u.p[1] = [
2304 comp.eval_number(node, "R2", time, 1.0, &self.expr) as f32,
2305 comp.eval_number(node, "G2", time, 1.0, &self.expr) as f32,
2306 comp.eval_number(node, "B2", time, 1.0, &self.expr) as f32,
2307 comp.eval_number(node, "A2", time, 1.0, &self.expr) as f32,
2308 ];
2309 u.p[2] = [
2310 comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32,
2311 if mask.is_some() { 1.0 } else { 0.0 },
2312 if mask_inv { 1.0 } else { 0.0 },
2313 0.0,
2314 ];
2315
2316 let key = self.make_key(node, "Fuse.Colorize", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
2317 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2318 stats.cache_hits += 1;
2319 return hit;
2320 }
2321 stats.cache_misses += 1;
2322 stats.nodes_evaluated += 1;
2323 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2324 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2325 self.dispatch(enc, &self.pipelines.colorize, &src.view, &self.dummy.view, mv, &dst, &u);
2326 self.cache.insert(key, dst.clone(), node.id, frame_i);
2327 dst
2328 }
2329
2330 fn eval_outline(
2331 &mut self,
2332 comp: &Comp,
2333 node: &Node,
2334 time: f64,
2335 frame_i: i64,
2336 enc: &mut wgpu::CommandEncoder,
2337 visiting: &mut HashSet<(NodeId, i64)>,
2338 stats: &mut EvalStats,
2339 ) -> CachedTexture {
2340 let Some(src_id) = node.connected_node("Image").or_else(|| node.connected_node("Input")).and_then(|s| comp.find_node(s)) else {
2341 return self.dummy.clone();
2342 };
2343 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2344 let amount = (comp.eval_number(node, "Amount", time, 0.05, &self.expr) as f32) / 10.0;
2345 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr) as f32;
2346 if amount <= 1e-5 {
2347 return src;
2348 }
2349 // Outline.fuse defaults: R=0, G=0, B=0, A=1
2350 let r = comp.eval_number(node, "Red", time, 0.0, &self.expr) as f32;
2351 let g = comp.eval_number(node, "Green", time, 0.0, &self.expr) as f32;
2352 let b = comp.eval_number(node, "Blue", time, 0.0, &self.expr) as f32;
2353 let a = comp.eval_number(node, "Alpha", time, 1.0, &self.expr) as f32;
2354
2355 let key = self.make_key(node, "Fuse.Outline", src.size, &[src.content_hash], &[amount, soft, r, g, b, a]);
2356 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2357 stats.cache_hits += 1;
2358 return hit;
2359 }
2360 stats.cache_misses += 1;
2361 stats.nodes_evaluated += 1;
2362
2363 // Outline.fuse multiplies alpha by 120 in float32, then runs BoxBlur(amount) and clamps to [0,1].
2364 // In int8 Rgba8Unorm, multiplying by 120 would clamp early, so a separable Dilate (mode=3)
2365 // of radius `amount * width` reproduces the exact float32 expansion faithfully!
2366 let radius_px = (amount * src.size[0] as f32).clamp(1.0, 96.0);
2367 let dil_h = create_texture(&self.device, src.size, 0);
2368 let dil_v = create_texture(&self.device, src.size, 0);
2369 let tinted = create_texture(&self.device, src.size, 0);
2370 let dst = create_texture(&self.device, src.size, key);
2371
2372 let u0 = UniformParams::default();
2373 let mut dh = UniformParams::default();
2374 dh.p[0] = [1.0, 0.0, radius_px, 3.0];
2375 dh.p[1] = [1.0, 0.0, 0.0, 0.0];
2376 self.dispatch(enc, &self.pipelines.blur, &src.view, &self.dummy.view, &self.dummy.view, &dil_h, &dh);
2377
2378 let mut dv = UniformParams::default();
2379 dv.p[0] = [0.0, 1.0, radius_px, 3.0];
2380 dv.p[1] = [1.0, 0.0, 0.0, 0.0];
2381 self.dispatch(enc, &self.pipelines.blur, &dil_h.view, &self.dummy.view, &self.dummy.view, &dil_v, &dv);
2382
2383 let mut ut = UniformParams::default();
2384 ut.p[0] = [r, g, b, a];
2385 ut.p[1] = [1.0, 0.0, 0.0, 0.0];
2386 self.dispatch(enc, &self.pipelines.outline_tint, &dil_v.view, &self.dummy.view, &self.dummy.view, &tinted, &ut);
2387
2388 let outline_tex = if soft > 1e-4 {
2389 let sr = (soft * radius_px).clamp(1.0, 96.0);
2390 let s1 = create_texture(&self.device, src.size, 0);
2391 let s2 = create_texture(&self.device, src.size, 0);
2392 let mut sh = UniformParams::default();
2393 sh.p[0] = [1.0, 0.0, sr, 1.0];
2394 sh.p[1] = [1.0, 0.0, 0.0, 0.0];
2395 self.dispatch(enc, &self.pipelines.blur, &tinted.view, &self.dummy.view, &self.dummy.view, &s1, &sh);
2396 let mut sv = UniformParams::default();
2397 sv.p[0] = [0.0, 1.0, sr, 1.0];
2398 sv.p[1] = [1.0, 0.0, 0.0, 0.0];
2399 self.dispatch(enc, &self.pipelines.blur, &s1.view, &self.dummy.view, &self.dummy.view, &s2, &sv);
2400 s2
2401 } else {
2402 tinted
2403 };
2404
2405 self.dispatch(enc, &self.pipelines.outline_composite, &outline_tex.view, &src.view, &self.dummy.view, &dst, &u0);
2406 self.cache.insert(key, dst.clone(), node.id, frame_i);
2407 dst
2408 }
2409
2410 fn eval_custom(
2411 &mut self,
2412 comp: &Comp,
2413 node: &Node,
2414 time: f64,
2415 frame_i: i64,
2416 comp_dims: [u32; 2],
2417 enc: &mut wgpu::CommandEncoder,
2418 visiting: &mut HashSet<(NodeId, i64)>,
2419 stats: &mut EvalStats,
2420 ) -> CachedTexture {
2421 let size = if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) {
2422 self.eval_node(comp, src_id, time, enc, visiting, stats).size
2423 } else {
2424 comp_dims
2425 };
2426 let n1 = comp.eval_number(node, "NumberIn1", time, 1.0, &self.expr) as f32;
2427 let n2 = comp.eval_number(node, "NumberIn2", time, 0.0, &self.expr) as f32;
2428 let red_expr = node.inputs.get("RedExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or("");
2429 let green_expr = node.inputs.get("GreenExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or("");
2430 let blue_expr = node.inputs.get("BlueExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or("");
2431 let wave_mode = |expr: &str| -> f32 {
2432 if !expr.contains("sin(") {
2433 0.0
2434 } else if expr.contains("y*w") || expr.contains("y * w") {
2435 2.0
2436 } else {
2437 1.0
2438 }
2439 };
2440 let rm = wave_mode(red_expr);
2441 let gm = wave_mode(green_expr);
2442 let bm = wave_mode(blue_expr);
2443 if rm > 0.5 || gm > 0.5 || bm > 0.5 {
2444 let mut u = UniformParams::default();
2445 // Fusion CustomTool `w` is Image1's full-res pixel width!
2446 let w_ref = (size[0] * self.proxy_scale.max(1)) as f32;
2447 u.p[0] = [n1, n2, w_ref, 0.0];
2448 u.p[1] = [rm, gm, bm, 1.0];
2449 let key = self.make_key(node, "CustomWave", size, &[], bytemuck::cast_slice(&u.p[..2]));
2450 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2451 stats.cache_hits += 1;
2452 return hit;
2453 }
2454 stats.cache_misses += 1;
2455 stats.nodes_evaluated += 1;
2456 let dst = create_texture(&self.device, size, key);
2457 self.dispatch(enc, &self.pipelines.custom_wave, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u);
2458 self.cache.insert(key, dst.clone(), node.id, frame_i);
2459 return dst;
2460 }
2461 if red_expr.contains("1-r1") || red_expr.contains("1 - r1") {
2462 return self.eval_invert(comp, node, time, frame_i, enc, visiting, stats);
2463 }
2464 // Fallback: passthrough Image1
2465 if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) {
2466 self.eval_node(comp, src_id, time, enc, visiting, stats)
2467 } else {
2468 self.dummy.clone()
2469 }
2470 }
2471
2472 fn eval_invert(
2473 &mut self,
2474 comp: &Comp,
2475 node: &Node,
2476 time: f64,
2477 frame_i: i64,
2478 enc: &mut wgpu::CommandEncoder,
2479 visiting: &mut HashSet<(NodeId, i64)>,
2480 stats: &mut EvalStats,
2481 ) -> CachedTexture {
2482 let Some(src_id) = node
2483 .connected_node("Input")
2484 .or_else(|| node.connected_node("Image1"))
2485 .and_then(|s| comp.find_node(s))
2486 else {
2487 return self.dummy.clone();
2488 };
2489 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2490 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2491 if blend <= 1e-6 {
2492 return src;
2493 }
2494 let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32;
2495 let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32;
2496 let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32;
2497 let proc_a = comp.eval_number(node, "ProcessAlpha", time, 0.0, &self.expr) as f32;
2498 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2499 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2500
2501 let mut u = UniformParams::default();
2502 u.p[0] = [proc_r, proc_g, proc_b, proc_a];
2503 u.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
2504 let key = self.make_key(node, "Invert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2]));
2505 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2506 stats.cache_hits += 1;
2507 return hit;
2508 }
2509 stats.cache_misses += 1;
2510 stats.nodes_evaluated += 1;
2511 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2512 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2513 self.dispatch(enc, &self.pipelines.invert, &src.view, &self.dummy.view, mv, &dst, &u);
2514 self.cache.insert(key, dst.clone(), node.id, frame_i);
2515 dst
2516 }
2517
2518 fn eval_color_gain(
2519 &mut self,
2520 comp: &Comp,
2521 node: &Node,
2522 time: f64,
2523 frame_i: i64,
2524 enc: &mut wgpu::CommandEncoder,
2525 visiting: &mut HashSet<(NodeId, i64)>,
2526 stats: &mut EvalStats,
2527 ) -> CachedTexture {
2528 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
2529 return self.dummy.clone();
2530 };
2531 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2532 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2533 if blend <= 1e-6 {
2534 return src;
2535 }
2536 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2537 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2538
2539 let high_hue = comp.eval_number(node, "HighHue", time, 0.0, &self.expr) as f32;
2540 let mid_hue = comp.eval_number(node, "MidHue", time, 0.0, &self.expr) as f32;
2541 let dark_hue = comp.eval_number(node, "DarkHue", time, 0.0, &self.expr) as f32;
2542 let sat_dark = comp.eval_number(node, "DarkSaturation", time, 1.0, &self.expr) as f32;
2543 let sat_mid = comp.eval_number(node, "MidSaturation", time, 1.0, &self.expr) as f32;
2544 let sat_high = comp.eval_number(node, "HighSaturation", time, 1.0, &self.expr) as f32;
2545 let gain_r = comp.eval_number(node, "GainRed", time, 1.0, &self.expr) as f32;
2546 let gain_g = comp.eval_number(node, "GainGreen", time, 1.0, &self.expr) as f32;
2547 let gain_b = comp.eval_number(node, "GainBlue", time, 1.0, &self.expr) as f32;
2548 let lift_r = comp.eval_number(node, "LiftRed", time, 0.0, &self.expr) as f32;
2549 let lift_g = comp.eval_number(node, "LiftGreen", time, 0.0, &self.expr) as f32;
2550 let lift_b = comp.eval_number(node, "LiftBlue", time, 0.0, &self.expr) as f32;
2551 let gamma_r = comp.eval_number(node, "GammaRed", time, 1.0, &self.expr) as f32;
2552 let gamma_g = comp.eval_number(node, "GammaGreen", time, 1.0, &self.expr) as f32;
2553 let gamma_b = comp.eval_number(node, "GammaBlue", time, 1.0, &self.expr) as f32;
2554 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
2555
2556 let mut u = UniformParams::default();
2557 u.p[0] = [gain_r, gain_g, gain_b, prediv];
2558 u.p[1] = [lift_r, lift_g, lift_b, blend];
2559 u.p[2] = [gamma_r, gamma_g, gamma_b, sat_mid];
2560 u.p[3] = [dark_hue, mid_hue, high_hue, if mask.is_some() { 1.0 } else { 0.0 }];
2561 u.p[4] = [if mask_inv { 1.0 } else { 0.0 }, sat_dark, sat_high, 0.0];
2562
2563 let key = self.make_key(node, "ColorGain", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
2564 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2565 stats.cache_hits += 1;
2566 return hit;
2567 }
2568 stats.cache_misses += 1;
2569 stats.nodes_evaluated += 1;
2570 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2571 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2572 self.dispatch(enc, &self.pipelines.color_gain, &src.view, &self.dummy.view, mv, &dst, &u);
2573 self.cache.insert(key, dst.clone(), node.id, frame_i);
2574 dst
2575 }
2576
2577 fn eval_color_curves(
2578 &mut self,
2579 comp: &Comp,
2580 node: &Node,
2581 time: f64,
2582 frame_i: i64,
2583 enc: &mut wgpu::CommandEncoder,
2584 visiting: &mut HashSet<(NodeId, i64)>,
2585 stats: &mut EvalStats,
2586 ) -> CachedTexture {
2587 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
2588 return self.dummy.clone();
2589 };
2590 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2591 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2592 if blend <= 1e-6 {
2593 return src;
2594 }
2595 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
2596 let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.0, &self.expr) as f32;
2597 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2598 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2599
2600 let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s));
2601 let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s));
2602 let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s));
2603 let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s));
2604 let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty());
2605
2606 let mut lut_bytes = [0u8; 256 * 4];
2607 for i in 0..256 {
2608 let x = i as f64 / 255.0;
2609 let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
2610 let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
2611 let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
2612 let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
2613 lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
2614 lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
2615 lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
2616 lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8;
2617 }
2618 let mut lh = DefaultHasher::new();
2619 lut_bytes.hash(&mut lh);
2620 let lut_hash = lh.finish();
2621
2622 let mut u = UniformParams::default();
2623 u.p[0] = [prediv, ignore_trans, blend, if mask.is_some() { 1.0 } else { 0.0 }];
2624 u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if apply_a { 1.0 } else { 0.0 }, 0.0, 0.0];
2625
2626 let key = self.make_key(
2627 node,
2628 "ColorCurves",
2629 src.size,
2630 &[src.content_hash, mask_hash, lut_hash],
2631 bytemuck::cast_slice(&u.p[..2]),
2632 );
2633 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2634 stats.cache_hits += 1;
2635 return hit;
2636 }
2637 stats.cache_misses += 1;
2638 stats.nodes_evaluated += 1;
2639
2640 let lut_tex = create_texture(&self.device, [256, 1], 0);
2641 self.queue.write_texture(
2642 lut_tex.texture.as_image_copy(),
2643 &lut_bytes,
2644 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
2645 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
2646 );
2647 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2648 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2649 self.dispatch(enc, &self.pipelines.color_curves, &src.view, &lut_tex.view, mv, &dst, &u);
2650 self.cache.insert(key, dst.clone(), node.id, frame_i);
2651 dst
2652 }
2653
2654 fn eval_xf_chroma(
2655 &mut self,
2656 comp: &Comp,
2657 node: &Node,
2658 time: f64,
2659 frame_i: i64,
2660 enc: &mut wgpu::CommandEncoder,
2661 visiting: &mut HashSet<(NodeId, i64)>,
2662 stats: &mut EvalStats,
2663 ) -> CachedTexture {
2664 let Some(src_id) = node
2665 .connected_node("Input")
2666 .or_else(|| node.connected_node("Image"))
2667 .and_then(|s| comp.find_node(s))
2668 else {
2669 return self.dummy.clone();
2670 };
2671 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2672 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2673 if blend <= 1e-6 {
2674 return src;
2675 }
2676 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2677 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2678
2679 let master = comp.eval_number(node, "MasterFactor", time, 1.0, &self.expr) as f32;
2680 let raw_center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
2681 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
2682 let use_sa = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, &self.expr) > 0.5;
2683 let (raw_xs, raw_ys) = if use_sa {
2684 let sz = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32;
2685 let asp = comp.eval_number(node, "Aspect", time, 1.0, &self.expr) as f32;
2686 (sz, sz * asp.max(1e-4))
2687 } else {
2688 (
2689 comp.eval_number(node, "XSize", time, 1.0, &self.expr) as f32,
2690 comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32,
2691 )
2692 };
2693 let raw_angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
2694
2695 let cx = (raw_center[0] as f32 - 0.5) * master + 0.5;
2696 let cy = (raw_center[1] as f32 - 0.5) * master + 0.5;
2697 let xs = (raw_xs - 1.0) * master + 1.0;
2698 let ys = (raw_ys - 1.0) * master + 1.0;
2699 let angle_rad = (raw_angle * master).to_radians();
2700
2701 let raw_steps = (comp.eval_number(node, "Steps", time, 8.0, &self.expr).round() as i32).clamp(1, 32);
2702 let steps = if self.hiq { raw_steps } else { raw_steps.min(6) } as f32;
2703 let acc_mode = comp.eval_number(node, "AccumulationMode", time, 0.0, &self.expr) as f32;
2704 let normalize = comp.eval_number(node, "NormalizeResult", time, 1.0, &self.expr) as f32;
2705 let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32;
2706 let gamma = comp.eval_number(node, "InputImageGamma", time, 1.0, &self.expr) as f32;
2707
2708 // Bake 256x1 RGBA gradient LUT (default XfChroma RGB rainbow if Gradient omitted)
2709 let grad = comp.eval_gradient(node, "Gradient", time);
2710 let mut grad_bytes = [0u8; 256 * 4];
2711 for i in 0..256 {
2712 let t = i as f64 / 255.0;
2713 let c = if let Some(g) = &grad {
2714 g.sample(t)
2715 } else if t <= 0.5 {
2716 let f = (t * 2.0) as f32;
2717 [1.0 - f, f, 0.0, 1.0]
2718 } else {
2719 let f = ((t - 0.5) * 2.0) as f32;
2720 [0.0, 1.0 - f, f, 1.0]
2721 };
2722 grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8;
2723 grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8;
2724 grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8;
2725 grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8;
2726 }
2727 let mut gh = DefaultHasher::new();
2728 grad_bytes.hash(&mut gh);
2729 let grad_hash = gh.finish();
2730
2731 let mut u = UniformParams::default();
2732 u.p[0] = [cx, cy, pivot[0] as f32, pivot[1] as f32];
2733 u.p[1] = [xs, ys, angle_rad, steps];
2734 u.p[2] = [acc_mode, normalize, gain, gamma];
2735 u.p[3] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
2736 if src.has_dod() {
2737 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];
2738 }
2739
2740 let key = self.make_key(
2741 node,
2742 "XfChroma",
2743 src.canvas_size,
2744 &[src.content_hash, mask_hash, grad_hash],
2745 bytemuck::cast_slice(&u.p[..5]),
2746 );
2747 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2748 stats.cache_hits += 1;
2749 return hit;
2750 }
2751 stats.cache_misses += 1;
2752 stats.nodes_evaluated += 1;
2753
2754 let grad_tex = create_texture(&self.device, [256, 1], 0);
2755 self.queue.write_texture(
2756 grad_tex.texture.as_image_copy(),
2757 &grad_bytes,
2758 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
2759 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
2760 );
2761 let dst = create_texture(&self.device, src.canvas_size, key);
2762 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2763 self.dispatch(enc, &self.pipelines.xf_chroma, &src.view, &grad_tex.view, mv, &dst, &u);
2764 self.cache.insert(key, dst.clone(), node.id, frame_i);
2765 dst
2766 }
2767
2768 fn eval_channel_boolean(
2769 &mut self,
2770 comp: &Comp,
2771 node: &Node,
2772 time: f64,
2773 frame_i: i64,
2774 enc: &mut wgpu::CommandEncoder,
2775 visiting: &mut HashSet<(NodeId, i64)>,
2776 stats: &mut EvalStats,
2777 ) -> CachedTexture {
2778 let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) else {
2779 return self.dummy.clone();
2780 };
2781 let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats);
2782 let op = comp.eval_number(node, "Operation", time, 0.0, &self.expr).round() as i32;
2783 let to_r = comp.eval_number(node, "ToRed", time, 0.0, &self.expr).round() as i32;
2784 let to_g = comp.eval_number(node, "ToGreen", time, 1.0, &self.expr).round() as i32;
2785 let to_b = comp.eval_number(node, "ToBlue", time, 2.0, &self.expr).round() as i32;
2786 let to_a = comp.eval_number(node, "ToAlpha", time, 3.0, &self.expr).round() as i32;
2787 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2788 if blend <= 1e-6 {
2789 return bg;
2790 }
2791 // Fast path: Copy BG R/G/B/A onto itself (e.g. ZBuffer-only ChannelBoolean)
2792 if op == 0 && to_r == 5 && to_g == 6 && to_b == 7 && to_a == 8 {
2793 return bg;
2794 }
2795 // When Foreground is unconnected, Fusion uses Background as Foreground
2796 let fg = if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
2797 self.eval_node(comp, fg_id, time, enc, visiting, stats)
2798 } else {
2799 bg.clone()
2800 };
2801 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats);
2802 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2803 let mut u = UniformParams::default();
2804 u.p[0] = [op as f32, to_r as f32, to_g as f32, to_b as f32];
2805 u.p[1] = [
2806 to_a as f32,
2807 blend,
2808 if mask.is_some() { 1.0 } else { 0.0 },
2809 if mask_inv { 1.0 } else { 0.0 },
2810 ];
2811 if fg.has_dod() {
2812 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];
2813 }
2814 let key = self.make_key(node, "ChannelBoolean", bg.size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
2815 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2816 stats.cache_hits += 1;
2817 return hit;
2818 }
2819 stats.cache_misses += 1;
2820 stats.nodes_evaluated += 1;
2821 let dst = create_texture(&self.device, bg.size, key);
2822 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2823 self.dispatch(enc, &self.pipelines.channel_boolean, &bg.view, &fg.view, mv, &dst, &u);
2824 self.cache.insert(key, dst.clone(), node.id, frame_i);
2825 dst
2826 }
2827
2828 fn eval_gamut_convert(
2829 &mut self,
2830 comp: &Comp,
2831 node: &Node,
2832 time: f64,
2833 frame_i: i64,
2834 enc: &mut wgpu::CommandEncoder,
2835 visiting: &mut HashSet<(NodeId, i64)>,
2836 stats: &mut EvalStats,
2837 ) -> CachedTexture {
2838 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
2839 return self.dummy.clone();
2840 };
2841 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2842 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2843 if blend <= 1e-6 {
2844 return src;
2845 }
2846 let map_space = |s: Option<&str>| -> f32 {
2847 match s.unwrap_or("NoChange") {
2848 "sRGB" => 1.0,
2849 "Rec709" | "Rec.709" => 2.0,
2850 _ => 0.0,
2851 }
2852 };
2853 let remove_gamma = comp.eval_number(node, "RemoveGamma", time, 1.0, &self.expr) > 0.5;
2854 let add_gamma = comp.eval_number(node, "AddGamma", time, 1.0, &self.expr) > 0.5;
2855 let src_sp = if remove_gamma { map_space(node.static_str("SourceSpace")) } else { 0.0 };
2856 let dst_sp = if add_gamma { map_space(node.static_str("OutputSpace")) } else { 0.0 };
2857 if src_sp == 0.0 && dst_sp == 0.0 {
2858 return src;
2859 }
2860 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 1.0, &self.expr) as f32;
2861 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2862 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2863
2864 let mut u = UniformParams::default();
2865 u.p[0] = [src_sp, dst_sp, prediv, blend];
2866 u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0];
2867 let key = self.make_key(node, "GamutConvert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2]));
2868 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2869 stats.cache_hits += 1;
2870 return hit;
2871 }
2872 stats.cache_misses += 1;
2873 stats.nodes_evaluated += 1;
2874 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2875 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2876 self.dispatch(enc, &self.pipelines.gamut_convert, &src.view, &self.dummy.view, mv, &dst, &u);
2877 self.cache.insert(key, dst.clone(), node.id, frame_i);
2878 dst
2879 }
2880
2881 fn eval_vari_blur(
2882 &mut self,
2883 comp: &Comp,
2884 node: &Node,
2885 time: f64,
2886 frame_i: i64,
2887 enc: &mut wgpu::CommandEncoder,
2888 visiting: &mut HashSet<(NodeId, i64)>,
2889 stats: &mut EvalStats,
2890 ) -> CachedTexture {
2891 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
2892 return self.dummy.clone();
2893 };
2894 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
2895 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
2896 if blend <= 1e-6 {
2897 return src;
2898 }
2899 let rx = (comp.eval_number(node, "XBlurSize", time, 1.0, &self.expr) as f32) * 2.0 / self.proxy_scale.max(1) as f32;
2900 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;
2901 let bmap = node
2902 .connected_node("BlurImage")
2903 .and_then(|s| comp.find_node(s))
2904 .map(|bid| self.eval_node(comp, bid, time, enc, visiting, stats));
2905 let bm_hash = bmap.as_ref().map_or(0, |b| b.content_hash);
2906 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2907 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2908 let rings = if self.hiq { 3.0 } else { 2.0 };
2909
2910 let mut u = UniformParams::default();
2911 u.p[0] = [rx, ry, if bmap.is_some() { 1.0 } else { 0.0 }, blend];
2912 u.p[1] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, rings, 0.0];
2913 let key = self.make_key(node, "VariBlur", src.size, &[src.content_hash, bm_hash, mask_hash], bytemuck::cast_slice(&u.p[..2]));
2914 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
2915 stats.cache_hits += 1;
2916 return hit;
2917 }
2918 stats.cache_misses += 1;
2919 stats.nodes_evaluated += 1;
2920 let dst = create_texture_dod(&self.device, src.size, src.origin, src.canvas_size, key);
2921 let bv = bmap.as_ref().map_or(&self.dummy.view, |b| &b.view);
2922 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
2923 self.dispatch(enc, &self.pipelines.vari_blur, &src.view, bv, mv, &dst, &u);
2924 self.cache.insert(key, dst.clone(), node.id, frame_i);
2925 dst
2926 }
2927
2928 #[allow(clippy::too_many_arguments)]
2929 fn eval_renderer3d(
2930 &mut self,
2931 comp: &Comp,
2932 node: &Node,
2933 time: f64,
2934 frame_i: i64,
2935 comp_dims: [u32; 2],
2936 enc: &mut wgpu::CommandEncoder,
2937 visiting: &mut HashSet<(NodeId, i64)>,
2938 stats: &mut EvalStats,
2939 ) -> CachedTexture {
2940 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
2941 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;
2942 let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims };
2943 let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4);
2944
2945 let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
2946 return create_texture(&self.device, size, 0);
2947 };
2948
2949 let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5;
2950 let mut cameras = Vec::new();
2951 let mut mesh_specs = Vec::new();
2952 let mut lights = crate::scene3d::SceneLights::default();
2953 crate::scene3d::collect_scene(
2954 comp,
2955 scene_id,
2956 time,
2957 &self.expr,
2958 crate::scene3d::mat4_identity(),
2959 aspect,
2960 &mut cameras,
2961 &mut mesh_specs,
2962 &mut lights,
2963 0,
2964 );
2965
2966 let (view, proj, cam_pos) = if let Some(cam) = cameras.first() {
2967 let v = crate::scene3d::mat4_inverse_rigid(cam.world);
2968 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);
2969 (v, p, [cam.world[12], cam.world[13], cam.world[14]])
2970 } else {
2971 let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0);
2972 let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0);
2973 (v, p, [0.0, 0.0, 5.0])
2974 };
2975 let view_proj = crate::scene3d::mat4_mul(proj, view);
2976
2977 let mut draw_meshes = Vec::with_capacity(mesh_specs.len());
2978 let mut upstream_hashes = Vec::with_capacity(mesh_specs.len());
2979 let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20);
2980 hash_floats.extend_from_slice(&view_proj);
2981 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
2982 hash_floats.extend_from_slice(&lights.ambient);
2983 hash_floats.extend_from_slice(&lights.dir_to_light);
2984 hash_floats.extend_from_slice(&lights.dir_color);
2985 for ms in mesh_specs {
2986 let tex = ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats));
2987 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));
2988 hash_floats.extend_from_slice(&ms.world);
2989 hash_floats.extend_from_slice(&ms.diffuse_col);
2990 draw_meshes.push(crate::scene3d::DrawMesh {
2991 world: ms.world,
2992 shape: ms.shape,
2993 tex,
2994 diffuse_col: ms.diffuse_col,
2995 roughness: ms.roughness,
2996 });
2997 }
2998
2999 let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats);
3000 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
3001 stats.cache_hits += 1;
3002 return hit;
3003 }
3004 stats.cache_misses += 1;
3005 stats.nodes_evaluated += 1;
3006
3007 let dst = create_texture(&self.device, size, key);
3008 self.scene3d.render_meshes(
3009 &self.device,
3010 &self.queue,
3011 enc,
3012 &dst,
3013 &self.dummy,
3014 view_proj,
3015 view,
3016 cam_pos,
3017 lights,
3018 lighting_enabled,
3019 &draw_meshes,
3020 );
3021 self.cache.insert(key, dst.clone(), node.id, frame_i);
3022 dst
3023 }
3024
3025 fn dispatch(
3026 &self,
3027 enc: &mut wgpu::CommandEncoder,
3028 pipeline: &wgpu::ComputePipeline,
3029 src_a: &wgpu::TextureView,
3030 src_b: &wgpu::TextureView,
3031 mask: &wgpu::TextureView,
3032 dst: &CachedTexture,
3033 params: &UniformParams,
3034 ) {
3035 self.dispatch_to_view(enc, pipeline, src_a, src_b, mask, &dst.view, dst.size, params);
3036 }
3037
3038 #[allow(clippy::too_many_arguments)]
3039 fn dispatch_to_view(
3040 &self,
3041 enc: &mut wgpu::CommandEncoder,
3042 pipeline: &wgpu::ComputePipeline,
3043 src_a: &wgpu::TextureView,
3044 src_b: &wgpu::TextureView,
3045 mask: &wgpu::TextureView,
3046 dst_view: &wgpu::TextureView,
3047 dst_size: [u32; 2],
3048 params: &UniformParams,
3049 ) {
3050 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
3051 label: Some("op-params"),
3052 size: std::mem::size_of::<UniformParams>() as u64,
3053 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
3054 mapped_at_creation: false,
3055 });
3056 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
3057
3058 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3059 label: Some("op-bg"),
3060 layout: &self.pipelines.bgl,
3061 entries: &[
3062 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
3063 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
3064 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
3065 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.pipelines.sampler) },
3066 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
3067 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
3068 ],
3069 });
3070
3071 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
3072 label: Some("comp-op"),
3073 timestamp_writes: None,
3074 });
3075 pass.set_pipeline(pipeline);
3076 pass.set_bind_group(0, &bg, &[]);
3077 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
3078 }
3079}
3080
3081pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture {
3082 create_texture_dod(device, size, [0, 0], size, content_hash)
3083}
3084
3085pub fn create_texture_dod(
3086 device: &wgpu::Device,
3087 size: [u32; 2],
3088 origin: [i32; 2],
3089 canvas_size: [u32; 2],
3090 content_hash: u64,
3091) -> CachedTexture {
3092 let clamped = [size[0].max(1), size[1].max(1)];
3093 let tex = device.create_texture(&wgpu::TextureDescriptor {
3094 label: Some("comp-tex"),
3095 size: wgpu::Extent3d {
3096 width: clamped[0],
3097 height: clamped[1],
3098 depth_or_array_layers: 1,
3099 },
3100 mip_level_count: 1,
3101 sample_count: 1,
3102 dimension: wgpu::TextureDimension::D2,
3103 format: wgpu::TextureFormat::Rgba8Unorm,
3104 usage: wgpu::TextureUsages::TEXTURE_BINDING
3105 | wgpu::TextureUsages::STORAGE_BINDING
3106 | wgpu::TextureUsages::COPY_SRC
3107 | wgpu::TextureUsages::COPY_DST
3108 | wgpu::TextureUsages::RENDER_ATTACHMENT,
3109 view_formats: &[],
3110 });
3111 CachedTexture::from_texture_dod(tex, clamped, origin, [canvas_size[0].max(1), canvas_size[1].max(1)], content_hash)
3112}
crates/engine/src/lib.rs created+7
...@@ -0,0 +1,7 @@
1pub mod cache;
2pub mod eval;
3pub mod media;
4pub mod scene3d;
5
6pub use cache::{CacheMode, CachedTexture, EvalStats, NodeCache};
7pub use eval::{DisplaySettings, Engine, create_texture};
crates/engine/src/media.rs created+658
...@@ -0,0 +1,658 @@
1//! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and
2//! CPU rasterizers (`TextPlus` via `knife/text` CoreText, `PolylineMask` via `zeno`).
3
4use model::{ClipSpec, ClsEntry, PolyPoint};
5use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8use std::sync::Arc;
9
10#[derive(Clone)]
11pub struct DecodedImage {
12 pub size: [u32; 2],
13 /// Premultiplied RGBA8 pixels, top-down.
14 pub rgba: Arc<Vec<u8>>,
15}
16
17#[derive(Clone, Copy, Debug)]
18struct VideoInfo {
19 width: u32,
20 height: u32,
21 fps: f64,
22 nb_frames: i64,
23}
24
25fn is_video_path(path: &Path) -> bool {
26 let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
27 return false;
28 };
29 matches!(
30 ext.to_ascii_lowercase().as_str(),
31 "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf"
32 )
33}
34
35fn probe_video(path: &Path) -> Option<VideoInfo> {
36 let out = Command::new("ffprobe")
37 .args([
38 "-v",
39 "error",
40 "-select_streams",
41 "v:0",
42 "-show_entries",
43 "stream=width,height,r_frame_rate,nb_frames",
44 "-of",
45 "default=noprint_wrappers=1",
46 ])
47 .arg(path)
48 .output()
49 .ok()?;
50 if !out.status.success() {
51 return None;
52 }
53 let text = String::from_utf8_lossy(&out.stdout);
54 let mut width = 0u32;
55 let mut height = 0u32;
56 let mut fps = 30.0_f64;
57 let mut nb_frames = 0i64;
58 for line in text.lines() {
59 if let Some((k, v)) = line.split_once('=') {
60 match k.trim() {
61 "width" => width = v.trim().parse().unwrap_or(0),
62 "height" => height = v.trim().parse().unwrap_or(0),
63 "nb_frames" => nb_frames = v.trim().parse().unwrap_or(0),
64 "r_frame_rate" => {
65 if let Some((n, d)) = v.trim().split_once('/') {
66 let num: f64 = n.parse().unwrap_or(30.0);
67 let den: f64 = d.parse().unwrap_or(1.0);
68 if den > 0.0 && num > 0.0 {
69 fps = num / den;
70 }
71 } else if let Ok(r) = v.trim().parse::<f64>() {
72 if r > 0.0 {
73 fps = r;
74 }
75 }
76 }
77 _ => {}
78 }
79 }
80 }
81 if width == 0 || height == 0 {
82 return None;
83 }
84 Some(VideoInfo { width, height, fps, nb_frames })
85}
86
87fn decode_video_frame(path: &Path, info: VideoInfo, frame_idx: i64) -> Option<Vec<u8>> {
88 let idx = frame_idx.max(0);
89 let ts = if idx == 0 {
90 0.0
91 } else {
92 ((idx as f64) - 0.005) / info.fps.max(1.0)
93 };
94 let out = Command::new("ffmpeg")
95 .args([
96 "-v",
97 "error",
98 "-ss",
99 &format!("{ts:.6}"),
100 "-i",
101 ])
102 .arg(path)
103 .args([
104 "-frames:v",
105 "1",
106 "-f",
107 "rawvideo",
108 "-pix_fmt",
109 "rgba",
110 "-",
111 ])
112 .output()
113 .ok()?;
114 if !out.status.success() {
115 return None;
116 }
117 let expected = (info.width as usize) * (info.height as usize) * 4;
118 if out.stdout.len() < expected {
119 return None;
120 }
121 let mut buf = out.stdout;
122 buf.truncate(expected);
123 Some(buf)
124}
125
126fn is_exr_path(path: &Path) -> bool {
127 path.extension()
128 .and_then(|e| e.to_str())
129 .is_some_and(|e| e.eq_ignore_ascii_case("exr"))
130}
131
132/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR
133/// into RGBA8 (`u8`, linear [0..1] clamped so downstream `GamutConvert` applies exact sRGB!).
134fn decode_exr_rgba(
135 path: &Path,
136 red_name: Option<&str>,
137 green_name: Option<&str>,
138 blue_name: Option<&str>,
139 alpha_name: Option<&str>,
140 post_multiply: bool,
141) -> Option<DecodedImage> {
142 use exr::prelude::*;
143 let img = read_all_flat_layers_from_file(path).ok()?;
144 let layer = img.layer_data.first()?;
145 let w = layer.size.width();
146 let h = layer.size.height();
147 if w == 0 || h == 0 {
148 return None;
149 }
150
151 let find_channel = |preferred: Option<&str>, fallbacks: &[&str]| -> Option<Vec<f32>> {
152 let mut names: Vec<&str> = Vec::new();
153 if let Some(p) = preferred {
154 names.push(p);
155 }
156 names.extend_from_slice(fallbacks);
157 for target in names {
158 for ch in &layer.channel_data.list {
159 let cname = ch.name.to_string();
160 if cname == target || cname.ends_with(&format!(".{target}")) {
161 let vals: Vec<f32> = ch.sample_data.values_as_f32().collect();
162 if vals.len() == w * h {
163 return Some(vals);
164 }
165 }
166 }
167 }
168 None
169 };
170
171 let ch_r = find_channel(red_name, &["ViewLayer.Combined.R", "Combined.R", "R", "r"])?;
172 let ch_g = find_channel(green_name, &["ViewLayer.Combined.G", "Combined.G", "G", "g"])
173 .unwrap_or_else(|| ch_r.clone());
174 let ch_b = find_channel(blue_name, &["ViewLayer.Combined.B", "Combined.B", "B", "b"])
175 .unwrap_or_else(|| ch_r.clone());
176 let ch_a = find_channel(alpha_name, &["ViewLayer.Combined.A", "Combined.A", "A", "a"]);
177
178 let mut raw = vec![0u8; w * h * 4];
179 for i in 0..(w * h) {
180 let a = ch_a.as_ref().map_or(1.0, |v| v[i]).clamp(0.0, 1.0);
181 let mut r = ch_r[i].clamp(0.0, 1.0);
182 let mut g = ch_g[i].clamp(0.0, 1.0);
183 let mut b = ch_b[i].clamp(0.0, 1.0);
184 if post_multiply && a < 1.0 {
185 r *= a;
186 g *= a;
187 b *= a;
188 }
189 raw[i * 4] = (r * 255.0 + 0.5) as u8;
190 raw[i * 4 + 1] = (g * 255.0 + 0.5) as u8;
191 raw[i * 4 + 2] = (b * 255.0 + 0.5) as u8;
192 raw[i * 4 + 3] = (a * 255.0 + 0.5) as u8;
193 }
194 Some(DecodedImage {
195 size: [w as u32, h as u32],
196 rgba: Arc::new(raw),
197 })
198}
199
200pub struct MediaCache {
201 images: HashMap<(PathBuf, i64), DecodedImage>,
202 video_info: HashMap<PathBuf, Option<VideoInfo>>,
203 total_bytes: u64,
204 budget_bytes: u64,
205 lru: HashMap<(PathBuf, i64), u64>,
206 tick: u64,
207}
208
209impl MediaCache {
210 pub fn new(budget_mb: u64) -> Self {
211 Self {
212 images: HashMap::new(),
213 video_info: HashMap::new(),
214 total_bytes: 0,
215 budget_bytes: budget_mb * 1024 * 1024,
216 lru: HashMap::new(),
217 tick: 0,
218 }
219 }
220
221 pub fn clear(&mut self) {
222 self.images.clear();
223 self.lru.clear();
224 self.total_bytes = 0;
225 }
226
227 pub fn entry_count(&self) -> usize {
228 self.images.len()
229 }
230
231 pub fn total_mb(&self) -> f64 {
232 self.total_bytes as f64 / (1024.0 * 1024.0)
233 }
234
235 fn insert_cached(&mut self, cache_key: (PathBuf, i64), decoded: DecodedImage) {
236 let bytes = decoded.rgba.len() as u64;
237 self.tick += 1;
238 if let Some(prev) = self.images.insert(cache_key.clone(), decoded) {
239 self.total_bytes = self.total_bytes.saturating_sub(prev.rgba.len() as u64);
240 }
241 self.lru.insert(cache_key, self.tick);
242 self.total_bytes += bytes;
243
244 while self.total_bytes > self.budget_bytes && self.images.len() > 2 {
245 let Some(oldest) = self.lru.iter().min_by_key(|&(_, &t)| t).map(|(k, _)| k.clone()) else {
246 break;
247 };
248 self.lru.remove(&oldest);
249 if let Some(rem) = self.images.remove(&oldest) {
250 self.total_bytes = self.total_bytes.saturating_sub(rem.rgba.len() as u64);
251 }
252 }
253 }
254
255 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.
256 /// Returns `(resolved_path, local_frame_idx, decoded_image, loaded_from_disk)`.
257 pub fn load_clip(
258 &mut self,
259 clip: &ClipSpec,
260 frame: i64,
261 post_multiply: bool,
262 exr_channels: [Option<&str>; 4],
263 ) -> Option<(PathBuf, i64, DecodedImage, bool)> {
264 let base = Path::new(&clip.filename);
265 if is_video_path(base) {
266 if !base.exists() {
267 return None;
268 }
269 // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast]
270 if clip.global_end >= clip.global_start && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) {
271 let min_f = clip.global_start - clip.extend_first.max(0);
272 let max_f = clip.global_end + clip.extend_last.max(0);
273 if frame < min_f || frame > max_f {
274 return None;
275 }
276 }
277 let base_buf = base.to_path_buf();
278 let info = if let Some(cached) = self.video_info.get(&base_buf).copied() {
279 cached?
280 } else {
281 let probed = probe_video(base);
282 self.video_info.insert(base_buf.clone(), probed);
283 probed?
284 };
285
286 let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1);
287 let trim_in = clip.trim_in.clamp(0, len - 1);
288 let trim_out = if clip.trim_out > 0 {
289 clip.trim_out.clamp(trim_in, len - 1)
290 } else {
291 len - 1
292 };
293 let span = (trim_out - trim_in + 1).max(1);
294 let mut rel = frame - clip.global_start;
295 if rel < 0 {
296 rel = 0;
297 } else if clip.loop_clip {
298 rel = rel.rem_euclid(span);
299 } else {
300 rel = rel.clamp(0, span - 1);
301 }
302 let idx = if clip.reverse { trim_out - rel } else { trim_in + rel };
303 let cache_key = (base_buf.clone(), idx);
304 if let Some(img) = self.images.get(&cache_key).cloned() {
305 self.tick += 1;
306 self.lru.insert(cache_key, self.tick);
307 return Some((base_buf, idx, img, false));
308 }
309 let raw = decode_video_frame(base, info, idx)?;
310 let decoded = DecodedImage {
311 size: [info.width, info.height],
312 rgba: Arc::new(raw),
313 };
314 self.insert_cached(cache_key, decoded.clone());
315 return Some((base_buf, idx, decoded, true));
316 }
317
318 let resolved = resolve_clip_path(clip, frame)?;
319 let cache_key = (resolved.clone(), -1);
320 if let Some(img) = self.images.get(&cache_key).cloned() {
321 self.tick += 1;
322 self.lru.insert(cache_key, self.tick);
323 return Some((resolved, -1, img, false));
324 }
325
326 let decoded = if is_exr_path(&resolved) {
327 // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply!
328 decode_exr_rgba(
329 &resolved,
330 exr_channels[0],
331 exr_channels[1],
332 exr_channels[2],
333 exr_channels[3],
334 false,
335 )?
336 } else {
337 let dyn_img = image::open(&resolved).ok()?;
338 let rgba_img = dyn_img.to_rgba8();
339 let size = [rgba_img.width(), rgba_img.height()];
340 let mut raw = rgba_img.into_raw();
341 if post_multiply {
342 for px in raw.chunks_exact_mut(4) {
343 let a = u16::from(px[3]);
344 if a < 255 {
345 px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8;
346 px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8;
347 px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8;
348 }
349 }
350 }
351 DecodedImage { size, rgba: Arc::new(raw) }
352 };
353 self.insert_cached(cache_key, decoded.clone());
354 Some((resolved, -1, decoded, true))
355 }
356}
357
358/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`.
359pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
360 let base = Path::new(&clip.filename);
361 let len = clip.length.unwrap_or(1);
362 let stem = base.file_stem()?.to_str()?;
363 let ext = base.extension().and_then(|e| e.to_str()).unwrap_or("");
364 let digit_start = stem.rfind(|c: char| !c.is_ascii_digit()).map(|i| i + 1).unwrap_or(0);
365 let prefix = &stem[..digit_start];
366 let digits = &stem[digit_start..];
367 let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty());
368 if !is_seq || digits.is_empty() {
369 return base.exists().then(|| base.to_path_buf());
370 }
371
372 let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 };
373 let len = len.max(1);
374 let trim_in = clip.trim_in.clamp(0, len - 1);
375 let trim_out = if clip.trim_out > 0 { clip.trim_out.clamp(trim_in, len - 1) } else { len - 1 };
376 let span = (trim_out - trim_in + 1).max(1);
377
378 let mut rel = frame - clip.global_start;
379 if clip.loop_clip {
380 rel = rel.rem_euclid(span);
381 } else {
382 rel = rel.clamp(0, span - 1);
383 }
384 let idx = if clip.reverse {
385 seq_start + trim_out - rel
386 } else {
387 seq_start + trim_in + rel
388 };
389
390 let width = digits.len();
391 let new_name = if ext.is_empty() {
392 format!("{prefix}{idx:0width$}")
393 } else {
394 format!("{prefix}{idx:0width$}.{ext}")
395 };
396 let candidate = base.with_file_name(new_name);
397 if candidate.exists() {
398 Some(candidate)
399 } else if base.exists() {
400 Some(base.to_path_buf())
401 } else {
402 None
403 }
404}
405
406/// Parameters for rasterizing a Fusion `TextPlus` node using `knife/text` (CoreText).
407pub struct TextPlusParams<'a> {
408 pub text: &'a str,
409 pub font_family: &'a str,
410 pub font_style: &'a str,
411 pub size_norm: f32, // Fusion Size (fraction of canvas width, ~0.08 default)
412 pub tracking: f32, // Fusion CharacterSpacing (1.0 = normal)
413 pub center: [f32; 2], // Fusion normalized Y-up (0.5, 0.5)
414 pub h_lcr: f32, // Fusion HorizontalLeftCenterRight: -1=Left, 0=Center, +1=Right
415 pub v_tcb: f32, // Fusion VerticalTopCenterBottom: -1=Top, 0=Center, +1=Bottom
416 pub fill_rgba: [f32; 4],
417 pub write_on_start: f32,
418 pub write_on_end: f32,
419 pub shear_x: f32, // Fusion CharacterShearX
420 pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides
421}
422
423/// Rasterizes a `TextPlus` fill layer into premultiplied RGBA8 with automatic Domain-of-Definition
424/// (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a downstream `Transform`)
425/// are never clipped. Returns `(tex_size, dod_origin_px, rgba)`.
426pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {
427 let [w, h] = dims;
428 if params.text.is_empty() || params.size_norm <= 1e-4 {
429 return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
430 }
431
432 // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on!
433 let total_chars = params.text.chars().count();
434 let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize;
435 let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize;
436 if c_start >= c_end || c_start >= total_chars {
437 return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
438 }
439
440 // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units).
441 let mut cls_dx = vec![0.0_f32; total_chars];
442 let mut cls_dy = vec![0.0_f32; total_chars];
443 for e in params.cls {
444 let s = e.start.min(total_chars);
445 let end = (e.end + 1).min(total_chars);
446 for i in s..end {
447 if e.prop_id == 1350 {
448 cls_dx[i] = e.value;
449 } else if e.prop_id == 1351 {
450 cls_dy[i] = e.value;
451 }
452 }
453 }
454
455 // Fusion Text+ `Size` is in frame-width units (calibrated across AT Name Sans / Helvetica / Liberation Sans:
456 // `0.68625 * w` equals `1.22 * h` on 16:9 and stays proportional on square/vertical frames!).
457 let font_px = (params.size_norm * w as f32 * 0.68625).clamp(6.0, 1024.0);
458 let weight = style_to_weight(params.font_style);
459 let italic = params.font_style.to_ascii_lowercase().contains("italic")
460 || params.font_style.to_ascii_lowercase().contains("oblique");
461
462 let families: Arc<[text::Family]> = if params.font_family.is_empty() {
463 Arc::from([text::Family::Sans])
464 } else {
465 Arc::from([
466 text::Family::Named(Arc::from(params.font_family)),
467 text::Family::Sans,
468 ])
469 };
470 let font = text::Font {
471 families,
472 size: font_px,
473 weight,
474 italic,
475 };
476 let handle = text::FontHandle::new(&font);
477 let metrics = handle.metrics();
478
479 // Extra tracking per glyph: Fusion `CharacterSpacing = 1.0` means 0 extra; >1.0 expands cleanly.
480 let extra_track = (params.tracking - 1.0) * font_px * 1.15;
481
482 let lines: Vec<&str> = params.text.split('\n').collect();
483 let line_height = (metrics.ascent + metrics.descent).max(font_px * 1.15);
484 let total_h = line_height * lines.len() as f32;
485
486 // Fusion Center is Y-up; convert to top-down pixel coordinates.
487 let cx = params.center[0] * w as f32;
488 let cy = (1.0 - params.center[1]) * h as f32;
489
490 let top_y = cy - total_h * (params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5);
491 let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5;
492 let fc = params.fill_rgba;
493 let shear_x = params.shear_x;
494
495 // Pass 1: rasterize all visible glyphs & collect exact bounds to expand DoD if anything overflows canvas!
496 struct PlacedGlyph {
497 ox: i32,
498 oy: i32,
499 baseline_y: f32,
500 w: i32,
501 h: i32,
502 data: Vec<u8>,
503 }
504 let mut placed = Vec::new();
505 let mut min_x = 0i32;
506 let mut min_y = 0i32;
507 let mut max_x = w as i32;
508 let mut max_y = h as i32;
509
510 let mut char_cursor = 0usize;
511 for (li, line_str) in lines.iter().enumerate() {
512 let mut glyphs = Vec::new();
513 let mut pen_x = 0.0_f32;
514 for ch in line_str.chars() {
515 let idx = char_cursor;
516 char_cursor += 1;
517 let adv = handle.advance(ch);
518 if idx >= c_start && idx < c_end {
519 if let Some(gid) = handle.glyph(ch) {
520 glyphs.push((gid, pen_x, idx));
521 }
522 }
523 pen_x += adv + extra_track;
524 }
525 char_cursor += 1; // account for '\n' separator
526 let line_w = (pen_x - extra_track).max(0.0);
527 let start_x = cx - line_w * h_frac;
528 let baseline_y = top_y + (li as f32) * line_height + metrics.ascent;
529
530 for (gid, gx, idx) in glyphs {
531 let Some(mask) = handle.rasterize(gid, 1.0, [0, 0]) else { continue };
532 let cdx = cls_dx[idx] * w as f32;
533 let cdy = -cls_dy[idx] * w as f32;
534 let ox = (start_x + gx + cdx).round() as i32 + mask.left;
535 let g_base_y = baseline_y + cdy;
536 let oy = g_base_y.round() as i32 - mask.top;
537 let mw = mask.width as i32;
538 let mh = mask.height as i32;
539 let shear_pad = (shear_x.abs() * mh as f32).ceil() as i32;
540 if mw > 0 && mh > 0 {
541 min_x = min_x.min(ox - outline_pad - shear_pad);
542 min_y = min_y.min(oy - outline_pad);
543 max_x = max_x.max(ox + mw + outline_pad + shear_pad);
544 max_y = max_y.max(oy + mh + outline_pad);
545 placed.push(PlacedGlyph { ox, oy, baseline_y: g_base_y, w: mw, h: mh, data: mask.data });
546 }
547 }
548 }
549
550 // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded.
551 let origin_x = min_x.max(-(w as i32));
552 let origin_y = min_y.max(-(h as i32));
553 let end_x = max_x.min((w as i32) * 2);
554 let end_y = max_y.min((h as i32) * 2);
555 let tw = (end_x - origin_x).max(1) as u32;
556 let th = (end_y - origin_y).max(1) as u32;
557 let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
558
559 for g in placed {
560 for my in 0..g.h {
561 let py = g.oy + my;
562 let dy = py - origin_y;
563 if dy < 0 || dy >= th as i32 { continue; }
564 let row_shear = if shear_x.abs() > 1e-4 {
565 (-((g.baseline_y - py as f32) * shear_x)).round() as i32
566 } else {
567 0
568 };
569 for mx in 0..g.w {
570 let dx = g.ox + mx + row_shear - origin_x;
571 if dx < 0 || dx >= tw as i32 { continue; }
572 let cov = g.data[(my * g.w + mx) as usize];
573 if cov > 0 {
574 let i = ((dy as usize) * (tw as usize) + (dx as usize)) * 4;
575 let a = (cov as f32 / 255.0) * fc[3];
576 let prev_a = out[i + 3] as f32 / 255.0;
577 let na = a.max(prev_a);
578 out[i] = (fc[0] * na * 255.0).clamp(0.0, 255.0) as u8;
579 out[i + 1] = (fc[1] * na * 255.0).clamp(0.0, 255.0) as u8;
580 out[i + 2] = (fc[2] * na * 255.0).clamp(0.0, 255.0) as u8;
581 out[i + 3] = (na * 255.0).clamp(0.0, 255.0) as u8;
582 }
583 }
584 }
585 }
586
587 ([tw, th], [origin_x, origin_y], out)
588}
589
590fn style_to_weight(style: &str) -> u16 {
591 let s = style.to_ascii_lowercase();
592 if s.contains("black") || s.contains("heavy") { 900 }
593 else if s.contains("extrabold") || s.contains("ultrabold") { 800 }
594 else if s.contains("bold") { 700 }
595 else if s.contains("semibold") || s.contains("demi") { 600 }
596 else if s.contains("medium") { 500 }
597 else if s.contains("light") { 300 }
598 else if s.contains("thin") || s.contains("hairline") { 100 }
599 else { 400 }
600}
601
602/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`.
603pub fn rasterize_polyline_mask(
604 dims: [u32; 2],
605 points: &[PolyPoint],
606 center: [f32; 2],
607 invert: bool,
608 level: f32,
609) -> Vec<u8> {
610 let [w, h] = dims;
611 let mut out = vec![0u8; (w as usize) * (h as usize) * 4];
612 if points.len() < 2 {
613 return out;
614 }
615 let to_px = |x: f64, y: f64| -> [f32; 2] {
616 let fx = (center[0] + x as f32) * w as f32;
617 let fy = (1.0 - (center[1] + y as f32)) * h as f32;
618 [fx, fy]
619 };
620 let mut cmds = Vec::new();
621 let p0 = to_px(points[0].x, points[0].y);
622 cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1])));
623 for i in 0..points.len() {
624 let a = &points[i];
625 let b = &points[(i + 1) % points.len()];
626 let c1 = to_px(a.x + a.rx, a.y + a.ry);
627 let c2 = to_px(b.x + b.lx, b.y + b.ly);
628 let p = to_px(b.x, b.y);
629 if a.linear && b.linear {
630 cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1])));
631 } else {
632 cmds.push(zeno::Command::CurveTo(
633 zeno::Vector::new(c1[0], c1[1]),
634 zeno::Vector::new(c2[0], c2[1]),
635 zeno::Vector::new(p[0], p[1]),
636 ));
637 }
638 }
639 cmds.push(zeno::Command::Close);
640
641 let mut mask = vec![0u8; (w as usize) * (h as usize)];
642 let mut scratch = zeno::Scratch::new();
643 let placement = zeno::Mask::with_scratch(&cmds, &mut scratch)
644 .size(w, h)
645 .origin(zeno::Origin::TopLeft)
646 .render_into(&mut mask, None);
647 let _ = placement;
648 for (i, &cov) in mask.iter().enumerate() {
649 let mut a = cov as f32 / 255.0;
650 if invert { a = 1.0 - a; }
651 let b = (a * level * 255.0).clamp(0.0, 255.0) as u8;
652 out[i * 4] = b;
653 out[i * 4 + 1] = b;
654 out[i * 4 + 2] = b;
655 out[i * 4 + 3] = b;
656 }
657 out
658}
crates/engine/src/scene3d.rs created+903
...@@ -0,0 +1,903 @@
1//! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`,
2//! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`,
3//! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes.
4//!
5//! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system,
6//! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`,
7//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection.
8
9use crate::cache::CachedTexture;
10use bytemuck::{Pod, Zeroable};
11use model::{Comp, ExprEngine, Node, NodeId};
12
13pub type Mat4 = [f32; 16]; // Column-major 4x4
14
15#[repr(C)]
16#[derive(Clone, Copy, Pod, Zeroable)]
17struct Vertex3D {
18 pos: [f32; 3],
19 normal: [f32; 3],
20 uv: [f32; 2],
21}
22
23#[repr(C)]
24#[derive(Clone, Copy, Pod, Zeroable)]
25struct MeshUniform {
26 mvp: [f32; 16],
27 model: [f32; 16],
28 /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)
29 dod: [f32; 4],
30 /// `[use_tex, lighting_enabled, roughness, 0]`
31 flags: [f32; 4],
32 /// Diffuse color multiplier `(r, g, b, a)`
33 diffuse_col: [f32; 4],
34 /// Ambient light `(r, g, b, 0)`
35 ambient: [f32; 4],
36 /// Directional light direction TO light `(dx, dy, dz, has_dir)`
37 dir_to_light: [f32; 4],
38 /// Directional light color * intensity `(r, g, b, 0)`
39 dir_color: [f32; 4],
40 /// Camera world position `(cx, cy, cz, 0)`
41 cam_pos: [f32; 4],
42}
43
44const SHADER_3D: &str = r#"
45struct MeshUniform {
46 mvp: mat4x4<f32>,
47 model: mat4x4<f32>,
48 dod: vec4<f32>,
49 flags: vec4<f32>,
50 diffuse_col: vec4<f32>,
51 ambient: vec4<f32>,
52 dir_to_light: vec4<f32>,
53 dir_color: vec4<f32>,
54 cam_pos: vec4<f32>,
55};
56
57@group(0) @binding(0) var<uniform> u: MeshUniform;
58@group(0) @binding(1) var mat_tex: texture_2d<f32>;
59@group(0) @binding(2) var mat_samp: sampler;
60
61struct VsIn {
62 @location(0) pos: vec3<f32>,
63 @location(1) normal: vec3<f32>,
64 @location(2) uv: vec2<f32>,
65};
66
67struct VsOut {
68 @builtin(position) clip: vec4<f32>,
69 @location(0) uv: vec2<f32>,
70 @location(1) world_pos: vec3<f32>,
71 @location(2) world_n: vec3<f32>,
72};
73
74@vertex
75fn vs_mesh(v: VsIn) -> VsOut {
76 var out: VsOut;
77 let wp = u.model * vec4<f32>(v.pos, 1.0);
78 out.clip = u.mvp * vec4<f32>(v.pos, 1.0);
79 out.uv = v.uv;
80 out.world_pos = wp.xyz;
81 let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz;
82 let nlen = length(wn);
83 out.world_n = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);
84 return out;
85}
86
87@fragment
88fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
89 var col = u.diffuse_col;
90 if (u.flags.x > 0.5) {
91 var uv = in.uv;
92 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
93 let tdims = vec2<f32>(textureDimensions(mat_tex));
94 let canvas_px = vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w);
95 uv = (canvas_px - u.dod.xy) / tdims;
96 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
97 discard;
98 }
99 }
100 col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col;
101 }
102 if (col.a <= 0.002) {
103 discard;
104 }
105
106 if (u.flags.y > 0.5) {
107 // Premultiplied -> unpremultiplied albedo for lighting
108 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
109 let n = normalize(in.world_n);
110 var lit = albedo * u.ambient.rgb;
111 if (u.dir_to_light.w > 0.5) {
112 let l = normalize(u.dir_to_light.xyz);
113 let ndotl = max(dot(n, l), 0.0);
114 lit = lit + albedo * u.dir_color.rgb * ndotl;
115 if (ndotl > 0.0) {
116 let v = normalize(u.cam_pos.xyz - in.world_pos);
117 let h = normalize(l + v);
118 let rough = clamp(u.flags.z, 0.05, 1.0);
119 let shininess = max(2.0 / (rough * rough) - 2.0, 2.0);
120 let spec = pow(max(dot(n, h), 0.0), shininess) * (1.0 - rough * 0.85) * 0.25;
121 lit = lit + u.dir_color.rgb * spec;
122 }
123 }
124 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);
125 }
126 return col;
127}
128"#;
129
130pub struct Scene3DRenderer {
131 bgl: wgpu::BindGroupLayout,
132 pipeline: wgpu::RenderPipeline,
133 sampler: wgpu::Sampler,
134}
135
136#[derive(Clone)]
137pub struct CameraInstance {
138 pub world: Mat4,
139 pub vfov_rad: f32,
140 pub near: f32,
141 pub far: f32,
142}
143
144#[derive(Clone, Debug)]
145pub enum ShapeKind {
146 ImagePlane,
147 Sphere { radius: f32, sub_base: u32, sub_height: u32 },
148 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },
149 Plane { width: f32, height: f32 },
150 Cube { width: f32, height: f32, depth: f32 },
151}
152
153#[derive(Clone)]
154pub struct MeshInstance {
155 pub world: Mat4,
156 pub shape: ShapeKind,
157 pub material_node: Option<NodeId>,
158 pub diffuse_col: [f32; 4],
159 pub roughness: f32,
160}
161
162#[derive(Clone, Copy, Debug)]
163pub struct SceneLights {
164 pub ambient: [f32; 3],
165 pub dir_to_light: [f32; 3],
166 pub dir_color: [f32; 3],
167 pub has_dir: bool,
168}
169
170impl Default for SceneLights {
171 fn default() -> Self {
172 Self {
173 ambient: [0.0, 0.0, 0.0],
174 dir_to_light: [0.0, 0.0, 1.0],
175 dir_color: [0.0, 0.0, 0.0],
176 has_dir: false,
177 }
178 }
179}
180
181pub struct DrawMesh {
182 pub world: Mat4,
183 pub shape: ShapeKind,
184 pub tex: Option<CachedTexture>,
185 pub diffuse_col: [f32; 4],
186 pub roughness: f32,
187}
188
189impl Scene3DRenderer {
190 pub fn new(device: &wgpu::Device) -> Self {
191 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
192 label: Some("scene3d-shader"),
193 source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()),
194 });
195 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
196 label: Some("scene3d-bgl"),
197 entries: &[
198 wgpu::BindGroupLayoutEntry {
199 binding: 0,
200 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
201 ty: wgpu::BindingType::Buffer {
202 ty: wgpu::BufferBindingType::Uniform,
203 has_dynamic_offset: false,
204 min_binding_size: None,
205 },
206 count: None,
207 },
208 wgpu::BindGroupLayoutEntry {
209 binding: 1,
210 visibility: wgpu::ShaderStages::FRAGMENT,
211 ty: wgpu::BindingType::Texture {
212 sample_type: wgpu::TextureSampleType::Float { filterable: true },
213 view_dimension: wgpu::TextureViewDimension::D2,
214 multisampled: false,
215 },
216 count: None,
217 },
218 wgpu::BindGroupLayoutEntry {
219 binding: 2,
220 visibility: wgpu::ShaderStages::FRAGMENT,
221 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
222 count: None,
223 },
224 ],
225 });
226 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
227 label: Some("scene3d-pl"),
228 bind_group_layouts: &[Some(&bgl)],
229 immediate_size: 0,
230 });
231 let vbuf_layout = wgpu::VertexBufferLayout {
232 array_stride: std::mem::size_of::<Vertex3D>() as u64,
233 step_mode: wgpu::VertexStepMode::Vertex,
234 attributes: &[
235 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 },
236 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 },
237 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
238 ],
239 };
240 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
241 label: Some("scene3d-mesh"),
242 layout: Some(&pl),
243 vertex: wgpu::VertexState {
244 module: &shader,
245 entry_point: Some("vs_mesh"),
246 compilation_options: Default::default(),
247 buffers: &[Some(vbuf_layout)],
248 },
249 fragment: Some(wgpu::FragmentState {
250 module: &shader,
251 entry_point: Some("fs_mesh"),
252 compilation_options: Default::default(),
253 targets: &[Some(wgpu::ColorTargetState {
254 format: wgpu::TextureFormat::Rgba8Unorm,
255 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
256 write_mask: wgpu::ColorWrites::ALL,
257 })],
258 }),
259 primitive: wgpu::PrimitiveState {
260 topology: wgpu::PrimitiveTopology::TriangleList,
261 cull_mode: None,
262 ..Default::default()
263 },
264 depth_stencil: Some(wgpu::DepthStencilState {
265 format: wgpu::TextureFormat::Depth32Float,
266 depth_write_enabled: Some(true),
267 depth_compare: Some(wgpu::CompareFunction::LessEqual),
268 stencil: wgpu::StencilState::default(),
269 bias: wgpu::DepthBiasState::default(),
270 }),
271 multisample: wgpu::MultisampleState::default(),
272 multiview_mask: None,
273 cache: None,
274 });
275 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
276 label: Some("scene3d-linear"),
277 address_mode_u: wgpu::AddressMode::ClampToEdge,
278 address_mode_v: wgpu::AddressMode::ClampToEdge,
279 mag_filter: wgpu::FilterMode::Linear,
280 min_filter: wgpu::FilterMode::Linear,
281 mipmap_filter: wgpu::MipmapFilterMode::Linear,
282 ..Default::default()
283 });
284 Self { bgl, pipeline, sampler }
285 }
286
287 #[allow(clippy::too_many_arguments)]
288 pub fn render_meshes(
289 &self,
290 device: &wgpu::Device,
291 queue: &wgpu::Queue,
292 enc: &mut wgpu::CommandEncoder,
293 dst: &CachedTexture,
294 dummy: &CachedTexture,
295 view_proj: Mat4,
296 view: Mat4,
297 cam_pos: [f32; 3],
298 lights: SceneLights,
299 lighting_enabled: bool,
300 meshes: &[DrawMesh],
301 ) {
302 let depth_tex = device.create_texture(&wgpu::TextureDescriptor {
303 label: Some("scene3d-depth"),
304 size: wgpu::Extent3d {
305 width: dst.size[0].max(1),
306 height: dst.size[1].max(1),
307 depth_or_array_layers: 1,
308 },
309 mip_level_count: 1,
310 sample_count: 1,
311 dimension: wgpu::TextureDimension::D2,
312 format: wgpu::TextureFormat::Depth32Float,
313 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
314 view_formats: &[],
315 });
316 let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
317
318 // Sort back-to-front in camera view space so semi-transparent planes blend cleanly.
319 let mut order: Vec<(usize, f32)> = meshes
320 .iter()
321 .enumerate()
322 .map(|(i, m)| {
323 let wx = m.world[12];
324 let wy = m.world[13];
325 let wz = m.world[14];
326 let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14];
327 (i, vz)
328 })
329 .collect();
330 order.sort_by(|a, b| a.1.total_cmp(&b.1));
331
332 struct GpuDraw {
333 bg: wgpu::BindGroup,
334 vbuf: wgpu::Buffer,
335 ibuf: wgpu::Buffer,
336 idx_count: u32,
337 }
338 let mut draw_items = Vec::with_capacity(order.len());
339 for (idx, _) in order {
340 let m = &meshes[idx];
341 let aspect = m
342 .tex
343 .as_ref()
344 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
345 .unwrap_or(16.0 / 9.0);
346 let (verts, indices) = build_shape_mesh(&m.shape, aspect);
347 if indices.is_empty() {
348 continue;
349 }
350 let vbytes = bytemuck::cast_slice(&verts);
351 let ibytes = bytemuck::cast_slice(&indices);
352 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
353 label: Some("scene3d-vb"),
354 size: vbytes.len() as u64,
355 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
356 mapped_at_creation: false,
357 });
358 queue.write_buffer(&vbuf, 0, vbytes);
359 let ibuf = device.create_buffer(&wgpu::BufferDescriptor {
360 label: Some("scene3d-ib"),
361 size: ibytes.len() as u64,
362 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
363 mapped_at_creation: false,
364 });
365 queue.write_buffer(&ibuf, 0, ibytes);
366
367 let mvp = mat4_mul(view_proj, m.world);
368 let dod = if let Some(t) = &m.tex {
369 if t.has_dod() {
370 [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32]
371 } else {
372 [0.0; 4]
373 }
374 } else {
375 [0.0; 4]
376 };
377 let uni = MeshUniform {
378 mvp,
379 model: m.world,
380 dod,
381 flags: [
382 if m.tex.is_some() { 1.0 } else { 0.0 },
383 if lighting_enabled { 1.0 } else { 0.0 },
384 m.roughness,
385 0.0,
386 ],
387 diffuse_col: m.diffuse_col,
388 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],
389 dir_to_light: [
390 lights.dir_to_light[0],
391 lights.dir_to_light[1],
392 lights.dir_to_light[2],
393 if lights.has_dir { 1.0 } else { 0.0 },
394 ],
395 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
396 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
397 };
398 let ubuf = device.create_buffer(&wgpu::BufferDescriptor {
399 label: Some("scene3d-u"),
400 size: std::mem::size_of::<MeshUniform>() as u64,
401 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
402 mapped_at_creation: false,
403 });
404 queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni));
405 let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view);
406 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
407 label: Some("scene3d-bg"),
408 layout: &self.bgl,
409 entries: &[
410 wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
411 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) },
412 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
413 ],
414 });
415 draw_items.push(GpuDraw {
416 bg,
417 vbuf,
418 ibuf,
419 idx_count: indices.len() as u32,
420 });
421 }
422
423 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
424 label: Some("scene3d-pass"),
425 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
426 view: &dst.view,
427 depth_slice: None,
428 resolve_target: None,
429 ops: wgpu::Operations {
430 load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
431 store: wgpu::StoreOp::Store,
432 },
433 })],
434 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
435 view: &depth_view,
436 depth_ops: Some(wgpu::Operations {
437 load: wgpu::LoadOp::Clear(1.0),
438 store: wgpu::StoreOp::Discard,
439 }),
440 stencil_ops: None,
441 }),
442 timestamp_writes: None,
443 occlusion_query_set: None,
444 multiview_mask: None,
445 });
446 pass.set_pipeline(&self.pipeline);
447 for d in &draw_items {
448 pass.set_bind_group(0, &d.bg, &[]);
449 pass.set_vertex_buffer(0, d.vbuf.slice(..));
450 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
451 pass.draw_indexed(0..d.idx_count, 0, 0..1);
452 }
453 }
454}
455
456fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) {
457 match *shape {
458 ShapeKind::ImagePlane => {
459 let hx = 0.5;
460 let hy = 0.5 / tex_aspect.max(1e-4);
461 let verts = vec![
462 Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] },
463 Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] },
464 Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] },
465 Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] },
466 ];
467 (verts, vec![0, 1, 2, 0, 2, 3])
468 }
469 ShapeKind::Plane { width, height } => {
470 let hx = width * 0.5;
471 let hy = height * 0.5;
472 let verts = vec![
473 Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] },
474 Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] },
475 Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] },
476 Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] },
477 ];
478 (verts, vec![0, 1, 2, 0, 2, 3])
479 }
480 ShapeKind::Sphere { radius, sub_base, sub_height } => {
481 let seg_u = sub_base.clamp(12, 96);
482 let seg_v = sub_height.clamp(8, 64);
483 let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize);
484 let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize);
485 for iv in 0..=seg_v {
486 let v = iv as f32 / seg_v as f32;
487 let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y)
488 let (sp, cp) = phi.sin_cos();
489 for iu in 0..=seg_u {
490 let u = iu as f32 / seg_u as f32;
491 let theta = u * std::f32::consts::TAU;
492 let (st, ct) = theta.sin_cos();
493 let nx = sp * st;
494 let ny = cp;
495 let nz = sp * ct;
496 verts.push(Vertex3D {
497 pos: [nx * radius, ny * radius, nz * radius],
498 normal: [nx, ny, nz],
499 uv: [u, v],
500 });
501 }
502 }
503 let row = seg_u + 1;
504 for iv in 0..seg_v {
505 for iu in 0..seg_u {
506 let a = iv * row + iu;
507 let b = (iv + 1) * row + iu;
508 let c = (iv + 1) * row + iu + 1;
509 let d = iv * row + iu + 1;
510 idx.extend_from_slice(&[a, b, c, a, c, d]);
511 }
512 }
513 (verts, idx)
514 }
515 ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => {
516 let seg_u = sub_base.clamp(16, 96);
517 let half_h = height * 0.5;
518 let a0 = start_sweep_deg.to_radians();
519 let a1 = end_sweep_deg.to_radians();
520 let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize);
521 let mut idx = Vec::with_capacity((seg_u * 6) as usize);
522 for iu in 0..=seg_u {
523 let u = iu as f32 / seg_u as f32;
524 // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc
525 let theta = a0 + (a1 - a0) * u;
526 let (st, ct) = theta.sin_cos();
527 let nx = ct;
528 let nz = st;
529 verts.push(Vertex3D {
530 pos: [nx * radius, half_h, nz * radius],
531 normal: [nx, 0.0, nz],
532 uv: [1.0 - u, 0.0],
533 });
534 verts.push(Vertex3D {
535 pos: [nx * radius, -half_h, nz * radius],
536 normal: [nx, 0.0, nz],
537 uv: [1.0 - u, 1.0],
538 });
539 }
540 for iu in 0..seg_u {
541 let a = iu * 2;
542 let b = a + 1;
543 let c = a + 3;
544 let d = a + 2;
545 idx.extend_from_slice(&[a, b, c, a, c, d]);
546 }
547 (verts, idx)
548 }
549 ShapeKind::Cube { width, height, depth } => {
550 let hx = width * 0.5;
551 let hy = height * 0.5;
552 let hz = depth * 0.5;
553 let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [
554 ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]),
555 ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]),
556 ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]),
557 ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]),
558 ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]),
559 ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]),
560 ];
561 let mut verts = Vec::with_capacity(24);
562 let mut idx = Vec::with_capacity(36);
563 for (n, corners) in faces {
564 let base = verts.len() as u32;
565 let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
566 for (p, uv) in corners.into_iter().zip(uvs) {
567 verts.push(Vertex3D { pos: p, normal: n, uv });
568 }
569 idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
570 }
571 (verts, idx)
572 }
573 }
574}
575
576/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`,
577/// `ImagePlane3D`, `Shape3D`, `LightAmbient`, `LightDirectional`).
578#[allow(clippy::too_many_arguments)]
579pub fn collect_scene(
580 comp: &Comp,
581 node_id: NodeId,
582 time: f64,
583 expr: &ExprEngine,
584 parent_xform: Mat4,
585 render_aspect: f32,
586 cameras: &mut Vec<CameraInstance>,
587 meshes: &mut Vec<MeshInstance>,
588 lights: &mut SceneLights,
589 depth: usize,
590) {
591 if depth > 32 {
592 return;
593 }
594 let node = comp.node(node_id);
595 if node.bypassed {
596 return;
597 }
598 let local = eval_transform3d(comp, node, time, expr);
599 let world = mat4_mul(parent_xform, local);
600
601 match node.kind.as_str() {
602 "Merge3D" | "Transform3D" => {
603 let mut input_names: Vec<&String> = node
604 .inputs
605 .keys()
606 .filter(|k| k.starts_with("SceneInput"))
607 .collect();
608 input_names.sort();
609 for in_name in input_names {
610 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {
611 collect_scene(comp, src_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1);
612 }
613 }
614 }
615 "Camera3D" => {
616 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;
617 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;
618 // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display).
619 // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°).
620 let has_aov = node.inputs.contains_key("AoV");
621 let has_fl = node.inputs.contains_key("FLength");
622 let aov_deg = if has_aov {
623 comp.eval_number(node, "AoV", time, 24.302, expr) as f32
624 } else if has_fl {
625 let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32;
626 let sensor_h_mm = ap_h * 25.4;
627 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees()
628 } else {
629 24.302
630 };
631 let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Inside");
632 let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4);
633
634 let half_aov = (aov_deg.to_radians() * 0.5).tan();
635 let half_v = match gate_fit {
636 "Height" | "Stretch" => half_aov,
637 "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)),
638 "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0),
639 _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!)
640 };
641 let vfov_rad = 2.0 * half_v.atan();
642 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;
643 let far = 5000.0_f32;
644 cameras.push(CameraInstance { world, vfov_rad, near, far });
645 }
646 "LightAmbient" => {
647 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
648 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
649 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
650 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
651 lights.ambient[0] += r * inten;
652 lights.ambient[1] += g * inten;
653 lights.ambient[2] += b * inten;
654 }
655 "LightDirectional" => {
656 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
657 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
658 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
659 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
660 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
661 let dx = world[8];
662 let dy = world[9];
663 let dz = world[10];
664 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
665 lights.dir_to_light = [dx / len, dy / len, dz / len];
666 lights.dir_color = [r * inten, g * inten, b * inten];
667 lights.has_dir = true;
668 }
669 "ImagePlane3D" => {
670 let mat_node = node
671 .connected_node("MaterialInput")
672 .or_else(|| node.connected_node("SceneInput"))
673 .and_then(|s| comp.find_node(s));
674 let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr);
675 meshes.push(MeshInstance {
676 world,
677 shape: ShapeKind::ImagePlane,
678 material_node: tex_node,
679 diffuse_col,
680 roughness,
681 });
682 }
683 "Shape3D" => {
684 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
685 let shape = match shape_name {
686 "SurfaceSphereInputs" => ShapeKind::Sphere {
687 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 0.5, expr) as f32,
688 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32,
689 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32,
690 },
691 "SurfaceCylinderInputs" => {
692 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;
693 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;
694 ShapeKind::Cylinder {
695 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32,
696 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32,
697 start_sweep_deg: start_sw,
698 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
699 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32,
700 }
701 }
702 "SurfaceCubeInputs" => ShapeKind::Cube {
703 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
704 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, 1.0, expr) as f32,
705 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, 1.0, expr) as f32,
706 },
707 _ => ShapeKind::Plane {
708 width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32,
709 height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32,
710 },
711 };
712 let mat_node = node
713 .connected_node("MaterialInput")
714 .and_then(|s| comp.find_node(s));
715 let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr);
716 meshes.push(MeshInstance {
717 world,
718 shape,
719 material_node: tex_node,
720 diffuse_col,
721 roughness,
722 });
723 }
724 "MacroOperator" | "GroupOperator" => {
725 if let Some(out_id) = node.macro_output {
726 collect_scene(comp, out_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1);
727 }
728 }
729 _ => {}
730 }
731}
732
733/// Resolves a 3D material input (either a 2D image node directly or a Fusion 3D material like
734/// `MtlCookTorrance` / `MtlBlinn` / `MtlPhong`) to `(diffuse_2d_node, diffuse_rgba, roughness)`.
735fn resolve_material(
736 comp: &Comp,
737 mat_node: Option<NodeId>,
738 time: f64,
739 expr: &ExprEngine,
740) -> (Option<NodeId>, [f32; 4], f32) {
741 let Some(mid) = mat_node else {
742 return (None, [1.0, 1.0, 1.0, 1.0], 0.5);
743 };
744 let n = comp.node(mid);
745 if n.kind.starts_with("Mtl") {
746 let diff_tex = n
747 .connected_node("Diffuse.Color.Material")
748 .or_else(|| n.connected_node("MaterialInput"))
749 .and_then(|s| comp.find_node(s));
750 let col = [
751 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,
752 comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32,
753 comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32,
754 comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32,
755 ];
756 let rough = comp.eval_number(n, "Specular.Roughness", time, 0.5, expr) as f32;
757 (diff_tex, col, rough)
758 } else {
759 (Some(mid), [1.0, 1.0, 1.0, 1.0], 0.5)
760 }
761}
762
763pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
764 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;
765 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
766 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32;
767
768 let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians();
769 let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians();
770 let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians();
771 let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ");
772
773 let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5;
774 let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32;
775 let sy = if scale_lock {
776 sx
777 } else {
778 comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32
779 };
780 let sz = if scale_lock {
781 sx
782 } else {
783 comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32
784 };
785
786 let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32;
787 let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32;
788 let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32;
789
790 let mx = mat4_rot_x(rx);
791 let my = mat4_rot_y(ry);
792 let mz = mat4_rot_z(rz);
793 let rot = match rot_order {
794 "XZY" => mat4_mul(my, mat4_mul(mz, mx)),
795 "YXZ" => mat4_mul(mz, mat4_mul(mx, my)),
796 "YZX" => mat4_mul(mx, mat4_mul(mz, my)),
797 "ZXY" => mat4_mul(my, mat4_mul(mx, mz)),
798 "ZYX" => mat4_mul(mx, mat4_mul(my, mz)),
799 _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default
800 };
801
802 let t = mat4_translate(tx + px, ty + py, tz + pz);
803 let s = mat4_scale(sx, sy, sz);
804 let inv_p = mat4_translate(-px, -py, -pz);
805 mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p)))
806}
807
808pub fn mat4_identity() -> Mat4 {
809 [
810 1.0, 0.0, 0.0, 0.0,
811 0.0, 1.0, 0.0, 0.0,
812 0.0, 0.0, 1.0, 0.0,
813 0.0, 0.0, 0.0, 1.0,
814 ]
815}
816
817pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 {
818 let mut out = [0.0_f32; 16];
819 for col in 0..4 {
820 for row in 0..4 {
821 out[col * 4 + row] = a[row] * b[col * 4]
822 + a[4 + row] * b[col * 4 + 1]
823 + a[8 + row] * b[col * 4 + 2]
824 + a[12 + row] * b[col * 4 + 3];
825 }
826 }
827 out
828}
829
830pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 {
831 [
832 1.0, 0.0, 0.0, 0.0,
833 0.0, 1.0, 0.0, 0.0,
834 0.0, 0.0, 1.0, 0.0,
835 x, y, z, 1.0,
836 ]
837}
838
839pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 {
840 [
841 x, 0.0, 0.0, 0.0,
842 0.0, y, 0.0, 0.0,
843 0.0, 0.0, z, 0.0,
844 0.0, 0.0, 0.0, 1.0,
845 ]
846}
847
848pub fn mat4_rot_x(r: f32) -> Mat4 {
849 let (s, c) = r.sin_cos();
850 [
851 1.0, 0.0, 0.0, 0.0,
852 0.0, c, s, 0.0,
853 0.0, -s, c, 0.0,
854 0.0, 0.0, 0.0, 1.0,
855 ]
856}
857
858pub fn mat4_rot_y(r: f32) -> Mat4 {
859 let (s, c) = r.sin_cos();
860 [
861 c, 0.0, -s, 0.0,
862 0.0, 1.0, 0.0, 0.0,
863 s, 0.0, c, 0.0,
864 0.0, 0.0, 0.0, 1.0,
865 ]
866}
867
868pub fn mat4_rot_z(r: f32) -> Mat4 {
869 let (s, c) = r.sin_cos();
870 [
871 c, s, 0.0, 0.0,
872 -s, c, 0.0, 0.0,
873 0.0, 0.0, 1.0, 0.0,
874 0.0, 0.0, 0.0, 1.0,
875 ]
876}
877
878pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 {
879 let r00 = m[0]; let r10 = m[1]; let r20 = m[2];
880 let r01 = m[4]; let r11 = m[5]; let r21 = m[6];
881 let r02 = m[8]; let r12 = m[9]; let r22 = m[10];
882 let tx = m[12]; let ty = m[13]; let tz = m[14];
883 let itx = -(r00 * tx + r10 * ty + r20 * tz);
884 let ity = -(r01 * tx + r11 * ty + r21 * tz);
885 let itz = -(r02 * tx + r12 * ty + r22 * tz);
886 [
887 r00, r01, r02, 0.0,
888 r10, r11, r12, 0.0,
889 r20, r21, r22, 0.0,
890 itx, ity, itz, 1.0,
891 ]
892}
893
894pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 {
895 let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5);
896 let nf = 1.0 / (near - far);
897 [
898 f / aspect.max(1e-4), 0.0, 0.0, 0.0,
899 0.0, f, 0.0, 0.0,
900 0.0, 0.0, far * nf, -1.0,
901 0.0, 0.0, far * near * nf, 0.0,
902 ]
903}
crates/engine/src/shaders.wgsl created+1741
...@@ -0,0 +1,1741 @@
1// Compositor GPU compute shaders (WGSL).
2// Coordinate convention: Fusion uses normalized UV (0,0) = bottom-left, (1,1) = top-right,
3// whereas textures store row 0 at the top. Helpers `pix_to_fu` / `fu_to_uv` bridge cleanly.
4
5@group(0) @binding(0) var src_a: texture_2d<f32>;
6@group(0) @binding(1) var src_b: texture_2d<f32>;
7@group(0) @binding(2) var mask_tex: texture_2d<f32>;
8@group(0) @binding(3) var samp_lin: sampler;
9@group(0) @binding(4) var dst_tex: texture_storage_2d<rgba8unorm, write>;
10
11struct Params {
12 // 16 vec4<f32> = 256 bytes of uniform parameters per dispatch.
13 p: array<vec4<f32>, 16>,
14};
15@group(0) @binding(5) var<uniform> u: Params;
16
17// Helper: output pixel (gid.xy, top-down) -> Fusion UV (0..1, bottom-up).
18fn pix_to_fu(gid: vec2<u32>, dims: vec2<u32>) -> vec2<f32> {
19 let f = vec2<f32>(dims);
20 return vec2<f32>((f32(gid.x) + 0.5) / f.x, 1.0 - (f32(gid.y) + 0.5) / f.y);
21}
22
23// Helper: Fusion UV (bottom-up) -> texture UV (top-down).
24fn fu_to_uv(fu: vec2<f32>) -> vec2<f32> {
25 return vec2<f32>(fu.x, 1.0 - fu.y);
26}
27
28fn sample_tex(tex: texture_2d<f32>, uv: vec2<f32>, nearest: bool) -> vec4<f32> {
29 if (nearest) {
30 let isdims = vec2<i32>(textureDimensions(tex));
31 let sx = clamp(i32(floor(uv.x * f32(isdims.x))), 0, isdims.x - 1);
32 let sy = clamp(i32(floor(uv.y * f32(isdims.y))), 0, isdims.y - 1);
33 return textureLoad(tex, vec2<i32>(sx, sy), 0);
34 }
35 return textureSampleLevel(tex, samp_lin, uv, 0.0);
36}
37
38// Helper: Sample texture with Fusion Edges mode: 0=Canvas, 1=Wrap, 2=Duplicate, 3=Mirror.
39// When `dod` (`origin_x, origin_y, canvas_w, canvas_h`) has `canvas_w > 0.5`, maps `fu`
40// (normalized to `canvas`) into the texture's expanded Domain of Definition!
41fn sample_dod_edges_mode(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32, dod: vec4<f32>, nearest: bool) -> vec4<f32> {
42 var uv: vec2<f32>;
43 if (dod.z > 0.5 && dod.w > 0.5) {
44 let tdims = vec2<f32>(textureDimensions(tex));
45 let canvas_px = vec2<f32>(fu.x * dod.z, (1.0 - fu.y) * dod.w);
46 uv = (canvas_px - dod.xy) / tdims;
47 } else {
48 uv = fu_to_uv(fu);
49 }
50 if (edges == 0) {
51 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
52 return vec4<f32>(0.0);
53 }
54 return sample_tex(tex, uv, nearest);
55 } else if (edges == 1) {
56 uv = fract(uv);
57 return sample_tex(tex, uv, nearest);
58 } else if (edges == 2) {
59 uv = clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0));
60 return sample_tex(tex, uv, nearest);
61 } else {
62 let m = abs(fract(uv * 0.5 + 0.5) * 2.0 - 1.0);
63 return sample_tex(tex, m, nearest);
64 }
65}
66
67fn sample_dod_edges(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32, dod: vec4<f32>) -> vec4<f32> {
68 return sample_dod_edges_mode(tex, fu, edges, dod, false);
69}
70
71fn sample_edges(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32) -> vec4<f32> {
72 return sample_dod_edges(tex, fu, edges, vec4<f32>(0.0));
73}
74
75fn read_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, invert: f32) -> f32 {
76 if (has_mask < 0.5) {
77 return 1.0;
78 }
79 let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims);
80 let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a;
81 return select(m, 1.0 - m, invert > 0.5);
82}
83
84// ============================================================================
85// 1. Background (Solid + Gradients)
86// p[0] = top_left rgba, p[1] = top_right rgba, p[2] = bottom_left rgba, p[3] = bottom_right rgba
87// p[4] = (type: 0=Solid, 1=Horiz, 2=Vert, 3=FourCorner, 4=Gradient, 5=Radial, sub_type, start_x, start_y)
88// p[5] = (end_x, end_y, 0, 0)
89// ============================================================================
90@compute @workgroup_size(8, 8)
91fn bg_op(@builtin(global_invocation_id) gid: vec3<u32>) {
92 let dims = textureDimensions(dst_tex);
93 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
94 let fu = pix_to_fu(gid.xy, dims);
95 let kind = i32(u.p[4].x + 0.5);
96 var col = u.p[0];
97 if (kind == 1) {
98 col = mix(u.p[0], u.p[1], fu.x);
99 } else if (kind == 2) {
100 col = mix(u.p[2], u.p[0], fu.y);
101 } else if (kind == 3) {
102 let top = mix(u.p[0], u.p[1], fu.x);
103 let bot = mix(u.p[2], u.p[3], fu.x);
104 col = mix(bot, top, fu.y);
105 } else if (kind == 4 || kind == 5) {
106 let s = u.p[4].zw;
107 let e = u.p[5].xy;
108 let d = e - s;
109 var t = 0.0;
110 if (kind == 5) {
111 let r = max(length(d), 1e-5);
112 t = clamp(length(fu - s) / r, 0.0, 1.0);
113 } else {
114 let len2 = max(dot(d, d), 1e-6);
115 t = clamp(dot(fu - s, d) / len2, 0.0, 1.0);
116 }
117 col = mix(u.p[0], u.p[1], t);
118 }
119 let m = read_mask(gid.xy, dims, u.p[5].z, u.p[5].w);
120 col = col * m;
121 // Output premultiplied RGBA
122 let out_col = vec4<f32>(col.rgb * col.a, col.a);
123 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
124}
125
126
127// ============================================================================
128// 2. Merge (Transform FG + ApplyMode + Gain + Blend + Mask)
129// p[0] = (center.x, center.y, size, angle_rad)
130// p[1] = (blend, gain, apply_mode_id, edges_mode)
131// p[2] = (flip_h, flip_v, fg_aspect, bg_aspect)
132// p[3] = (has_mask, mask_invert, fg_w, fg_h)
133// ============================================================================
134fn blend_lum(c: vec3<f32>) -> f32 {
135 return dot(c, vec3<f32>(0.299, 0.587, 0.114));
136}
137
138fn clip_color(col_in: vec3<f32>) -> vec3<f32> {
139 var c = col_in;
140 let l = blend_lum(c);
141 let n = min(c.r, min(c.g, c.b));
142 let x = max(c.r, max(c.g, c.b));
143 if (n < 0.0) {
144 c = vec3<f32>(l) + ((c - vec3<f32>(l)) * l) / max(l - n, 1e-5);
145 }
146 if (x > 1.0) {
147 c = vec3<f32>(l) + ((c - vec3<f32>(l)) * (1.0 - l)) / max(x - l, 1e-5);
148 }
149 return c;
150}
151
152fn set_lum(c: vec3<f32>, l: f32) -> vec3<f32> {
153 let d = l - blend_lum(c);
154 return clip_color(c + vec3<f32>(d));
155}
156
157fn sat_val(c: vec3<f32>) -> f32 {
158 return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b));
159}
160
161fn set_sat(c_in: vec3<f32>, s: f32) -> vec3<f32> {
162 let mn = min(c_in.r, min(c_in.g, c_in.b));
163 let mx = max(c_in.r, max(c_in.g, c_in.b));
164 let span = mx - mn;
165 if (span <= 1e-5) {
166 return vec3<f32>(0.0);
167 }
168 return (c_in - vec3<f32>(mn)) * (s / span);
169}
170
171fn apply_blend_mode(bg: vec3<f32>, fg: vec3<f32>, mode: i32) -> vec3<f32> {
172 switch mode {
173 case 1: { // Screen
174 return 1.0 - (1.0 - bg) * (1.0 - fg);
175 }
176 case 2: { // Multiply
177 return bg * fg;
178 }
179 case 3: { // Darken
180 return min(bg, fg);
181 }
182 case 4: { // Lighten
183 return max(bg, fg);
184 }
185 case 5: { // Difference
186 return abs(bg - fg);
187 }
188 case 6: { // Exclusion
189 return bg + fg - 2.0 * bg * fg;
190 }
191 case 7: { // Overlay
192 let lo = 2.0 * bg * fg;
193 let hi = 1.0 - 2.0 * (1.0 - bg) * (1.0 - fg);
194 return select(hi, lo, bg < vec3<f32>(0.5));
195 }
196 case 8: { // Hard Light
197 let lo = 2.0 * bg * fg;
198 let hi = 1.0 - 2.0 * (1.0 - bg) * (1.0 - fg);
199 return select(hi, lo, fg < vec3<f32>(0.5));
200 }
201 case 9: { // Soft Light (W3C / Photoshop / Fusion exact)
202 let d_lo = ((16.0 * bg - 12.0) * bg + 4.0) * bg;
203 let d_hi = sqrt(max(bg, vec3<f32>(0.0)));
204 let d = select(d_hi, d_lo, bg <= vec3<f32>(0.25));
205 let lo = bg - (1.0 - 2.0 * fg) * bg * (1.0 - bg);
206 let hi = bg + (2.0 * fg - 1.0) * (d - bg);
207 return select(hi, lo, fg <= vec3<f32>(0.5));
208 }
209 case 10: { // Linear Light
210 return clamp(bg + 2.0 * fg - 1.0, vec3<f32>(0.0), vec3<f32>(1.0));
211 }
212 case 11: { // Color Dodge
213 return clamp(bg / max(1.0 - fg, vec3<f32>(1e-4)), vec3<f32>(0.0), vec3<f32>(1.0));
214 }
215 case 12: { // Linear Dodge / Add
216 return clamp(bg + fg, vec3<f32>(0.0), vec3<f32>(1.0));
217 }
218 case 13: { // Vivid Light
219 let burn = 1.0 - (1.0 - bg) / max(2.0 * fg, vec3<f32>(1e-4));
220 let dodge = bg / max(2.0 * (1.0 - fg), vec3<f32>(1e-4));
221 return clamp(select(dodge, burn, fg < vec3<f32>(0.5)), vec3<f32>(0.0), vec3<f32>(1.0));
222 }
223 case 14: { // Hypotenuse
224 return clamp(sqrt(bg * bg + fg * fg), vec3<f32>(0.0), vec3<f32>(1.0));
225 }
226 case 15: { // Darker Color (Fusion compares Rec.601 luma, picks darker pixel whole)
227 let l_fg = dot(fg, vec3<f32>(0.299, 0.587, 0.114));
228 let l_bg = dot(bg, vec3<f32>(0.299, 0.587, 0.114));
229 return select(bg, fg, l_fg < l_bg);
230 }
231 case 16: { // Lighter Color (Fusion compares Rec.601 luma, picks lighter pixel whole)
232 let l_fg = dot(fg, vec3<f32>(0.299, 0.587, 0.114));
233 let l_bg = dot(bg, vec3<f32>(0.299, 0.587, 0.114));
234 return select(bg, fg, l_fg > l_bg);
235 }
236 case 17: { // Pin Light
237 let lo = min(bg, 2.0 * fg);
238 let hi = max(bg, 2.0 * fg - 1.0);
239 return select(hi, lo, fg < vec3<f32>(0.5));
240 }
241 case 18: { // Color Burn
242 return 1.0 - clamp((1.0 - bg) / max(fg, vec3<f32>(1e-4)), vec3<f32>(0.0), vec3<f32>(1.0));
243 }
244 case 19: { // Linear Burn
245 return clamp(bg + fg - 1.0, vec3<f32>(0.0), vec3<f32>(1.0));
246 }
247 case 20: { // Geometric
248 return (2.0 * fg * bg) / max(fg + bg, vec3<f32>(1e-5));
249 }
250 case 21: { // Hue
251 return set_lum(set_sat(fg, sat_val(bg)), blend_lum(bg));
252 }
253 case 22: { // Saturation
254 return set_lum(set_sat(bg, sat_val(fg)), blend_lum(bg));
255 }
256 case 23: { // Color
257 return set_lum(fg, blend_lum(bg));
258 }
259 case 24: { // Luminosity
260 return set_lum(bg, blend_lum(fg));
261 }
262 default: { // 0: Normal
263 return fg;
264 }
265 }
266}
267
268@compute @workgroup_size(8, 8)
269fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
270 let dims = textureDimensions(dst_tex);
271 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
272 let bg_dod = u.p[5];
273 let has_bg_dod = bg_dod.z > 0.5 && bg_dod.w > 0.5;
274 let bg_dims = select(vec2<f32>(dims), bg_dod.zw, has_bg_dod);
275 let fg_dims = max(u.p[3].zw, vec2<f32>(1.0));
276
277 let bg = textureLoad(src_a, vec2<i32>(gid.xy), 0);
278 // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV!
279 let canvas_px = select(
280 vec2<f32>(gid.xy) + vec2<f32>(0.5),
281 vec2<f32>(gid.xy) + vec2<f32>(0.5) + bg_dod.xy,
282 has_bg_dod,
283 );
284 let fu = vec2<f32>(canvas_px.x / bg_dims.x, 1.0 - canvas_px.y / bg_dims.y);
285
286 let center = u.p[0].xy;
287 let size = max(u.p[0].z, 1e-5);
288 let angle = u.p[0].w;
289 let blend = u.p[1].x;
290 let gain = u.p[1].y;
291 let mode = i32(u.p[1].z + 0.5);
292 let edges = i32(u.p[1].w + 0.5);
293 let nearest = u.p[2].z > 0.5;
294
295 // Map output pixel in Fusion pixel space relative to Center into FG pixel space.
296 let delta_px = (fu - center) * bg_dims;
297 let c = cos(angle);
298 let s = sin(angle);
299 // Fusion Angle rotates CCW in Y-up, so inverse rotates CW:
300 let rot_px = vec2<f32>(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size;
301 var fg_fu = rot_px / fg_dims + vec2<f32>(0.5);
302 if (u.p[2].x > 0.5) { fg_fu.x = 1.0 - fg_fu.x; }
303 if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; }
304
305 let fg = sample_dod_edges_mode(src_b, fg_fu, edges, u.p[4], nearest);
306 let mask = read_mask(gid.xy, dims, u.p[3].x, u.p[3].y);
307 let eff_blend = clamp(blend * mask, 0.0, 1.0);
308 let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr
309
310 let burn_in = u.p[6].x;
311
312 var out_col: vec4<f32>;
313 if (mode == 0) {
314 let fg_occ = fg.a * gain * (1.0 - burn_in);
315 var comp: vec4<f32>;
316 if (op == 1) {
317 // Under: FG behind BG
318 let bg_occ = bg.a;
319 comp = vec4<f32>(bg.rgb + fg.rgb * (1.0 - bg_occ), bg.a + fg.a * (1.0 - bg_occ));
320 } else if (op == 2) {
321 // In: FG masked by BG alpha
322 comp = fg * bg.a;
323 } else if (op == 3) {
324 // HeldOut: BG masked by (1 - FG alpha)
325 comp = bg * (1.0 - fg_occ);
326 } else if (op == 4) {
327 // Atop: FG inside BG + BG outside FG
328 comp = vec4<f32>(fg.rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a);
329 } else if (op == 5) {
330 // XOr
331 comp = fg * (1.0 - bg.a) + bg * (1.0 - fg_occ);
332 } else {
333 // Over (default) with Fusion Alpha Gain, Subtractive/Additive, and BurnIn
334 let over_rgb = fg.rgb + bg.rgb * (1.0 - fg_occ);
335 let over_a = fg.a * gain + bg.a * (1.0 - fg.a * gain);
336 comp = vec4<f32>(over_rgb, over_a);
337 }
338 out_col = mix(bg, comp, eff_blend);
339 } else if (mode == 15 || mode == 16) {
340 // Fusion DarkerColor/LighterColor with AlphaGain: candidate is FG + BG*(1 - fg.a*gain),
341 // compared against BG by Rec.601 luma! (Verified bit-exact on probe_merge f09 & f10!)
342 let fg_a_eff = fg.a * gain;
343 let bg_u = select(vec3<f32>(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5);
344 let fg_u = select(vec3<f32>(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5);
345 let cand = fg_u + bg_u * (1.0 - fg_a_eff);
346 let blended = apply_blend_mode(bg_u, cand, mode);
347 let comp_rgb = bg.a * fg.a * blended + fg.rgb * (1.0 - bg.a) + (1.0 - fg.a) * bg.rgb;
348 let comp_a = bg.a + fg_a_eff * (1.0 - bg.a);
349 out_col = mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
350 } else {
351 let bg_u = select(vec3<f32>(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5);
352 let fg_u = select(vec3<f32>(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5);
353 // In Fusion's special fill-opacity modes (Difference, Exclusion, Screen, LinearDodge),
354 // Gain scales FG color intensity BEFORE blending (e.g. Difference = |bg - gain*fg|!).
355 let scale_fg_rgb = (mode == 5 || mode == 6 || mode == 1 || mode == 12);
356 let fg_blend_in = select(fg_u, fg_u * gain, scale_fg_rgb);
357 let blended = apply_blend_mode(bg_u, fg_blend_in, mode);
358 let fg_eff = select(fg.a * gain, fg.a, scale_fg_rgb);
359 let comp_rgb = fg_eff * bg.a * blended + fg_eff * (1.0 - bg.a) * fg_blend_in + (1.0 - fg_eff) * bg.rgb;
360 let comp_a = bg.a + fg_eff * (1.0 - bg.a);
361 out_col = mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
362 }
363 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
364}
365
366
367// ============================================================================
368// 3. Transform
369// p[0] = (center.x, center.y, pivot.x, pivot.y)
370// p[1] = (size_x, size_y, angle_rad, edges)
371// p[2] = (flip_h, flip_v, blend, has_mask)
372// p[3] = (mask_invert, 0, 0, 0)
373// ============================================================================
374@compute @workgroup_size(8, 8)
375fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
376 let dims = textureDimensions(dst_tex);
377 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
378 let fdims = vec2<f32>(dims);
379 let fu = pix_to_fu(gid.xy, dims);
380
381 let center = u.p[0].xy;
382 let pivot = u.p[0].zw;
383 let sx = max(u.p[1].x, 1e-5);
384 let sy = max(u.p[1].y, 1e-5);
385 let angle = u.p[1].z;
386 let edges = i32(u.p[1].w + 0.5);
387
388 // Forward in Fusion: p' = R(angle) * S(sx, sy) * (p - pivot) + pivot + (center - 0.5)
389 let shift = center - vec2<f32>(0.5);
390 let rel_px = (fu - pivot - shift) * fdims;
391 let c = cos(angle);
392 let s = sin(angle);
393 let unrot = vec2<f32>(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c);
394 var src_fu = vec2<f32>(unrot.x / sx, unrot.y / sy) / fdims + pivot;
395 if (u.p[2].x > 0.5) { src_fu.x = 1.0 - src_fu.x; }
396 if (u.p[2].y > 0.5) { src_fu.y = 1.0 - src_fu.y; }
397
398 let nearest = u.p[3].y > 0.5;
399 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
400 let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest);
401 let m = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x) * u.p[2].z;
402 let out_col = mix(orig, moved, clamp(m, 0.0, 1.0));
403 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
404}
405
406
407// ============================================================================
408// 4. BrightnessContrast
409// p[0] = (gain, lift, gamma, contrast)
410// p[1] = (brightness, saturation, prediv, blend)
411// p[2] = (has_mask, mask_invert, low, high)
412// p[3] = (proc_r, proc_g, proc_b, proc_a)
413// ============================================================================
414fn bc_curve_scalar(v_in: f32, low: f32, high: f32, gain: f32, lift: f32, gamma: f32, contrast: f32, brightness: f32) -> f32 {
415 var v = v_in;
416 if (abs(low) > 1e-5 || abs(high - 1.0) > 1e-5) {
417 let span = max(high - low, 1e-5);
418 v = (v - low) / span;
419 }
420 v = v * (gain - lift) + lift;
421 v = pow(max(v, 0.0), 1.0 / gamma);
422 v = (v - 0.5) * (1.0 + contrast) + 0.5;
423 v = v + brightness;
424 return v;
425}
426
427@compute @workgroup_size(8, 8)
428fn bc_op(@builtin(global_invocation_id) gid: vec3<u32>) {
429 let dims = textureDimensions(dst_tex);
430 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
431 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
432 let gain = u.p[0].x;
433 let lift = u.p[0].y;
434 let gamma = max(u.p[0].z, 1e-4);
435 let contrast = u.p[0].w;
436 let brightness = u.p[1].x;
437 let sat = u.p[1].y;
438 let prediv = u.p[1].z > 0.5;
439 let low = u.p[2].z;
440 let high = u.p[2].w;
441 let proc_r = u.p[3].x > 0.5;
442 let proc_g = u.p[3].y > 0.5;
443 let proc_b = u.p[3].z > 0.5;
444 let proc_a = u.p[3].w > 0.5;
445
446 var rgb = src.rgb;
447 if (prediv && src.a > 1e-5) {
448 rgb = rgb / src.a;
449 }
450
451 var adj_rgb = vec3<f32>(
452 bc_curve_scalar(rgb.r, low, high, gain, lift, gamma, contrast, brightness),
453 bc_curve_scalar(rgb.g, low, high, gain, lift, gamma, contrast, brightness),
454 bc_curve_scalar(rgb.b, low, high, gain, lift, gamma, contrast, brightness),
455 );
456 let luma = dot(adj_rgb, vec3<f32>(0.299, 0.587, 0.114));
457 adj_rgb = mix(vec3<f32>(luma), adj_rgb, sat);
458
459 let out_rgb_unpre = vec3<f32>(
460 select(rgb.r, adj_rgb.r, proc_r),
461 select(rgb.g, adj_rgb.g, proc_g),
462 select(rgb.b, adj_rgb.b, proc_b),
463 );
464 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);
465 let out_rgb = select(out_rgb_unpre, out_rgb_unpre * out_a, prediv);
466 let adjusted = vec4<f32>(out_rgb, out_a);
467 let m = read_mask(gid.xy, dims, u.p[2].x, u.p[2].y) * u.p[1].w;
468 let out_col = mix(src, adjusted, clamp(m, 0.0, 1.0));
469 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
470}
471
472
473// ============================================================================
474// 5. ColorCorrector (Lightness-preserving hue rotation + saturation + tint + LGG + contrast)
475// p[0] = (hue_turns, sat, tint_angle_rad, tint_len)
476// p[1] = (gain, lift, gamma, contrast)
477// p[2] = (brightness, prediv, blend, has_mask)
478// p[3] = (mask_invert, 0, 0, 0)
479// ============================================================================
480fn rotate_hue_preserve_luma(c: vec3<f32>, angle: f32) -> vec3<f32> {
481 // Paul Haeberli luminance-preserving shear-rotate-unshear around (1,1,1) with Rec.601 weights.
482 // Verified 0.00/255 bit-exact against Fusion Studio 21.1 ColorCorrector!
483 let k = vec3<f32>(0.299, 0.587, 0.114);
484 let y = dot(c, k);
485 let ch = c - vec3<f32>(y);
486 let ca = cos(angle);
487 let sa = sin(angle);
488 let s3 = 0.5773502691896258; // 1 / sqrt(3)
489 let ndv = (ch.r + ch.g + ch.b) * (1.0 / 3.0);
490 let nxv = vec3<f32>(ch.g - ch.b, ch.b - ch.r, ch.r - ch.g) * s3;
491 let v = ch * ca + nxv * sa + vec3<f32>(ndv * (1.0 - ca));
492 let dy = dot(v, k);
493 return vec3<f32>(y) + v - vec3<f32>(dy);
494}
495
496fn hsv_pure_hue(h_turns: f32) -> vec3<f32> {
497 let h = fract(h_turns) * 6.0;
498 let r = clamp(abs(h - 3.0) - 1.0, 0.0, 1.0);
499 let g = clamp(2.0 - abs(h - 2.0), 0.0, 1.0);
500 let b = clamp(2.0 - abs(h - 4.0), 0.0, 1.0);
501 return vec3<f32>(r, g, b);
502}
503
504@compute @workgroup_size(8, 8)
505fn cc_op(@builtin(global_invocation_id) gid: vec3<u32>) {
506 let dims = textureDimensions(dst_tex);
507 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
508 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
509 let hue_turns = u.p[0].x;
510 let sat = u.p[0].y;
511 let tint_turns = u.p[0].z;
512 let tint_len = u.p[0].w;
513 let gain = u.p[1].x;
514 let lift = u.p[1].y;
515 let gamma = max(u.p[1].z, 1e-4);
516 let contrast = u.p[1].w;
517 let brightness = u.p[2].x;
518 let prediv = u.p[2].y > 0.5;
519 let k_luma = vec3<f32>(0.299, 0.587, 0.114);
520
521 var rgb = src.rgb;
522 if (prediv && src.a > 1e-5) {
523 rgb = rgb / src.a;
524 }
525
526 // 1. Hue rotation (verified 0.00/255 vs Fusion 21.1: +turns rotates Red -> Yellow -> Green -> Cyan -> Blue -> Magenta)
527 if (abs(hue_turns) > 1e-5) {
528 rgb = rotate_hue_preserve_luma(rgb, -hue_turns * 6.28318530718);
529 }
530
531 // 2. Fusion Color Wheel Tint (verified 0.00/255 vs Fusion 21.1: lerp toward pure HSV chroma * 2*min(Y, 1-Y))
532 if (tint_len > 1e-5) {
533 let y_t = dot(rgb, k_luma);
534 let pure = hsv_pure_hue(tint_turns);
535 let pure_y = dot(pure, k_luma);
536 let tc = pure - vec3<f32>(pure_y);
537 let y_clamped = clamp(y_t, 0.0, 1.0);
538 let amp = 2.0 * min(y_clamped, 1.0 - y_clamped);
539 let tint_rgb = vec3<f32>(y_t) + tc * amp;
540 rgb = mix(rgb, tint_rgb, clamp(tint_len, 0.0, 1.0));
541 }
542
543 // 3. Saturation (Rec.601 luma, no gamut crushing — verified 0.00/255 at sat=0, 1.6, 3.0, 6.0!)
544 let luma = dot(rgb, k_luma);
545 rgb = mix(vec3<f32>(luma), rgb, sat);
546
547 // 4. Contrast -> Lift/Gain -> Brightness -> Gamma (verified 0.00/255 vs Fusion 21.1!)
548 rgb = (rgb - 0.5) * contrast + 0.5;
549 rgb = rgb * (gain - lift) + lift;
550 rgb = rgb + brightness;
551 rgb = pow(max(rgb, vec3<f32>(0.0)), vec3<f32>(1.0 / gamma));
552
553 if (prediv) {
554 rgb = rgb * src.a;
555 }
556 let m = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x) * u.p[2].z;
557 let out_col = mix(src, vec4<f32>(rgb, src.a), clamp(m, 0.0, 1.0));
558 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
559}
560
561
562// ============================================================================
563// 6. LumaKeyer
564// p[0] = (low, high, invert, blend)
565// p[1] = (has_mask, mask_invert, 0, 0)
566// ============================================================================
567@compute @workgroup_size(8, 8)
568fn luma_key_op(@builtin(global_invocation_id) gid: vec3<u32>) {
569 let dims = textureDimensions(dst_tex);
570 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
571 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
572 let low = u.p[0].x;
573 let high = u.p[0].y;
574 let invert = u.p[0].z > 0.5;
575 let rgb = select(vec3<f32>(0.0), src.rgb / max(src.a, 1e-5), src.a > 1e-5);
576 let luma = dot(rgb, vec3<f32>(0.299, 0.587, 0.114));
577 var a = clamp((luma - low) / max(high - low, 1e-5), 0.0, 1.0);
578 if (invert) {
579 a = 1.0 - a;
580 }
581 let out_a = a * src.a;
582 let keyed = vec4<f32>(rgb * out_a, out_a);
583 let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * u.p[0].w;
584 let out_col = mix(src, keyed, clamp(m, 0.0, 1.0));
585 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
586}
587
588
589// ============================================================================
590// 7. Separable Gaussian / Box Blur & Directional Blur
591// p[0] = (dir.x, dir.y, radius_px, mode: 0=gauss, 1=box, 2=erode, 3=dilate)
592// p[1] = (blend, has_mask, mask_invert, 0)
593// ============================================================================
594@compute @workgroup_size(8, 8)
595fn blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
596 let dims = textureDimensions(dst_tex);
597 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
598 let fdims = vec2<f32>(dims);
599 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
600 let dir = u.p[0].xy / fdims;
601 let radius = u.p[0].z;
602 let mode = i32(u.p[0].w + 0.5);
603
604 if (radius < 0.25) {
605 textureStore(dst_tex, vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0));
606 return;
607 }
608
609 let taps = clamp(i32(ceil(radius)), 1, 64);
610 let step_scale = radius / f32(taps);
611
612 var acc = vec4<f32>(0.0);
613 var wsum = 0.0;
614
615 let clamp_edges = u.p[1].w > 0.5;
616 if (mode == 2 || mode == 3) {
617 // Erode (min) / Dilate (max)
618 acc = textureLoad(src_a, vec2<i32>(gid.xy), 0);
619 for (var i = -taps; i <= taps; i = i + 1) {
620 let s = textureSampleLevel(src_a, samp_lin, clamp(uv + dir * (f32(i) * step_scale), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
621 acc = select(max(acc, s), min(acc, s), mode == 2);
622 }
623 } else if (mode == 1) {
624 // Box blur
625 for (var i = -taps; i <= taps; i = i + 1) {
626 let off = uv + dir * (f32(i) * step_scale);
627 let s = select(
628 select(vec4<f32>(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),
629 textureSampleLevel(src_a, samp_lin, clamp(off, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0),
630 clamp_edges,
631 );
632 acc = acc + s;
633 wsum = wsum + 1.0;
634 }
635 acc = acc / max(wsum, 1.0);
636 } else {
637 // Gaussian blur
638 let sigma = max(radius * 0.45, 0.5);
639 let inv2s2 = 0.5 / (sigma * sigma);
640 for (var i = -taps; i <= taps; i = i + 1) {
641 let d = f32(i) * step_scale;
642 let w = exp(-d * d * inv2s2);
643 let off = uv + dir * d;
644 let s = select(
645 select(vec4<f32>(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),
646 textureSampleLevel(src_a, samp_lin, clamp(off, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0),
647 clamp_edges,
648 );
649 acc = acc + s * w;
650 wsum = wsum + w;
651 }
652 acc = acc / max(wsum, 1e-6);
653 }
654
655 let orig = select(
656 textureLoad(src_a, vec2<i32>(gid.xy), 0),
657 textureLoad(src_b, vec2<i32>(gid.xy), 0),
658 u.p[2].x > 0.5,
659 );
660 let m = read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x;
661 let out_col = mix(orig, acc, clamp(m, 0.0, 1.0));
662 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
663}
664
665
666// ============================================================================
667// 8. FastNoise (2D FBM value/gradient noise with Seethe & Discontinuous)
668// p[0] = (x_scale, y_scale, detail, contrast)
669// p[1] = (brightness, seethe, discontinuous, center_x)
670// p[2] = (center_y, angle, inverted, 0)
671// p[3] = color1 rgba, p[4] = color2 rgba
672// ============================================================================
673fn hash3(p: vec3<f32>) -> f32 {
674 var q = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
675 q = q + dot(q, q.yxz + 33.33);
676 return fract((q.x + q.y) * q.z);
677}
678
679fn noise3d(p: vec3<f32>) -> f32 {
680 let i = floor(p);
681 let f = fract(p);
682 let u_f = f * f * (3.0 - 2.0 * f);
683 let n000 = hash3(i + vec3<f32>(0.0, 0.0, 0.0));
684 let n100 = hash3(i + vec3<f32>(1.0, 0.0, 0.0));
685 let n010 = hash3(i + vec3<f32>(0.0, 1.0, 0.0));
686 let n110 = hash3(i + vec3<f32>(1.0, 1.0, 0.0));
687 let n001 = hash3(i + vec3<f32>(0.0, 0.0, 1.0));
688 let n101 = hash3(i + vec3<f32>(1.0, 0.0, 1.0));
689 let n011 = hash3(i + vec3<f32>(0.0, 1.0, 1.0));
690 let n111 = hash3(i + vec3<f32>(1.0, 1.0, 1.0));
691 let nx00 = mix(n000, n100, u_f.x);
692 let nx10 = mix(n010, n110, u_f.x);
693 let nx01 = mix(n001, n101, u_f.x);
694 let nx11 = mix(n011, n111, u_f.x);
695 let nxy0 = mix(nx00, nx10, u_f.y);
696 let nxy1 = mix(nx01, nx11, u_f.y);
697 return mix(nxy0, nxy1, u_f.z) * 2.0 - 1.0;
698}
699
700@compute @workgroup_size(8, 8)
701fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
702 let dims = textureDimensions(dst_tex);
703 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
704 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
705 let fu = pix_to_fu(gid.xy, dims);
706 let center = vec2<f32>(u.p[1].w, u.p[2].x);
707 let scale = u.p[0].xy;
708 let detail = clamp(u.p[0].z, 1.0, 10.0);
709 let contrast = u.p[0].w;
710 let brightness = u.p[1].x;
711 let seethe = u.p[1].y;
712 let disc = u.p[1].z > 0.5;
713
714 var p = (fu - center) * vec2<f32>(aspect, 1.0) * scale;
715 let octaves = i32(ceil(detail));
716 var sum = 0.0;
717 var amp = 0.5;
718 var freq = 1.0;
719 var norm = 0.0;
720 for (var i = 0; i < 10; i = i + 1) {
721 if (i >= octaves) { break; }
722 let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4);
723 var n = noise3d(vec3<f32>(p * freq, seethe * 0.37 + f32(i) * 1.7));
724 if (disc) { n = abs(n) * 2.0 - 1.0; }
725 sum = sum + n * weight;
726 norm = norm + weight;
727 freq = freq * 2.0;
728 amp = amp * 0.5;
729 }
730 // Fusion FastNoise uses Perlin-scale FBM (~0.26 amplitude) so sharp high-threshold gradients (e.g. 0.95..0.96)
731 // isolate sparse pinpoint peaks rather than flooding 15% of the frame!
732 var val = (sum / max(norm, 1e-4)) * 0.26 * contrast + 0.5 + brightness;
733 val = clamp(val, 0.0, 1.0);
734 if (u.p[2].z > 0.5) { val = 1.0 - val; }
735 var col: vec4<f32>;
736 if (u.p[2].w > 0.5) {
737 // High-precision 256x1 gradient LUT in src_b (supports razor-sharp thresholds like starfields!)
738 col = textureSampleLevel(src_b, samp_lin, vec2<f32>(val, 0.5), 0.0);
739 } else {
740 let lut_pos = val * 12.0;
741 let i0 = u32(clamp(floor(lut_pos), 0.0, 11.0));
742 let f = lut_pos - f32(i0);
743 col = mix(u.p[3u + i0], u.p[4u + i0], f);
744 }
745 let out_col = vec4<f32>(col.rgb * col.a, col.a);
746 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
747}
748
749
750// ============================================================================
751// 9. Displace (Type 0 = Radial/Bump with Spread RGB dispersion & LightPower, Type 1 = XY Refraction)
752// p[0] = (type, x_ref, y_ref, x_off)
753// p[1] = (y_off, ref_strength, blend, has_mask)
754// p[2] = (mask_invert, spread, light_power, offset)
755// p[3] = (center.x, center.y, 0, 0)
756// ============================================================================
757fn pick_channel(c: vec4<f32>, ch: i32) -> f32 {
758 switch ch {
759 case 0: { return c.r; }
760 case 1: { return c.g; }
761 case 2: { return c.b; }
762 case 3: { return c.a; }
763 default: { return dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114)); }
764 }
765}
766
767@compute @workgroup_size(8, 8)
768fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
769 let dims = textureDimensions(dst_tex);
770 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
771 let fdims = vec2<f32>(dims);
772 let fu = pix_to_fu(gid.xy, dims);
773 let uv = fu_to_uv(fu);
774 let kind = i32(u.p[0].x + 0.5);
775 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
776
777 var warped: vec4<f32>;
778 if (kind == 1) {
779 // XY Refraction: Fusion formula is `(fg[channel] + offset) * refraction` with clamped (Duplicate) edges!
780 let fg = textureSampleLevel(src_b, samp_lin, uv, 0.0);
781 let xch = i32(u.p[3].z + 0.5);
782 let ych = i32(u.p[3].w + 0.5);
783 let vx = pick_channel(fg, xch);
784 let vy = pick_channel(fg, ych);
785 let disp = vec2<f32>(
786 (vx + u.p[0].w) * u.p[0].y,
787 (vy + u.p[1].x) * u.p[0].z,
788 );
789 warped = sample_edges(src_a, fu + disp, 2);
790 } else {
791 // Radial displace: Fusion shifts radially from Center by -(fu - center) * (luma + offset) * strength * 0.51.
792 let fg_c = textureSampleLevel(src_b, samp_lin, uv, 0.0);
793 let l_c = dot(fg_c.rgb, vec3<f32>(0.299, 0.587, 0.114));
794 let offset = u.p[2].w;
795 let strength = u.p[1].y;
796 let spread = u.p[2].y;
797 let light_power = u.p[2].z;
798 let center = u.p[3].xy;
799 let dir_c = fu - center;
800 let base_disp = -dir_c * (l_c + offset) * strength * 0.51;
801
802 if (abs(spread) > 1e-4) {
803 let sp = spread * 0.02;
804 let sr = sample_edges(src_a, fu + base_disp * (1.0 - sp), 2);
805 let sg = sample_edges(src_a, fu + base_disp, 2);
806 let sb = sample_edges(src_a, fu + base_disp * (1.0 + sp), 2);
807 warped = vec4<f32>(sr.r, sg.g, sb.b, max(sr.a, max(sg.a, sb.a)));
808 } else {
809 warped = sample_edges(src_a, fu + base_disp, 2);
810 }
811
812 if (light_power > 1e-4) {
813 let dx = 1.0 / fdims.x;
814 let dy = 1.0 / fdims.y;
815 let lx0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2<f32>(dx, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114));
816 let lx1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2<f32>(dx, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114));
817 let ly0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2<f32>(0.0, dy), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114));
818 let ly1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2<f32>(0.0, dy), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114));
819 let grad = vec2<f32>(lx1 - lx0, ly0 - ly1);
820 let shade = clamp(1.0 + dot(grad, vec2<f32>(0.707, 0.707)) * light_power * 1.2, 0.0, 2.0);
821 warped = vec4<f32>(warped.rgb * shade, warped.a);
822 }
823 }
824
825 let m = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * u.p[1].z;
826 let out_col = mix(orig, warped, clamp(m, 0.0, 1.0));
827 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
828}
829
830
831// ============================================================================
832// 10. Mask Shapes (EllipseMask & RectangleMask) + Mask Combine / Apply
833// p[0] = (center.x, center.y, width, height)
834// p[1] = (angle_rad, soft_edge, corner_radius, invert)
835// p[2] = (shape: 0=Ellipse, 1=Rect, level, has_prev_mask, paint_mode)
836// paint_mode: 0=Merge, 1=Add, 2=Subtract, 3=Multiply, 4=Min, 5=Max, 6=Invert, 7=Replace
837// ============================================================================
838fn combine_mask_val(prev: f32, cur: f32, mode: i32) -> f32 {
839 if (mode == 1) { return clamp(prev + cur, 0.0, 1.0); } // Add
840 if (mode == 2) { return clamp(prev - cur, 0.0, 1.0); } // Subtract
841 if (mode == 3) { return prev * cur; } // Multiply
842 if (mode == 4) { return min(prev, cur); } // Minimum
843 if (mode == 5) { return max(prev, cur); } // Maximum
844 if (mode == 6) { return abs(prev - cur); } // Invert
845 if (mode == 7) { return cur; } // Replace
846 return clamp(prev + cur * (1.0 - prev), 0.0, 1.0); // Merge (default)
847}
848
849@compute @workgroup_size(8, 8)
850fn mask_shape_op(@builtin(global_invocation_id) gid: vec3<u32>) {
851 let dims = textureDimensions(dst_tex);
852 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
853 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
854 let fu = pix_to_fu(gid.xy, dims);
855
856 let center = u.p[0].xy;
857 let half_sz = max(u.p[0].zw * 0.5, vec2<f32>(1e-5));
858 let angle = u.p[1].x;
859 let soft = max(u.p[1].y, 1.0 / max(f32(dims.x), 1.0));
860 let radius = u.p[1].z;
861 let invert = u.p[1].w > 0.5;
862 let shape = i32(u.p[2].x + 0.5);
863 let level = u.p[2].y;
864 let has_prev = u.p[2].z > 0.5;
865 let paint_mode = i32(u.p[2].w + 0.5);
866
867 // Work in isotropic frame-width units (1.0 = canvas width) so rotations & circles are exact!
868 let rel_w = (fu - center) * vec2<f32>(1.0, 1.0 / aspect);
869 let c = cos(angle);
870 let s = sin(angle);
871 let p_w = vec2<f32>(rel_w.x * c + rel_w.y * s, -rel_w.x * s + rel_w.y * c);
872
873 var dist: f32;
874 if (shape == 0) {
875 // Fusion EllipseMask: BOTH Width and Height are in frame-width units (Width == Height -> circle)!
876 let q = p_w / half_sz;
877 let grad_len = max(length(q / half_sz), 1e-5);
878 dist = (length(q) - 1.0) * (length(q) / grad_len);
879 } else {
880 // Fusion RectangleMask: Width is in frame-width units, Height is in frame-height units!
881 let h_w = vec2<f32>(half_sz.x, half_sz.y / aspect);
882 // CornerRadius in Fusion is 0..1 fraction of the shorter half-dimension.
883 let r_w = clamp(radius, 0.0, 1.0) * min(h_w.x, h_w.y);
884 let q = abs(p_w) - (h_w - vec2<f32>(r_w));
885 dist = length(max(q, vec2<f32>(0.0))) + min(max(q.x, q.y), 0.0) - r_w;
886 }
887
888 var a = 1.0 - smoothstep(-soft, soft, dist);
889 if (invert) { a = 1.0 - a; }
890 a = clamp(a * level, 0.0, 1.0);
891 if (has_prev) {
892 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
893 let prev = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a;
894 a = combine_mask_val(prev, a, paint_mode);
895 }
896 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(a, a, a, a));
897}
898
899@compute @workgroup_size(8, 8)
900fn mask_combine_op(@builtin(global_invocation_id) gid: vec3<u32>) {
901 let dims = textureDimensions(dst_tex);
902 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
903 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
904 let paint_mode = i32(u.p[0].x + 0.5);
905 let invert = u.p[0].y > 0.5;
906 let level = select(1.0, u.p[0].z, u.p[0].z > -0.5);
907 let has_prev = u.p[0].w > 0.5;
908 var cur = textureLoad(src_a, vec2<i32>(gid.xy), 0).a;
909 if (invert) { cur = 1.0 - cur; }
910 cur = clamp(cur * level, 0.0, 1.0);
911 var a = cur;
912 if (has_prev) {
913 let prev = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a;
914 a = combine_mask_val(prev, cur, paint_mode);
915 }
916 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(a, a, a, a));
917}
918
919@compute @workgroup_size(8, 8)
920fn mask_apply_op(@builtin(global_invocation_id) gid: vec3<u32>) {
921 let dims = textureDimensions(dst_tex);
922 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
923 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
924 let m = read_mask(gid.xy, dims, 1.0, u.p[0].x);
925 textureStore(dst_tex, vec2<i32>(gid.xy), src * m);
926}
927
928// ============================================================================
929// 11. Fuse.Colorize (Clover's exact 2020 Colorize.fuse formula!)
930// p[0] = (r1, g1, b1, a1), p[1] = (r2, g2, b2, a2), p[2] = (blend, has_mask, mask_invert, 0)
931// ============================================================================
932@compute @workgroup_size(8, 8)
933fn colorize_op(@builtin(global_invocation_id) gid: vec3<u32>) {
934 let dims = textureDimensions(dst_tex);
935 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
936 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
937 let c1 = u.p[0];
938 let c2 = u.p[1];
939
940 let ab = src.a;
941 let aa = c1.a + ab * (c2.a - c1.a);
942 let unpre = select(vec3<f32>(0.0), src.rgb / ab, ab > 1e-6);
943 let out_rgb = (c1.rgb + unpre * (c2.rgb - c1.rgb)) * aa;
944 let col = vec4<f32>(out_rgb, aa);
945 let m = read_mask(gid.xy, dims, u.p[2].y, u.p[2].z) * u.p[2].x;
946 let out_col = mix(src, col, clamp(m, 0.0, 1.0));
947 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
948}
949
950
951// ============================================================================
952// 12. Fuse.Outline (Clover's exact 2020 Outline.fuse passes!)
953// outline_boost: boosts alpha * 120 (clamped in R/A via normalized scale, so we pass scale factor!)
954// outline_finish: clamps dilated alpha, tints with outline color, then composites original on top!
955// ============================================================================
956@compute @workgroup_size(8, 8)
957fn outline_boost(@builtin(global_invocation_id) gid: vec3<u32>) {
958 let dims = textureDimensions(dst_tex);
959 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
960 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
961 let a = clamp(src.a * 120.0, 0.0, 1.0);
962 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(a, a, a, a));
963}
964
965@compute @workgroup_size(8, 8)
966fn outline_tint(@builtin(global_invocation_id) gid: vec3<u32>) {
967 let dims = textureDimensions(dst_tex);
968 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
969 let blurred = textureLoad(src_a, vec2<i32>(gid.xy), 0);
970 let col = u.p[0]; // (r, g, b, a)
971 // Because we clamped boosted alpha to 1.0 in u8, emulate the 120x dilation threshold
972 let a = clamp(blurred.a * u.p[1].x, 0.0, 1.0) * col.a;
973 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(col.rgb * a, a));
974}
975
976@compute @workgroup_size(8, 8)
977fn outline_composite(@builtin(global_invocation_id) gid: vec3<u32>) {
978 let dims = textureDimensions(dst_tex);
979 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
980 let outline = textureLoad(src_a, vec2<i32>(gid.xy), 0);
981 let orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
982 // Original over outline
983 let out_rgb = orig.rgb + outline.rgb * (1.0 - orig.a);
984 let out_a = orig.a + outline.a * (1.0 - orig.a);
985 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(vec4<f32>(out_rgb, out_a), vec4<f32>(0.0), vec4<f32>(1.0)));
986}
987
988// ============================================================================
989// 12c. TextPlus Circular Euclidean L2 Outline + Fill-Over-Outline Composite
990// p[0] = (outline_r, outline_g, outline_b, outline_a)
991// p[1] = (radius_px, 0, 0, 0)
992// ============================================================================
993@compute @workgroup_size(8, 8)
994fn text_outline_op(@builtin(global_invocation_id) gid: vec3<u32>) {
995 let dims = textureDimensions(dst_tex);
996 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
997 let p = vec2<i32>(gid.xy);
998 let orig = textureLoad(src_a, p, 0);
999 if (orig.a >= 0.999) {
1000 textureStore(dst_tex, p, orig);
1001 return;
1002 }
1003
1004 let radius = clamp(u.p[1].x, 0.5, 28.0);
1005 let r_int = i32(ceil(radius + 0.5));
1006 let r_max = radius + 0.5;
1007 let r_max2 = r_max * r_max;
1008 let max_p = vec2<i32>(dims) - vec2<i32>(1, 1);
1009
1010 var max_a = orig.a;
1011 for (var dy = -r_int; dy <= r_int; dy = dy + 1) {
1012 let dy2 = f32(dy * dy);
1013 for (var dx = -r_int; dx <= r_int; dx = dx + 1) {
1014 let d2 = f32(dx * dx) + dy2;
1015 if (d2 > r_max2) { continue; }
1016 let sp = p + vec2<i32>(dx, dy);
1017 if (sp.x < 0 || sp.y < 0 || sp.x > max_p.x || sp.y > max_p.y) { continue; }
1018 let sa = textureLoad(src_a, sp, 0).a;
1019 if (sa <= 0.0) { continue; }
1020 let cov = clamp(r_max - sqrt(d2), 0.0, 1.0);
1021 max_a = max(max_a, sa * cov);
1022 }
1023 }
1024
1025 let oa = max_a * u.p[0].a;
1026 let outline_rgb = u.p[0].rgb * oa;
1027 let out_rgb = orig.rgb + outline_rgb * (1.0 - orig.a);
1028 let out_a = orig.a + oa * (1.0 - orig.a);
1029 textureStore(dst_tex, p, clamp(vec4<f32>(out_rgb, out_a), vec4<f32>(0.0), vec4<f32>(1.0)));
1030}
1031
1032// ============================================================================
1033// 13. Custom Wave Shader (matches `sin(x|y * w * n1 + n2 * n1 * w) * 0.5 + 0.5` per channel)
1034// p[0] = (n1, n2, w_ref, 0)
1035// p[1] = (r_mode, g_mode, b_mode, a_const) where mode: 0=const 0, 1=sin(x*...), 2=sin(y*...)
1036// ============================================================================
1037fn eval_wave_ch(mode: i32, fu: vec2<f32>, n1: f32, n2: f32, w: f32) -> f32 {
1038 let deg2rad = 0.017453292519943295;
1039 if (mode == 1) {
1040 return sin((fu.x * w * n1 + n2 * n1 * w) * deg2rad) * 0.5 + 0.5;
1041 } else if (mode == 2) {
1042 return sin((fu.y * w * n1 + n2 * n1 * w) * deg2rad) * 0.5 + 0.5;
1043 }
1044 return 0.0;
1045}
1046
1047@compute @workgroup_size(8, 8)
1048fn custom_wave_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1049 let dims = textureDimensions(dst_tex);
1050 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1051 let fu = pix_to_fu(gid.xy, dims);
1052 let n1 = u.p[0].x;
1053 let n2 = u.p[0].y;
1054 let w = u.p[0].z;
1055 // Fusion CustomTool trig functions operate in DEGREES!
1056 let r = eval_wave_ch(i32(u.p[1].x + 0.5), fu, n1, n2, w);
1057 let g = eval_wave_ch(i32(u.p[1].y + 0.5), fu, n1, n2, w);
1058 let b = eval_wave_ch(i32(u.p[1].z + 0.5), fu, n1, n2, w);
1059 let a = u.p[1].w;
1060 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(r, g, b, a));
1061}
1062
1063// ============================================================================
1064// 14. Crop / Scale / Copy
1065// p[0] = (x_off_norm, y_off_norm, x_scale, y_scale)
1066// ============================================================================
1067@compute @workgroup_size(8, 8)
1068fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1069 let dims = textureDimensions(dst_tex);
1070 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1071 let src_dims = vec2<f32>(textureDimensions(src_a));
1072 let dst_dims = vec2<f32>(dims);
1073 let x_off = u.p[0].x;
1074 let y_off = u.p[0].y;
1075 // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from bottom-left (x_off, y_off)
1076 let dst_y_up = dst_dims.y - 1.0 - f32(gid.y);
1077 let src_x = f32(gid.x) + x_off;
1078 let src_y_up = dst_y_up + y_off;
1079 let src_y = src_dims.y - 1.0 - src_y_up;
1080 if (src_x < 0.0 || src_x >= src_dims.x || src_y < 0.0 || src_y >= src_dims.y) {
1081 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(0.0));
1082 return;
1083 }
1084 let uv = (vec2<f32>(src_x, src_y) + 0.5) / src_dims;
1085 let c = textureSampleLevel(src_a, samp_lin, uv, 0.0);
1086 textureStore(dst_tex, vec2<i32>(gid.xy), c);
1087}
1088
1089// ============================================================================
1090// 15. Glow / SoftGlow Combine
1091// p[0] = (gain, blend, has_mask, mask_invert)
1092// p[1] = (mode: 0=Screen [SoftGlow], 1=Replace [Glow], 2=Additive, 0, 0, 0)
1093// ============================================================================
1094@compute @workgroup_size(8, 8)
1095fn glow_add_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1096 let dims = textureDimensions(dst_tex);
1097 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1098 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1099 let blurred = textureLoad(src_b, vec2<i32>(gid.xy), 0);
1100 let gain = u.p[0].x;
1101 let mode = i32(u.p[1].x + 0.5);
1102 let m = read_mask(gid.xy, dims, u.p[0].z, u.p[0].w) * u.p[0].y;
1103 var added: vec4<f32>;
1104 if (mode == 1) {
1105 // Fusion Glow tool: blurred / (1 - Glow), preserving blurred alpha
1106 added = vec4<f32>(blurred.rgb * gain, clamp(blurred.a, 0.0, 1.0));
1107 } else if (mode == 2) {
1108 added = vec4<f32>(orig.rgb + blurred.rgb * gain, clamp(orig.a + blurred.a * gain * 0.5, 0.0, 1.0));
1109 } else {
1110 // Fusion SoftGlow: Screen blend `orig + g - orig * g` where `g = clamp(blurred * gain, 0, 1)`
1111 let g = clamp(blurred * gain, vec4<f32>(0.0), vec4<f32>(1.0));
1112 added = orig + g - orig * g;
1113 }
1114 let out_col = mix(orig, added, clamp(m, 0.0, 1.0));
1115 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1116}
1117
1118// ============================================================================
1119// 15b. MT_XGlow Preprocess (Threshold -> Gain -> SrcSat -> GlowMask RGB multiply)
1120// p[0] = (thresh_low, thresh_high, src_sat, has_glow_mask)
1121// p[1] = (gain, 0, 0, 0)
1122// ============================================================================
1123@compute @workgroup_size(8, 8)
1124fn xglow_prep_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1125 let dims = textureDimensions(dst_tex);
1126 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1127 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1128 let t_lo = u.p[0].x;
1129 let t_hi = u.p[0].y;
1130 let src_sat = u.p[0].z;
1131 let has_gm = u.p[0].w > 0.5;
1132 let gain = u.p[1].x;
1133
1134 var col = src;
1135 if (t_lo > 1e-5 || t_hi > 1e-5) {
1136 let hi = select(1.0, t_hi, t_hi > t_lo + 1e-5);
1137 let denom = max(hi - t_lo, 1e-5);
1138 col = clamp((col - vec4<f32>(t_lo)) / denom, vec4<f32>(0.0), vec4<f32>(1.0));
1139 }
1140 var rgb = col.rgb * gain;
1141 let y = dot(rgb, vec3<f32>(0.299, 0.587, 0.114));
1142 rgb = mix(vec3<f32>(y), rgb, src_sat);
1143 if (has_gm) {
1144 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
1145 let gm = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a;
1146 rgb = rgb * gm;
1147 }
1148 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(vec4<f32>(rgb, col.a), vec4<f32>(0.0), vec4<f32>(1.0)));
1149}
1150
1151// ============================================================================
1152// 15c. MT_XGlow Octave Accumulate (Gradient tint -> YUV falloff + GlowSat -> Additive)
1153// src_a = running glow accumulator (or base), src_b = blurred octave (bilinearly upsampled!)
1154// p[0] = (grad_r, grad_g, grad_b, y_scale) where y_scale = gain / (falloff^i)
1155// p[1] = (uv_scale, add_base, alpha_scale, 0)
1156// ============================================================================
1157@compute @workgroup_size(8, 8)
1158fn xglow_accum_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1159 let dims = textureDimensions(dst_tex);
1160 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1161 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
1162 let base = select(vec4<f32>(0.0), textureLoad(src_a, vec2<i32>(gid.xy), 0), u.p[1].y > 0.5);
1163 let oct = textureSampleLevel(src_b, samp_lin, uv, 0.0);
1164
1165 let c = oct.rgb * u.p[0].xyz;
1166 // Rec.601 RGB -> YUV -> scale (y_scale, uv_scale, uv_scale) -> RGB (matches MT_XGlow.fuse lines 421-423)
1167 let y = 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;
1168 let u_c = (c.b - y) * 0.492111;
1169 let v_c = (c.r - y) * 0.877283;
1170 let ys = y * u.p[0].w;
1171 let us = u_c * u.p[1].x;
1172 let vs = v_c * u.p[1].x;
1173 let r2 = ys + vs / 0.877283;
1174 let b2 = ys + us / 0.492111;
1175 let g2 = (ys - 0.299 * r2 - 0.114 * b2) / 0.587;
1176 let add_rgb = max(vec3<f32>(r2, g2, b2), vec3<f32>(0.0));
1177 let add_a = max(oct.a * u.p[1].z, 0.0);
1178
1179 let out_col = vec4<f32>(base.rgb + add_rgb, clamp(base.a + add_a, 0.0, 1.0));
1180 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1181}
1182
1183
1184// ============================================================================
1185// 16. Blit / Scale (source -> destination of any size, premultiplied)
1186// p[0] = (exposure_mul, gamma, channel_mode: 0=RGBA,1=R,2=G,3=B,4=A, checker_bg)
1187// ============================================================================
1188@compute @workgroup_size(8, 8)
1189fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1190 let dims = textureDimensions(dst_tex);
1191 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1192 let t = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
1193 let has_uv = (u.p[1].z > u.p[1].x) || (u.p[1].w > u.p[1].y);
1194 let uv = select(
1195 t,
1196 vec2<f32>(mix(u.p[1].x, u.p[1].z, t.x), mix(u.p[1].y, u.p[1].w, t.y)),
1197 has_uv,
1198 );
1199 let has_dod = u.p[4].z > 0.5 && u.p[4].w > 0.5;
1200 let sdims = vec2<f32>(textureDimensions(src_a));
1201 let sample_uv = select(
1202 uv,
1203 (vec2<f32>(uv.x * u.p[4].z, uv.y * u.p[4].w) - u.p[4].xy) / sdims,
1204 has_dod,
1205 );
1206 let nearest = u.p[2].x > 0.5;
1207 var src: vec4<f32>;
1208 if (sample_uv.x < 0.0 || sample_uv.x >= 1.0 || sample_uv.y < 0.0 || sample_uv.y >= 1.0) {
1209 src = vec4<f32>(0.0);
1210 } else if (nearest) {
1211 let isdims = vec2<i32>(textureDimensions(src_a));
1212 let sx = clamp(i32(floor(sample_uv.x * f32(isdims.x))), 0, isdims.x - 1);
1213 let sy = clamp(i32(floor(sample_uv.y * f32(isdims.y))), 0, isdims.y - 1);
1214 src = textureLoad(src_a, vec2<i32>(sx, sy), 0);
1215 } else {
1216 src = textureSampleLevel(src_a, samp_lin, sample_uv, 0.0);
1217 }
1218 let exp_mul = u.p[0].x;
1219 let inv_gamma = 1.0 / max(u.p[0].y, 1e-4);
1220 let ch = i32(u.p[0].z + 0.5);
1221 let checker = u.p[0].w > 0.5;
1222
1223 var out_col = src;
1224 if (ch == 1) {
1225 out_col = vec4<f32>(src.r, src.r, src.r, 1.0);
1226 } else if (ch == 2) {
1227 out_col = vec4<f32>(src.g, src.g, src.g, 1.0);
1228 } else if (ch == 3) {
1229 out_col = vec4<f32>(src.b, src.b, src.b, 1.0);
1230 } else if (ch == 4) {
1231 out_col = vec4<f32>(src.a, src.a, src.a, 1.0);
1232 } else {
1233 var rgb = pow(max(src.rgb * exp_mul, vec3<f32>(0.0)), vec3<f32>(inv_gamma));
1234 if (checker) {
1235 let cx = (gid.x / 16u) & 1u;
1236 let cy = (gid.y / 16u) & 1u;
1237 let bg = select(0.14, 0.20, (cx ^ cy) == 1u);
1238 rgb = rgb + vec3<f32>(bg) * (1.0 - src.a);
1239 out_col = vec4<f32>(rgb, 1.0);
1240 } else {
1241 out_col = vec4<f32>(rgb, src.a);
1242 }
1243 }
1244 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1245}
1246
1247
1248
1249// ============================================================================
1250// 17. InvertColor / Invert Macro
1251// p[0] = (proc_r, proc_g, proc_b, proc_a)
1252// p[1] = (blend, has_mask, mask_invert, 0)
1253// ============================================================================
1254@compute @workgroup_size(8, 8)
1255fn invert_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1256 let dims = textureDimensions(dst_tex);
1257 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1258 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1259 let a = src.a;
1260 let unpre = select(vec3<f32>(0.0), src.rgb / max(a, 1e-5), a > 1e-5);
1261 let new_a = select(a, 1.0 - a, u.p[0].w > 0.5);
1262 let inv_rgb = vec3<f32>(
1263 select(unpre.r, 1.0 - unpre.r, u.p[0].x > 0.5),
1264 select(unpre.g, 1.0 - unpre.g, u.p[0].y > 0.5),
1265 select(unpre.b, 1.0 - unpre.b, u.p[0].z > 0.5),
1266 );
1267 let inv = vec4<f32>(inv_rgb * new_a, new_a);
1268 let m = read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x;
1269 let out_col = mix(src, inv, clamp(m, 0.0, 1.0));
1270 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1271}
1272
1273// ============================================================================
1274// 17b. ChannelBoolean (full Fusion Operation + per-channel ToRed/Green/Blue/Alpha)
1275// src_a = Background, src_b = Foreground (or Background if unconnected)
1276// p[0] = (operation, to_r, to_g, to_b)
1277// p[1] = (to_a, blend, has_mask, mask_invert)
1278// ============================================================================
1279fn cb_pick(ch: i32, bg: vec4<f32>, fg: vec4<f32>, bg_ch: f32) -> f32 {
1280 switch ch {
1281 case 0: { return fg.r; }
1282 case 1: { return fg.g; }
1283 case 2: { return fg.b; }
1284 case 3: { return fg.a; }
1285 case 4: { return bg_ch; } // Do Nothing
1286 case 5: { return bg.r; }
1287 case 6: { return bg.g; }
1288 case 7: { return bg.b; }
1289 case 8: { return bg.a; }
1290 case 9: { return dot(bg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } // Luma BG
1291 case 10: { return dot(fg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } // Luma FG
1292 case 15: { return 0.0; } // Black / Clear
1293 case 16: { return 1.0; } // White / Solid
1294 default: { return fg.r; }
1295 }
1296}
1297
1298fn cb_apply_op(op: i32, bg_v: f32, fg_v: f32) -> f32 {
1299 switch op {
1300 case 0: { return fg_v; } // Copy
1301 case 1: { return bg_v + fg_v; } // Add
1302 case 2: { return bg_v - fg_v; } // Subtract
1303 case 6: { return bg_v * fg_v; } // Multiply
1304 case 7: { return bg_v / max(fg_v, 1e-5); } // Divide
1305 case 8: { return max(bg_v, fg_v); } // Maximum
1306 case 9: { return min(bg_v, fg_v); } // Minimum
1307 case 10: { return 1.0 - fg_v; } // Negative
1308 case 11: { return 1.0; } // Solid
1309 case 12: { return 0.0; } // Clear
1310 case 13: { return abs(bg_v - fg_v); } // Difference
1311 default: { return fg_v; }
1312 }
1313}
1314
1315@compute @workgroup_size(8, 8)
1316fn channel_boolean_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1317 let dims = textureDimensions(dst_tex);
1318 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1319 let bg = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1320 let fu = pix_to_fu(gid.xy, dims);
1321 let fg = sample_dod_edges_mode(src_b, fu, 0, u.p[2], false);
1322
1323 let op = i32(u.p[0].x + 0.5);
1324 let to_r = i32(u.p[0].y + 0.5);
1325 let to_g = i32(u.p[0].z + 0.5);
1326 let to_b = i32(u.p[0].w + 0.5);
1327 let to_a = i32(u.p[1].x + 0.5);
1328
1329 let vr = select(cb_apply_op(op, bg.r, cb_pick(to_r, bg, fg, bg.r)), bg.r, to_r == 4);
1330 let vg = select(cb_apply_op(op, bg.g, cb_pick(to_g, bg, fg, bg.g)), bg.g, to_g == 4);
1331 let vb = select(cb_apply_op(op, bg.b, cb_pick(to_b, bg, fg, bg.b)), bg.b, to_b == 4);
1332 let va = select(cb_apply_op(op, bg.a, cb_pick(to_a, bg, fg, bg.a)), bg.a, to_a == 4);
1333
1334 let res = clamp(vec4<f32>(vr, vg, vb, va), vec4<f32>(0.0), vec4<f32>(1.0));
1335 let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * u.p[1].y;
1336 let out_col = mix(bg, res, clamp(m, 0.0, 1.0));
1337 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1338}
1339
1340
1341// ============================================================================
1342// 18. DirectionalBlur (Type 0=Linear, 1=Centered, 2=Radial, 3=Zoom + Glow)
1343// p[0] = (type, length, angle_rad, glow)
1344// p[1] = (center.x, center.y, blend, has_mask)
1345// p[2] = (mask_invert, sample_count, 0, 0)
1346// ============================================================================
1347@compute @workgroup_size(8, 8)
1348fn dir_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1349 let dims = textureDimensions(dst_tex);
1350 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1351 let fdims = vec2<f32>(dims);
1352 let aspect = fdims.x / max(fdims.y, 1.0);
1353 let fu = pix_to_fu(gid.xy, dims);
1354 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1355
1356 let kind = i32(u.p[0].x + 0.5);
1357 let length_v = u.p[0].y;
1358 let angle = u.p[0].z;
1359 let glow = u.p[0].w;
1360 let center = u.p[1].xy;
1361 let blend = u.p[1].z;
1362 let samples = clamp(i32(u.p[2].y + 0.5), 4, 64);
1363
1364 if (abs(length_v) < 1e-5 && abs(angle) < 1e-5) {
1365 textureStore(dst_tex, vec2<i32>(gid.xy), orig);
1366 return;
1367 }
1368
1369 var acc = vec4<f32>(0.0);
1370 let inv_n = 1.0 / f32(samples);
1371 let dir_vec = vec2<f32>(cos(angle), sin(angle) * aspect);
1372
1373 for (var i = 0; i < samples; i = i + 1) {
1374 let u_t = (f32(i) + 0.5) * inv_n; // 0..1
1375 var s_fu = fu;
1376 if (kind == 0) {
1377 // Type 0 = Linear (one-sided along +Angle)
1378 s_fu = fu + dir_vec * (u_t * length_v);
1379 } else if (kind == 1) {
1380 // Type 1 = Radial (clockwise swirl by -u_t * angle + inward radial step by -u_t * length)
1381 let rel = (fu - center) * vec2<f32>(aspect, 1.0);
1382 let dist = length(rel);
1383 let a = -u_t * angle;
1384 let ca = cos(a);
1385 let sa = sin(a);
1386 let r_rot = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);
1387 let radial_scale = select(0.0, max(1.0 - (u_t * length_v) / dist, 0.0), dist > 1e-5);
1388 s_fu = center + (r_rot * radial_scale) / vec2<f32>(aspect, 1.0);
1389 } else if (kind == 2) {
1390 // Type 2 = Centered (symmetric span of total width length_v along Angle)
1391 s_fu = fu + dir_vec * ((u_t - 0.5) * length_v);
1392 } else {
1393 // Type 3 = Zoom (streaks radiate outward from Center by sampling inward toward Center)
1394 let rel = (fu - center) * vec2<f32>(aspect, 1.0);
1395 let a = -u_t * angle;
1396 let ca = cos(a);
1397 let sa = sin(a);
1398 let r_rot = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);
1399 let scale = max(1.0 - u_t * length_v, 0.05);
1400 s_fu = center + (r_rot * scale) / vec2<f32>(aspect, 1.0);
1401 }
1402 let uv = clamp(fu_to_uv(s_fu), vec2<f32>(0.0), vec2<f32>(1.0));
1403 acc = acc + textureSampleLevel(src_a, samp_lin, uv, 0.0);
1404 }
1405 acc = acc * inv_n;
1406 // Fusion DirectionalBlur Glow brightens streaks smoothly (~1 + 5*glow)
1407 if (glow > 1e-4) {
1408 acc = vec4<f32>(acc.rgb * (1.0 + glow * 5.0), acc.a);
1409 }
1410
1411 let m = read_mask(gid.xy, dims, u.p[1].w, u.p[2].x) * blend;
1412 let out_col = mix(orig, acc, clamp(m, 0.0, 1.0));
1413 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1414}
1415
1416
1417// ============================================================================
1418// 19. ColorGain (Non-luma-preserving HSV Hue shift across Dark/Mid/High + per-channel Gain/Lift/Gamma/Sat)
1419// p[0] = (gain_r, gain_g, gain_b, prediv)
1420// p[1] = (lift_r, lift_g, lift_b, blend)
1421// p[2] = (gamma_r, gamma_g, gamma_b, sat_mid)
1422// p[3] = (dark_hue, mid_hue, high_hue, has_mask)
1423// p[4] = (mask_invert, sat_dark, sat_high, 0)
1424// ============================================================================
1425fn rgb_to_hsv(c: vec3<f32>) -> vec3<f32> {
1426 let k = vec4<f32>(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
1427 let p = select(vec4<f32>(c.gb, k.xy), vec4<f32>(c.bg, k.wz), c.g < c.b);
1428 let q = select(vec4<f32>(c.r, p.yzx), vec4<f32>(p.xyw, c.r), c.r < p.x);
1429 let d = q.x - min(q.w, q.y);
1430 let e = 1.0e-10;
1431 return vec3<f32>(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
1432}
1433
1434fn hsv_to_rgb(c: vec3<f32>) -> vec3<f32> {
1435 let k = vec4<f32>(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
1436 let p = abs(fract(c.xxx + k.xyz) * 6.0 - k.www);
1437 return c.z * mix(k.xxx, clamp(p - k.xxx, vec3<f32>(0.0), vec3<f32>(1.0)), c.y);
1438}
1439
1440@compute @workgroup_size(8, 8)
1441fn color_gain_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1442 let dims = textureDimensions(dst_tex);
1443 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1444 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1445 let gain = u.p[0].xyz;
1446 let prediv = u.p[0].w > 0.5;
1447 let lift = u.p[1].xyz;
1448 let blend = u.p[1].w;
1449 let gamma = max(u.p[2].xyz, vec3<f32>(1e-4));
1450 let sat_mid = u.p[2].w;
1451 let dark_hue = u.p[3].x;
1452 let mid_hue = u.p[3].y;
1453 let high_hue = u.p[3].z;
1454 let sat_dark = u.p[4].y;
1455 let sat_high = u.p[4].z;
1456
1457 var rgb = src.rgb;
1458 if (prediv && src.a > 1e-5) {
1459 rgb = rgb / src.a;
1460 }
1461
1462 // Per-channel Gain -> Lift -> Gamma
1463 rgb = rgb * gain;
1464 rgb = rgb + lift * (1.0 - rgb);
1465 rgb = pow(max(rgb, vec3<f32>(0.0)), vec3<f32>(1.0) / gamma);
1466
1467 // Tonal range weights using HSV Value max(r,g,b) so saturated primaries & outer anti-aliased
1468 // outline edges (>= 0.5) land cleanly in Mid without reddish DarkHue halos, while RGB band blending
1469 // completely prevents green hue-interpolation fringes!
1470 let c_pos = max(rgb, vec3<f32>(0.0));
1471 let lum = clamp(max(c_pos.r, max(c_pos.g, c_pos.b)), 0.0, 1.0);
1472 let w_dark = clamp(1.0 - lum * 2.0, 0.0, 1.0);
1473 let w_high = clamp((lum - 0.5) * 2.0, 0.0, 1.0);
1474 let w_mid = clamp(1.0 - w_dark - w_high, 0.0, 1.0);
1475
1476 // Fusion ColorGain evaluates Dark, High, then Mid sequentially as RGB mixes against base_hsv
1477 // using V = max(r,g,b) for the range curve — matches Fusion 21.1 to ~0.002 and stays green-fringe-free!
1478 let any_hsv = abs(dark_hue) > 1e-5 || abs(mid_hue) > 1e-5 || abs(high_hue) > 1e-5
1479 || abs(sat_dark - 1.0) > 1e-4 || abs(sat_mid - 1.0) > 1e-4 || abs(sat_high - 1.0) > 1e-4;
1480 if (any_hsv) {
1481 let base_hsv = rgb_to_hsv(c_pos);
1482 var cur = c_pos;
1483 if ((abs(dark_hue) > 1e-5 || abs(sat_dark - 1.0) > 1e-4) && w_dark > 1e-5) {
1484 let h_d = vec3<f32>(fract(base_hsv.x + dark_hue), clamp(base_hsv.y * sat_dark, 0.0, 1.0), base_hsv.z);
1485 cur = mix(cur, hsv_to_rgb(h_d), w_dark);
1486 }
1487 if ((abs(high_hue) > 1e-5 || abs(sat_high - 1.0) > 1e-4) && w_high > 1e-5) {
1488 let h_h = vec3<f32>(fract(base_hsv.x + high_hue), clamp(base_hsv.y * sat_high, 0.0, 1.0), base_hsv.z);
1489 cur = mix(cur, hsv_to_rgb(h_h), w_high);
1490 }
1491 if ((abs(mid_hue) > 1e-5 || abs(sat_mid - 1.0) > 1e-4) && w_mid > 1e-5) {
1492 let h_m = vec3<f32>(fract(base_hsv.x + mid_hue), clamp(base_hsv.y * sat_mid, 0.0, 1.0), base_hsv.z);
1493 cur = mix(cur, hsv_to_rgb(h_m), w_mid);
1494 }
1495 rgb = cur;
1496 }
1497
1498 if (prediv) {
1499 rgb = rgb * src.a;
1500 }
1501 let m = read_mask(gid.xy, dims, u.p[3].w, u.p[4].x) * blend;
1502 let out_col = mix(src, vec4<f32>(rgb, src.a), clamp(m, 0.0, 1.0));
1503 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1504}
1505
1506
1507// ============================================================================
1508// 20. ColorCurves (per-channel 256x1 LUT texture in src_b)
1509// p[0] = (prediv, ignore_transparent, blend, has_mask)
1510// p[1] = (mask_invert, apply_alpha, 0, 0)
1511// ============================================================================
1512@compute @workgroup_size(8, 8)
1513fn color_curves_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1514 let dims = textureDimensions(dst_tex);
1515 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1516 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1517 let prediv = u.p[0].x > 0.5;
1518 let ignore_trans = u.p[0].y > 0.5;
1519 let blend = u.p[0].z;
1520 let apply_a = u.p[1].y > 0.5;
1521
1522 if (ignore_trans && src.a <= 1e-5) {
1523 textureStore(dst_tex, vec2<i32>(gid.xy), src);
1524 return;
1525 }
1526
1527 var rgb = src.rgb;
1528 let unpre = (prediv || ignore_trans) && src.a > 1e-5;
1529 if (unpre) {
1530 rgb = clamp(rgb / src.a, vec3<f32>(0.0), vec3<f32>(1.0));
1531 }
1532
1533 let r = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.r, 0.0, 1.0), 0.5), 0.0).r;
1534 let g = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.g, 0.0, 1.0), 0.5), 0.0).g;
1535 let b = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.b, 0.0, 1.0), 0.5), 0.0).b;
1536 var a = src.a;
1537 if (apply_a) {
1538 a = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(src.a, 0.0, 1.0), 0.5), 0.0).a;
1539 }
1540
1541 var out_rgb = vec3<f32>(r, g, b);
1542 if (unpre) {
1543 out_rgb = out_rgb * a;
1544 }
1545 let m = read_mask(gid.xy, dims, u.p[0].w, u.p[1].x) * blend;
1546 let out_col = mix(src, vec4<f32>(out_rgb, a), clamp(m, 0.0, 1.0));
1547 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1548}
1549
1550
1551// ============================================================================
1552// 21. Fuse.XfChroma (Chromatic Aberration multi-step transform + Gradient LUT in src_b)
1553// p[0] = (center.x, center.y, pivot.x, pivot.y) (MasterFactor already applied)
1554// p[1] = (xsize, ysize, angle_rad, steps)
1555// p[2] = (acc_mode: 0=Add,1=Screen,2=Max,3=Merge, normalize, gain, gamma)
1556// p[3] = (blend, has_mask, mask_invert, 0)
1557// p[4] = (dod_ox, dod_oy, dod_cw, dod_ch)
1558// ============================================================================
1559@compute @workgroup_size(8, 8)
1560fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1561 let dims = textureDimensions(dst_tex);
1562 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1563 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1564 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
1565 let fu = pix_to_fu(gid.xy, dims);
1566
1567 let center = u.p[0].xy;
1568 let pivot = u.p[0].zw;
1569 let xsize = u.p[1].x;
1570 let ysize = u.p[1].y;
1571 let angle = u.p[1].z;
1572 let steps = clamp(i32(u.p[1].w + 0.5), 1, 32);
1573 let acc_mode = i32(u.p[2].x + 0.5);
1574 let normalize = u.p[2].y > 0.5;
1575 let gain = u.p[2].z;
1576 let gamma = max(u.p[2].w, 0.05);
1577 let blend = u.p[3].x;
1578
1579 var acc = vec4<f32>(0.0);
1580 var grad_sum = vec4<f32>(0.0);
1581 let inv_steps = 1.0 / f32(steps);
1582
1583 for (var i = 0; i <= steps; i = i + 1) {
1584 let n = f32(i) * inv_steps;
1585 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(n, 0.5), 0.0);
1586
1587 let cur_c = mix(vec2<f32>(0.5, 0.5), center, n);
1588 let cur_sx = max(mix(1.0, xsize, n), 1e-4);
1589 let cur_sy = max(mix(1.0, ysize, n), 1e-4);
1590 let cur_a = angle * n;
1591
1592 // Inverse transform matching Fusion Transform/XfChroma around pivot
1593 let rel = (fu - cur_c + (pivot - vec2<f32>(0.5, 0.5))) * vec2<f32>(aspect, 1.0);
1594 let ca = cos(cur_a);
1595 let sa = sin(cur_a);
1596 let rot = vec2<f32>(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca);
1597 let scaled = rot / vec2<f32>(cur_sx, cur_sy);
1598 let src_fu = pivot + scaled / vec2<f32>(aspect, 1.0);
1599
1600 var s = sample_dod_edges_mode(src_a, src_fu, 0, u.p[4], false);
1601 if (abs(gamma - 1.0) > 1e-3) {
1602 s = vec4<f32>(pow(max(s.rgb, vec3<f32>(0.0)), vec3<f32>(gamma)), s.a);
1603 }
1604 let tinted = s * grad;
1605 grad_sum = grad_sum + grad;
1606
1607 if (acc_mode == 0) {
1608 acc = acc + tinted;
1609 } else if (acc_mode == 1) {
1610 acc = vec4<f32>(1.0) - (vec4<f32>(1.0) - acc) * (vec4<f32>(1.0) - tinted);
1611 } else if (acc_mode == 2) {
1612 acc = max(acc, tinted);
1613 } else {
1614 acc = tinted + acc * (1.0 - tinted.a);
1615 }
1616 }
1617
1618 if (normalize && acc_mode == 0) {
1619 acc = vec4<f32>(
1620 select(acc.r, acc.r / grad_sum.r, grad_sum.r > 1e-5),
1621 select(acc.g, acc.g / grad_sum.g, grad_sum.g > 1e-5),
1622 select(acc.b, acc.b / grad_sum.b, grad_sum.b > 1e-5),
1623 select(acc.a, acc.a / grad_sum.a, grad_sum.a > 1e-5),
1624 );
1625 }
1626 if (abs(gamma - 1.0) > 1e-3) {
1627 acc = vec4<f32>(pow(max(acc.rgb, vec3<f32>(0.0)), vec3<f32>(1.0 / gamma)), acc.a);
1628 }
1629 acc = vec4<f32>(acc.rgb * gain, clamp(acc.a, 0.0, 1.0));
1630
1631 let m = read_mask(gid.xy, dims, u.p[3].y, u.p[3].z) * blend;
1632 let out_col = mix(orig, acc, clamp(m, 0.0, 1.0));
1633 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1634}
1635
1636
1637// ============================================================================
1638// 22. GamutConvert (sRGB / Rec.709 / Gamma transfer conversion)
1639// p[0] = (src_space: 0=None/Linear,1=sRGB,2=Rec709, dst_space: 0=None/Linear,1=sRGB,2=Rec709, prediv, blend)
1640// p[1] = (has_mask, mask_invert, 0, 0)
1641// ============================================================================
1642fn srgb_to_linear_ch(c: f32) -> f32 {
1643 if (c <= 0.04045) { return c / 12.92; }
1644 return pow((c + 0.055) / 1.055, 2.4);
1645}
1646fn linear_to_srgb_ch(c: f32) -> f32 {
1647 let x = max(c, 0.0);
1648 if (x <= 0.0031308) { return x * 12.92; }
1649 return 1.055 * pow(x, 1.0 / 2.4) - 0.055;
1650}
1651fn rec709_to_linear_ch(c: f32) -> f32 {
1652 if (c < 0.081) { return c / 4.5; }
1653 return pow((c + 0.099) / 1.099, 1.0 / 0.45);
1654}
1655fn linear_to_rec709_ch(c: f32) -> f32 {
1656 let x = max(c, 0.0);
1657 if (x < 0.018) { return x * 4.5; }
1658 return 1.099 * pow(x, 0.45) - 0.099;
1659}
1660
1661@compute @workgroup_size(8, 8)
1662fn gamut_convert_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1663 let dims = textureDimensions(dst_tex);
1664 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1665 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1666 let src_sp = i32(u.p[0].x + 0.5);
1667 let dst_sp = i32(u.p[0].y + 0.5);
1668 let prediv = u.p[0].z > 0.5;
1669 let blend = u.p[0].w;
1670
1671 var rgb = src.rgb;
1672 if (prediv && src.a > 1e-5) {
1673 rgb = rgb / src.a;
1674 }
1675
1676 // Remove source gamma -> Linear
1677 if (src_sp == 1) {
1678 rgb = vec3<f32>(srgb_to_linear_ch(rgb.r), srgb_to_linear_ch(rgb.g), srgb_to_linear_ch(rgb.b));
1679 } else if (src_sp == 2) {
1680 rgb = vec3<f32>(rec709_to_linear_ch(rgb.r), rec709_to_linear_ch(rgb.g), rec709_to_linear_ch(rgb.b));
1681 }
1682 // Add destination gamma <- Linear
1683 if (dst_sp == 1) {
1684 rgb = vec3<f32>(linear_to_srgb_ch(rgb.r), linear_to_srgb_ch(rgb.g), linear_to_srgb_ch(rgb.b));
1685 } else if (dst_sp == 2) {
1686 rgb = vec3<f32>(linear_to_rec709_ch(rgb.r), linear_to_rec709_ch(rgb.g), linear_to_rec709_ch(rgb.b));
1687 }
1688
1689 if (prediv) {
1690 rgb = rgb * src.a;
1691 }
1692 let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * blend;
1693 let out_col = mix(src, vec4<f32>(rgb, src.a), clamp(m, 0.0, 1.0));
1694 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1695}
1696
1697
1698// ============================================================================
1699// 23. VariBlur (per-pixel variable blur driven by BlurImage in src_b)
1700// p[0] = (radius_x_px, radius_y_px, has_blur_map, blend)
1701// p[1] = (has_mask, mask_invert, taps, 0)
1702// ============================================================================
1703@compute @workgroup_size(8, 8)
1704fn vari_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1705 let dims = textureDimensions(dst_tex);
1706 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
1707 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
1708 let fdims = vec2<f32>(dims);
1709 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
1710 var factor = 1.0;
1711 if (u.p[0].z > 0.5) {
1712 let bm = textureSampleLevel(src_b, samp_lin, uv, 0.0);
1713 factor = dot(bm.rgb, vec3<f32>(0.299, 0.587, 0.114));
1714 }
1715 let rx = u.p[0].x * factor;
1716 let ry = u.p[0].y * factor;
1717 if (max(rx, ry) < 0.25) {
1718 textureStore(dst_tex, vec2<i32>(gid.xy), orig);
1719 return;
1720 }
1721 // 2D Poisson-like concentric disc tap kernel
1722 let rings = clamp(i32(u.p[1].z + 0.5), 2, 4);
1723 var acc = orig;
1724 var wsum = 1.0;
1725 for (var ring = 1; ring <= rings; ring = ring + 1) {
1726 let rf = f32(ring) / f32(rings);
1727 let n_ang = ring * 6;
1728 let w = exp(-rf * rf * 2.0);
1729 for (var a = 0; a < n_ang; a = a + 1) {
1730 let ang = f32(a) * 6.28318530718 / f32(n_ang);
1731 let off = vec2<f32>(cos(ang) * rx * rf, sin(ang) * ry * rf) / fdims;
1732 let suv = clamp(uv + off, vec2<f32>(0.0), vec2<f32>(1.0));
1733 acc = acc + textureSampleLevel(src_a, samp_lin, suv, 0.0) * w;
1734 wsum = wsum + w;
1735 }
1736 }
1737 let blurred = acc / wsum;
1738 let m = read_mask(gid.xy, dims, u.p[1].x, u.p[1].y) * u.p[0].w;
1739 let out_col = mix(orig, blurred, clamp(m, 0.0, 1.0));
1740 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0)));
1741}
crates/flow/Cargo.toml created+13
...@@ -0,0 +1,13 @@
1[package]
2name = "flow"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[dependencies]
8draw.workspace = true
9model.workspace = true
10text.workspace = true
11theme.workspace = true
12ui.workspace = true
13winit.workspace = true
crates/flow/src/lib.rs created+1162
...@@ -0,0 +1,1162 @@
1//! Node Flow canvas built on `draw` + `ui`:
2//! - Sleek thin Fusion-style node bars with colored bottom stripe
3//! - Auto-wrapping output/input ports that snap to whichever side faces connected nodes
4//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal)
5//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks
6//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.
7
8use draw::{Glyphs, PathStyle, Primitive};
9use model::{Comp, NodeId, PortRole, default_main_input_port};
10use std::collections::{HashMap, HashSet};
11use std::sync::Arc;
12use winit::event::{ElementState, MouseButton};
13use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
14
15// Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires).
16const NODE_W: f32 = 84.0;
17const NODE_H: f32 = 21.0;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum TransformMode {
21 Grab,
22 Rotate,
23 Scale,
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum AxisLock {
28 None,
29 X,
30 Y,
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34enum Edge {
35 Left,
36 Right,
37 Top,
38 Bottom,
39}
40
41impl Edge {
42 fn normal(self) -> [f32; 2] {
43 match self {
44 Edge::Left => [-1.0, 0.0],
45 Edge::Right => [1.0, 0.0],
46 Edge::Top => [0.0, -1.0],
47 Edge::Bottom => [0.0, 1.0],
48 }
49 }
50
51 fn point_on_rect(self, r: [f32; 4], t: f32) -> [f32; 2] {
52 match self {
53 Edge::Left => [r[0], r[1] + (r[3] - r[1]) * t],
54 Edge::Right => [r[2], r[1] + (r[3] - r[1]) * t],
55 Edge::Top => [r[0] + (r[2] - r[0]) * t, r[1]],
56 Edge::Bottom => [r[0] + (r[2] - r[0]) * t, r[3]],
57 }
58 }
59}
60
61#[derive(Clone, Debug)]
62struct ModalTransform {
63 mode: TransformMode,
64 axis: AxisLock,
65 pivot_world: [f32; 2],
66 start_pointer_world: [f32; 2],
67 saved_positions: Vec<(NodeId, [f32; 2])>,
68}
69
70#[derive(Clone, Debug)]
71struct WireDrag {
72 src: NodeId,
73 cursor_local: [f32; 2],
74}
75
76#[derive(Clone, Debug)]
77struct BoxSelect {
78 start_local: [f32; 2],
79 cur_local: [f32; 2],
80}
81
82#[derive(Clone, Debug)]
83pub enum FlowAction {
84 SelectionChanged(Option<NodeId>),
85 /// Slot 0 = Viewer 1 (`1` key), Slot 1 = Viewer 2 (`2` key).
86 ViewNode(usize, NodeId),
87 /// `` ` `` key: clear both Viewer 1 and Viewer 2.
88 ClearViewers,
89 GraphMutated,
90}
91
92#[derive(Clone, Debug)]
93struct WireRef {
94 src: NodeId,
95 dst: NodeId,
96 port: String,
97}
98
99#[derive(Clone, Copy, Debug)]
100pub struct FlowPalette {
101 pub bg: [f32; 4],
102 pub grid_minor: [f32; 4],
103 pub grid_major: [f32; 4],
104 pub node_fill: [f32; 4],
105 pub node_hover: [f32; 4],
106 pub node_selected: [f32; 4],
107 pub node_border: [f32; 4],
108 pub text: [f32; 4],
109 pub text_dim: [f32; 4],
110 pub accent: [f32; 4],
111}
112
113impl FlowPalette {
114 pub fn from_ui(theme: &ui::Theme) -> Self {
115 let b = theme.base;
116 let lift = |c: [f32; 4], d: f32| {
117 [(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]
118 };
119 Self {
120 bg: b,
121 grid_minor: lift(b, 0.012),
122 grid_major: lift(b, 0.028),
123 node_fill: lift(b, 0.036),
124 node_hover: lift(b, 0.056),
125 node_selected: lift(b, 0.078),
126 node_border: theme.chip,
127 text: theme.text,
128 text_dim: theme.text_dim,
129 accent: theme.accent,
130 }
131 }
132}
133
134pub struct FlowView {
135 pub pan: [f32; 2],
136 pub zoom: f32,
137 pub size: [f32; 2],
138 pub selected: HashSet<NodeId>,
139 pub primary: Option<NodeId>,
140 /// `[viewer_1_node, viewer_2_node]`.
141 pub viewed_nodes: [Option<NodeId>; 2],
142 pub palette: FlowPalette,
143 hovered_node: Option<NodeId>,
144 hovered_wire: Option<WireRef>,
145 modal: Option<ModalTransform>,
146 wire_drag: Option<WireDrag>,
147 box_select: Option<BoxSelect>,
148 panning: Option<([f32; 2], [f32; 2])>,
149 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,
150 pointer_local: [f32; 2],
151 label_cache: HashMap<String, text::Layout>,
152 badge_cache: HashMap<String, text::Layout>,
153 fitted_once: bool,
154}
155
156impl FlowView {
157 pub fn new(theme: &ui::Theme) -> Self {
158 Self {
159 pan: [0.0, 0.0],
160 zoom: 1.0,
161 size: [800.0, 500.0],
162 selected: HashSet::new(),
163 primary: None,
164 viewed_nodes: [None, None],
165 palette: FlowPalette::from_ui(theme),
166 hovered_node: None,
167 hovered_wire: None,
168 modal: None,
169 wire_drag: None,
170 box_select: None,
171 panning: None,
172 lmb_drag_node: None,
173 pointer_local: [0.0, 0.0],
174 label_cache: HashMap::new(),
175 badge_cache: HashMap::new(),
176 fitted_once: false,
177 }
178 }
179
180 pub fn resize(&mut self, size: [f32; 2]) {
181 self.size = [size[0].max(1.0), size[1].max(1.0)];
182 }
183
184 pub fn background(&self) -> [f32; 4] {
185 self.palette.bg
186 }
187
188 pub fn fit_all(&mut self, comp: &Comp) {
189 let ids: Vec<NodeId> = if !self.selected.is_empty() {
190 self.selected.iter().copied().collect()
191 } else {
192 comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect()
193 };
194 self.fit_ids(comp, ids);
195 }
196
197 pub fn fit_comp(&mut self, comp: &Comp) {
198 let ids: Vec<NodeId> = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect();
199 self.fit_ids(comp, ids);
200 }
201
202 fn fit_ids(&mut self, comp: &Comp, target_ids: Vec<NodeId>) {
203 if target_ids.is_empty() {
204 return;
205 }
206 let mut min_x = f32::INFINITY;
207 let mut min_y = f32::INFINITY;
208 let mut max_x = f32::NEG_INFINITY;
209 let mut max_y = f32::NEG_INFINITY;
210 for id in target_ids {
211 let p = comp.node(id).pos;
212 min_x = min_x.min(p[0] - NODE_W * 0.5);
213 max_x = max_x.max(p[0] + NODE_W * 0.5);
214 min_y = min_y.min(p[1] - NODE_H * 0.5);
215 max_y = max_y.max(p[1] + NODE_H * 0.5);
216 }
217 let span_x = (max_x - min_x).max(200.0);
218 let span_y = (max_y - min_y).max(120.0);
219 let pad = 64.0;
220 let zx = ((self.size[0] - pad) / span_x).clamp(0.15, 1.5);
221 let zy = ((self.size[1] - pad) / span_y).clamp(0.15, 1.5);
222 self.zoom = zx.min(zy);
223 self.pan = [(min_x + max_x) * 0.5, (min_y + max_y) * 0.5];
224 self.fitted_once = true;
225 }
226
227 pub fn ensure_fitted(&mut self, comp: &Comp) {
228 if !self.fitted_once && self.size[0] > 40.0 && self.size[1] > 40.0 {
229 self.fit_comp(comp);
230 }
231 }
232
233 fn world_to_local(&self, w: [f32; 2]) -> [f32; 2] {
234 [
235 (w[0] - self.pan[0]) * self.zoom + self.size[0] * 0.5,
236 (w[1] - self.pan[1]) * self.zoom + self.size[1] * 0.5,
237 ]
238 }
239
240 fn local_to_world(&self, l: [f32; 2]) -> [f32; 2] {
241 [
242 (l[0] - self.size[0] * 0.5) / self.zoom + self.pan[0],
243 (l[1] - self.size[1] * 0.5) / self.zoom + self.pan[1],
244 ]
245 }
246
247 fn node_rect_local(&self, pos: [f32; 2]) -> [f32; 4] {
248 let c = self.world_to_local(pos);
249 let hw = NODE_W * 0.5 * self.zoom;
250 let hh = NODE_H * 0.5 * self.zoom;
251 [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh]
252 }
253
254 /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the
255 /// closest facing sides of each node (Fusion's signature clean multi-directional routing!).
256 fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) {
257 let sp = comp.node(src).pos;
258 let dp = comp.node(dst).pos;
259 let sr = self.node_rect_local(sp);
260 let dr = self.node_rect_local(dp);
261
262 let dx = dp[0] - sp[0];
263 let dy = dp[1] - sp[1];
264 // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)!
265 let out_edge = closest_edge(dx, dy);
266 let in_edge = closest_edge_for_input(-dx, -dy, role);
267
268 let a = out_edge.point_on_rect(sr, 0.5);
269 let b = in_edge.point_on_rect(dr, 0.5);
270 (a, out_edge, b, in_edge)
271 }
272
273 /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right).
274 fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge {
275 let name = &comp.node(id).name;
276 let sp = comp.node(id).pos;
277 let mut sx = 0.0_f32;
278 let mut sy = 0.0_f32;
279 let mut count = 0;
280 for other in &comp.nodes {
281 for binding in other.inputs.values() {
282 if binding.source_op.as_deref() == Some(name.as_str()) {
283 let dx = other.pos[0] - sp[0];
284 let dy = other.pos[1] - sp[1];
285 let len = (dx * dx + dy * dy).sqrt().max(1.0);
286 sx += dx / len;
287 sy += dy / len;
288 count += 1;
289 }
290 }
291 }
292 if count == 0 {
293 Edge::Right
294 } else {
295 closest_edge(sx, sy)
296 }
297 }
298
299 fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
300 for n in comp.nodes.iter().rev() {
301 if n.internal { continue; }
302 let r = self.node_rect_local(n.pos);
303 if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] {
304 return Some(n.id);
305 }
306 }
307 None
308 }
309
310 fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
311 for n in comp.nodes.iter().rev() {
312 if n.internal { continue; }
313 let r = self.node_rect_local(n.pos);
314 let edge = self.node_output_edge(comp, n.id);
315 let nrm = edge.normal();
316 let p0 = edge.point_on_rect(r, 0.5);
317 let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0];
318 let dx = local[0] - p[0];
319 let dy = local[1] - p[1];
320 if dx * dx + dy * dy <= 10.0 * 10.0 {
321 return Some(n.id);
322 }
323 }
324 None
325 }
326
327 fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {
328 for n in comp.nodes.iter().rev() {
329 let r = self.node_rect_local(n.pos);
330 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 {
331 // Pick Background/Foreground/Mask cleanly based on approach edge for Merge!
332 if n.kind == "Merge" || n.kind == "Displace" {
333 let cy = (r[1] + r[3]) * 0.5;
334 if local[1] < r[1] + 2.0 {
335 return Some((n.id, "Foreground"));
336 }
337 if local[1] > r[3] - 2.0 {
338 return Some((n.id, "EffectMask"));
339 }
340 let _ = cy;
341 }
342 return Some((n.id, default_main_input_port(&n.kind)));
343 }
344 }
345 None
346 }
347
348 fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {
349 let mut best: Option<(f32, WireRef)> = None;
350 for dst in &comp.nodes {
351 if Some(dst.id) == ignore_node {
352 continue;
353 }
354 for (port, binding) in &dst.inputs {
355 let Some(src_name) = &binding.source_op else { continue };
356 let Some(src_id) = comp.find_node(src_name) else { continue };
357 if Some(src_id) == ignore_node {
358 continue;
359 }
360 let role = PortRole::from_input_name(port);
361 let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);
362 let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom);
363 if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) {
364 best = Some((
365 d,
366 WireRef {
367 src: src_id,
368 dst: dst.id,
369 port: port.clone(),
370 },
371 ));
372 }
373 }
374 }
375 best.map(|(_, w)| w)
376 }
377
378 fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) {
379 if self.selected.is_empty() {
380 return;
381 }
382 let mut cx = 0.0_f32;
383 let mut cy = 0.0_f32;
384 let mut saved = Vec::with_capacity(self.selected.len());
385 for &id in &self.selected {
386 let p = comp.node(id).pos;
387 cx += p[0];
388 cy += p[1];
389 saved.push((id, p));
390 }
391 let n = saved.len() as f32;
392 self.modal = Some(ModalTransform {
393 mode,
394 axis: AxisLock::None,
395 pivot_world: [cx / n, cy / n],
396 start_pointer_world: self.local_to_world(self.pointer_local),
397 saved_positions: saved,
398 });
399 }
400
401 fn apply_modal(&mut self, comp: &mut Comp) {
402 let Some(m) = &self.modal else { return };
403 let cur = self.local_to_world(self.pointer_local);
404 let dx = cur[0] - m.start_pointer_world[0];
405 let dy = cur[1] - m.start_pointer_world[1];
406 let piv = m.pivot_world;
407
408 match m.mode {
409 TransformMode::Grab => {
410 let (mx, my) = match m.axis {
411 AxisLock::None => (dx, dy),
412 AxisLock::X => (dx, 0.0),
413 AxisLock::Y => (0.0, dy),
414 };
415 for &(id, orig) in &m.saved_positions {
416 comp.node_mut(id).pos = [orig[0] + mx, orig[1] + my];
417 }
418 }
419 TransformMode::Rotate => {
420 let a0 = (m.start_pointer_world[1] - piv[1]).atan2(m.start_pointer_world[0] - piv[0]);
421 let a1 = (cur[1] - piv[1]).atan2(cur[0] - piv[0]);
422 let da = a1 - a0;
423 let (c, s) = (da.cos(), da.sin());
424 for &(id, orig) in &m.saved_positions {
425 let rx = orig[0] - piv[0];
426 let ry = orig[1] - piv[1];
427 comp.node_mut(id).pos = [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c];
428 }
429 }
430 TransformMode::Scale => {
431 let d0 = ((m.start_pointer_world[0] - piv[0]).powi(2) + (m.start_pointer_world[1] - piv[1]).powi(2)).sqrt().max(12.0);
432 let d1 = ((cur[0] - piv[0]).powi(2) + (cur[1] - piv[1]).powi(2)).sqrt();
433 let factor = (d1 / d0).clamp(0.1, 10.0);
434 let (sx, sy) = match m.axis {
435 AxisLock::None => (factor, factor),
436 AxisLock::X => (factor, 1.0),
437 AxisLock::Y => (1.0, factor),
438 };
439 for &(id, orig) in &m.saved_positions {
440 comp.node_mut(id).pos = [
441 piv[0] + (orig[0] - piv[0]) * sx,
442 piv[1] + (orig[1] - piv[1]) * sy,
443 ];
444 }
445 }
446 }
447 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {
448 let id = m.saved_positions[0].0;
449 let c_local = self.world_to_local(comp.node(id).pos);
450 self.hovered_wire = self.hit_wire(comp, c_local, Some(id));
451 } else {
452 self.hovered_wire = None;
453 }
454 }
455
456 fn cancel_modal(&mut self, comp: &mut Comp) {
457 if let Some(m) = self.modal.take() {
458 for (id, orig) in m.saved_positions {
459 comp.node_mut(id).pos = orig;
460 }
461 }
462 self.hovered_wire = None;
463 }
464
465 fn confirm_modal(&mut self, comp: &mut Comp) -> bool {
466 let mut mutated = false;
467 if let Some(m) = self.modal.take() {
468 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {
469 let id = m.saved_positions[0].0;
470 if let Some(w) = self.hovered_wire.take() {
471 comp.insert_on_wire(id, w.src, w.dst, &w.port);
472 mutated = true;
473 }
474 }
475 }
476 self.hovered_wire = None;
477 mutated
478 }
479
480 fn handle_key(&mut self, comp: &mut Comp, physical: Option<PhysicalKey>, key: &Key, kmod: ModifiersState, actions: &mut Vec<FlowAction>) {
481 // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F
482 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
483 self.fit_all(comp);
484 return;
485 }
486 if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) {
487 self.viewed_nodes = [None, None];
488 actions.push(FlowAction::ClearViewers);
489 return;
490 }
491 match key {
492 Key::Named(NamedKey::Escape) => {
493 if self.modal.is_some() {
494 self.cancel_modal(comp);
495 }
496 self.wire_drag = None;
497 }
498 Key::Named(NamedKey::Enter) => {
499 if self.modal.is_some() && self.confirm_modal(comp) {
500 actions.push(FlowAction::GraphMutated);
501 }
502 }
503 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
504 "`" | "~" => {
505 self.viewed_nodes = [None, None];
506 actions.push(FlowAction::ClearViewers);
507 }
508 "f" if kmod.super_key() => self.fit_all(comp),
509 "f" if !kmod.super_key() => self.fit_all(comp),
510 "." if !kmod.super_key() => self.fit_all(comp),
511 "g" if !kmod.super_key() && self.modal.is_none() => {
512 self.begin_modal(comp, TransformMode::Grab);
513 }
514 "r" if !kmod.super_key() && self.modal.is_none() => {
515 self.begin_modal(comp, TransformMode::Rotate);
516 }
517 "s" if !kmod.super_key() && self.modal.is_none() => {
518 self.begin_modal(comp, TransformMode::Scale);
519 }
520 "x" if self.modal.is_some() => {
521 if let Some(m) = &mut self.modal {
522 m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X };
523 }
524 self.apply_modal(comp);
525 }
526 "y" if self.modal.is_some() => {
527 if let Some(m) = &mut self.modal {
528 m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y };
529 }
530 self.apply_modal(comp);
531 }
532 "a" if !kmod.super_key() => {
533 if self.selected.len() == comp.nodes.len() {
534 self.selected.clear();
535 self.primary = None;
536 } else {
537 self.selected = comp.nodes.iter().map(|n| n.id).collect();
538 self.primary = comp.nodes.first().map(|n| n.id);
539 }
540 actions.push(FlowAction::SelectionChanged(self.primary));
541 }
542 "1" if !kmod.super_key() => {
543 if let Some(id) = self.primary {
544 self.viewed_nodes[0] = Some(id);
545 actions.push(FlowAction::ViewNode(0, id));
546 }
547 }
548 "2" if !kmod.super_key() => {
549 if let Some(id) = self.primary {
550 self.viewed_nodes[1] = Some(id);
551 actions.push(FlowAction::ViewNode(1, id));
552 }
553 }
554 "p" => {
555 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
556 for id in ids {
557 comp.toggle_bypass(id);
558 }
559 if !self.selected.is_empty() {
560 actions.push(FlowAction::GraphMutated);
561 }
562 }
563 _ => {}
564 },
565 _ => {}
566 }
567 }
568
569 pub fn input(
570 &mut self,
571 comp: &mut Comp,
572 event: ui::Event,
573 rect: [f32; 4],
574 pointer_window: [f32; 2],
575 modifiers: ModifiersState,
576 ) -> Vec<FlowAction> {
577 let mut actions = Vec::new();
578 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
579
580 match event {
581 ui::Event::PointerMoved(p) => {
582 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
583 if let Some((start_p, start_pan)) = self.panning {
584 self.pan = [
585 start_pan[0] - (self.pointer_local[0] - start_p[0]) / self.zoom,
586 start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom,
587 ];
588 } else if self.modal.is_some() {
589 self.apply_modal(comp);
590 } else if let Some(wd) = &mut self.wire_drag {
591 wd.cursor_local = self.pointer_local;
592 } else if let Some(bs) = &mut self.box_select {
593 bs.cur_local = self.pointer_local;
594 } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node {
595 let dx = self.pointer_local[0] - start_l[0];
596 let dy = self.pointer_local[1] - start_l[1];
597 if !*moved && dx * dx + dy * dy > 16.0 {
598 *moved = true;
599 if !self.selected.contains(&nid) {
600 self.selected.clear();
601 self.selected.insert(nid);
602 self.primary = Some(nid);
603 actions.push(FlowAction::SelectionChanged(self.primary));
604 }
605 self.begin_modal(comp, TransformMode::Grab);
606 }
607 } else {
608 self.hovered_node = self.hit_node(comp, self.pointer_local);
609 self.hovered_wire = if self.hovered_node.is_none() {
610 self.hit_wire(comp, self.pointer_local, None)
611 } else {
612 None
613 };
614 }
615 }
616 ui::Event::Button { button, pressed, .. } => {
617 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
618 if pressed {
619 self.panning = Some((self.pointer_local, self.pan));
620 } else {
621 self.panning = None;
622 }
623 } else if button == MouseButton::Right {
624 if pressed && self.modal.is_some() {
625 self.cancel_modal(comp);
626 } else if pressed && self.wire_drag.is_some() {
627 self.wire_drag = None;
628 }
629 } else if button == MouseButton::Left {
630 if pressed {
631 if self.modal.is_some() {
632 if self.confirm_modal(comp) {
633 actions.push(FlowAction::GraphMutated);
634 }
635 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) {
636 self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local });
637 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
638 if modifiers.shift_key() {
639 if !self.selected.remove(&nid) {
640 self.selected.insert(nid);
641 self.primary = Some(nid);
642 }
643 } else if !self.selected.contains(&nid) {
644 self.selected.clear();
645 self.selected.insert(nid);
646 self.primary = Some(nid);
647 } else {
648 self.primary = Some(nid);
649 }
650 actions.push(FlowAction::SelectionChanged(self.primary));
651 self.lmb_drag_node = Some((nid, self.pointer_local, false));
652 } else {
653 if !modifiers.shift_key() {
654 self.selected.clear();
655 self.primary = None;
656 actions.push(FlowAction::SelectionChanged(None));
657 }
658 self.box_select = Some(BoxSelect {
659 start_local: self.pointer_local,
660 cur_local: self.pointer_local,
661 });
662 }
663 } else {
664 if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() {
665 if moved && self.modal.is_some() {
666 if self.confirm_modal(comp) {
667 actions.push(FlowAction::GraphMutated);
668 }
669 }
670 }
671 if let Some(wd) = self.wire_drag.take() {
672 if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) {
673 comp.connect(wd.src, dst, port);
674 actions.push(FlowAction::GraphMutated);
675 }
676 }
677 if let Some(bs) = self.box_select.take() {
678 let x0 = bs.start_local[0].min(bs.cur_local[0]);
679 let x1 = bs.start_local[0].max(bs.cur_local[0]);
680 let y0 = bs.start_local[1].min(bs.cur_local[1]);
681 let y1 = bs.start_local[1].max(bs.cur_local[1]);
682 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
683 for n in &comp.nodes {
684 let c = self.world_to_local(n.pos);
685 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {
686 self.selected.insert(n.id);
687 self.primary = Some(n.id);
688 }
689 }
690 actions.push(FlowAction::SelectionChanged(self.primary));
691 }
692 }
693 }
694 }
695 }
696 ui::Event::Wheel(delta) => {
697 // Blender & Fusion convention: plain scroll zooms toward mouse cursor; Shift+scroll pans.
698 if modifiers.shift_key() {
699 self.pan[0] -= delta[0] / self.zoom;
700 self.pan[1] -= delta[1] / self.zoom;
701 } else {
702 let factor = (1.0 + delta[1] * 0.0045).clamp(0.7, 1.4);
703 self.zoom_at(factor, self.pointer_local);
704 }
705 }
706 ui::Event::Pinch(delta) => {
707 let factor = (1.0 + delta).clamp(0.7, 1.4);
708 self.zoom_at(factor, self.pointer_local);
709 }
710 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
711 self.handle_key(comp, Some(physical), &key, kmod, &mut actions);
712 }
713 ui::Event::Key { key, modifiers: kmod, .. } => {
714 self.handle_key(comp, None, &key, kmod, &mut actions);
715 }
716 _ => {}
717 }
718
719 actions
720 }
721
722 fn zoom_at(&mut self, factor: f32, pivot_local: [f32; 2]) {
723 let before = self.local_to_world(pivot_local);
724 self.zoom = (self.zoom * factor).clamp(0.12, 3.5);
725 let after = self.local_to_world(pivot_local);
726 self.pan[0] += before[0] - after[0];
727 self.pan[1] += before[1] - after[1];
728 }
729
730 pub fn prepare_labels(&mut self, comp: &Comp) {
731 let label_font = text::Font {
732 families: Arc::from([text::Family::Sans]),
733 size: 9.5,
734 weight: 500,
735 italic: false,
736 };
737 let badge_font = text::Font {
738 families: Arc::from([text::Family::Mono]),
739 size: 10.0,
740 weight: 500,
741 italic: false,
742 };
743 let make_layout = |s: &str, font: &text::Font| {
744 let styles = [text::Style::new(font.clone())];
745 text::Paragraph {
746 text: s,
747 styles: &styles,
748 spans: &[],
749 replacements: &[],
750 width: None,
751 indent: 0.0,
752 line_height: 1.2,
753 align: text::Align::Left,
754 tab: 32.0,
755 }
756 .layout()
757 };
758 for n in &comp.nodes {
759 self.label_cache.entry(n.name.clone()).or_insert_with(|| make_layout(&n.name, &label_font));
760 }
761 for key in [
762 "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom",
763 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
764 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
765 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
766 ] {
767 self.badge_cache.entry(key.to_owned()).or_insert_with(|| make_layout(key, &badge_font));
768 }
769 }
770
771 pub fn paint<'a>(&'a self, comp: &'a Comp) -> Vec<Primitive<'a>> {
772 let mut out = Vec::with_capacity(comp.nodes.len() * 10 + 128);
773 let [w, h] = self.size;
774
775 // 1. Subtle architectural grid aligned to Fusion's 110×33 flow cells
776 let mult = if self.zoom < 0.35 { 4.0 } else if self.zoom < 0.70 { 2.0 } else { 1.0 };
777 let step_x = 110.0 * mult;
778 let step_y = 33.0 * mult * 2.0;
779 let tl = self.local_to_world([0.0, 0.0]);
780 let br = self.local_to_world([w, h]);
781 let gx0 = (tl[0] / step_x).floor() as i32;
782 let gx1 = (br[0] / step_x).ceil() as i32;
783 let gy0 = (tl[1] / step_y).floor() as i32;
784 let gy1 = (br[1] / step_y).ceil() as i32;
785 for gx in gx0..=gx1 {
786 let x = self.world_to_local([gx as f32 * step_x, 0.0])[0];
787 let col = if gx % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor };
788 out.push(Primitive::Segment { from: [x, 0.0], to: [x, h], width: 1.0, color: col });
789 }
790 for gy in gy0..=gy1 {
791 let y = self.world_to_local([0.0, gy as f32 * step_y])[1];
792 let col = if gy % 4 == 0 { self.palette.grid_major } else { self.palette.grid_minor };
793 out.push(Primitive::Segment { from: [0.0, y], to: [w, y], width: 1.0, color: col });
794 }
795
796 // 2. Modal Blender axis-lock guide lines
797 if let Some(m) = &self.modal {
798 let piv = self.world_to_local(m.pivot_world);
799 match m.axis {
800 AxisLock::X => out.push(Primitive::Segment {
801 from: [0.0, piv[1]],
802 to: [w, piv[1]],
803 width: 1.5,
804 color: [0.95, 0.28, 0.34, 0.85],
805 }),
806 AxisLock::Y => out.push(Primitive::Segment {
807 from: [piv[0], 0.0],
808 to: [piv[0], h],
809 width: 1.5,
810 color: [0.28, 0.90, 0.42, 0.85],
811 }),
812 AxisLock::None => {}
813 }
814 }
815
816 // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)!
817 let large_ports = self.zoom >= 0.72;
818 let tri_len = if large_ports { 6.5 } else { 4.5 };
819 let out_half = if large_ports { 2.8 } else { 2.0 };
820 let out_gap = if large_ports { 2.2 } else { 1.5 };
821 let port_outline = [0.04, 0.04, 0.06, 0.92];
822
823 for dst in &comp.nodes {
824 if dst.internal { continue; }
825 // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping
826 let mut used_edges: HashMap<u8, usize> = HashMap::new();
827 let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect();
828 sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) {
829 PortRole::Background => 0u8,
830 PortRole::Foreground => 1,
831 PortRole::Mask => 2,
832 PortRole::Scene3D => 3,
833 PortRole::Aux => 4,
834 });
835 for (port, binding) in sorted_ports {
836 let Some(src_name) = &binding.source_op else { continue };
837 let Some(src_id) = comp.find_node(src_name) else { continue };
838 let role = PortRole::from_input_name(port);
839 let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role);
840 let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 };
841 let count = used_edges.entry(ekey(be)).or_insert(0);
842 if *count > 0 {
843 // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge
844 let dr = self.node_rect_local(dst.pos);
845 if matches!(be, Edge::Top | Edge::Bottom) {
846 let t = if *count == 1 { 0.25 } else { 0.75 };
847 b = be.point_on_rect(dr, t);
848 } else if role == PortRole::Mask {
849 be = Edge::Bottom;
850 b = be.point_on_rect(dr, 0.5);
851 } else {
852 let t = if *count == 1 { 0.30 } else { 0.70 };
853 b = be.point_on_rect(dr, t);
854 }
855 }
856 *count += 1;
857
858 let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port);
859 let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id);
860
861 let wire_col = if is_hot {
862 [0.98, 0.82, 0.24, 1.0]
863 } else if is_sel {
864 [0.92, 0.94, 0.98, 0.96]
865 } else {
866 [0.64, 0.66, 0.72, 0.76]
867 };
868 let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 };
869 let an = ae.normal();
870 let bn = be.normal();
871 let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)];
872 let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len];
873
874 // Straight wire directly from output square center to input triangle base (exact Fusion look!)
875 out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col });
876
877 if self.zoom >= 0.36 {
878 // Output port: crisp Fusion white square `□` with thin dark outline
879 out.push(Primitive::RoundedRect {
880 rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half],
881 radius: 0.6,
882 stroke: None,
883 color: [0.94, 0.95, 0.98, 0.98],
884 });
885 out.push(Primitive::RoundedRect {
886 rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half],
887 radius: 0.6,
888 stroke: Some(0.9),
889 color: port_outline,
890 });
891
892 // Input port: crisp Fusion colored triangle pointing INTO `dst`!
893 let pcol = port_color(role);
894 let tri = input_arrow_svg(be, large_ports);
895 out.push(Primitive::Path {
896 data: tri,
897 origin: b,
898 style: PathStyle::Fill,
899 color: pcol,
900 });
901 out.push(Primitive::Path {
902 data: tri,
903 origin: b,
904 style: PathStyle::Stroke(0.9),
905 color: port_outline,
906 });
907 }
908 }
909 }
910
911 // Active wire drag preview
912 if let Some(wd) = &self.wire_drag {
913 let sr = self.node_rect_local(comp.node(wd.src).pos);
914 let edge = self.node_output_edge(comp, wd.src);
915 let a = edge.point_on_rect(sr, 0.5);
916 out.push(Primitive::Segment { from: a, to: wd.cursor_local, width: 2.0, color: [0.98, 0.84, 0.30, 1.0] });
917 }
918
919 // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!)
920 for n in &comp.nodes {
921 if n.internal { continue; }
922 let r = self.node_rect_local(n.pos);
923 if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 {
924 continue;
925 }
926 let sel = self.selected.contains(&n.id);
927 let primary = self.primary == Some(n.id);
928 let hovered = self.hovered_node == Some(n.id);
929 let v1 = self.viewed_nodes[0] == Some(n.id);
930 let v2 = self.viewed_nodes[1] == Some(n.id);
931 let accent = node_accent(&n.kind);
932
933 let bg = if n.bypassed {
934 [self.palette.node_fill[0] * 0.6, self.palette.node_fill[1] * 0.6, self.palette.node_fill[2] * 0.6, 0.65]
935 } else if sel {
936 self.palette.node_selected
937 } else if hovered {
938 self.palette.node_hover
939 } else {
940 self.palette.node_fill
941 };
942
943 let radius = (3.5 * self.zoom).clamp(1.5, 5.0);
944 out.push(Primitive::RoundedRect { rect: r, radius, stroke: None, color: bg });
945
946 // Bottom category color line (exact Fusion look — thin sleek strip on bottom edge!)
947 let bar_h = (2.6 * self.zoom).clamp(1.4, 3.4);
948 out.push(Primitive::Rect {
949 rect: [r[0] + 1.5, (r[3] - bar_h).max(r[1]), r[2] - 1.5, r[3]],
950 color: if n.bypassed { [0.28, 0.28, 0.32, 0.6] } else { accent },
951 });
952
953 // Crisp border
954 let border_col = if primary {
955 [0.98, 0.78, 0.30, 1.0]
956 } else if sel {
957 self.palette.accent
958 } else {
959 self.palette.node_border
960 };
961 out.push(Primitive::RoundedRect {
962 rect: r,
963 radius,
964 stroke: Some(if sel || primary { 1.4 } else { 0.9 }),
965 color: border_col,
966 });
967
968 // Node label centered cleanly inside thin bar
969 if self.zoom >= 0.42 {
970 if let Some(layout) = self.label_cache.get(&n.name) {
971 let ink = if n.bypassed { self.palette.text_dim } else { self.palette.text };
972 let pad_x = (6.0 * self.zoom).clamp(3.0, 8.0);
973 let text_y = (r[1] + r[3] - bar_h) * 0.5 - 6.0;
974 out.push(Primitive::Text {
975 text: layout as &dyn Glyphs,
976 origin: [r[0] + pad_x, text_y],
977 clip: Some([r[0] + pad_x, r[1] + 1.0, r[2] - 4.0, r[3] - bar_h]),
978 ink,
979 });
980 }
981 }
982
983 // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!)
984 if v1 || v2 {
985 let pw = 22.0;
986 let ph = 9.0;
987 let px = r[0] + 4.0;
988 let py = r[3] + 1.5;
989 out.push(Primitive::RoundedRect {
990 rect: [px, py, px + pw, py + ph],
991 radius: 3.0,
992 stroke: None,
993 color: [0.02, 0.02, 0.03, 0.92],
994 });
995 let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] };
996 let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] };
997 out.push(Primitive::RoundedRect {
998 rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0],
999 radius: 2.5,
1000 stroke: None,
1001 color: d1,
1002 });
1003 out.push(Primitive::RoundedRect {
1004 rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0],
1005 radius: 2.5,
1006 stroke: None,
1007 color: d2,
1008 });
1009 }
1010
1011 if n.bypassed {
1012 let ym = (r[1] + r[3]) * 0.5;
1013 out.push(Primitive::Segment {
1014 from: [r[0] + 3.0, ym],
1015 to: [r[2] - 3.0, ym],
1016 width: 1.4,
1017 color: [0.95, 0.35, 0.35, 0.85],
1018 });
1019 }
1020 }
1021
1022 // 5. Box select marquee
1023 if let Some(bs) = &self.box_select {
1024 let x0 = bs.start_local[0].min(bs.cur_local[0]);
1025 let x1 = bs.start_local[0].max(bs.cur_local[0]);
1026 let y0 = bs.start_local[1].min(bs.cur_local[1]);
1027 let y1 = bs.start_local[1].max(bs.cur_local[1]);
1028 out.push(Primitive::RoundedRect {
1029 rect: [x0, y0, x1, y1],
1030 radius: 2.0,
1031 stroke: None,
1032 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16],
1033 });
1034 out.push(Primitive::RoundedRect {
1035 rect: [x0, y0, x1, y1],
1036 radius: 2.0,
1037 stroke: Some(1.2),
1038 color: self.palette.accent,
1039 });
1040 }
1041
1042 // 6. Status HUD strip
1043 let hud_key = match self.modal.as_ref().map(|m| m.mode) {
1044 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
1045 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1046 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
1047 None => "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+F / Num.: Fit Scroll: Zoom",
1048 };
1049 if let Some(l) = self.badge_cache.get(hud_key) {
1050 let pill_h = 20.0;
1051 out.push(Primitive::RoundedRect {
1052 rect: [8.0, h - pill_h - 6.0, w - 8.0, h - 6.0],
1053 radius: 4.0,
1054 stroke: None,
1055 color: [self.palette.bg[0] * 0.75, self.palette.bg[1] * 0.75, self.palette.bg[2] * 0.75, 0.86],
1056 });
1057 out.push(Primitive::Text {
1058 text: l as &dyn Glyphs,
1059 origin: [14.0, h - pill_h - 2.5],
1060 clip: Some([12.0, h - pill_h - 6.0, w - 12.0, h - 6.0]),
1061 ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim },
1062 });
1063 }
1064
1065 out
1066 }
1067}
1068
1069/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border).
1070fn input_arrow_svg(edge: Edge, large: bool) -> &'static str {
1071 match (edge, large) {
1072 (Edge::Left, true) => "M 0 0 L -6.5 -3.6 L -6.5 3.6 Z",
1073 (Edge::Left, false) => "M 0 0 L -4.5 -2.6 L -4.5 2.6 Z",
1074 (Edge::Right, true) => "M 0 0 L 6.5 -3.6 L 6.5 3.6 Z",
1075 (Edge::Right, false) => "M 0 0 L 4.5 -2.6 L 4.5 2.6 Z",
1076 (Edge::Top, true) => "M 0 0 L -3.6 -6.5 L 3.6 -6.5 Z",
1077 (Edge::Top, false) => "M 0 0 L -2.6 -4.5 L 2.6 -4.5 Z",
1078 (Edge::Bottom, true) => "M 0 0 L -3.6 6.5 L 3.6 6.5 Z",
1079 (Edge::Bottom, false) => "M 0 0 L -2.6 4.5 L 2.6 4.5 Z",
1080 }
1081}
1082
1083/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect.
1084fn closest_edge(dx: f32, dy: f32) -> Edge {
1085 // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right
1086 // while vertical stacks naturally snap Top/Bottom!
1087 if dx.abs() * 0.58 >= dy.abs() {
1088 if dx >= 0.0 { Edge::Right } else { Edge::Left }
1089 } else if dy >= 0.0 {
1090 Edge::Bottom
1091 } else {
1092 Edge::Top
1093 }
1094}
1095
1096/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed.
1097fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge {
1098 let primary = closest_edge(dx_to_src, dy_to_src);
1099 match role {
1100 PortRole::Mask => {
1101 // Masks prefer Top/Bottom unless directly horizontal
1102 if dy_to_src.abs() >= dx_to_src.abs() * 0.35 {
1103 if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top }
1104 } else {
1105 primary
1106 }
1107 }
1108 _ => primary,
1109 }
1110}
1111
1112fn port_color(role: PortRole) -> [f32; 4] {
1113 match role {
1114 PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold
1115 PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green
1116 PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue
1117 PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan
1118 PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet
1119 }
1120}
1121
1122fn node_accent(kind: &str) -> [f32; 4] {
1123 match kind {
1124 "Loader" | "Saver" => [0.32, 0.72, 0.92, 1.0],
1125 "Merge" | "Switch" | "Fuse.Switch" => [0.58, 0.60, 0.66, 1.0],
1126 "Background" | "FastNoise" => [0.36, 0.80, 0.42, 1.0],
1127 "TextPlus" | "Text3D" => [0.34, 0.86, 0.54, 1.0],
1128 "ColorCorrector" | "BrightnessContrast" | "ColorCurves" | "HueCurves" | "LumaKeyer" | "UltraKeyer" => {
1129 [0.92, 0.58, 0.22, 1.0]
1130 }
1131 "Blur" | "DirectionalBlur" | "Glow" | "SoftGlow" | "Displace" | "ErodeDilate" => {
1132 [0.92, 0.52, 0.24, 1.0]
1133 }
1134 "Transform" | "Scale" | "Crop" | "TimeStretcher" | "TimeSpeed" => [0.84, 0.66, 0.28, 1.0],
1135 "EllipseMask" | "RectangleMask" | "PolylineMask" | "BitmapMask" => [0.32, 0.62, 0.98, 1.0],
1136 k if k.starts_with("Fuse.") => [0.88, 0.44, 0.76, 1.0],
1137 _ => [0.54, 0.54, 0.60, 1.0],
1138 }
1139}
1140
1141fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 {
1142 let stub = (8.0 * zoom).clamp(4.0, 11.0);
1143 let an = ae.normal();
1144 let bn = be.normal();
1145 let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub];
1146 let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub];
1147 dist_to_seg(pt, a, a_out)
1148 .min(dist_to_seg(pt, a_out, b_out))
1149 .min(dist_to_seg(pt, b_out, b))
1150}
1151
1152fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
1153 let ab = [b[0] - a[0], b[1] - a[1]];
1154 let len2 = ab[0] * ab[0] + ab[1] * ab[1];
1155 let t = if len2 < 1e-6 {
1156 0.0
1157 } else {
1158 (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / len2).clamp(0.0, 1.0)
1159 };
1160 let q = [a[0] + ab[0] * t, a[1] + ab[1] * t];
1161 ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt()
1162}
crates/model/Cargo.toml created+8
...@@ -0,0 +1,8 @@
1[package]
2name = "model"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[dependencies]
8mlua.workspace = true
crates/model/src/comp.rs created+1246
...@@ -0,0 +1,1246 @@
1//! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing.
2
3use crate::expr::ExprEngine;
4use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};
5use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2};
6use std::collections::{HashMap, HashSet};
7use std::path::{Path, PathBuf};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct NodeId(pub usize);
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub enum PortRole {
14 Background, // Gold / yellow (Fusion main input)
15 Foreground, // Green
16 Mask, // Blue (EffectMask)
17 Aux, // Purple / grey
18 Scene3D, // Cyan
19}
20
21impl PortRole {
22 pub fn from_input_name(name: &str) -> Self {
23 match name {
24 "EffectMask" | "GarbageMatte" | "SolidMatte" | "Mask" => Self::Mask,
25 "Foreground" | "Image2" => Self::Foreground,
26 "SceneInput" | "SceneInput1" | "SceneInput2" | "SceneInput3" | "SceneInput4" => {
27 Self::Scene3D
28 }
29 "Background" | "Input" | "Image" | "Image1" => Self::Background,
30 _ => Self::Aux,
31 }
32 }
33}
34
35#[derive(Clone, Debug, PartialEq)]
36pub enum ParamValue {
37 Number(f64),
38 Point([f64; 2]),
39 Text(String),
40 FuId(String),
41 Gradient(Gradient),
42 Raw(LuaValue),
43}
44
45impl ParamValue {
46 pub fn as_f64(&self) -> Option<f64> {
47 match self {
48 ParamValue::Number(n) => Some(*n),
49 _ => None,
50 }
51 }
52
53 pub fn as_point(&self) -> Option<[f64; 2]> {
54 match self {
55 ParamValue::Point(p) => Some(*p),
56 _ => None,
57 }
58 }
59
60 pub fn as_str(&self) -> Option<&str> {
61 match self {
62 ParamValue::Text(s) | ParamValue::FuId(s) => Some(s.as_str()),
63 _ => None,
64 }
65 }
66}
67
68#[derive(Clone, Debug, PartialEq)]
69pub struct InputBinding {
70 pub value: Option<ParamValue>,
71 pub source_op: Option<String>,
72 pub source_output: Option<String>,
73 pub expression: Option<String>,
74}
75
76#[derive(Clone, Debug, PartialEq)]
77pub struct ClipSpec {
78 pub filename: String,
79 pub alternate_filename: Option<String>,
80 pub start_frame: i64,
81 pub length: Option<i64>,
82 pub trim_in: i64,
83 pub trim_out: i64,
84 pub global_start: i64,
85 pub global_end: i64,
86 pub extend_first: i64,
87 pub extend_last: i64,
88 pub loop_clip: bool,
89 pub reverse: bool,
90}
91
92#[derive(Clone, Debug, PartialEq)]
93pub struct Node {
94 pub id: NodeId,
95 pub name: String,
96 /// Original Fusion operator class name (e.g. `"Merge"`, `"Fuse.Colorize"`, `"TextPlus"`).
97 pub kind: String,
98 /// Position in Flow coordinates (Fusion `ViewInfo.Pos`).
99 pub pos: [f32; 2],
100 pub bypassed: bool,
101 /// True for internal tools unpacked from a MacroOperator/GroupOperator (hidden from top-level Flow).
102 pub internal: bool,
103 /// For MacroOperator / GroupOperator nodes, the internal tool that produces this macro's output.
104 pub macro_output: Option<NodeId>,
105 pub inputs: HashMap<String, InputBinding>,
106 /// Ordered list of image/mask connection ports (`(input_name, source_node_name, source_port)`).
107 pub clips: Vec<ClipSpec>,
108 /// Preserved raw Lua table for lossless roundtrip / debugging.
109 pub raw: LuaTable,
110}
111
112impl Node {
113 /// Returns all image/mask connections targeting another flow node.
114 pub fn image_connections(&self, node_names: &HashSet<String>) -> Vec<(String, String, PortRole)> {
115 let mut out = Vec::new();
116 for (port, binding) in &self.inputs {
117 if let Some(src) = &binding.source_op {
118 if node_names.contains(src) {
119 let role = PortRole::from_input_name(port);
120 out.push((port.clone(), src.clone(), role));
121 }
122 }
123 }
124 out.sort_by(|a, b| a.0.cmp(&b.0));
125 out
126 }
127
128 /// Returns static number value if present.
129 pub fn static_number(&self, name: &str) -> Option<f64> {
130 self.inputs.get(name)?.value.as_ref()?.as_f64()
131 }
132
133 pub fn static_str(&self, name: &str) -> Option<&str> {
134 self.inputs.get(name)?.value.as_ref()?.as_str()
135 }
136
137 pub fn static_point(&self, name: &str) -> Option<[f64; 2]> {
138 self.inputs.get(name)?.value.as_ref()?.as_point()
139 }
140
141 pub fn connected_node(&self, port: &str) -> Option<&str> {
142 self.inputs.get(port)?.source_op.as_deref()
143 }
144}
145
146/// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`).
147/// Common Fusion property IDs: `1350` = Character X offset, `1351` = Character Y offset.
148#[derive(Clone, Debug, PartialEq)]
149pub struct ClsEntry {
150 pub prop_id: u32,
151 pub start: usize,
152 pub end: usize,
153 pub value: f32,
154}
155
156#[derive(Clone, Debug)]
157pub struct Comp {
158 pub path: Option<PathBuf>,
159 pub name: String,
160 pub width: u32,
161 pub height: u32,
162 pub fps: f64,
163 pub current_time: f64,
164 pub global_range: [i64; 2],
165 pub render_range: [i64; 2],
166 pub audio_filename: Option<String>,
167 pub audio_offset: f64,
168 /// Flow operators (excludes BezierSpline / PolyPath / LUTBezier modifiers).
169 pub nodes: Vec<Node>,
170 pub node_by_name: HashMap<String, NodeId>,
171 /// Animation splines keyed by Fusion modifier tool name (e.g. `"Merge6Blend"`).
172 pub splines: HashMap<String, BezierSpline>,
173 /// 2D PolyPath animation modifiers keyed by name (e.g. `"Path5"`).
174 pub poly_paths: HashMap<String, PolyPath>,
175 /// Animated gradients (stored as a spline-like modifier with keyframes of Gradients or static).
176 pub gradient_modifiers: HashMap<String, Vec<(f64, Gradient)>>,
177 /// Text modifiers such as `StyledTextCLS` (`CharacterLevelStyling1`) keyed by name.
178 pub text_modifiers: HashMap<String, String>,
179 /// Keyframed `StyledText` splines (`BezierSpline` with `Value = Text { Value = "..." }`).
180 pub text_splines: HashMap<String, Vec<(f64, String)>>,
181 /// Keyframed `Polyline` splines (`BezierSpline` with `Value = Polyline { Points = ... }`).
182 pub polyline_splines: HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>,
183 /// Per-character styling overrides from `StyledTextCLS` keyed by modifier name.
184 pub text_cls: HashMap<String, Vec<ClsEntry>>,
185 /// Generation counter incremented whenever any node, wire, or spline mutates.
186 pub revision: u64,
187}
188
189const MODIFIER_TYPES: &[&str] = &[
190 "BezierSpline",
191 "LUTBezier",
192 "PolyPath",
193 "Path",
194 "XYPath",
195 "Shake",
196 "Perturb",
197 "Expression",
198 "StyledTextCLS",
199 "CharacterLevelStyling",
200 "Follower",
201 "TrackerModifier",
202 "PublishNumber",
203 "PublishPoint",
204 "Calculation",
205 "TimeCode",
206 "Offset",
207 "Probe",
208 "FromImage",
209 "AnimCurves",
210 "GradientModifier",
211];
212
213fn is_modifier_type(kind: &str) -> bool {
214 MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier")
215}
216
217impl Comp {
218 pub fn from_fusion_file(path: impl AsRef<Path>) -> Result<Self, Box<dyn std::error::Error>> {
219 let path = path.as_ref();
220 let bytes = std::fs::read(path)?;
221 let text = String::from_utf8_lossy(&bytes);
222 let mut comp = Self::from_fusion_str(&text)?;
223 comp.path = Some(path.to_path_buf());
224 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
225 comp.name = stem.to_owned();
226 }
227 Ok(comp)
228 }
229
230 pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> {
231 let root_val = parse_lua(text)?;
232 let root = root_val
233 .as_table()
234 .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?;
235
236 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);
237 let global_range = root
238 .get_table("GlobalRange")
239 .and_then(read_vec2)
240 .map(|[a, b]| [a as i64, b as i64])
241 .unwrap_or([0, 1000]);
242 let render_range = root
243 .get_table("RenderRange")
244 .and_then(read_vec2)
245 .map(|[a, b]| [a as i64, b as i64])
246 .unwrap_or(global_range);
247 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);
248 let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0);
249
250 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps)
251 let mut width = 1920u32;
252 let mut height = 1080u32;
253 let mut fps = 30.0_f64;
254 if let Some(ff) = root
255 .get_table("Prefs")
256 .and_then(|p| p.get_table("Comp"))
257 .and_then(|c| c.get_table("FrameFormat"))
258 {
259 if let Some(w) = ff.get_f64("Width") {
260 width = w.round().max(1.0) as u32;
261 }
262 if let Some(h) = ff.get_f64("Height") {
263 height = h.round().max(1.0) as u32;
264 }
265 if let Some(r) = ff.get_f64("Rate") {
266 if r > 0.0 {
267 fps = r;
268 }
269 }
270 }
271
272 let mut nodes = Vec::new();
273 let mut node_by_name = HashMap::new();
274 let mut splines = HashMap::new();
275 let mut poly_paths = HashMap::new();
276 let mut gradient_modifiers = HashMap::new();
277 let mut text_modifiers = HashMap::new();
278 let mut text_splines = HashMap::new();
279 let mut polyline_splines = HashMap::new();
280 let mut text_cls = HashMap::new();
281 let mut tracker_aliases: Vec<(String, String)> = Vec::new();
282 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();
283 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();
284
285 if let Some(tools) = root.get_table("Tools") {
286 parse_tools_table(
287 tools,
288 false,
289 &mut nodes,
290 &mut node_by_name,
291 &mut splines,
292 &mut poly_paths,
293 &mut gradient_modifiers,
294 &mut text_modifiers,
295 &mut text_splines,
296 &mut polyline_splines,
297 &mut text_cls,
298 &mut tracker_aliases,
299 &mut macro_defaults,
300 &mut instanced_from,
301 );
302 }
303
304 // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths`
305 for (tracker_name, src_path) in tracker_aliases {
306 if let Some(pp) = poly_paths.get(&src_path).cloned() {
307 poly_paths.insert(tracker_name, pp);
308 }
309 }
310
311 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
312 for (target_op, target_param, val) in macro_defaults {
313 if let Some(&nid) = node_by_name.get(&target_op) {
314 let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding {
315 value: None,
316 source_op: None,
317 source_output: None,
318 expression: None,
319 });
320 if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() {
321 entry.value = Some(val);
322 }
323 }
324 }
325
326 // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets
327 // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`.
328 let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes
329 .iter()
330 .map(|n| (n.name.clone(), n.inputs.clone()))
331 .collect();
332 let snap_map: HashMap<String, HashMap<String, InputBinding>> = node_inputs_snapshot.into_iter().collect();
333 for n in &mut nodes {
334 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
335 let mut flow_wires = HashMap::new();
336 for (in_name, b) in &n.inputs {
337 if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) {
338 if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) {
339 if let Some(ext_src) = &inner_in.source_op {
340 // Only connect if ext_src is a visible (non-internal) flow node
341 if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) {
342 let port_name = if in_name.starts_with("MainInput") || in_name == "Input" {
343 "Input".to_owned()
344 } else {
345 in_name.clone()
346 };
347 flow_wires.insert(
348 port_name,
349 InputBinding {
350 value: None,
351 source_op: Some(ext_src.clone()),
352 source_output: inner_in.source_output.clone(),
353 expression: None,
354 },
355 );
356 }
357 }
358 }
359 }
360 }
361 if !flow_wires.is_empty() {
362 n.inputs = flow_wires;
363 }
364 }
365 }
366
367 // Resolve Fusion instanced tools (e.g. `Instance_ColorGain1 = ColorGain { SourceOp = "ColorGain1" }`)
368 for (nid, master_name) in instanced_from {
369 if let Some(&mid) = node_by_name.get(&master_name) {
370 if mid != nid {
371 let master_inputs = nodes[mid.0].inputs.clone();
372 let inst_inputs = &mut nodes[nid.0].inputs;
373 for (k, mb) in master_inputs {
374 let empty = inst_inputs.get(&k).is_none_or(|b| {
375 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
376 });
377 if empty {
378 inst_inputs.insert(k, mb);
379 }
380 }
381 }
382 }
383 }
384
385 // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height
386 if width == 1920 && height == 1080 {
387 for n in &nodes {
388 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
389 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
390 if w >= 64.0 && h >= 64.0 {
391 width = w as u32;
392 height = h as u32;
393 break;
394 }
395 }
396 }
397 }
398 }
399
400 Ok(Self {
401 path: None,
402 name: "Untitled".to_owned(),
403 width,
404 height,
405 fps,
406 current_time,
407 global_range,
408 render_range,
409 audio_filename,
410 audio_offset,
411 nodes,
412 node_by_name,
413 splines,
414 poly_paths,
415 gradient_modifiers,
416 text_modifiers,
417 text_splines,
418 polyline_splines,
419 text_cls,
420 revision: 1,
421 })
422 }
423
424 /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`).
425 pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option<Vec<crate::spline::PolyPoint>> {
426 let (spline, kfs) = self.polyline_splines.get(name)?;
427 if kfs.is_empty() {
428 return None;
429 }
430 if kfs.len() == 1 || time <= kfs[0].0 {
431 return Some(kfs[0].1.clone());
432 }
433 if time >= kfs[kfs.len() - 1].0 {
434 return Some(kfs[kfs.len() - 1].1.clone());
435 }
436 // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing.
437 let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64);
438 let idx = (u.floor() as usize).min(kfs.len() - 2);
439 let frac = (u - idx as f64).clamp(0.0, 1.0);
440 let a = &kfs[idx].1;
441 let b = &kfs[idx + 1].1;
442 if a.len() != b.len() || frac <= 1e-6 {
443 return Some(a.clone());
444 }
445 if frac >= 1.0 - 1e-6 {
446 return Some(b.clone());
447 }
448 let lerp = |x: f64, y: f64| x + (y - x) * frac;
449 Some(
450 a.iter()
451 .zip(b.iter())
452 .map(|(pa, pb)| crate::spline::PolyPoint {
453 x: lerp(pa.x, pb.x),
454 y: lerp(pa.y, pb.y),
455 lx: lerp(pa.lx, pb.lx),
456 ly: lerp(pa.ly, pb.ly),
457 rx: lerp(pa.rx, pb.rx),
458 ry: lerp(pa.ry, pb.ry),
459 linear: pa.linear && pb.linear,
460 })
461 .collect(),
462 )
463 }
464
465 pub fn node(&self, id: NodeId) -> &Node {
466 &self.nodes[id.0]
467 }
468
469 pub fn node_mut(&mut self, id: NodeId) -> &mut Node {
470 self.revision += 1;
471 &mut self.nodes[id.0]
472 }
473
474 pub fn find_node(&self, name: &str) -> Option<NodeId> {
475 self.node_by_name.get(name).copied()
476 }
477
478 /// Picks the default output node to view (the input of `Saver1`/first `Saver`, or the last `Merge`).
479 pub fn default_output_node(&self) -> Option<NodeId> {
480 // Prefer the upstream input of the first Saver (or Saver itself)
481 for n in &self.nodes {
482 if n.kind == "Saver" {
483 if let Some(src) = n.connected_node("Input").and_then(|s| self.find_node(s)) {
484 return Some(src);
485 }
486 return Some(n.id);
487 }
488 }
489 // Fallback: non-internal node with no outgoing connections, preferring the last sink (ColorCorrector/Merge)
490 let mut has_consumer = HashSet::new();
491 let names: HashSet<String> = self.node_by_name.keys().cloned().collect();
492 for n in &self.nodes {
493 for (_, src, _) in n.image_connections(&names) {
494 has_consumer.insert(src);
495 }
496 }
497 let non_internal_sinks = || {
498 self.nodes
499 .iter()
500 .rev()
501 .filter(|n| !n.internal && !has_consumer.contains(&n.name))
502 };
503 non_internal_sinks()
504 .find(|n| matches!(n.kind.as_str(), "ColorCorrector" | "BrightnessContrast" | "Merge"))
505 .or_else(|| non_internal_sinks().next())
506 .or_else(|| self.nodes.iter().rev().find(|n| !n.internal))
507 .or_else(|| self.nodes.last())
508 .map(|n| n.id)
509 }
510
511 /// Returns all `(param_label, spline_name)` animated channels attached to `node_id`
512 /// (including `PolyPath`'s `Displacement` spline!).
513 pub fn node_splines(&self, node_id: NodeId) -> Vec<(String, String)> {
514 let Some(node) = self.nodes.get(node_id.0) else { return Vec::new() };
515 let mut out = Vec::new();
516 for (param, binding) in &node.inputs {
517 if let Some(src) = &binding.source_op {
518 if self.splines.contains_key(src) {
519 out.push((param.clone(), src.clone()));
520 } else if let Some(pp) = self.poly_paths.get(src) {
521 if let Some(disp) = &pp.displacement_op {
522 if self.splines.contains_key(disp) {
523 out.push((format!("{param} (Path)"), disp.clone()));
524 }
525 }
526 }
527 }
528 }
529 out.sort_by(|a, b| a.0.cmp(&b.0));
530 out
531 }
532
533 /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`.
534 pub fn eval_number(
535 &self,
536 node: &Node,
537 param: &str,
538 time: f64,
539 default: f64,
540 expr_engine: &ExprEngine,
541 ) -> f64 {
542 let Some(binding) = node.inputs.get(param) else {
543 return default;
544 };
545 if let Some(expr) = &binding.expression {
546 if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) {
547 if v.is_finite() {
548 return v;
549 }
550 }
551 }
552 if let Some(src) = &binding.source_op {
553 if let Some(sp) = self.splines.get(src) {
554 return sp.eval(time);
555 }
556 }
557 binding
558 .value
559 .as_ref()
560 .and_then(ParamValue::as_f64)
561 .unwrap_or(default)
562 }
563
564 /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`.
565 pub fn eval_point(
566 &self,
567 node: &Node,
568 param: &str,
569 time: f64,
570 default: [f64; 2],
571 expr_engine: &ExprEngine,
572 ) -> [f64; 2] {
573 let Some(binding) = node.inputs.get(param) else {
574 return default;
575 };
576 if let Some(expr) = &binding.expression {
577 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {
578 return p;
579 }
580 }
581 if let Some(src) = &binding.source_op {
582 if let Some(pp) = self.poly_paths.get(src) {
583 let disp = pp
584 .displacement_op
585 .as_deref()
586 .and_then(|d| self.splines.get(d))
587 .map(|sp| sp.eval(time))
588 .unwrap_or(pp.displacement_value);
589 return pp.eval_center(disp);
590 }
591 }
592 binding
593 .value
594 .as_ref()
595 .and_then(ParamValue::as_point)
596 .unwrap_or(default)
597 }
598
599 pub fn eval_text(
600 &self,
601 node: &Node,
602 param: &str,
603 time: f64,
604 default: &str,
605 expr_engine: &ExprEngine,
606 ) -> String {
607 let Some(binding) = node.inputs.get(param) else {
608 return default.to_owned();
609 };
610 if let Some(expr) = &binding.expression {
611 let (sp, spts, en) = self.collect_expr_env(node, time);
612 if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) {
613 return s;
614 }
615 }
616 if let Some(src) = &binding.source_op {
617 if let Some(kfs) = self.text_splines.get(src) {
618 if !kfs.is_empty() {
619 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
620 return kfs[idx].1.clone();
621 }
622 }
623 if let Some(txt) = self.text_modifiers.get(src) {
624 return txt.clone();
625 }
626 }
627 binding
628 .value
629 .as_ref()
630 .and_then(ParamValue::as_str)
631 .unwrap_or(default)
632 .to_owned()
633 }
634
635 pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] {
636 node.inputs
637 .get(param)
638 .and_then(|b| b.source_op.as_deref())
639 .and_then(|src| self.text_cls.get(src))
640 .map(Vec::as_slice)
641 .unwrap_or(&[])
642 }
643
644 pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option<Gradient> {
645 let binding = node.inputs.get(param)?;
646 if let Some(src) = &binding.source_op {
647 if let Some(kfs) = self.gradient_modifiers.get(src) {
648 if kfs.is_empty() {
649 return None;
650 }
651 if kfs.len() == 1 || time <= kfs[0].0 {
652 return Some(kfs[0].1.clone());
653 }
654 let last = &kfs[kfs.len() - 1];
655 if time >= last.0 {
656 return Some(last.1.clone());
657 }
658 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
659 let (t0, g0) = &kfs[idx];
660 let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)];
661 let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32;
662 // Bake 17 blended stops across [0..1]
663 let mut stops = Vec::with_capacity(17);
664 for i in 0..=16 {
665 let p = i as f64 / 16.0;
666 let a = g0.sample(p);
667 let b = g1.sample(p);
668 stops.push(crate::spline::GradientStop {
669 pos: p,
670 rgba: [
671 a[0] + (b[0] - a[0]) * f,
672 a[1] + (b[1] - a[1]) * f,
673 a[2] + (b[2] - a[2]) * f,
674 a[3] + (b[3] - a[3]) * f,
675 ],
676 });
677 }
678 return Some(Gradient { stops });
679 }
680 }
681 if let Some(ParamValue::Gradient(g)) = &binding.value {
682 return Some(g.clone());
683 }
684 None
685 }
686
687 fn collect_expr_env(
688 &self,
689 node: &Node,
690 time: f64,
691 ) -> (
692 HashMap<String, f64>,
693 HashMap<String, [f64; 2]>,
694 HashMap<String, HashMap<String, f64>>,
695 ) {
696 let mut self_params = HashMap::new();
697 let mut self_points = HashMap::new();
698 for (k, b) in &node.inputs {
699 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
700 self_params.insert(k.clone(), v);
701 } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) {
702 self_points.insert(k.clone(), pt);
703 } else if let Some(src) = &b.source_op {
704 if let Some(sp) = self.splines.get(src) {
705 self_params.insert(k.clone(), sp.eval(time));
706 } else if let Some(pp) = self.poly_paths.get(src) {
707 let disp = pp
708 .displacement_op
709 .as_deref()
710 .and_then(|d| self.splines.get(d))
711 .map(|sp| sp.eval(time))
712 .unwrap_or(pp.displacement_value);
713 self_points.insert(k.clone(), pp.eval_center(disp));
714 }
715 }
716 }
717 let mut env_nodes = HashMap::new();
718 for n in &self.nodes {
719 let mut m = HashMap::new();
720 for (k, b) in &n.inputs {
721 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
722 m.insert(k.clone(), v);
723 } else if let Some(src) = &b.source_op {
724 if let Some(sp) = self.splines.get(src) {
725 m.insert(k.clone(), sp.eval(time));
726 }
727 }
728 }
729 if !m.is_empty() {
730 env_nodes.insert(n.name.clone(), m);
731 }
732 }
733 (self_params, self_points, env_nodes)
734 }
735
736 fn eval_expr_number(
737 &self,
738 node: &Node,
739 expr: &str,
740 time: f64,
741 expr_engine: &ExprEngine,
742 ) -> Option<f64> {
743 let needs_nodes = expr.contains('.')
744 || expr.trim_start().starts_with(':')
745 || expr
746 .split(|c: char| !c.is_alphanumeric() && c != '_')
747 .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok));
748 if !needs_nodes {
749 let empty_self = HashMap::new();
750 let empty_pts = HashMap::new();
751 let empty_env = HashMap::new();
752 return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env);
753 }
754 let (sp, spts, en) = self.collect_expr_env(node, time);
755 expr_engine.eval_number(expr, time, &sp, &spts, &en)
756 }
757
758 fn eval_expr_point(
759 &self,
760 node: &Node,
761 expr: &str,
762 time: f64,
763 expr_engine: &ExprEngine,
764 ) -> Option<[f64; 2]> {
765 let (sp, spts, en) = self.collect_expr_env(node, time);
766 expr_engine.eval_point(expr, time, &sp, &spts, &en)
767 }
768
769 /// Connects `src` node's output to `dst` node's `port` input.
770 pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) {
771 if src == dst {
772 return;
773 }
774 let src_name = self.nodes[src.0].name.clone();
775 let entry = self.nodes[dst.0]
776 .inputs
777 .entry(port.to_owned())
778 .or_insert(InputBinding {
779 value: None,
780 source_op: None,
781 source_output: None,
782 expression: None,
783 });
784 entry.source_op = Some(src_name);
785 entry.source_output = Some("Output".to_owned());
786 self.revision += 1;
787 }
788
789 /// Disconnects `dst` node's `port` input.
790 pub fn disconnect(&mut self, dst: NodeId, port: &str) {
791 if let Some(entry) = self.nodes[dst.0].inputs.get_mut(port) {
792 entry.source_op = None;
793 entry.source_output = None;
794 self.revision += 1;
795 }
796 }
797
798 /// Inserts `mid` node cleanly onto the wire `src -> dst.dst_port`!
799 /// Wires `src -> mid.(default_input)` and `mid -> dst.dst_port`.
800 pub fn insert_on_wire(&mut self, mid: NodeId, src: NodeId, dst: NodeId, dst_port: &str) {
801 if mid == src || mid == dst {
802 return;
803 }
804 let mid_port = default_main_input_port(&self.nodes[mid.0].kind);
805 self.connect(src, mid, mid_port);
806 self.connect(mid, dst, dst_port);
807 }
808
809 /// Toggles bypass (`PassThrough`) on a node.
810 pub fn toggle_bypass(&mut self, id: NodeId) {
811 self.nodes[id.0].bypassed = !self.nodes[id.0].bypassed;
812 self.revision += 1;
813 }
814}
815
816pub fn default_main_input_port(kind: &str) -> &'static str {
817 match kind {
818 "Merge" => "Background",
819 "Fuse.Colorize" | "Fuse.Outline" => "Image",
820 "Custom" => "Image1",
821 _ => "Input",
822 }
823}
824
825fn parse_input_binding(t: &LuaTable) -> InputBinding {
826 let source_op = t.get_str("SourceOp").map(str::to_owned);
827 let source_output = t.get_str("Source").map(str::to_owned);
828 let expression = t.get_str("Expression").map(str::to_owned);
829
830 let value = t.get("Value").map(parse_param_value);
831 InputBinding {
832 value,
833 source_op,
834 source_output,
835 expression,
836 }
837}
838
839fn parse_param_value(v: &LuaValue) -> ParamValue {
840 match v {
841 LuaValue::Number(n) => ParamValue::Number(*n),
842 LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }),
843 LuaValue::String(s) => ParamValue::Text(s.clone()),
844 LuaValue::Table(t) => match t.tag.as_deref() {
845 Some("FuID") => ParamValue::FuId(
846 t.get_index(1)
847 .and_then(LuaValue::as_str)
848 .unwrap_or("")
849 .to_owned(),
850 ),
851 Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)),
852 Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)),
853 _ => {
854 if let Some(p) = read_vec2(t) {
855 ParamValue::Point(p)
856 } else {
857 ParamValue::Raw(v.clone())
858 }
859 }
860 },
861 LuaValue::Nil => ParamValue::Raw(LuaValue::Nil),
862 }
863}
864
865fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>> {
866 let kfs = table.get_table("KeyFrames")?;
867 let mut grads = Vec::new();
868 for (k, v) in &kfs.entries {
869 let time = match k {
870 LuaKey::Index(i) => *i as f64,
871 LuaKey::Number(n) => *n,
872 _ => continue,
873 };
874 let kt = v.as_table()?;
875 let val = kt
876 .get_table("Value")
877 .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?;
878 if val.tag.as_deref() == Some("Gradient") {
879 grads.push((time, Gradient::from_lua(val)));
880 } else {
881 return None;
882 }
883 }
884 if grads.is_empty() {
885 return None;
886 }
887 grads.sort_by(|a, b| a.0.total_cmp(&b.0));
888 Some(grads)
889}
890
891fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> {
892 let kfs = table.get_table("KeyFrames")?;
893 let mut texts = Vec::new();
894 for (k, v) in &kfs.entries {
895 let time = match k {
896 LuaKey::Index(i) => *i as f64,
897 LuaKey::Number(n) => *n,
898 _ => continue,
899 };
900 let kt = v.as_table()?;
901 let val = kt.get_table("Value")?;
902 if val.tag.as_deref() == Some("Text") {
903 let s = val.get_str("Value").unwrap_or("").to_owned();
904 texts.push((time, s));
905 } else {
906 return None;
907 }
908 }
909 if texts.is_empty() {
910 return None;
911 }
912 texts.sort_by(|a, b| a.0.total_cmp(&b.0));
913 Some(texts)
914}
915
916fn try_parse_polyline_keyframes(table: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> {
917 let kfs = table.get_table("KeyFrames")?;
918 let mut shapes = Vec::new();
919 for (k, v) in &kfs.entries {
920 let time = match k {
921 LuaKey::Index(i) => *i as f64,
922 LuaKey::Number(n) => *n,
923 _ => continue,
924 };
925 let kt = v.as_table()?;
926 let val = kt.get_table("Value")?;
927 if val.tag.as_deref() == Some("Polyline") {
928 let (_, pts) = PolyPath::parse_polyline_table(val);
929 shapes.push((time, pts));
930 } else {
931 return None;
932 }
933 }
934 if shapes.is_empty() {
935 return None;
936 }
937 shapes.sort_by(|a, b| a.0.total_cmp(&b.0));
938 Some(shapes)
939}
940
941#[allow(clippy::too_many_arguments)]
942fn parse_tools_table(
943 tools: &LuaTable,
944 is_internal: bool,
945 nodes: &mut Vec<Node>,
946 node_by_name: &mut HashMap<String, NodeId>,
947 splines: &mut HashMap<String, BezierSpline>,
948 poly_paths: &mut HashMap<String, PolyPath>,
949 gradient_modifiers: &mut HashMap<String, Vec<(f64, Gradient)>>,
950 text_modifiers: &mut HashMap<String, String>,
951 text_splines: &mut HashMap<String, Vec<(f64, String)>>,
952 polyline_splines: &mut HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>,
953 text_cls: &mut HashMap<String, Vec<ClsEntry>>,
954 tracker_aliases: &mut Vec<(String, String)>,
955 macro_defaults: &mut Vec<(String, String, ParamValue)>,
956 instanced_from: &mut Vec<(NodeId, String)>,
957) {
958 for (key, val) in &tools.entries {
959 let LuaKey::Str(name) = key else { continue };
960 let Some(tbl) = val.as_table() else { continue };
961 let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned());
962
963 if kind == "BezierSpline" || kind == "LUTBezier" {
964 if let Some(grads) = try_parse_gradient_keyframes(tbl) {
965 gradient_modifiers.insert(name.clone(), grads);
966 } else if let Some(txts) = try_parse_text_keyframes(tbl) {
967 text_splines.insert(name.clone(), txts);
968 } else if let Some(polys) = try_parse_polyline_keyframes(tbl) {
969 polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys));
970 } else {
971 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
972 }
973 continue;
974 }
975 if kind == "PolyPath" || kind == "Path" {
976 poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl));
977 continue;
978 }
979 if kind == "TrackerModifier" {
980 if let Some(in_tbl) = tbl.get_table("Inputs") {
981 if let Some(src_op) = in_tbl
982 .get_table("TrackedCenter0")
983 .and_then(|c| c.get_str("SourceOp"))
984 {
985 tracker_aliases.push((name.clone(), src_op.to_owned()));
986 } else if let Some(p) = in_tbl
987 .get_table("PatternCenter0")
988 .and_then(|c| c.get_table("Value"))
989 .and_then(read_vec2)
990 {
991 poly_paths.insert(
992 name.clone(),
993 PolyPath {
994 name: name.clone(),
995 displacement_op: None,
996 displacement_value: 0.0,
997 closed: false,
998 points: vec![crate::spline::PolyPoint {
999 x: p[0] - 0.5,
1000 y: p[1] - 0.5,
1001 lx: 0.0,
1002 ly: 0.0,
1003 rx: 0.0,
1004 ry: 0.0,
1005 linear: true,
1006 }],
1007 },
1008 );
1009 }
1010 }
1011 continue;
1012 }
1013 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
1014 if let Some(in_tbl) = tbl.get_table("Inputs") {
1015 if let Some(txt) = in_tbl
1016 .get_table("Text")
1017 .or_else(|| in_tbl.get_table("StyledText"))
1018 .and_then(|s| s.get_str("Value"))
1019 {
1020 text_modifiers.insert(name.clone(), txt.to_owned());
1021 }
1022 if let Some(arr) = in_tbl
1023 .get_table("CharacterLevelStyling")
1024 .and_then(|c| c.get_table("Value"))
1025 .and_then(|v| v.get_table("Array"))
1026 {
1027 let mut entries = Vec::new();
1028 for (_, ev) in &arr.entries {
1029 let Some(et) = ev.as_table() else { continue };
1030 let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue };
1031 let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue };
1032 let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue };
1033 let Some(val) = et.get_f64("Value") else { continue };
1034 entries.push(ClsEntry {
1035 prop_id: pid.round().max(0.0) as u32,
1036 start: s.round().max(0.0) as usize,
1037 end: e.round().max(0.0) as usize,
1038 value: val as f32,
1039 });
1040 }
1041 if !entries.is_empty() {
1042 text_cls.insert(name.clone(), entries);
1043 }
1044 }
1045 }
1046 continue;
1047 }
1048 if is_modifier_type(&kind) {
1049 if tbl.get_table("KeyFrames").is_some() {
1050 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
1051 }
1052 continue;
1053 }
1054
1055 let pos = tbl
1056 .get_table("ViewInfo")
1057 .and_then(|vi| vi.get_table("Pos"))
1058 .and_then(read_vec2)
1059 .map(|[x, y]| [x as f32, y as f32])
1060 .unwrap_or([0.0, 0.0]);
1061 let bypassed = tbl.get_bool("PassThrough").unwrap_or(false);
1062
1063 let mut inputs = HashMap::new();
1064 if let Some(in_tbl) = tbl.get_table("Inputs") {
1065 for (ik, iv) in &in_tbl.entries {
1066 let LuaKey::Str(in_name) = ik else { continue };
1067 let Some(it) = iv.as_table() else { continue };
1068 let binding = parse_input_binding(it);
1069 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
1070 if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) {
1071 if let Some(def_v) = it.get("Default") {
1072 macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v)));
1073 }
1074 }
1075 }
1076 inputs.insert(in_name.clone(), binding);
1077 }
1078 }
1079
1080 // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.)
1081 if let Some(uc) = tbl.get_table("UserControls") {
1082 for (uk, uv) in &uc.entries {
1083 let LuaKey::Str(uname) = uk else { continue };
1084 let Some(ut) = uv.as_table() else { continue };
1085 let missing = inputs.get(uname).is_none_or(|b| {
1086 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
1087 });
1088 if missing {
1089 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
1090 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
1091 let def_val = if is_point {
1092 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
1093 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
1094 Some(ParamValue::Point([dx, dy]))
1095 } else {
1096 ut.get("INP_Default").map(parse_param_value)
1097 };
1098 if let Some(val) = def_val {
1099 inputs.insert(
1100 uname.clone(),
1101 InputBinding {
1102 value: Some(val),
1103 source_op: None,
1104 source_output: None,
1105 expression: None,
1106 },
1107 );
1108 }
1109 }
1110 }
1111 }
1112
1113 let mut clips = Vec::new();
1114 if let Some(clips_tbl) = tbl.get_table("Clips") {
1115 for (_, cv) in &clips_tbl.entries {
1116 if let Some(ct) = cv.as_table() {
1117 if let Some(filename) = ct.get_str("Filename") {
1118 clips.push(ClipSpec {
1119 filename: filename.to_owned(),
1120 alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned),
1121 start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64,
1122 length: ct.get_f64("Length").map(|v| v as i64),
1123 trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64,
1124 trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64,
1125 global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64,
1126 global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64,
1127 extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64,
1128 extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64,
1129 loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5,
1130 reverse: ct.get_bool("Reverse").unwrap_or(false),
1131 });
1132 }
1133 }
1134 }
1135 }
1136
1137 if kind == "Saver" && clips.is_empty() {
1138 if let Some(c) = tbl
1139 .get_table("Inputs")
1140 .and_then(|i| i.get_table("Clip"))
1141 .and_then(|c| c.get_table("Value"))
1142 {
1143 if let Some(filename) = c.get_str("Filename") {
1144 clips.push(ClipSpec {
1145 filename: filename.to_owned(),
1146 alternate_filename: None,
1147 start_frame: 0,
1148 length: None,
1149 trim_in: 0,
1150 trim_out: 0,
1151 global_start: 0,
1152 global_end: 0,
1153 extend_first: 0,
1154 extend_last: 0,
1155 loop_clip: false,
1156 reverse: false,
1157 });
1158 }
1159 }
1160 }
1161
1162 // ColorCurves embeds its R/G/B/A LUTBezier splines inside a nested `Tools` table!
1163 if kind == "ColorCurves" {
1164 if let Some(inner_tools) = tbl.get_table("Tools") {
1165 parse_tools_table(
1166 inner_tools,
1167 true,
1168 nodes,
1169 node_by_name,
1170 splines,
1171 poly_paths,
1172 gradient_modifiers,
1173 text_modifiers,
1174 text_splines,
1175 polyline_splines,
1176 text_cls,
1177 tracker_aliases,
1178 macro_defaults,
1179 instanced_from,
1180 );
1181 }
1182 }
1183
1184 let mut macro_output = None;
1185 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
1186 let mut out_name: Option<String> = None;
1187 if let Some(outs) = tbl.get_table("Outputs") {
1188 for (_, ov) in &outs.entries {
1189 if let Some(ot) = ov.as_table() {
1190 if let Some(src_op) = ot.get_str("SourceOp") {
1191 out_name = Some(src_op.to_owned());
1192 break;
1193 }
1194 }
1195 }
1196 }
1197 let inner_start = nodes.len();
1198 if let Some(inner_tools) = tbl.get_table("Tools") {
1199 parse_tools_table(
1200 inner_tools,
1201 true,
1202 nodes,
1203 node_by_name,
1204 splines,
1205 poly_paths,
1206 gradient_modifiers,
1207 text_modifiers,
1208 text_splines,
1209 polyline_splines,
1210 text_cls,
1211 tracker_aliases,
1212 macro_defaults,
1213 instanced_from,
1214 );
1215 }
1216 if let Some(oname) = out_name {
1217 macro_output = nodes[inner_start..]
1218 .iter()
1219 .find(|n| n.name == oname)
1220 .map(|n| n.id)
1221 .or_else(|| node_by_name.get(&oname).copied());
1222 }
1223 }
1224
1225 let id = NodeId(nodes.len());
1226 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.
1227 if !is_internal || !node_by_name.contains_key(name) {
1228 node_by_name.insert(name.clone(), id);
1229 }
1230 if let Some(master) = tbl.get_str("SourceOp") {
1231 instanced_from.push((id, master.to_owned()));
1232 }
1233 nodes.push(Node {
1234 id,
1235 name: name.clone(),
1236 kind,
1237 pos,
1238 bypassed,
1239 internal: is_internal,
1240 macro_output,
1241 inputs,
1242 clips,
1243 raw: tbl.clone(),
1244 });
1245 }
1246}
crates/model/src/expr.rs created+171
...@@ -0,0 +1,171 @@
1//! Fusion SimpleExpression evaluator backed by `mlua` (Lua 5.4).
2//!
3//! Supports Fusion globals (`time`, `iif`, `Point`, `Text`, `sin`/`cos`/`floor`/`ceil`/etc.)
4//! and `NodeName.ParamName` lookups without requiring full Fusion runtime scripting.
5
6use mlua::{Lua, MultiValue, Value};
7use std::collections::HashMap;
8
9pub struct ExprEngine {
10 lua: Lua,
11}
12
13impl Default for ExprEngine {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl ExprEngine {
20 pub fn new() -> Self {
21 let lua = Lua::new();
22 // Install Fusion SimpleExpression standard library into global scope.
23 let init = r#"
24 abs = math.abs
25 acos = math.acos
26 asin = math.asin
27 atan = math.atan
28 atan2 = math.atan
29 ceil = math.ceil
30 cos = math.cos
31 cosh = function(x) return (math.exp(x) + math.exp(-x)) * 0.5 end
32 deg = math.deg
33 exp = math.exp
34 floor = math.floor
35 fmod = math.fmod
36 log = math.log
37 log10 = function(x) return math.log(x, 10) end
38 max = math.max
39 min = math.min
40 mod = math.fmod
41 pi = math.pi
42 pow = function(a, b) return a ^ b end
43 rad = math.rad
44 sin = math.sin
45 sinh = function(x) return (math.exp(x) - math.exp(-x)) * 0.5 end
46 sqrt = math.sqrt
47 tan = math.tan
48 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end
49 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end
50 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end
51 Text = function(s) return tostring(s or "") end
52 clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end
53 mix = function(a, b, t) return a + (b - a) * t end
54 "#;
55 let _ = lua.load(init).exec();
56 Self { lua }
57 }
58
59 fn expr_chunk(expr: &str) -> String {
60 let trimmed = expr.trim_start();
61 if let Some(body) = trimmed.strip_prefix(':') {
62 body.to_owned()
63 } else {
64 format!("return ({expr})")
65 }
66 }
67
68 /// Evaluates a Fusion SimpleExpression returning a number.
69 /// `env_nodes` provides `node_name -> (param_name -> f64)` and `self_params` provides
70 /// unqualified parameter names on the current node.
71 pub fn eval_number(
72 &self,
73 expr: &str,
74 time: f64,
75 self_params: &HashMap<String, f64>,
76 self_points: &HashMap<String, [f64; 2]>,
77 env_nodes: &HashMap<String, HashMap<String, f64>>,
78 ) -> Option<f64> {
79 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
80 let chunk = Self::expr_chunk(expr);
81 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
82 match val {
83 Value::Number(n) => Some(n),
84 Value::Integer(i) => Some(i as f64),
85 Value::Boolean(b) => Some(if b { 1.0 } else { 0.0 }),
86 Value::String(s) => s.to_str().ok()?.trim().parse::<f64>().ok(),
87 _ => None,
88 }
89 }
90
91 /// Evaluates a Fusion SimpleExpression returning a 2D point `[x, y]`.
92 pub fn eval_point(
93 &self,
94 expr: &str,
95 time: f64,
96 self_params: &HashMap<String, f64>,
97 self_points: &HashMap<String, [f64; 2]>,
98 env_nodes: &HashMap<String, HashMap<String, f64>>,
99 ) -> Option<[f64; 2]> {
100 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
101 let chunk = Self::expr_chunk(expr);
102 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
103 if let Value::Table(t) = val {
104 let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?;
105 let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?;
106 return Some([x, y]);
107 }
108 None
109 }
110
111 /// Evaluates a Fusion SimpleExpression returning a string.
112 pub fn eval_string(
113 &self,
114 expr: &str,
115 time: f64,
116 self_params: &HashMap<String, f64>,
117 self_points: &HashMap<String, [f64; 2]>,
118 env_nodes: &HashMap<String, HashMap<String, f64>>,
119 ) -> Option<String> {
120 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
121 let chunk = Self::expr_chunk(expr);
122 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
123 match val {
124 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
125 Value::Number(n) => Some(format!("{n}")),
126 Value::Integer(i) => Some(format!("{i}")),
127 _ => None,
128 }
129 }
130
131 fn build_env(
132 &self,
133 time: f64,
134 self_params: &HashMap<String, f64>,
135 self_points: &HashMap<String, [f64; 2]>,
136 env_nodes: &HashMap<String, HashMap<String, f64>>,
137 ) -> mlua::Result<mlua::Table> {
138 let env = self.lua.create_table()?;
139 let mt = self.lua.create_table()?;
140 mt.set("__index", self.lua.globals())?;
141 env.set_metatable(Some(mt));
142 env.set("time", time)?;
143 env.set("comp", self.lua.create_table()?)?;
144 for (k, v) in self_params {
145 env.set(k.as_str(), *v)?;
146 }
147 for (k, p) in self_points {
148 let pt = self.lua.create_table()?;
149 pt.set("X", p[0])?;
150 pt.set("Y", p[1])?;
151 pt.set(1, p[0])?;
152 pt.set(2, p[1])?;
153 env.set(k.as_str(), pt)?;
154 }
155 for (node_name, params) in env_nodes {
156 let nt = self.lua.create_table()?;
157 for (pk, pv) in params {
158 nt.set(pk.as_str(), *pv)?;
159 }
160 // Also default missing fields to 0 so expressions don't nil-crash
161 let nmt = self.lua.create_table()?;
162 nmt.set(
163 "__index",
164 self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?,
165 )?;
166 nt.set_metatable(Some(nmt));
167 env.set(node_name.as_str(), nt)?;
168 }
169 Ok(env)
170 }
171}
crates/model/src/lib.rs created+80
...@@ -0,0 +1,80 @@
1pub mod comp;
2pub mod expr;
3pub mod lua_value;
4pub mod spline;
5
6pub use comp::{ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, default_main_input_port};
7pub use expr::ExprEngine;
8pub use lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};
9pub use spline::{BezierSpline, Gradient, GradientStop, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint};
10
11#[cfg(test)]
12mod tests {
13 use super::*;
14 use std::path::Path;
15
16 #[test]
17 fn parses_all_337_real_fusion_comps() {
18 let mut paths = Vec::new();
19 fn collect(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
20 let Ok(rd) = std::fs::read_dir(dir) else { return };
21 for entry in rd.flatten() {
22 let p = entry.path();
23 if p.is_dir() {
24 collect(&p, out);
25 } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("comp")) {
26 out.push(p);
27 }
28 }
29 }
30 collect(Path::new("/Users/clo/dev/compositor/private/samples"), &mut paths);
31 collect(Path::new("/Volumes/Project/trees/fusion"), &mut paths);
32 paths.sort();
33 assert!(!paths.is_empty(), "expected sample .comp files");
34
35 let mut failures = Vec::new();
36 let mut total_nodes = 0usize;
37 let mut total_splines = 0usize;
38 for p in &paths {
39 match Comp::from_fusion_file(p) {
40 Ok(comp) => {
41 total_nodes += comp.nodes.len();
42 total_splines += comp.splines.len();
43 }
44 Err(e) => failures.push(format!("{}: {e}", p.display())),
45 }
46 }
47 assert!(
48 failures.is_empty(),
49 "failed to parse {}/{} comps:\n{}",
50 failures.len(),
51 paths.len(),
52 failures.join("\n")
53 );
54 eprintln!(
55 "Parsed {}/{} real .comp files ({total_nodes} nodes, {total_splines} splines) cleanly!",
56 paths.len(),
57 paths.len()
58 );
59 }
60
61 #[test]
62 fn evaluates_20_falling_splines_and_expressions() {
63 let comp = Comp::from_fusion_file("/Volumes/Project/trees/fusion/20_falling.comp")
64 .expect("load 20_falling.comp");
65 let expr = ExprEngine::new();
66 assert_eq!(comp.width, 1920);
67 assert_eq!(comp.height, 1080);
68
69 let ts = comp.node(comp.find_node("TimeStretcher1_2").unwrap());
70 assert_eq!(comp.eval_number(ts, "SourceTime", 2200.0, 0.0, &expr), 2199.0);
71
72 let noise = comp.node(comp.find_node("Noise_3").unwrap());
73 assert_eq!(comp.eval_number(noise, "Seethe", 2200.0, 0.0, &expr), 733.0 * 42.0);
74
75 let merge19 = comp.node(comp.find_node("Merge19").unwrap());
76 let p0 = comp.eval_point(merge19, "Center", 2318.0, [0.5, 0.5], &expr);
77 let p1 = comp.eval_point(merge19, "Center", 2361.0, [0.5, 0.5], &expr);
78 assert!((p0[0] - p1[0]).abs() + (p0[1] - p1[1]).abs() > 1e-4);
79 }
80}
crates/model/src/lua_value.rs created+603
...@@ -0,0 +1,603 @@
1//! Recursive-descent parser for Fusion `.comp` / `.setting` Lua table literals.
2//!
3//! Handles Fusion's full table syntax including constructor tags (`Composition { ... }`,
4//! `ordered() { ... }`, `Input { ... }`, `FuID { ... }`), string/numeric/positional keys,
5//! Lua escape sequences, long bracket strings, and line/block comments without executing code.
6
7use std::fmt;
8
9#[derive(Clone, Debug, PartialEq)]
10pub enum LuaValue {
11 Nil,
12 Bool(bool),
13 Number(f64),
14 String(String),
15 Table(LuaTable),
16}
17
18#[derive(Clone, Debug, Default, PartialEq)]
19pub struct LuaTable {
20 /// Optional Fusion constructor tag, e.g. `"Composition"`, `"Input"`, `"Merge"`, `"ordered"`.
21 pub tag: Option<String>,
22 /// Ordered entries preserving insertion order (crucial for `ordered()` and `Tools`).
23 pub entries: Vec<(LuaKey, LuaValue)>,
24}
25
26#[derive(Clone, Debug, PartialEq)]
27pub enum LuaKey {
28 Index(i64),
29 Number(f64),
30 Str(String),
31}
32
33impl LuaTable {
34 pub fn get(&self, key: &str) -> Option<&LuaValue> {
35 self.entries.iter().find_map(|(k, v)| match k {
36 LuaKey::Str(s) if s == key => Some(v),
37 _ => None,
38 })
39 }
40
41 pub fn get_index(&self, idx: i64) -> Option<&LuaValue> {
42 self.entries.iter().find_map(|(k, v)| match k {
43 LuaKey::Index(i) if *i == idx => Some(v),
44 LuaKey::Number(n) if (*n - idx as f64).abs() < 1e-9 => Some(v),
45 _ => None,
46 })
47 }
48
49 pub fn get_table(&self, key: &str) -> Option<&LuaTable> {
50 self.get(key)?.as_table()
51 }
52
53 pub fn get_str(&self, key: &str) -> Option<&str> {
54 self.get(key)?.as_str()
55 }
56
57 pub fn get_f64(&self, key: &str) -> Option<f64> {
58 self.get(key)?.as_f64()
59 }
60
61 pub fn get_bool(&self, key: &str) -> Option<bool> {
62 self.get(key)?.as_bool()
63 }
64
65 pub fn positional_values(&self) -> impl Iterator<Item = &LuaValue> {
66 self.entries.iter().filter_map(|(k, v)| match k {
67 LuaKey::Index(_) => Some(v),
68 _ => None,
69 })
70 }
71}
72
73impl LuaValue {
74 pub fn as_table(&self) -> Option<&LuaTable> {
75 match self {
76 LuaValue::Table(t) => Some(t),
77 _ => None,
78 }
79 }
80
81 pub fn as_str(&self) -> Option<&str> {
82 match self {
83 LuaValue::String(s) => Some(s.as_str()),
84 _ => None,
85 }
86 }
87
88 pub fn as_f64(&self) -> Option<f64> {
89 match self {
90 LuaValue::Number(n) => Some(*n),
91 _ => None,
92 }
93 }
94
95 pub fn as_bool(&self) -> Option<bool> {
96 match self {
97 LuaValue::Bool(b) => Some(*b),
98 _ => None,
99 }
100 }
101
102 /// Extracts a Fusion `FuID { "Name" }` or plain string.
103 pub fn as_fuid(&self) -> Option<&str> {
104 match self {
105 LuaValue::String(s) => Some(s.as_str()),
106 LuaValue::Table(t) => t.get_index(1).and_then(LuaValue::as_str),
107 _ => None,
108 }
109 }
110}
111
112#[derive(Clone, Debug)]
113pub struct ParseError {
114 pub offset: usize,
115 pub line: usize,
116 pub message: String,
117}
118
119impl fmt::Display for ParseError {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(f, "line {} (byte {}): {}", self.line, self.offset, self.message)
122 }
123}
124
125impl std::error::Error for ParseError {}
126
127pub fn parse_lua(input: &str) -> Result<LuaValue, ParseError> {
128 let mut parser = Parser::new(input);
129 parser.skip_ws_and_comments()?;
130 let val = parser.parse_value()?;
131 parser.skip_ws_and_comments()?;
132 Ok(val)
133}
134
135struct Parser<'a> {
136 src: &'a [u8],
137 pos: usize,
138}
139
140impl<'a> Parser<'a> {
141 fn new(input: &'a str) -> Self {
142 let mut pos = 0;
143 // Strip UTF-8 BOM if present
144 if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) {
145 pos = 3;
146 }
147 Self { src: input.as_bytes(), pos }
148 }
149
150 fn err(&self, msg: impl Into<String>) -> ParseError {
151 let line = self.src[..self.pos.min(self.src.len())]
152 .iter()
153 .filter(|&&b| b == b'\n')
154 .count()
155 + 1;
156 ParseError {
157 offset: self.pos,
158 line,
159 message: msg.into(),
160 }
161 }
162
163 fn peek(&self) -> Option<u8> {
164 self.src.get(self.pos).copied()
165 }
166
167 fn peek_at(&self, delta: usize) -> Option<u8> {
168 self.src.get(self.pos + delta).copied()
169 }
170
171 fn bump(&mut self) -> Option<u8> {
172 let b = self.peek()?;
173 self.pos += 1;
174 Some(b)
175 }
176
177 fn skip_ws_and_comments(&mut self) -> Result<(), ParseError> {
178 loop {
179 while let Some(b) = self.peek() {
180 if matches!(b, b' ' | b'\t' | b'\r' | b'\n') {
181 self.pos += 1;
182 } else {
183 break;
184 }
185 }
186 if self.peek() == Some(b'-') && self.peek_at(1) == Some(b'-') {
187 self.pos += 2;
188 if self.peek() == Some(b'[') {
189 if let Some(level) = self.try_open_long_bracket() {
190 self.skip_long_bracket(level)?;
191 continue;
192 }
193 }
194 while let Some(b) = self.bump() {
195 if b == b'\n' {
196 break;
197 }
198 }
199 continue;
200 }
201 break;
202 }
203 Ok(())
204 }
205
206 fn try_open_long_bracket(&mut self) -> Option<usize> {
207 if self.peek() != Some(b'[') {
208 return None;
209 }
210 let mut i = self.pos + 1;
211 while i < self.src.len() && self.src[i] == b'=' {
212 i += 1;
213 }
214 if i < self.src.len() && self.src[i] == b'[' {
215 let level = i - (self.pos + 1);
216 self.pos = i + 1;
217 Some(level)
218 } else {
219 None
220 }
221 }
222
223 fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> {
224 let start = self.pos;
225 while self.pos < self.src.len() {
226 if self.src[self.pos] == b']' {
227 let mut i = self.pos + 1;
228 let mut eq = 0;
229 while i < self.src.len() && self.src[i] == b'=' && eq < level {
230 i += 1;
231 eq += 1;
232 }
233 if eq == level && i < self.src.len() && self.src[i] == b']' {
234 let s = String::from_utf8_lossy(&self.src[start..self.pos]).into_owned();
235 self.pos = i + 1;
236 return Ok(s);
237 }
238 }
239 self.pos += 1;
240 }
241 Err(self.err("unterminated long bracket string/comment"))
242 }
243
244 fn parse_value(&mut self) -> Result<LuaValue, ParseError> {
245 self.skip_ws_and_comments()?;
246 let Some(b) = self.peek() else {
247 return Err(self.err("unexpected EOF while parsing value"));
248 };
249 match b {
250 b'{' => self.parse_table(None).map(LuaValue::Table),
251 b'"' | b'\'' => self.parse_quoted_string().map(LuaValue::String),
252 b'[' => {
253 if let Some(level) = self.try_open_long_bracket() {
254 // Lua drops a single immediate newline after opening long bracket
255 if self.peek() == Some(b'\r') && self.peek_at(1) == Some(b'\n') {
256 self.pos += 2;
257 } else if self.peek() == Some(b'\n') {
258 self.pos += 1;
259 }
260 let s = self.skip_long_bracket(level)?;
261 Ok(LuaValue::String(s))
262 } else {
263 Err(self.err("unexpected '['"))
264 }
265 }
266 b'-' | b'+' | b'0'..=b'9' | b'.' => self.parse_number(),
267 _ if is_ident_start(b) => self.parse_ident_or_constructor(),
268 other => Err(self.err(format!("unexpected byte 0x{other:02x} ('{}')", other as char))),
269 }
270 }
271
272 fn parse_ident_or_constructor(&mut self) -> Result<LuaValue, ParseError> {
273 let start = self.pos;
274 while let Some(b) = self.peek() {
275 if is_ident_cont(b) || b == b'.' {
276 self.pos += 1;
277 } else {
278 break;
279 }
280 }
281 let ident = std::str::from_utf8(&self.src[start..self.pos])
282 .map_err(|_| self.err("invalid UTF-8 identifier"))?
283 .to_owned();
284
285 match ident.as_str() {
286 "true" => return Ok(LuaValue::Bool(true)),
287 "false" => return Ok(LuaValue::Bool(false)),
288 "nil" => return Ok(LuaValue::Nil),
289 "inf" | "INF" => return Ok(LuaValue::Number(f64::INFINITY)),
290 "nan" | "NaN" | "NAN" => return Ok(LuaValue::Number(f64::NAN)),
291 _ => {}
292 }
293
294 self.skip_ws_and_comments()?;
295
296 // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)`
297 if self.peek() == Some(b'(') {
298 self.pos += 1;
299 let mut args = Vec::new();
300 self.skip_ws_and_comments()?;
301 if self.peek() != Some(b')') {
302 loop {
303 args.push(self.parse_value()?);
304 self.skip_ws_and_comments()?;
305 if self.peek() == Some(b',') {
306 self.pos += 1;
307 } else {
308 break;
309 }
310 }
311 }
312 if self.bump() != Some(b')') {
313 return Err(self.err(format!("expected ')' after {ident}(...")));
314 }
315 self.skip_ws_and_comments()?;
316 if self.peek() == Some(b'{') {
317 let mut table = self.parse_table(Some(ident))?;
318 // Preserve any call arguments if non-empty
319 for (i, arg) in args.into_iter().enumerate() {
320 table.entries.insert(i, (LuaKey::Str(format!("__arg{i}")), arg));
321 }
322 return Ok(LuaValue::Table(table));
323 }
324 // Standalone call like `Point(0.5, 0.5)` or `FuID("Foo")`
325 let mut table = LuaTable { tag: Some(ident), entries: Vec::new() };
326 for (i, arg) in args.into_iter().enumerate() {
327 table.entries.push((LuaKey::Index((i + 1) as i64), arg));
328 }
329 return Ok(LuaValue::Table(table));
330 }
331
332 // Handle constructor `Tag { ... }` or `Tag "str"`
333 if self.peek() == Some(b'{') {
334 return self.parse_table(Some(ident)).map(LuaValue::Table);
335 }
336 if matches!(self.peek(), Some(b'"' | b'\'')) {
337 let s = self.parse_quoted_string()?;
338 let table = LuaTable {
339 tag: Some(ident),
340 entries: vec![(LuaKey::Index(1), LuaValue::String(s))],
341 };
342 return Ok(LuaValue::Table(table));
343 }
344
345 // Bare identifier (rare, e.g., symbolic constants in old Fusion 9 files)
346 Ok(LuaValue::String(ident))
347 }
348
349 fn parse_table(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {
350 if self.bump() != Some(b'{') {
351 return Err(self.err("expected '{'"));
352 }
353 let mut entries = Vec::new();
354 let mut next_index: i64 = 1;
355
356 loop {
357 self.skip_ws_and_comments()?;
358 match self.peek() {
359 None => {
360 // Gracefully close open tables on truncated/export-clipped `.comp` files.
361 break;
362 }
363 Some(b'}') => {
364 self.pos += 1;
365 break;
366 }
367 Some(b',') | Some(b';') => {
368 self.pos += 1;
369 continue;
370 }
371 _ => {}
372 }
373
374 // Decide between `[expr] = val`, `ident = val`, or positional `val`
375 if self.peek() == Some(b'[') && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') {
376 self.pos += 1; // consume '['
377 self.skip_ws_and_comments()?;
378 let key_val = self.parse_value()?;
379 self.skip_ws_and_comments()?;
380 if self.bump() != Some(b']') {
381 return Err(self.err("expected ']' after table key"));
382 }
383 self.skip_ws_and_comments()?;
384 if self.bump() != Some(b'=') {
385 return Err(self.err("expected '=' after [key]"));
386 }
387 let val = self.parse_value()?;
388 let key = match key_val {
389 LuaValue::String(s) => LuaKey::Str(s),
390 LuaValue::Number(n) => {
391 if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) {
392 LuaKey::Index(n as i64)
393 } else {
394 LuaKey::Number(n)
395 }
396 }
397 other => LuaKey::Str(format!("{other:?}")),
398 };
399 entries.push((key, val));
400 } else if let Some((key, saved_pos)) = self.try_ident_equals() {
401 let _ = saved_pos;
402 let val = self.parse_value()?;
403 entries.push((LuaKey::Str(key), val));
404 } else {
405 let val = self.parse_value()?;
406 entries.push((LuaKey::Index(next_index), val));
407 next_index += 1;
408 }
409
410 self.skip_ws_and_comments()?;
411 if matches!(self.peek(), Some(b',' | b';')) {
412 self.pos += 1;
413 }
414 }
415
416 Ok(LuaTable { tag, entries })
417 }
418
419 fn try_ident_equals(&mut self) -> Option<(String, usize)> {
420 let saved = self.pos;
421 let b = self.peek()?;
422 if !is_ident_start(b) {
423 return None;
424 }
425 let start = self.pos;
426 while let Some(c) = self.peek() {
427 if is_ident_cont(c) {
428 self.pos += 1;
429 } else {
430 break;
431 }
432 }
433 let end = self.pos;
434 let _ = self.skip_ws_and_comments();
435 if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') {
436 self.pos += 1;
437 let key = std::str::from_utf8(&self.src[start..end]).ok()?.to_owned();
438 Some((key, saved))
439 } else {
440 self.pos = saved;
441 None
442 }
443 }
444
445 fn parse_quoted_string(&mut self) -> Result<String, ParseError> {
446 let quote = self.bump().ok_or_else(|| self.err("expected quote"))?;
447 let mut out = Vec::new();
448 while let Some(b) = self.bump() {
449 if b == quote {
450 return Ok(String::from_utf8_lossy(&out).into_owned());
451 }
452 if b == b'\\' {
453 let Some(esc) = self.bump() else {
454 return Err(self.err("unterminated escape sequence"));
455 };
456 match esc {
457 b'n' => out.push(b'\n'),
458 b'r' => out.push(b'\r'),
459 b't' => out.push(b'\t'),
460 b'\\' => out.push(b'\\'),
461 b'"' => out.push(b'"'),
462 b'\'' => out.push(b'\''),
463 b'a' => out.push(0x07),
464 b'b' => out.push(0x08),
465 b'f' => out.push(0x0C),
466 b'v' => out.push(0x0B),
467 b'\n' => out.push(b'\n'),
468 b'\r' => {
469 if self.peek() == Some(b'\n') {
470 self.pos += 1;
471 }
472 out.push(b'\n');
473 }
474 b'z' => {
475 while let Some(ws) = self.peek() {
476 if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') {
477 self.pos += 1;
478 } else {
479 break;
480 }
481 }
482 }
483 b'x' => {
484 let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
485 let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?;
486 let s = [h1, h2];
487 let byte = u8::from_str_radix(std::str::from_utf8(&s).unwrap_or("00"), 16)
488 .map_err(|_| self.err("invalid hex escape"))?;
489 out.push(byte);
490 }
491 b'0'..=b'9' => {
492 let mut val = (esc - b'0') as u32;
493 for _ in 0..2 {
494 if let Some(d @ b'0'..=b'9') = self.peek() {
495 self.pos += 1;
496 val = val * 10 + (d - b'0') as u32;
497 } else {
498 break;
499 }
500 }
501 out.push((val & 0xFF) as u8);
502 }
503 other => out.push(other),
504 }
505 } else {
506 out.push(b);
507 }
508 }
509 Err(self.err("unterminated string literal"))
510 }
511
512 fn parse_number(&mut self) -> Result<LuaValue, ParseError> {
513 let start = self.pos;
514 if matches!(self.peek(), Some(b'-' | b'+')) {
515 self.pos += 1;
516 }
517 // Check for -inf / -nan / -1.#INF / -1.#IND (Windows MSVC Fusion files!)
518 if self.src[self.pos..].starts_with(b"inf") || self.src[self.pos..].starts_with(b"INF") {
519 self.pos += 3;
520 let neg = self.src[start] == b'-';
521 return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY }));
522 }
523 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") {
524 self.pos += 3;
525 return Ok(LuaValue::Number(f64::NAN));
526 }
527
528 // Hex integer / float `0x...`
529 if self.peek() == Some(b'0') && matches!(self.peek_at(1), Some(b'x' | b'X')) {
530 self.pos += 2;
531 let hex_start = self.pos;
532 while let Some(b) = self.peek() {
533 if b.is_ascii_hexdigit() {
534 self.pos += 1;
535 } else {
536 break;
537 }
538 }
539 let s = std::str::from_utf8(&self.src[hex_start..self.pos]).unwrap_or("0");
540 let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64;
541 let neg = self.src[start] == b'-';
542 return Ok(LuaValue::Number(if neg { -v } else { v }));
543 }
544
545 while let Some(b) = self.peek() {
546 if b.is_ascii_digit() {
547 self.pos += 1;
548 } else {
549 break;
550 }
551 }
552 if self.peek() == Some(b'.') {
553 self.pos += 1;
554 // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN`
555 if self.peek() == Some(b'#') {
556 while let Some(b) = self.peek() {
557 if b.is_ascii_alphanumeric() || b == b'#' {
558 self.pos += 1;
559 } else {
560 break;
561 }
562 }
563 let raw = std::str::from_utf8(&self.src[start..self.pos]).unwrap_or("");
564 if raw.contains("INF") {
565 return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }));
566 }
567 return Ok(LuaValue::Number(f64::NAN));
568 }
569 while let Some(b) = self.peek() {
570 if b.is_ascii_digit() {
571 self.pos += 1;
572 } else {
573 break;
574 }
575 }
576 }
577 if matches!(self.peek(), Some(b'e' | b'E')) {
578 self.pos += 1;
579 if matches!(self.peek(), Some(b'+' | b'-')) {
580 self.pos += 1;
581 }
582 while let Some(b) = self.peek() {
583 if b.is_ascii_digit() {
584 self.pos += 1;
585 } else {
586 break;
587 }
588 }
589 }
590 let s = std::str::from_utf8(&self.src[start..self.pos])
591 .map_err(|_| self.err("invalid UTF-8 in number"))?;
592 let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?;
593 Ok(LuaValue::Number(n))
594 }
595}
596
597fn is_ident_start(b: u8) -> bool {
598 b.is_ascii_alphabetic() || b == b'_'
599}
600
601fn is_ident_cont(b: u8) -> bool {
602 b.is_ascii_alphanumeric() || b == b'_'
603}
crates/model/src/spline.rs created+491
...@@ -0,0 +1,491 @@
1//! Fusion BezierSpline, PolyPath, LUTBezier, and Gradient animation data & evaluators.
2
3use crate::lua_value::{LuaKey, LuaTable, LuaValue};
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub enum HandleMode {
7 #[default]
8 Free,
9 Aligned,
10 Vector,
11 Auto,
12}
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub struct KeyFlags {
16 pub linear: bool,
17 pub step_in: bool,
18 pub step_out: bool,
19 pub loop_after: bool,
20 pub loop_rel: bool,
21 pub ping_pong: bool,
22 pub locked_y: bool,
23}
24
25#[derive(Clone, Debug, PartialEq)]
26pub struct Keyframe {
27 pub time: f64,
28 pub value: f64,
29 /// Left tangent handle in absolute `(time, value)` coordinates (Fusion convention).
30 pub lh: Option<[f64; 2]>,
31 /// Right tangent handle in absolute `(time, value)` coordinates (Fusion convention).
32 pub rh: Option<[f64; 2]>,
33 pub flags: KeyFlags,
34 pub handle_mode: HandleMode,
35}
36
37impl Keyframe {
38 pub fn new(time: f64, value: f64) -> Self {
39 Self {
40 time,
41 value,
42 lh: None,
43 rh: None,
44 flags: KeyFlags { linear: true, ..Default::default() },
45 handle_mode: HandleMode::Aligned,
46 }
47 }
48}
49
50#[derive(Clone, Debug, PartialEq)]
51pub struct BezierSpline {
52 pub name: String,
53 pub color: [u8; 3],
54 pub keyframes: Vec<Keyframe>,
55}
56
57impl BezierSpline {
58 pub fn from_lua(name: String, table: &LuaTable) -> Self {
59 let color = table
60 .get_table("SplineColor")
61 .map(|c| {
62 [
63 c.get_f64("Red").unwrap_or(200.0) as u8,
64 c.get_f64("Green").unwrap_or(140.0) as u8,
65 c.get_f64("Blue").unwrap_or(255.0) as u8,
66 ]
67 })
68 .unwrap_or([210, 140, 255]);
69
70 let mut keyframes = Vec::new();
71 // BezierSpline uses `KeyFrames`; LUTBezier uses `KeyColorSplines[0]`
72 let kf_table = table.get_table("KeyFrames").or_else(|| {
73 table
74 .get_table("KeyColorSplines")
75 .and_then(|kc| kc.get_index(0))
76 .and_then(LuaValue::as_table)
77 });
78
79 if let Some(kfs) = kf_table {
80 for (k, v) in &kfs.entries {
81 let time = match k {
82 LuaKey::Index(i) => *i as f64,
83 LuaKey::Number(n) => *n,
84 _ => continue,
85 };
86 let Some(kt) = v.as_table() else { continue };
87 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);
88 let lh = kt.get_table("LH").and_then(read_vec2);
89 let rh = kt.get_table("RH").and_then(read_vec2);
90 let mut flags = KeyFlags::default();
91 if let Some(ft) = kt.get_table("Flags") {
92 flags.linear = ft.get_bool("Linear").unwrap_or(false);
93 flags.step_in = ft.get_bool("StepIn").unwrap_or(false);
94 flags.step_out = ft.get_bool("StepOut").unwrap_or(false);
95 flags.loop_after = ft.get_bool("Loop").unwrap_or(false);
96 flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false);
97 flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false);
98 flags.locked_y = ft.get_bool("LockedY").unwrap_or(false);
99 }
100 let handle_mode = if flags.linear {
101 HandleMode::Vector
102 } else {
103 HandleMode::Free
104 };
105 keyframes.push(Keyframe {
106 time,
107 value,
108 lh,
109 rh,
110 flags,
111 handle_mode,
112 });
113 }
114 }
115 keyframes.sort_by(|a, b| a.time.total_cmp(&b.time));
116 Self { name, color, keyframes }
117 }
118
119 pub fn sort(&mut self) {
120 self.keyframes.sort_by(|a, b| a.time.total_cmp(&b.time));
121 }
122
123 /// Evaluates the spline at arbitrary continuous time `t`.
124 pub fn eval(&self, t: f64) -> f64 {
125 let kfs = &self.keyframes;
126 if kfs.is_empty() {
127 return 0.0;
128 }
129 if kfs.len() == 1 {
130 return kfs[0].value;
131 }
132 let first = &kfs[0];
133 let last = &kfs[kfs.len() - 1];
134
135 // Handle loop / relative-loop (`LoopRel`) / ping-pong if set on first or last keyframe
136 let mut t = t;
137 let mut value_offset = 0.0_f64;
138 let span = last.time - first.time;
139 let dv_cycle = last.value - first.value;
140 let do_loop_after = last.flags.loop_after || last.flags.loop_rel || last.flags.ping_pong;
141 let do_loop_before = first.flags.loop_after || first.flags.loop_rel || first.flags.ping_pong;
142
143 if span > 1e-9 && ((t > last.time && do_loop_after) || (t < first.time && do_loop_before)) {
144 let offset = t - first.time;
145 let cycle = (offset / span).floor();
146 let rem = offset - cycle * span;
147 if (t > last.time && last.flags.ping_pong) || (t < first.time && first.flags.ping_pong) {
148 t = if (cycle as i64) & 1 == 0 {
149 first.time + rem
150 } else {
151 last.time - rem
152 };
153 } else {
154 t = first.time + rem;
155 if (t > last.time || offset >= span) && (last.flags.loop_rel || first.flags.loop_rel) {
156 value_offset = cycle * dv_cycle;
157 } else if offset < 0.0 && (first.flags.loop_rel || last.flags.loop_rel) {
158 value_offset = cycle * dv_cycle;
159 }
160 }
161 }
162
163 if t <= first.time {
164 return first.value + value_offset;
165 }
166 if t >= last.time {
167 return last.value + value_offset;
168 }
169
170 // Binary search segment [k0, k1] with k0.time <= t <= k1.time
171 let idx = kfs.partition_point(|k| k.time <= t).saturating_sub(1);
172 let k0 = &kfs[idx];
173 let k1 = &kfs[(idx + 1).min(kfs.len() - 1)];
174 eval_segment(k0, k1, t) + value_offset
175 }
176
177 /// Returns the effective cubic Bezier control points `[p0, p1, p2, p3]` for segment `idx -> idx+1`.
178 pub fn segment_points(&self, idx: usize) -> Option<[[f64; 2]; 4]> {
179 let k0 = self.keyframes.get(idx)?;
180 let k1 = self.keyframes.get(idx + 1)?;
181 Some(segment_control_points(k0, k1))
182 }
183}
184
185pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
186 let p0 = [k0.time, k0.value];
187 let p3 = [k1.time, k1.value];
188 let dt = k1.time - k0.time;
189 let dv = k1.value - k0.value;
190
191 let p1 = if k1.flags.linear && k0.rh.is_none() {
192 [k0.time + dt / 3.0, k0.value + dv / 3.0]
193 } else if let Some(rh) = k0.rh {
194 [rh[0].clamp(k0.time, k1.time), rh[1]]
195 } else {
196 [k0.time + dt / 3.0, k0.value + dv / 3.0]
197 };
198
199 let p2 = if k1.flags.linear && k1.lh.is_none() {
200 [k1.time - dt / 3.0, k1.value - dv / 3.0]
201 } else if let Some(lh) = k1.lh {
202 [lh[0].clamp(k0.time, k1.time), lh[1]]
203 } else {
204 [k1.time - dt / 3.0, k1.value - dv / 3.0]
205 };
206
207 [p0, p1, p2, p3]
208}
209
210fn eval_segment(k0: &Keyframe, k1: &Keyframe, t: f64) -> f64 {
211 let dt = k1.time - k0.time;
212 if dt.abs() < 1e-12 {
213 return k1.value;
214 }
215 if k0.flags.step_out {
216 return k1.value;
217 }
218 if k1.flags.step_in {
219 return k0.value;
220 }
221 if k1.flags.linear && k0.rh.is_none() && k1.lh.is_none() {
222 let u = (t - k0.time) / dt;
223 return k0.value + (k1.value - k0.value) * u;
224 }
225
226 let [p0, p1, p2, p3] = segment_control_points(k0, k1);
227
228 // Solve cubic X(u) = t for u in [0, 1] using Newton-Raphson + bisection guard.
229 let mut lo = 0.0_f64;
230 let mut hi = 1.0_f64;
231 let mut u = ((t - p0[0]) / dt).clamp(0.0, 1.0);
232 for _ in 0..12 {
233 let x = cubic(p0[0], p1[0], p2[0], p3[0], u);
234 let err = x - t;
235 if err.abs() < 1e-7 {
236 break;
237 }
238 if err < 0.0 {
239 lo = u;
240 } else {
241 hi = u;
242 }
243 let dx = cubic_deriv(p0[0], p1[0], p2[0], p3[0], u);
244 let next = if dx.abs() > 1e-9 { u - err / dx } else { 0.5 * (lo + hi) };
245 u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) };
246 }
247 cubic(p0[1], p1[1], p2[1], p3[1], u)
248}
249
250#[inline]
251pub fn cubic(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 {
252 let inv = 1.0 - u;
253 inv * inv * inv * a + 3.0 * inv * inv * u * b + 3.0 * inv * u * u * c + u * u * u * d
254}
255
256#[inline]
257fn cubic_deriv(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 {
258 let inv = 1.0 - u;
259 3.0 * inv * inv * (b - a) + 6.0 * inv * u * (c - b) + 3.0 * u * u * (d - c)
260}
261
262/// 2D Bezier path used by Fusion `PolyPath` (Point animation) and `PolylineMask`.
263#[derive(Clone, Debug, PartialEq)]
264pub struct PolyPoint {
265 pub x: f64,
266 pub y: f64,
267 /// Relative left tangent handle `(lx, ly)` from `(x, y)`.
268 pub lx: f64,
269 pub ly: f64,
270 /// Relative right tangent handle `(rx, ry)` from `(x, y)`.
271 pub rx: f64,
272 pub ry: f64,
273 pub linear: bool,
274}
275
276#[derive(Clone, Debug, PartialEq)]
277pub struct PolyPath {
278 pub name: String,
279 pub displacement_op: Option<String>,
280 pub displacement_value: f64,
281 pub closed: bool,
282 pub points: Vec<PolyPoint>,
283}
284
285impl PolyPath {
286 pub fn parse_polyline_table(pl: &LuaTable) -> (bool, Vec<PolyPoint>) {
287 let closed = pl.get_bool("Closed").unwrap_or(false);
288 let mut points = Vec::new();
289 if let Some(pts) = pl.get_table("Points") {
290 for (_, v) in &pts.entries {
291 if let Some(pt) = v.as_table() {
292 points.push(PolyPoint {
293 x: pt.get_f64("X").unwrap_or(0.0),
294 y: pt.get_f64("Y").unwrap_or(0.0),
295 lx: pt.get_f64("LX").unwrap_or(0.0),
296 ly: pt.get_f64("LY").unwrap_or(0.0),
297 rx: pt.get_f64("RX").unwrap_or(0.0),
298 ry: pt.get_f64("RY").unwrap_or(0.0),
299 linear: pt.get_bool("Linear").unwrap_or(false),
300 });
301 }
302 }
303 }
304 (closed, points)
305 }
306
307 pub fn from_lua(name: String, table: &LuaTable) -> Self {
308 let mut displacement_op = None;
309 let mut displacement_value = 0.0;
310 let mut closed = false;
311 let mut points = Vec::new();
312
313 if let Some(inputs) = table.get_table("Inputs") {
314 if let Some(disp) = inputs.get_table("Displacement") {
315 displacement_op = disp.get_str("SourceOp").map(str::to_owned);
316 displacement_value = disp.get_f64("Value").unwrap_or(0.0);
317 }
318 if let Some(pl_in) = inputs.get_table("PolyLine").or_else(|| inputs.get_table("Polyline")) {
319 if let Some(pl) = pl_in.get_table("Value") {
320 let (c, pts) = Self::parse_polyline_table(pl);
321 closed = c;
322 points = pts;
323 }
324 }
325 }
326
327 Self {
328 name,
329 displacement_op,
330 displacement_value,
331 closed,
332 points,
333 }
334 }
335
336 /// Evaluates the PolyPath at normalized arc-length `displacement ∈ [0, 1]`,
337 /// returning Fusion normalized `[x, y]` coordinates (with `(0.5, 0.5)` origin!).
338 pub fn eval_center(&self, displacement: f64) -> [f64; 2] {
339 let p = self.eval_raw(displacement);
340 [0.5 + p[0], 0.5 + p[1]]
341 }
342
343 /// Evaluates raw Polyline coordinates centered around `(0, 0)`.
344 /// Supports extrapolation when `displacement` is outside `[0, 1]` (e.g. from `LoopRel`!).
345 pub fn eval_raw(&self, displacement: f64) -> [f64; 2] {
346 if self.points.is_empty() {
347 return [0.0, 0.0];
348 }
349 if self.points.len() == 1 {
350 return [self.points[0].x, self.points[0].y];
351 }
352 let seg_count = if self.closed { self.points.len() } else { self.points.len() - 1 };
353
354 // Sample arc lengths along segments for accurate constant-speed displacement.
355 const SUBS: usize = 16;
356 let mut samples = Vec::with_capacity(seg_count * SUBS + 1);
357 let mut cum_len = 0.0_f64;
358 let mut prev = [self.points[0].x, self.points[0].y];
359 samples.push((0.0_f64, prev));
360
361 for s in 0..seg_count {
362 let a = &self.points[s];
363 let b = &self.points[(s + 1) % self.points.len()];
364 let p0 = [a.x, a.y];
365 let p3 = [b.x, b.y];
366 let p1 = [a.x + a.rx, a.y + a.ry];
367 let p2 = [b.x + b.lx, b.y + b.ly];
368 for step in 1..=SUBS {
369 let u = step as f64 / SUBS as f64;
370 let cur = if a.linear && b.linear {
371 [p0[0] + (p3[0] - p0[0]) * u, p0[1] + (p3[1] - p0[1]) * u]
372 } else {
373 [
374 cubic(p0[0], p1[0], p2[0], p3[0], u),
375 cubic(p0[1], p1[1], p2[1], p3[1], u),
376 ]
377 };
378 let dx = cur[0] - prev[0];
379 let dy = cur[1] - prev[1];
380 cum_len += (dx * dx + dy * dy).sqrt();
381 samples.push((cum_len, cur));
382 prev = cur;
383 }
384 }
385
386 if cum_len <= 1e-12 {
387 return samples[0].1;
388 }
389 // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1]
390 if displacement > 1.0 && samples.len() >= 2 {
391 let (l0, v0) = samples[samples.len() - 2];
392 let (l1, v1) = samples[samples.len() - 1];
393 let seg = (l1 - l0).max(1e-12);
394 let extra = (displacement - 1.0) * cum_len;
395 return [
396 v1[0] + (v1[0] - v0[0]) / seg * extra,
397 v1[1] + (v1[1] - v0[1]) / seg * extra,
398 ];
399 }
400 if displacement < 0.0 && samples.len() >= 2 {
401 let (l0, v0) = samples[0];
402 let (l1, v1) = samples[1];
403 let seg = (l1 - l0).max(1e-12);
404 let extra = displacement * cum_len;
405 return [
406 v0[0] + (v1[0] - v0[0]) / seg * extra,
407 v0[1] + (v1[1] - v0[1]) / seg * extra,
408 ];
409 }
410
411 let d = displacement.clamp(0.0, 1.0);
412 let target = d * cum_len;
413 let idx = samples.partition_point(|(l, _)| *l < target);
414 if idx == 0 {
415 return samples[0].1;
416 }
417 if idx >= samples.len() {
418 return samples[samples.len() - 1].1;
419 }
420 let (l0, v0) = samples[idx - 1];
421 let (l1, v1) = samples[idx];
422 let span = (l1 - l0).max(1e-12);
423 let frac = (target - l0) / span;
424 [v0[0] + (v1[0] - v0[0]) * frac, v0[1] + (v1[1] - v0[1]) * frac]
425 }
426}
427
428#[derive(Clone, Debug, PartialEq)]
429pub struct GradientStop {
430 pub pos: f64,
431 pub rgba: [f32; 4],
432}
433
434#[derive(Clone, Debug, Default, PartialEq)]
435pub struct Gradient {
436 pub stops: Vec<GradientStop>,
437}
438
439impl Gradient {
440 pub fn from_lua(table: &LuaTable) -> Self {
441 let mut stops = Vec::new();
442 if let Some(colors) = table.get_table("Colors") {
443 for (k, v) in &colors.entries {
444 let pos = match k {
445 LuaKey::Index(i) => *i as f64,
446 LuaKey::Number(n) => *n,
447 _ => continue,
448 };
449 if let Some(ct) = v.as_table() {
450 let r = ct.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32;
451 let g = ct.get_index(2).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32;
452 let b = ct.get_index(3).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32;
453 let a = ct.get_index(4).and_then(LuaValue::as_f64).unwrap_or(1.0) as f32;
454 stops.push(GradientStop { pos, rgba: [r, g, b, a] });
455 }
456 }
457 }
458 stops.sort_by(|a, b| a.pos.total_cmp(&b.pos));
459 Self { stops }
460 }
461
462 pub fn sample(&self, t: f64) -> [f32; 4] {
463 if self.stops.is_empty() {
464 return [0.0, 0.0, 0.0, 1.0];
465 }
466 if self.stops.len() == 1 || t <= self.stops[0].pos {
467 return self.stops[0].rgba;
468 }
469 let last = &self.stops[self.stops.len() - 1];
470 if t >= last.pos {
471 return last.rgba;
472 }
473 let idx = self.stops.partition_point(|s| s.pos <= t).saturating_sub(1);
474 let a = &self.stops[idx];
475 let b = &self.stops[(idx + 1).min(self.stops.len() - 1)];
476 let span = (b.pos - a.pos).max(1e-9);
477 let f = ((t - a.pos) / span) as f32;
478 [
479 a.rgba[0] + (b.rgba[0] - a.rgba[0]) * f,
480 a.rgba[1] + (b.rgba[1] - a.rgba[1]) * f,
481 a.rgba[2] + (b.rgba[2] - a.rgba[2]) * f,
482 a.rgba[3] + (b.rgba[3] - a.rgba[3]) * f,
483 ]
484 }
485}
486
487pub fn read_vec2(t: &LuaTable) -> Option<[f64; 2]> {
488 let x = t.get_index(1)?.as_f64()?;
489 let y = t.get_index(2)?.as_f64()?;
490 Some([x, y])
491}
crates/spline/Cargo.toml created+13
...@@ -0,0 +1,13 @@
1[package]
2name = "spline"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[dependencies]
8draw.workspace = true
9model.workspace = true
10text.workspace = true
11theme.workspace = true
12ui.workspace = true
13winit.workspace = true
crates/spline/src/lib.rs created+1282
...@@ -0,0 +1,1282 @@
1//! Blender-style Bezier Spline Editor built on `draw` + `ui`.
2//!
3//! Features:
4//! - Both direct LMB drag AND Blender `G` (Grab), `R` (Rotate), `S` (Scale) modal editing
5//! - `X`/`Y` axis locks with red/green guides, integer-frame snapping (`Shift` for fine)
6//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `T` Step, `I` Insert key, `Del/BS` Delete
7//! - Crisp high-contrast curves (zero XOR!), generous hit targets, live GPU Viewer feedback.
8
9use draw::{Glyphs, Primitive};
10use model::spline::{cubic, segment_control_points};
11use model::{Comp, Keyframe, NodeId};
12use std::collections::{HashMap, HashSet};
13use std::sync::Arc;
14use winit::event::{ElementState, MouseButton};
15use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
16
17const RULER_H: f32 = 24.0;
18const SIDEBAR_W: f32 = 172.0;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum HandlePart {
22 Key,
23 LeftHandle,
24 RightHandle,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Hash)]
28pub struct PointRef {
29 pub spline: String,
30 pub key_idx: usize,
31 pub part: HandlePart,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum TransformMode {
36 Grab,
37 Rotate,
38 Scale,
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum AxisLock {
43 None,
44 X,
45 Y,
46}
47
48#[derive(Clone, Debug)]
49struct ModalEdit {
50 mode: TransformMode,
51 axis: AxisLock,
52 pivot: [f64; 2],
53 start_pointer: [f64; 2],
54 saved_splines: HashMap<String, Vec<Keyframe>>,
55}
56
57#[derive(Clone, Debug)]
58struct BoxSelect {
59 start_local: [f32; 2],
60 cur_local: [f32; 2],
61}
62
63#[derive(Clone, Debug)]
64pub enum SplineAction {
65 SplineEdited,
66 ScrubFrame(f64),
67}
68
69#[derive(Clone, Copy, Debug)]
70pub struct SplinePalette {
71 pub bg: [f32; 4],
72 pub sidebar: [f32; 4],
73 pub ruler: [f32; 4],
74 pub rule: [f32; 4],
75 pub grid: [f32; 4],
76 pub zero_line: [f32; 4],
77 pub text: [f32; 4],
78 pub text_dim: [f32; 4],
79 pub accent: [f32; 4],
80}
81
82impl SplinePalette {
83 pub fn from_ui(theme: &ui::Theme) -> Self {
84 let b = theme.base;
85 let lift = |c: [f32; 4], d: f32| {
86 [(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]
87 };
88 Self {
89 bg: b,
90 sidebar: lift(b, 0.012),
91 ruler: lift(b, 0.018),
92 rule: theme.rule,
93 grid: lift(b, 0.022),
94 zero_line: lift(b, 0.065),
95 text: theme.text,
96 text_dim: theme.text_dim,
97 accent: theme.accent,
98 }
99 }
100}
101
102pub struct SplineView {
103 pub t_range: [f64; 2],
104 pub v_range: [f64; 2],
105 pub size: [f32; 2],
106 pub channels: Vec<(String, String)>,
107 pub hidden_splines: HashSet<String>,
108 pub selected: HashSet<PointRef>,
109 pub palette: SplinePalette,
110 hovered: Option<PointRef>,
111 modal: Option<ModalEdit>,
112 lmb_drag_point: Option<([f32; 2], bool)>,
113 box_select: Option<BoxSelect>,
114 panning: Option<([f32; 2], [f64; 2], [f64; 2])>,
115 scrubbing: bool,
116 pointer_local: [f32; 2],
117 current_node: Option<NodeId>,
118 text_cache: HashMap<String, text::Layout>,
119}
120
121impl SplineView {
122 pub fn new(theme: &ui::Theme) -> Self {
123 Self {
124 t_range: [0.0, 300.0],
125 v_range: [-0.2, 1.2],
126 size: [800.0, 360.0],
127 channels: Vec::new(),
128 hidden_splines: HashSet::new(),
129 selected: HashSet::new(),
130 palette: SplinePalette::from_ui(theme),
131 hovered: None,
132 modal: None,
133 lmb_drag_point: None,
134 box_select: None,
135 panning: None,
136 scrubbing: false,
137 pointer_local: [0.0, 0.0],
138 current_node: None,
139 text_cache: HashMap::new(),
140 }
141 }
142
143 pub fn resize(&mut self, size: [f32; 2]) {
144 self.size = [size[0].max(1.0), size[1].max(1.0)];
145 }
146
147 pub fn background(&self) -> [f32; 4] {
148 self.palette.bg
149 }
150
151 pub fn set_target_node(&mut self, comp: &Comp, selected_node: Option<NodeId>) {
152 if self.current_node == selected_node && !self.channels.is_empty() {
153 return;
154 }
155 self.current_node = selected_node;
156 self.selected.clear();
157 self.modal = None;
158 self.lmb_drag_point = None;
159
160 let mut ch = selected_node
161 .map(|id| comp.node_splines(id))
162 .unwrap_or_default();
163
164 if ch.is_empty() {
165 // Skip 0..1 LUT splines (e.g. CustomTool LUTIn) so the frame timeline doesn't stretch to 0..2500.
166 let mut all: Vec<String> = comp
167 .splines
168 .iter()
169 .filter(|(k, s)| s.keyframes.len() >= 2 && !k.contains("LUTIn"))
170 .map(|(k, _)| k.clone())
171 .collect();
172 all.sort();
173 for s in all.into_iter().take(12) {
174 ch.push((s.clone(), s));
175 }
176 }
177 self.channels = ch;
178 self.fit_all(comp);
179 }
180
181 pub fn fit_all(&mut self, comp: &Comp) {
182 let mut t0 = f64::INFINITY;
183 let mut t1 = f64::NEG_INFINITY;
184 let mut v0 = f64::INFINITY;
185 let mut v1 = f64::NEG_INFINITY;
186
187 // If keyframes are selected, frame them (Blender Numpad `.` behavior!); otherwise frame all visible curves!
188 let use_sel = !self.selected.is_empty();
189 if use_sel {
190 for pref in &self.selected {
191 if let Some(sp) = comp.splines.get(&pref.spline) {
192 if let Some(kf) = sp.keyframes.get(pref.key_idx) {
193 t0 = t0.min(kf.time);
194 t1 = t1.max(kf.time);
195 v0 = v0.min(kf.value);
196 v1 = v1.max(kf.value);
197 }
198 }
199 }
200 }
201 if !t0.is_finite() {
202 for (_, sname) in &self.channels {
203 if self.hidden_splines.contains(sname) {
204 continue;
205 }
206 let Some(sp) = comp.splines.get(sname) else { continue };
207 for kf in &sp.keyframes {
208 t0 = t0.min(kf.time);
209 t1 = t1.max(kf.time);
210 v0 = v0.min(kf.value);
211 v1 = v1.max(kf.value);
212 if let Some(lh) = kf.lh {
213 v0 = v0.min(lh[1]);
214 v1 = v1.max(lh[1]);
215 }
216 if let Some(rh) = kf.rh {
217 v0 = v0.min(rh[1]);
218 v1 = v1.max(rh[1]);
219 }
220 }
221 }
222 }
223
224 if !t0.is_finite() {
225 self.t_range = [comp.render_range[0] as f64, comp.render_range[1] as f64];
226 self.v_range = [-0.2, 1.2];
227 return;
228 }
229 let dt = (t1 - t0).max(20.0);
230 let dv = (v1 - v0).max(0.2);
231 self.t_range = [t0 - dt * 0.14, t1 + dt * 0.14];
232 self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20];
233 }
234
235 fn plot_rect(&self) -> [f32; 4] {
236 [
237 SIDEBAR_W,
238 RULER_H,
239 self.size[0].max(SIDEBAR_W + 40.0),
240 (self.size[1] - 24.0).max(RULER_H + 40.0),
241 ]
242 }
243
244 fn data_to_local(&self, t: f64, v: f64) -> [f32; 2] {
245 let r = self.plot_rect();
246 let tx = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6);
247 let ty = (v - self.v_range[0]) / (self.v_range[1] - self.v_range[0]).max(1e-6);
248 [
249 r[0] + (tx as f32) * (r[2] - r[0]),
250 r[3] - (ty as f32) * (r[3] - r[1]),
251 ]
252 }
253
254 fn local_to_data(&self, l: [f32; 2]) -> [f64; 2] {
255 let r = self.plot_rect();
256 let tx = f64::from((l[0] - r[0]) / (r[2] - r[0]).max(1.0));
257 let ty = f64::from((r[3] - l[1]) / (r[3] - r[1]).max(1.0));
258 [
259 self.t_range[0] + tx * (self.t_range[1] - self.t_range[0]),
260 self.v_range[0] + ty * (self.v_range[1] - self.v_range[0]),
261 ]
262 }
263
264 fn hit_point(&self, comp: &Comp, local: [f32; 2]) -> Option<PointRef> {
265 let mut best_handle: Option<(f32, PointRef)> = None;
266 let mut best_key: Option<(f32, PointRef)> = None;
267
268 for (_, sname) in &self.channels {
269 if self.hidden_splines.contains(sname) {
270 continue;
271 }
272 let Some(sp) = comp.splines.get(sname) else { continue };
273 for (ki, kf) in sp.keyframes.iter().enumerate() {
274 let kp = self.data_to_local(kf.time, kf.value);
275 let kd = hypot2(local, kp);
276 if kd < 15.0 && best_key.as_ref().is_none_or(|(d, _)| kd < *d) {
277 best_key = Some((
278 kd,
279 PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key },
280 ));
281 }
282
283 if self.is_key_or_handle_selected(sname, ki) {
284 if let Some(lh) = kf.lh {
285 let lp = self.data_to_local(lh[0], lh[1]);
286 let ld = hypot2(local, lp);
287 if ld < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| ld < *d) {
288 best_handle = Some((
289 ld,
290 PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::LeftHandle },
291 ));
292 }
293 }
294 if let Some(rh) = kf.rh {
295 let rp = self.data_to_local(rh[0], rh[1]);
296 let rd = hypot2(local, rp);
297 if rd < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| rd < *d) {
298 best_handle = Some((
299 rd,
300 PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::RightHandle },
301 ));
302 }
303 }
304 }
305 }
306 }
307 best_handle.or(best_key).map(|(_, pr)| pr)
308 }
309
310 fn is_key_or_handle_selected(&self, spline: &str, key_idx: usize) -> bool {
311 self.selected.iter().any(|p| p.spline == spline && p.key_idx == key_idx)
312 }
313
314 fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) {
315 if self.selected.is_empty() {
316 return;
317 }
318 let mut sum_t = 0.0;
319 let mut sum_v = 0.0;
320 let mut count = 0usize;
321 let mut saved = HashMap::new();
322
323 for pref in &self.selected {
324 if let Some(sp) = comp.splines.get(&pref.spline) {
325 saved.entry(pref.spline.clone()).or_insert_with(|| sp.keyframes.clone());
326 if let Some(kf) = sp.keyframes.get(pref.key_idx) {
327 let pt = match pref.part {
328 HandlePart::Key => [kf.time, kf.value],
329 HandlePart::LeftHandle => kf.lh.unwrap_or([kf.time, kf.value]),
330 HandlePart::RightHandle => kf.rh.unwrap_or([kf.time, kf.value]),
331 };
332 let piv_pt = if self.selected.len() == 1 && pref.part != HandlePart::Key {
333 [kf.time, kf.value]
334 } else {
335 pt
336 };
337 sum_t += piv_pt[0];
338 sum_v += piv_pt[1];
339 count += 1;
340 }
341 }
342 }
343 if count == 0 {
344 return;
345 }
346 self.modal = Some(ModalEdit {
347 mode,
348 axis: AxisLock::None,
349 pivot: [sum_t / count as f64, sum_v / count as f64],
350 start_pointer: self.local_to_data(self.pointer_local),
351 saved_splines: saved,
352 });
353 }
354
355 fn apply_modal(&mut self, comp: &mut Comp, fine: bool) -> bool {
356 let Some(m) = &self.modal else { return false };
357 let cur = self.local_to_data(self.pointer_local);
358 let dt = cur[0] - m.start_pointer[0];
359 let dv = cur[1] - m.start_pointer[1];
360 let piv = m.pivot;
361
362 for (sname, orig_kfs) in &m.saved_splines {
363 if let Some(sp) = comp.splines.get_mut(sname) {
364 sp.keyframes = orig_kfs.clone();
365 }
366 }
367
368 let snap_t = |t: f64| if fine { t } else { t.round() };
369
370 match m.mode {
371 TransformMode::Grab => {
372 let (mt, mv) = match m.axis {
373 AxisLock::None => (dt, dv),
374 AxisLock::X => (dt, 0.0),
375 AxisLock::Y => (0.0, dv),
376 };
377 for pref in &self.selected {
378 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
379 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
380 match pref.part {
381 HandlePart::Key => {
382 let new_t = snap_t(kf.time + mt);
383 let actual_dt = new_t - kf.time;
384 kf.time = new_t;
385 kf.value += mv;
386 if let Some(lh) = &mut kf.lh {
387 lh[0] += actual_dt;
388 lh[1] += mv;
389 }
390 if let Some(rh) = &mut kf.rh {
391 rh[0] += actual_dt;
392 rh[1] += mv;
393 }
394 }
395 HandlePart::LeftHandle => {
396 let mut h = kf.lh.unwrap_or([kf.time - 5.0, kf.value]);
397 h[0] = (h[0] + mt).min(kf.time - 0.01);
398 h[1] += mv;
399 kf.lh = Some(h);
400 kf.flags.linear = false;
401 }
402 HandlePart::RightHandle => {
403 let mut h = kf.rh.unwrap_or([kf.time + 5.0, kf.value]);
404 h[0] = (h[0] + mt).max(kf.time + 0.01);
405 h[1] += mv;
406 kf.rh = Some(h);
407 kf.flags.linear = false;
408 }
409 }
410 }
411 }
412 TransformMode::Scale => {
413 let s0 = self.data_to_local(m.start_pointer[0], m.start_pointer[1]);
414 let s1 = self.pointer_local;
415 let sp = self.data_to_local(piv[0], piv[1]);
416 let d0 = hypot2(s0, sp).max(10.0);
417 let d1 = hypot2(s1, sp);
418 let f = f64::from((d1 / d0).clamp(0.05, 10.0));
419 let (st, sv) = match m.axis {
420 AxisLock::None => (f, f),
421 AxisLock::X => (f, 1.0),
422 AxisLock::Y => (1.0, f),
423 };
424 for pref in &self.selected {
425 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
426 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
427 match pref.part {
428 HandlePart::Key => {
429 kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st);
430 kf.value = piv[1] + (kf.value - piv[1]) * sv;
431 if let Some(lh) = &mut kf.lh {
432 lh[0] = piv[0] + (lh[0] - piv[0]) * st;
433 lh[1] = piv[1] + (lh[1] - piv[1]) * sv;
434 }
435 if let Some(rh) = &mut kf.rh {
436 rh[0] = piv[0] + (rh[0] - piv[0]) * st;
437 rh[1] = piv[1] + (rh[1] - piv[1]) * sv;
438 }
439 }
440 HandlePart::LeftHandle => {
441 if let Some(lh) = &mut kf.lh {
442 lh[0] = (kf.time + (lh[0] - kf.time) * st).min(kf.time - 0.01);
443 lh[1] = kf.value + (lh[1] - kf.value) * sv;
444 }
445 }
446 HandlePart::RightHandle => {
447 if let Some(rh) = &mut kf.rh {
448 rh[0] = (kf.time + (rh[0] - kf.time) * st).max(kf.time + 0.01);
449 rh[1] = kf.value + (rh[1] - kf.value) * sv;
450 }
451 }
452 }
453 }
454 }
455 TransformMode::Rotate => {
456 let sp_px = self.data_to_local(piv[0], piv[1]);
457 let s0_px = self.data_to_local(m.start_pointer[0], m.start_pointer[1]);
458 let a0 = (s0_px[1] - sp_px[1]).atan2(s0_px[0] - sp_px[0]);
459 let a1 = (self.pointer_local[1] - sp_px[1]).atan2(self.pointer_local[0] - sp_px[0]);
460 let da = a1 - a0;
461 let (c, s) = (da.cos(), da.sin());
462
463 let rot = |pt: [f64; 2], center_px: [f32; 2]| -> [f64; 2] {
464 let p = self.data_to_local(pt[0], pt[1]);
465 let rx = p[0] - center_px[0];
466 let ry = p[1] - center_px[1];
467 let np = [center_px[0] + rx * c - ry * s, center_px[1] + rx * s + ry * c];
468 self.local_to_data(np)
469 };
470
471 for pref in &self.selected {
472 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
473 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
474 match pref.part {
475 HandlePart::Key => {
476 if self.selected.len() == 1 {
477 let kp = self.data_to_local(kf.time, kf.value);
478 ensure_handles(kf);
479 if let Some(lh) = kf.lh {
480 let nl = rot(lh, kp);
481 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);
482 }
483 if let Some(rh) = kf.rh {
484 let nr = rot(rh, kp);
485 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);
486 }
487 kf.flags.linear = false;
488 } else {
489 let nk = rot([kf.time, kf.value], sp_px);
490 kf.time = snap_t(nk[0]);
491 kf.value = nk[1];
492 }
493 }
494 HandlePart::LeftHandle => {
495 let kp = self.data_to_local(kf.time, kf.value);
496 if let Some(lh) = kf.lh {
497 let nl = rot(lh, kp);
498 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);
499 kf.flags.linear = false;
500 }
501 }
502 HandlePart::RightHandle => {
503 let kp = self.data_to_local(kf.time, kf.value);
504 if let Some(rh) = kf.rh {
505 let nr = rot(rh, kp);
506 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);
507 kf.flags.linear = false;
508 }
509 }
510 }
511 }
512 }
513 }
514 comp.revision += 1;
515 true
516 }
517
518 fn cancel_modal(&mut self, comp: &mut Comp) {
519 if let Some(m) = self.modal.take() {
520 for (sname, orig) in m.saved_splines {
521 if let Some(sp) = comp.splines.get_mut(&sname) {
522 sp.keyframes = orig;
523 }
524 }
525 comp.revision += 1;
526 }
527 }
528
529 fn confirm_modal(&mut self, comp: &mut Comp) {
530 if let Some(m) = self.modal.take() {
531 for sname in m.saved_splines.keys() {
532 if let Some(sp) = comp.splines.get_mut(sname) {
533 sp.sort();
534 }
535 }
536 comp.revision += 1;
537 }
538 }
539
540 fn handle_key(
541 &mut self,
542 comp: &mut Comp,
543 current_frame: f64,
544 physical: Option<PhysicalKey>,
545 key: &Key,
546 kmod: ModifiersState,
547 actions: &mut Vec<SplineAction>,
548 ) {
549 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
550 self.fit_all(comp);
551 return;
552 }
553 match key {
554 Key::Named(NamedKey::Escape) => {
555 if self.modal.is_some() {
556 self.cancel_modal(comp);
557 actions.push(SplineAction::SplineEdited);
558 }
559 }
560 Key::Named(NamedKey::Enter) => {
561 if self.modal.is_some() {
562 self.confirm_modal(comp);
563 actions.push(SplineAction::SplineEdited);
564 }
565 }
566 Key::Named(NamedKey::Delete | NamedKey::Backspace) => {
567 if self.delete_selected(comp) {
568 actions.push(SplineAction::SplineEdited);
569 }
570 }
571 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
572 "f" if kmod.super_key() => self.fit_all(comp),
573 "f" | "." if !kmod.super_key() => self.fit_all(comp),
574 "g" if !kmod.super_key() && self.modal.is_none() => {
575 self.begin_modal(comp, TransformMode::Grab);
576 }
577 "r" if !kmod.super_key() && self.modal.is_none() => {
578 self.begin_modal(comp, TransformMode::Rotate);
579 }
580 "s" if !kmod.super_key() && self.modal.is_none() => {
581 self.begin_modal(comp, TransformMode::Scale);
582 }
583 "x" if self.modal.is_some() => {
584 if let Some(m) = &mut self.modal {
585 m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X };
586 }
587 if self.apply_modal(comp, kmod.shift_key()) {
588 actions.push(SplineAction::SplineEdited);
589 }
590 }
591 "x" if self.modal.is_none() && !kmod.super_key() => {
592 // Blender `X` deletes selected keys when not in a modal transform!
593 if self.delete_selected(comp) {
594 actions.push(SplineAction::SplineEdited);
595 }
596 }
597 "y" if self.modal.is_some() => {
598 if let Some(m) = &mut self.modal {
599 m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y };
600 }
601 if self.apply_modal(comp, kmod.shift_key()) {
602 actions.push(SplineAction::SplineEdited);
603 }
604 }
605 "i" if !kmod.super_key() && self.modal.is_none() => {
606 // Blender `I` inserts keyframe at current integer frame on all visible channels
607 let t = current_frame.round();
608 let mut inserted = false;
609 for (_, sname) in &self.channels {
610 if self.hidden_splines.contains(sname) {
611 continue;
612 }
613 if let Some(sp) = comp.splines.get_mut(sname) {
614 if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) {
615 let v = sp.eval(t);
616 sp.keyframes.push(Keyframe::new(t, v));
617 sp.sort();
618 inserted = true;
619 }
620 }
621 }
622 if inserted {
623 comp.revision += 1;
624 actions.push(SplineAction::SplineEdited);
625 }
626 }
627 "a" if !kmod.super_key() => {
628 if !self.selected.is_empty() {
629 self.selected.clear();
630 } else {
631 for (_, sname) in &self.channels {
632 if self.hidden_splines.contains(sname) {
633 continue;
634 }
635 if let Some(sp) = comp.splines.get(sname) {
636 for ki in 0..sp.keyframes.len() {
637 self.selected.insert(PointRef {
638 spline: sname.clone(),
639 key_idx: ki,
640 part: HandlePart::Key,
641 });
642 }
643 }
644 }
645 }
646 }
647 "l" => {
648 for pref in &self.selected {
649 if let Some(sp) = comp.splines.get_mut(&pref.spline) {
650 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {
651 kf.flags.linear = !kf.flags.linear;
652 if kf.flags.linear {
653 kf.lh = None;
654 kf.rh = None;
655 } else {
656 ensure_handles(kf);
657 }
658 }
659 }
660 }
661 if !self.selected.is_empty() {
662 comp.revision += 1;
663 actions.push(SplineAction::SplineEdited);
664 }
665 }
666 "t" => {
667 for pref in &self.selected {
668 if let Some(sp) = comp.splines.get_mut(&pref.spline) {
669 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {
670 kf.flags.step_in = !kf.flags.step_in;
671 }
672 }
673 }
674 if !self.selected.is_empty() {
675 comp.revision += 1;
676 actions.push(SplineAction::SplineEdited);
677 }
678 }
679 _ => {}
680 },
681 _ => {}
682 }
683 }
684
685 fn delete_selected(&mut self, comp: &mut Comp) -> bool {
686 let mut by_spline: HashMap<String, Vec<usize>> = HashMap::new();
687 for pref in &self.selected {
688 if pref.part == HandlePart::Key {
689 by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx);
690 }
691 }
692 let mut changed = false;
693 for (sname, mut idxs) in by_spline {
694 idxs.sort_unstable();
695 idxs.dedup();
696 if let Some(sp) = comp.splines.get_mut(&sname) {
697 for &idx in idxs.iter().rev() {
698 if sp.keyframes.len() > 1 && idx < sp.keyframes.len() {
699 sp.keyframes.remove(idx);
700 changed = true;
701 }
702 }
703 }
704 }
705 if changed {
706 self.selected.clear();
707 comp.revision += 1;
708 }
709 changed
710 }
711
712 pub fn input(
713 &mut self,
714 comp: &mut Comp,
715 current_frame: f64,
716 event: ui::Event,
717 rect: [f32; 4],
718 pointer_window: [f32; 2],
719 modifiers: ModifiersState,
720 ) -> Vec<SplineAction> {
721 let mut actions = Vec::new();
722 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
723 let plot = self.plot_rect();
724
725 match event {
726 ui::Event::PointerMoved(p) => {
727 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
728 if self.scrubbing {
729 let t = self.local_to_data(self.pointer_local)[0].round();
730 actions.push(SplineAction::ScrubFrame(t));
731 } else if let Some((sp, tr, vr)) = self.panning {
732 let dx = f64::from((self.pointer_local[0] - sp[0]) / (plot[2] - plot[0]).max(1.0));
733 let dy = f64::from((self.pointer_local[1] - sp[1]) / (plot[3] - plot[1]).max(1.0));
734 let dt = dx * (tr[1] - tr[0]);
735 let dv = dy * (vr[1] - vr[0]);
736 self.t_range = [tr[0] - dt, tr[1] - dt];
737 self.v_range = [vr[0] + dv, vr[1] + dv];
738 } else if self.modal.is_some() {
739 if self.apply_modal(comp, modifiers.shift_key()) {
740 actions.push(SplineAction::SplineEdited);
741 }
742 } else if let Some((start_l, ref mut dragging)) = self.lmb_drag_point {
743 if !*dragging && hypot2(self.pointer_local, start_l) > 3.5 {
744 *dragging = true;
745 self.begin_modal(comp, TransformMode::Grab);
746 if self.apply_modal(comp, modifiers.shift_key()) {
747 actions.push(SplineAction::SplineEdited);
748 }
749 }
750 } else if let Some(bs) = &mut self.box_select {
751 bs.cur_local = self.pointer_local;
752 } else {
753 self.hovered = self.hit_point(comp, self.pointer_local);
754 }
755 }
756 ui::Event::Button { button, pressed, .. } => {
757 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
758 if pressed {
759 self.panning = Some((self.pointer_local, self.t_range, self.v_range));
760 } else {
761 self.panning = None;
762 }
763 } else if button == MouseButton::Right {
764 if pressed && self.modal.is_some() {
765 self.cancel_modal(comp);
766 self.lmb_drag_point = None;
767 actions.push(SplineAction::SplineEdited);
768 }
769 } else if button == MouseButton::Left {
770 if pressed {
771 if self.modal.is_some() {
772 self.confirm_modal(comp);
773 self.lmb_drag_point = None;
774 actions.push(SplineAction::SplineEdited);
775 } else if self.pointer_local[0] < SIDEBAR_W {
776 let row = ((self.pointer_local[1] - RULER_H - 6.0) / 22.0).floor() as isize;
777 if row >= 0 && (row as usize) < self.channels.len() {
778 let sname = self.channels[row as usize].1.clone();
779 if !self.hidden_splines.remove(&sname) {
780 self.hidden_splines.insert(sname);
781 }
782 }
783 } else if self.pointer_local[1] < RULER_H {
784 self.scrubbing = true;
785 let t = self.local_to_data(self.pointer_local)[0].round();
786 actions.push(SplineAction::ScrubFrame(t));
787 } else if let Some(hit) = self.hit_point(comp, self.pointer_local) {
788 if modifiers.shift_key() {
789 if !self.selected.remove(&hit) {
790 self.selected.insert(hit);
791 }
792 } else if !self.selected.contains(&hit) {
793 self.selected.clear();
794 self.selected.insert(hit);
795 }
796 for pref in &self.selected {
797 if let Some(sp) = comp.splines.get_mut(&pref.spline) {
798 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {
799 ensure_handles(kf);
800 }
801 }
802 }
803 // Allow direct drag right from mouse down!
804 self.lmb_drag_point = Some((self.pointer_local, false));
805 } else {
806 if !modifiers.shift_key() {
807 self.selected.clear();
808 }
809 self.box_select = Some(BoxSelect {
810 start_local: self.pointer_local,
811 cur_local: self.pointer_local,
812 });
813 }
814 } else {
815 self.scrubbing = false;
816 if let Some((_start, dragging)) = self.lmb_drag_point.take() {
817 if dragging && self.modal.is_some() {
818 self.confirm_modal(comp);
819 actions.push(SplineAction::SplineEdited);
820 }
821 }
822 if let Some(bs) = self.box_select.take() {
823 let x0 = bs.start_local[0].min(bs.cur_local[0]);
824 let x1 = bs.start_local[0].max(bs.cur_local[0]);
825 let y0 = bs.start_local[1].min(bs.cur_local[1]);
826 let y1 = bs.start_local[1].max(bs.cur_local[1]);
827 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
828 for (_, sname) in &self.channels {
829 if self.hidden_splines.contains(sname) {
830 continue;
831 }
832 let Some(sp) = comp.splines.get(sname) else { continue };
833 for (ki, kf) in sp.keyframes.iter().enumerate() {
834 let p = self.data_to_local(kf.time, kf.value);
835 if p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1 {
836 self.selected.insert(PointRef {
837 spline: sname.clone(),
838 key_idx: ki,
839 part: HandlePart::Key,
840 });
841 }
842 }
843 }
844 }
845 }
846 }
847 }
848 }
849 ui::Event::Wheel(delta) => {
850 // Blender convention: plain scroll zooms toward mouse cursor; Shift zooms Y; Alt pans.
851 if modifiers.alt_key() {
852 let dx = f64::from(delta[0] / (plot[2] - plot[0]).max(1.0));
853 let dy = f64::from(delta[1] / (plot[3] - plot[1]).max(1.0));
854 let dt = dx * (self.t_range[1] - self.t_range[0]);
855 let dv = dy * (self.v_range[1] - self.v_range[0]);
856 self.t_range = [self.t_range[0] - dt, self.t_range[1] - dt];
857 self.v_range = [self.v_range[0] + dv, self.v_range[1] + dv];
858 } else if modifiers.shift_key() {
859 let f = f64::from((1.0 - delta[1] * 0.004).clamp(0.7, 1.4));
860 self.zoom_at(1.0, f, self.pointer_local);
861 } else {
862 let f = f64::from((1.0 - delta[1] * 0.0045).clamp(0.7, 1.4));
863 self.zoom_at(f, f, self.pointer_local);
864 }
865 }
866 ui::Event::Pinch(delta) => {
867 let f = f64::from((1.0 - delta).clamp(0.7, 1.4));
868 self.zoom_at(f, f, self.pointer_local);
869 }
870 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
871 self.handle_key(comp, current_frame, Some(physical), &key, kmod, &mut actions);
872 }
873 ui::Event::Key { key, modifiers: kmod, .. } => {
874 self.handle_key(comp, current_frame, None, &key, kmod, &mut actions);
875 }
876 _ => {}
877 }
878
879 actions
880 }
881
882 fn zoom_at(&mut self, ft: f64, fv: f64, pivot_local: [f32; 2]) {
883 let p = self.local_to_data(pivot_local);
884 let t0 = p[0] - (p[0] - self.t_range[0]) * ft;
885 let t1 = p[0] + (self.t_range[1] - p[0]) * ft;
886 let v0 = p[1] - (p[1] - self.v_range[0]) * fv;
887 let v1 = p[1] + (self.v_range[1] - p[1]) * fv;
888 if (t1 - t0) > 2.0 && (t1 - t0) < 100_000.0 {
889 self.t_range = [t0, t1];
890 }
891 if (v1 - v0) > 1e-4 && (v1 - v0) < 1_000_000.0 {
892 self.v_range = [v0, v1];
893 }
894 }
895
896 pub fn prepare_labels(&mut self, comp: &Comp) {
897 let font_sm = text::Font {
898 families: Arc::from([text::Family::Mono]),
899 size: 10.0,
900 weight: 500,
901 italic: false,
902 };
903 let font_ch = text::Font {
904 families: Arc::from([text::Family::Sans]),
905 size: 11.0,
906 weight: 500,
907 italic: false,
908 };
909 let make_layout = |s: &str, font: &text::Font| {
910 let styles = [text::Style::new(font.clone())];
911 text::Paragraph {
912 text: s,
913 styles: &styles,
914 spans: &[],
915 replacements: &[],
916 width: None,
917 indent: 0.0,
918 line_height: 1.2,
919 align: text::Align::Left,
920 tab: 32.0,
921 }
922 .layout()
923 };
924 for (label, _) in &self.channels {
925 self.text_cache.entry(label.clone()).or_insert_with(|| make_layout(label, &font_ch));
926 }
927 let header = self
928 .current_node
929 .map(|id| format!("Splines: {}", comp.node(id).name))
930 .unwrap_or_else(|| "Splines (Comp)".to_owned());
931 self.text_cache.entry(header.clone()).or_insert_with(|| make_layout(&header, &font_ch));
932 for hud in [
933 "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit",
934 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",
935 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
936 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",
937 ] {
938 self.text_cache.entry(hud.to_owned()).or_insert_with(|| make_layout(hud, &font_sm));
939 }
940
941 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0);
942 let t_start = (self.t_range[0] / t_step).floor() as i64;
943 let t_end = (self.t_range[1] / t_step).ceil() as i64;
944 for ti in t_start..=t_end {
945 let key = format!("t:{}", (ti as f64 * t_step).round() as i64);
946 self.text_cache.entry(key.clone()).or_insert_with(|| make_layout(&key[2..], &font_sm));
947 }
948 let v_step = nice_step((self.v_range[1] - self.v_range[0]) / 6.0);
949 let v_start = (self.v_range[0] / v_step).floor() as i64;
950 let v_end = (self.v_range[1] / v_step).ceil() as i64;
951 for vi in v_start..=v_end {
952 let val = vi as f64 * v_step;
953 let s = format!("{val:.2}");
954 let key = format!("v:{s}");
955 self.text_cache.entry(key).or_insert_with(|| make_layout(&s, &font_sm));
956 }
957 }
958
959 pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec<Primitive<'a>> {
960 let mut out = Vec::with_capacity(512);
961 let [w, h] = self.size;
962 let plot = self.plot_rect();
963
964 out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar });
965 out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule });
966 out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler });
967 out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule });
968
969 let header = self
970 .current_node
971 .map(|id| format!("Splines: {}", comp.node(id).name))
972 .unwrap_or_else(|| "Splines (Comp)".to_owned());
973 if let Some(hl) = self.text_cache.get(&header) {
974 out.push(Primitive::Text {
975 text: hl as &dyn Glyphs,
976 origin: [10.0, 5.0],
977 clip: Some([8.0, 0.0, SIDEBAR_W - 8.0, RULER_H]),
978 ink: self.palette.text,
979 });
980 }
981
982 for (i, (label, sname)) in self.channels.iter().enumerate() {
983 let y = RULER_H + 6.0 + i as f32 * 22.0;
984 if y > h - 24.0 {
985 break;
986 }
987 let hidden = self.hidden_splines.contains(sname);
988 let col = spline_color(comp, sname, i);
989 out.push(Primitive::RoundedRect {
990 rect: [10.0, y + 4.0, 20.0, y + 14.0],
991 radius: 3.0,
992 stroke: if hidden { Some(1.2) } else { None },
993 color: if hidden { self.palette.text_dim } else { col },
994 });
995 if let Some(tl) = self.text_cache.get(label) {
996 out.push(Primitive::Text {
997 text: tl as &dyn Glyphs,
998 origin: [26.0, y + 2.0],
999 clip: Some([26.0, y, SIDEBAR_W - 8.0, y + 20.0]),
1000 ink: if hidden { self.palette.text_dim } else { self.palette.text },
1001 });
1002 }
1003 }
1004
1005 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0);
1006 let t_start = (self.t_range[0] / t_step).floor() as i64;
1007 let t_end = (self.t_range[1] / t_step).ceil() as i64;
1008 for ti in t_start..=t_end {
1009 let t = ti as f64 * t_step;
1010 let x = self.data_to_local(t, 0.0)[0];
1011 if x < plot[0] || x > plot[2] {
1012 continue;
1013 }
1014 out.push(Primitive::Segment { from: [x, plot[1]], to: [x, plot[3]], width: 1.0, color: self.palette.grid });
1015 let key = format!("t:{}", t.round() as i64);
1016 if let Some(tl) = self.text_cache.get(&key) {
1017 out.push(Primitive::Text {
1018 text: tl as &dyn Glyphs,
1019 origin: [x + 3.0, 6.0],
1020 clip: Some([plot[0], 0.0, plot[2], RULER_H]),
1021 ink: self.palette.text_dim,
1022 });
1023 }
1024 }
1025
1026 let v_step = nice_step((self.v_range[1] - self.v_range[0]) / 6.0);
1027 let v_start = (self.v_range[0] / v_step).floor() as i64;
1028 let v_end = (self.v_range[1] / v_step).ceil() as i64;
1029 for vi in v_start..=v_end {
1030 let v = vi as f64 * v_step;
1031 let y = self.data_to_local(0.0, v)[1];
1032 if y < plot[1] || y > plot[3] {
1033 continue;
1034 }
1035 let is_zero = v.abs() < 1e-6;
1036 out.push(Primitive::Segment {
1037 from: [plot[0], y],
1038 to: [plot[2], y],
1039 width: if is_zero { 1.3 } else { 1.0 },
1040 color: if is_zero { self.palette.zero_line } else { self.palette.grid },
1041 });
1042 let key = format!("v:{v:.2}");
1043 if let Some(vl) = self.text_cache.get(&key) {
1044 out.push(Primitive::Text {
1045 text: vl as &dyn Glyphs,
1046 origin: [plot[0] + 4.0, y - 12.0],
1047 clip: Some(plot),
1048 ink: self.palette.text_dim,
1049 });
1050 }
1051 }
1052
1053 out.push(Primitive::PushClip { rect: plot, radius: 0.0 });
1054
1055 if let Some(m) = &self.modal {
1056 let piv = self.data_to_local(m.pivot[0], m.pivot[1]);
1057 match m.axis {
1058 AxisLock::X => out.push(Primitive::Segment {
1059 from: [plot[0], piv[1]],
1060 to: [plot[2], piv[1]],
1061 width: 1.5,
1062 color: [0.95, 0.28, 0.34, 0.85],
1063 }),
1064 AxisLock::Y => out.push(Primitive::Segment {
1065 from: [piv[0], plot[1]],
1066 to: [piv[0], plot[3]],
1067 width: 1.5,
1068 color: [0.28, 0.90, 0.42, 0.85],
1069 }),
1070 AxisLock::None => {}
1071 }
1072 }
1073
1074 let px = self.data_to_local(current_frame, 0.0)[0];
1075 if px >= plot[0] && px <= plot[2] {
1076 out.push(Primitive::Segment {
1077 from: [px, plot[1]],
1078 to: [px, plot[3]],
1079 width: 1.6,
1080 color: [0.96, 0.36, 0.34, 0.90],
1081 });
1082 }
1083
1084 for (ci, (_, sname)) in self.channels.iter().enumerate() {
1085 if self.hidden_splines.contains(sname) {
1086 continue;
1087 }
1088 let Some(sp) = comp.splines.get(sname) else { continue };
1089 let col = spline_color(comp, sname, ci);
1090 let any_sel = self.selected.iter().any(|p| p.spline == *sname);
1091 let curve_w = if any_sel { 2.4 } else { 1.7 };
1092 let curve_col = if any_sel {
1093 [(col[0] + 0.15).min(1.0), (col[1] + 0.15).min(1.0), (col[2] + 0.15).min(1.0), 1.0]
1094 } else {
1095 col
1096 };
1097
1098 if let Some(first) = sp.keyframes.first() {
1099 let p = self.data_to_local(first.time, first.value);
1100 if p[0] > plot[0] {
1101 out.push(Primitive::Segment {
1102 from: [plot[0], p[1]],
1103 to: p,
1104 width: 1.1,
1105 color: [curve_col[0], curve_col[1], curve_col[2], 0.35],
1106 });
1107 }
1108 }
1109 if let Some(last) = sp.keyframes.last() {
1110 let p = self.data_to_local(last.time, last.value);
1111 if p[0] < plot[2] {
1112 out.push(Primitive::Segment {
1113 from: p,
1114 to: [plot[2], p[1]],
1115 width: 1.1,
1116 color: [curve_col[0], curve_col[1], curve_col[2], 0.35],
1117 });
1118 }
1119 }
1120
1121 let dense = sp.keyframes.len() > 250;
1122 for seg in 0..sp.keyframes.len().saturating_sub(1) {
1123 let k0 = &sp.keyframes[seg];
1124 let k1 = &sp.keyframes[seg + 1];
1125 if k1.time < self.t_range[0] || k0.time > self.t_range[1] {
1126 continue;
1127 }
1128 if k1.flags.step_in {
1129 let a = self.data_to_local(k0.time, k0.value);
1130 let m = self.data_to_local(k1.time, k0.value);
1131 let b = self.data_to_local(k1.time, k1.value);
1132 out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col });
1133 out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col });
1134 } else if dense || (k1.flags.linear && k0.rh.is_none() && k1.lh.is_none()) {
1135 let a = self.data_to_local(k0.time, k0.value);
1136 let b = self.data_to_local(k1.time, k1.value);
1137 out.push(Primitive::Segment { from: a, to: b, width: curve_w, color: curve_col });
1138 } else {
1139 let [p0, p1, p2, p3] = segment_control_points(k0, k1);
1140 const SUBS: usize = 20;
1141 let mut prev = self.data_to_local(p0[0], p0[1]);
1142 for s in 1..=SUBS {
1143 let u = s as f64 / SUBS as f64;
1144 let t = cubic(p0[0], p1[0], p2[0], p3[0], u);
1145 let v = cubic(p0[1], p1[1], p2[1], p3[1], u);
1146 let cur = self.data_to_local(t, v);
1147 out.push(Primitive::Segment { from: prev, to: cur, width: curve_w, color: curve_col });
1148 prev = cur;
1149 }
1150 }
1151 }
1152
1153 if !dense || (self.t_range[1] - self.t_range[0]) < 180.0 {
1154 for (ki, kf) in sp.keyframes.iter().enumerate() {
1155 if kf.time < self.t_range[0] - 5.0 || kf.time > self.t_range[1] + 5.0 {
1156 continue;
1157 }
1158 let kp = self.data_to_local(kf.time, kf.value);
1159 let kref = PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key };
1160 let ksel = self.selected.contains(&kref);
1161 let khov = self.hovered.as_ref() == Some(&kref);
1162 let show_handles = self.is_key_or_handle_selected(sname, ki);
1163
1164 if show_handles {
1165 for (part, hopt) in [(HandlePart::LeftHandle, kf.lh), (HandlePart::RightHandle, kf.rh)] {
1166 if let Some(h) = hopt {
1167 let hp = self.data_to_local(h[0], h[1]);
1168 let href = PointRef { spline: sname.clone(), key_idx: ki, part };
1169 let hsel = self.selected.contains(&href);
1170 let hhov = self.hovered.as_ref() == Some(&href);
1171 out.push(Primitive::Segment {
1172 from: kp,
1173 to: hp,
1174 width: 1.4,
1175 color: if hsel { [1.0, 0.85, 0.35, 1.0] } else { [0.75, 0.78, 0.86, 0.75] },
1176 });
1177 let hr = if hsel || hhov { 5.2 } else { 4.2 };
1178 out.push(Primitive::RoundedRect {
1179 rect: [hp[0] - hr, hp[1] - hr, hp[0] + hr, hp[1] + hr],
1180 radius: hr,
1181 stroke: None,
1182 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] },
1183 });
1184 }
1185 }
1186 }
1187
1188 let kr = if ksel || khov { 5.4 } else { 4.2 };
1189 out.push(Primitive::RoundedRect {
1190 rect: [kp[0] - kr, kp[1] - kr, kp[0] + kr, kp[1] + kr],
1191 radius: 1.5,
1192 stroke: None,
1193 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 },
1194 });
1195 out.push(Primitive::RoundedRect {
1196 rect: [kp[0] - kr, kp[1] - kr, kp[0] + kr, kp[1] + kr],
1197 radius: 1.5,
1198 stroke: Some(1.2),
1199 color: [0.02, 0.02, 0.03, 1.0],
1200 });
1201 }
1202 }
1203 }
1204
1205 if let Some(bs) = &self.box_select {
1206 let x0 = bs.start_local[0].min(bs.cur_local[0]);
1207 let x1 = bs.start_local[0].max(bs.cur_local[0]);
1208 let y0 = bs.start_local[1].min(bs.cur_local[1]);
1209 let y1 = bs.start_local[1].max(bs.cur_local[1]);
1210 out.push(Primitive::RoundedRect {
1211 rect: [x0, y0, x1, y1],
1212 radius: 2.0,
1213 stroke: None,
1214 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16],
1215 });
1216 out.push(Primitive::RoundedRect {
1217 rect: [x0, y0, x1, y1],
1218 radius: 2.0,
1219 stroke: Some(1.2),
1220 color: self.palette.accent,
1221 });
1222 }
1223
1224 out.push(Primitive::PopClip);
1225
1226 let hud_key = match self.modal.as_ref().map(|m| m.mode) {
1227 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",
1228 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1229 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",
1230 None => "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit",
1231 };
1232 out.push(Primitive::Rect { rect: [SIDEBAR_W, h - 24.0, w, h], color: self.palette.ruler });
1233 if let Some(hl) = self.text_cache.get(hud_key) {
1234 out.push(Primitive::Text {
1235 text: hl as &dyn Glyphs,
1236 origin: [SIDEBAR_W + 10.0, h - 18.0],
1237 clip: Some([SIDEBAR_W + 6.0, h - 24.0, w - 6.0, h]),
1238 ink: if self.modal.is_some() { [0.98, 0.82, 0.30, 1.0] } else { self.palette.text_dim },
1239 });
1240 }
1241
1242 out
1243 }
1244}
1245
1246fn ensure_handles(kf: &mut Keyframe) {
1247 if kf.lh.is_none() {
1248 kf.lh = Some([kf.time - 8.0, kf.value]);
1249 }
1250 if kf.rh.is_none() {
1251 kf.rh = Some([kf.time + 8.0, kf.value]);
1252 }
1253}
1254
1255fn spline_color(comp: &Comp, name: &str, idx: usize) -> [f32; 4] {
1256 if let Some(sp) = comp.splines.get(name) {
1257 let [r, g, b] = sp.color;
1258 if r as u16 + g as u16 + b as u16 > 120 {
1259 return [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0];
1260 }
1261 }
1262 const PALETTE: &[[f32; 4]] = &[
1263 [0.98, 0.44, 0.62, 1.0],
1264 [0.36, 0.84, 0.96, 1.0],
1265 [0.50, 0.92, 0.46, 1.0],
1266 [0.98, 0.78, 0.28, 1.0],
1267 [0.74, 0.56, 0.98, 1.0],
1268 ];
1269 PALETTE[idx % PALETTE.len()]
1270}
1271
1272fn nice_step(raw: f64) -> f64 {
1273 let raw = raw.max(1e-6);
1274 let pow = 10.0_f64.powf(raw.log10().floor());
1275 let frac = raw / pow;
1276 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 };
1277 nice * pow
1278}
1279
1280fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 {
1281 ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
1282}
crates/studio/Cargo.toml created+33
...@@ -0,0 +1,33 @@
1[package]
2name = "studio"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[[bin]]
8name = "compositor"
9path = "src/main.rs"
10
11[dependencies]
12accesskit.workspace = true
13accesskit_winit.workspace = true
14dock.workspace = true
15draw.workspace = true
16engine.workspace = true
17flow.workspace = true
18model.workspace = true
19png.workspace = true
20pollster.workspace = true
21spline.workspace = true
22state.workspace = true
23text.workspace = true
24theme.workspace = true
25ui.workspace = true
26viewer.workspace = true
27wgpu.workspace = true
28winit.workspace = true
29
30[target.'cfg(target_os = "macos")'.dependencies]
31objc2.workspace = true
32objc2-app-kit = { workspace = true, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSResponder", "NSMenu", "NSMenuItem"] }
33objc2-foundation = { workspace = true, features = ["std", "NSString"] }
crates/studio/src/main.rs created+872
...@@ -0,0 +1,872 @@
1//! Compositor Studio — docked zero-copy `wgpu` Multi-Viewer (`1`/`2`) + Flow + Blender-style Spline Editor
2//! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris).
3
4use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};
5use engine::{CacheMode, Engine};
6use flow::{FlowAction, FlowView};
7use model::Comp;
8use spline::{SplineAction, SplineView};
9use std::collections::HashMap;
10use std::error::Error;
11use std::fs::File;
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15use ui::host::{Accessibility, Clipboard, Surface};
16use viewer::{PlaybackClock, SyncMode, ViewerAction, ViewerState};
17use winit::application::ApplicationHandler;
18use winit::dpi::LogicalSize;
19use winit::event::{ElementState, WindowEvent};
20use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
21use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey};
22use winit::window::{CursorIcon, Window, WindowId};
23
24const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp";
25const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline"];
26
27fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) }
28fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) }
29fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") }
30fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") }
31
32struct Cli {
33 comp_path: PathBuf,
34 snapshot: Option<PathBuf>,
35 frame: Option<f64>,
36 select_node: Option<String>,
37 dual_viewer: bool,
38}
39
40fn parse_cli() -> Cli {
41 let args: Vec<String> = std::env::args().collect();
42 let mut comp_path = PathBuf::from(DEFAULT_COMP);
43 let mut snapshot = None;
44 let mut frame = None;
45 let mut select_node = None;
46 let mut dual_viewer = false;
47 let mut i = 1;
48 while i < args.len() {
49 match args[i].as_str() {
50 "--snapshot" if i + 1 < args.len() => {
51 snapshot = Some(PathBuf::from(&args[i + 1]));
52 i += 2;
53 }
54 "--frame" if i + 1 < args.len() => {
55 frame = args[i + 1].parse().ok();
56 i += 2;
57 }
58 "--select" if i + 1 < args.len() => {
59 select_node = Some(args[i + 1].clone());
60 i += 2;
61 }
62 "--dual" => {
63 dual_viewer = true;
64 i += 1;
65 }
66 other if !other.starts_with("--") => {
67 comp_path = PathBuf::from(other);
68 i += 1;
69 }
70 _ => i += 1,
71 }
72 }
73 Cli { comp_path, snapshot, frame, select_node, dual_viewer }
74}
75
76fn main() {
77 let cli = parse_cli();
78 let res = match &cli.snapshot {
79 Some(out) => run_snapshot(&cli, out),
80 None => run_window(&cli),
81 };
82 if let Err(e) = res {
83 eprintln!("compositor error: {e}");
84 std::process::exit(1);
85 }
86}
87
88struct Studio {
89 ui: ui::Ui,
90 dock: Dock<String>,
91 layout: dock::Layout<String>,
92 seen: dock::Seen<String>,
93 renderer: draw::Renderer,
94 engine: Engine,
95 comp: Comp,
96 playback: PlaybackClock,
97 viewers: [ViewerState; 2],
98 flow: FlowView,
99 spline: SplineView,
100 size: [f32; 2],
101 scale: f32,
102 clock: Instant,
103}
104
105impl Studio {
106 fn new(renderer: draw::Renderer, comp: Comp, init_frame: Option<f64>, select_node: Option<&str>, dual_viewer: bool) -> Self {
107 let engine = Engine::new(renderer.device().clone(), renderer.queue().clone());
108 // Knife's soft toned Iris quiet-layered theme!
109 let ui_theme = ui::Theme::new(&theme::KNIFE, true);
110 let mut ui = ui::Ui::new(ui_theme.clone());
111 ui.window_focused = true;
112
113 let g_v1 = GroupId(1);
114 let g_flow = GroupId(2);
115 let g_spline = GroupId(3);
116 let g_v2 = GroupId(4);
117
118 let top_node = if dual_viewer {
119 DockNode::Split {
120 id: SplitId(3),
121 axis: DockAxis::X,
122 parts: vec![
123 DockPart {
124 share: 0.5,
125 node: DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() },
126 rest: Default::default(),
127 },
128 DockPart {
129 share: 0.5,
130 node: DockNode::Group { id: g_v2, tabs: vec!["Viewer 2".to_owned()], preview: None, rest: Default::default() },
131 rest: Default::default(),
132 },
133 ],
134 rest: Default::default(),
135 }
136 } else {
137 DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() }
138 };
139
140 let layout = dock::Layout {
141 root: DockNode::Split {
142 id: SplitId(1),
143 axis: DockAxis::Y,
144 parts: vec![
145 DockPart { share: 0.54, node: top_node, rest: Default::default() },
146 DockPart {
147 share: 0.46,
148 node: DockNode::Split {
149 id: SplitId(2),
150 axis: DockAxis::X,
151 parts: vec![
152 DockPart {
153 share: 0.52,
154 node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() },
155 rest: Default::default(),
156 },
157 DockPart {
158 share: 0.48,
159 node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() },
160 rest: Default::default(),
161 },
162 ],
163 rest: Default::default(),
164 },
165 rest: Default::default(),
166 },
167 ],
168 rest: Default::default(),
169 },
170 issued: 5,
171 rest: Default::default(),
172 };
173 let mut seen = dock::Seen::default();
174 seen.active.insert(g_v1, "Viewer 1".to_owned());
175 if dual_viewer {
176 seen.active.insert(g_v2, "Viewer 2".to_owned());
177 }
178 seen.active.insert(g_flow, "Flow".to_owned());
179 seen.active.insert(g_spline, "Spline".to_owned());
180 seen.focused = Some(g_flow);
181 let dock = Dock::new();
182
183 let mut playback = PlaybackClock::new();
184 playback.init_from_comp(&comp);
185 if let Some(f) = init_frame {
186 playback.set_frame(&comp, f, Instant::now());
187 }
188
189 let mut v1 = ViewerState::new(0, &ui_theme);
190 v1.viewed_node = comp.default_output_node();
191 let mut v2 = ViewerState::new(1, &ui_theme);
192 v2.viewed_node = select_node.and_then(|n| comp.find_node(n)).or(v1.viewed_node);
193
194 let mut flow = FlowView::new(&ui_theme);
195 flow.viewed_nodes = [v1.viewed_node, if dual_viewer { v2.viewed_node } else { None }];
196
197 let default_sel = select_node
198 .and_then(|n| comp.find_node(n))
199 .or_else(|| comp.nodes.iter().find(|n| !comp.node_splines(n.id).is_empty()).map(|n| n.id))
200 .or(v1.viewed_node);
201 if let Some(id) = default_sel {
202 flow.selected.insert(id);
203 flow.primary = Some(id);
204 }
205
206 let mut spline = SplineView::new(&ui_theme);
207 spline.set_target_node(&comp, default_sel);
208
209 Self {
210 ui,
211 dock,
212 layout,
213 seen,
214 renderer,
215 engine,
216 comp,
217 playback,
218 viewers: [v1, v2],
219 flow,
220 spline,
221 size: [1440.0, 900.0],
222 scale: 2.0,
223 clock: Instant::now(),
224 }
225 }
226
227 fn ensure_viewer2_open(&mut self) {
228 if self.layout.group_of(&"Viewer 2".to_owned(), String::clone).is_some() {
229 return;
230 }
231 let target_group = self
232 .layout
233 .group_of(&"Viewer 1".to_owned(), String::clone)
234 .unwrap_or_else(|| self.dock.at(&mut self.layout, &mut self.seen, &String::clone).focused());
235 self.dock
236 .at(&mut self.layout, &mut self.seen, &String::clone)
237 .open("Viewer 2".to_owned(), Place::Beside(target_group, Side::Right));
238 }
239
240 fn clear_viewers(&mut self) {
241 for v in &mut self.viewers {
242 v.clear();
243 }
244 self.flow.viewed_nodes = [None, None];
245 }
246
247 fn frame(&mut self, now: Instant) -> bool {
248 self.clock = now;
249 let (animating, frame_changed) = self.playback.tick(&self.comp, now);
250 if frame_changed {
251 for v in &mut self.viewers {
252 v.dirty = true;
253 }
254 }
255
256 let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();
257 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {
258 if shown.contains(&pane_name.to_owned()) {
259 self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale);
260 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);
261 }
262 }
263 self.flow.prepare_labels(&self.comp);
264 self.spline.prepare_labels(&self.comp);
265
266 self.ui.begin(self.size, self.scale, now);
267
268 let choices: Vec<ui::popup::Item<'static>> = PANES
269 .iter()
270 .map(|&name| ui::popup::Item { text: name, ..Default::default() })
271 .collect();
272
273 let Studio {
274 ui,
275 dock,
276 layout,
277 seen,
278 engine,
279 playback,
280 viewers,
281 flow,
282 spline,
283 size,
284 ..
285 } = self;
286
287 let v1_bg = viewers[0].background();
288 let v2_bg = viewers[1].background();
289 let flow_bg = flow.background();
290 let spline_bg = spline.background();
291 let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new();
292
293 let mut d = dock.at(layout, seen, &String::clone);
294 let events = d.build(
295 ui,
296 "studio-dock",
297 *size,
298 |_| Plus::Menu("Open Pane", &choices),
299 &(),
300 |name: &String, _| {
301 let bg = match name.as_str() {
302 "Viewer 1" => v1_bg,
303 "Viewer 2" => v2_bg,
304 "Flow" => flow_bg,
305 "Spline" => spline_bg,
306 _ => flow_bg,
307 };
308 Tab {
309 title: name,
310 icon: None,
311 unsaved: false,
312 closable: true,
313 action: None,
314 background: bg,
315 }
316 },
317 |ui, name| {
318 let name = name?.as_str();
319 match name {
320 "Viewer 1" => {
321 let acts = viewers[0].build_ui(ui, viewer_pane_id(0), viewer_canvas_id(0), engine, playback);
322 for a in acts { viewer_actions.push((0, a)); }
323 Some(viewer_canvas_id(0))
324 }
325 "Viewer 2" => {
326 let acts = viewers[1].build_ui(ui, viewer_pane_id(1), viewer_canvas_id(1), engine, playback);
327 for a in acts { viewer_actions.push((1, a)); }
328 Some(viewer_canvas_id(1))
329 }
330 "Flow" => {
331 let id = ui.open_as(
332 flow_canvas_id(),
333 ui::Spec {
334 flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT,
335 size: [ui::fill(), ui::fill()],
336 ..ui::Spec::default()
337 },
338 );
339 ui.close();
340 Some(id)
341 }
342 "Spline" => {
343 let id = ui.open_as(
344 spline_canvas_id(),
345 ui::Spec {
346 flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT,
347 size: [ui::fill(), ui::fill()],
348 ..ui::Spec::default()
349 },
350 );
351 ui.close();
352 Some(id)
353 }
354 _ => None,
355 }
356 },
357 );
358 self.ui.end();
359
360 for ev in events {
361 match ev {
362 Event::Close(name) => {
363 self.dock.at(&mut self.layout, &mut self.seen, &String::clone).close(&name);
364 }
365 Event::Plus { group, choice: Some(idx), .. } => {
366 if let Some(&name) = PANES.get(idx) {
367 self.dock.at(&mut self.layout, &mut self.seen, &String::clone).open(name.to_owned(), Place::Group(group));
368 }
369 }
370 _ => {}
371 }
372 }
373
374 self.route_viewer_actions(viewer_actions, now);
375
376 for slot in [0usize, 1] {
377 let cid = viewer_canvas_id(slot);
378 if let Some(rect) = self.ui.laid_out(cid) {
379 self.viewers[slot].resize([rect[2] - rect[0], rect[3] - rect[1]]);
380 let sig = self.ui.signal(cid);
381 let ptr = self.ui.last_pointer();
382 let mods = self.ui.modifiers();
383 let mut acts = Vec::new();
384 for ev in sig.events {
385 for a in self.viewers[slot].input(&self.comp, &self.playback, ev, rect, ptr, mods) {
386 acts.push((slot, a));
387 }
388 }
389 self.route_viewer_actions(acts, now);
390 }
391 }
392
393 if let Some(rect) = self.ui.laid_out(flow_canvas_id()) {
394 self.flow.resize([rect[2] - rect[0], rect[3] - rect[1]]);
395 self.flow.ensure_fitted(&self.comp);
396 let sig = self.ui.signal(flow_canvas_id());
397 let ptr = self.ui.last_pointer();
398 let mods = self.ui.modifiers();
399 let mut acts = Vec::new();
400 for ev in sig.events {
401 acts.extend(self.flow.input(&mut self.comp, ev, rect, ptr, mods));
402 }
403 for a in acts {
404 match a {
405 FlowAction::SelectionChanged(sel) => {
406 self.spline.set_target_node(&self.comp, sel);
407 }
408 FlowAction::ViewNode(slot, id) => {
409 self.viewers[slot].viewed_node = Some(id);
410 self.viewers[slot].dirty = true;
411 self.flow.viewed_nodes[slot] = Some(id);
412 if slot == 1 {
413 self.ensure_viewer2_open();
414 }
415 }
416 FlowAction::ClearViewers => {
417 self.clear_viewers();
418 }
419 FlowAction::GraphMutated => {
420 for v in &mut self.viewers {
421 v.dirty = true;
422 }
423 }
424 }
425 }
426 }
427
428 if let Some(rect) = self.ui.laid_out(spline_canvas_id()) {
429 self.spline.resize([rect[2] - rect[0], rect[3] - rect[1]]);
430 let sig = self.ui.signal(spline_canvas_id());
431 let ptr = self.ui.last_pointer();
432 let mods = self.ui.modifiers();
433 let mut acts = Vec::new();
434 for ev in sig.events {
435 acts.extend(self.spline.input(&mut self.comp, self.playback.current_frame, ev, rect, ptr, mods));
436 }
437 for a in acts {
438 match a {
439 SplineAction::SplineEdited => {
440 if let Some(id) = self.flow.primary {
441 self.engine.bust_subtree(id);
442 }
443 for v in &mut self.viewers {
444 v.cached_frames.clear();
445 v.dirty = true;
446 }
447 }
448 SplineAction::ScrubFrame(f) => {
449 if self.playback.set_frame(&self.comp, f, now) {
450 for v in &mut self.viewers {
451 v.dirty = true;
452 }
453 }
454 }
455 }
456 }
457 }
458
459 // Immediately re-render any dirty visible viewer before painting this frame!
460 let shown_now = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();
461 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {
462 if shown_now.contains(&pane_name.to_owned()) && self.viewers[slot].dirty {
463 self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale);
464 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);
465 }
466 }
467
468 animating || self.ui.wants_frame() || self.dock.moving()
469 }
470
471 fn route_viewer_actions(&mut self, actions: Vec<(usize, ViewerAction)>, now: Instant) {
472 for (slot, a) in actions {
473 match a {
474 ViewerAction::TogglePlay => self.playback.toggle_play(now),
475 ViewerAction::SetFrame(f) => {
476 if self.playback.set_frame(&self.comp, f, now) {
477 for v in &mut self.viewers {
478 v.dirty = true;
479 }
480 }
481 }
482 ViewerAction::ToggleSyncMode => {
483 self.playback.sync_mode = match self.playback.sync_mode {
484 SyncMode::RealtimeDrop => SyncMode::EveryFrame,
485 SyncMode::EveryFrame => SyncMode::RealtimeDrop,
486 };
487 }
488 ViewerAction::NeedRender => {
489 self.viewers[slot].dirty = true;
490 }
491 ViewerAction::BustFrame(f) => {
492 self.engine.bust_frame(f);
493 for v in &mut self.viewers {
494 v.cached_frames.remove(&f);
495 v.dirty = true;
496 }
497 }
498 ViewerAction::BustSubtree => {
499 if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) {
500 self.engine.bust_subtree(id);
501 }
502 for v in &mut self.viewers {
503 v.cached_frames.clear();
504 v.dirty = true;
505 }
506 }
507 ViewerAction::BustGpu => {
508 self.engine.bust_gpu_cache();
509 for v in &mut self.viewers {
510 v.cached_frames.clear();
511 v.dirty = true;
512 }
513 }
514 ViewerAction::BustAll => {
515 self.engine.bust_all_caches();
516 for v in &mut self.viewers {
517 v.cached_frames.clear();
518 v.dirty = true;
519 }
520 }
521 ViewerAction::ToggleCacheBypass => {
522 let next = match self.engine.cache.mode {
523 CacheMode::Enabled => CacheMode::Bypass,
524 CacheMode::Bypass => CacheMode::Enabled,
525 };
526 self.engine.set_cache_mode(next);
527 for v in &mut self.viewers {
528 v.dirty = true;
529 }
530 }
531 ViewerAction::SetProxy(scale) => {
532 if self.engine.proxy_scale != scale {
533 self.engine.proxy_scale = scale;
534 self.engine.bust_gpu_cache();
535 for v in &mut self.viewers {
536 v.cached_frames.clear();
537 v.dirty = true;
538 }
539 }
540 }
541 ViewerAction::ToggleHiQ => {
542 self.engine.hiq = !self.engine.hiq;
543 for v in &mut self.viewers {
544 v.cached_frames.clear();
545 v.dirty = true;
546 }
547 }
548 ViewerAction::ClearViewers => {
549 self.clear_viewers();
550 }
551 }
552 }
553 }
554
555 fn paint(&mut self, target: &wgpu::TextureView, pixels: [u32; 2]) -> Result<(), Box<dyn Error>> {
556 let scale = self.scale;
557 let cur_f = self.playback.current_frame;
558 let Studio { ui, renderer, comp, viewers, flow, spline, .. } = self;
559
560 let mut custom_prims: HashMap<ui::Id, ([f32; 4], [f32; 2], Vec<draw::Primitive<'_>>)> = HashMap::new();
561 for slot in [0usize, 1] {
562 let cid = viewer_canvas_id(slot);
563 if let Some(r) = ui.laid_out(cid) {
564 custom_prims.insert(cid, (viewers[slot].background(), [r[0], r[1]], viewers[slot].paint(comp, cur_f)));
565 }
566 }
567 if let Some(r) = ui.laid_out(flow_canvas_id()) {
568 custom_prims.insert(flow_canvas_id(), (flow.background(), [r[0], r[1]], flow.paint(comp)));
569 }
570 if let Some(r) = ui.laid_out(spline_canvas_id()) {
571 custom_prims.insert(spline_canvas_id(), (spline.background(), [r[0], r[1]], spline.paint(comp, cur_f)));
572 }
573
574 let interface = ui.layers();
575 let layers: Vec<draw::Layer> = interface
576 .iter()
577 .filter_map(|layer| match layer {
578 ui::Layer::Primitives(prims) => Some(prims.layer(scale)),
579 ui::Layer::Custom { id, rect, .. } => {
580 let (bg, corner, prims) = custom_prims.get(id)?;
581 Some(draw::Layer {
582 scale,
583 origin: corner.map(|v| v * scale),
584 clip: Some(rect.map(|v| v * scale)),
585 backdrop: Some(*bg),
586 round: None,
587 motion: None,
588 primitives: prims,
589 })
590 }
591 })
592 .collect();
593
594 renderer
595 .draw(target, pixels, ui.theme.base, &layers)
596 .map_err(|e| format!("{e:?}"))?;
597 Ok(())
598 }
599}
600
601fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> {
602 theme::fonts::register()?;
603 let comp = Comp::from_fusion_file(&cli.comp_path)?;
604 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
605 let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?;
606 let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?;
607 let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm);
608
609 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer);
610 studio.size = [1440.0, 900.0];
611 studio.scale = 2.0;
612
613 let now = Instant::now();
614 studio.frame(now);
615 studio.frame(now + Duration::from_millis(16));
616
617 let pixels = studio.size.map(|s| (s * studio.scale) as u32);
618 let tex = studio.renderer.offscreen(pixels);
619 let view = tex.create_view(&Default::default());
620 studio.paint(&view, pixels)?;
621 let rgba = studio.renderer.read(&tex)?;
622
623 let mut enc = png::Encoder::new(File::create(out_path)?, pixels[0], pixels[1]);
624 enc.set_color(png::ColorType::Rgba);
625 enc.set_depth(png::BitDepth::Eight);
626 enc.write_header()?.write_image_data(&rgba)?;
627 eprintln!(
628 "Wrote docked Studio snapshot to {} ({}x{}) | eval={:.1}ms",
629 out_path.display(),
630 pixels[0],
631 pixels[1],
632 studio.viewers[0].last_stats.eval_ms
633 );
634 Ok(())
635}
636
637#[allow(dead_code)]
638enum UserEvent {
639 Redraw,
640 #[cfg(target_os = "macos")]
641 Quit,
642 Accessibility(accesskit_winit::Event),
643}
644
645impl From<accesskit_winit::Event> for UserEvent {
646 fn from(event: accesskit_winit::Event) -> Self {
647 Self::Accessibility(event)
648 }
649}
650
651struct WindowHost {
652 window: Arc<Window>,
653 surface: Surface,
654 studio: Studio,
655 access: Accessibility,
656 occluded: bool,
657}
658
659struct App {
660 proxy: EventLoopProxy<UserEvent>,
661 cli: Cli,
662 host: Option<WindowHost>,
663 error: Option<Box<dyn Error>>,
664}
665
666fn run_window(cli: &Cli) -> Result<(), Box<dyn Error>> {
667 theme::fonts::register()?;
668 let mut builder = EventLoop::<UserEvent>::with_user_event();
669 #[cfg(target_os = "macos")]
670 {
671 use winit::platform::macos::EventLoopBuilderExtMacOS;
672 builder.with_activate_ignoring_other_apps(false);
673 }
674 let event_loop = builder.build()?;
675 let proxy = event_loop.create_proxy();
676 let mut app = App {
677 proxy,
678 cli: Cli {
679 comp_path: cli.comp_path.clone(),
680 snapshot: None,
681 frame: cli.frame,
682 select_node: cli.select_node.clone(),
683 dual_viewer: cli.dual_viewer,
684 },
685 host: None,
686 error: None,
687 };
688 event_loop.run_app(&mut app)?;
689 match app.error {
690 Some(e) => Err(e),
691 None => Ok(()),
692 }
693}
694
695impl WindowHost {
696 fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy<UserEvent>, cli: &Cli) -> Result<Self, Box<dyn Error>> {
697 let comp = Comp::from_fusion_file(&cli.comp_path)?;
698 let title = format!("Compositor — {}", comp.name);
699 let attrs = Window::default_attributes()
700 .with_title(title)
701 .with_inner_size(LogicalSize::new(1440.0, 900.0));
702 let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?;
703 let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?;
704 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer);
705 studio.ui.window_focused = window.has_focus();
706 studio.ui.clipboard = Clipboard::system();
707 window.request_redraw();
708 #[cfg(target_os = "macos")]
709 {
710 let quit = proxy.clone();
711 ui::host::macos::quit(move || { let _ = quit.send_event(UserEvent::Quit); });
712 }
713 Ok(Self { window, surface, studio, access, occluded: false })
714 }
715
716 fn redraw(&mut self) -> Result<(), Box<dyn Error>> {
717 let now = Instant::now();
718 let wheel = self.surface.wheel.frame(now, self.studio.ui.reduces_motion());
719 if wheel != [0.0; 2] {
720 self.studio.ui.event(ui::Event::Wheel(wheel));
721 }
722 self.studio.scale = self.window.scale_factor() as f32;
723 let pixels = self.surface.fit(&self.studio.renderer);
724 if pixels.contains(&0) {
725 return Ok(());
726 }
727 self.studio.size = pixels.map(|s| s as f32 / self.studio.scale);
728 let wants_more = self.studio.frame(now);
729
730 self.window.set_cursor(self.studio.ui.cursor().unwrap_or(CursorIcon::Default));
731 self.access.update_views(&mut self.studio.ui, "Compositor", f64::from(self.studio.scale), Vec::new);
732
733 if !self.occluded && let Some(frame) = self.surface.frame(&self.studio.renderer, Some(&mut self.studio.ui))? {
734 self.studio.paint(&frame.target, pixels)?;
735 self.surface.present(&self.studio.renderer, frame);
736 }
737 if wants_more && !self.occluded {
738 self.window.request_redraw();
739 }
740 Ok(())
741 }
742
743 fn input(&mut self, event: ui::Event) {
744 // Global Space toggles playback and `` ` `` clears both viewers from any focused pane!
745 let is_space = matches!(
746 &event,
747 ui::Event::KeyInput { key: Key::Named(NamedKey::Space), state: ElementState::Pressed, repeat: false, .. }
748 | ui::Event::Key { key: Key::Named(NamedKey::Space), .. }
749 );
750 if is_space {
751 self.studio.playback.toggle_play(Instant::now());
752 self.window.request_redraw();
753 return;
754 }
755 let is_backquote = match &event {
756 ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true,
757 ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true,
758 _ => false,
759 };
760 if is_backquote {
761 self.studio.clear_viewers();
762 self.window.request_redraw();
763 return;
764 }
765 if !self.studio.ui.popups_open() && let ui::Event::Key { key, modifiers, .. } = &event {
766 let cmd = match key {
767 Key::Named(NamedKey::Tab) if modifiers.control_key() => {
768 Some(if modifiers.shift_key() { Command::Previous } else { Command::Next })
769 }
770 _ => None,
771 };
772 if let Some(cmd) = cmd {
773 let _ = self.studio.dock.at(&mut self.studio.layout, &mut self.studio.seen, &String::clone).run(cmd);
774 self.window.request_redraw();
775 return;
776 }
777 }
778 self.studio.ui.event(event);
779 self.window.request_redraw();
780 }
781}
782
783impl ApplicationHandler<UserEvent> for App {
784 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
785 if self.host.is_some() { return; }
786 match WindowHost::new(event_loop, self.proxy.clone(), &self.cli) {
787 Ok(host) => self.host = Some(host),
788 Err(e) => {
789 self.error = Some(e);
790 event_loop.exit();
791 }
792 }
793 }
794
795 fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
796 #[cfg(not(target_os = "macos"))]
797 let _ = event_loop;
798 let Some(host) = &mut self.host else { return };
799 match event {
800 UserEvent::Redraw => host.window.request_redraw(),
801 #[cfg(target_os = "macos")]
802 UserEvent::Quit => {
803 ui::host::macos::finish_quit(true);
804 event_loop.exit();
805 }
806 UserEvent::Accessibility(ev) => match ev.window_event {
807 accesskit_winit::WindowEvent::InitialTreeRequested => {
808 host.access.forget(&mut host.studio.ui);
809 host.window.request_redraw();
810 }
811 accesskit_winit::WindowEvent::AccessibilityDeactivated => host.access.forget(&mut host.studio.ui),
812 accesskit_winit::WindowEvent::ActionRequested(req) => host.input(ui::Event::Access(req)),
813 },
814 }
815 }
816
817 fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
818 let Some(host) = &mut self.host else { return };
819 host.access.adapter.process_event(&host.window, &event);
820 if let Some(Err(e)) = ui::host::draw(&event, || host.redraw()) {
821 self.error = Some(e);
822 event_loop.exit();
823 return;
824 }
825 let page = host.surface.size[1] as f32 / host.window.scale_factor() as f32;
826 if let Some(wheel) = host.surface.wheel.input(&host.window, &event, page, host.studio.ui.reduces_motion(), Instant::now()) {
827 if wheel != [0.0; 2] { host.input(ui::Event::Wheel(wheel)); }
828 host.window.request_redraw();
829 return;
830 }
831 match event {
832 WindowEvent::CloseRequested => event_loop.exit(),
833 WindowEvent::Focused(focused) => {
834 ui::host::focus(&mut host.studio.ui, focused);
835 host.window.request_redraw();
836 }
837 WindowEvent::ScaleFactorChanged { .. } => {
838 host.studio.renderer.clear_glyph_cache();
839 host.window.request_redraw();
840 }
841 WindowEvent::Occluded(occluded) => {
842 host.occluded = occluded;
843 if occluded { host.surface.wheel.cancel(); }
844 else { host.window.request_redraw(); }
845 }
846 // Route full physical + logical key events when a custom pane (Viewer/Flow/Spline) has focus!
847 WindowEvent::KeyboardInput { event: key_ev, is_synthetic: false, .. }
848 if host.studio.ui.full_key_input() =>
849 {
850 let held = host.studio.ui.modifiers();
851 host.input(ui::Event::from_key(key_ev, held));
852 }
853 other => {
854 if let Some(input) = ui::Event::from_window(other, host.window.scale_factor() as f32, host.studio.ui.modifiers()) {
855 host.input(input);
856 }
857 }
858 }
859 }
860
861 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
862 if let Some(host) = &self.host {
863 if host.studio.playback.playing && !host.occluded {
864 let wake = host.studio.playback.next_wake(&host.studio.comp);
865 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake));
866 host.window.request_redraw();
867 return;
868 }
869 }
870 event_loop.set_control_flow(ControlFlow::Wait);
871 }
872}
crates/viewer/Cargo.toml created+15
...@@ -0,0 +1,15 @@
1[package]
2name = "viewer"
3edition.workspace = true
4version.workspace = true
5publish.workspace = true
6
7[dependencies]
8draw.workspace = true
9engine.workspace = true
10model.workspace = true
11text.workspace = true
12theme.workspace = true
13ui.workspace = true
14wgpu.workspace = true
15winit.workspace = true
crates/viewer/src/lib.rs created+803
...@@ -0,0 +1,803 @@
1//! Minimal zero-copy `wgpu` comp video player built on `draw` + `ui`.
2//!
3//! Features:
4//! - Multi-viewer support (Viewer 1 & Viewer 2 sharing a synchronized timeline clock)
5//! - Realtime (drop frames) AND Every-Frame (throttled to <= comp.fps — never faster than realtime!)
6//! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions
7//! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view.
8
9use draw::{Glyphs, Primitive, RasterImage};
10use engine::{CacheMode, DisplaySettings, Engine, EvalStats};
11use model::{Comp, NodeId};
12use std::collections::HashSet;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15use winit::event::{ElementState, MouseButton};
16use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum SyncMode {
20 /// Wall/audio clock master: skips frames to hold real-time FPS.
21 RealtimeDrop,
22 /// Steps exactly +1 integer frame, throttled so it never runs faster than `comp.fps`.
23 EveryFrame,
24}
25
26/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline).
27pub struct PlaybackClock {
28 pub current_frame: f64,
29 pub playing: bool,
30 pub sync_mode: SyncMode,
31 anchor_time: Instant,
32 anchor_frame: f64,
33 last_every_step: Instant,
34}
35
36impl Default for PlaybackClock {
37 fn default() -> Self {
38 Self::new()
39 }
40}
41
42impl PlaybackClock {
43 pub fn new() -> Self {
44 let now = Instant::now();
45 Self {
46 current_frame: 0.0,
47 playing: false,
48 sync_mode: SyncMode::RealtimeDrop,
49 anchor_time: now,
50 anchor_frame: 0.0,
51 last_every_step: now,
52 }
53 }
54
55 pub fn init_from_comp(&mut self, comp: &Comp) {
56 let cur = comp.current_time.round();
57 let r0 = comp.render_range[0] as f64;
58 let r1 = comp.render_range[1] as f64;
59 self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 };
60 self.anchor_frame = self.current_frame;
61 self.anchor_time = Instant::now();
62 self.last_every_step = self.anchor_time;
63 }
64
65 pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool {
66 let clamped = frame
67 .round()
68 .clamp(comp.global_range[0] as f64, comp.global_range[1] as f64);
69 let changed = (clamped - self.current_frame).abs() > 1e-6;
70 self.current_frame = clamped;
71 if self.playing {
72 self.anchor_time = now;
73 self.anchor_frame = self.current_frame;
74 self.last_every_step = now;
75 }
76 changed
77 }
78
79 pub fn toggle_play(&mut self, now: Instant) {
80 self.playing = !self.playing;
81 self.anchor_time = now;
82 self.anchor_frame = self.current_frame;
83 self.last_every_step = now;
84 }
85
86 /// Advances the playback clock; returns `(still_playing, frame_changed)`.
87 /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime!
88 pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) {
89 if !self.playing {
90 return (false, false);
91 }
92 let r0 = comp.render_range[0] as f64;
93 let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64;
94 let span = (r1 - r0 + 1.0).max(1.0);
95 let fps = comp.fps.max(1.0);
96 let frame_dur = Duration::from_secs_f64(1.0 / fps);
97
98 let mut changed = false;
99 match self.sync_mode {
100 SyncMode::RealtimeDrop => {
101 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();
102 let adv = (elapsed * fps).floor();
103 let next = r0 + (self.anchor_frame - r0 + adv).rem_euclid(span);
104 if (next - self.current_frame).abs() >= 1.0 {
105 self.current_frame = next;
106 changed = true;
107 }
108 }
109 SyncMode::EveryFrame => {
110 if now.saturating_duration_since(self.last_every_step) >= frame_dur {
111 let next = if self.current_frame + 1.0 > r1 {
112 r0
113 } else {
114 self.current_frame + 1.0
115 };
116 self.current_frame = next;
117 self.last_every_step = now;
118 changed = true;
119 }
120 }
121 }
122 (true, changed)
123 }
124
125 pub fn next_wake(&self, comp: &Comp) -> Duration {
126 let fps = comp.fps.max(1.0);
127 Duration::from_secs_f64((0.5 / fps).min(0.016))
128 }
129}
130
131pub enum ViewerAction {
132 TogglePlay,
133 SetFrame(f64),
134 ToggleSyncMode,
135 NeedRender,
136 BustFrame(i64),
137 BustSubtree,
138 BustGpu,
139 BustAll,
140 ToggleCacheBypass,
141 SetProxy(u32),
142 ToggleHiQ,
143 ClearViewers,
144}
145
146#[derive(Clone, Copy, Debug)]
147pub struct ViewerPalette {
148 pub bg: [f32; 4],
149 pub bar: [f32; 4],
150 pub scrub_bg: [f32; 4],
151 pub border: [f32; 4],
152 pub text: [f32; 4],
153 pub accent: [f32; 4],
154}
155
156impl ViewerPalette {
157 pub fn from_ui(theme: &ui::Theme) -> Self {
158 let b = theme.base;
159 let lift = |c: [f32; 4], d: f32| {
160 [(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]
161 };
162 Self {
163 bg: b,
164 bar: theme.strip,
165 scrub_bg: lift(b, 0.024),
166 border: theme.rule,
167 text: theme.text,
168 accent: theme.accent,
169 }
170 }
171}
172
173pub struct ViewerState {
174 pub slot: usize, // 0 = Viewer 1, 1 = Viewer 2
175 pub viewed_node: Option<NodeId>,
176 pub display: DisplaySettings,
177 pub zoom: f32,
178 pub pan: [f32; 2],
179 pub fit_mode: bool,
180 pub size: [f32; 2],
181 pub last_stats: EvalStats,
182 pub cached_frames: HashSet<i64>,
183 pub dirty: bool,
184 pub palette: ViewerPalette,
185 last_revision: u64,
186 last_rendered_frame: i64,
187 last_viewed_node: Option<NodeId>,
188 output_tex: Option<wgpu::Texture>,
189 output_image: Option<RasterImage>,
190 output_size: [u32; 2],
191 last_uv_rect: [f32; 4],
192 panning: Option<([f32; 2], [f32; 2])>,
193 scrubbing: bool,
194 pointer_local: [f32; 2],
195 hud_layout: Option<(String, text::Layout)>,
196}
197
198impl ViewerState {
199 pub fn new(slot: usize, theme: &ui::Theme) -> Self {
200 Self {
201 slot,
202 viewed_node: None,
203 display: DisplaySettings::default(),
204 zoom: 1.0,
205 pan: [0.0, 0.0],
206 fit_mode: true,
207 size: [800.0, 500.0],
208 last_stats: EvalStats::default(),
209 cached_frames: HashSet::new(),
210 dirty: true,
211 palette: ViewerPalette::from_ui(theme),
212 last_revision: 0,
213 last_rendered_frame: i64::MIN,
214 last_viewed_node: None,
215 output_tex: None,
216 output_image: None,
217 output_size: [0, 0],
218 last_uv_rect: [0.0, 0.0, 1.0, 1.0],
219 panning: None,
220 scrubbing: false,
221 pointer_local: [0.0, 0.0],
222 hud_layout: None,
223 }
224 }
225
226 pub fn background(&self) -> [f32; 4] {
227 self.palette.bg
228 }
229
230 pub fn resize(&mut self, size: [f32; 2]) {
231 let clamped = [size[0].max(1.0), size[1].max(1.0)];
232 if (self.size[0] - clamped[0]).abs() > 0.5 || (self.size[1] - clamped[1]).abs() > 0.5 {
233 self.size = clamped;
234 self.dirty = true;
235 }
236 }
237
238 pub fn fit(&mut self) {
239 self.fit_mode = true;
240 self.pan = [0.0, 0.0];
241 self.dirty = true;
242 }
243
244 pub fn clear(&mut self) {
245 self.viewed_node = None;
246 self.last_viewed_node = None;
247 self.output_tex = None;
248 self.output_image = None;
249 self.output_size = [0, 0];
250 self.dirty = false;
251 }
252
253 /// Computes `(full_img_rect, visible_rect, uv_rect, effective_scale)` in viewer-local coordinates.
254 fn image_layout(&self, comp: &Comp) -> ([f32; 4], [f32; 4], [f32; 4], f32) {
255 let [w, h] = self.size;
256 let top_pad = 30.0;
257 let view_h = (h - 34.0).max(20.0);
258 let avail_h = (view_h - top_pad - 6.0).max(20.0);
259 let iw = comp.width.max(1) as f32;
260 let ih = comp.height.max(1) as f32;
261 let scale = if self.fit_mode {
262 ((w - 24.0) / iw).min((avail_h - 4.0) / ih).max(0.05)
263 } else {
264 self.zoom
265 };
266 let dw = iw * scale;
267 let dh = ih * scale;
268 let cx = w * 0.5 + if self.fit_mode { 0.0 } else { self.pan[0] };
269 let cy = top_pad + avail_h * 0.5 + if self.fit_mode { 0.0 } else { self.pan[1] };
270 let img = [cx - dw * 0.5, cy - dh * 0.5, cx + dw * 0.5, cy + dh * 0.5];
271 let vp = [4.0, top_pad, (w - 4.0).max(8.0), (view_h - 2.0).max(top_pad + 4.0)];
272 let vis = [
273 img[0].max(vp[0]),
274 img[1].max(vp[1]),
275 img[2].min(vp[2]),
276 img[3].min(vp[3]),
277 ];
278 let u0 = ((vis[0] - img[0]) / dw.max(1e-4)).clamp(0.0, 1.0);
279 let v0 = ((vis[1] - img[1]) / dh.max(1e-4)).clamp(0.0, 1.0);
280 let u1 = ((vis[2] - img[0]) / dw.max(1e-4)).clamp(0.0, 1.0);
281 let v1 = ((vis[3] - img[1]) / dh.max(1e-4)).clamp(0.0, 1.0);
282 (img, vis, [u0, v0, u1, v1], scale)
283 }
284
285 fn zoom_at(&mut self, comp: &Comp, factor: f32, pivot_local: [f32; 2]) {
286 let (img, _, _, cur_scale) = self.image_layout(comp);
287 let [w, h] = self.size;
288 let top_pad = 30.0;
289 let view_h = (h - 34.0).max(20.0);
290 let avail_h = (view_h - top_pad - 6.0).max(20.0);
291 let iw = comp.width.max(1) as f32;
292 let ih = comp.height.max(1) as f32;
293
294 // Image UV right underneath the mouse cursor stays fixed through zoom!
295 let u = (pivot_local[0] - img[0]) / (img[2] - img[0]).max(1e-4);
296 let v = (pivot_local[1] - img[1]) / (img[3] - img[1]).max(1e-4);
297
298 let new_scale = (cur_scale * factor).clamp(0.05, 32.0);
299 let new_dw = iw * new_scale;
300 let new_dh = ih * new_scale;
301 let new_x0 = pivot_local[0] - u * new_dw;
302 let new_y0 = pivot_local[1] - v * new_dh;
303 let new_cx = new_x0 + new_dw * 0.5;
304 let new_cy = new_y0 + new_dh * 0.5;
305
306 self.fit_mode = false;
307 self.zoom = new_scale;
308 self.pan = [new_cx - w * 0.5, new_cy - (top_pad + avail_h * 0.5)];
309 self.dirty = true;
310 }
311
312 pub fn ensure_rendered(&mut self, engine: &mut Engine, comp: &Comp, current_frame: f64, dpi_scale: f32) {
313 let Some(target) = self.viewed_node else {
314 return;
315 };
316 let frame_i = current_frame.round() as i64;
317 let (_, vis, uv_rect, _) = self.image_layout(comp);
318 if vis[2] <= vis[0] + 1.0 || vis[3] <= vis[1] + 1.0 {
319 return;
320 }
321 // Viewport-exact physical pixel backing texture -> 1:1 display with ZERO bilinear blur when Smooth Resize is OFF!
322 let desired_size = [
323 ((vis[2] - vis[0]) * dpi_scale).round().clamp(1.0, 2880.0) as u32,
324 ((vis[3] - vis[1]) * dpi_scale).round().clamp(1.0, 1800.0) as u32,
325 ];
326
327 if self.output_size != desired_size || self.output_tex.is_none() {
328 let tex = engine.device().create_texture(&wgpu::TextureDescriptor {
329 label: Some("viewer-output"),
330 size: wgpu::Extent3d {
331 width: desired_size[0],
332 height: desired_size[1],
333 depth_or_array_layers: 1,
334 },
335 mip_level_count: 1,
336 sample_count: 1,
337 dimension: wgpu::TextureDimension::D2,
338 format: wgpu::TextureFormat::Rgba8Unorm,
339 usage: wgpu::TextureUsages::TEXTURE_BINDING
340 | wgpu::TextureUsages::STORAGE_BINDING
341 | wgpu::TextureUsages::COPY_SRC,
342 view_formats: &[],
343 });
344 let tex_for_draw = tex.clone();
345 let img = RasterImage::from_texture(desired_size, move |_| tex_for_draw.clone());
346 self.output_tex = Some(tex);
347 self.output_image = Some(img);
348 self.output_size = desired_size;
349 self.dirty = true;
350 }
351
352 let uv_changed = (0..4).any(|i| (uv_rect[i] - self.last_uv_rect[i]).abs() > 1e-5);
353 let needs_eval = self.dirty
354 || uv_changed
355 || self.last_revision != comp.revision
356 || self.last_rendered_frame != frame_i
357 || self.last_viewed_node != Some(target);
358
359 if needs_eval {
360 if let Some(tex) = &self.output_tex {
361 let mut disp = self.display;
362 disp.uv_rect = uv_rect;
363 self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp);
364 if engine.cache.mode == CacheMode::Enabled {
365 self.cached_frames.insert(frame_i);
366 }
367 self.dirty = false;
368 self.last_uv_rect = uv_rect;
369 self.last_revision = comp.revision;
370 self.last_rendered_frame = frame_i;
371 self.last_viewed_node = Some(target);
372 }
373 }
374 }
375
376 pub fn prepare_hud(&mut self, comp: &Comp, engine: &Engine, clock: &PlaybackClock) {
377 let node_name = self
378 .viewed_node
379 .map(|id| comp.node(id).name.as_str())
380 .unwrap_or("(empty)");
381 let cache_lbl = match engine.cache.mode {
382 CacheMode::Enabled => "CACHE",
383 CacheMode::Bypass => "BYPASS",
384 };
385 let sync_lbl = match clock.sync_mode {
386 SyncMode::RealtimeDrop => "RT",
387 SyncMode::EveryFrame => "EVERY",
388 };
389 let hiq_lbl = if engine.hiq { "HiQ" } else { "FAST" };
390 let (_, _, _, eff_scale) = self.image_layout(comp);
391 let zoom_pct = (eff_scale * 100.0).round() as i32;
392 let s = &self.last_stats;
393 let line = format!(
394 "[V{}] {} · f{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}",
395 self.slot + 1,
396 node_name,
397 clock.current_frame.round() as i64,
398 zoom_pct,
399 s.eval_ms,
400 s.nodes_evaluated,
401 s.cache_hits,
402 s.cache_misses,
403 s.cached_vram_mb,
404 engine.proxy_scale,
405 hiq_lbl,
406 cache_lbl,
407 sync_lbl,
408 );
409 if self.hud_layout.as_ref().is_none_or(|(prev, _)| prev != &line) {
410 let font = text::Font {
411 families: Arc::from([text::Family::Mono]),
412 size: 10.5,
413 weight: 500,
414 italic: false,
415 };
416 let styles = [text::Style::new(font)];
417 let layout = text::Paragraph {
418 text: &line,
419 styles: &styles,
420 spans: &[],
421 replacements: &[],
422 width: None,
423 indent: 0.0,
424 line_height: 1.2,
425 align: text::Align::Left,
426 tab: 32.0,
427 }
428 .layout();
429 self.hud_layout = Some((line, layout));
430 }
431 }
432
433 pub fn build_ui(
434 &mut self,
435 ui: &mut ui::Ui,
436 pane_id: ui::Id,
437 canvas_id: ui::Id,
438 engine: &Engine,
439 clock: &PlaybackClock,
440 ) -> Vec<ViewerAction> {
441 let mut actions = Vec::new();
442 ui.open_as(
443 pane_id,
444 ui::Spec {
445 size: [ui::fill(), ui::fill()],
446 axis: ui::Axis::Y,
447 fill: Some(self.background()),
448 ..ui::Spec::default()
449 },
450 );
451
452 ui.open(
453 ("top_bar", self.slot),
454 ui::Spec {
455 size: [ui::fill(), ui::px(30.0)],
456 axis: ui::Axis::X,
457 pad: [6.0, 4.0],
458 gap: 4.0,
459 fill: Some(self.palette.bar),
460 ..ui::Spec::default()
461 },
462 );
463
464 if self.slot == 0 {
465 let play_lbl = if clock.playing { "Pause" } else { "Play" };
466 if tool_btn(ui, ("play", self.slot), play_lbl, clock.playing).clicked {
467 actions.push(ViewerAction::TogglePlay);
468 }
469 if tool_btn(ui, ("prev", self.slot), "<", false).clicked {
470 actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0));
471 }
472 if tool_btn(ui, ("next", self.slot), ">", false).clicked {
473 actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0));
474 }
475 let sync_lbl = match clock.sync_mode {
476 SyncMode::RealtimeDrop => "RT",
477 SyncMode::EveryFrame => "Every",
478 };
479 if tool_btn(ui, ("sync", self.slot), sync_lbl, clock.sync_mode == SyncMode::EveryFrame).clicked {
480 actions.push(ViewerAction::ToggleSyncMode);
481 }
482 for scale in [1u32, 2, 4] {
483 let lbl = format!("1:{scale}");
484 if tool_btn(ui, ("proxy", self.slot, scale), &lbl, engine.proxy_scale == scale).clicked {
485 actions.push(ViewerAction::SetProxy(scale));
486 }
487 }
488 if tool_btn(ui, ("hiq", self.slot), "HiQ", engine.hiq).clicked {
489 actions.push(ViewerAction::ToggleHiQ);
490 }
491 }
492
493 let ch_lbl = match self.display.channel {
494 1 => "R",
495 2 => "G",
496 3 => "B",
497 4 => "A",
498 _ => "RGBA",
499 };
500 if tool_btn(ui, ("chan", self.slot), ch_lbl, self.display.channel != 0).clicked {
501 self.display.channel = (self.display.channel + 1) % 5;
502 self.dirty = true;
503 actions.push(ViewerAction::NeedRender);
504 }
505 let filt_lbl = if self.display.smooth_resize { "Smooth" } else { "Pixel" };
506 if tool_btn(ui, ("smooth", self.slot), filt_lbl, self.display.smooth_resize).clicked {
507 self.display.smooth_resize = !self.display.smooth_resize;
508 self.dirty = true;
509 actions.push(ViewerAction::NeedRender);
510 }
511 if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked {
512 self.fit();
513 }
514
515 if self.slot == 0 {
516 let bypass_lbl = match engine.cache.mode {
517 CacheMode::Enabled => "Cache",
518 CacheMode::Bypass => "Bypass",
519 };
520 if tool_btn(ui, ("cache_mode", self.slot), bypass_lbl, engine.cache.mode == CacheMode::Bypass).clicked {
521 actions.push(ViewerAction::ToggleCacheBypass);
522 }
523 if tool_btn(ui, ("bust_frame", self.slot), "Bust F", false).clicked {
524 let f = clock.current_frame.round() as i64;
525 self.cached_frames.remove(&f);
526 self.dirty = true;
527 actions.push(ViewerAction::BustFrame(f));
528 }
529 if tool_btn(ui, ("bust_sub", self.slot), "Node", false).clicked {
530 self.cached_frames.clear();
531 self.dirty = true;
532 actions.push(ViewerAction::BustSubtree);
533 }
534 if tool_btn(ui, ("bust_gpu", self.slot), "GPU", false).clicked {
535 self.cached_frames.clear();
536 self.dirty = true;
537 actions.push(ViewerAction::BustGpu);
538 }
539 if tool_btn(ui, ("bust_all", self.slot), "All", false).clicked {
540 self.cached_frames.clear();
541 self.dirty = true;
542 actions.push(ViewerAction::BustAll);
543 }
544 }
545 ui.close();
546
547 ui.open_as(
548 canvas_id,
549 ui::Spec {
550 flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT,
551 size: [ui::fill(), ui::fill()],
552 ..ui::Spec::default()
553 },
554 );
555 ui.close();
556
557 ui.close();
558 actions
559 }
560
561 fn scrubber_rect(&self) -> [f32; 4] {
562 [
563 10.0,
564 (self.size[1] - 26.0).max(4.0),
565 (self.size[0] - 10.0).max(20.0),
566 (self.size[1] - 8.0).max(20.0),
567 ]
568 }
569
570 fn frame_at_x(&self, comp: &Comp, local_x: f32) -> f64 {
571 let r = self.scrubber_rect();
572 let frac = ((local_x - r[0]) / (r[2] - r[0]).max(1.0)).clamp(0.0, 1.0);
573 let r0 = comp.render_range[0] as f64;
574 let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64;
575 (r0 + f64::from(frac) * (r1 - r0)).round()
576 }
577
578 fn handle_key(&mut self, clock: &PlaybackClock, physical: Option<PhysicalKey>, key: &Key, kmod: ModifiersState, actions: &mut Vec<ViewerAction>) {
579 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
580 self.fit();
581 return;
582 }
583 if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) {
584 actions.push(ViewerAction::ClearViewers);
585 return;
586 }
587 match key {
588 Key::Named(NamedKey::Space) => actions.push(ViewerAction::TogglePlay),
589 Key::Named(NamedKey::ArrowLeft) => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)),
590 Key::Named(NamedKey::ArrowRight) => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)),
591 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
592 "`" | "~" => actions.push(ViewerAction::ClearViewers),
593 "f" if kmod.super_key() => self.fit(),
594 "f" | "." if !kmod.super_key() => self.fit(),
595 "0" => {
596 self.fit_mode = false;
597 self.zoom = 1.0;
598 self.pan = [0.0, 0.0];
599 self.dirty = true;
600 }
601 "[" => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)),
602 "]" => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)),
603 _ => {}
604 },
605 _ => {}
606 }
607 }
608
609 pub fn input(
610 &mut self,
611 comp: &Comp,
612 clock: &PlaybackClock,
613 event: ui::Event,
614 rect: [f32; 4],
615 pointer_window: [f32; 2],
616 modifiers: ModifiersState,
617 ) -> Vec<ViewerAction> {
618 let mut actions = Vec::new();
619 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
620 let scrub = self.scrubber_rect();
621
622 match event {
623 ui::Event::PointerMoved(p) => {
624 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
625 if self.scrubbing {
626 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));
627 } else if let Some((sp, span)) = self.panning {
628 self.fit_mode = false;
629 self.pan = [
630 span[0] + (self.pointer_local[0] - sp[0]),
631 span[1] + (self.pointer_local[1] - sp[1]),
632 ];
633 self.dirty = true;
634 }
635 }
636 ui::Event::Button { button, pressed, .. } => {
637 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
638 if pressed {
639 if self.fit_mode {
640 let (_, _, _, cur_scale) = self.image_layout(comp);
641 self.zoom = cur_scale;
642 self.pan = [0.0, 0.0];
643 self.fit_mode = false;
644 }
645 self.panning = Some((self.pointer_local, self.pan));
646 } else {
647 self.panning = None;
648 }
649 } else if button == MouseButton::Left {
650 if pressed {
651 if self.pointer_local[1] >= scrub[1] - 6.0 {
652 self.scrubbing = true;
653 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));
654 }
655 } else {
656 self.scrubbing = false;
657 }
658 }
659 }
660 ui::Event::Wheel(delta) => {
661 // Blender & Fusion convention: plain scroll zooms toward mouse cursor; Shift+scroll pans.
662 if modifiers.shift_key() {
663 if self.fit_mode {
664 let (_, _, _, cur_scale) = self.image_layout(comp);
665 self.zoom = cur_scale;
666 self.pan = [0.0, 0.0];
667 self.fit_mode = false;
668 }
669 self.pan[0] += delta[0];
670 self.pan[1] += delta[1];
671 self.dirty = true;
672 } else {
673 let factor = (1.0 + delta[1] * 0.0045).clamp(0.7, 1.4);
674 self.zoom_at(comp, factor, self.pointer_local);
675 }
676 }
677 ui::Event::Pinch(delta) => {
678 let factor = (1.0 + delta).clamp(0.7, 1.4);
679 self.zoom_at(comp, factor, self.pointer_local);
680 }
681 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, .. } => {
682 self.handle_key(clock, Some(physical), &key, modifiers, &mut actions);
683 }
684 ui::Event::Key { key, modifiers: kmod, .. } => {
685 self.handle_key(clock, None, &key, kmod, &mut actions);
686 }
687 _ => {}
688 }
689 actions
690 }
691
692 pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec<Primitive<'a>> {
693 let mut out = Vec::with_capacity(64);
694 let [w, _h] = self.size;
695
696 if self.viewed_node.is_some() {
697 if let Some(img) = &self.output_image {
698 let (full_rect, vis, _, _) = self.image_layout(comp);
699 if vis[2] > vis[0] + 0.5 && vis[3] > vis[1] + 0.5 {
700 out.push(Primitive::Image { image: img, rect: vis, radius: 0.0 });
701 out.push(Primitive::RoundedRect {
702 rect: [
703 full_rect[0].max(vis[0]),
704 full_rect[1].max(vis[1]),
705 full_rect[2].min(vis[2]),
706 full_rect[3].min(vis[3]),
707 ],
708 radius: 1.0,
709 stroke: Some(1.0),
710 color: self.palette.border,
711 });
712 }
713 }
714 }
715
716 if let Some((_, layout)) = &self.hud_layout {
717 out.push(Primitive::RoundedRect {
718 rect: [8.0, 5.0, (w - 8.0).max(20.0), 24.0],
719 radius: 4.0,
720 stroke: None,
721 color: [self.palette.bg[0] * 0.72, self.palette.bg[1] * 0.72, self.palette.bg[2] * 0.72, 0.82],
722 });
723 out.push(Primitive::Text {
724 text: layout as &dyn Glyphs,
725 origin: [14.0, 8.0],
726 clip: Some([12.0, 5.0, w - 12.0, 24.0]),
727 ink: self.palette.text,
728 });
729 }
730
731 let sr = self.scrubber_rect();
732 out.push(Primitive::RoundedRect { rect: sr, radius: 4.0, stroke: None, color: self.palette.scrub_bg });
733 let r0 = comp.render_range[0] as f64;
734 let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64;
735 let span = (r1 - r0).max(1.0);
736 let bar_w = (sr[2] - sr[0]).max(1.0);
737 let tick_w = (bar_w / span as f32).max(2.0);
738 for &cf in &self.cached_frames {
739 if (cf as f64) >= r0 && (cf as f64) <= r1 {
740 let frac = ((cf as f64 - r0) / span) as f32;
741 let x = sr[0] + frac * bar_w;
742 out.push(Primitive::Rect {
743 rect: [x, sr[3] - 4.0, (x + tick_w).min(sr[2]), sr[3] - 1.0],
744 color: [0.24, 0.84, 0.50, 0.85],
745 });
746 }
747 }
748
749 let frac = ((current_frame - r0) / span).clamp(0.0, 1.0) as f32;
750 let px = sr[0] + frac * bar_w;
751 out.push(Primitive::RoundedRect {
752 rect: [sr[0], sr[1], px.max(sr[0] + 2.0), sr[3]],
753 radius: 4.0,
754 stroke: None,
755 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25],
756 });
757 out.push(Primitive::RoundedRect {
758 rect: [px - 3.0, sr[1] - 2.0, px + 3.0, sr[3] + 2.0],
759 radius: 2.0,
760 stroke: None,
761 color: [0.98, 0.40, 0.36, 1.0],
762 });
763
764 out
765 }
766}
767
768/// Sleek Knife-style compact toolbar control (soft tinted surface + hairline border,
769/// accent tint when active — replaces the chunky generic `ui::button`).
770fn tool_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal {
771 let t = &ui.theme;
772 let fill = if active {
773 [t.accent[0], t.accent[1], t.accent[2], 0.24]
774 } else {
775 [t.base[0], t.base[1], t.base[2], 0.65]
776 };
777 let border = if active {
778 [t.accent[0], t.accent[1], t.accent[2], 0.65]
779 } else {
780 t.rule
781 };
782 let ink = if active { t.text } else { t.text_dim };
783 ui.leaf(
784 part,
785 ui::Spec {
786 cursor: Some(winit::window::CursorIcon::Pointer),
787 flags: ui::Flags::CLICKABLE,
788 size: [ui::fit(), ui::px(22.0)],
789 text: Some(label),
790 font_size: Some(11.5),
791 medium: true,
792 color: Some(ink),
793 fill: Some(fill),
794 border: Some(border),
795 hover_fill: Some(t.ghost_soft),
796 hover_border: Some(t.accent),
797 radius: 5.0,
798 pad: [7.0, 0.0],
799 center: true,
800 ..ui::Spec::default()
801 },
802 )
803}
scripts/fusion_probes.py created+1033
...@@ -0,0 +1,1033 @@
1#!/usr/bin/env python3
2"""Fusion Render Node (sg render) conformance probe generator & comparator.
3
4Generates compact multi-frame .comp files, renders ground truth on Snow Globe's RTX 3090 via
5`sg render` (using /Volumes/clover directly if mounted, or sg upload/download to /srv/clover),
6and compares every frame against our `target/release/render-check`.
7"""
8
9import math
10import os
11import struct
12import subprocess
13import sys
14import zlib
15from pathlib import Path
16
17SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes")
18REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes"
19CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes"
20LOCAL_FALLBACK = Path(
21 "/Users/clo/.knife/agent/gemini-roPs/antigravity-cli/brain/d42ef021-5bce-4812-b5e5-1e3ed7ce6c77/scratch/probes"
22)
23REPO = Path("/Users/clo/dev/compositor")
24RENDER_CHECK = REPO / "target/release/render-check"
25
26
27def use_smb() -> bool:
28 return SMB_ROOT.parent.exists()
29
30
31def local_root() -> Path:
32 return SMB_ROOT if use_smb() else LOCAL_FALLBACK
33
34
35def ensure_dirs():
36 r = local_root()
37 for sub in ("comps", "assets", "gt", "ours"):
38 (r / sub).mkdir(parents=True, exist_ok=True)
39
40
41def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes):
42 def chunk(tag: bytes, data: bytes) -> bytes:
43 return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
44
45 raw = bytearray()
46 stride = w * 4
47 for y in range(h):
48 raw.append(0)
49 raw.extend(rgba_bytes[y * stride : (y + 1) * stride])
50
51 ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)
52 png = (
53 b"\x89PNG\r\n\x1a\n"
54 + chunk(b"IHDR", ihdr)
55 + chunk(b"IDAT", zlib.compress(bytes(raw), level=6))
56 + chunk(b"IEND", b"")
57 )
58 path.write_bytes(png)
59
60
61def hsv_to_rgb(h: float, s: float, v: float):
62 h = (h % 1.0) * 6.0
63 i = int(h)
64 f = h - i
65 p = v * (1.0 - s)
66 q = v * (1.0 - s * f)
67 t = v * (1.0 - s * (1.0 - f))
68 return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6]
69
70
71def sync_asset(local_path: Path):
72 if not use_smb():
73 subprocess.run(["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"], check=True)
74
75
76def generate_color_chart() -> str:
77 """Straight-alpha PNG color chart (512x512)."""
78 p = local_root() / "assets" / "color_chart.png"
79 if p.exists() and p.stat().st_size > 1000:
80 return f"{CONTAINER_ROOT}/assets/color_chart.png"
81 w, h = 512, 512
82 buf = bytearray(w * h * 4)
83 for y in range(h):
84 ny = y / (h - 1)
85 for x in range(w):
86 nx = x / (w - 1)
87 r, g, b, a = 0.0, 0.0, 0.0, 1.0
88 if ny < 0.45:
89 r, g, b = hsv_to_rgb(nx, ny / 0.45, 0.85)
90 elif ny < 0.70:
91 t = (ny - 0.45) / 0.25
92 wave = 0.5 + 0.5 * math.sin(nx * 25.0 + ny * 40.0)
93 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))
94 elif ny < 0.85:
95 if nx < 0.5:
96 g0 = nx * 2.0
97 r, g, b = g0, g0, g0
98 else:
99 r, g, b = hsv_to_rgb((nx - 0.5) * 2.0, 1.0, 0.35 + 0.65 * ((ny - 0.70) / 0.15))
100 else:
101 r, g, b = hsv_to_rgb(nx, 0.9, 0.9)
102 a = 1.0 - (ny - 0.85) / 0.15
103 idx = (y * w + x) * 4
104 buf[idx] = max(0, min(255, int(round(r * 255))))
105 buf[idx + 1] = max(0, min(255, int(round(g * 255))))
106 buf[idx + 2] = max(0, min(255, int(round(b * 255))))
107 buf[idx + 3] = max(0, min(255, int(round(a * 255))))
108 write_png_rgba(p, w, h, bytes(buf))
109 sync_asset(p)
110 return f"{CONTAINER_ROOT}/assets/color_chart.png"
111
112
113def generate_grid_chart() -> str:
114 """512x512 crisp colored grid + asymmetric L-shape for 3D / Transform / Displace orientation tests."""
115 p = local_root() / "assets" / "grid_chart.png"
116 if p.exists() and p.stat().st_size > 1000:
117 return f"{CONTAINER_ROOT}/assets/grid_chart.png"
118 w, h = 512, 512
119 buf = bytearray(w * h * 4)
120 for y in range(h):
121 for x in range(w):
122 r, g, b, a = 24, 28, 36, 255
123 # Colored quadrants
124 if x < 256 and y < 256:
125 r, g, b = 190, 60, 60 # top-left = red
126 elif x >= 256 and y < 256:
127 r, g, b = 60, 180, 75 # top-right = green
128 elif x < 256 and y >= 256:
129 r, g, b = 60, 95, 200 # bottom-left = blue
130 else:
131 r, g, b = 210, 180, 50 # bottom-right = yellow
132 # Grid lines every 64px
133 if x % 64 < 3 or y % 64 < 3:
134 r, g, b = 245, 245, 245
135 # Asymmetric white arrow pointing UP-RIGHT in center
136 if 220 <= x <= 290 and 120 <= y <= 380 and abs(x - 256) < 12:
137 r, g, b = 255, 255, 255
138 if 120 <= y <= 180 and abs(x - 256) < (y - 120):
139 r, g, b = 255, 255, 255
140 # Small bright square at top-left (x=64..96, y=64..96)
141 if 64 <= x < 112 and 64 <= y < 112:
142 r, g, b = 255, 255, 0
143 idx = (y * w + x) * 4
144 buf[idx:idx+4] = bytes((r, g, b, a))
145 write_png_rgba(p, w, h, bytes(buf))
146 sync_asset(p)
147 return f"{CONTAINER_ROOT}/assets/grid_chart.png"
148
149
150def step_spline(name: str, frame_values: dict) -> str:
151 kfs = []
152 for f, v in sorted(frame_values.items()):
153 kfs.append(f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }},")
154 return f"""\t\t{name} = BezierSpline {{
155\t\t\tKeyFrames = {{
156{chr(10).join(kfs)}
157\t\t\t}},
158\t\t}},"""
159
160
161def make_loader(name: str, container_path: str, post_mult: int = 1) -> str:
162 return f"""\t\t{name} = Loader {{
163\t\t\tClips = {{
164\t\t\t\tClip {{
165\t\t\t\t\tID = "Clip1",
166\t\t\t\t\tFilename = "{container_path}",
167\t\t\t\t\tFormatID = "PNGFormat",
168\t\t\t\t\tLength = 1,
169\t\t\t\t\tLengthSetManually = true,
170\t\t\t\t\tTrimIn = 0,
171\t\t\t\t\tTrimOut = 0,
172\t\t\t\t\tExtendFirst = 0,
173\t\t\t\t\tExtendLast = 0,
174\t\t\t\t\tLoop = 1,
175\t\t\t\t\tStartFrame = -1,
176\t\t\t\t\tGlobalStart = 0,
177\t\t\t\t\tGlobalEnd = 100,
178\t\t\t\t}},
179\t\t\t}},
180\t\t\tInputs = {{
181\t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }},
182\t\t\t}},
183\t\t}},"""
184
185
186def make_saver(src_op: str, prefix: str) -> str:
187 return f"""\t\tSaver1 = Saver {{
188\t\t\tInputs = {{
189\t\t\t\tClip = Input {{
190\t\t\t\t\tValue = Clip {{
191\t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png",
192\t\t\t\t\t\tFormatID = "PNGFormat",
193\t\t\t\t\t\tLength = 0,
194\t\t\t\t\t\tSaving = true,
195\t\t\t\t\t\tTrimIn = 0,
196\t\t\t\t\t\tExtendFirst = 0,
197\t\t\t\t\t\tExtendLast = 0,
198\t\t\t\t\t\tLoop = 1,
199\t\t\t\t\t\tAspectMode = 0,
200\t\t\t\t\t\tDepth = 0,
201\t\t\t\t\t\tGlobalStart = -2000000000,
202\t\t\t\t\t\tGlobalEnd = 0,
203\t\t\t\t\t}},
204\t\t\t\t}},
205\t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }},
206\t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }},
207\t\t\t}},
208\t\t}},"""
209
210
211def make_comp(tools_body: str, end_frame: int, w: int = 512, h: int = 512) -> str:
212 return f"""Composition {{
213\tCurrentTime = 0,
214\tRenderRange = {{ 0, {end_frame} }},
215\tGlobalRange = {{ 0, {end_frame} }},
216\tCurrentID = 200,
217\tHiQ = true,
218\tPlaybackUpdateMode = 0,
219\tVersion = "Fusion Studio 21.1 build 23",
220\tTools = ordered() {{
221{tools_body}
222\t}},
223\tPrefs = {{
224\t\tComp = {{
225\t\t\tFrameFormat = {{
226\t\t\t\tWidth = {w},
227\t\t\t\tHeight = {h},
228\t\t\t\tRate = 24,
229\t\t\t}},
230\t\t}},
231\t}},
232}}
233"""
234
235
236def build_probe_merge():
237 """Tests Merge ApplyModes + Gain (0, 0.5, 0.92, 1.0) + Operator=Under + BurnIn + SubtractiveAdditive!"""
238 chart = generate_color_chart()
239 grid = generate_grid_chart()
240 # Each case gets its own Merge node chained with Blend=1 on its frame and 0 on all other frames!
241 cases = [
242 # (frame, label, apply_mode, operator, gain, sub_add, burn_in, extra_inputs)
243 (0, "Normal_gain1.0", "Normal", "Over", 1.0, 1.0, 0.0, ""),
244 (1, "Normal_gain0.5", "Normal", "Over", 0.5, 1.0, 0.0, ""),
245 (2, "Normal_gain0.0_add", "Normal", "Over", 0.0, 1.0, 0.0, ""),
246 (3, "Normal_sub0.0_add", "Normal", "Over", 1.0, 0.0, 0.0, ""),
247 (4, "Normal_Under", "Normal", "Under", 1.0, 1.0, 0.0, ""),
248 (5, "Difference_gain1.0", "Difference", "Over", 1.0, 1.0, 0.0, ""),
249 (6, "Difference_gain0.92", "Difference", "Over", 0.92, 1.0, 0.0, ""),
250 (7, "Difference_gain0.5", "Difference", "Over", 0.5, 1.0, 0.0, ""),
251 (8, "Difference_gain0.0", "Difference", "Over", 0.0, 1.0, 0.0, ""),
252 (9, "DarkerColor_gain1.0", "DarkerColor", "Over", 1.0, 1.0, 0.0, ""),
253 (10, "DarkerColor_gain0.5", "DarkerColor", "Over", 0.5, 1.0, 0.0, ""),
254 (11, "Darken_gain1.0", "Darken", "Over", 1.0, 1.0, 0.0, ""),
255 (12, "Multiply_gain1.0", "Multiply", "Over", 1.0, 1.0, 0.0, ""),
256 (13, "Screen_gain1.0", "Screen", "Over", 1.0, 1.0, 0.0, ""),
257 (14, "Screen_gain0.5", "Screen", "Over", 0.5, 1.0, 0.0, ""),
258 (15, "LinearDodge_gain1.0", "LinearDodge", "Over", 1.0, 1.0, 0.0, ""),
259 (16, "LinearLight_gain1.0", "LinearLight", "Over", 1.0, 1.0, 0.0, ""),
260 (17, "HardLight_gain1.0", "Hard Light", "Over", 1.0, 1.0, 0.0, ""),
261 (18, "SoftLight_gain1.0", "Soft Light", "Over", 1.0, 1.0, 0.0, ""),
262 (19, "Normal_BurnIn0.5", "Normal", "Over", 1.0, 1.0, 0.5, ""),
263 ]
264
265 nodes = [
266 make_loader("BG_Loader", chart, post_mult=1),
267 make_loader("FG_Loader", grid, post_mult=1),
268 # Also make a semi-transparent FG (alpha=0.75) by merging FG over transparent or multiplying?
269 # 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!
270 ]
271 splines = []
272 # Chain merges on a clean BG_Loader -> Switch via Blend=1 on active frame
273 # 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!
274 prev = "BG_Loader"
275 for f, label, mode, op, gain, sub_add, burn_in, extra in cases:
276 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
277 sname = f"M{f}_Blend"
278 splines.append(step_spline(sname, bl))
279 nodes.append(f"""\t\tMerge_{f} = Merge {{
280\t\t\tInputs = {{
281\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
282\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
283\t\t\t\tForeground = Input {{ SourceOp = "FG_Loader", Source = "Output", }},
284\t\t\t\tSize = Input {{ Value = 0.85, }},
285\t\t\t\tApplyMode = Input {{ Value = FuID {{ "{mode}" }}, }},
286\t\t\t\tOperator = Input {{ Value = FuID {{ "{op}" }}, }},
287\t\t\t\tGain = Input {{ Value = {gain}, }},
288\t\t\t\tSubtractiveAdditive = Input {{ Value = {sub_add}, }},
289\t\t\t\tBurnIn = Input {{ Value = {burn_in}, }},
290\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
291{extra}
292\t\t\t}},
293\t\t}},""")
294 prev = f"Merge_{f}"
295
296 nodes.append(make_saver(prev, "merge"))
297 comp_path = local_root() / "comps" / "probe_merge.comp"
298 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
299 return comp_path, "merge", [(c[0], c[1]) for c in cases]
300
301
302def build_probe_cam3d():
303 """Tests Camera3D RotOrder (all 6 orders!) + AoV + Shape3D Cylinder/Plane projection."""
304 grid = generate_grid_chart()
305 # 12 frames at 640x360 (16:9!):
306 # f0..f5: All 6 RotOrder values on Camera3D with (RX=15, RY=-25, RZ=12) looking at ImagePlane3D at Z=-3!
307 # f6: Exact 60_moon_guide_u f5500 camera angles (XZY, RX=11.152, RY=-16.972, RZ=0.0004) looking at vertical Shape3D Cylinder!
308 # f7: Same cylinder with RotOrder=YXZ
309 # f8: Same cylinder with RotOrder=XYZ
310 # f9: Exact 21_ground001 f2760 camera angles (XZY, RX=13.05, RY=34.09, RZ=0) looking at grid plane!
311 # f10: AoVType=1 (Horizontal) vs AoVType=0 (Vertical) check
312 # f11: Nested Transform3D with RotOrder=XZY (RX=20, RY=30, RZ=15)
313 orders = ["XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"]
314 cases = [
315 (0, "cam_RotOrder_XYZ"),
316 (1, "cam_RotOrder_XZY"),
317 (2, "cam_RotOrder_YXZ"),
318 (3, "cam_RotOrder_YZX"),
319 (4, "cam_RotOrder_ZXY"),
320 (5, "cam_RotOrder_ZYX"),
321 (6, "moon5500_cyl_XZY"),
322 (7, "moon5500_cyl_YXZ"),
323 (8, "moon5500_cyl_XYZ"),
324 (9, "ground2760_plane_XZY"),
325 (10, "cam_AoV_horiz_45"),
326 (11, "xf3d_RotOrder_XZY"),
327 ]
328 nodes = [make_loader("GridLoader", grid, post_mult=1)]
329 splines = []
330 # Build one Renderer3D per frame (so static RotOrder/Shape dropdowns are exact!) and switch via Merge Blend!
331 nodes.append("""\t\tBlackBG = Background {
332\t\t\tInputs = {
333\t\t\t\tWidth = Input { Value = 640, },
334\t\t\t\tHeight = Input { Value = 360, },
335\t\t\t\tTopLeftAlpha = Input { Value = 1, },
336\t\t\t},
337\t\t},""")
338 prev = "BlackBG"
339 for f, label in cases:
340 if f < 6:
341 ro = orders[f]
342 cam_rx, cam_ry, cam_rz = 15.0, -25.0, 12.0
343 cam_tz = 3.0
344 aov, aov_type = 35.0, 0
345 shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{
346\t\t\tInputs = {{
347\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
348\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -1.2, }},
349\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.7, }},
350\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
351\t\t\t}},
352\t\t}},"""
353 scene_in = f"Plane_{f}"
354 elif f in (6, 7, 8):
355 ro = {6: "XZY", 7: "YXZ", 8: "XYZ"}[f]
356 cam_rx, cam_ry, cam_rz = 11.152, -16.972, 0.0004
357 cam_tz = 0.0
358 aov, aov_type = 27.99, 0
359 shape_blk = f"""\t\tCyl_{f} = Shape3D {{
360\t\t\tInputs = {{
361\t\t\t\t["SurfaceCylinderInputs.Radius"] = Input {{ Value = 100.0, }},
362\t\t\t\t["SurfaceCylinderInputs.Height"] = Input {{ Value = 150.0, }},
363\t\t\t\t["SurfaceCylinderInputs.SubdivisionLevelBase"] = Input {{ Value = 32, }},
364\t\t\t\t["SurfaceCylinderInputs.SubdivisionLevelHeight"] = Input {{ Value = 16, }},
365\t\t\t\tShape = Input {{ Value = FuID {{ "SurfaceCylinderInputs" }}, }},
366\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 30.0, }},
367\t\t\t\t["MtlStdInputs.MaterialID"] = Input {{ Value = 1, }},
368\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
369\t\t\t}},
370\t\t}},"""
371 scene_in = f"Cyl_{f}"
372 elif f == 9:
373 ro = "XZY"
374 cam_rx, cam_ry, cam_rz = 13.05, 34.09, 0.0
375 cam_tz = 0.0
376 aov, aov_type = 35.0, 0
377 shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{
378\t\t\tInputs = {{
379\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -2.2, }},
380\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.8, }},
381\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -3.0, }},
382\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
383\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
384\t\t\t}},
385\t\t}},"""
386 scene_in = f"Plane_{f}"
387 elif f == 10:
388 ro = "XYZ"
389 cam_rx, cam_ry, cam_rz = 0.0, 0.0, 0.0
390 cam_tz = 3.0
391 aov, aov_type = 45.0, 1
392 shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{
393\t\t\tInputs = {{
394\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
395\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
396\t\t\t}},
397\t\t}},"""
398 scene_in = f"Plane_{f}"
399 else:
400 ro = "XYZ"
401 cam_rx, cam_ry, cam_rz = 0.0, 0.0, 0.0
402 cam_tz = 4.0
403 aov, aov_type = 35.0, 0
404 shape_blk = f"""\t\tPlane_{f} = ImagePlane3D {{
405\t\t\tInputs = {{
406\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
407\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
408\t\t\t}},
409\t\t}},
410\t\tXf3D_{f} = Transform3D {{
411\t\t\tInputs = {{
412\t\t\t\tSceneInput = Input {{ SourceOp = "Plane_{f}", Source = "Output", }},
413\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "XZY" }}, }},
414\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 20.0, }},
415\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 35.0, }},
416\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 15.0, }},
417\t\t\t}},
418\t\t}},"""
419 scene_in = f"Xf3D_{f}"
420
421 nodes.append(shape_blk)
422 nodes.append(f"""\t\tCam_{f} = Camera3D {{
423\t\t\tInputs = {{
424\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = {cam_tz}, }},
425\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }},
426\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = {cam_rx}, }},
427\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = {cam_ry}, }},
428\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = {cam_rz}, }},
429\t\t\t\tAoV = Input {{ Value = {aov}, }},
430\t\t\t\tAoVType = Input {{ Value = {aov_type}, }},
431\t\t\t}},
432\t\t}},
433\t\tM3D_{f} = Merge3D {{
434\t\t\tInputs = {{
435\t\t\t\tSceneInput1 = Input {{ SourceOp = "{scene_in}", Source = "Output", }},
436\t\t\t\tSceneInput2 = Input {{ SourceOp = "Cam_{f}", Source = "Output", }},
437\t\t\t}},
438\t\t}},
439\t\tRen_{f} = Renderer3D {{
440\t\t\tInputs = {{
441\t\t\t\tWidth = Input {{ Value = 640, }},
442\t\t\t\tHeight = Input {{ Value = 360, }},
443\t\t\t\tSceneInput = Input {{ SourceOp = "M3D_{f}", Source = "Output", }},
444\t\t\t}},
445\t\t}},""")
446 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
447 sname = f"Sw3D_{f}_Blend"
448 splines.append(step_spline(sname, bl))
449 nodes.append(f"""\t\tSw3D_{f} = Merge {{
450\t\t\tInputs = {{
451\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
452\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
453\t\t\t\tForeground = Input {{ SourceOp = "Ren_{f}", Source = "Output", }},
454\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
455\t\t\t}},
456\t\t}},""")
457 prev = f"Sw3D_{f}"
458
459 nodes.append(make_saver(prev, "cam3d"))
460 comp_path = local_root() / "comps" / "probe_cam3d.comp"
461 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360))
462 return comp_path, "cam3d", cases
463
464
465def build_probe_mask():
466 """Tests EllipseMask & RectangleMask aspect, SoftEdge, CornerRadius, Angle, PaintModes on 16:9 640x360."""
467 cases = [
468 (0, "ellipse_0.5x0.5_circle"),
469 (1, "ellipse_0.5x0.3_rot35"),
470 (2, "ellipse_soft0.1_fastgauss"),
471 (3, "ellipse_soft0.2_gauss"),
472 (4, "rect_0.5x0.5_16x9"),
473 (5, "rect_0.5x0.5_corner0.3"),
474 (6, "rect_0.6x0.4_rot30_soft0.05"),
475 (7, "chain_ellipse_sub_rect"),
476 (8, "chain_ellipse_mul_rect"),
477 (9, "chain_ellipse_inv_rect"),
478 ]
479 nodes = ["""\t\tWhiteBG = Background {
480\t\t\tInputs = {
481\t\t\t\tWidth = Input { Value = 640, },
482\t\t\t\tHeight = Input { Value = 360, },
483\t\t\t\tTopLeftRed = Input { Value = 1, },
484\t\t\t\tTopLeftGreen = Input { Value = 1, },
485\t\t\t\tTopLeftBlue = Input { Value = 1, },
486\t\t\t\tTopLeftAlpha = Input { Value = 1, },
487\t\t\t},
488\t\t},
489\t\tBlackBG = Background {
490\t\t\tInputs = {
491\t\t\t\tWidth = Input { Value = 640, },
492\t\t\t\tHeight = Input { Value = 360, },
493\t\t\t\tTopLeftAlpha = Input { Value = 1, },
494\t\t\t},
495\t\t},"""]
496 splines = []
497 prev = "BlackBG"
498 for f, label in cases:
499 if f == 0:
500 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, }}, }}, }},"""
501 elif f == 1:
502 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, }}, }}, }},"""
503 elif f == 2:
504 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" }}, }}, }}, }},"""
505 elif f == 3:
506 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" }}, }}, }}, }},"""
507 elif f == 4:
508 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, }}, }}, }},"""
509 elif f == 5:
510 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, }}, }}, }},"""
511 elif f == 6:
512 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, }}, }}, }},"""
513 else:
514 pm = {7: "Subtract", 8: "Multiply", 9: "Invert"}[f]
515 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, }}, }}, }},
516\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, }}, }}, }},"""
517 nodes.append(mblk)
518 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
519 sname = f"SwM_{f}_Blend"
520 splines.append(step_spline(sname, bl))
521 nodes.append(f"""\t\tSwM_{f} = Merge {{
522\t\t\tInputs = {{
523\t\t\t\tEffectMask = Input {{ SourceOp = "Mask_{f}", Source = "Mask", }},
524\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
525\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
526\t\t\t\tForeground = Input {{ SourceOp = "WhiteBG", Source = "Output", }},
527\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
528\t\t\t}},
529\t\t}},""")
530 prev = f"SwM_{f}"
531
532 nodes.append(make_saver(prev, "mask"))
533 comp_path = local_root() / "comps" / "probe_mask.comp"
534 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360))
535 return comp_path, "mask", cases
536
537
538def run_probe(comp_path: Path, prefix: str, cases: list, render_gt: bool = True):
539 end_f = max(f for f, _ in cases)
540 if render_gt:
541 if use_smb():
542 target_comp = str(comp_path)
543 else:
544 remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}"
545 subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True)
546 target_comp = remote_comp
547 print(f"=== sg render {comp_path.name} (0..{end_f}) ===")
548 subprocess.run(["sg", "render", target_comp, "--start", "0", "--end", str(end_f)], check=True)
549 if not use_smb():
550 # Download rendered GT frames in one tar stream!
551 gt_dir = local_root() / "gt"
552 files = " ".join(f"{prefix}_{f:04d}.png" for f, _ in cases)
553 subprocess.run(
554 f'ssh root@10.0.0.1 "tar -C {REMOTE_ROOT}/gt -cf - {files}" | tar -C "{gt_dir}" -xf -',
555 shell=True, check=True,
556 )
557
558 # Also write a local-paths copy of the comp for render-check if SMB isn't mounted
559 eval_comp = comp_path
560 if not use_smb():
561 txt = comp_path.read_text().replace(CONTAINER_ROOT, str(local_root()))
562 eval_comp = comp_path.with_suffix(".local.comp")
563 eval_comp.write_text(txt)
564
565 print(f"\n=== Comparing {comp_path.name} ===")
566 for f, label in cases:
567 gt_p = local_root() / "gt" / f"{prefix}_{f:04d}.png"
568 out_p = local_root() / "ours" / f"{prefix}_{f:04d}.png"
569 res = subprocess.run(
570 [str(RENDER_CHECK), str(eval_comp), str(f), "--out", str(out_p), "--ref", str(gt_p)],
571 capture_output=True, text=True, check=True,
572 )
573 out_all = res.stdout + "\n" + res.stderr
574 diff_line = [ln for ln in out_all.splitlines() if ln.startswith("Diff vs")]
575 summary = diff_line[-1].split(": ", 1)[-1] if diff_line else out_all.strip()
576 print(f" f{f:02d} {label:<30s} | {summary}")
577
578
579def build_probe_cam3d_fov():
580 """Pinpoints exact Camera3D FilmGate/ResolutionGateFit/AoV/FLength + 60_moon_guide_u f5500 cylinder + all RotOrders IN-FRAME!"""
581 grid = generate_grid_chart()
582 cases = [
583 (0, "cam_default_no_aov"),
584 (1, "exportCam_Inside_37.85"),
585 (2, "exportCam_Width_37.85"),
586 (3, "exportCam_Height_37.85"),
587 (4, "exportCam_Outside_37.85"),
588 (5, "exportCam_AoVType_Horiz"),
589 (6, "exportCam_FLength_24mm"),
590 (7, "moon5500_exact_XZY"),
591 (8, "moon5500_exact_XYZ"),
592 (9, "moon5500_exact_YXZ"),
593 (10, "inframe_cam_XZY_15_20_10"),
594 (11, "inframe_cam_YXZ_15_20_10"),
595 ]
596 nodes = [make_loader("GridLoader", grid, post_mult=1), """\t\tBlackBG = Background {
597\t\t\tInputs = {
598\t\t\t\tWidth = Input { Value = 640, },
599\t\t\t\tHeight = Input { Value = 360, },
600\t\t\t\tTopLeftAlpha = Input { Value = 1, },
601\t\t\t},
602\t\t},"""]
603 splines = []
604 prev = "BlackBG"
605 for f, label in cases:
606 if f in (0, 1, 2, 3, 4, 5, 6):
607 extra_cam = {
608 0: "",
609 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, },',
610 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" }, },',
611 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" }, },',
612 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" }, },',
613 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, },',
614 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, },',
615 }[f]
616 nodes.append(f"""\t\tObj_{f} = ImagePlane3D {{
617\t\t\tInputs = {{
618\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
619\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
620\t\t\t}},
621\t\t}},
622\t\tCam_{f} = Camera3D {{
623\t\t\tInputs = {{
624\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = 4.0, }},
625{extra_cam}
626\t\t\t}},
627\t\t}},""")
628 elif f in (7, 8, 9):
629 ro = {7: "XZY", 8: "XYZ", 9: "YXZ"}[f]
630 nodes.append(f"""\t\tObj_{f} = Shape3D {{
631\t\t\tInputs = {{
632\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 62.087, }},
633\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -44.83, }},
634\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 362.6, }},
635\t\t\t\tShape = Input {{ Value = FuID {{ "SurfaceCylinderInputs" }}, }},
636\t\t\t\t["SurfaceCylinderInputs.Radius"] = Input {{ Value = 200, }},
637\t\t\t\t["SurfaceCylinderInputs.Height"] = Input {{ Value = 200, }},
638\t\t\t\t["SurfaceCylinderInputs.StartSweep"] = Input {{ Value = 196, }},
639\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
640\t\t\t}},
641\t\t}},
642\t\tCam_{f} = Camera3D {{
643\t\t\tInputs = {{
644\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }},
645\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 11.152, }},
646\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = -16.972, }},
647\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 0.0004, }},
648\t\t\t\tAoV = Input {{ Value = 37.8493078162983, }},
649\t\t\t\tFilmBack = Input {{ Value = 1, }},
650\t\t\t\tFilmGate = Input {{ Value = FuID {{ "User" }}, }},
651\t\t\t\tApertureW = Input {{ Value = 1.4173236, }},
652\t\t\t\tApertureH = Input {{ Value = 0.9448824, }},
653\t\t\t}},
654\t\t}},""")
655 else:
656 ro = "XZY" if f == 10 else "YXZ"
657 nodes.append(f"""\t\tObj_{f} = ImagePlane3D {{
658\t\t\tInputs = {{
659\t\t\t\t["Transform3DOp.Translate.X"] = Input {{ Value = -1.2, }},
660\t\t\t\t["Transform3DOp.Translate.Y"] = Input {{ Value = 0.9, }},
661\t\t\t\t["Transform3DOp.Translate.Z"] = Input {{ Value = -3.5, }},
662\t\t\t\t["Transform3DOp.Scale.X"] = Input {{ Value = 2.0, }},
663\t\t\t\tMaterialInput = Input {{ SourceOp = "GridLoader", Source = "Output", }},
664\t\t\t}},
665\t\t}},
666\t\tCam_{f} = Camera3D {{
667\t\t\tInputs = {{
668\t\t\t\t["Transform3DOp.Rotate.RotOrder"] = Input {{ Value = FuID {{ "{ro}" }}, }},
669\t\t\t\t["Transform3DOp.Rotate.X"] = Input {{ Value = 15.0, }},
670\t\t\t\t["Transform3DOp.Rotate.Y"] = Input {{ Value = 20.0, }},
671\t\t\t\t["Transform3DOp.Rotate.Z"] = Input {{ Value = 10.0, }},
672\t\t\t\tAoV = Input {{ Value = 37.8493078162983, }},
673\t\t\t\tFilmBack = Input {{ Value = 1, }},
674\t\t\t\tFilmGate = Input {{ Value = FuID {{ "User" }}, }},
675\t\t\t\tApertureW = Input {{ Value = 1.4173236, }},
676\t\t\t\tApertureH = Input {{ Value = 0.9448824, }},
677\t\t\t}},
678\t\t}},""")
679 nodes.append(f"""\t\tM3D_{f} = Merge3D {{
680\t\t\tInputs = {{
681\t\t\t\tSceneInput1 = Input {{ SourceOp = "Obj_{f}", Source = "Output", }},
682\t\t\t\tSceneInput2 = Input {{ SourceOp = "Cam_{f}", Source = "Output", }},
683\t\t\t}},
684\t\t}},
685\t\tRen_{f} = Renderer3D {{
686\t\t\tInputs = {{
687\t\t\t\tWidth = Input {{ Value = 640, }},
688\t\t\t\tHeight = Input {{ Value = 360, }},
689\t\t\t\tSceneInput = Input {{ SourceOp = "M3D_{f}", Source = "Output", }},
690\t\t\t}},
691\t\t}},""")
692 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
693 sname = f"SwF_{f}_Blend"
694 splines.append(step_spline(sname, bl))
695 nodes.append(f"""\t\tSwF_{f} = Merge {{
696\t\t\tInputs = {{
697\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
698\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
699\t\t\t\tForeground = Input {{ SourceOp = "Ren_{f}", Source = "Output", }},
700\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
701\t\t\t}},
702\t\t}},""")
703 prev = f"SwF_{f}"
704 nodes.append(make_saver(prev, "cam3d_fov"))
705 comp_path = local_root() / "comps" / "probe_cam3d_fov.comp"
706 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360))
707 return comp_path, "cam3d_fov", cases
708
709
710def build_probe_transform():
711 """Tests Transform FilterMethod (Nearest/Box/Linear/Catmull), Edges (Canvas/Wrap/Dup/Mirror), Pivot+Angle+Aspect+Flip."""
712 grid = generate_grid_chart()
713 cases = [
714 (0, "xf_nearest_zoom4x", 'Size = Input { Value = 4.0, }, FilterMethod = Input { Value = 0, },'),
715 (1, "xf_linear_zoom4x", 'Size = Input { Value = 4.0, }, FilterMethod = Input { Value = 2, },'),
716 (2, "xf_edges_canvas", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 0, },'),
717 (3, "xf_edges_wrap", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 1, },'),
718 (4, "xf_edges_duplicate", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 2, },'),
719 (5, "xf_edges_mirror", 'Center = Input { Value = { 0.8, 0.7 }, }, Size = Input { Value = 0.6, }, Edges = Input { Value = 3, },'),
720 (6, "xf_pivot_angle37", 'Pivot = Input { Value = { 0.25, 0.75 }, }, Angle = Input { Value = 37.0, }, Size = Input { Value = 0.85, },'),
721 (7, "xf_nonuniform_xy", 'UseSizeAndAspect = Input { Value = 0, }, XSize = Input { Value = 1.35, }, YSize = Input { Value = 0.65, }, Angle = Input { Value = 20.0, },'),
722 (8, "xf_aspect_1.6", 'Size = Input { Value = 0.8, }, Aspect = Input { Value = 1.6, }, Angle = Input { Value = -25.0, },'),
723 (9, "xf_flip_hv", 'FlipHoriz = Input { Value = 1, }, FlipVert = Input { Value = 1, }, Size = Input { Value = 0.8, },'),
724 (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, },'),
725 (11, "xf_nearest_rot15_zoom3", 'Size = Input { Value = 3.0, }, Angle = Input { Value = 15.0, }, FilterMethod = Input { Value = 0, },'),
726 ]
727 nodes = [make_loader("GridLoader", grid, post_mult=1)]
728 splines = []
729 prev = "GridLoader"
730 for f, label, extra in cases:
731 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
732 sname = f"Xf_{f}_Blend"
733 splines.append(step_spline(sname, bl))
734 nodes.append(f"""\t\tXf_{f} = Transform {{
735\t\t\tInputs = {{
736\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
737\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }},
738\t\t\t\t{extra}
739\t\t\t}},
740\t\t}},""")
741 prev = f"Xf_{f}"
742 nodes.append(make_saver(prev, "xf"))
743 comp_path = local_root() / "comps" / "probe_xf.comp"
744 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
745 return comp_path, "xf", [(c[0], c[1]) for c in cases]
746
747
748def build_probe_blur():
749 """Tests Blur (FastGauss/Gauss/Box + ClippingMode), DirectionalBlur (Linear/Centered/Radial/Zoom+Glow), ErodeDilate (+/-/Box/Circle)."""
750 grid = generate_grid_chart()
751 cases = [
752 (0, "blur_fgauss_5", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 5.0, },'),
753 (1, "blur_fgauss_20", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 20.0, },'),
754 (2, "blur_gauss_10", "Blur", 'Filter = Input { Value = FuID { "Gaussian" }, }, XBlurSize = Input { Value = 10.0, },'),
755 (3, "blur_box_10", "Blur", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 10.0, },'),
756 (4, "blur_clip_none_15", "Blur", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 15.0, }, ClippingMode = Input { Value = FuID { "None" }, },'),
757 (5, "dirblur_linear_0.08", "DirectionalBlur", 'Type = Input { Value = 0, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 30.0, },'),
758 (6, "dirblur_radial_0.08", "DirectionalBlur", 'Type = Input { Value = 1, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 30.0, },'),
759 (7, "dirblur_centered_0.08", "DirectionalBlur", 'Type = Input { Value = 2, }, Length = Input { Value = 0.08, }, Center = Input { Value = { 0.4, 0.6 }, },'),
760 (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 }, },'),
761 (9, "erode_box_+0.02", "ErodeDilate", 'XAmount = Input { Value = 0.02, },'),
762 (10, "erode_box_-0.02", "ErodeDilate", 'XAmount = Input { Value = -0.02, },'),
763 (11, "erode_circle_+0.02", "ErodeDilate", 'Filter = Input { Value = 3, }, XAmount = Input { Value = 0.02, },'),
764 ]
765 nodes = [make_loader("GridLoader", grid, post_mult=1)]
766 splines = []
767 prev = "GridLoader"
768 for f, label, kind, extra in cases:
769 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
770 sname = f"Bl_{f}_Blend"
771 splines.append(step_spline(sname, bl))
772 nodes.append(f"""\t\tOp_{f} = {kind} {{
773\t\t\tInputs = {{
774\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
775\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }},
776\t\t\t\t{extra}
777\t\t\t}},
778\t\t}},""")
779 prev = f"Op_{f}"
780 nodes.append(make_saver(prev, "blur"))
781 comp_path = local_root() / "comps" / "probe_blur.comp"
782 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
783 return comp_path, "blur", [(c[0], c[1]) for c in cases]
784
785
786def build_probe_color_ops():
787 """Tests BrightnessContrast, ColorGain, and ChannelBoolean edge cases."""
788 chart = generate_color_chart()
789 grid = generate_grid_chart()
790 cases = [
791 (0, "bc_gain1.4_lift0.1", "BrightnessContrast", 'Gain = Input { Value = 1.4, }, Lift = Input { Value = 0.1, },'),
792 (1, "bc_gamma0.6_con0.4", "BrightnessContrast", 'Gamma = Input { Value = 0.6, }, Contrast = Input { Value = 0.4, }, Brightness = Input { Value = 0.05, },'),
793 (2, "bc_low0.2_high0.8", "BrightnessContrast", 'Low = Input { Value = 0.2, }, High = Input { Value = 0.8, },'),
794 (3, "bc_sat0.3_prediv1", "BrightnessContrast", 'Saturation = Input { Value = 0.3, }, Brightness = Input { Value = 0.15, }, PreDividePostMultiply = Input { Value = 1, },'),
795 (4, "cg_midhigh_hue0.58", "ColorGain", 'MidHue = Input { Value = 0.583, }, HighHue = Input { Value = 0.583, },'),
796 (5, "cg_dark0.2_mid0.6_hi0.9", "ColorGain", 'DarkHue = Input { Value = 0.2, }, MidHue = Input { Value = 0.6, }, HighHue = Input { Value = 0.9, },'),
797 (6, "cg_gain_lift_gamma_rgb", "ColorGain", 'GainRed = Input { Value = 1.3, }, LiftGreen = Input { Value = 0.15, }, GammaBlue = Input { Value = 0.7, },'),
798 (7, "cg_sat_bands", "ColorGain", 'SaturationLow = Input { Value = 0.3, }, SaturationMid = Input { Value = 1.6, }, SaturationHigh = Input { Value = 0.5, },'),
799 (8, "cb_copy_swizzle_gbr", "ChannelBoolean", 'Operation = Input { Value = 0, }, ToRed = Input { Value = 1, }, ToGreen = Input { Value = 2, }, ToBlue = Input { Value = 0, },'),
800 (9, "cb_add_fg", "ChannelBoolean", 'Operation = Input { Value = 1, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'),
801 (10, "cb_mul_fg", "ChannelBoolean", 'Operation = Input { Value = 6, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'),
802 (11, "cb_diff_fg", "ChannelBoolean", 'Operation = Input { Value = 8, }, Foreground = Input { SourceOp = "GridLoader", Source = "Output", },'),
803 ]
804 nodes = [
805 make_loader("ChartLoader", chart, post_mult=1),
806 make_loader("GridLoader", grid, post_mult=1),
807 ]
808 splines = []
809 prev = "ChartLoader"
810 for f, label, kind, extra in cases:
811 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
812 sname = f"Co_{f}_Blend"
813 splines.append(step_spline(sname, bl))
814 in_port = "Background" if kind == "ChannelBoolean" else "Input"
815 nodes.append(f"""\t\tCo_{f} = {kind} {{
816\t\t\tInputs = {{
817\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
818\t\t\t\t{in_port} = Input {{ SourceOp = "{prev}", Source = "Output", }},
819\t\t\t\t{extra}
820\t\t\t}},
821\t\t}},""")
822 prev = f"Co_{f}"
823 nodes.append(make_saver(prev, "color_ops"))
824 comp_path = local_root() / "comps" / "probe_color_ops.comp"
825 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
826 return comp_path, "color_ops", [(c[0], c[1]) for c in cases]
827
828
829def build_probe_displace():
830 """Tests Displace XY (sign, offsets, channels) + Radial/Bump (strength, spread, light)."""
831 grid = generate_grid_chart()
832 chart = generate_color_chart()
833 cases = [
834 (0, "disp_xy_default_off", 'Type = Input { Value = 1, }, XRefraction = Input { Value = 0.08, }, YRefraction = Input { Value = 0.04, },'),
835 (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, },'),
836 (2, "disp_xy_ch_g_only", 'Type = Input { Value = 1, }, XChannel = Input { Value = 1, }, XOffset = Input { Value = -0.5, }, XRefraction = Input { Value = 0.12, },'),
837 (3, "disp_xy_neg_refract", 'Type = Input { Value = 1, }, XChannel = Input { Value = 0, }, XOffset = Input { Value = -0.5, }, XRefraction = Input { Value = -0.10, },'),
838 (4, "disp_radial_0.15", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, },'),
839 (5, "disp_radial_spread0.4", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, }, Spread = Input { Value = 0.4, },'),
840 (6, "disp_radial_light0.5", 'Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.15, }, LightPower = Input { Value = 0.5, },'),
841 ]
842 nodes = [
843 make_loader("GridLoader", grid, post_mult=1),
844 make_loader("ChartLoader", chart, post_mult=1),
845 ]
846 splines = []
847 prev = "GridLoader"
848 for f, label, extra in cases:
849 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
850 sname = f"Dp_{f}_Blend"
851 splines.append(step_spline(sname, bl))
852 nodes.append(f"""\t\tDp_{f} = Displace {{
853\t\t\tInputs = {{
854\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
855\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }},
856\t\t\t\tForeground = Input {{ SourceOp = "ChartLoader", Source = "Output", }},
857\t\t\t\t{extra}
858\t\t\t}},
859\t\t}},""")
860 prev = f"Dp_{f}"
861 nodes.append(make_saver(prev, "displace"))
862 comp_path = local_root() / "comps" / "probe_displace.comp"
863 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
864 return comp_path, "displace", [(c[0], c[1]) for c in cases]
865
866
867def build_probe_glow():
868 """Tests SoftGlow and Glow edge cases (Gain, XGlowSize=0, Threshold, GlowOnly, GlowSize)."""
869 grid = generate_grid_chart()
870 cases = [
871 (0, "sg_default", "SoftGlow", ''),
872 (1, "sg_size0_gain1.38", "SoftGlow", 'XGlowSize = Input { Value = 0.0, }, Gain = Input { Value = 1.378, },'),
873 (2, "sg_size21_gain1.06", "SoftGlow", 'XGlowSize = Input { Value = 21.3, }, Gain = Input { Value = 1.063, },'),
874 (3, "sg_size6_gain2.0", "SoftGlow", 'XGlowSize = Input { Value = 6.3, }, Gain = Input { Value = 2.0, },'),
875 (4, "sg_thresh0.6_size12", "SoftGlow", 'Threshold = Input { Value = 0.6, }, XGlowSize = Input { Value = 12.0, }, Gain = Input { Value = 1.5, },'),
876 (5, "sg_glow_only", "SoftGlow", 'GlowOnly = Input { Value = 1, }, XGlowSize = Input { Value = 10.0, }, Gain = Input { Value = 1.2, },'),
877 (6, "glow_default", "Glow", ''),
878 (7, "glow_0.58_size12", "Glow", 'Glow = Input { Value = 0.583, }, GlowSize = Input { Value = 12.0, },'),
879 ]
880 nodes = [make_loader("GridLoader", grid, post_mult=1)]
881 splines = []
882 prev = "GridLoader"
883 for f, label, kind, extra in cases:
884 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
885 sname = f"Gl_{f}_Blend"
886 splines.append(step_spline(sname, bl))
887 nodes.append(f"""\t\tGl_{f} = {kind} {{
888\t\t\tInputs = {{
889\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
890\t\t\t\tInput = Input {{ SourceOp = "{prev}", Source = "Output", }},
891\t\t\t\t{extra}
892\t\t\t}},
893\t\t}},""")
894 prev = f"Gl_{f}"
895 nodes.append(make_saver(prev, "glow"))
896 comp_path = local_root() / "comps" / "probe_glow.comp"
897 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
898 return comp_path, "glow", [(c[0], c[1]) for c in cases]
899
900
901def build_probe_text():
902 """Tests TextPlus size, alignment, tracking, and outline shading (Liberation Sans)."""
903 cases = [
904 (0, "txt_center_0.12", 'StyledText = Input { Value = "Hello 123", }, Size = Input { Value = 0.12, },'),
905 (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, },'),
906 (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, },'),
907 (3, "txt_tracking_1.3", 'StyledText = Input { Value = "WIDE", }, Size = Input { Value = 0.12, }, CharacterSpacing = Input { Value = 1.3, },'),
908 (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, },'),
909 ]
910 nodes = ["""\t\tBlackBG = Background {
911\t\t\tInputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, },
912\t\t},"""]
913 splines = []
914 prev = "BlackBG"
915 for f, label, extra in cases:
916 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
917 sname = f"Tx_{f}_Blend"
918 splines.append(step_spline(sname, bl))
919 nodes.append(f"""\t\tTxt_{f} = TextPlus {{
920\t\t\tInputs = {{
921\t\t\t\tWidth = Input {{ Value = 512, }},
922\t\t\t\tHeight = Input {{ Value = 512, }},
923\t\t\t\tFont = Input {{ Value = "Liberation Sans", }},
924\t\t\t\tStyle = Input {{ Value = "Regular", }},
925\t\t\t\t{extra}
926\t\t\t}},
927\t\t}},
928\t\tM_{f} = Merge {{
929\t\t\tInputs = {{
930\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
931\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
932\t\t\t\tForeground = Input {{ SourceOp = "Txt_{f}", Source = "Output", }},
933\t\t\t}},
934\t\t}},""")
935 prev = f"M_{f}"
936 nodes.append(make_saver(prev, "text"))
937 comp_path = local_root() / "comps" / "probe_text.comp"
938 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
939 return comp_path, "text", [(c[0], c[1]) for c in cases]
940
941
942def build_probe_noise_text():
943 """Dissects Fusion 21.1 FastNoise exact lattice/seed/fBm AND TextPlus red-outline + ColorGain outer edge."""
944 cases = [
945 (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, },'),
946 (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, },'),
947 (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, },'),
948 (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, },'),
949 (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, },'),
950 (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, },'),
951 (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, },'),
952 (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, },'),
953 (8, "txt_red_outline", "TextCG", 'cg=0'),
954 (9, "txt_red_cg_blue", "TextCG", 'cg=1'),
955 (10, "txt_red_cg_prediv","TextCG", 'cg=2'),
956 ]
957 nodes = ["""\t\tDarkBG = Background {
958\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, }, },
959\t\t},
960\t\tTxtW = TextPlus {
961\t\t\tInputs = {
962\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, },
963\t\t\t\tFont = Input { Value = "Liberation Sans", }, Style = Input { Value = "Bold", },
964\t\t\t\tStyledText = Input { Value = "W", }, Size = Input { Value = 0.55, },
965\t\t\t\tRed1 = Input { Value = 0, }, Green1 = Input { Value = 0, }, Blue1 = Input { Value = 0, },
966\t\t\t\tEnabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 1, },
967\t\t\t\tThickness2 = Input { Value = 0.05, }, Round2 = Input { Value = 1, },
968\t\t\t\tRed2 = Input { Value = 1, }, Green2 = Input { Value = 0, }, Blue2 = Input { Value = 0, },
969\t\t\t},
970\t\t},
971\t\tCG_Blue = ColorGain {
972\t\t\tInputs = { MidHue = Input { Value = 0.62, }, HighHue = Input { Value = 0.62, }, Input = Input { SourceOp = "TxtW", Source = "Output", }, },
973\t\t},
974\t\tCG_Blue_PD = ColorGain {
975\t\t\tInputs = { MidHue = Input { Value = 0.62, }, HighHue = Input { Value = 0.62, }, PreDividePostMultiply = Input { Value = 1, }, Input = Input { SourceOp = "TxtW", Source = "Output", }, },
976\t\t},"""]
977 splines = []
978 prev = "DarkBG"
979 for f, label, kind, extra in cases:
980 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
981 sname = f"Nt_{f}_Blend"
982 splines.append(step_spline(sname, bl))
983 if kind == "FastNoise":
984 nodes.append(f"""\t\tFn_{f} = FastNoise {{
985\t\t\tInputs = {{ {extra} }},
986\t\t}},
987\t\tM_{f} = Merge {{
988\t\t\tInputs = {{
989\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
990\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
991\t\t\t\tForeground = Input {{ SourceOp = "Fn_{f}", Source = "Output", }},
992\t\t\t}},
993\t\t}},""")
994 else:
995 src_op = {"cg=0": "TxtW", "cg=1": "CG_Blue", "cg=2": "CG_Blue_PD"}[extra]
996 nodes.append(f"""\t\tM_{f} = Merge {{
997\t\t\tInputs = {{
998\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
999\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
1000\t\t\t\tForeground = Input {{ SourceOp = "{src_op}", Source = "Output", }},
1001\t\t\t}},
1002\t\t}},""")
1003 prev = f"M_{f}"
1004 nodes.append(make_saver(prev, "noise_text"))
1005 comp_path = local_root() / "comps" / "probe_noise_text.comp"
1006 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
1007 return comp_path, "noise_text", [(c[0], c[1]) for c in cases]
1008
1009
1010def main():
1011 ensure_dirs()
1012 which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"]
1013 skip_gt = "--no-gt" in sys.argv
1014 builders = {
1015 "merge": build_probe_merge,
1016 "cam3d": build_probe_cam3d,
1017 "cam3d_fov": build_probe_cam3d_fov,
1018 "mask": build_probe_mask,
1019 "xf": build_probe_transform,
1020 "blur": build_probe_blur,
1021 "color_ops": build_probe_color_ops,
1022 "displace": build_probe_displace,
1023 "glow": build_probe_glow,
1024 "text": build_probe_text,
1025 "noise_text": build_probe_noise_text,
1026 }
1027 for w in which:
1028 comp_path, prefix, cases = builders[w]()
1029 run_probe(comp_path, prefix, cases, render_gt=not skip_gt)
1030
1031
1032if __name__ == "__main__":
1033 main()