Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79f21bf6f3 | ||
|
|
d75a21deef | ||
|
|
05955c08b4 | ||
|
|
549e9d8251 | ||
|
|
7a9213611e | ||
|
|
91ee7bf1b3 | ||
|
|
6c799f3c3b | ||
|
|
3ac283eee4 | ||
|
|
900b921dbf | ||
|
|
eb2b734059 | ||
|
|
02c412b835 | ||
|
|
5f4b3aee86 | ||
|
|
f2d481ce20 | ||
|
|
c5bb5f4397 | ||
|
|
1b4ea03fd2 | ||
|
|
acb77a8c85 | ||
|
|
bb4972a886 | ||
|
|
66c08de572 | ||
|
|
286a521598 | ||
|
|
f096470dec | ||
|
|
4ffd605296 | ||
|
|
1765dc53df | ||
|
|
9aabb5da4f | ||
|
|
6d5bcaa058 | ||
|
|
32792ff172 | ||
|
|
2647357a0b | ||
|
|
f9d6457f6a | ||
|
|
430c968e52 | ||
|
|
4574fb62bc | ||
|
|
120ecb9892 | ||
|
|
5281171282 | ||
|
|
aa7a8714bd | ||
|
|
287c35dae7 | ||
|
|
8a256a67ef | ||
|
|
6ffb2823c7 | ||
|
|
6e47aa3f00 | ||
|
|
ec4c3c782f | ||
|
|
e5e36aa3eb | ||
|
|
08e20e5dba | ||
|
|
07047c7ec9 | ||
|
|
3d2c4a67a1 | ||
|
|
9f985ff374 | ||
|
|
197ca451c0 | ||
|
|
c4a162b2dc | ||
|
|
c720a1d30b | ||
|
|
90621e2b04 | ||
|
|
7197d2fb7e | ||
|
|
3aac824976 | ||
|
|
12e21b5938 | ||
|
|
fa5ce34012 | ||
|
|
a985dfb36b | ||
|
|
5249ff8bad | ||
|
|
a43cf2002a | ||
|
|
767f1f6265 | ||
|
|
e248c172e8 | ||
|
|
5bc3aea264 | ||
|
|
6be321153c | ||
|
|
ec86cdb584 | ||
|
|
37b681ac12 | ||
|
|
bd74443238 | ||
|
|
0cfb563764 | ||
|
|
f46c825225 | ||
|
|
1d8fe7a8a0 | ||
|
|
f0fa92ceef | ||
|
|
61d2b48911 | ||
|
|
1ca068c5b1 | ||
|
|
3e6d07af0e | ||
|
|
dc3131b339 | ||
|
|
0e4f3bfb8f | ||
|
|
9396e39ae5 | ||
|
|
155368e613 | ||
|
|
bb0273dd91 | ||
|
|
b3e8a7e431 | ||
|
|
ee682bbfd9 | ||
|
|
092834b703 | ||
|
|
4f57d5d73d | ||
|
|
fc54b5debc | ||
|
|
ac9d4eb72f | ||
|
|
b438cdd702 | ||
|
|
a55af3b235 | ||
|
|
e4532bff1e | ||
|
|
ce67e02d88 | ||
|
|
15d2030d73 | ||
|
|
c5d2a54507 | ||
|
|
d5496e50bc | ||
|
|
84f7f80617 | ||
|
|
a55155bd7d | ||
|
|
1a74961d26 | ||
|
|
66be8857b5 | ||
|
|
84ef901714 | ||
|
|
e02c60c08a | ||
|
|
5c0ac48f31 | ||
|
|
7da7358504 | ||
|
|
39ef24af3a | ||
|
|
2a1a98006c | ||
|
|
cbe710220a | ||
|
|
0e424b45f1 | ||
|
|
61a6d95e51 | ||
|
|
c3644e59d4 | ||
|
|
3484f91c3f | ||
|
|
ad83f9ae1a | ||
|
|
7293148c3c | ||
|
|
7955ae81ce | ||
|
|
b77018ea8f | ||
|
|
d9f300f940 | ||
|
|
96a29bb2f0 | ||
|
|
a62d03130a | ||
|
|
1b3c88dcc5 | ||
|
|
396231a9f8 | ||
|
|
936b9842d0 | ||
|
|
7f584f9ba8 | ||
|
|
85bc2d220d | ||
|
|
69f416e3b0 | ||
|
|
c069a72928 | ||
|
|
59bf40a5da | ||
|
|
dcd46ca57d | ||
|
|
c7692aa697 | ||
|
|
b743410e72 | ||
|
|
c46f80faa2 | ||
|
|
3095217ce8 | ||
|
|
8c986a1bec | ||
|
|
e655159382 | ||
|
|
40a8e50de9 | ||
|
|
0aa2ea5e12 | ||
|
|
004984d853 | ||
|
|
de0f573620 | ||
|
|
26b2451836 | ||
|
|
a96c80788a | ||
|
|
3aaefab270 | ||
|
|
544d46a218 | ||
|
|
e643457fa3 | ||
|
|
3db5aebb33 | ||
|
|
af1133a1f3 | ||
|
|
ecf485e375 | ||
|
|
dbaf559b58 | ||
|
|
41b04bf414 | ||
|
|
b9a9a0a414 | ||
|
|
73ea427015 | ||
|
|
bf911d18bc | ||
|
|
bcfb25ca93 | ||
|
|
765915e126 | ||
|
|
f816cd5e38 | ||
|
|
98796a29b8 | ||
|
|
63e5068f7c | ||
|
|
863a6aff6c | ||
|
|
9e8112499c | ||
|
|
56f6612f78 | ||
|
|
5530560fb8 | ||
|
|
a26f1a3749 | ||
|
|
64945f2ef9 | ||
|
|
5e97eaddba | ||
|
|
8eece41c7e | ||
|
|
b2cf845624 | ||
|
|
be99fecfdc | ||
|
|
bfb7507565 | ||
|
|
e1c9c33fb1 | ||
|
|
f72b8993ef | ||
|
|
41f7736959 | ||
|
|
a69c7d7cd2 | ||
|
|
e2d50ec926 | ||
|
|
5d9bab268d | ||
|
|
d85601f8eb | ||
|
|
94b4d0ca34 | ||
|
|
28e9e5229e | ||
|
|
7643f803e0 | ||
|
|
b4e7f8615f | ||
|
|
4a08f8fdf4 | ||
|
|
4101cef8b4 | ||
|
|
35c5ff5fa1 | ||
|
|
6259bf0b57 | ||
|
|
cf22417c1a | ||
|
|
130bcb2385 | ||
|
|
4f9a04fcf5 | ||
|
|
a3e2271e94 | ||
|
|
463a4a5221 | ||
|
|
e6dd37e62c | ||
|
|
b845562f4c | ||
|
|
a179714108 | ||
|
|
5789c1c7d8 | ||
|
|
00afd27dca | ||
|
|
e91b19f2a5 | ||
|
|
19e4fc7c60 | ||
|
|
07fe9cb1dc | ||
|
|
8e21e5dbc1 | ||
|
|
91e46af99c | ||
|
|
51371939ad | ||
|
|
97514ef198 | ||
|
|
af28bc4ddb | ||
|
|
81521d9b06 | ||
|
|
f11792827e | ||
|
|
00799d8c77 | ||
|
|
f7b366197d | ||
|
|
bf53ae6094 | ||
|
|
c6a87a2798 | ||
|
|
cf912d5049 | ||
|
|
d444eceb90 | ||
|
|
a644bb07c9 | ||
|
|
a27f9f54b9 | ||
|
|
3840d227ff | ||
|
|
8703f52d12 | ||
|
|
8e5605d0e6 | ||
|
|
b00c7f582a | ||
|
|
5bcfc0a4a5 | ||
|
|
5b2b99464d | ||
|
|
9af5560c1f | ||
|
|
66812324c9 | ||
|
|
def8b6f3b4 | ||
|
|
223b21b06a | ||
|
|
520ea11059 | ||
|
|
c4fdbd6064 | ||
|
|
ac442f8c61 | ||
|
|
923ec0fc4a | ||
|
|
c8aaac824d | ||
|
|
0553180092 | ||
|
|
376f5757fc | ||
|
|
55ee9c9e76 | ||
|
|
c3fe609ee4 | ||
|
|
4e7eafa82d | ||
|
|
bb540559d8 | ||
|
|
e23b926efc | ||
|
|
2cb5d199ea | ||
|
|
85a269b609 | ||
|
|
ecc131fc86 | ||
|
|
42c7a7141e | ||
|
|
2ef3d977a6 | ||
|
|
4d105f02d4 | ||
|
|
0852511c3f | ||
|
|
9375cc3406 | ||
|
|
925760c9c8 | ||
|
|
4acea86d4f | ||
|
|
7304f4c672 | ||
|
|
0eda174706 | ||
|
|
498dbc0c71 | ||
|
|
dfff9ba2dc | ||
|
|
eec84a8095 | ||
|
|
4ee7e03584 | ||
|
|
6f5bd0c272 | ||
|
|
767120f6ca | ||
|
|
92e3939ca7 | ||
|
|
a50e49df73 | ||
|
|
aa6c47395c | ||
|
|
2669e1a1de | ||
|
|
f9808423d6 | ||
|
|
3e900db974 | ||
|
|
f96663b1f5 | ||
|
|
de26297c36 | ||
|
|
41071f0bbf | ||
|
|
55ef2d05db | ||
|
|
9d63ec19fc | ||
|
|
a96c85b0e5 | ||
|
|
db6e3c5cc6 | ||
|
|
d33e82a571 | ||
|
|
742472440e | ||
|
|
35124cc924 | ||
|
|
f5c6487cf1 | ||
|
|
0c343212ae | ||
|
|
66a6b99d12 | ||
|
|
341076359a | ||
|
|
cbc1ce26e2 | ||
|
|
c99012a77a | ||
|
|
fcf56415dc | ||
|
|
63cfcfbb90 | ||
|
|
b0ea0e787b | ||
|
|
fbb74339da | ||
|
|
dc1b048f8a | ||
|
|
424dcab40b | ||
|
|
3174e68d0e | ||
|
|
9e66e0d2ec | ||
|
|
e9c8d703a7 | ||
|
|
e2188c436c | ||
|
|
47dbd8dbd5 | ||
|
|
d9b8f65d7c | ||
|
|
f6497177b4 | ||
|
|
15385121b1 | ||
|
|
649ba2e8cf | ||
|
|
ea5e629d1a | ||
|
|
bc6a145203 | ||
|
|
d8ff1189dc | ||
|
|
9c5c187292 | ||
|
|
eec81bbe0e | ||
|
|
a8de199aca | ||
|
|
3466538d0e | ||
|
|
560767dfe7 | ||
|
|
0c695cff77 | ||
|
|
4fc7b52351 | ||
|
|
c21a93e45e | ||
|
|
953fbbc730 |
@@ -67,6 +67,8 @@ Screenshots of EffectCraft itself, rendered headlessly, showing only procedurall
|
||||
Drop In Lines): `crates/engine/presets/text_animators.json` (sidecar `.attribution`).
|
||||
- Transition animation presets (23: wipes, clock and fan reveals, blinds, dissolves, card flips, CC wipes, fades):
|
||||
`crates/engine/presets/transitions.json` (sidecar `.attribution`).
|
||||
- Backgrounds animation presets (23: drifting gradients, fog, cloud and smoke, plasma and magma, cells and crystals, scrolling grids
|
||||
and checks, pulse rings, bokeh, light sweep): `crates/engine/presets/backgrounds.json` (sidecar `.attribution`).
|
||||
- Sample scripts (File ▸ Scripts) and ScriptUI panel: `crates/engine/scripts/Rename Layers.jsx`,
|
||||
`crates/engine/scripts/Sort Layers by In Point.jsx`, `crates/engine/scripts/Create Null at Selected Layers.jsx`,
|
||||
`crates/engine/scripts/Render Queue Batch.jsx`, `crates/engine/scripts/ScriptUI Panels/Layer Tools.jsx`
|
||||
|
||||
Generated
+45
-36
@@ -1143,7 +1143,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"cpal",
|
||||
"effectcraft-engine",
|
||||
@@ -1168,7 +1168,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-automation"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-engine",
|
||||
"effectcraft-host",
|
||||
@@ -1180,14 +1180,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-av1enc"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"filmcraft-av1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-cli"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"cpu-time",
|
||||
"effectcraft-automation",
|
||||
@@ -1203,7 +1203,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-color"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -1211,7 +1211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-effects"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-geom",
|
||||
@@ -1228,7 +1228,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-engine"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-effects",
|
||||
@@ -1243,6 +1243,7 @@ dependencies = [
|
||||
"effectcraft-psd",
|
||||
"effectcraft-raster",
|
||||
"effectcraft-render",
|
||||
"effectcraft-rustmotion-common",
|
||||
"effectcraft-segment",
|
||||
"effectcraft-svg",
|
||||
"effectcraft-text",
|
||||
@@ -1261,7 +1262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-export"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-av1enc",
|
||||
"effectcraft-color",
|
||||
@@ -1273,6 +1274,7 @@ dependencies = [
|
||||
"effectcraft-project",
|
||||
"effectcraft-raster",
|
||||
"effectcraft-render",
|
||||
"effectcraft-rustmotion-common",
|
||||
"effectcraft-time",
|
||||
"effectcraft-vp9enc",
|
||||
"filmcraft-aac",
|
||||
@@ -1291,7 +1293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-expr"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"boa_engine",
|
||||
"effectcraft-color",
|
||||
@@ -1308,7 +1310,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-geom"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -1316,7 +1318,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-gpu"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"effectcraft-color",
|
||||
@@ -1338,14 +1340,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-hevcenc"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"filmcraft-hevc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-host"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-engine",
|
||||
"effectcraft-export",
|
||||
@@ -1363,13 +1365,14 @@ dependencies = [
|
||||
"exr",
|
||||
"gif",
|
||||
"image",
|
||||
"log",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-interchange"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-keyframe",
|
||||
@@ -1388,7 +1391,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-keyframe"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-geom",
|
||||
@@ -1400,7 +1403,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-lottie"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-effects",
|
||||
@@ -1417,7 +1420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-media"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-model",
|
||||
"effectcraft-pdf",
|
||||
@@ -1444,7 +1447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-model"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-geom",
|
||||
"image",
|
||||
@@ -1456,14 +1459,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-opusenc"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"filmcraft-opus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-path"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-geom",
|
||||
"effectcraft-keyframe",
|
||||
@@ -1475,7 +1478,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-pdf"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-raster",
|
||||
"effectcraft-svg",
|
||||
@@ -1489,7 +1492,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-plugin"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-effects",
|
||||
"effectcraft-keyframe",
|
||||
@@ -1501,7 +1504,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-project"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-geom",
|
||||
@@ -1514,14 +1517,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-psd"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-raster"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-geom",
|
||||
@@ -1530,7 +1533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-render"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-effects",
|
||||
@@ -1540,6 +1543,7 @@ dependencies = [
|
||||
"effectcraft-path",
|
||||
"effectcraft-project",
|
||||
"effectcraft-raster",
|
||||
"effectcraft-rustmotion-common",
|
||||
"effectcraft-text",
|
||||
"effectcraft-time",
|
||||
"kurbo",
|
||||
@@ -1550,9 +1554,13 @@ dependencies = [
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-rustmotion-common"
|
||||
version = "0.10.0"
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-script"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"boa_engine",
|
||||
"effectcraft-engine",
|
||||
@@ -1569,7 +1577,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-segment"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"miniz_oxide 0.8.9",
|
||||
"ndarray",
|
||||
@@ -1578,7 +1586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-svg"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-geom",
|
||||
"effectcraft-path",
|
||||
@@ -1590,7 +1598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-text"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-keyframe",
|
||||
"harfrust",
|
||||
@@ -1602,7 +1610,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-time"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -1610,7 +1618,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-track"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-raster",
|
||||
"effectcraft-segment",
|
||||
@@ -1622,7 +1630,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-ui-egui"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"effectcraft-color",
|
||||
@@ -1634,6 +1642,7 @@ dependencies = [
|
||||
"effectcraft-path",
|
||||
"effectcraft-project",
|
||||
"effectcraft-render",
|
||||
"effectcraft-rustmotion-common",
|
||||
"effectcraft-text",
|
||||
"effectcraft-time",
|
||||
"eframe",
|
||||
@@ -1654,11 +1663,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-vp9enc"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-web"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"effectcraft-engine",
|
||||
"effectcraft-export",
|
||||
@@ -6468,7 +6477,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+2
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.2"
|
||||
version = "0.10.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -12,6 +12,7 @@ repository = "https://github.com/storytold/effectcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# internal
|
||||
effectcraft-rustmotion-common = { path = "crates/rustmotion-common" }
|
||||
effectcraft-time = { path = "crates/time" }
|
||||
effectcraft-geom = { path = "crates/geom" }
|
||||
effectcraft-color = { path = "crates/color" }
|
||||
|
||||
+14
-10
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (full re-measure against After Effects 2026 26.5; standard progress-docs layout) · **Target:** Adobe After Effects 2026 (26.5.0.89)
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (open-issue count, crash list and localization share re-audited against `upstream/main` 470ea7a3) · **Target:** Adobe After Effects 2026 (26.5.0.89)
|
||||
|
||||
EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written
|
||||
from scratch in Rust. This page is the one-page summary; the evidence is in
|
||||
@@ -37,7 +37,7 @@ Hours are one Opus 5.5 agent working sequentially, calibrated on this repository
|
||||
(set up, animate, text and shapes, composite, preview, save and deliver) work end to end on macOS
|
||||
and the work saves and reopens, and ready for real work (≈ 45%) is above the ≈ 40% bar. But: After Effects projects (`.aep`) can't be opened, which
|
||||
alone rules out beta; fidelity against After Effects is measured for one narrow case (scalar ease,
|
||||
168 samples); 134 issues are open, eight of them crash reports. Beta needs ≈ 75% ready and `.aep`
|
||||
168 samples); 216 issues are open on 12 October, six of them crash reports (#580, #501, #426, #341, #234, #879). Beta needs ≈ 75% ready and `.aep`
|
||||
opening reliably: the `.aep` owner decision and importer (80–160 h), the fidelity harness and
|
||||
P0/P1 corpus (60–100 h), the crash and bug backlog (40–80 h), performance (40–70 h),
|
||||
Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and text (100–160 h).
|
||||
@@ -51,7 +51,7 @@ Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and
|
||||
| UI/UX fidelity | 65% | 60–120 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | 50% | 130–230 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware | 40% | 60–120 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization | 12% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Localization | 18% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | 35% | 50–100 | [gaps.md](docs/gaps.md#g5-performance-at-real-world-scale) |
|
||||
| Stability | 45% | 40–80 | [gaps.md](docs/gaps.md#g3-stability-and-a-green-main) |
|
||||
| Platforms | 65% | 30–60 | [gaps.md](docs/gaps.md#g2-real-user-reliability-on-every-platform) |
|
||||
@@ -85,19 +85,19 @@ UI strings translated out of ≈ 3,900 (detail: [localization-parity.md](docs/lo
|
||||
| Language | Status | % |
|
||||
|---|---|---:|
|
||||
| English | full | 100% |
|
||||
| Simplified Chinese | partial (menus, part of the panels) | 28% |
|
||||
| Simplified Chinese | partial (menus, part of the panels) | 29% |
|
||||
| Spanish | menus only | 16% |
|
||||
| Hindi | none | 0% |
|
||||
| Arabic | none | 0% |
|
||||
| French | none | 0% |
|
||||
| Portuguese (Brazil) | menus only | 16% |
|
||||
| French | menus only | 16% |
|
||||
| Portuguese (Brazil) | partial (menus, part of the panels) | 26% |
|
||||
| Indonesian | none | 0% |
|
||||
| Japanese | partial (menus, part of the panels) | 26% |
|
||||
| German | none | 0% |
|
||||
| Japanese | partial (menus, part of the panels) | 27% |
|
||||
| German | menus only | 16% |
|
||||
| Korean | none | 0% |
|
||||
| Vietnamese | none | 0% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 28%) and Ukrainian (partial, 29%). No language has had
|
||||
Also shipped: Traditional Chinese (partial, 29%), Ukrainian (partial, 29%), Czech (partial, 29%) and Russian (menus only, 16%). No language has had
|
||||
native-speaker review.
|
||||
|
||||
## Upcoming
|
||||
@@ -111,12 +111,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
| 3 | Real-user reliability on Linux and Windows; the open mask, effect, text and 3D bugs (G2) | 100–190 |
|
||||
| 4 | `.aep` / `.aepx` import, after the owner's clean-room decision (G4) | 80–160 |
|
||||
| 5 | Performance: benchmarks at 1080p / 4K, real-time cached playback, hardware video (G5) | 50–100 |
|
||||
| 6 | Localization depth: effect names, all panels, French / German / Korean (G9) | 60–110 |
|
||||
| 6 | Localization depth: effect names, all panels, Korean / Italian (G9) | 60–110 |
|
||||
|
||||
Come tell us what matters most to you on [Discord](https://discord.gg/artcraft).
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking;
|
||||
strokes and undo history are preserved so restoring the timing allows the span edit again.
|
||||
- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel
|
||||
catalog gained since 9 October are translated: the Home screen (recent files, their Kind and
|
||||
Opened columns, the empty and no-match states), the viewer's toolbar tooltips, magnification,
|
||||
@@ -148,6 +150,8 @@ Come tell us what matters most to you on [Discord](https://discord.gg/artcraft).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | Open-issue count (134 to 216), crash list and localization share (12% to 18%) updated to match docs/gaps.md |
|
||||
| 2026-10-12 | patch | Roto Brush span validation after trimming; command regressions for both layer edges |
|
||||
| 2026-10-10 | minor | Hours to ≈ 95% for each audience |
|
||||
| 2026-10-10 | minor | Headline adds mainstream practitioner (≈ 47%) and essentials user (≈ 52%) |
|
||||
| 2026-10-10 | minor | Stage checked against the new core-workflow gate (all six pass; still alpha) |
|
||||
|
||||
@@ -404,7 +404,7 @@ export function frameWorkerStart(base, onMessage, gpu) {
|
||||
// ends in a checksum) and read the layer buffers they prefetch; the page lists, reads and
|
||||
// deletes.
|
||||
const CACHE_ROOT = "effectcraft-cache";
|
||||
const CACHE_KINDS = ["frames", "layers"];
|
||||
const CACHE_KINDS = ["frames", "layers", "mattes"];
|
||||
const cacheDirHandles = {};
|
||||
|
||||
async function cacheDir(kind = "frames") {
|
||||
@@ -419,6 +419,7 @@ async function cacheDir(kind = "frames") {
|
||||
/// The folder and file name of an entry name (`layers/<hex>.ecc` or `<hex>.ecc`).
|
||||
async function entryDir(name) {
|
||||
if (name.startsWith("layers/")) return [await cacheDir("layers"), name.slice(7)];
|
||||
if (name.startsWith("mattes/")) return [await cacheDir("mattes"), name.slice(7)];
|
||||
return [await cacheDir("frames"), name];
|
||||
}
|
||||
|
||||
|
||||
@@ -105,19 +105,23 @@ pub fn init() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An entry's name in `js/host.js`'s cache folders (`layers/` for layer buffers).
|
||||
/// An entry's name in `js/host.js`'s cache folders (`layers/` for layer buffers, `mattes/` for segmentations).
|
||||
pub(crate) fn name_of(kind: Kind, key: u128) -> String {
|
||||
match kind {
|
||||
Kind::Frame => disk_cache::entry_name(key),
|
||||
Kind::Layer => format!("layers/{}", disk_cache::entry_name(key)),
|
||||
Kind::Matte => format!("mattes/{}", disk_cache::entry_name(key)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_name(name: &str) -> Option<(Kind, u128)> {
|
||||
match name.strip_prefix("layers/") {
|
||||
Some(n) => Some((Kind::Layer, disk_cache::parse_entry_name(n)?)),
|
||||
None => Some((Kind::Frame, disk_cache::parse_entry_name(name)?)),
|
||||
if let Some(n) = name.strip_prefix("layers/") {
|
||||
return Some((Kind::Layer, disk_cache::parse_entry_name(n)?));
|
||||
}
|
||||
if let Some(n) = name.strip_prefix("mattes/") {
|
||||
return Some((Kind::Matte, disk_cache::parse_entry_name(n)?));
|
||||
}
|
||||
Some((Kind::Frame, disk_cache::parse_entry_name(name)?))
|
||||
}
|
||||
|
||||
/// Layer entries (32 hex digits) a frame worker should read before its next frame: recent
|
||||
|
||||
+137
-17
@@ -1,6 +1,8 @@
|
||||
//! EffectCraft desktop app.
|
||||
//!
|
||||
//! Usage: `effectcraft [--control <port>] [--demo|--empty|--home] [project.ecproj | media files…]`
|
||||
//! Usage: `effectcraft [--control <port>] [--demo|--empty|--home] [--] [project.ecproj | media files…]`
|
||||
//!
|
||||
//! An unknown option or a bad port prints an error and exits with status 1 before anything starts.
|
||||
//!
|
||||
//! Without a project the app starts with an empty Untitled Project, as After Effects does;
|
||||
//! `--demo` opens the demo project instead (also Help ▸ Open Demo Project).
|
||||
@@ -29,6 +31,8 @@ mod window;
|
||||
use effectcraft_ui_egui::EffectcraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
const APP_NAME: &str = "EffectCraft";
|
||||
|
||||
/// The app icon for the window, taskbar and Dock (assets/app-icon, regenerated by
|
||||
/// `packaging/icons.sh`). macOS gets the padded variant so it sits on Apple's icon grid in the Dock.
|
||||
/// The 256 px app icon (Windows, Linux; the AppImage's desktop integration installs it too).
|
||||
@@ -70,22 +74,54 @@ struct Args {
|
||||
home: Option<bool>,
|
||||
}
|
||||
|
||||
/// Parse the arguments after the program name; `None` for `--version`. `env_port` is
|
||||
/// `EFFECTCRAFT_CONTROL_PORT`.
|
||||
fn parse_args(args: impl IntoIterator<Item = String>, env_port: Option<String>) -> Option<Args> {
|
||||
let mut out = Args { control_port: env_port.and_then(|p| p.parse().ok()), ..Default::default() };
|
||||
/// Parse the arguments after the program name; `Ok(None)` for `--version`. `env_port` is
|
||||
/// `EFFECTCRAFT_CONTROL_PORT`, used when `--control` isn't given. An unknown option or a bad port
|
||||
/// is an error, so it is neither imported as a file nor dropped; after `--` every argument is a file.
|
||||
fn parse_args(args: impl IntoIterator<Item = String>, env_port: Result<String, std::env::VarError>) -> Result<Option<Args>, String> {
|
||||
let mut out = Args::default();
|
||||
let mut args = args.into_iter();
|
||||
let mut options = true;
|
||||
while let Some(a) = args.next() {
|
||||
if !options {
|
||||
out.files.push(a);
|
||||
continue;
|
||||
}
|
||||
match a.as_str() {
|
||||
"--control" => out.control_port = args.next().and_then(|p| p.parse().ok()),
|
||||
"--" => options = false,
|
||||
"--control" => out.control_port = Some(control_port("--control", args.next().as_deref())?),
|
||||
"--demo" => out.demo = true,
|
||||
"--empty" => out.demo = false,
|
||||
"--home" => out.home = Some(true),
|
||||
"--version" => return None,
|
||||
_ => out.files.push(a),
|
||||
"--version" => return Ok(None),
|
||||
_ => match a.strip_prefix("--control=") {
|
||||
Some(v) => out.control_port = Some(control_port("--control", Some(v))?),
|
||||
// macOS LaunchServices may pass a process serial number (`-psn_0_1234`), notably on
|
||||
// the first launch of a downloaded app; it is not an option of ours.
|
||||
None if a.starts_with("-psn_") => {}
|
||||
None if a.starts_with('-') && a != "-" => return Err(format!("unknown option `{a}`")),
|
||||
None => out.files.push(a),
|
||||
},
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
if out.control_port.is_none() {
|
||||
out.control_port = match env_port {
|
||||
Ok(v) if v.is_empty() => None,
|
||||
Ok(v) => Some(control_port("EFFECTCRAFT_CONTROL_PORT", Some(&v))?),
|
||||
Err(std::env::VarError::NotPresent) => None,
|
||||
Err(std::env::VarError::NotUnicode(v)) => Some(control_port("EFFECTCRAFT_CONTROL_PORT", Some(&v.to_string_lossy()))?),
|
||||
};
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// A control-channel port from 1 to 65535 (0 would listen on a port nobody is told); `name` is
|
||||
/// the flag or variable it came from.
|
||||
fn control_port(name: &str, value: Option<&str>) -> Result<u16, String> {
|
||||
let need = format!("{name} needs a port number from 1 to 65535");
|
||||
match value {
|
||||
None => Err(need),
|
||||
Some(v) => v.parse().ok().filter(|&p| p != 0).ok_or(format!("{need}, not `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
@@ -94,9 +130,17 @@ fn main() -> eframe::Result {
|
||||
// feed the compatibility report.
|
||||
effectcraft_engine::logging::install();
|
||||
effectcraft_engine::logging::install_panic_hook();
|
||||
let Some(Args { control_port, files, demo, home }) = parse_args(std::env::args().skip(1), std::env::var("EFFECTCRAFT_CONTROL_PORT").ok()) else {
|
||||
println!("effectcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
let Args { control_port, files, demo, home } = match parse_args(std::env::args().skip(1), std::env::var("EFFECTCRAFT_CONTROL_PORT")) {
|
||||
Ok(Some(args)) => args,
|
||||
Ok(None) => {
|
||||
println!("effectcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
// Before the session log, preferences and the window: nothing has started yet.
|
||||
Err(e) => {
|
||||
eprintln!("effectcraft: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
// The session log lives in the settings folder (`Logs/effectcraft.log`, the previous two runs
|
||||
// kept): a launch from the Dock or a menu has no terminal. Opened after the arguments, so
|
||||
@@ -119,7 +163,7 @@ fn main() -> eframe::Result {
|
||||
let notice = launch.notice.take();
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("EffectCraft")
|
||||
.with_title(APP_NAME)
|
||||
.with_inner_size(window::DEFAULT_SIZE)
|
||||
.with_min_inner_size(window::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
@@ -142,7 +186,7 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
let result = eframe::run_native(
|
||||
"EffectCraft",
|
||||
APP_NAME,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
match &cc.wgpu_render_state {
|
||||
@@ -308,6 +352,11 @@ fn wgpu_options(backends: Option<eframe::wgpu::Backends>) -> eframe::WgpuConfigu
|
||||
if let Some(b) = backends {
|
||||
setup.instance_descriptor.backends = b;
|
||||
}
|
||||
// Nothing draws or dispatches indirectly, so wgpu's check of indirect arguments only costs
|
||||
// a compute shader when the device is created, one that Metal can't compile on an Intel
|
||||
// Iris Pro: the device is lost and the window never opens.
|
||||
// `WGPU_VALIDATION_INDIRECT_CALL=1` turns the check back on.
|
||||
setup.instance_descriptor.flags = setup.instance_descriptor.flags.difference(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
|
||||
setup.device_descriptor = std::sync::Arc::new(|adapter| eframe::wgpu::DeviceDescriptor {
|
||||
label: Some("EffectCraft device"),
|
||||
required_limits: device_limits(adapter.limits()),
|
||||
@@ -339,7 +388,7 @@ fn startup_failed(e: &eframe::Error, gl_next: bool) {
|
||||
}
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_title("EffectCraft")
|
||||
.set_title(APP_NAME)
|
||||
.set_description(message)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
@@ -425,9 +474,18 @@ fn disable_app_nap() {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Args, parse_args};
|
||||
use std::env::VarError;
|
||||
|
||||
fn parse_env(args: &[&str], env_port: Result<String, VarError>) -> Result<Option<Args>, String> {
|
||||
parse_args(args.iter().map(|a| a.to_string()), env_port)
|
||||
}
|
||||
|
||||
fn parse(args: &[&str]) -> Option<Args> {
|
||||
parse_args(args.iter().map(|a| a.to_string()), None)
|
||||
parse_env(args, Err(VarError::NotPresent)).unwrap()
|
||||
}
|
||||
|
||||
fn fails(args: &[&str]) -> String {
|
||||
parse_env(args, Err(VarError::NotPresent)).unwrap_err()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -441,6 +499,19 @@ mod tests {
|
||||
assert!(super::wayland_drop_notice(Some(OsStr::new("wayland-0")), Some(OsStr::new("x11"))).is_none());
|
||||
}
|
||||
|
||||
/// The window's wgpu instance skips indirect-call validation (Intel Metal, #1153).
|
||||
#[test]
|
||||
fn the_window_instance_skips_indirect_call_validation() {
|
||||
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_some() {
|
||||
return;
|
||||
}
|
||||
let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = super::wgpu_options(None).wgpu_setup else {
|
||||
panic!("the default setup creates its own instance");
|
||||
};
|
||||
// Intel Metal can't compile the validation's compute shader, and the device is lost.
|
||||
assert!(!setup.instance_descriptor.flags.contains(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
|
||||
}
|
||||
|
||||
/// The window's device never asks for more than the adapter offers (#198).
|
||||
#[test]
|
||||
fn device_limits_fit_the_adapter() {
|
||||
@@ -477,6 +548,55 @@ mod tests {
|
||||
let a = parse(&["--control", "9877", "--home", "a.ecproj"]).unwrap_or_default();
|
||||
assert_eq!((a.control_port, a.home, a.files), (Some(9877), Some(true), vec!["a.ecproj".to_string()]));
|
||||
assert_eq!(parse(&["--version"]), None);
|
||||
assert_eq!(parse_args(Vec::new(), Some("9000".into())).map(|a| a.control_port), Some(Some(9000)));
|
||||
assert_eq!(parse_env(&[], Ok("9000".into())).unwrap().map(|a| a.control_port), Some(Some(9000)));
|
||||
}
|
||||
|
||||
/// A missing, non-numeric or zero `--control` value stops the launch instead of starting
|
||||
/// without a control server, and the argument after `--control` isn't reinterpreted (#997).
|
||||
#[test]
|
||||
fn control_needs_a_port_from_1_to_65535() {
|
||||
let need = "--control needs a port number from 1 to 65535";
|
||||
assert_eq!(fails(&["--control"]), need);
|
||||
assert_eq!(fails(&["--control", "--demo"]), format!("{need}, not `--demo`"));
|
||||
assert_eq!(fails(&["--control", "--version"]), format!("{need}, not `--version`"));
|
||||
for bad in ["abc", "0", "70000", "-1", ""] {
|
||||
assert_eq!(fails(&["--control", bad]), format!("{need}, not `{bad}`"));
|
||||
assert_eq!(fails(&[&format!("--control={bad}")]), format!("{need}, not `{bad}`"));
|
||||
}
|
||||
assert_eq!(parse(&["--control=9877"]).map(|a| a.control_port), Some(Some(9877)));
|
||||
assert_eq!(parse(&["--control", "65535"]).map(|a| a.control_port), Some(Some(65535)));
|
||||
}
|
||||
|
||||
/// An unknown option is an error, not a file to import (#997); `--` ends the options.
|
||||
#[test]
|
||||
fn unknown_options_are_errors_not_files() {
|
||||
for bad in ["--automation-read-root", "--automation-write-root=/tmp", "-h", "--Demo", "--demo=yes"] {
|
||||
assert_eq!(fails(&[bad, "/tmp/folder"]), format!("unknown option `{bad}`"));
|
||||
}
|
||||
// Parsed left to right: an error before `--version` wins.
|
||||
assert_eq!(fails(&["--nope", "--version"]), "unknown option `--nope`");
|
||||
// Finder's process serial number is ignored, not imported or refused.
|
||||
assert_eq!(parse(&["-psn_0_12345"]).map(|a| a.files), Some(vec![]));
|
||||
let a = parse(&["clip.mov", "-", "--", "--demo", "-name.png"]).unwrap_or_default();
|
||||
assert_eq!(a.files, ["clip.mov", "-", "--demo", "-name.png"]);
|
||||
assert!(!a.demo);
|
||||
}
|
||||
|
||||
/// `--control` wins over `EFFECTCRAFT_CONTROL_PORT`; the variable is checked only when it is
|
||||
/// used, so a bad value doesn't stop `--control` or `--version`.
|
||||
#[test]
|
||||
fn control_port_variable_is_checked_when_used() {
|
||||
let need = "EFFECTCRAFT_CONTROL_PORT needs a port number from 1 to 65535";
|
||||
assert_eq!(parse_env(&[], Ok("abc".into())).unwrap_err(), format!("{need}, not `abc`"));
|
||||
assert_eq!(parse_env(&[], Ok("0".into())).unwrap_err(), format!("{need}, not `0`"));
|
||||
assert_eq!(parse_env(&[], Ok(String::new())), Ok(Some(Args::default())));
|
||||
assert_eq!(parse_env(&["--control", "9877"], Ok("abc".into())).unwrap().map(|a| a.control_port), Some(Some(9877)));
|
||||
assert_eq!(parse_env(&["--version"], Ok("abc".into())), Ok(None));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let not_utf8 = VarError::NotUnicode(std::ffi::OsString::from_vec(vec![0x39, 0xff]));
|
||||
assert_eq!(parse_env(&[], Err(not_utf8)).unwrap_err(), format!("{need}, not `9\u{fffd}`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The desktop binary rejects a bad command line before it starts anything (#997).
|
||||
// Integration tests: unwrapping and panicking on failure is fine here.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A settings folder of its own, so a launch that got past the arguments would show up as
|
||||
/// preferences (Recent Footage) written there instead of in the user's settings.
|
||||
fn config_dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("ec-args-test-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Runs the app, which must exit at once with `effectcraft: <message>` and a failure status. A
|
||||
/// regression fails instead of leaving a window open: the process is killed after 5 s.
|
||||
fn rejects(name: &str, args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
let config = config_dir(name);
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_effectcraft"));
|
||||
cmd.args(args).env_remove("EFFECTCRAFT_CONTROL_PORT").env_remove("RUST_LOG").env("EFFECTCRAFT_CONFIG_DIR", &config);
|
||||
for (k, v) in env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(!timed_out, "{args:?}: the app started or did not exit promptly");
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}: {:?}", String::from_utf8_lossy(&out.stdout));
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("effectcraft: {message}\n"), "{args:?}");
|
||||
let written: Vec<_> = std::fs::read_dir(&config).unwrap().collect();
|
||||
assert!(written.is_empty(), "{args:?}: wrote {written:?}");
|
||||
let _ = std::fs::remove_dir_all(&config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_stop_the_launch_before_anything_is_imported() {
|
||||
let folder = config_dir("folder");
|
||||
rejects("read-root", &["--control", "47613", "--automation-read-root", folder.to_str().unwrap()], &[], "unknown option `--automation-read-root`");
|
||||
rejects("write-root", &["--automation-write-root=/tmp"], &[], "unknown option `--automation-write-root=/tmp`");
|
||||
rejects("short", &["-h"], &[], "unknown option `-h`");
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_control_port_stops_the_launch() {
|
||||
let need = "--control needs a port number from 1 to 65535";
|
||||
rejects("missing", &["--control"], &[], need);
|
||||
rejects("flag", &["--control", "--demo"], &[], &format!("{need}, not `--demo`"));
|
||||
rejects("text", &["--control", "abc"], &[], &format!("{need}, not `abc`"));
|
||||
rejects("zero", &["--control=0"], &[], &format!("{need}, not `0`"));
|
||||
rejects("env", &[], &[("EFFECTCRAFT_CONTROL_PORT", "abc")], "EFFECTCRAFT_CONTROL_PORT needs a port number from 1 to 65535, not `abc`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_still_prints_with_a_bad_port_variable() {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_effectcraft")).arg("--version").env("EFFECTCRAFT_CONTROL_PORT", "abc").output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("effectcraft {}\n", env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
@@ -64,3 +64,17 @@ sync_github_name = true
|
||||
|
||||
[people.webdevtodayjason]
|
||||
display_name = "Jason Brashear"
|
||||
|
||||
[people.nanox333]
|
||||
display_name = "nanox333"
|
||||
|
||||
[people.Nael-Nathanael]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
[people.moecr7]
|
||||
real_name = "Moein Saharkhiz"
|
||||
display_name = "onlymoein"
|
||||
|
||||
@@ -379,6 +379,49 @@ pub fn selection_hashes(sel: &str, manifest: Option<&[(String, u32)]>) -> Vec<u3
|
||||
|
||||
pub const CRYPTO_LAYERS: [&str; 3] = ["CryptoObject", "CryptoMaterial", "CryptoAsset"];
|
||||
|
||||
/// Rank planes as [`AuxChannels::crypto_rank_planes`] returns them.
|
||||
type RankPlanes<'a> = [(&'a [f32], &'a [f32])];
|
||||
|
||||
/// The selection's coverage at aux pixel `i`: the summed coverage of the selected IDs over all
|
||||
/// ranks (the Cryptomatte spec's matte), clamped to 0..1.
|
||||
#[inline]
|
||||
fn crypto_matte(planes: &RankPlanes, sel: &[u32], i: usize) -> f32 {
|
||||
planes
|
||||
.iter()
|
||||
.filter_map(|(id, c)| Some((*id.get(i)?, *c.get(i)?)))
|
||||
.filter(|(id, c)| *c > 0.0 && sel.contains(&id.to_bits()))
|
||||
.map(|(_, c)| c)
|
||||
.sum::<f32>()
|
||||
.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The coverage-weighted ID colours at aux pixel `i` (the spec's preview).
|
||||
#[inline]
|
||||
fn crypto_colors(planes: &RankPlanes, i: usize) -> [f32; 3] {
|
||||
let mut c = [0.0f32; 3];
|
||||
for (id, cov) in planes {
|
||||
let (Some(&id), Some(&cov)) = (id.get(i), cov.get(i)) else { continue };
|
||||
let k = id_color(id);
|
||||
for j in 0..3 {
|
||||
c[j] += k[j] * cov;
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Per aux pixel of Cryptomatte layer `layer`: the coverage-weighted ID colours (RGB) and the
|
||||
/// selection's coverage (A), computed in parallel with the rank planes resolved once. The GPU
|
||||
/// effect uploads this image and samples it per layer pixel.
|
||||
pub fn crypto_aux_image(a: &AuxChannels, layer: &str, sel: &[u32]) -> Image {
|
||||
let planes = a.crypto_rank_planes(layer);
|
||||
let mut img = Image::new(a.width, a.height);
|
||||
img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let c = crypto_colors(&planes, i);
|
||||
*px = [c[0], c[1], c[2], crypto_matte(&planes, sel, i)];
|
||||
});
|
||||
img
|
||||
}
|
||||
|
||||
fn cryptomatte(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let Some(a) = aux(ctx) else { return b };
|
||||
let layers = a.crypto_layers();
|
||||
@@ -392,10 +435,10 @@ fn cryptomatte(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let idx = index_map(&b, &a);
|
||||
let display = ctx.params.e("display");
|
||||
let matte_only = ctx.params.b("matteOnly");
|
||||
let planes = a.crypto_rank_planes(&layer);
|
||||
let src = b.img.clone();
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let ranks = idx[i].map(|k| a.crypto_ranks(&layer, k)).unwrap_or_default();
|
||||
let m: f32 = ranks.iter().filter(|(id, c)| *c > 0.0 && sel.contains(&id.to_bits())).map(|(_, c)| *c).sum::<f32>().clamp(0.0, 1.0);
|
||||
let m = idx[i].map_or(0.0, |k| crypto_matte(&planes, &sel, k));
|
||||
if matte_only {
|
||||
*px = [m, m, m, m];
|
||||
return;
|
||||
@@ -403,13 +446,7 @@ fn cryptomatte(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
*px = match display {
|
||||
// Colors: coverage-weighted ID colours (the spec's preview), selection brighter.
|
||||
0 => {
|
||||
let mut c = [0.0f32; 3];
|
||||
for (id, cov) in &ranks {
|
||||
let k = id_color(*id);
|
||||
for j in 0..3 {
|
||||
c[j] += k[j] * cov;
|
||||
}
|
||||
}
|
||||
let c = idx[i].map_or([0.0; 3], |k| crypto_colors(&planes, k));
|
||||
let c = c.map(|v| v * (1.0 - 0.5 * m) + 0.5 * m);
|
||||
[c[0], c[1], c[2], 1.0]
|
||||
}
|
||||
@@ -692,6 +729,159 @@ mod tests {
|
||||
assert_ne!(c.get(2, 5), c.get(12, 5));
|
||||
}
|
||||
|
||||
/// The parallel aux image (rank planes resolved once) is bit-identical to the per-pixel
|
||||
/// reduction over `crypto_ranks` it replaces.
|
||||
#[test]
|
||||
fn crypto_aux_image_matches_the_per_pixel_reduction() {
|
||||
let (w, h) = (7u32, 5u32);
|
||||
let n = (w * h) as usize;
|
||||
let mut a = AuxChannels::new(w, h, 1.0);
|
||||
let ids = [crypto_hash("cube"), crypto_hash("sphere"), crypto_hash("ring")].map(effectcraft_raster::channels3d::crypto_float);
|
||||
for (k, ch) in ["00.R", "00.G", "00.B", "00.A", "01.R", "01.G", "01.B", "01.A"].iter().enumerate() {
|
||||
let v: Vec<f32> = (0..n).map(|i| if k % 2 == 0 { ids[(i + k) % 3] } else { ((i * 7 + k * 3) % 11) as f32 / 10.0 }).collect();
|
||||
a.channels.push((format!("CryptoObject{ch}"), v));
|
||||
}
|
||||
let sel = vec![crypto_hash("sphere"), crypto_hash("ring")];
|
||||
let img = crypto_aux_image(&a, "CryptoObject", &sel);
|
||||
for i in 0..n {
|
||||
let ranks = a.crypto_ranks("CryptoObject", i);
|
||||
let m: f32 = ranks.iter().filter(|(id, c)| *c > 0.0 && sel.contains(&id.to_bits())).map(|(_, c)| *c).sum::<f32>().clamp(0.0, 1.0);
|
||||
let mut c = [0.0f32; 3];
|
||||
for (id, cov) in &ranks {
|
||||
let k = id_color(*id);
|
||||
for j in 0..3 {
|
||||
c[j] += k[j] * cov;
|
||||
}
|
||||
}
|
||||
let want = [c[0], c[1], c[2], m];
|
||||
assert_eq!(img.data[i].map(f32::to_bits), want.map(f32::to_bits), "pixel {i}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup before #473, kept as the reference: the rank channels formatted and searched
|
||||
/// by name for every pixel.
|
||||
fn ranks_by_name(a: &AuxChannels, layer: &str, i: usize) -> Vec<(f32, f32)> {
|
||||
let mut out = vec![];
|
||||
for k in 0.. {
|
||||
let get = |c: &str| a.get(&format!("{layer}{k:02}.{c}"));
|
||||
let (Some(r), Some(g)) = (get("R"), get("G")) else { break };
|
||||
out.push((r[i], g[i]));
|
||||
if let (Some(b), Some(al)) = (get("B"), get("A")) {
|
||||
out.push((b[i], al[i]));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The reduction before #473 over those ranks: (ID colours, selection coverage).
|
||||
fn reduce_by_name(a: &AuxChannels, layer: &str, sel: &[u32], i: usize) -> ([f32; 3], f32) {
|
||||
let ranks = ranks_by_name(a, layer, i);
|
||||
let m: f32 = ranks.iter().filter(|(id, c)| *c > 0.0 && sel.contains(&id.to_bits())).map(|(_, c)| *c).sum::<f32>().clamp(0.0, 1.0);
|
||||
let mut c = [0.0f32; 3];
|
||||
for (id, cov) in &ranks {
|
||||
let k = id_color(*id);
|
||||
for j in 0..3 {
|
||||
c[j] += k[j] * cov;
|
||||
}
|
||||
}
|
||||
(c, m)
|
||||
}
|
||||
|
||||
/// A 6×2 Cryptomatte layer with awkward values: NaN, ±inf, negative and -0.0 coverage, NaN
|
||||
/// and -0.0 IDs; rank 01 has no B/A pair, rank 02 is missing, so rank 03 (filled with values
|
||||
/// that would change every pixel) must be ignored as before.
|
||||
fn edge_aux(with_rank_after_gap: bool) -> AuxChannels {
|
||||
let (w, h) = (6u32, 2u32);
|
||||
let nan_payload = f32::from_bits(0x7fc0_1234);
|
||||
let (hs, hc) = (crypto_float(crypto_hash("sphere")), crypto_float(crypto_hash("cube")));
|
||||
let cov = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.5, -0.0, 0.0, 0.25, 1.0, 2.0, f32::MIN_POSITIVE, nan_payload, 0.5];
|
||||
let ids = [hs, f32::NAN, hc, -0.0, 0.0, nan_payload, hs, hc, f32::NAN, hs, hc, -0.0];
|
||||
let rot = |v: &[f32; 12], k: usize| -> Vec<f32> { (0..12).map(|i| v[(i + k) % 12]).collect() };
|
||||
let mut a = AuxChannels::new(w, h, 1.0);
|
||||
let mut push = |n: &str, v: Vec<f32>| a.channels.push((format!("CryptoObject{n}"), v));
|
||||
push("00.R", rot(&ids, 0));
|
||||
push("00.G", rot(&cov, 0));
|
||||
push("00.B", rot(&ids, 3));
|
||||
push("00.A", rot(&cov, 5));
|
||||
push("01.R", rot(&ids, 7));
|
||||
push("01.G", rot(&cov, 2));
|
||||
if with_rank_after_gap {
|
||||
push("03.R", vec![hs; 12]);
|
||||
push("03.G", vec![1.0; 12]);
|
||||
push("03.B", vec![hc; 12]);
|
||||
push("03.A", vec![1.0; 12]);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn edge_selection() -> Vec<u32> {
|
||||
vec![crypto_hash("sphere"), f32::NAN.to_bits(), 0x7fc0_1234, (-0.0f32).to_bits()]
|
||||
}
|
||||
|
||||
/// Edge values give bit-identical results to the lookup by name, the missing B/A pair is
|
||||
/// skipped and a rank after a gap is ignored.
|
||||
#[test]
|
||||
fn crypto_aux_image_is_bit_exact_on_edge_values() {
|
||||
let sel = edge_selection();
|
||||
let a = edge_aux(true);
|
||||
assert_eq!(a.crypto_rank_planes("CryptoObject").len(), 3, "00.R/G, 00.B/A, 01.R/G; not 03 after the gap");
|
||||
let img = crypto_aux_image(&a, "CryptoObject", &sel);
|
||||
let without_gap_rank = crypto_aux_image(&edge_aux(false), "CryptoObject", &sel);
|
||||
for i in 0..12 {
|
||||
let (c, m) = reduce_by_name(&a, "CryptoObject", &sel, i);
|
||||
let want = [c[0], c[1], c[2], m];
|
||||
assert_eq!(img.data[i].map(f32::to_bits), want.map(f32::to_bits), "pixel {i}");
|
||||
assert_eq!(img.data[i].map(f32::to_bits), without_gap_rank.data[i].map(f32::to_bits), "pixel {i}: the rank after the gap was used");
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU effect on a 20×10 layer over the 6×2 edge aux: pixels inside the aux area match
|
||||
/// the lookup by name bit for bit in every display mode, pixels outside it (no aux index)
|
||||
/// get an empty matte and no ID colour.
|
||||
#[test]
|
||||
fn cryptomatte_cpu_path_is_bit_exact_inside_and_outside_the_aux_area() {
|
||||
let a = edge_aux(true);
|
||||
let host = AuxHost(Arc::new(a.clone()));
|
||||
let names = "sphere, <7fc00000>, <7fc01234>, <80000000>";
|
||||
assert_eq!(selection_hashes(names, None), edge_selection());
|
||||
let src = img().data[0];
|
||||
for (display, matte_only) in [(0, false), (1, false), (2, false), (0, true)] {
|
||||
let out = run(
|
||||
"ec.3d.cryptomatte",
|
||||
&[("selection", Value::Str(names.into())), ("display", Value::Enum(display)), ("matteOnly", Value::Bool(matte_only))],
|
||||
&host,
|
||||
);
|
||||
let expect = |c: [f32; 3], m: f32| -> [f32; 4] {
|
||||
if matte_only {
|
||||
return [m; 4];
|
||||
}
|
||||
match display {
|
||||
0 => {
|
||||
let c = c.map(|v| v * (1.0 - 0.5 * m) + 0.5 * m);
|
||||
[c[0], c[1], c[2], 1.0]
|
||||
}
|
||||
1 => src.map(|v| v * m),
|
||||
_ => [src[0] * (1.0 - 0.5 * m) + 0.5 * m * src[3], src[1] * (1.0 - 0.5 * m) + 0.5 * m * src[3], src[2] * (1.0 - 0.5 * m), src[3]],
|
||||
}
|
||||
};
|
||||
for (x, y) in [(0u32, 0u32), (1, 0), (5, 0), (0, 1), (3, 1), (5, 1)] {
|
||||
let (c, m) = reduce_by_name(&a, "CryptoObject", &edge_selection(), (y * 6 + x) as usize);
|
||||
assert_eq!(
|
||||
out.get(x as i64, y as i64).map(f32::to_bits),
|
||||
expect(c, m).map(f32::to_bits),
|
||||
"display {display} matteOnly {matte_only} at ({x}, {y})"
|
||||
);
|
||||
}
|
||||
for (x, y) in [(6u32, 0u32), (19, 0), (0, 2), (12, 9)] {
|
||||
assert_eq!(
|
||||
out.get(x as i64, y as i64).map(f32::to_bits),
|
||||
expect([0.0; 3], 0.0).map(f32::to_bits),
|
||||
"display {display} matteOnly {matte_only} outside the aux at ({x}, {y})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cryptomatte_selects_by_name_and_wildcard() {
|
||||
let h = scene();
|
||||
|
||||
@@ -44,7 +44,9 @@ fn gradient_ramp(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
}
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let c = [c0[0] + (c1[0] - c0[0]) * t, c0[1] + (c1[1] - c0[1]) * t, c0[2] + (c1[2] - c0[2]) * t];
|
||||
put(px, c, 1.0, blend);
|
||||
// The ramp fills only where the layer has alpha (#1063), so it keeps the source alpha.
|
||||
let a = px[3];
|
||||
put(px, c, a, blend);
|
||||
}
|
||||
});
|
||||
b
|
||||
@@ -400,6 +402,24 @@ mod generator_tests {
|
||||
Image::filled(32, 32, [1.0, 0.0, 0.0, 1.0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_ramp_stays_inside_the_layer_alpha() {
|
||||
// #1063: a shape's transparent pixels stay transparent; the ramp fills only the shape.
|
||||
let mut img = Image::filled(40, 24, [1.0, 0.0, 0.0, 1.0]);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
let a = if i % 40 < 10 { 0.0 } else { 1.0 };
|
||||
*p = p.map(|c| c * a);
|
||||
}
|
||||
for blend in [0.0, 50.0] {
|
||||
let o = run_fx("ec.generate.gradientramp", &[("blend", num(blend))], img.clone(), 0.0, EffectEnv::default());
|
||||
for (src, out) in img.data.iter().zip(&o.img.data) {
|
||||
assert!((src[3] - out[3]).abs() < 1e-6, "blend {blend}: alpha {} became {}", src[3], out[3]);
|
||||
assert!(out[..3].iter().all(|&c| c <= out[3] + 1e-6), "blend {blend}: premultiplied colour above alpha");
|
||||
}
|
||||
assert!(o.img.data.iter().any(|p| p[3] > 0.99), "blend {blend}: the ramp is drawn inside the shape");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkerboard_blending_none_shows_pattern_only_and_size_from_width() {
|
||||
let set = [("width", num(8.0)), ("height", num(2.0))];
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod mocha_shape;
|
||||
mod noise;
|
||||
mod noise2;
|
||||
mod noise3;
|
||||
pub mod object_matte;
|
||||
mod obsolete;
|
||||
mod ocio;
|
||||
pub mod ocio_config;
|
||||
@@ -109,7 +110,7 @@ pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time,
|
||||
// effectcraft-gpu fx_tone.
|
||||
pub use ocio::color_stabilizer_maps;
|
||||
// GPU effects, part B (3D Channel, Immersive Video, colour management, simulation render passes).
|
||||
pub use channel3d::{CRYPTO_LAYERS, id_color, selection_hashes};
|
||||
pub use channel3d::{CRYPTO_LAYERS, crypto_aux_image, id_color, selection_hashes};
|
||||
pub use ocio::{ColorOp, Straight, Tf, color_program};
|
||||
pub use sim::{Acc, Blob, Bubble, Post, Shape, Sprite, SpritePlan, Tint, bubble_list, drizzle_drops, mercury_blobs, sprite_plan};
|
||||
pub use sim2::{
|
||||
@@ -354,8 +355,8 @@ pub trait EffectHost: Sync {
|
||||
self.layer(id, false)
|
||||
}
|
||||
/// The effect's own layer at another **layer time** `layer_time` (seconds): its source with
|
||||
/// masks applied, followed by the first `effects` effects of its stack (0 = none, which is
|
||||
/// what After Effects' Time effects see). `None` when unavailable (no host, recursion
|
||||
/// masks applied, followed by the first `effects` effects of its stack (0 = none; the host
|
||||
/// never goes past the effect being rendered). `None` when unavailable (no host, recursion
|
||||
/// limit, adjustment layers). Time effects use this to read neighbouring frames.
|
||||
fn self_at(&self, _layer_time: f64, _effects: usize) -> Option<Buf> {
|
||||
None
|
||||
@@ -533,6 +534,7 @@ pub fn registry() -> &'static [EffectSpec] {
|
||||
v.extend(camera_tracker::specs());
|
||||
v.extend(face_track::specs());
|
||||
v.extend(roto::specs());
|
||||
v.extend(object_matte::specs());
|
||||
v.sort_by(|a, b| a.category.cmp(b.category).then(a.name.cmp(b.name)));
|
||||
for s in v.iter_mut() {
|
||||
if GPU_EFFECTS.contains(&s.id) {
|
||||
@@ -841,7 +843,15 @@ pub const PARAM_GROUPS: &[(&str, &str)] = &[
|
||||
|
||||
/// Display names of nested parameter groups by match id.
|
||||
fn group_name(m: &str) -> &str {
|
||||
warp_stab::GROUPS.iter().chain(roto::GROUPS).chain(keylight::GROUPS).chain(PARAM_GROUPS).find(|(id, _)| *id == m).map(|(_, n)| *n).unwrap_or(m)
|
||||
warp_stab::GROUPS
|
||||
.iter()
|
||||
.chain(roto::GROUPS)
|
||||
.chain(object_matte::GROUPS)
|
||||
.chain(keylight::GROUPS)
|
||||
.chain(PARAM_GROUPS)
|
||||
.find(|(id, _)| *id == m)
|
||||
.map(|(_, n)| *n)
|
||||
.unwrap_or(m)
|
||||
}
|
||||
|
||||
/// The nested group at `path` (`borders/autoScale`) under `g`, created on first use.
|
||||
@@ -1216,6 +1226,7 @@ pub const TIME_DEPENDENT: &[&str] = &[
|
||||
camera_tracker::ID,
|
||||
// Each frame has its own segmentation.
|
||||
roto::ID,
|
||||
object_matte::ID,
|
||||
];
|
||||
|
||||
/// See [`TIME_DEPENDENT`].
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
//! Object Matte (Effect ▸ Matte): isolate one object from a click, and follow it through the
|
||||
//! shot (After Effects 26.2's Object Matte, from its public description: pick an object with a
|
||||
//! point, optionally a box around it, and get a matte that tracks it).
|
||||
//!
|
||||
//! The prompt is the **Object Point** (layer pixels) and, with **Use Box**, a box around the
|
||||
//! object. On the **Reference Frame** it is segmented by the same engine as Roto Brush: the
|
||||
//! trained model chosen in Settings ▸ Roto Brush (MobileSAM, `effectcraft_segment`) when one is
|
||||
//! installed, the classical graph cut otherwise. The model gets the point as a foreground point
|
||||
//! and the box as its box prompt; the graph cut gets the point as a foreground stroke and the
|
||||
//! box's edges (without a box, the layer's border) as background strokes. With **Track Object** the
|
||||
//! matte is then carried frame by frame up to **Frames Before** / **Frames After** away (optical
|
||||
//! flow, re-segmented by the model prompted with the carried matte); without it every frame is
|
||||
//! segmented on its own from the prompt (useful when the point is animated).
|
||||
//!
|
||||
//! Like Roto Brush, the segmentation is derived data in Roto Brush's content-keyed cache
|
||||
//! ([`crate::roto::cached`]): the chain seed holds the engine-maintained Input Key (what the
|
||||
//! frames are made of), the layer size, the frame rate, the mode and the model, and every
|
||||
//! frame's key the prompt, so edits upstream or to the prompt recompute it and undo never sees a
|
||||
//! stale matte. The engine fills that cache in a background job (`objectMatte.propagate`,
|
||||
//! outward from the reference frame over [`job_frames`]) and **Freeze** (`objectMatte.freeze`)
|
||||
//! stores the final mattes in the hidden **Frozen** parameter ([`FrozenCache`], as Roto Brush
|
||||
//! does): they are used, without segmenting, while [`frozen_key`] still matches. **Feather**,
|
||||
//! **Contrast** and **Shift Edge** shape the matte, **Invert** keeps everything but the object
|
||||
//! and **View ▸ Matte** shows the matte in grey.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_segment::MaskModel;
|
||||
use effectcraft_track::roto::refine::MatteParams;
|
||||
use effectcraft_track::roto::{FrameSeg, RotoData, SegOpts, Stroke, StrokeKind, rle};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::roto::{self, Chain, FROZEN, FrozenCache, INPUT_KEY};
|
||||
use crate::warp_stab::param;
|
||||
use crate::{Buf, EffectCtx, EffectSpec, Params, num, p, popup, slider};
|
||||
|
||||
/// The effect's id.
|
||||
pub const ID: &str = "ec.matte.objectmatte";
|
||||
|
||||
/// Display names of the instance's parameter groups.
|
||||
pub const GROUPS: &[(&str, &str)] = &[("objectTracking", "Tracking"), ("objectMatte", "Matte")];
|
||||
|
||||
pub const VIEWS: [&str; 2] = ["Final Output", "Matte"];
|
||||
|
||||
/// Most frames a matte is carried from the reference frame each way.
|
||||
pub const MAX_REACH: f64 = 600.0;
|
||||
/// Default reach each way (frames).
|
||||
pub const DEFAULT_REACH: f64 = 30.0;
|
||||
|
||||
/// Radius (layer pixels) of the foreground stroke the Object Point becomes.
|
||||
const POINT_RADIUS: f64 = 3.0;
|
||||
/// Radius (layer pixels) of the background strokes along the box / the layer's border.
|
||||
const EDGE_RADIUS: f64 = 2.0;
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![EffectSpec {
|
||||
id: ID,
|
||||
name: "Object Matte",
|
||||
category: "Matte",
|
||||
params: vec![
|
||||
p("objectPoint", "Object Point", Value::Vec2([0.5, 0.5]), ParamUi::Point),
|
||||
p("useBox", "Use Box", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("boxTopLeft", "Box Top Left", Value::Vec2([0.25, 0.25]), ParamUi::Point),
|
||||
p("boxBottomRight", "Box Bottom Right", Value::Vec2([0.75, 0.75]), ParamUi::Point),
|
||||
p("objectTracking/trackObject", "Track Object", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("objectTracking/referenceFrame", "Reference Frame", num(0.0), ParamUi::Number),
|
||||
p("objectTracking/framesBefore", "Frames Before", num(DEFAULT_REACH), slider(0.0, MAX_REACH, 0.0, 120.0, 0)),
|
||||
p("objectTracking/framesAfter", "Frames After", num(DEFAULT_REACH), slider(0.0, MAX_REACH, 0.0, 120.0, 0)),
|
||||
p("objectMatte/feather", "Feather", num(0.0), slider(0.0, 100.0, 0.0, 20.0, 1)),
|
||||
p("objectMatte/contrast", "Contrast", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
|
||||
p("objectMatte/shiftEdge", "Shift Edge", num(0.0), slider(-100.0, 100.0, -100.0, 100.0, 0)),
|
||||
p("invert", "Invert", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("view", "View", Value::Enum(0), popup(&VIEWS)),
|
||||
p(INPUT_KEY, "Input Key", Value::Str(String::new()), ParamUi::Hidden),
|
||||
p(FROZEN, "Frozen", Value::Str(String::new()), ParamUi::Hidden),
|
||||
],
|
||||
render,
|
||||
gpu: false,
|
||||
float: true,
|
||||
}]
|
||||
}
|
||||
|
||||
fn f(params: &Params, id: &str) -> f64 {
|
||||
param(params, id).map(Value::as_f64).unwrap_or(0.0)
|
||||
}
|
||||
fn b(params: &Params, id: &str) -> bool {
|
||||
param(params, id).map(Value::as_bool).unwrap_or(false)
|
||||
}
|
||||
fn v2(params: &Params, id: &str) -> Option<[f64; 2]> {
|
||||
let v = param(params, id)?.as_vec2();
|
||||
v.iter().all(|c| c.is_finite()).then_some(v)
|
||||
}
|
||||
fn s<'a>(params: &'a Params, id: &str) -> &'a str {
|
||||
match param(params, id) {
|
||||
Some(Value::Str(s)) => s,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
fn fnv(h: &mut u64, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
*h ^= *b as u64;
|
||||
*h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame count parameter (finite, clamped to `lo..=hi`).
|
||||
fn frames(params: &Params, id: &str, lo: f64, hi: f64) -> i64 {
|
||||
let v = f(params, id);
|
||||
if v.is_finite() { v.round().clamp(lo, hi) as i64 } else { 0 }
|
||||
}
|
||||
|
||||
/// The reference frame (layer frame).
|
||||
pub fn reference_frame(params: &Params) -> i64 {
|
||||
frames(params, "objectTracking/referenceFrame", -1e9, 1e9)
|
||||
}
|
||||
|
||||
/// Frames Before / After (finite, clamped to `0..=MAX_REACH`).
|
||||
pub fn reach(params: &Params) -> [i64; 2] {
|
||||
[frames(params, "objectTracking/framesBefore", 0.0, MAX_REACH), frames(params, "objectTracking/framesAfter", 0.0, MAX_REACH)]
|
||||
}
|
||||
|
||||
/// Whether the matte is carried from the reference frame (else every frame is segmented on its
|
||||
/// own).
|
||||
pub fn tracks(params: &Params) -> bool {
|
||||
b(params, "objectTracking/trackObject")
|
||||
}
|
||||
|
||||
/// The prompt as Roto Brush strokes on layer frame `frame`: the Object Point as a foreground
|
||||
/// stroke; the box as a box stroke (the model's box prompt) with a model, its edges as
|
||||
/// background strokes for the graph cut without one; without a box, the layer's border when
|
||||
/// there is no model (the graph cut needs background samples; a model does not, and a border
|
||||
/// stroke would cut objects touching the frame edge). `None` when the point is unusable.
|
||||
pub fn prompt_strokes(params: &Params, layer_size: [f64; 2], frame: i64, with_model: bool) -> Option<Vec<Stroke>> {
|
||||
let [w, h] = layer_size;
|
||||
if !(w.is_finite() && h.is_finite() && w >= 1.0 && h >= 1.0) {
|
||||
return None;
|
||||
}
|
||||
let pt = v2(params, "objectPoint")?;
|
||||
let inside = |q: [f64; 2]| q[0] >= 0.0 && q[1] >= 0.0 && q[0] <= w && q[1] <= h;
|
||||
if !inside(pt) {
|
||||
return None;
|
||||
}
|
||||
let mut out = vec![Stroke { kind: StrokeKind::Fg, frame, radius: POINT_RADIUS, points: vec![pt] }];
|
||||
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]];
|
||||
let boxed = b(params, "useBox").then(|| Some((v2(params, "boxTopLeft")?, v2(params, "boxBottomRight")?))).flatten();
|
||||
match boxed {
|
||||
Some((a, c)) => {
|
||||
let (x0, x1) = (a[0].min(c[0]).clamp(0.0, w), a[0].max(c[0]).clamp(0.0, w));
|
||||
let (y0, y1) = (a[1].min(c[1]).clamp(0.0, h), a[1].max(c[1]).clamp(0.0, h));
|
||||
// The point must lie inside the box, clear of its edges, for the box to mean anything.
|
||||
let m = POINT_RADIUS + EDGE_RADIUS;
|
||||
if pt[0] - m <= x0 || pt[0] + m >= x1 || pt[1] - m <= y0 || pt[1] + m >= y1 {
|
||||
return None;
|
||||
}
|
||||
out.push(if with_model {
|
||||
// The model takes the box itself as its box prompt.
|
||||
Stroke { kind: StrokeKind::Box, frame, radius: 0.0, points: vec![[x0, y0], [x1, y1]] }
|
||||
} else {
|
||||
Stroke { kind: StrokeKind::Bg, frame, radius: EDGE_RADIUS, points: rect(x0, y0, x1, y1) }
|
||||
});
|
||||
}
|
||||
None if !with_model => {
|
||||
let i = EDGE_RADIUS;
|
||||
if w <= 4.0 * i || h <= 4.0 * i {
|
||||
return None;
|
||||
}
|
||||
out.push(Stroke { kind: StrokeKind::Bg, frame, radius: EDGE_RADIUS, points: rect(i, i, w - i, h - i) });
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The segmentation data the matte of layer frame `f` comes from: with Track Object, the prompt
|
||||
/// on the reference frame and the span it is carried over; otherwise the prompt on `f` alone.
|
||||
pub fn roto_data(params: &Params, layer_size: [f64; 2], f: i64, with_model: bool) -> Option<RotoData> {
|
||||
if tracks(params) {
|
||||
let base = reference_frame(params);
|
||||
let [before, after] = reach(params);
|
||||
let strokes = prompt_strokes(params, layer_size, base, with_model)?;
|
||||
Some(RotoData { base: Some(base), span: [base.saturating_sub(before), base.saturating_add(after)], strokes })
|
||||
} else {
|
||||
Some(RotoData { base: Some(f), span: [f, f], strokes: prompt_strokes(params, layer_size, f, with_model)? })
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed of the chain keys: what the frames are (the Input Key), the layer size, the frame rate,
|
||||
/// the mode and the model. The prompt is in each frame's key.
|
||||
pub fn seed(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn MaskModel>) -> u64 {
|
||||
let mut h = 0xcbf2_9ce4_8422_2325;
|
||||
fnv(&mut h, ID.as_bytes());
|
||||
fnv(&mut h, s(params, INPUT_KEY).as_bytes());
|
||||
for v in [layer_size[0], layer_size[1], fps] {
|
||||
fnv(&mut h, &v.to_bits().to_le_bytes());
|
||||
}
|
||||
fnv(&mut h, &[tracks(params) as u8]);
|
||||
fnv(&mut h, model.map_or(effectcraft_segment::CLASSICAL, |m| m.info().id).as_bytes());
|
||||
h
|
||||
}
|
||||
|
||||
/// The layer frames a background job computes, outward from the reference frame: the tracked
|
||||
/// span (Frames Before / After around it), clipped to `limits` (the layer's frames). Without
|
||||
/// Track Object, the same frames, each segmented on its own.
|
||||
pub fn job_frames(params: &Params, limits: [i64; 2]) -> Vec<i64> {
|
||||
let base = reference_frame(params);
|
||||
let [before, after] = reach(params);
|
||||
let (lo, hi) = (base.saturating_sub(before).max(limits[0]), base.saturating_add(after).min(limits[1]));
|
||||
if base < limits[0] || base > limits[1] {
|
||||
return vec![];
|
||||
}
|
||||
let mut v = vec![base];
|
||||
v.extend(base.saturating_add(1)..=hi);
|
||||
v.extend((lo..base).rev());
|
||||
v
|
||||
}
|
||||
|
||||
/// The segmentation chain the matte of layer frame `f` comes from (`None`: no usable prompt).
|
||||
pub fn chain(params: &Params, layer_size: [f64; 2], fps: f64, f: i64, scale: f64, model: Option<Arc<dyn MaskModel>>) -> Option<Chain> {
|
||||
let data = roto_data(params, layer_size, f, model.is_some())?;
|
||||
let keys = data.chain_keys(seed(params, layer_size, fps, model.as_deref()));
|
||||
Some(Chain { data: Arc::new(data), keys, opts: seg_opts(scale), refine_radius: 0.0, model })
|
||||
}
|
||||
|
||||
/// Frame `f`'s segmentation at full resolution, computing what is missing (the background
|
||||
/// job's step). `None` outside the tracked span, without a prompt, or when cancelled.
|
||||
pub fn ensure(
|
||||
params: &Params,
|
||||
layer_size: [f64; 2],
|
||||
fps: f64,
|
||||
f: i64,
|
||||
model: Option<Arc<dyn MaskModel>>,
|
||||
frame: &mut dyn FnMut(i64) -> Option<Arc<Image>>,
|
||||
cancel: &dyn Fn() -> bool,
|
||||
) -> Option<Arc<FrameSeg>> {
|
||||
let ch = chain(params, layer_size, fps, f, 1.0, model)?;
|
||||
if !ch.data.in_span(f) {
|
||||
return None;
|
||||
}
|
||||
ch.ensure(f, frame, cancel)
|
||||
}
|
||||
|
||||
/// The chain key of each of `frames` (what a computed segmentation is cached under).
|
||||
pub fn frame_keys(params: &Params, layer_size: [f64; 2], fps: f64, frames: &[i64], model: Option<Arc<dyn MaskModel>>) -> Vec<(i64, u64)> {
|
||||
if tracks(params) {
|
||||
let Some(ch) = chain(params, layer_size, fps, 0, 1.0, model) else { return vec![] };
|
||||
return frames.iter().filter_map(|f| Some((*f, *ch.keys.get(f)?))).collect();
|
||||
}
|
||||
frames.iter().filter_map(|f| Some((*f, *chain(params, layer_size, fps, *f, 1.0, model.clone())?.keys.get(f)?))).collect()
|
||||
}
|
||||
|
||||
/// What frozen mattes depend on: what the frames are (the seed: Input Key, size, rate, mode,
|
||||
/// model), the prompt, the tracked span and the matte settings.
|
||||
pub fn frozen_key(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn MaskModel>) -> String {
|
||||
let mut h = seed(params, layer_size, fps, model);
|
||||
let base = reference_frame(params);
|
||||
if let Some(st) = prompt_strokes(params, layer_size, base, model.is_some()) {
|
||||
fnv(&mut h, serde_json::to_string(&st).unwrap_or_default().as_bytes());
|
||||
}
|
||||
for v in [base, reach(params)[0], reach(params)[1]] {
|
||||
fnv(&mut h, &v.to_le_bytes());
|
||||
}
|
||||
fnv(&mut h, format!("{:?}", matte_params(params)).as_bytes());
|
||||
format!("{h:016x}")
|
||||
}
|
||||
|
||||
/// Whether the instance is frozen (has frozen mattes).
|
||||
pub fn is_frozen(params: &Params) -> bool {
|
||||
!s(params, FROZEN).is_empty()
|
||||
}
|
||||
|
||||
/// Frame `f`'s frozen matte on a `w`×`h` grid, when the instance is frozen, the mattes still
|
||||
/// match ([`frozen_key`]) and `f` is one of them.
|
||||
pub fn frozen_alpha(params: &Params, layer_size: [f64; 2], fps: f64, f: i64, w: usize, h: usize, model: Option<&dyn MaskModel>) -> Option<Vec<f32>> {
|
||||
let j = s(params, FROZEN);
|
||||
if j.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fc = frozen_cache(j)?;
|
||||
if fc.key != frozen_key(params, layer_size, fps, model) {
|
||||
return None;
|
||||
}
|
||||
let fr = fc.frames.get(&f)?;
|
||||
let a = rle::decode(&fr.a)?;
|
||||
let [fw, fh] = fc.size;
|
||||
if fw == 0 || fh == 0 || a.len() != fw.checked_mul(fh)? {
|
||||
return None;
|
||||
}
|
||||
let af: Vec<f32> = a.iter().map(|v| *v as f32 / 255.0).collect();
|
||||
if fw == w && fh == h {
|
||||
return Some(af);
|
||||
}
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let (sx, sy) = ((x as f64 + 0.5) * fw as f64 / w as f64, (y as f64 + 0.5) * fh as f64 / h as f64);
|
||||
out[y * w + x] = effectcraft_track::roto::matting::sample(&af, fw, fh, sx, sy);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The parsed Frozen parameter (parsed once per content).
|
||||
fn frozen_cache(j: &str) -> Option<Arc<FrozenCache>> {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static C: OnceLock<Mutex<HashMap<u64, Arc<FrozenCache>>>> = OnceLock::new();
|
||||
let mut h = 0xcbf2_9ce4_8422_2325;
|
||||
fnv(&mut h, j.as_bytes());
|
||||
let c = C.get_or_init(Default::default);
|
||||
if let Some(d) = c.lock().unwrap_or_else(|e| e.into_inner()).get(&h) {
|
||||
return Some(d.clone());
|
||||
}
|
||||
let d = Arc::new(FrozenCache::from_json(j)?);
|
||||
let mut m = c.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if m.len() > 8 {
|
||||
m.clear();
|
||||
}
|
||||
m.insert(h, d.clone());
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Segmentation settings at `scale` (Roto Brush's defaults).
|
||||
fn seg_opts(scale: f64) -> SegOpts {
|
||||
SegOpts { scale, search_radius: 15.0, motion_threshold: 10.0, motion_damping: 20.0, best: false }
|
||||
}
|
||||
|
||||
/// Matte settings: Feather, Contrast, Shift Edge (no Refine Edge band).
|
||||
pub fn matte_params(params: &Params) -> MatteParams {
|
||||
let num = |id: &str| {
|
||||
let v = f(params, id);
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
};
|
||||
MatteParams {
|
||||
rb_feather: num("objectMatte/feather").clamp(0.0, 100.0),
|
||||
rb_contrast: num("objectMatte/contrast").clamp(0.0, 100.0),
|
||||
rb_shift: num("objectMatte/shiftEdge").clamp(-100.0, 100.0),
|
||||
decontaminate: false,
|
||||
..MatteParams::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a frame's matte is: the object's alpha on the layer grid, or why there is none.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FrameMatte {
|
||||
/// The object's alpha (0–1) on the frame's layer grid.
|
||||
Alpha(Vec<f32>),
|
||||
/// The prompt is unusable (point outside the layer, outside the box…): the layer passes.
|
||||
NoPrompt,
|
||||
/// The frame is beyond the tracked range, or its matte could not be computed.
|
||||
Outside,
|
||||
}
|
||||
|
||||
/// The matte of layer frame `f` on the layer grid of `img` (the effect's input on that frame at
|
||||
/// `scale`), computing what is missing. `frame(g)`: the input on frame g on the same grid.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn frame_matte(
|
||||
params: &Params,
|
||||
layer_size: [f64; 2],
|
||||
fps: f64,
|
||||
f: i64,
|
||||
scale: f64,
|
||||
img: &Image,
|
||||
model: Option<Arc<dyn MaskModel>>,
|
||||
frame: &mut dyn FnMut(i64) -> Option<Arc<Image>>,
|
||||
cancel: &dyn Fn() -> bool,
|
||||
) -> FrameMatte {
|
||||
let Some(chain) = chain(params, layer_size, fps, f, scale, model) else { return FrameMatte::NoPrompt };
|
||||
if !chain.data.in_span(f) {
|
||||
return FrameMatte::Outside;
|
||||
}
|
||||
let Some(seg) = chain.ensure(f, frame, cancel) else { return FrameMatte::Outside };
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let seg = if seg.w == w && seg.h == h { (*seg).clone() } else { roto::resample(&seg, w, h) };
|
||||
FrameMatte::Alpha(roto::final_alpha(img, &seg, None, None, &matte_params(params), 0.0, scale))
|
||||
}
|
||||
|
||||
fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
if ctx.adjustment {
|
||||
return buf;
|
||||
}
|
||||
let fps = ctx.fps();
|
||||
let f = roto::frame_of(ctx.time, fps);
|
||||
let sc = if buf.scale > 0.0 { buf.scale } else { 1.0 };
|
||||
let img = Arc::new(roto::layer_grid(&buf, ctx.layer_size));
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let host = ctx.env.host;
|
||||
let effects = ctx.env.effect_index;
|
||||
let layer_size = ctx.layer_size;
|
||||
let me = img.clone();
|
||||
let mut frame = |g: i64| -> Option<Arc<Image>> {
|
||||
if g == f {
|
||||
return Some(me.clone());
|
||||
}
|
||||
let other = host?.self_at(g as f64 / fps, effects)?;
|
||||
let im = roto::layer_grid(&other, layer_size);
|
||||
(im.width as usize == w && im.height as usize == h).then(|| Arc::new(im))
|
||||
};
|
||||
let model = roto::installed_model();
|
||||
// Frozen mattes are used as they are (no segmentation).
|
||||
if let Some(a) = frozen_alpha(ctx.params, layer_size, fps, f, w, h, model.as_deref()) {
|
||||
return compose(&buf, Some(&a), w, h, b(ctx.params, "invert"), param(ctx.params, "view").map(Value::as_enum).unwrap_or(0) == 1);
|
||||
}
|
||||
let alpha = match frame_matte(ctx.params, layer_size, fps, f, sc, &img, model, &mut frame, &|| false) {
|
||||
FrameMatte::Alpha(a) if a.len() == w * h => Some(a),
|
||||
FrameMatte::NoPrompt => return buf,
|
||||
_ => None,
|
||||
};
|
||||
compose(&buf, alpha.as_deref(), w, h, b(ctx.params, "invert"), param(ctx.params, "view").map(Value::as_enum).unwrap_or(0) == 1)
|
||||
}
|
||||
|
||||
/// The output: the input keyed by the matte (`None`: no object, all zero), or the matte itself.
|
||||
fn compose(buf: &Buf, alpha: Option<&[f32]>, w: usize, h: usize, invert: bool, view_matte: bool) -> Buf {
|
||||
let (ox, oy) = (buf.offset[0].round() as i64, buf.offset[1].round() as i64);
|
||||
let mut out = Buf { img: Image::new(buf.img.width, buf.img.height), offset: buf.offset, scale: buf.scale };
|
||||
out.img.rows_mut().for_each(|(by, row)| {
|
||||
for (bx, px) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (bx as i64 - ox, by as i64 - oy);
|
||||
let a = if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h {
|
||||
alpha.and_then(|a| a.get(y as usize * w + x as usize)).copied().unwrap_or(0.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let a = if invert { 1.0 - a } else { a }.clamp(0.0, 1.0);
|
||||
let src = buf.img.get(bx as i64, by as i64);
|
||||
*px = if view_matte {
|
||||
let v = a * src[3];
|
||||
[v, v, v, 1.0]
|
||||
} else {
|
||||
[src[0] * a, src[1] * a, src[2] * a, src[3] * a]
|
||||
};
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, EffectHost, LayerPixels};
|
||||
|
||||
/// A red disk of radius 15 moving 2 px a frame right over a textured blue background
|
||||
/// (100×80, 25 fps), plus a still green square in the corner.
|
||||
fn frame_at(fi: i64) -> Image {
|
||||
let c = [40.0 + 2.0 * fi as f64, 40.0];
|
||||
let mut img = Image::new(100, 80);
|
||||
for y in 0..80 {
|
||||
for x in 0..100 {
|
||||
let d = ((x as f64 + 0.5 - c[0]).hypot(y as f64 + 0.5 - c[1])) - 15.0;
|
||||
let a = (0.5 - d).clamp(0.0, 1.0) as f32;
|
||||
let tex = ((x * 7 + y * 13) % 9) as f32 / 60.0;
|
||||
let bg = if x >= 80 && y >= 60 { [0.1, 0.8, 0.2] } else { [0.1, 0.4 + tex, 0.7] };
|
||||
let fg = [0.85 + tex, 0.2, 0.1];
|
||||
img.set(x, y, [fg[0] * a + bg[0] * (1.0 - a), fg[1] * a + bg[1] * (1.0 - a), fg[2] * a + bg[2] * (1.0 - a), 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
fn frame_of_time(t: f64) -> Image {
|
||||
frame_at((t * 25.0 + 1e-6).floor() as i64)
|
||||
}
|
||||
|
||||
struct Seq;
|
||||
impl EffectHost for Seq {
|
||||
fn layer(&self, _: u64, _: bool) -> Option<LayerPixels> {
|
||||
None
|
||||
}
|
||||
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
fn self_at(&self, t: f64, _: usize) -> Option<Buf> {
|
||||
Some(Buf { img: frame_of_time(t), offset: [0.0; 2], scale: 1.0 })
|
||||
}
|
||||
}
|
||||
|
||||
fn params(vals: &[(&str, Value)]) -> Params {
|
||||
let s = &specs()[0];
|
||||
let mut p = Params { values: s.params.iter().map(|p| (p.id.to_string(), crate::default_value(p, [100.0, 80.0]))).collect() };
|
||||
for (k, v) in vals {
|
||||
p.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn run(p: &Params, fi: i64) -> Image {
|
||||
let host = Seq;
|
||||
let t = fi as f64 / 25.0 + 0.001;
|
||||
let ctx = EffectCtx {
|
||||
params: p,
|
||||
time: t,
|
||||
layer_size: [100.0, 80.0],
|
||||
seed: 1,
|
||||
adjustment: false,
|
||||
env: EffectEnv { host: Some(&host), frame_rate: 25.0, ..Default::default() },
|
||||
};
|
||||
crate::apply(&specs()[0], &ctx, Buf { img: frame_of_time(t), offset: [0.0; 2], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
/// Pixels whose alpha disagrees with the disk centred at `cx` (1 px of slack at the edge).
|
||||
fn wrong(out: &Image, cx: f64) -> usize {
|
||||
let mut n = 0;
|
||||
for y in 0..80u32 {
|
||||
for x in 0..100u32 {
|
||||
let d = (x as f64 + 0.5 - cx).hypot(y as f64 + 0.5 - 40.0);
|
||||
let a = out.data[(y * 100 + x) as usize][3];
|
||||
if (d < 14.0 && a < 0.5) || (d > 16.0 && a > 0.5) {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_isolates_the_object_and_tracks_it() {
|
||||
let p = params(&[("objectPoint", Value::Vec2([40.0, 40.0]))]);
|
||||
// The reference frame: the disk, nothing else.
|
||||
let out = run(&p, 0);
|
||||
assert!(wrong(&out, 40.0) < 20, "{} wrong pixels on the reference frame", wrong(&out, 40.0));
|
||||
// Six frames on (carried through frames 1–5), the disk has moved 12 px and the matte with it.
|
||||
let out = run(&p, 6);
|
||||
assert!(wrong(&out, 52.0) < 30, "{} wrong pixels on frame 6", wrong(&out, 52.0));
|
||||
// Beyond Frames After: no matte.
|
||||
let p2 = params(&[("objectPoint", Value::Vec2([40.0, 40.0])), ("objectTracking/framesAfter", Value::Scalar(3.0))]);
|
||||
assert!(run(&p2, 6).data.iter().all(|px| px[3] == 0.0));
|
||||
// Invert keeps everything but the disk; View ▸ Matte shows it in grey, opaque.
|
||||
let inv = run(¶ms(&[("objectPoint", Value::Vec2([40.0, 40.0])), ("invert", Value::Bool(true))]), 0);
|
||||
assert!(inv.data[40 * 100 + 40][3] < 0.5 && inv.data[5 * 100 + 95][3] > 0.5);
|
||||
let m = run(¶ms(&[("objectPoint", Value::Vec2([40.0, 40.0])), ("view", Value::Enum(1))]), 0);
|
||||
assert!(m.data[40 * 100 + 40][0] > 0.5 && m.data[5 * 100 + 95][0] < 0.5 && m.data.iter().all(|px| px[3] == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_tracking_every_frame_follows_the_prompt() {
|
||||
// The point animated onto the disk at frame 9: frame 9 is segmented from it alone.
|
||||
let p = params(&[("objectPoint", Value::Vec2([58.0, 40.0])), ("objectTracking/trackObject", Value::Bool(false))]);
|
||||
let out = run(&p, 9);
|
||||
assert!(wrong(&out, 58.0) < 20, "{} wrong pixels", wrong(&out, 58.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_and_bad_prompts() {
|
||||
// A box around the green square, the point in it: the square, not the disk.
|
||||
let p = params(&[
|
||||
("objectPoint", Value::Vec2([90.0, 70.0])),
|
||||
("useBox", Value::Bool(true)),
|
||||
("boxTopLeft", Value::Vec2([74.0, 54.0])),
|
||||
("boxBottomRight", Value::Vec2([100.0, 80.0])),
|
||||
]);
|
||||
let out = run(&p, 0);
|
||||
assert!(out.data[70 * 100 + 90][3] > 0.5 && out.data[40 * 100 + 40][3] < 0.5);
|
||||
// Unusable prompts pass the layer through instead of failing: a point off the layer, a
|
||||
// non-finite point, a point outside its box.
|
||||
let src = frame_at(0);
|
||||
for vals in [
|
||||
vec![("objectPoint", Value::Vec2([-5.0, 40.0]))],
|
||||
vec![("objectPoint", Value::Vec2([f64::NAN, 40.0]))],
|
||||
vec![
|
||||
("objectPoint", Value::Vec2([40.0, 40.0])),
|
||||
("useBox", Value::Bool(true)),
|
||||
("boxTopLeft", Value::Vec2([60.0, 10.0])),
|
||||
("boxBottomRight", Value::Vec2([90.0, 30.0])),
|
||||
],
|
||||
] {
|
||||
let p = params(&vals);
|
||||
assert_eq!(run(&p, 0).data, src.data, "{vals:?}");
|
||||
}
|
||||
// A huge reference frame or reach doesn't overflow.
|
||||
let p = params(&[("objectTracking/referenceFrame", Value::Scalar(1e300)), ("objectTracking/framesBefore", Value::Scalar(f64::INFINITY))]);
|
||||
assert!(run(&p, 0).data.iter().all(|px| px[3] == 0.0));
|
||||
}
|
||||
|
||||
/// A stand-in model (the weights are an optional download): a disk around the first
|
||||
/// foreground point, radius 15, so the test sees the model's answer in the matte.
|
||||
#[derive(Default)]
|
||||
struct Stub {
|
||||
calls: std::sync::atomic::AtomicUsize,
|
||||
/// The box prompt of the last call.
|
||||
bbox: std::sync::Mutex<Option<[f32; 4]>>,
|
||||
}
|
||||
impl MaskModel for Stub {
|
||||
fn info(&self) -> &'static effectcraft_segment::ModelInfo {
|
||||
&effectcraft_segment::MOBILE_SAM
|
||||
}
|
||||
fn segment(&self, _: &[[f32; 3]], w: usize, h: usize, prompt: &effectcraft_segment::Prompt) -> effectcraft_segment::Result<Vec<f32>> {
|
||||
self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
*self.bbox.lock().unwrap() = prompt.bbox;
|
||||
let Some(([cx, cy], _)) = prompt.points.iter().find(|(_, fg)| *fg) else { return Err("no point".into()) };
|
||||
Ok((0..w * h).map(|i| (((i % w) as f32 + 0.5 - cx).hypot((i / w) as f32 + 0.5 - cy) < 15.0) as u8 as f32).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn segments_with_the_installed_model_without_a_border_stroke() {
|
||||
let p = params(&[("objectPoint", Value::Vec2([40.0, 40.0]))]);
|
||||
// With a model, no border stroke: an object touching the frame edge stays whole.
|
||||
assert_eq!(prompt_strokes(&p, [100.0, 80.0], 0, true).map(|s| s.len()), Some(1));
|
||||
assert_eq!(prompt_strokes(&p, [100.0, 80.0], 0, false).map(|s| s.len()), Some(2));
|
||||
// The model's answer is part of the cache key, and drives the matte.
|
||||
let stub = Arc::new(Stub::default());
|
||||
assert_ne!(seed(&p, [100.0, 80.0], 25.0, Some(stub.as_ref())), seed(&p, [100.0, 80.0], 25.0, None));
|
||||
let img = frame_at(0);
|
||||
let mut frame = |g: i64| Some(Arc::new(frame_at(g)));
|
||||
let FrameMatte::Alpha(a) = frame_matte(&p, [100.0, 80.0], 25.0, 0, 1.0, &img, Some(stub.clone()), &mut frame, &|| false) else { panic!("no matte") };
|
||||
assert!(a[40 * 100 + 40] > 0.5 && a[5 * 100 + 5] < 0.5);
|
||||
assert_eq!(stub.calls.load(std::sync::atomic::Ordering::Relaxed), 1);
|
||||
assert_eq!(*stub.bbox.lock().unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_box_reaches_the_model_as_a_box_prompt() {
|
||||
let p = params(&[
|
||||
("objectPoint", Value::Vec2([90.0, 70.0])),
|
||||
("useBox", Value::Bool(true)),
|
||||
("boxTopLeft", Value::Vec2([100.0, 80.0])),
|
||||
("boxBottomRight", Value::Vec2([74.0, 54.0])),
|
||||
]);
|
||||
// With a model: the point and a box stroke (corners ordered); without: the box's edges
|
||||
// as a background stroke, as before.
|
||||
let with = prompt_strokes(&p, [100.0, 80.0], 0, true).unwrap();
|
||||
assert_eq!(with.iter().map(|s| s.kind).collect::<Vec<_>>(), [StrokeKind::Fg, StrokeKind::Box]);
|
||||
assert_eq!(with[1].points, [[74.0, 54.0], [100.0, 80.0]]);
|
||||
let without = prompt_strokes(&p, [100.0, 80.0], 0, false).unwrap();
|
||||
assert_eq!(without.iter().map(|s| s.kind).collect::<Vec<_>>(), [StrokeKind::Fg, StrokeKind::Bg]);
|
||||
// The model is called with the box itself (matte pixels at scale 1) and only one
|
||||
// foreground point: no background points along the edges.
|
||||
let stub = Arc::new(Stub::default());
|
||||
let img = frame_at(0);
|
||||
let mut frame = |g: i64| Some(Arc::new(frame_at(g)));
|
||||
let FrameMatte::Alpha(a) = frame_matte(&p, [100.0, 80.0], 25.0, 0, 1.0, &img, Some(stub.clone()), &mut frame, &|| false) else { panic!("no matte") };
|
||||
assert_eq!(*stub.bbox.lock().unwrap(), Some([74.0, 54.0, 100.0, 80.0]));
|
||||
assert!(a[70 * 100 + 90] > 0.5 && a[40 * 100 + 40] < 0.5);
|
||||
// At half resolution the box is scaled with the frame (another Input Key, so the
|
||||
// full-resolution result above is not reused).
|
||||
let mut p = p;
|
||||
p.values.insert(INPUT_KEY.into(), Value::Str("half".into()));
|
||||
let half = effectcraft_raster::resample(&img, 50, 40);
|
||||
let mut frame = |g: i64| Some(Arc::new(effectcraft_raster::resample(&frame_at(g), 50, 40)));
|
||||
let _ = frame_matte(&p, [100.0, 80.0], 25.0, 0, 0.5, &half, Some(stub.clone()), &mut frame, &|| false);
|
||||
assert_eq!(*stub.bbox.lock().unwrap(), Some([37.0, 27.0, 50.0, 40.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_frames_go_outward_from_the_reference_frame_inside_the_layer() {
|
||||
let p = params(&[
|
||||
("objectTracking/referenceFrame", Value::Scalar(5.0)),
|
||||
("objectTracking/framesBefore", Value::Scalar(2.0)),
|
||||
("objectTracking/framesAfter", Value::Scalar(3.0)),
|
||||
]);
|
||||
assert_eq!(job_frames(&p, [0, 100]), [5, 6, 7, 8, 4, 3]);
|
||||
assert_eq!(job_frames(&p, [4, 6]), [5, 6, 4]);
|
||||
assert!(job_frames(&p, [10, 20]).is_empty());
|
||||
let huge = params(&[("objectTracking/referenceFrame", Value::Scalar(1e300)), ("objectTracking/framesAfter", Value::Scalar(f64::INFINITY))]);
|
||||
assert!(job_frames(&huge, [0, 100]).is_empty());
|
||||
}
|
||||
|
||||
/// Frozen mattes are used as stored while their key matches (no segmentation: a stored
|
||||
/// pattern the segmentation could never produce comes out), and ignored once it doesn't.
|
||||
#[test]
|
||||
fn frozen_mattes_are_used_while_their_key_matches() {
|
||||
let mut p = params(&[("objectPoint", Value::Vec2([40.0, 40.0])), ("objectTracking/framesAfter", Value::Scalar(3.0))]);
|
||||
p.values.insert(INPUT_KEY.into(), Value::Str("frozen-test".into()));
|
||||
// Left half opaque on frame 2.
|
||||
let alpha: Vec<f32> = (0..100 * 80).map(|i| ((i % 100) < 50) as u8 as f32).collect();
|
||||
let mut fc = FrozenCache { key: frozen_key(&p, [100.0, 80.0], 25.0, None), size: [100, 80], ..Default::default() };
|
||||
fc.frames.insert(2, roto::freeze_frame(&alpha, &[]));
|
||||
p.values.insert(FROZEN.into(), Value::Str(fc.to_json()));
|
||||
assert!(is_frozen(&p));
|
||||
let out = run(&p, 2);
|
||||
assert!(out.data[40 * 100 + 10][3] > 0.99 && out.data[40 * 100 + 90][3] < 0.01, "the frozen matte is used");
|
||||
// At half resolution too.
|
||||
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 50, 40, None).map(|a| (a[20 * 50 + 5], a[20 * 50 + 45])), Some((1.0, 0.0)));
|
||||
// A frame without a frozen matte is computed (the disk).
|
||||
assert!(wrong(&run(&p, 1), 42.0) < 30);
|
||||
// Another prompt: the frozen mattes no longer apply.
|
||||
p.values.insert("objectPoint".into(), Value::Vec2([41.0, 40.0]));
|
||||
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
|
||||
assert!(wrong(&run(&p, 2), 44.0) < 30);
|
||||
// Damaged frozen data is ignored, not a crash.
|
||||
p.values.insert(FROZEN.into(), Value::Str("{\"key\": 3, \"frames\": [".into()));
|
||||
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
|
||||
let mut fc2 = fc.clone();
|
||||
fc2.size = [usize::MAX, 2];
|
||||
p.values.insert("objectPoint".into(), Value::Vec2([40.0, 40.0]));
|
||||
p.values.insert(FROZEN.into(), Value::Str(fc2.to_json()));
|
||||
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
//! out to the frame), so it lives in a process-wide content-keyed cache ([`cached`]) that the
|
||||
//! engine's propagation job fills at full resolution and rendering fills on demand (reading
|
||||
//! neighbouring frames with [`crate::EffectHost::self_at`]). Undo, redo and reopening a project
|
||||
//! therefore never see stale mattes. **Freeze** stores the final mattes in the hidden **Frozen**
|
||||
//! therefore never see stale mattes. Behind the memory cache an optional [`SegStore`] (the
|
||||
//! persistent disk cache, set by the engine) keeps computed segmentations across restarts. **Freeze** stores the final mattes in the hidden **Frozen**
|
||||
//! parameter ([`FrozenCache`]); they are used while their key still matches.
|
||||
//!
|
||||
//! Rendering: binary segmentation → Roto Brush Matte (Shift Edge, Reduce Chatter, Feather,
|
||||
@@ -23,21 +24,21 @@
|
||||
//! higher working resolution with more iterations.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex, OnceLock, RwLock};
|
||||
use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_segment::MaskModel;
|
||||
use effectcraft_track::roto::refine::{self, MatteParams};
|
||||
use effectcraft_track::roto::{self as rb, FrameSeg, RotoData, SegOpts, rle};
|
||||
use effectcraft_track::roto::{self as rb, RotoData, SegOpts, rle};
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::warp_stab::param;
|
||||
use crate::{Buf, EffectCtx, EffectSpec, Params, num, p, popup, slider};
|
||||
|
||||
pub use effectcraft_track::roto::{Stroke, StrokeKind};
|
||||
pub use effectcraft_track::roto::{FrameSeg, Stroke, StrokeKind};
|
||||
|
||||
/// The effect's id.
|
||||
pub const ID: &str = "ec.matte.rotobrush";
|
||||
@@ -195,6 +196,12 @@ pub fn model_for(params: &Params) -> Option<Arc<dyn MaskModel>> {
|
||||
if e(params, "version") == 0 {
|
||||
return None;
|
||||
}
|
||||
installed_model()
|
||||
}
|
||||
|
||||
/// The trained model chosen in Settings ▸ Roto Brush, if one is installed (Roto Brush 2.0 / 3.0
|
||||
/// and Object Matte segment with it).
|
||||
pub fn installed_model() -> Option<Arc<dyn MaskModel>> {
|
||||
model_slot().read().ok().and_then(|m| m.clone())
|
||||
}
|
||||
|
||||
@@ -260,6 +267,37 @@ pub fn store(key: u64, scale: f64, seg: Arc<FrameSeg>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A second-level store for segmentations, keyed like the memory cache (chain key, scale): the
|
||||
/// persistent disk cache, so computed mattes survive the memory cache and restarts.
|
||||
pub trait SegStore: Send + Sync {
|
||||
fn get_seg(&self, key: u64, scale: f64) -> Option<FrameSeg>;
|
||||
fn put_seg(&self, key: u64, scale: f64, seg: &FrameSeg);
|
||||
}
|
||||
|
||||
fn seg_store_slot() -> &'static RwLock<Option<Weak<dyn SegStore>>> {
|
||||
static S: OnceLock<RwLock<Option<Weak<dyn SegStore>>>> = OnceLock::new();
|
||||
S.get_or_init(|| RwLock::new(None))
|
||||
}
|
||||
|
||||
/// Use `store` behind the memory cache (held weakly: once its owner drops it, e.g. the disk
|
||||
/// cache is switched off, it is no longer used). `None` turns it off.
|
||||
pub fn set_seg_store(store: Option<Weak<dyn SegStore>>) {
|
||||
if let Ok(mut s) = seg_store_slot().write() {
|
||||
*s = store;
|
||||
}
|
||||
}
|
||||
|
||||
fn seg_store() -> Option<Arc<dyn SegStore>> {
|
||||
seg_store_slot().read().ok()?.as_ref()?.upgrade()
|
||||
}
|
||||
|
||||
/// A segmentation from the second-level store, put into the memory cache.
|
||||
fn from_store(key: u64, scale: f64) -> Option<Arc<FrameSeg>> {
|
||||
let seg = Arc::new(seg_store()?.get_seg(key, scale)?);
|
||||
store(key, scale, seg.clone());
|
||||
Some(seg)
|
||||
}
|
||||
|
||||
/// Drop the cached segmentations of these chain keys (every scale).
|
||||
pub fn forget(keys: impl IntoIterator<Item = u64>) {
|
||||
let keys: std::collections::HashSet<u64> = keys.into_iter().collect();
|
||||
@@ -319,11 +357,11 @@ impl Chain {
|
||||
let sc = self.opts.scale;
|
||||
let lookup = |g: i64| -> Option<Arc<FrameSeg>> {
|
||||
let k = *self.keys.get(&g)?;
|
||||
if let Some(s) = cached(k, sc) {
|
||||
if let Some(s) = cached(k, sc).or_else(|| from_store(k, sc)) {
|
||||
return Some(s);
|
||||
}
|
||||
if sc != 1.0 {
|
||||
let full = cached(k, 1.0)?;
|
||||
let full = cached(k, 1.0).or_else(|| from_store(k, 1.0))?;
|
||||
let s = Arc::new(downscale(&full, sc));
|
||||
store(k, sc, s.clone());
|
||||
return Some(s);
|
||||
@@ -373,7 +411,11 @@ impl Chain {
|
||||
}
|
||||
};
|
||||
let seg = Arc::new(seg);
|
||||
store(*self.keys.get(&g)?, sc, seg.clone());
|
||||
let k = *self.keys.get(&g)?;
|
||||
store(k, sc, seg.clone());
|
||||
if let Some(st) = seg_store() {
|
||||
st.put_seg(k, sc, &seg);
|
||||
}
|
||||
cur = Some(seg);
|
||||
prev_img = Some(img);
|
||||
}
|
||||
@@ -392,7 +434,7 @@ pub fn downscale(s: &FrameSeg, scale: f64) -> FrameSeg {
|
||||
resample(s, w, h)
|
||||
}
|
||||
|
||||
fn resample(s: &FrameSeg, w: usize, h: usize) -> FrameSeg {
|
||||
pub(crate) fn resample(s: &FrameSeg, w: usize, h: usize) -> FrameSeg {
|
||||
if s.w == w && s.h == h {
|
||||
return s.clone();
|
||||
}
|
||||
|
||||
+31
-13
@@ -1196,18 +1196,9 @@ fn particle_world_plan(ctx: &EffectCtx, b: &Buf) -> Option<SpritePlan> {
|
||||
/// The CC particle systems' sprites with their Transfer Mode (Composite, Screen, Add, Black
|
||||
/// Background).
|
||||
fn particle_sprites(sprites: Vec<Sprite>, mode: u32) -> SpritePlan {
|
||||
SpritePlan {
|
||||
sprites,
|
||||
tints: vec![],
|
||||
acc: if mode == 2 { Acc::Add } else { Acc::Over },
|
||||
post: Post::Combine(match mode {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 5,
|
||||
_ => 0,
|
||||
}),
|
||||
}
|
||||
// The particles replace the layer (After Effects shows no trace of the source in any
|
||||
// Transfer Mode, which sets how the particles meet each other).
|
||||
SpritePlan { sprites, tints: vec![], acc: if mode == 2 { Acc::Add } else { Acc::Over }, post: Post::Replace }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Particle Systems II
|
||||
@@ -1920,8 +1911,35 @@ mod tests {
|
||||
let blank = Image::new(48, 48);
|
||||
let y = mass_y(&a, &blank);
|
||||
assert!((0.0..24.0).contains(&y), "{y}");
|
||||
// The particles replace the layer: with none born it is empty.
|
||||
let none = run("ec.sim.ccparticlesystems2", &[("birthRate", num(0.0))], grey(20, 20), 1.0);
|
||||
assert_eq!(none, grey(20, 20));
|
||||
assert_eq!(none, Image::new(20, 20));
|
||||
}
|
||||
|
||||
/// CC Particle World and CC Particle Systems II replace their layer with the particles, in
|
||||
/// every Transfer Mode (which only sets how particles meet each other). SceneYard frames from
|
||||
/// After Effects 2026 show no trace of the source solid: "Task Preparation UI" (black solids
|
||||
/// under fireworks hid a white page), "Burnout matchstick" (a red rectangle around the
|
||||
/// flame), "Documentary Man Falling" (a black block over the light).
|
||||
#[test]
|
||||
fn cc_particles_replace_their_layer() {
|
||||
let red = || {
|
||||
let mut img = Image::new(48, 48);
|
||||
img.data.iter_mut().for_each(|p| *p = [0.7, 0.1, 0.1, 1.0]);
|
||||
img
|
||||
};
|
||||
for id in ["ec.sim.ccparticlesystems2", "ec.sim.ccparticleworld"] {
|
||||
for mode in 0..4 {
|
||||
let v = vec![("birthRate", num(3.0)), ("particle/transferMode", Value::Enum(mode))];
|
||||
let _ = run(id, &v, red(), 0.5);
|
||||
let out = run(id, &v, red(), 1.0);
|
||||
// No source left: the corners, far from the producer, are clear.
|
||||
for (x, y) in [(0, 0), (47, 0), (0, 47), (47, 47)] {
|
||||
assert!(out.get(x, y)[3] < 1e-6, "{id} mode {mode} ({x},{y}): {:?}", out.get(x, y));
|
||||
}
|
||||
assert!(out.data.iter().any(|p| p[3] > 0.05), "{id} mode {mode}: particles drawn");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Time effects (Effect > Time): Echo, Posterize Time, Time Difference, Time Displacement,
|
||||
//! Timewarp, CC Force Motion Blur, CC Wide Time and Pixel Motion Blur.
|
||||
//!
|
||||
//! These read the layer at *other* layer times through [`EffectHost::self_at`] with zero
|
||||
//! preceding effects: like After Effects' Time effects they see the layer's source with its
|
||||
//! masks and ignore effects applied before them (precompose to include those). Without a host
|
||||
//! (tests, thumbnails) they pass their input through.
|
||||
//! These read the layer at *other* layer times through [`EffectHost::self_at`]: its source with
|
||||
//! its masks and the effects applied before them, as After Effects renders them (SceneYard:
|
||||
//! Echo after CC Particle Systems II echoes the fireworks, not the black solid under them;
|
||||
//! Posterize Time after Turbulent Displace steps the displacement). Without a host (tests,
|
||||
//! thumbnails) they pass their input through.
|
||||
//!
|
||||
//! Timewarp's Pixel Motion estimates block-matching optical flow between neighbouring frames
|
||||
//! ([`effectcraft_raster::flow`]); Pixel Motion Blur averages sub-frame samples.
|
||||
@@ -169,7 +170,8 @@ fn fetch(ctx: &EffectCtx, times: &[f64]) -> Option<Frames> {
|
||||
let mut uniq: Vec<i64> = times.iter().map(|t| (t * 1e6).round() as i64).collect();
|
||||
uniq.sort_unstable();
|
||||
uniq.dedup();
|
||||
let bufs: Vec<(i64, Option<Buf>)> = uniq.iter().map(|&k| (k, host.self_at(k as f64 / 1e6, 0))).collect();
|
||||
// Every effect before this one (the host bounds the count to them).
|
||||
let bufs: Vec<(i64, Option<Buf>)> = uniq.iter().map(|&k| (k, host.self_at(k as f64 / 1e6, usize::MAX))).collect();
|
||||
let first = bufs.iter().find_map(|(_, b)| b.as_ref())?;
|
||||
let scale = first.scale;
|
||||
// Union of every frame's extent in layer pixels (offset = where layer (0,0) sits).
|
||||
@@ -1014,7 +1016,8 @@ mod tests {
|
||||
None
|
||||
}
|
||||
fn self_at(&self, t: f64, effects: usize) -> Option<Buf> {
|
||||
assert_eq!(effects, 0);
|
||||
// Time effects see every effect before them.
|
||||
assert_eq!(effects, usize::MAX);
|
||||
let v = if self.static_layer { 0.4 } else { t as f32 };
|
||||
Some(Buf { img: Image::filled(6, 4, [v, v, v, 1.0]), offset: [0.0; 2], scale: 1.0 })
|
||||
}
|
||||
|
||||
@@ -334,34 +334,34 @@ fn particle_effects_golden_hashes() {
|
||||
|
||||
/// Pinned hashes (aarch64 macOS).
|
||||
const GOLDEN: &[(&str, u64)] = &[
|
||||
("ec.sim.ccparticleworld/0/8bpc/t0.5", 0x263d8f88e7ae651b),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t1.5", 0xb7697683e3cc6d43),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t0.8", 0xb5065326c8bd674a),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t2.2", 0x7f8eb5f2e8d38506),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t0.5", 0x6141abad89cd53ca),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t1.5", 0x2b5682e32bb3e916),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t0.8", 0xe6aaed9716d15c42),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t2.2", 0xa6e9a6f2acad94c0),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t0.5", 0xbb0b6803512a6b99),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t1.5", 0x70c578ea73992099),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t0.8", 0x2d26cb3f73a26b4f),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t2.2", 0x2b474438a48ee0e4),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t0.5", 0x294502dc827b0326),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t1.5", 0xf7874709f4012aaa),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t0.8", 0x87664ce9a05e67f9),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t2.2", 0x46e1b5162a0284f4),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t0.5", 0x02d8499e93133cb9),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t1.5", 0x97218172dec765c6),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t0.8", 0xee7da06e0b16e3b7),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t2.2", 0x6b9da0aa7d2a6abb),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t0.5", 0x71468ce82bba3cb2),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t1.5", 0x48595f55e8741a7e),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t0.8", 0x5ebc35e9eb02c8d7),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t2.2", 0xf9a0f63c72bd35f0),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t0.5", 0x757f80d45a2159b1),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t1.5", 0x7924f1cb9c8bf8c7),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t0.8", 0x22f507420a062c87),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t2.2", 0x41171121719a307a),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t0.5", 0x4444ad969d8a228e),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t1.5", 0xcad2aad73a6d603e),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t0.8", 0x513b356b746dacd0),
|
||||
("ec.sim.ccparticleworld/0/8bpc/t2.2", 0x6c1915f3f8282023),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t0.5", 0x41943ef09dec3b46),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t1.5", 0x9f90b72b4f674214),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t0.8", 0xecd3343277ff0ea8),
|
||||
("ec.sim.ccparticleworld/0/32bpc/t2.2", 0x7aff8cf24f352f11),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t0.5", 0x80dc4ec079743731),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t1.5", 0x79b651a929d56eba),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t0.8", 0xc537e2eae2138c98),
|
||||
("ec.sim.ccparticleworld/0/8bpc/half/t2.2", 0x6dec97915b8a85a0),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t0.5", 0xbe5fff3969b604b1),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t1.5", 0x0505795960f35d94),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t0.8", 0x7337a55ab762142d),
|
||||
("ec.sim.ccparticleworld/1/8bpc/t2.2", 0x82e9d79c843b8f73),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t0.5", 0x85e6f2dfa2cc2342),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t1.5", 0x3fc16468de930ff4),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t0.8", 0x0c8eede3cae44849),
|
||||
("ec.sim.ccparticleworld/1/32bpc/t2.2", 0xabbc670cfdf0bedf),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t0.5", 0x5dd6f8961dc8aa01),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t1.5", 0x6632451f98c2bb66),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t0.8", 0x9c9840445d995203),
|
||||
("ec.sim.ccparticleworld/2/8bpc/t2.2", 0xaa29bed036be7d9d),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t0.5", 0x7507310c57e5bc42),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t1.5", 0x6f0216e5fe64f20c),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t0.8", 0x0def6a02489d3bc7),
|
||||
("ec.sim.ccparticleworld/2/32bpc/t2.2", 0xb0d1af988e47a2d5),
|
||||
("ec.sim.ccparticleworld/3/8bpc/t0.5", 0xbca7e3d574cf5e37),
|
||||
("ec.sim.ccparticleworld/3/8bpc/t1.5", 0x5c4347a6c70b48ec),
|
||||
("ec.sim.ccparticleworld/3/8bpc/t0.8", 0xc79131dbaa8ff129),
|
||||
@@ -370,74 +370,74 @@ const GOLDEN: &[(&str, u64)] = &[
|
||||
("ec.sim.ccparticleworld/3/32bpc/t1.5", 0xf9751b9225a373a4),
|
||||
("ec.sim.ccparticleworld/3/32bpc/t0.8", 0xb6026343f72dfaeb),
|
||||
("ec.sim.ccparticleworld/3/32bpc/t2.2", 0x2f0e149de9623753),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t0.5", 0xd53dad7a75976197),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t1.5", 0x2cd0f3cbed038289),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t0.8", 0x46c089373ed50088),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t2.2", 0xfb17c5c3ba44657c),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t0.5", 0x80b338b7bb9794b1),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t1.5", 0x86811f65519e9790),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t0.8", 0x6aad5efc09bc64ff),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t2.2", 0x9957090d6fc97293),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t0.5", 0x56f989c5d7fc1eeb),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t1.5", 0x128313333a936e16),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t0.8", 0xa0efb8bdc0157788),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t2.2", 0x4af31455e2fe2631),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t0.5", 0xf3057d8cf6540f4a),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t1.5", 0x28203947d78e5ee3),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t0.8", 0xa6d8a9a848443344),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t2.2", 0xade682a437a4cba1),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t0.5", 0xa65b30a36baee78a),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t1.5", 0xbf7e4675fec18c48),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t0.8", 0xf98c7d9af9d6c9e2),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t2.2", 0xdf090357b8e4f471),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t0.5", 0x1721a9f149c922de),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t1.5", 0xf378db3b55dff048),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t0.8", 0x72a5d8dc0ea744ad),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t2.2", 0xfbb8e14088bb51ef),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t0.5", 0xc56801146ef15811),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t1.5", 0x3ca9b694e5e55f82),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t0.8", 0x2d72c095e0be6f47),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t2.2", 0x135b14387e6ea480),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t0.5", 0xad79b2f2d63d0c45),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t1.5", 0x902c6b68c6ed615d),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t0.8", 0x45045d7931c23788),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t2.2", 0xd8f8883374a3784f),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t0.5", 0xb681fe6e20dccbf3),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t1.5", 0xfa78174cb4fa5cd4),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t0.8", 0xd4f486333d843f09),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t2.2", 0xbee37590ce17b8b4),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t0.5", 0xccf4339bc42c3c01),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t1.5", 0xc51a8ee4e3c4a826),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t0.8", 0xee3d66e0c4ffb0ec),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t2.2", 0x449fc6d506e837fb),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t0.5", 0x3edb24bfeab4b00a),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t1.5", 0x78cb639f211cbd5b),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t0.8", 0x634c71924e4c68f1),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t2.2", 0xe09d41dcb6286423),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t0.5", 0xacdb6aec643a9bba),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t1.5", 0x4c50991034336999),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t0.8", 0xaacc2ea722f2e9e3),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t2.2", 0x1a5f7fc66db90a83),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t0.5", 0x8c89f83a2829dba1),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t1.5", 0x9239cd8895757d17),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t0.8", 0x91a16fb0a382d8e1),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t2.2", 0xc86d8250fe1402c5),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t0.5", 0xabade8d131837f05),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t1.5", 0x6a3566257b9a0bad),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t0.8", 0xc1199f209bad5c33),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t2.2", 0xaf337959d8264a5f),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t0.5", 0xb1816c2e5562be88),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t1.5", 0x02413f0ec8284e39),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t0.8", 0xd9bc645b90055a9a),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t2.2", 0x2c788bb5816167a3),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t0.5", 0xe18fd350f7155fc8),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t1.5", 0x956e03e2c83c3899),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t0.8", 0x7d16738562170622),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t2.2", 0x4e5838737bda7317),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t0.5", 0x27d909b24d165f6c),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t1.5", 0x47fb5492c0bcb748),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t0.8", 0x7dd63be8a11f4d71),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t2.2", 0x139259fc5f942375),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t0.5", 0xdfd4cff821add47f),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t1.5", 0x4ed5d9c97c8b323e),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t0.8", 0x13c8b1929529a4b1),
|
||||
("ec.sim.ccparticleworld/4/8bpc/t2.2", 0xd9702ad6bbd34752),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t0.5", 0xabb4834618b86cb8),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t1.5", 0x54de0787c35112ff),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t0.8", 0xfe9ed5ed6c1fd8bd),
|
||||
("ec.sim.ccparticleworld/4/32bpc/t2.2", 0x8278e2b011770e33),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t0.5", 0x11abba82d18e4540),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t1.5", 0x1be834f3d8d64464),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t0.8", 0xf3ad76cb0f38394d),
|
||||
("ec.sim.ccparticleworld/5/8bpc/t2.2", 0x64e10ae00b8e48e5),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t0.5", 0xc5d6ad16b9b6f662),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t1.5", 0xcb7b7777e8ba0ea1),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t0.8", 0x09692a677eed64fc),
|
||||
("ec.sim.ccparticleworld/5/32bpc/t2.2", 0x63e921f1dd7b52bc),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t0.5", 0xa954ad832566044b),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t1.5", 0x27fd580241299755),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t0.8", 0x8749025b3c953f71),
|
||||
("ec.sim.ccparticleworld/6/8bpc/t2.2", 0xd01aff9a0712e02d),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t0.5", 0xd2213ab758ed6cb9),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t1.5", 0xa7287da977d06904),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t0.8", 0xd02d00dc0e651852),
|
||||
("ec.sim.ccparticleworld/6/32bpc/t2.2", 0xc8930de7171f5ab3),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t0.5", 0x9166865a7c9ac035),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t1.5", 0x93901b6547233c1f),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t0.8", 0xe5d835162c42b6a5),
|
||||
("ec.sim.ccparticleworld/7/8bpc/t2.2", 0xe81b1c734e88c7cb),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t0.5", 0x27924fd1804d9a61),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t1.5", 0x9daca8989bbd99f1),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t0.8", 0xcd2932f1ee19e946),
|
||||
("ec.sim.ccparticleworld/7/32bpc/t2.2", 0x886af8fedcd62969),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t0.5", 0xe08dd245cbd88371),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t1.5", 0xcbe7b22563e912f4),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t0.8", 0x81bcded7ad281386),
|
||||
("ec.sim.ccparticleworld/8/8bpc/t2.2", 0x5d176ad19ac06da2),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t0.5", 0x1dff22388b30e96d),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t1.5", 0x6f29f64ba5e160df),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t0.8", 0xfba8c8d708e417e4),
|
||||
("ec.sim.ccparticleworld/8/32bpc/t2.2", 0xf3b2f2a1ea8c71d6),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t0.5", 0x01d2a42a3a56c69b),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t1.5", 0x953091e15d03438f),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t0.8", 0x668ea154b17b2eb0),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/t2.2", 0x1862446b0c54b86c),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t0.5", 0xa1fb78a64db56ef3),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t1.5", 0x20ec7913584e6b71),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t0.8", 0xab390d348d0a66fd),
|
||||
("ec.sim.ccparticlesystems2/0/32bpc/t2.2", 0x82f78af53a7c0096),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t0.5", 0xf7cf34b83bd3af18),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t1.5", 0x461020f3a3a4410d),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t0.8", 0xcd190eb7b38db0e8),
|
||||
("ec.sim.ccparticlesystems2/0/8bpc/half/t2.2", 0x7f35000229186023),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t0.5", 0xf711d4d5244de44b),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t1.5", 0x61ea1dd478d0f90e),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t0.8", 0x1d23c2c8bb26577c),
|
||||
("ec.sim.ccparticlesystems2/1/8bpc/t2.2", 0x0ca22baad9654c06),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t0.5", 0x6dc7b6570e174ee2),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t1.5", 0x491a30b9f0dac574),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t0.8", 0xfd9c7f0d0abd959e),
|
||||
("ec.sim.ccparticlesystems2/1/32bpc/t2.2", 0x95ea630041185e8b),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t0.5", 0x165e69bf2a5f7a6a),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t1.5", 0xc5ce39b6beb3a4a1),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t0.8", 0x635bf9e56db3087d),
|
||||
("ec.sim.ccparticlesystems2/2/8bpc/t2.2", 0x03bb626e929e6cdd),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t0.5", 0x92b5a331852e40fe),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t1.5", 0xae453b6fd4bbaeed),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t0.8", 0xfa4621a685214620),
|
||||
("ec.sim.ccparticlesystems2/2/32bpc/t2.2", 0x84c180368e4411ad),
|
||||
("ec.sim.ccparticlesystems2/3/8bpc/t0.5", 0xf14aad048c3b4181),
|
||||
("ec.sim.ccparticlesystems2/3/8bpc/t1.5", 0xc261983ac6805eda),
|
||||
("ec.sim.ccparticlesystems2/3/8bpc/t0.8", 0xf93ad1d6a9c493a5),
|
||||
@@ -446,22 +446,22 @@ const GOLDEN: &[(&str, u64)] = &[
|
||||
("ec.sim.ccparticlesystems2/3/32bpc/t1.5", 0x1c415c633baec738),
|
||||
("ec.sim.ccparticlesystems2/3/32bpc/t0.8", 0x81a765f6e435e762),
|
||||
("ec.sim.ccparticlesystems2/3/32bpc/t2.2", 0x7810e7f2ae55f619),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t0.5", 0xd246be64fea5db5f),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t1.5", 0x78ca37c0d19e87cf),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t0.8", 0xa5eacfbc0cc28a7c),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t2.2", 0xa527d1d2cdce5c96),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t0.5", 0x41c8b38886ae9652),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t1.5", 0x1e6d16247bb9c7a7),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t0.8", 0x05b125bdcd9a1794),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t2.2", 0x4752ed7777528cc8),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t0.5", 0x8ff7adb3b1720dbe),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t1.5", 0x2bb835296a78fccb),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t0.8", 0x674810581e32f80a),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t2.2", 0xecba1a3a740f4325),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t0.5", 0x30f53c7cb869066c),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t1.5", 0x1eb455f68b9decc8),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t0.8", 0xf396c8bdd516ef26),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t2.2", 0x7d0a6e30425ea5c3),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t0.5", 0x0106a8009fa18e2f),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t1.5", 0x5f12647281ea7ec9),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t0.8", 0x9f2655dbad770023),
|
||||
("ec.sim.ccparticlesystems2/4/8bpc/t2.2", 0x44ca687ef817c0a1),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t0.5", 0x895b20656b6d3c98),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t1.5", 0x3a8b85da736ae6f0),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t0.8", 0x139f04a2dcf67d69),
|
||||
("ec.sim.ccparticlesystems2/4/32bpc/t2.2", 0x02c844b7371128ac),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t0.5", 0x7b4a7112b6c8bb11),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t1.5", 0xf16ff18c451dbf63),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t0.8", 0xdedadbd43089dafe),
|
||||
("ec.sim.ccparticlesystems2/5/8bpc/t2.2", 0x1e6fdb272dabf94c),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t0.5", 0xd17e5a60f476d0f7),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t1.5", 0xbfd43b69b45cd67c),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t0.8", 0x79fb89759eea8a6a),
|
||||
("ec.sim.ccparticlesystems2/5/32bpc/t2.2", 0x0a70bc480c847d7e),
|
||||
("ec.sim.particleplayground/0/8bpc/t0.5", 0x1842226399d43e19),
|
||||
("ec.sim.particleplayground/0/8bpc/t1.5", 0xd5676389299c50e9),
|
||||
("ec.sim.particleplayground/0/8bpc/t0.8", 0x30517e3b37e099d5),
|
||||
|
||||
@@ -10,6 +10,7 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-rustmotion-common = { workspace = true }
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-geom = { workspace = true }
|
||||
effectcraft-color = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
{
|
||||
"format": "effectcraft.animationPresets/1",
|
||||
"notes": "Original EffectCraft background presets (MIT OR Apache-2.0), written from scratch on EffectCraft's own generator, noise, colour and stylize effects. Apply to a solid or any layer with effects. Key times are seconds from the current time; most motion comes from expressions (time-based, so the background keeps moving for the layer's whole duration). Point values are fractions of the layer size; effect paths are the effect's parameter ids.",
|
||||
"presets": [
|
||||
{
|
||||
"id": "softGradientDrift",
|
||||
"name": "Soft Gradient Drift",
|
||||
"category": "Backgrounds",
|
||||
"description": "Four soft colour corners slowly drift around the frame.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fourcolor", "set": {"positionsColors/color1": [0.1137, 0.1686, 0.3922, 1], "positionsColors/color2": [0.1647, 0.6157, 0.5608, 1], "positionsColors/color3": [0.4824, 0.1765, 0.5608, 1], "positionsColors/color4": [0.9569, 0.6353, 0.3804, 1], "blend": 100}, "expr": {"positionsColors/point1": "[thisComp.width*(0.15+0.1*Math.sin(time*0.7)), thisComp.height*(0.2+0.1*Math.cos(time*0.5))]", "positionsColors/point2": "[thisComp.width*(0.85+0.08*Math.cos(time*0.6)), thisComp.height*(0.15+0.1*Math.sin(time*0.8))]", "positionsColors/point3": "[thisComp.width*(0.2+0.1*Math.sin(time*0.9+1)), thisComp.height*(0.85+0.08*Math.cos(time*0.4))]", "positionsColors/point4": "[thisComp.width*(0.8+0.1*Math.cos(time*0.5+2)), thisComp.height*(0.8+0.1*Math.sin(time*0.7+1))]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "auroraVeil",
|
||||
"name": "Aurora Veil",
|
||||
"category": "Backgrounds",
|
||||
"description": "Tall green curtains of light ripple slowly across a night sky.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 170, "brightness": -40, "complexity": 6, "fractalType": 1, "transform/uniformScaling": false, "transform/scaleWidth": 500, "transform/scaleHeight": 70}, "expr": {"evolution": "time*18", "transform/offset": "[thisComp.width/2 + Math.sin(time*0.3)*thisComp.width*0.2, thisComp.height/2]"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0078, 0.0392, 0.0784, 1], "white": [0.302, 1.0, 0.7529, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "slowFog",
|
||||
"name": "Slow Fog",
|
||||
"category": "Backgrounds",
|
||||
"description": "Heavy grey-blue fog banks roll gently through the frame.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 75, "brightness": -5, "complexity": 6, "fractalType": 1, "transform/scale": 320}, "expr": {"evolution": "time*14", "transform/offset": "[thisComp.width/2 + time*25, thisComp.height/2]"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0588, 0.0941, 0.1333, 1], "white": [0.6235, 0.7059, 0.7765, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "cloudBank",
|
||||
"name": "Cloud Bank",
|
||||
"category": "Backgrounds",
|
||||
"description": "Soft cumulus clouds drift across a blue sky.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 130, "brightness": 8, "complexity": 7, "transform/scale": 240}, "expr": {"evolution": "time*10", "transform/offset": "[thisComp.width/2 + time*40, thisComp.height/2]"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.1843, 0.4353, 0.702, 1], "white": [1.0, 1.0, 1.0, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "darkSmoke",
|
||||
"name": "Dark Smoke",
|
||||
"category": "Backgrounds",
|
||||
"description": "Thick dark smoke rises slowly and curls as it goes.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.turbulent", "set": {"contrast": 140, "brightness": -15, "complexity": 6, "transform/scale": 200}, "expr": {"evolution": "time*45", "transform/offset": "[thisComp.width/2, thisComp.height/2 + time*70]"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0, 0.0, 0.0, 1], "white": [0.4157, 0.4157, 0.4549, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "emberHaze",
|
||||
"name": "Ember Haze",
|
||||
"category": "Backgrounds",
|
||||
"description": "A warm glowing haze of embers, black to deep red to amber.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 120, "brightness": 0, "complexity": 6, "fractalType": 1, "transform/scale": 180}, "expr": {"evolution": "time*30", "transform/offset": "[thisComp.width/2, thisComp.height/2 + time*40]"}},
|
||||
{"effect": "ec.color.tritone", "set": {"shadows": [0.051, 0.0078, 0.0, 1], "midtones": [0.6275, 0.1569, 0.0, 1], "highlights": [1.0, 0.702, 0.2784, 1]}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "magmaFlow",
|
||||
"name": "Magma Flow",
|
||||
"category": "Backgrounds",
|
||||
"description": "Fire-coloured plasma that slowly cycles through its palette.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 110, "brightness": 0, "complexity": 6, "transform/scale": 260}, "expr": {"evolution": "time*20"}},
|
||||
{"effect": "ec.color.colorama", "set": {"outputCycle/usePresetPalette": 2}, "expr": {"inputPhase/phaseShift": "time*30"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "iceFlow",
|
||||
"name": "Ice Flow",
|
||||
"category": "Backgrounds",
|
||||
"description": "Cold blue and white veins drift through a frozen field.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 60, "brightness": -5, "complexity": 6, "fractalType": 1, "transform/scale": 300}, "expr": {"evolution": "time*12"}},
|
||||
{"effect": "ec.color.colorama", "set": {"outputCycle/usePresetPalette": 3, "outputCycle/cycles": 1}, "expr": {"inputPhase/phaseShift": "Math.sin(time*0.4)*40"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "pastelPlasma",
|
||||
"name": "Pastel Plasma",
|
||||
"category": "Backgrounds",
|
||||
"description": "Soft pastel plasma with colours that endlessly cycle.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 170, "brightness": 0, "complexity": 6, "transform/scale": 300}, "expr": {"evolution": "time*16"}},
|
||||
{"effect": "ec.color.colorama", "set": {"outputCycle/usePresetPalette": 7}, "expr": {"inputPhase/phaseShift": "time*25"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "cellDrift",
|
||||
"name": "Cell Drift",
|
||||
"category": "Backgrounds",
|
||||
"description": "Bubble-like cells slowly swell and merge in teal tones.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.cellpattern", "set": {"cellPattern": 0, "size": 90, "contrast": 140, "disperse": 1.2}, "expr": {"evolution": "time*40"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0157, 0.1255, 0.1686, 1], "white": [0.3725, 0.8902, 0.7843, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "crystalFacets",
|
||||
"name": "Crystal Facets",
|
||||
"category": "Backgrounds",
|
||||
"description": "Sharp crystal facets shimmer in warm violet light.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.cellpattern", "set": {"cellPattern": 1, "size": 110, "contrast": 120}, "expr": {"evolution": "time*25"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.102, 0.0431, 0.1804, 1], "white": [0.8784, 0.6392, 1.0, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "hexMosaic",
|
||||
"name": "Hex Mosaic",
|
||||
"category": "Backgrounds",
|
||||
"description": "A hexagon mosaic that glows as fog passes beneath it.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 110, "brightness": 0, "complexity": 6, "transform/scale": 300}, "expr": {"evolution": "time*20", "transform/offset": "[thisComp.width/2 + time*20, thisComp.height/2]"}},
|
||||
{"effect": "ec.stylize.cchextile", "set": {"radius": 45}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0392, 0.0588, 0.2392, 1], "white": [0.3216, 0.8196, 1.0, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mirroredSilk",
|
||||
"name": "Mirrored Silk",
|
||||
"category": "Backgrounds",
|
||||
"description": "Flowing silk ribbons mirrored down the centre.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.fractal", "set": {"contrast": 130, "brightness": 0, "complexity": 6, "fractalType": 1, "transform/scale": 260}, "expr": {"evolution": "time*15", "transform/offset": "[thisComp.width/2 + Math.sin(time*0.4)*thisComp.width*0.15, thisComp.height/2]"}},
|
||||
{"effect": "ec.distort.mirror", "set": {"center": [0.5, 0.5], "angle": 0}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.1686, 0.0392, 0.1176, 1], "white": [1.0, 0.7608, 0.851, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "waterCaustics",
|
||||
"name": "Water Caustics",
|
||||
"category": "Backgrounds",
|
||||
"description": "Bright caustic filaments shimmer across a turquoise pool floor.",
|
||||
"effects": [
|
||||
{"effect": "ec.noise.turbulent", "set": {"contrast": 120, "brightness": -25, "complexity": 6, "transform/scale": 110, "fractalType": 2}, "expr": {"evolution": "time*60"}},
|
||||
{"effect": "ec.color.tint", "set": {"black": [0.0, 0.2275, 0.3216, 1], "white": [0.5608, 0.9529, 1.0, 1], "amount": 100}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "blueprintGrid",
|
||||
"name": "Blueprint Grid",
|
||||
"category": "Backgrounds",
|
||||
"description": "A technical grid slides across a deep blue plate.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fill", "set": {"allMasks": true, "color": [0.0431, 0.2392, 0.5686, 1]}},
|
||||
{"effect": "ec.generate.grid", "set": {"width": 16, "height": 16, "border": 1, "color": [0.6235, 0.8314, 1.0, 1], "opacity": 18, "blendingMode": 1}, "expr": {"anchor": "[time*8, time*8]"}},
|
||||
{"effect": "ec.generate.grid", "set": {"width": 80, "height": 80, "border": 1.5, "color": [0.8471, 0.9373, 1.0, 1], "opacity": 45, "blendingMode": 1}, "expr": {"anchor": "[time*16, time*16]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "checkerScroll",
|
||||
"name": "Checker Scroll",
|
||||
"category": "Backgrounds",
|
||||
"description": "A two-tone checkerboard scrolls diagonally.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fill", "set": {"allMasks": true, "color": [0.1098, 0.1216, 0.2275, 1]}},
|
||||
{"effect": "ec.generate.checkerboard", "set": {"sizeFrom": 1, "width": 90, "height": 90, "color": [0.1765, 0.2, 0.3882, 1], "opacity": 100, "blendingMode": 1}, "expr": {"anchor": "[time*45, time*45]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "scrollingStripes",
|
||||
"name": "Scrolling Stripes",
|
||||
"category": "Backgrounds",
|
||||
"description": "Wide vertical stripes slide steadily sideways.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fill", "set": {"allMasks": true, "color": [0.949, 0.9098, 0.8118, 1]}},
|
||||
{"effect": "ec.generate.checkerboard", "set": {"sizeFrom": 0, "corner": [0.11, 20], "color": [0.2196, 0.4, 0.2549, 1], "opacity": 100, "blendingMode": 1}, "expr": {"anchor": "[time*60, 0]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "pulseRings",
|
||||
"name": "Pulse Rings",
|
||||
"category": "Backgrounds",
|
||||
"description": "Soft rings expand from the centre in a steady rhythm.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fill", "set": {"allMasks": true, "color": [0.0235, 0.0784, 0.1686, 1]}},
|
||||
{"effect": "ec.generate.circle", "set": {"edge": 2, "thickness": 4, "feather/feather": 3, "color": [0.498, 0.9059, 1.0, 1], "blendingMode": 1}, "expr": {"center": "[thisComp.width/2, thisComp.height/2]", "radius": "((time+0)%3)/3*Math.max(thisComp.width,thisComp.height)*0.7", "opacity": "100*Math.pow(1-((time+0)%3)/3, 1.5)"}},
|
||||
{"effect": "ec.generate.circle", "set": {"edge": 2, "thickness": 4, "feather/feather": 3, "color": [0.498, 0.9059, 1.0, 1], "blendingMode": 1}, "expr": {"center": "[thisComp.width/2, thisComp.height/2]", "radius": "((time+1)%3)/3*Math.max(thisComp.width,thisComp.height)*0.7", "opacity": "100*Math.pow(1-((time+1)%3)/3, 1.5)"}},
|
||||
{"effect": "ec.generate.circle", "set": {"edge": 2, "thickness": 4, "feather/feather": 3, "color": [0.498, 0.9059, 1.0, 1], "blendingMode": 1}, "expr": {"center": "[thisComp.width/2, thisComp.height/2]", "radius": "((time+2)%3)/3*Math.max(thisComp.width,thisComp.height)*0.7", "opacity": "100*Math.pow(1-((time+2)%3)/3, 1.5)"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "bokehDrift",
|
||||
"name": "Bokeh Drift",
|
||||
"category": "Backgrounds",
|
||||
"description": "Out-of-focus lights float lazily over a dark violet backdrop.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.fill", "set": {"allMasks": true, "color": [0.0784, 0.0627, 0.1647, 1]}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 40, "feather/feather": 70, "color": [1.0, 0.6196, 0.7961, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.12+0.05*Math.sin(time*0.3+0)), thisComp.height*(0.25+0.07*Math.cos(time*0.25+0))]"}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 49, "feather/feather": 70, "color": [0.5608, 0.8275, 1.0, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.27+0.05*Math.sin(time*0.41+1)), thisComp.height*(0.6+0.07*Math.cos(time*0.32+2))]"}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 58, "feather/feather": 70, "color": [1.0, 0.8471, 0.5412, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.42+0.05*Math.sin(time*0.52+2)), thisComp.height*(0.45+0.07*Math.cos(time*0.39+4))]"}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 67, "feather/feather": 70, "color": [0.7137, 0.6118, 1.0, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.57+0.05*Math.sin(time*0.63+3)), thisComp.height*(0.3+0.07*Math.cos(time*0.46+6))]"}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 76, "feather/feather": 70, "color": [0.5412, 1.0, 0.7569, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.72+0.05*Math.sin(time*0.74+4)), thisComp.height*(0.65+0.07*Math.cos(time*0.53+8))]"}},
|
||||
{"effect": "ec.generate.circle", "set": {"radius": 85, "feather/feather": 70, "color": [1.0, 0.6196, 0.4784, 1], "opacity": 32, "blendingMode": 1}, "expr": {"center": "[thisComp.width*(0.87+0.05*Math.sin(time*0.8500000000000001+5)), thisComp.height*(0.5+0.07*Math.cos(time*0.6000000000000001+10))]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "spotlightFloor",
|
||||
"name": "Spotlight Floor",
|
||||
"category": "Backgrounds",
|
||||
"description": "A soft pool of light on a dark floor that gently breathes.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.gradientramp", "set": {"shape": 1, "startColor": [0.2902, 0.3608, 0.5216, 1], "endColor": [0.0196, 0.0275, 0.051, 1]}, "expr": {"start": "[thisComp.width/2, thisComp.height*0.45]", "end": "[thisComp.width/2 + thisComp.width*(0.55+0.04*Math.sin(time*1.3)), thisComp.height*0.45]"}},
|
||||
{"effect": "ec.stylize.ccvignette", "set": {"amount": 35}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "dawnSky",
|
||||
"name": "Dawn Sky",
|
||||
"category": "Backgrounds",
|
||||
"description": "A night sky warms into sunrise over six seconds.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.gradientramp", "set": {"start": [0.5, 0.0], "end": [0.5, 1.0]}, "keys": {"startColor": [[0, [0.1216, 0.2275, 0.5412, 1]], [6, [0.3569, 0.5255, 0.8392, 1]]], "endColor": [[0, [0.0118, 0.0157, 0.0471, 1]], [6, [1.0, 0.702, 0.4196, 1]]]}, "ease": true}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sweepingLight",
|
||||
"name": "Sweeping Light",
|
||||
"category": "Backgrounds",
|
||||
"description": "A band of light sweeps repeatedly across a dark slate backdrop.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.gradientramp", "set": {"startColor": [0.0706, 0.0863, 0.1216, 1], "endColor": [0.1451, 0.1686, 0.2275, 1]}},
|
||||
{"effect": "ec.generate.cclightsweep", "set": {"direction": -30, "width": 60, "sweepIntensity": 70}, "expr": {"center": "[(time%3)/3*thisComp.width*1.6 - thisComp.width*0.3, thisComp.height/2]"}}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grainyWash",
|
||||
"name": "Grainy Wash",
|
||||
"category": "Backgrounds",
|
||||
"description": "A muted diagonal wash with live film grain.",
|
||||
"effects": [
|
||||
{"effect": "ec.generate.gradientramp", "set": {"start": [0.1, 0.1], "end": [0.9, 0.9], "startColor": [0.9098, 0.8353, 0.7686, 1], "endColor": [0.5451, 0.4353, 0.5608, 1]}},
|
||||
{"effect": "ec.noise.addgrain", "set": {"tweaking/intensity": 2.2, "tweaking/size": 1.4}},
|
||||
{"effect": "ec.stylize.ccvignette", "set": {"amount": 25}}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
asset: backgrounds.json
|
||||
title: EffectCraft Backgrounds animation presets (Soft Gradient Drift, Aurora Veil, Slow Fog, Cloud Bank, Dark Smoke, Ember Haze, Magma Flow, Ice Flow, Pastel Plasma, Cell Drift, Crystal Facets, Hex Mosaic, Mirrored Silk, Water Caustics, Blueprint Grid, Checker Scroll, Scrolling Stripes, Pulse Rings, Bokeh Drift, Spotlight Floor, Dawn Sky, Sweeping Light, Grainy Wash)
|
||||
author: EffectCraft contributors
|
||||
source: original work
|
||||
license: MIT OR Apache-2.0
|
||||
added: 2026-10-12 by vangel76 (Claude Code agent, gap 7, #1096)
|
||||
notes: Effect choices, colours, values and expressions written from scratch for EffectCraft on its own generator, noise, colour and stylize effects; not derived from any Adobe preset (.ffx) or its values.
|
||||
@@ -1,14 +1,18 @@
|
||||
//! EffectCraft's own animation preset library (Effects & Presets ▸ * Animation Presets): the
|
||||
//! Transitions category, original presets built on our Transition effects and layer opacity.
|
||||
//! Transitions category (original presets built on our Transition effects and layer opacity) and
|
||||
//! the Backgrounds category (generators, noise and colour effects driven by expressions).
|
||||
//!
|
||||
//! Each preset adds effects (with values and keyframes) and/or keys layer properties, starting
|
||||
//! at the current time, on every selected layer. The library is data
|
||||
//! (`presets/transitions.json`), written from scratch; nothing comes from After Effects' `.ffx`
|
||||
//! presets.
|
||||
//! (`presets/*.json`), written from scratch; nothing comes from After Effects' `.ffx` presets.
|
||||
//!
|
||||
//! A preset effect or layer block has `set` (static values), `keys` (`[[seconds, value], …]`
|
||||
//! from the current time), `expr` (an expression text per property) and `ease`. Values of
|
||||
//! point parameters are fractions of the layer size, like the effects' own defaults.
|
||||
|
||||
use effectcraft_keyframe::Keyframe;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{Node, Property};
|
||||
use effectcraft_project::{Expression, Node, ParamUi, Property, Value as KV};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -19,11 +23,19 @@ use crate::{EngineError, Result, Session, cmd, query};
|
||||
/// The original transition presets (`presets/transitions.json`).
|
||||
pub const TRANSITIONS_JSON: &str = include_str!("../../presets/transitions.json");
|
||||
|
||||
/// The original background presets (`presets/backgrounds.json`).
|
||||
pub const BACKGROUNDS_JSON: &str = include_str!("../../presets/backgrounds.json");
|
||||
|
||||
/// Keys per animated property, so a hostile inline preset can't allocate without bound.
|
||||
const MAX_KEYS: usize = 256;
|
||||
/// Longest expression text an inline preset may carry.
|
||||
const MAX_EXPR: usize = 4096;
|
||||
|
||||
fn presets() -> Vec<Value> {
|
||||
serde_json::from_str::<Value>(TRANSITIONS_JSON).ok().and_then(|v| v.get("presets").and_then(Value::as_array).cloned()).unwrap_or_default()
|
||||
[TRANSITIONS_JSON, BACKGROUNDS_JSON]
|
||||
.iter()
|
||||
.flat_map(|src| serde_json::from_str::<Value>(src).ok().and_then(|v| v.get("presets").and_then(Value::as_array).cloned()).unwrap_or_default())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn text<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
@@ -44,11 +56,16 @@ fn find_preset(want: &str) -> Option<Value> {
|
||||
|
||||
/// Set `pr` to `v` (when given) and replace its keys with `keys` (`[[seconds, value], …]`,
|
||||
/// seconds from `at`). Returns false when nothing in the request fits the property.
|
||||
fn set_prop(pr: &mut Property, v: Option<&Value>, keys: Option<&Value>, at: Tick, ease: bool) -> bool {
|
||||
fn set_prop(pr: &mut Property, v: Option<&Value>, keys: Option<&Value>, at: Tick, ease: bool, size: [f64; 2]) -> bool {
|
||||
// Point parameters are written as fractions of the layer size.
|
||||
let scale = |val: KV| match val {
|
||||
KV::Vec2(f) if matches!(pr.ui, ParamUi::Point) => KV::Vec2([f[0] * size[0], f[1] * size[1]]),
|
||||
other => other,
|
||||
};
|
||||
let mut ok = true;
|
||||
if let Some(v) = v {
|
||||
match json_value(v, &pr.value) {
|
||||
Some(val) => pr.value = val,
|
||||
Some(val) => pr.value = scale(val),
|
||||
None => ok = false,
|
||||
}
|
||||
}
|
||||
@@ -58,7 +75,7 @@ fn set_prop(pr: &mut Property, v: Option<&Value>, keys: Option<&Value>, at: Tick
|
||||
for k in list.iter().take(MAX_KEYS) {
|
||||
let t = k.get(0).and_then(Value::as_f64).filter(|t| t.is_finite() && t.abs() <= 86_400.0);
|
||||
let (Some(t), Some(val)) = (t, k.get(1).and_then(|x| json_value(x, &pr.value))) else { return false };
|
||||
let mut key = Keyframe::new(at + Tick::from_seconds_f64(t), val);
|
||||
let mut key = Keyframe::new(at + Tick::from_seconds_f64(t), scale(val));
|
||||
if pr.hold_only {
|
||||
key = key.hold();
|
||||
} else if ease {
|
||||
@@ -76,22 +93,30 @@ fn set_prop(pr: &mut Property, v: Option<&Value>, keys: Option<&Value>, at: Tick
|
||||
|
||||
/// Apply `set` / `keys` maps to the properties under `root`; returns the paths that don't exist
|
||||
/// or don't take the given values.
|
||||
fn apply_maps(root: &mut effectcraft_project::PropGroup, spec: &Value, at: Tick) -> Vec<String> {
|
||||
fn apply_maps(root: &mut effectcraft_project::PropGroup, spec: &Value, at: Tick, size: [f64; 2]) -> Vec<String> {
|
||||
let ease = spec.get("ease").and_then(Value::as_bool).unwrap_or(false);
|
||||
let empty = Map::new();
|
||||
let set = spec.get("set").and_then(Value::as_object).unwrap_or(&empty);
|
||||
let keys = spec.get("keys").and_then(Value::as_object).unwrap_or(&empty);
|
||||
let exprs = spec.get("expr").and_then(Value::as_object).unwrap_or(&empty);
|
||||
let mut skipped = Vec::new();
|
||||
for (path, v) in set {
|
||||
if !root.prop_mut(path).is_some_and(|pr| set_prop(pr, Some(v), None, at, false)) {
|
||||
if !root.prop_mut(path).is_some_and(|pr| set_prop(pr, Some(v), None, at, false, size)) {
|
||||
skipped.push(path.clone());
|
||||
}
|
||||
}
|
||||
for (path, list) in keys {
|
||||
if !root.prop_mut(path).is_some_and(|pr| !pr.static_only && set_prop(pr, None, Some(list), at, ease)) {
|
||||
if !root.prop_mut(path).is_some_and(|pr| !pr.static_only && set_prop(pr, None, Some(list), at, ease, size)) {
|
||||
skipped.push(path.clone());
|
||||
}
|
||||
}
|
||||
for (path, text) in exprs {
|
||||
let body = text.as_str().filter(|t| !t.trim().is_empty() && t.len() <= MAX_EXPR);
|
||||
match (root.prop_mut(path), body) {
|
||||
(Some(pr), Some(body)) if !pr.static_only => pr.expr = Some(Expression { text: body.to_string(), enabled: true }),
|
||||
_ => skipped.push(path.clone()),
|
||||
}
|
||||
}
|
||||
skipped
|
||||
}
|
||||
|
||||
@@ -134,13 +159,13 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let same = fx.groups().filter(|g| g.match_id == spec.id).count();
|
||||
let inst = if same == 0 { spec.name.to_string() } else { format!("{} {}", spec.name, same.saturating_add(1)) };
|
||||
let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), &inst, *size);
|
||||
skipped.extend(apply_maps(&mut g, ej, at).into_iter().map(|path| format!("{}/{path}", spec.id)));
|
||||
skipped.extend(apply_maps(&mut g, ej, at, *size).into_iter().map(|path| format!("{}/{path}", spec.id)));
|
||||
added.push(g.uid);
|
||||
fx.children.push(Node::Group(g));
|
||||
}
|
||||
}
|
||||
if let Some(ls) = &layer_spec {
|
||||
skipped.extend(apply_maps(&mut l.props, ls, at));
|
||||
skipped.extend(apply_maps(&mut l.props, ls, at, *size));
|
||||
}
|
||||
proj.next_id = next;
|
||||
}
|
||||
|
||||
@@ -349,6 +349,25 @@ fn changed_from(g: &PropGroup, default: &PropGroup, out: &mut Vec<Uid>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// What of effect group `g` differs from `new`, a new instance of the effect: parameters with
|
||||
/// another value, and in full the groups a new instance lacks (puppet meshes and pins, paint
|
||||
/// strokes: what the user made).
|
||||
fn effect_changes(g: &PropGroup, new: &PropGroup, out: &mut Vec<Uid>) {
|
||||
for c in &g.children {
|
||||
match c {
|
||||
Node::Prop(pr) => {
|
||||
if new.get(&pr.match_id).is_some_and(|d| d.value != pr.value) && !out.contains(&pr.uid) {
|
||||
out.push(pr.uid);
|
||||
}
|
||||
}
|
||||
Node::Group(sg) => match new.sub(&sg.match_id) {
|
||||
Some(d) => effect_changes(sg, d, out),
|
||||
None => out.push(sg.uid),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").unwrap_or("keyframes").to_string();
|
||||
let cid = super::comp_id(s, p)?;
|
||||
@@ -361,11 +380,11 @@ fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let anchor = [w as f64 / 2.0, h as f64 / 2.0];
|
||||
let center = [comp.width as f64 / 2.0, comp.height as f64 / 2.0];
|
||||
// Properties at the top of the layer's tree (Time Remap): enabled time remapping is a
|
||||
// modification in itself.
|
||||
// modification in itself, so it reveals even with no keys left on it (#990).
|
||||
for pr in l.props.props() {
|
||||
let hit = match kind.as_str() {
|
||||
"keyframes" => pr.is_animated(),
|
||||
"animation" => pr.is_animated() || pr.has_expression(),
|
||||
"keyframes" => pr.is_animated() || pr.match_id == "timeRemap",
|
||||
"animation" => pr.is_animated() || pr.has_expression() || pr.match_id == "timeRemap",
|
||||
_ => pr.match_id == "timeRemap" || modified(pr, "", anchor, center),
|
||||
};
|
||||
if hit {
|
||||
@@ -389,12 +408,30 @@ fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
found.push(pr.uid);
|
||||
}
|
||||
});
|
||||
// Modified: effects and masks count as modifications in full (AE reveals them).
|
||||
if kind == "modified" && matches!(top.match_id.as_str(), "effects" | "masks") {
|
||||
// Modified: masks count as modifications in full (AE reveals them).
|
||||
if kind == "modified" && top.match_id == "masks" {
|
||||
for g in top.groups() {
|
||||
found.push(g.uid);
|
||||
}
|
||||
}
|
||||
// Modified: an effect's parameters that differ from a new instance's.
|
||||
if kind == "modified" && top.match_id == "effects" {
|
||||
let size = effectcraft_render::effect_bounds(&s.project, comp, l).0;
|
||||
for g in top.groups() {
|
||||
let spec = match &g.kind {
|
||||
GroupKind::Effect { effect } => effectcraft_effects::find(effect),
|
||||
_ => None,
|
||||
};
|
||||
// A missing plug-in's defaults aren't known: the effect shows in full.
|
||||
let Some(spec) = spec else {
|
||||
found.push(g.uid);
|
||||
continue;
|
||||
};
|
||||
let mut next = 0;
|
||||
let new = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), "", size);
|
||||
effect_changes(g, &new, &mut found);
|
||||
}
|
||||
}
|
||||
if kind == "modified" && top.match_id == "text" {
|
||||
for g in top.group("animators").into_iter().flat_map(|a| a.groups()) {
|
||||
found.push(g.uid);
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
//! (Create VR Environment, Extract Cubemap), the "Assign Shortcut to …" submenus, Help ▸ Enable
|
||||
//! Logging / Reveal Logging File / System Compatibility Report, and `File.execute()` for scripts.
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_geom::{Mat4, Vec3, vec3};
|
||||
use effectcraft_project::{ItemId, ItemKind, LayerSource};
|
||||
use effectcraft_project::{Comp, FootageKind, ItemId, ItemKind, LayerSource};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, b_p, bad, comp_id, has_comp, has_layers, has_project_selection, str_p};
|
||||
@@ -170,6 +172,71 @@ fn replace_with_layered_comp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// File ▸ Replace Footage ▸ With Precomposition (also in the Project panel's context menu):
|
||||
/// the footage or solid item goes into a new composition of its size, pixel aspect and frame
|
||||
/// rate, placed in the same folder, and every layer in every composition that used the item now
|
||||
/// uses that composition instead. The layers keep their timing, transforms, effects and masks;
|
||||
/// the item stays in the project (the new composition uses it). The composition lasts as long as
|
||||
/// the footage, or as long as the longest layer that showed it for stills and solids. One undo
|
||||
/// step.
|
||||
fn replace_with_precomp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "file.replaceWithPrecomp";
|
||||
let item = p.get("item").and_then(Value::as_u64).map(ItemId).or_else(|| s.state.project_selection.first().copied());
|
||||
let item = item.ok_or_else(|| bad(CMD, "select a footage or solid item"))?;
|
||||
let it = s.project.item(item).ok_or_else(|| bad(CMD, "no such item"))?.clone();
|
||||
let (w, h, pixel_aspect, rate, own) = match &it.kind {
|
||||
ItemKind::Footage(f) if matches!(f.kind, FootageKind::Video | FootageKind::Still | FootageKind::Sequence) && f.has_video => {
|
||||
(f.width, f.height, f.pixel_aspect, it.frame_rate(), it.duration())
|
||||
}
|
||||
ItemKind::Solid(so) => (so.width, so.height, so.pixel_aspect, None, None),
|
||||
_ => return Err(bad(CMD, "the item is not visual footage or a solid")),
|
||||
};
|
||||
// Adjustment layers only borrow a solid for their size; they keep it.
|
||||
let is_user = |l: &effectcraft_project::Layer| {
|
||||
!l.switches.adjustment && matches!(l.source, LayerSource::Footage { item: i } | LayerSource::Solid { item: i } if i == item)
|
||||
};
|
||||
// The longest stretch of the item's own time any layer shows, and the first comp's rate.
|
||||
let mut used = Tick::ZERO;
|
||||
let mut used_rate = None;
|
||||
for (_, c) in s.project.comps() {
|
||||
for l in c.layers.iter().filter(|l| is_user(l)) {
|
||||
used = used.max(l.layer_time(l.in_point)).max(l.layer_time(l.out_point));
|
||||
used_rate.get_or_insert(c.frame_rate);
|
||||
}
|
||||
}
|
||||
let rate = rate.or(used_rate).unwrap_or(FrameRate::FPS_29_97);
|
||||
let fallback = Tick::from_seconds_f64(if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 });
|
||||
let dur = own.filter(|d| *d > Tick::ZERO).unwrap_or(if used > Tick::ZERO { used } else { fallback }).max(rate.frame_duration());
|
||||
let base = it.name.rsplit_once('.').map(|(a, _)| a.to_string()).unwrap_or(it.name.clone());
|
||||
let name = format!("{base} Comp");
|
||||
grouped(s, "Replace with Precomposition", |s| {
|
||||
let c = Comp { pixel_aspect, ..Comp::new(w.max(1), h.max(1), rate, dur) };
|
||||
let comp = s.edit("Replace with Precomposition", None, |proj, _| Ok(proj.add_item(&name, Label::Sandstone, it.parent, ItemKind::Comp(c.into()))))?;
|
||||
let inner = id_of(&s.execute("layer.addItem", json!({"comp": comp.0, "item": item.0, "time": 0.0, "duration": dur.seconds()}))?, "layer")?;
|
||||
let replaced = s.edit("Replace with Precomposition", None, |proj, st| {
|
||||
let mut n = 0u64;
|
||||
let ids: Vec<ItemId> = proj.items.keys().copied().filter(|c| *c != comp).collect();
|
||||
for cid in ids {
|
||||
if let Some(c) = proj.comp_mut(cid) {
|
||||
for l in c.layers.iter_mut().filter(|l| is_user(l)) {
|
||||
l.source = LayerSource::Comp { item: comp };
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
st.project_selection = vec![comp];
|
||||
Ok(n)
|
||||
})?;
|
||||
Ok(json!({"comp": comp.0, "layer": inner, "replaced": replaced}))
|
||||
})
|
||||
}
|
||||
|
||||
fn has_footage_or_solid(s: &Session) -> std::result::Result<(), String> {
|
||||
has_project_selection(s)?;
|
||||
let ok = s.state.project_selection.iter().any(|i| matches!(s.project.item(*i).map(|x| &x.kind), Some(ItemKind::Footage(_) | ItemKind::Solid(_))));
|
||||
if ok { Ok(()) } else { Err("select a footage or solid item".into()) }
|
||||
}
|
||||
|
||||
fn has_footage(s: &Session) -> std::result::Result<(), String> {
|
||||
has_project_selection(s)?;
|
||||
let ok = s.state.project_selection.iter().any(|i| matches!(s.project.item(*i).map(|x| &x.kind), Some(ItemKind::Footage(_))));
|
||||
@@ -582,7 +649,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("edit.history", "History", [], None, "{steps?: n (undo n steps), redo?: n}", has_history, history),
|
||||
cmd!("file.importRecent", "Import Recent Footage", [], None, "{index? | path?}", has_recent_footage, import_recent),
|
||||
cmd!("file.clearRecentFootage", "Clear Recent Footage", ["File", "Import Recent Footage"], None, "{}", has_recent_footage, clear_recent_footage),
|
||||
cmd!("anim.applyRecentPreset", "Recent Animation Presets", [], None, "{index? | path?, layers?}", has_recent_presets, apply_recent_preset),
|
||||
cmd!(
|
||||
"anim.applyRecentPreset",
|
||||
"Recent Animation Presets",
|
||||
[],
|
||||
Some("Cmd+Alt+Shift+F"),
|
||||
"{index? | path?, layers?}",
|
||||
has_recent_presets,
|
||||
apply_recent_preset
|
||||
),
|
||||
cmd!(
|
||||
"anim.clearRecentPresets",
|
||||
"Clear Recent Presets",
|
||||
@@ -594,6 +669,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("file.saveCopyAsXml", "Save a Copy As XML...", ["File", "Save As"], None, "{path: .ecprojx}", always, save_copy_xml),
|
||||
cmd!("file.replaceWithLayeredComp", "With Layered Comp", ["File", "Replace Footage"], None, "{item?}", has_footage, replace_with_layered_comp),
|
||||
cmd!("file.replaceWithPrecomp", "Replace with Precomposition", [], None, "{item?}", has_footage_or_solid, replace_with_precomp),
|
||||
cmd!("file.executeFile", "Execute File", [], None, "{path, confirmed?}", always, execute_file),
|
||||
cmd!("view.assign3dShortcut", "Assign Shortcut to 3D View", [], None, "{slot: F10|F11|F12, comp?}", has_comp, assign_view_shortcut),
|
||||
cmd!(
|
||||
|
||||
@@ -108,12 +108,7 @@ fn new_comp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
apply_settings(&mut c, p);
|
||||
let id = s.edit("New Composition", None, |proj, st| {
|
||||
let mut name = name.clone();
|
||||
let mut k = 2;
|
||||
while proj.items.values().any(|i| i.name == name) {
|
||||
name = format!("{} {k}", name.trim_end_matches(|ch: char| ch.is_ascii_digit()).trim_end());
|
||||
k += 1;
|
||||
}
|
||||
let name = proj.unique_item_name(&name, |_| false);
|
||||
let id = proj.add_item(&name, Label::Sandstone, None, ItemKind::Comp(c.into()));
|
||||
st.project_selection = vec![id];
|
||||
Ok(id)
|
||||
@@ -159,10 +154,11 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = comp_id(s, p)?;
|
||||
s.state.open_comps.retain(|c| *c != id);
|
||||
if s.state.active_comp == Some(id) {
|
||||
s.state.active_comp = s.state.open_comps.last().copied();
|
||||
s.state.selected_layers.clear();
|
||||
s.state.selected_keys.clear();
|
||||
s.state.selected_props.clear();
|
||||
if let Some(next) = s.state.open_comps.last().copied() {
|
||||
s.activate_comp(next);
|
||||
} else {
|
||||
s.activate_comp_none();
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ fn crop(s: &mut Session, cid: effectcraft_project::ItemId, r: [f64; 4], label: &
|
||||
let (w, h) = (effectcraft_project::limits::size_f64(r[2]), effectcraft_project::limits::size_f64(r[3]));
|
||||
s.edit(label, None, |proj, st| {
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let (old_w, old_h) = (c.width, c.height);
|
||||
c.width = w;
|
||||
c.height = h;
|
||||
for l in c.layers.iter_mut().filter(|l| l.parent.is_none()) {
|
||||
@@ -30,7 +31,8 @@ fn crop(s: &mut Session, cid: effectcraft_project::ItemId, r: [f64; 4], label: &
|
||||
}
|
||||
}
|
||||
for g in &mut c.guides {
|
||||
g.position -= if g.vertical { x } else { y };
|
||||
let px = g.px(old_w, old_h) - if g.vertical { x } else { y };
|
||||
g.set_px(px, w, h);
|
||||
}
|
||||
st.region_of_interest = None;
|
||||
Ok(())
|
||||
|
||||
@@ -863,14 +863,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_comp,
|
||||
paste_svg
|
||||
),
|
||||
cmd!("edit.pasteReversedKeyframes", "Paste Reversed Keyframes", ["Edit"], None, "{layers?, prop?|path?, time?}", has_key_clip, paste_reversed),
|
||||
cmd!(
|
||||
"edit.pasteReversedKeyframes",
|
||||
"Paste Reversed Keyframes",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+V"),
|
||||
"{layers?, prop?|path?, time?}",
|
||||
has_key_clip,
|
||||
paste_reversed
|
||||
),
|
||||
cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{layers?}", layers_or_keys, delete),
|
||||
cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+D"), "{layers?} (effects or shape items when they are selected)", has_layers, duplicate),
|
||||
cmd!("edit.splitLayer", "Split Layer", ["Edit"], Some("Cmd+Shift+D"), "{layers?}", has_layers, split),
|
||||
cmd!("edit.liftWorkArea", "Lift Work Area", ["Edit"], None, "{layers?}", has_comp, lift),
|
||||
cmd!("edit.extractWorkArea", "Extract Work Area", ["Edit"], None, "{layers?}", has_comp, extract),
|
||||
cmd!("edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", has_comp, select_all),
|
||||
cmd!("edit.deselectAll", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always_ok, deselect_all),
|
||||
cmd!("edit.deselectAll", "Deselect All", ["Edit"], ["Cmd+Shift+A", "F2"], "{}", always_ok, deselect_all),
|
||||
cmd!("edit.label", "Label", ["Edit", "Label"], None, "{label: Red|Yellow|Aqua|…, layers?, keys?, target?: layers}", always_ok, label),
|
||||
cmd!("edit.selectLabelGroup", "Select Label Group", ["Edit", "Label"], None, "{}", has_props_or_layers_or_items, select_label_group),
|
||||
cmd!("edit.purgeUndo", "Undo", ["Edit", "Purge"], None, "{}", always_ok, purge),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Effect menu and Effect Controls gestures.
|
||||
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, LayerId, PropGroup, Uid};
|
||||
use effectcraft_project::{GroupKind, Layer, LayerId, PropGroup, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_layers, layer_mut, layers_p, str_p};
|
||||
@@ -117,7 +118,7 @@ fn find_fx(s: &Session, p: &Value, cmd: &str) -> Result<(effectcraft_project::It
|
||||
let g = match p.get("effect") {
|
||||
Some(Value::Number(n)) => {
|
||||
let n = n.as_u64().unwrap_or(0);
|
||||
fx.groups().find(|g| g.uid == n).or_else(|| fx.groups().nth(n.saturating_sub(1) as usize))
|
||||
fx.groups().find(|g| g.uid == n).or_else(|| usize::try_from(n.saturating_sub(1)).ok().and_then(|i| fx.groups().nth(i)))
|
||||
}
|
||||
Some(Value::String(name)) => fx.groups().find(|g| &g.name == name || g.match_id == *name),
|
||||
_ => s.state.selected_props.iter().find_map(|(l, u)| (*l == lid).then(|| fx.groups().find(|g| g.uid == *u)).flatten()),
|
||||
@@ -227,6 +228,25 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!(r))
|
||||
}
|
||||
|
||||
/// `effect.setLabel`: the effect's colour label (None clears it).
|
||||
fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "effect.setLabel";
|
||||
let (cid, lid, uid) = find_fx(s, p, c)?;
|
||||
let lab = match p.get("label") {
|
||||
Some(Value::Number(n)) => n.as_u64().and_then(|i| effectcraft_color::Label::ALL.get(usize::try_from(i).ok()?).copied()),
|
||||
Some(Value::String(name)) => s.prefs.label_from_name(name),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| bad(c, "missing or unknown `label` (name or index 0-16; 0 / None clears it)"))?;
|
||||
s.edit("Effect Label", None, |proj, _| {
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let g = l.props.find_group_mut(uid).ok_or_else(|| bad(c, "gone"))?;
|
||||
g.label = (lab != effectcraft_color::Label::None).then_some(lab);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = find_fx(s, p, "effect.reorder")?;
|
||||
let to = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("effect.reorder", "missing `index` (1-based)"))? as usize;
|
||||
@@ -300,12 +320,108 @@ fn effects_p(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(LayerId, Uid)>> {
|
||||
Ok(sel)
|
||||
}
|
||||
|
||||
/// Edit ▸ Copy with effects selected: puts the effect instances on the effect clipboard.
|
||||
fn effect_time_error(cmd: &str) -> EngineError {
|
||||
bad(cmd, "an effect keyframe converts outside the supported time range")
|
||||
}
|
||||
|
||||
/// Validate before Layer's saturating conversions, so a bad stretch or time never silently
|
||||
/// moves a copied key to another frame. Normal-speed layers keep their exact integer ticks.
|
||||
fn effect_time(layer: &Layer, time: Tick, to_comp: bool, cmd: &str) -> Result<Tick> {
|
||||
if !layer.stretch.is_finite() || layer.stretch == 0.0 {
|
||||
return Err(bad(cmd, "the layer has an invalid time stretch"));
|
||||
}
|
||||
let in_range = |t: i64| (Tick::MIN.0..=Tick::MAX.0).contains(&t);
|
||||
if !in_range(time.0) {
|
||||
return Err(effect_time_error(cmd));
|
||||
}
|
||||
let offset = if to_comp { time.0 } else { time.0.checked_sub(layer.start_time.0).ok_or_else(|| effect_time_error(cmd))? };
|
||||
let scaled = if (layer.stretch - 100.0).abs() < 1e-9 {
|
||||
offset
|
||||
} else {
|
||||
let scaled = if to_comp { offset as f64 * layer.stretch / 100.0 } else { offset as f64 * 100.0 / layer.stretch };
|
||||
if !scaled.is_finite() || scaled < Tick::MIN.0 as f64 || scaled > Tick::MAX.0 as f64 {
|
||||
return Err(effect_time_error(cmd));
|
||||
}
|
||||
scaled as i64
|
||||
};
|
||||
if !in_range(scaled) {
|
||||
return Err(effect_time_error(cmd));
|
||||
}
|
||||
let time = if to_comp { layer.start_time.0.checked_add(scaled).ok_or_else(|| effect_time_error(cmd))? } else { scaled };
|
||||
if !in_range(time) {
|
||||
return Err(effect_time_error(cmd));
|
||||
}
|
||||
Ok(Tick(time))
|
||||
}
|
||||
|
||||
/// Change the key time coordinate system throughout an effect, including nested controls.
|
||||
/// Ease speeds are per second in that coordinate system; reversed time swaps the key sides.
|
||||
fn retime_effect(group: &mut PropGroup, scale: f64, cmd: &str, mut time: impl FnMut(Tick) -> Result<Tick>) -> Result<()> {
|
||||
let mut result = Ok(());
|
||||
group.walk_mut(&mut |pr| {
|
||||
if result.is_err() {
|
||||
return;
|
||||
}
|
||||
for key in &mut pr.keys {
|
||||
let mapped = time(key.time).and_then(|t| {
|
||||
if !scale.is_finite() || scale == 0.0 {
|
||||
return Err(effect_time_error(cmd));
|
||||
}
|
||||
// Spatial paths and non-numeric values ease along positive progress;
|
||||
// numeric components instead store a signed value derivative.
|
||||
let speed_scale = if pr.spatial || key.value.dims() == 0 { scale.abs() } else { scale };
|
||||
for ease in key.in_ease.iter_mut().chain(&mut key.out_ease) {
|
||||
ease.speed /= speed_scale;
|
||||
if !ease.speed.is_finite() {
|
||||
return Err(bad(cmd, "an effect keyframe ease converts outside the supported range"));
|
||||
}
|
||||
}
|
||||
if scale < 0.0 {
|
||||
std::mem::swap(&mut key.in_interp, &mut key.out_interp);
|
||||
std::mem::swap(&mut key.in_ease, &mut key.out_ease);
|
||||
std::mem::swap(&mut key.spatial_in, &mut key.spatial_out);
|
||||
}
|
||||
Ok(t)
|
||||
});
|
||||
match mapped {
|
||||
Ok(t) => key.time = t,
|
||||
Err(e) => {
|
||||
result = Err(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
pr.keys.sort_by_key(|key| key.time);
|
||||
if pr.keys.windows(2).any(|pair| pair[0].time == pair[1].time) {
|
||||
result = Err(bad(cmd, "the layer's time stretch maps effect keyframes to the same tick"));
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// Edit ▸ Copy with effects selected: times on the clipboard are comp-time offsets from the
|
||||
/// earliest copied key, shared by all copied effects and their parameters (#989).
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.copy";
|
||||
let fx = effects_p(s, p, "effect.copy")?;
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let groups: Vec<PropGroup> =
|
||||
fx.iter().filter_map(|(l, u)| comp.layer(*l).and_then(|l| l.effects()).and_then(|e| e.groups().find(|g| g.uid == *u)).cloned()).collect();
|
||||
let mut groups = Vec::new();
|
||||
let mut earliest: Option<Tick> = None;
|
||||
for (lid, uid) in fx {
|
||||
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
let mut group = layer.effects().and_then(|fx| fx.groups().find(|g| g.uid == uid)).cloned().ok_or_else(|| bad(CMD, "the effect no longer exists"))?;
|
||||
retime_effect(&mut group, layer.stretch / 100.0, CMD, |t| {
|
||||
let t = effect_time(layer, t, true, CMD)?;
|
||||
earliest = Some(earliest.map_or(t, |first| first.min(t)));
|
||||
Ok(t)
|
||||
})?;
|
||||
groups.push(group);
|
||||
}
|
||||
if let Some(first) = earliest {
|
||||
for group in &mut groups {
|
||||
retime_effect(group, 1.0, CMD, |t| Ok(Tick(t.0.checked_sub(first.0).ok_or_else(|| effect_time_error(CMD))?)))?;
|
||||
}
|
||||
}
|
||||
s.state.clipboard.clear();
|
||||
s.state.key_clipboard.clear();
|
||||
s.state.contents_clipboard.clear();
|
||||
@@ -326,8 +442,10 @@ pub(crate) fn unique_name(fx: &PropGroup, base: &str) -> String {
|
||||
}
|
||||
|
||||
/// Edit ▸ Paste with effects on the clipboard: adds copies to every target layer, after the
|
||||
/// layer's selected effect when it has one, else at the end of its stack.
|
||||
/// layer's selected effect when it has one, else at the end of its stack. The earliest copied
|
||||
/// key lands at the destination comp's CTI; all other keys keep their comp-time offsets.
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.paste";
|
||||
let clip = s.state.effect_clipboard.clone();
|
||||
if clip.is_empty() {
|
||||
return Err(bad("effect.paste", "no effects on the clipboard"));
|
||||
@@ -337,6 +455,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("effect.paste", "select a layer to paste effects onto"));
|
||||
}
|
||||
let sel = selected_effects(s);
|
||||
let cti = s.time_of(cid);
|
||||
let label = if clip.len() == 1 { format!("Paste {}", clip[0].name) } else { "Paste Effects".to_string() };
|
||||
let uids = s.edit(&label, None, |proj, st| {
|
||||
let mut out = vec![];
|
||||
@@ -344,6 +463,13 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut new_sel = vec![];
|
||||
for lid in &ids {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let mut groups = clip.clone();
|
||||
for group in &mut groups {
|
||||
retime_effect(group, 100.0 / l.stretch, CMD, |offset| {
|
||||
let t = Tick(cti.0.checked_add(offset.0).ok_or_else(|| effect_time_error(CMD))?);
|
||||
effect_time(l, t, false, CMD)
|
||||
})?;
|
||||
}
|
||||
let Some(fx) = l.props.sub_mut("effects") else { continue };
|
||||
let at = sel
|
||||
.iter()
|
||||
@@ -352,8 +478,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.max()
|
||||
.map(|i| i + 1)
|
||||
.unwrap_or(fx.children.len());
|
||||
for (k, g) in clip.iter().enumerate() {
|
||||
let mut g = g.clone();
|
||||
for (k, mut g) in groups.into_iter().enumerate() {
|
||||
g.reassign_uids(&mut next);
|
||||
g.name = unique_name(fx, &g.name);
|
||||
out.push(g.uid);
|
||||
@@ -397,6 +522,35 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Tint's Swap Colors button edits both swatches at the CTI in one undo step. Like Reset,
|
||||
/// it keys animated parameters without moving their existing keys or replacing expressions.
|
||||
fn swap_tint_colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "effect.swapTintColors";
|
||||
if !p.is_object() || p.get("effect").is_some_and(|v| !v.is_string() && v.as_u64().is_none_or(|n| n == 0)) {
|
||||
return Err(bad(cmd, "effect must be a positive index, uid or name"));
|
||||
}
|
||||
let (cid, lid, uid) = find_fx(s, p, cmd)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
let g = layer.props.find_group(uid).filter(|g| g.match_id == "ec.color.tint").ok_or_else(|| bad(cmd, "not a Tint effect"))?;
|
||||
let lt = layer.layer_time(s.time_of(cid));
|
||||
let color = |id| {
|
||||
g.prop(id)
|
||||
.map(|pr| pr.value_at(lt))
|
||||
.filter(|v| matches!(v, effectcraft_keyframe::Value::Color(_)))
|
||||
.ok_or_else(|| bad(cmd, "Tint is missing a colour parameter"))
|
||||
};
|
||||
let (black, white) = (color("black")?, color("white")?);
|
||||
s.edit("Swap Tint Colors", None, |proj, _| {
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad(cmd, "effect gone"))?;
|
||||
for (id, value) in [("black", white), ("white", black)] {
|
||||
g.prop_mut(id).ok_or_else(|| bad(cmd, "Tint is missing a colour parameter"))?.set_value_at(lt, value);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"effect": uid}))
|
||||
}
|
||||
|
||||
fn last(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = s.state.last_effect.clone().ok_or_else(|| bad("effect.applyLast", "no effect applied yet"))?;
|
||||
let mut q = p.clone();
|
||||
@@ -482,11 +636,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("effect.removeAll", "Remove All", ["Effect"], Some("Cmd+Shift+E"), "{layers?}", has_layers, remove_all),
|
||||
cmd!("effect.remove", "Remove Effect", [], None, "{layer?, effect: index|uid|name}", has_layers, remove),
|
||||
cmd!("effect.toggle", "Toggle Effect", [], None, "{layer?, effect, value?}", has_layers, toggle),
|
||||
cmd!("effect.setLabel", "Effect Label", [], None, "{layer?, effect, label: name|index 0-16 (None clears)}", has_layers, set_label),
|
||||
cmd!("effect.reorder", "Reorder Effect", [], None, "{layer?, effect, index}", has_layers, reorder),
|
||||
cmd!("effect.duplicate", "Duplicate Effect", [], None, "{layer?, effect}", has_layers, duplicate),
|
||||
cmd!("effect.copy", "Copy Effects", [], None, "{layer?, effect? | effects?: [uid|name|index]} (default: the selected effects)", has_layers, copy),
|
||||
cmd!("effect.paste", "Paste Effects", [], None, "{layers?} — adds the copied effects to the layers", has_layers, paste),
|
||||
cmd!("effect.reset", "Reset Effect", [], None, "{layer?, effect}", has_layers, reset),
|
||||
cmd!(
|
||||
"effect.swapTintColors",
|
||||
"Swap Tint Colors",
|
||||
[],
|
||||
None,
|
||||
"{comp?, layer?, effect?: index|uid|name} — swaps Tint's Map Black To and Map White To at the current layer time in one undo step",
|
||||
has_layers,
|
||||
swap_tint_colors
|
||||
),
|
||||
crate::query!(
|
||||
"effect.list",
|
||||
"List Effects",
|
||||
|
||||
@@ -245,6 +245,8 @@ struct PendingImport {
|
||||
comps: Vec<u64>,
|
||||
items: Vec<u64>,
|
||||
errors: Vec<String>,
|
||||
/// EffectCraft projects merged in (`file.importProject` results); never added to a comp.
|
||||
projects: Vec<Value>,
|
||||
}
|
||||
|
||||
/// Everything probing a file needs, apart from the session (it can run on a background thread).
|
||||
@@ -370,10 +372,18 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result<PendingImport> {
|
||||
_ => return Err(bad("file.import", "page: a page number from 1")),
|
||||
},
|
||||
};
|
||||
let mut paths = paths;
|
||||
let mut comps = vec![];
|
||||
let mut items = vec![];
|
||||
let mut errors = vec![];
|
||||
// EffectCraft projects import as projects, as After Effects imports an .aep.
|
||||
let (project_paths, mut paths): (Vec<String>, Vec<String>) = paths.into_iter().partition(|x| super::import_project::is_project_path(x));
|
||||
let mut projects = vec![];
|
||||
for path in project_paths {
|
||||
match s.execute("file.importProject", json!({"path": path})) {
|
||||
Ok(r) => projects.push(r),
|
||||
Err(e) => errors.push(format!("{path}: {e}")),
|
||||
}
|
||||
}
|
||||
if let Some(retain) = retain {
|
||||
let mut rest = vec![];
|
||||
for path in paths {
|
||||
@@ -424,13 +434,13 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result<PendingImport> {
|
||||
page,
|
||||
psd_layer: p.get("layer").cloned(),
|
||||
};
|
||||
Ok(PendingImport { sources, prober, comps, items, errors })
|
||||
Ok(PendingImport { sources, prober, comps, items, errors, projects })
|
||||
}
|
||||
|
||||
/// The last part of an import: add the probed files to the project (one undo step) and select
|
||||
/// everything the import made, so the Project panel shows it.
|
||||
fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result::Result<Probed, String>>) -> Result<Value> {
|
||||
let PendingImport { comps, mut items, mut errors, .. } = pending;
|
||||
let PendingImport { comps, mut items, mut errors, projects, .. } = pending;
|
||||
let mut found = vec![];
|
||||
let mut warnings = vec![];
|
||||
for r in probed {
|
||||
@@ -445,6 +455,11 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result:
|
||||
let mut asked: Vec<u64> = vec![];
|
||||
let made: Vec<ItemId> = comps.iter().map(|c| ItemId(*c)).collect();
|
||||
if !found.is_empty() {
|
||||
// The file may have been overwritten since an earlier import or project decoded it (the
|
||||
// media layer keys frames by path): a fresh import reads it again (#1070).
|
||||
for f in &found {
|
||||
s.forget_decoded(&f.footage);
|
||||
}
|
||||
s.edit("Import", None, |proj, st| {
|
||||
let mut selection = made;
|
||||
for f in found {
|
||||
@@ -482,7 +497,11 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result:
|
||||
if let Some(first) = asked.first() {
|
||||
s.events.push(crate::Event::Frontend { command: "file.interpretFootage".into(), params: json!({"item": first, "reason": "unlabeledAlpha"}) });
|
||||
}
|
||||
Ok(json!({"items": items, "comps": comps, "errors": errors, "warnings": warnings, "unlabeledAlpha": asked}))
|
||||
let mut out = json!({"items": items, "comps": comps, "errors": errors, "warnings": warnings, "unlabeledAlpha": asked});
|
||||
if !projects.is_empty() {
|
||||
out["projects"] = Value::Array(projects);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether a file format states how its alpha is stored (PNG, GIF, WebP and PSD are straight by
|
||||
|
||||
@@ -207,6 +207,10 @@ fn new_comp_from_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = lead.name.rsplit_once('.').map(|(a, _)| a.to_string()).unwrap_or(lead.name.clone());
|
||||
let c = Comp { pixel_aspect, ..Comp::new(w.max(1), h.max(1), rate, dur) };
|
||||
let cid = s.edit("New Comp from Selection", None, |proj, st| {
|
||||
// A name another item already has gets the next free number, as Duplicate gives
|
||||
// ("clip", "clip 2", "clip 3"). The comp's own footage and solid sources don't
|
||||
// count, so an extensionless one still names its first comp; a source comp does.
|
||||
let name = proj.unique_item_name(&name, |i| g.contains(&i.id) && !matches!(i.kind, ItemKind::Comp(_)));
|
||||
let cid = proj.add_item(&name, Label::Sandstone, None, ItemKind::Comp(c.into()));
|
||||
st.project_selection = vec![cid];
|
||||
Ok(cid)
|
||||
@@ -771,9 +775,9 @@ fn interpret(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Interpret Footage", None, |proj, _| {
|
||||
for (i, g) in items.iter().zip(&guesses) {
|
||||
let Some(ItemKind::Footage(f)) = proj.item_mut(*i).map(|x| &mut x.kind) else { continue };
|
||||
let old = f.duration;
|
||||
let old = f.looped_duration();
|
||||
it.apply(f, *g);
|
||||
let new = f.duration;
|
||||
let new = f.looped_duration();
|
||||
if new == old {
|
||||
continue;
|
||||
}
|
||||
@@ -849,14 +853,32 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src = crate::sequence::source_of(s.services.as_ref(), &path, opts);
|
||||
let f = crate::sequence::probe(importer.as_ref(), &src, s.sequence_rate()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let name = src.name();
|
||||
// Replacing a missing file relinks the other missing files that moved with it (as After Effects
|
||||
// does when you locate one).
|
||||
let moved = match s.project.item(item).map(|it| &it.kind) {
|
||||
Some(ItemKind::Footage(previous)) if previous.missing || !s.services.exists(&previous.path) => {
|
||||
super::relink_moved::moved_with(s, item, &previous.path, &path)
|
||||
}
|
||||
_ => vec![],
|
||||
};
|
||||
let relinked: Vec<u64> = moved.iter().map(|(id, _)| id.0).collect();
|
||||
s.edit("Replace Footage", None, |proj, _| {
|
||||
let it = proj.item_mut(item).ok_or_else(|| bad("file.replaceFootage", "no such item"))?;
|
||||
it.name = name;
|
||||
it.kind = ItemKind::Footage(f);
|
||||
retarget_layers(proj, item, |_| LayerSource::Footage { item });
|
||||
for (id, nf) in moved {
|
||||
if let Some(it) = proj.item_mut(id) {
|
||||
it.kind = ItemKind::Footage(nf);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
if relinked.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
s.toast(format!("Also relinked {} other missing footage item(s)", relinked.len()));
|
||||
Ok(json!({"relinked": relinked}))
|
||||
}
|
||||
|
||||
/// Point every layer using `item` at a new source kind.
|
||||
|
||||
@@ -37,6 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fe!("app.keyboardShortcuts", "Keyboard Shortcuts", ["Edit"], Some("Cmd+Alt+'"), "{}", always),
|
||||
fe!("app.templates", "Templates", [], None, "{kind: renderSettings|outputModule}", always),
|
||||
fe!("app.find", "Find", ["File"], Some("Cmd+F"), "{query?}", always),
|
||||
fe!("effects.copyPresetsFolderPath", "Copy Presets Folder Path", [], None, "{}", always),
|
||||
// Preview.
|
||||
fe!(
|
||||
"playback.toggle",
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! File ▸ Import ▸ EffectCraft Project: merge another `.ecproj` (or its XML copy) into the
|
||||
//! current project, as After Effects imports an `.aep` into the open project. The imported
|
||||
//! items land in a folder named after the file; every id is shifted past the current project's
|
||||
//! so nothing collides, and the whole import is one undo step.
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_project::{ItemId, ItemKind, LayerSource, Project, essential};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
const C: &str = "file.importProject";
|
||||
|
||||
/// Whether `path` names a project EffectCraft imports as a project (not as footage).
|
||||
pub(crate) fn is_project_path(path: &str) -> bool {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
lower.ends_with(".ecproj") || lower.ends_with(".ecprojx")
|
||||
}
|
||||
|
||||
/// Read a project file (JSON or its XML copy), as File ▸ Open does.
|
||||
fn read_project(s: &Session, path: &str) -> Result<(Project, Option<String>)> {
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let text = String::from_utf8(bytes).map_err(|_| bad(C, format!("{path} is not a text project file")))?;
|
||||
let text = if crate::xml_project::is_xml(&text) { crate::xml_project::from_xml(&text).map_err(EngineError::Other)? } else { text };
|
||||
let project = Project::from_json(&text).map_err(|e| bad(C, format!("{path} is not a project EffectCraft can open: {e}")))?;
|
||||
Ok((project, effectcraft_project::saved_by(&text)))
|
||||
}
|
||||
|
||||
/// Footage paths relative to the imported project's folder become absolute when the file is
|
||||
/// there; returns the footage paths that are missing.
|
||||
fn resolve_footage(s: &Session, project: &mut Project, dir: &std::path::Path) -> Vec<String> {
|
||||
let services = s.services.clone();
|
||||
let resolve = |raw: &mut String| -> bool {
|
||||
if raw.is_empty() || services.exists(raw) {
|
||||
return true;
|
||||
}
|
||||
if std::path::Path::new(raw.as_str()).is_absolute() {
|
||||
return false;
|
||||
}
|
||||
let joined = dir.join(raw.as_str()).to_string_lossy().to_string();
|
||||
if services.exists(&joined) {
|
||||
*raw = joined;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
let mut missing = vec![];
|
||||
for it in project.items.values_mut() {
|
||||
if let ItemKind::Footage(f) = &mut it.kind {
|
||||
if f.sequence.is_empty() {
|
||||
if !resolve(&mut f.path) {
|
||||
missing.push(f.path.clone());
|
||||
}
|
||||
} else {
|
||||
let mut all = true;
|
||||
for frame in &mut f.sequence {
|
||||
all &= resolve(frame);
|
||||
}
|
||||
if !all {
|
||||
missing.push(f.path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
missing
|
||||
}
|
||||
|
||||
/// The comps no other comp of `project` nests: the ones to open or place.
|
||||
fn root_comps(project: &Project) -> Vec<ItemId> {
|
||||
let nested: std::collections::HashSet<ItemId> =
|
||||
project.comps().flat_map(|(_, c)| c.layers.iter().filter_map(|l| if let LayerSource::Comp { item } = l.source { Some(item) } else { None })).collect();
|
||||
project.comps().map(|(id, _)| *id).filter(|id| !nested.contains(id)).collect()
|
||||
}
|
||||
|
||||
fn import_project(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(C, "missing `path` (.ecproj)"))?.to_string();
|
||||
let (mut sub, saved_by) = read_project(s, &path)?;
|
||||
crate::upgrade_effects(&mut sub);
|
||||
let file = std::path::Path::new(&path);
|
||||
let dir = file.parent().map(|d| d.to_path_buf()).unwrap_or_default();
|
||||
let missing = resolve_footage(s, &mut sub, &dir);
|
||||
// The imported project's own render queue stays behind (as for templates).
|
||||
let base = s.project.next_id;
|
||||
if sub.next_id.checked_add(base).is_none() {
|
||||
return Err(bad(C, format!("{path} has ids out of range")));
|
||||
}
|
||||
essential::offset_ids(&mut sub, base);
|
||||
let roots: Vec<ItemId> = root_comps(&sub);
|
||||
let folder_name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Imported Project".into());
|
||||
let (folder, items) = s.edit("Import Project", None, |proj, st| {
|
||||
let folder = proj.add_item(&folder_name, Label::Yellow, None, ItemKind::Folder);
|
||||
let mut items = vec![];
|
||||
for (id, mut it) in std::mem::take(&mut sub.items) {
|
||||
if it.parent.is_none() {
|
||||
it.parent = Some(folder);
|
||||
}
|
||||
items.push(id.0);
|
||||
proj.items.insert(id, it);
|
||||
}
|
||||
proj.next_id = proj.next_id.max(sub.next_id);
|
||||
proj.fix_next_id();
|
||||
st.project_selection = vec![folder];
|
||||
Ok((folder, items))
|
||||
})?;
|
||||
let comps: Vec<Value> = s
|
||||
.project
|
||||
.comps()
|
||||
.filter(|(id, _)| items.contains(&id.0))
|
||||
.map(|(id, _)| json!({"id": id.0, "name": s.project.item(*id).map(|i| i.name.clone()).unwrap_or_default()}))
|
||||
.collect();
|
||||
let primary = if let [one] = roots.as_slice() { Some(one.0) } else { None };
|
||||
let mut warnings = vec![];
|
||||
if let Some(v) = saved_by.as_deref().filter(|v| effectcraft_project::is_newer_version(v, effectcraft_project::APP_VERSION)) {
|
||||
warnings.push(format!("saved by EffectCraft {v}, newer than this version ({})", effectcraft_project::APP_VERSION));
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
warnings.push(format!("{} footage file{} missing", missing.len(), if missing.len() == 1 { " is" } else { "s are" }));
|
||||
}
|
||||
s.toast(if warnings.is_empty() { format!("Imported {folder_name}") } else { format!("Imported {folder_name}: {}", warnings.join("; ")) });
|
||||
Ok(json!({
|
||||
"folder": folder.0,
|
||||
"items": items,
|
||||
"comps": comps,
|
||||
"rootComps": roots.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
"primaryComp": primary,
|
||||
"missingMedia": missing,
|
||||
"warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"file.importProject",
|
||||
"EffectCraft Project...",
|
||||
["File", "Import"],
|
||||
None,
|
||||
"{path (.ecproj or .ecprojx)} — merges the project into a folder named after the file; returns {folder, items, comps, rootComps, primaryComp (the only root comp, else null), missingMedia, warnings}",
|
||||
always,
|
||||
import_project
|
||||
)]
|
||||
}
|
||||
@@ -283,7 +283,7 @@ fn add_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&serde_json::json!({"comp": cid.0, "item": item.0, "time": f_p(p, "time"), "index": p.get("index"), "position": p.get("position")}),
|
||||
);
|
||||
}
|
||||
ItemKind::Footage(f) => (LayerSource::Footage { item }, (f.width, f.height), Some(f.duration)),
|
||||
ItemKind::Footage(f) => (LayerSource::Footage { item }, (f.width, f.height), Some(f.looped_duration())),
|
||||
ItemKind::Solid(so) => (LayerSource::Solid { item }, (so.width, so.height), None),
|
||||
ItemKind::Folder => return Err(bad("layer.addItem", "folders can't be layers")),
|
||||
};
|
||||
@@ -647,6 +647,28 @@ impl ParentFix {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Cameras and lights aim with Point of Interest: move it by the same parent-space
|
||||
// change, so a two-node rig keeps its world frame (#1010, #1020).
|
||||
if let Some(pr) = tr.get_mut("poi") {
|
||||
pr.value = map_position(&pr.value);
|
||||
for key in &mut pr.keys {
|
||||
key.value = map_position(&key.value);
|
||||
for tangent in [&mut key.spatial_in, &mut key.spatial_out] {
|
||||
let v = m.apply_vec(effectcraft_geom::Vec3::from(*tangent));
|
||||
*tangent = [v.x, v.y, v.z];
|
||||
}
|
||||
}
|
||||
if let Some(factor) = position_speed
|
||||
.filter(|_| pr.spatial)
|
||||
.filter(|factor| pr.keys.iter().flat_map(|key| key.in_ease.iter().chain(&key.out_ease)).all(|ease| (ease.speed * *factor).is_finite()))
|
||||
{
|
||||
for key in &mut pr.keys {
|
||||
for ease in key.in_ease.iter_mut().chain(&mut key.out_ease) {
|
||||
ease.speed *= factor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((orientation, factor)) = self.pose_3d {
|
||||
if let Some(pr) = tr.get_mut("orientation") {
|
||||
pr.value = KV::Vec3(orientation);
|
||||
@@ -743,13 +765,15 @@ fn uniform_parent_pose(m: effectcraft_geom::Mat4, orientation: [f64; 3]) -> Opti
|
||||
return Some((orientation, factor));
|
||||
}
|
||||
let r = (rotation * Mat4::orientation(Vec3::from(orientation))).0;
|
||||
let sy = (-r[2][0]).clamp(-1.0, 1.0);
|
||||
let y = sy.asin();
|
||||
let (x, z) = if (1.0 - sy * sy).sqrt() > 1e-9 { (r[2][1].atan2(r[2][2]), r[1][0].atan2(r[0][0])) } else { ((-r[1][2]).atan2(r[1][1]), 0.0) };
|
||||
// atan2 rather than asin: near ±90 degrees asin loses precision, while cos(y) stays exact.
|
||||
let cy = r[0][0].hypot(r[1][0]);
|
||||
let y = (-r[2][0]).atan2(cy);
|
||||
let (x, z) = if cy > 1e-9 { (r[2][1].atan2(r[2][2]), r[1][0].atan2(r[0][0])) } else { ((-r[1][2]).atan2(r[1][1]), 0.0) };
|
||||
Some(([x.to_degrees(), y.to_degrees(), z.to_degrees()], factor))
|
||||
}
|
||||
|
||||
/// A parent change retains 2D transforms and the world-space anchor of 3D AV layers. Position is
|
||||
/// A parent change retains 2D transforms and the world-space anchor of 3D layers (Position,
|
||||
/// and Point of Interest for two-node cameras and lights). Position is
|
||||
/// re-expressed in the new parent's space (`None`: the composition), evaluated at the current
|
||||
/// time.
|
||||
pub(crate) fn parent_fixes(s: &Session, cid: ItemId, ids: &[LayerId], parent: Option<LayerId>) -> Vec<ParentFix> {
|
||||
@@ -793,7 +817,10 @@ pub(crate) fn parent_fixes(s: &Session, cid: ItemId, ids: &[LayerId], parent: Op
|
||||
})
|
||||
};
|
||||
if let Some(inv) = space_3d(parent).inverse().filter(|m| m.0.iter().flatten().all(|v| v.is_finite())) {
|
||||
for layer in comp.layers.iter().filter(|l| ids.contains(&l.id) && l.is_3d() && !l.is_camera() && !l.is_light() && l.parent != parent) {
|
||||
// Cameras and lights compensate like 3D layers (Position, and Point of Interest for
|
||||
// two-node rigs), so parenting keeps the world frame (#1010, #1020). They have no
|
||||
// Scale, so `pose_3d` below stays `None` and Orientation is kept as authored.
|
||||
for layer in comp.layers.iter().filter(|l| ids.contains(&l.id) && l.is_3d() && l.parent != parent) {
|
||||
let m = inv * space_3d(layer.parent);
|
||||
if m.0.iter().flatten().all(|v| v.is_finite()) {
|
||||
let pose_3d = layer.transform().and_then(|tr| {
|
||||
@@ -919,6 +946,14 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = t - l.out_point;
|
||||
shift(l, d);
|
||||
}
|
||||
"moveInToStart" => {
|
||||
let d = Tick::ZERO - l.in_point;
|
||||
shift(l, d);
|
||||
}
|
||||
"moveOutToEnd" => {
|
||||
let d = comp_dur - l.out_point;
|
||||
shift(l, d);
|
||||
}
|
||||
"trimInToTime" => l.in_point = t.min(l.out_point - fd),
|
||||
"trimOutToTime" => l.out_point = t.max(l.in_point + fd),
|
||||
_ => {
|
||||
@@ -951,6 +986,20 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// `p` with `key` set.
|
||||
fn with(p: &Value, key: &str, v: Value) -> Value {
|
||||
let mut p = if p.is_object() { p.clone() } else { json!({}) };
|
||||
p[key] = v;
|
||||
p
|
||||
}
|
||||
|
||||
/// Move the layers `frames` frames in time (Alt+Page Up / Page Down, with Shift ten frames).
|
||||
fn move_frames(s: &mut Session, p: &Value, frames: i64) -> Result<Value> {
|
||||
let (cid, _) = layers_p(s, p)?;
|
||||
let delta = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_rate.tick_of(frames).seconds();
|
||||
timing(s, &with(p, "delta", json!(delta)))
|
||||
}
|
||||
|
||||
/// Slip edit: move a layer's source (footage or precomp) under its fixed in and out points, like
|
||||
/// dragging the source-duration bar in After Effects. `delta` in seconds or `frames`; positive
|
||||
/// moves the source later. Clamped so the source still covers the in–out span. Keyframes and
|
||||
@@ -972,7 +1021,7 @@ fn slip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let dur = match &l.source {
|
||||
LayerSource::Footage { item } => match s.project.item(*item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) if f.kind != effectcraft_project::FootageKind::Still => Some(Tick(f.duration.0 * f.loop_count.max(1) as i64)),
|
||||
Some(ItemKind::Footage(f)) if f.kind != effectcraft_project::FootageKind::Still => Some(f.looped_duration()),
|
||||
_ => None,
|
||||
},
|
||||
LayerSource::Comp { item } => s.project.comp(*item).map(|c| c.duration),
|
||||
@@ -1580,6 +1629,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("layer.select", "Select Layers", [], None, "{layers: [id|name|#n], add?, toggle?}", has_comp, select),
|
||||
cmd!("layer.selectNext", "Select Next Layer", [], Some("Cmd+ArrowDown"), "{add?}", has_comp, select_next),
|
||||
cmd!("layer.selectPrevious", "Select Previous Layer", [], Some("Cmd+ArrowUp"), "{add?}", has_comp, select_prev),
|
||||
cmd!("layer.extendSelectionNext", "Extend Selection to Next Layer", [], Some("Cmd+Shift+ArrowDown"), "{}", has_comp, |s, _| select_step(
|
||||
s,
|
||||
&json!({"add": true}),
|
||||
1
|
||||
)),
|
||||
cmd!("layer.extendSelectionPrevious", "Extend Selection to Previous Layer", [], Some("Cmd+Shift+ArrowUp"), "{}", has_comp, |s, _| select_step(
|
||||
s,
|
||||
&json!({"add": true}),
|
||||
-1
|
||||
)),
|
||||
cmd!(
|
||||
"layer.setSwitch",
|
||||
"Layer Switch",
|
||||
@@ -1607,17 +1666,29 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Timing",
|
||||
[],
|
||||
None,
|
||||
"{layers?, op?: moveInToTime|moveOutToTime|trimInToTime|trimOutToTime, delta?, start?, in?, out?, inDelta?, outDelta? (seconds, per layer), merge?}",
|
||||
"{layers?, op?: moveInToTime|moveOutToTime|moveInToStart|moveOutToEnd|trimInToTime|trimOutToTime, delta?, start?, in?, out?, inDelta?, outDelta? (seconds, per layer), merge?}",
|
||||
has_layers,
|
||||
timing
|
||||
),
|
||||
cmd!("layer.moveInToStart", "Move Layer In Point to Beginning of Comp", [], Some("Alt+Home"), "{layers?}", has_layers, |s, p| timing(
|
||||
s,
|
||||
&with(p, "op", json!("moveInToStart"))
|
||||
)),
|
||||
cmd!("layer.moveOutToEnd", "Move Layer Out Point to End of Comp", [], Some("Alt+End"), "{layers?}", has_layers, |s, p| timing(
|
||||
s,
|
||||
&with(p, "op", json!("moveOutToEnd"))
|
||||
)),
|
||||
cmd!("layer.moveEarlier", "Move Layers 1 Frame Earlier", [], Some("Alt+PageUp"), "{layers?}", has_layers, |s, p| move_frames(s, p, -1)),
|
||||
cmd!("layer.moveLater", "Move Layers 1 Frame Later", [], Some("Alt+PageDown"), "{layers?}", has_layers, |s, p| move_frames(s, p, 1)),
|
||||
cmd!("layer.moveEarlier10", "Move Layers 10 Frames Earlier", [], Some("Alt+Shift+PageUp"), "{layers?}", has_layers, |s, p| move_frames(s, p, -10)),
|
||||
cmd!("layer.moveLater10", "Move Layers 10 Frames Later", [], Some("Alt+Shift+PageDown"), "{layers?}", has_layers, |s, p| move_frames(s, p, 10)),
|
||||
cmd!("layer.slip", "Slip Edit", [], None, "{layers?, delta? (seconds) | frames?, merge?}", has_layers, slip),
|
||||
cmd!("layer.slipBack", "Slip Edit 1 Frame Earlier", [], Some("Alt+PageUp"), "{layers?}", has_layers, |s, p| {
|
||||
cmd!("layer.slipBack", "Slip Edit 1 Frame Earlier", [], None, "{layers?}", has_layers, |s, p| {
|
||||
let mut p = p.clone();
|
||||
p["frames"] = json!(-1);
|
||||
slip(s, &p)
|
||||
}),
|
||||
cmd!("layer.slipForward", "Slip Edit 1 Frame Later", [], Some("Alt+PageDown"), "{layers?}", has_layers, |s, p| {
|
||||
cmd!("layer.slipForward", "Slip Edit 1 Frame Later", [], None, "{layers?}", has_layers, |s, p| {
|
||||
let mut p = p.clone();
|
||||
p["frames"] = json!(1);
|
||||
slip(s, &p)
|
||||
|
||||
@@ -6,7 +6,7 @@ use effectcraft_project::{FrameBlend, GroupKind, ItemId, LayerId, LayerSource, M
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, comp_id, f_p, frontend, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, str_p};
|
||||
use super::{CommandSpec, b_p, bad, comp_id, f_p, frontend, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, str_p, time_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
// ---------------------------------------------------------------- enablement
|
||||
@@ -76,6 +76,13 @@ fn sampling(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"bicubic" => Sampling::Bicubic,
|
||||
q => return Err(bad("layer.sampling", format!("sampling must be bilinear|bicubic, not `{q}`"))),
|
||||
};
|
||||
// `toggle`: layers that all have it already get the other one.
|
||||
let all = s.project.comp(cid).is_some_and(|c| c.layers.iter().filter(|l| ids.contains(&l.id)).all(|l| l.switches.sampling == q));
|
||||
let q = match q {
|
||||
Sampling::Bilinear if all && b_p(p, "toggle").unwrap_or(false) => Sampling::Bicubic,
|
||||
Sampling::Bicubic if all && b_p(p, "toggle").unwrap_or(false) => Sampling::Bilinear,
|
||||
q => q,
|
||||
};
|
||||
s.edit("Layer Sampling", None, |proj, _| {
|
||||
for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
l.switches.sampling = q;
|
||||
@@ -545,11 +552,17 @@ fn mask_lock_others(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn add_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("layer.addMarker", "no layer"));
|
||||
}
|
||||
let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(s.time());
|
||||
let t = time_p(s, p, s.project.comp(cid));
|
||||
let comment = str_p(p, "comment").unwrap_or_default().to_string();
|
||||
if ids.is_empty() {
|
||||
s.edit("Add Marker", None, |proj, _| {
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
c.markers.push(Marker { time: t, comment, ..Default::default() });
|
||||
c.markers.sort_by_key(|m| m.time);
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"time": t.seconds()}));
|
||||
}
|
||||
s.edit("Add Marker", None, |proj, _| {
|
||||
for lid in &ids {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
@@ -800,7 +813,7 @@ fn sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("layer.quality", "Quality", [], None, "{layers?, quality: best|draft|wireframe}", has_layers, quality),
|
||||
cmd!("layer.sampling", "Sampling", [], None, "{layers?, sampling: bilinear|bicubic}", has_layers, sampling),
|
||||
cmd!("layer.sampling", "Sampling", [], None, "{layers?, sampling: bilinear|bicubic, toggle?}", has_layers, sampling),
|
||||
cmd!("layer.frameBlending", "Frame Blending", [], None, "{layers?, mode: off|frameMix|pixelMotion}", has_layers, frame_blending),
|
||||
cmd!("layer.hideOtherVideo", "Hide Other Video", ["Layer", "Switches"], Some("Cmd+Alt+Shift+V"), "{layers?}", has_layers, hide_other_video),
|
||||
cmd!("layer.showAllVideo", "Show All Video", ["Layer", "Switches"], None, "{comp?}", has_comp, show_all_video),
|
||||
@@ -842,7 +855,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("layer.mask.lock", "Locked", ["Layer", "Mask"], None, "{layer?, mask?, value?}", has_masks, mask_lock),
|
||||
cmd!("layer.mask.unlockAll", "Unlock All Masks", ["Layer", "Mask"], None, "{layers?}", has_masks, mask_unlock_all),
|
||||
cmd!("layer.mask.lockOthers", "Lock Other Masks", ["Layer", "Mask"], None, "{layer?, mask?}", has_masks, mask_lock_others),
|
||||
cmd!("layer.addMarker", "Add Marker", ["Layer", "Markers"], None, "{layers?, time?, comment?}", has_layers, add_marker),
|
||||
cmd!("layer.addMarker", "Add Marker", ["Layer", "Markers"], None, "{layers?, time?, comment?}", has_comp, add_marker),
|
||||
cmd!("layer.markersLock", "Lock Markers", ["Layer", "Markers"], None, "{layers?, value?}", has_layers, markers_lock),
|
||||
cmd!("layer.deleteAllMarkers", "Delete All Markers", ["Layer", "Markers"], None, "{layers?}", has_markers, delete_all_markers),
|
||||
cmd!("layer.trackMatte", "Track Matte", [], None, "{layers?, op: none|alpha|alphaInverted|luma|lumaInverted|above|below}", has_layers, track_matte_op),
|
||||
|
||||
@@ -24,6 +24,11 @@ fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pct = f_p(p, "percent");
|
||||
let dur = f_p(p, "duration");
|
||||
let hold = str_p(p, "hold").unwrap_or("in").to_string();
|
||||
// `to`: stretch so the In (or Out) point lands on the current time, the other point held.
|
||||
let to = str_p(p, "to").map(str::to_string);
|
||||
if to.as_deref().is_some_and(|t| t != "in" && t != "out") {
|
||||
return Err(bad("layer.timeStretch", "to: in|out"));
|
||||
}
|
||||
let cti = s.time();
|
||||
let comp_rate = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_rate;
|
||||
let fd = comp_rate.frame_duration();
|
||||
@@ -39,6 +44,16 @@ fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let span = (l.out_point - l.in_point).seconds();
|
||||
let (dur, hold) = match to.as_deref() {
|
||||
Some("in") => (Some((l.out_point - cti).seconds()), "out"),
|
||||
Some(_) => (Some((cti - l.in_point).seconds()), "in"),
|
||||
None => (dur, hold.as_str()),
|
||||
};
|
||||
// The current time is on the wrong side of the held point: nothing to stretch to.
|
||||
if to.is_some() && dur.is_some_and(|d| d < fd.seconds()) {
|
||||
continue;
|
||||
}
|
||||
let pct = if to.is_some() { None } else { pct };
|
||||
let new = match (pct, dur) {
|
||||
(Some(v), _) => v,
|
||||
(None, Some(d)) if span > 0.0 => old * d / span,
|
||||
@@ -48,7 +63,7 @@ fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("layer.timeStretch", "the stretch factor must be at least 1 %"));
|
||||
}
|
||||
// The hold point keeps showing the same layer time.
|
||||
let h = match hold.as_str() {
|
||||
let h = match hold {
|
||||
"current" => cti,
|
||||
"out" => l.out_point,
|
||||
_ => l.in_point,
|
||||
@@ -220,6 +235,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layers,
|
||||
time_stretch
|
||||
),
|
||||
cmd!("layer.stretchInToTime", "Stretch Layer In Point to Current Time", [], Some("Cmd+Shift+,"), "{layers?}", has_layers, |s, p| {
|
||||
let mut p = if p.is_object() { p.clone() } else { json!({}) };
|
||||
p["to"] = json!("in");
|
||||
time_stretch(s, &p)
|
||||
}),
|
||||
cmd!("layer.stretchOutToTime", "Stretch Layer Out Point to Current Time", [], Some("Cmd+Alt+,"), "{layers?}", has_layers, |s, p| {
|
||||
let mut p = if p.is_object() { p.clone() } else { json!({}) };
|
||||
p["to"] = json!("out");
|
||||
time_stretch(s, &p)
|
||||
}),
|
||||
cmd!("layer.timeReverse", "Time-Reverse Layer", ["Layer", "Time"], Some("Cmd+Alt+R"), "{layers?}", has_layers, |s, p| {
|
||||
let mut p = p.clone();
|
||||
p["op"] = json!("reverse");
|
||||
|
||||
@@ -26,6 +26,7 @@ pub mod footage_panel;
|
||||
pub(crate) mod frame_export;
|
||||
mod frontend;
|
||||
mod help;
|
||||
mod import_project;
|
||||
mod key_labels;
|
||||
mod key_transform;
|
||||
mod keys_more;
|
||||
@@ -39,6 +40,7 @@ pub mod markers;
|
||||
mod mask;
|
||||
pub mod mask_interp;
|
||||
pub(crate) mod model3d;
|
||||
mod nav_more;
|
||||
pub mod paint;
|
||||
pub mod panels_cmds;
|
||||
pub(crate) mod path_nulls;
|
||||
@@ -49,7 +51,9 @@ mod prop_groups;
|
||||
mod proxy;
|
||||
pub mod puppet;
|
||||
mod query;
|
||||
mod quick_offset;
|
||||
mod relink;
|
||||
pub(crate) mod relink_moved;
|
||||
mod render_queue;
|
||||
pub(crate) mod rig3d;
|
||||
pub mod roto_cmds;
|
||||
@@ -175,6 +179,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(paths::specs());
|
||||
v.extend(effect::specs());
|
||||
v.extend(time::specs());
|
||||
v.extend(nav_more::specs());
|
||||
v.extend(render_queue::specs());
|
||||
v.extend(help::specs());
|
||||
v.extend(query::specs());
|
||||
@@ -190,9 +195,12 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(focus::specs());
|
||||
v.extend(key_labels::specs());
|
||||
v.extend(key_transform::specs());
|
||||
v.extend(quick_offset::specs());
|
||||
v.extend(file_more::specs());
|
||||
v.extend(relink::specs());
|
||||
v.extend(relink_moved::specs());
|
||||
v.extend(lottie::specs());
|
||||
v.extend(import_project::specs());
|
||||
v.extend(timeline::specs());
|
||||
v.extend(comp_more::specs());
|
||||
v.extend(frame_export::specs());
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Keyboard-driven commands that have no menu entry.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::{ItemId, LayerSource, Project};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, comp_id, has_comp, has_layers, layers_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// Ctrl+Alt+B: the work area spans the selected layers (their earliest In to their latest Out
|
||||
/// point), or the whole composition with none selected.
|
||||
fn work_area_to_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
s.edit("Work Area", None, |proj, _| {
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let fd = c.frame_duration();
|
||||
let spans: Vec<(Tick, Tick)> = c.layers.iter().filter(|l| ids.contains(&l.id)).map(|l| (l.in_point, l.out_point)).collect();
|
||||
let (start, end) = match (spans.iter().map(|s| s.0).min(), spans.iter().map(|s| s.1).max()) {
|
||||
(Some(a), Some(b)) => (a, b),
|
||||
_ => (Tick::ZERO, c.duration),
|
||||
};
|
||||
// min/max, not clamp: the bounds cross on a comp shorter than a frame.
|
||||
let start = start.min(c.duration - fd).max(Tick::ZERO);
|
||||
c.work_area = (start, end.min(c.duration).max(start + fd));
|
||||
Ok(())
|
||||
})?;
|
||||
let c = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
Ok(json!({"start": c.work_area.0.seconds(), "end": c.work_area.1.seconds()}))
|
||||
}
|
||||
|
||||
/// Shift+F2: no keyframe, property or property group is selected; the layers stay selected.
|
||||
fn deselect_keys(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.state.selected_keys.clear();
|
||||
s.state.selected_props.clear();
|
||||
s.state.selected_vertices.clear();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Alt+` / Alt+Shift+`: select the next (previous) mask of the layer, wrapping around; the first
|
||||
/// (last) one when none is selected.
|
||||
fn step_mask(s: &mut Session, p: &Value, dir: i64) -> Result<Value> {
|
||||
let cmd = if dir > 0 { "layer.mask.selectNext" } else { "layer.mask.selectPrevious" };
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let (lid, masks) = ids
|
||||
.iter()
|
||||
.filter_map(|id| comp.layer(*id))
|
||||
.find_map(|l| l.masks().filter(|m| m.groups().next().is_some()).map(|m| (l.id, m)))
|
||||
.ok_or_else(|| bad(cmd, "the selected layers have no masks"))?;
|
||||
let groups: Vec<_> = masks.groups().collect();
|
||||
let n = groups.len() as i64;
|
||||
// The selected mask: its group, or a property inside it.
|
||||
let selected = |g: &effectcraft_project::PropGroup| {
|
||||
s.state.selected_props.iter().any(|(l, uid)| *l == lid && (g.find_group(*uid).is_some() || g.find(*uid).is_some()))
|
||||
};
|
||||
let i = match groups.iter().position(|g| selected(g)) {
|
||||
Some(i) => (i as i64 + dir).rem_euclid(n.max(1)),
|
||||
None if dir > 0 => 0,
|
||||
None => n - 1,
|
||||
};
|
||||
let uid = groups.get(i as usize).map(|g| g.uid).ok_or_else(|| bad(cmd, "the selected layers have no masks"))?;
|
||||
s.state.selected_props = vec![(lid, uid)];
|
||||
s.state.selected_keys.clear();
|
||||
s.state.selected_vertices.clear();
|
||||
Ok(json!({"layer": lid.0, "mask": uid, "index": i + 1}))
|
||||
}
|
||||
|
||||
/// Alt+Shift+C: Casts Shadows on or off for the selected 3D layers (all follow the first one).
|
||||
fn casts_shadows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const PATH: &str = "materialOptions/castsShadows";
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let with: Vec<_> = ids.iter().filter_map(|id| comp.layer(*id)).filter(|l| l.switches.three_d && l.props.prop(PATH).is_some()).collect();
|
||||
let first = with.first().ok_or_else(|| bad("layer.castsShadows", "select a 3D layer"))?;
|
||||
let on = match p.get("value").and_then(Value::as_bool) {
|
||||
Some(v) => v,
|
||||
None => first.props.prop(PATH).is_none_or(|pr| pr.value == KV::Enum(0)),
|
||||
};
|
||||
let layers: Vec<u64> = with.iter().map(|l| l.id.0).collect();
|
||||
let set = super::find("material.set").ok_or_else(|| bad("layer.castsShadows", "Material Options are not available"))?;
|
||||
(set.run)(s, &json!({"comp": cid.0, "layers": layers, "castsShadows": if on { "on" } else { "off" }}))?;
|
||||
Ok(json!({"castsShadows": on, "layers": layers}))
|
||||
}
|
||||
|
||||
/// The comps connected to `from` by nesting, in either direction (its network of nested
|
||||
/// compositions), `from` included.
|
||||
fn hierarchy(proj: &Project, from: ItemId) -> BTreeSet<ItemId> {
|
||||
let mut edges: Vec<(ItemId, ItemId)> = Vec::new();
|
||||
for item in proj.items.values() {
|
||||
let Some(c) = item.as_comp() else { continue };
|
||||
for l in &c.layers {
|
||||
if let LayerSource::Comp { item: nested } = &l.source {
|
||||
edges.push((item.id, *nested));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::from([from]);
|
||||
let mut todo = vec![from];
|
||||
while let Some(c) = todo.pop() {
|
||||
for (a, b) in &edges {
|
||||
let other = if *a == c {
|
||||
*b
|
||||
} else if *b == c {
|
||||
*a
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if seen.insert(other) {
|
||||
todo.push(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Shift+Esc: activate the composition that was active most recently among those in the active
|
||||
/// composition's nesting hierarchy.
|
||||
fn activate_recent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let related = hierarchy(&s.project, cid);
|
||||
let next = s.state.recent_comps.iter().copied().find(|c| *c != cid && related.contains(c) && s.project.comp(*c).is_some());
|
||||
let Some(next) = next else { return Ok(Value::Null) };
|
||||
s.open_comp(next);
|
||||
Ok(json!({"comp": next.0}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"comp.workAreaToSelection",
|
||||
"Set Work Area to Selected Layers",
|
||||
[],
|
||||
Some("Cmd+Alt+B"),
|
||||
"{comp?, layers? (default the selected layers; the whole composition with none)}",
|
||||
has_comp,
|
||||
work_area_to_selection
|
||||
),
|
||||
cmd!("comp.activateRecent", "Activate Most Recent Composition in Hierarchy", [], Some("Shift+Escape"), "{comp?}", has_comp, activate_recent),
|
||||
cmd!("keys.deselectAll", "Deselect All Keyframes and Properties", [], ["Shift+F2", "Cmd+Alt+Shift+A"], "{}", always, deselect_keys),
|
||||
cmd!("layer.mask.selectNext", "Select Next Mask", [], Some("Alt+`"), "{layer?}", has_layers, |s, p| step_mask(s, p, 1)),
|
||||
cmd!("layer.mask.selectPrevious", "Select Previous Mask", [], Some("Alt+Shift+`"), "{layer?}", has_layers, |s, p| step_mask(s, p, -1)),
|
||||
cmd!("layer.castsShadows", "Casts Shadows", [], Some("Alt+Shift+C"), "{layers?, value?}", has_layers, casts_shadows),
|
||||
]
|
||||
}
|
||||
@@ -168,6 +168,22 @@ fn usage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"items": doomed.len(), "layers": layers, "comps": comps}))
|
||||
}
|
||||
|
||||
/// How many times an item (default: the first selected) is used: the layers, in every
|
||||
/// composition, whose source it is, as the Project panel's "used N times", and the compositions
|
||||
/// that use it (its ▾ menu opens one), ordered by name.
|
||||
fn used_in(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "project.usedIn";
|
||||
let id = match p.get("item") {
|
||||
Some(v) => item_ref(s, v, c)?,
|
||||
None => *s.state.project_selection.first().ok_or_else(|| bad(c, "no `item` given and nothing selected in the Project panel"))?,
|
||||
};
|
||||
let users = s.project.item_users(id);
|
||||
let count = users.iter().fold(0usize, |n, (_, k)| n.saturating_add(*k));
|
||||
let comps: Vec<Value> =
|
||||
users.iter().map(|(cid, n)| json!({"id": cid.0, "name": s.project.item(*cid).map(|i| i.name.as_str()).unwrap_or_default(), "layers": n})).collect();
|
||||
Ok(json!({"item": id.0, "count": count, "comps": comps}))
|
||||
}
|
||||
|
||||
/// Delete project items (folders with their contents). Layers that use a deleted item and Render
|
||||
/// Queue items of deleted comps go too, like After Effects' Edit ▸ Clear in the Project panel.
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -219,8 +235,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if it.is_folder() {
|
||||
return Err(bad(c, "folders can't be duplicated"));
|
||||
}
|
||||
let base = it.name.trim_end_matches(|ch: char| ch.is_ascii_digit()).trim_end().to_string();
|
||||
let name = (2..).map(|i| format!("{base} {i}")).find(|n| proj.find_by_name(n).is_none()).unwrap_or_default();
|
||||
let name = proj.numbered_item_name(&it.name, |_| false);
|
||||
let mut kind = it.kind.clone();
|
||||
if let effectcraft_project::ItemKind::Comp(comp) = &mut kind {
|
||||
let comp = std::sync::Arc::make_mut(comp);
|
||||
@@ -266,6 +281,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
delete
|
||||
),
|
||||
query!("project.usage", "Project Item Usage", "{items?: [id|name] (default: selected)} → {items, layers, comps} that deleting them removes", usage),
|
||||
query!("project.usedIn", "Project Item Used In", "{item?: id|name (default: selected)} → {item, count, comps: [{id, name, layers}]}", used_in),
|
||||
cmd!("project.duplicate", "Duplicate Project Items", [], None, "{items?: [id|name] (default: selected)} → {items}", always, duplicate),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -631,11 +631,12 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.reset")?;
|
||||
let def = p.get("default").cloned();
|
||||
let own = default_value(s, cid, lid, uid);
|
||||
with_prop(s, "Reset Property", None, cid, lid, uid, |pr, _| {
|
||||
pr.keys.clear();
|
||||
with_prop(s, "Reset Property", None, cid, lid, uid, |pr, t| {
|
||||
pr.expr = None;
|
||||
// An animated property keeps its keyframes and gets the default as a key at the
|
||||
// current time, as in After Effects (#1078).
|
||||
if let Some(d) = def.as_ref().and_then(|d| pr.value.coerce_json(d)).or(own) {
|
||||
pr.value = d;
|
||||
pr.set_value_at(t, d);
|
||||
}
|
||||
Ok(Value::Null)
|
||||
})
|
||||
@@ -862,67 +863,98 @@ pub(crate) fn edit_keys(s: &mut Session, label: &str, merge: Option<&str>, f: im
|
||||
})
|
||||
}
|
||||
|
||||
/// Move the selected keys by `d` comp seconds, snapped to the comp's frames in comp time (keys
|
||||
/// of time-stretched layers move with the pointer, not by the layer-time distance). Keys of
|
||||
/// locked layers stay. A key landing on another key of its property replaces it.
|
||||
/// The keys a key drag's step applies to, the drag's total and the project as it was before the
|
||||
/// drag. Steps of one drag (one `merge` key) start again from the keys as they were then, so a key
|
||||
/// passed over survives; `d` adds to the drag's total, or is that total (`absolute`).
|
||||
pub(crate) fn key_gesture(
|
||||
s: &Session,
|
||||
merge: Option<&str>,
|
||||
d: Tick,
|
||||
absolute: bool,
|
||||
) -> (Vec<KeyRef>, Tick, Option<std::sync::Arc<effectcraft_project::Project>>) {
|
||||
let gesture = merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m)) && s.key_move.as_ref().map(|g| g.merge.as_str()) == merge;
|
||||
match (&s.key_move, s.history.undo.last()) {
|
||||
(Some(g), Some((_, base))) if gesture => (g.from.clone(), if absolute { d } else { g.total + d }, Some(base.clone())),
|
||||
_ => (s.state.selected_keys.clone(), d, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move keys `from` to the layer times `to` gives (from a key's layer and layer time). A key
|
||||
/// landing on another key of its property replaces it, roving keys follow their neighbours and
|
||||
/// keys of locked layers stay. Returns the keys' new references in `from`'s order: the selection
|
||||
/// keeps the order it was made in.
|
||||
pub(crate) fn move_key_refs(comp: &mut effectcraft_project::Comp, from: &[KeyRef], to: impl Fn(&Layer, Tick) -> Result<Tick>) -> Result<Vec<KeyRef>> {
|
||||
let mut remapped: std::collections::HashMap<KeyRef, KeyRef> = Default::default();
|
||||
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
|
||||
for k in from {
|
||||
groups.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
for ((lid, uid), times) in groups {
|
||||
let Some(l) = comp.layer_mut(lid) else { continue };
|
||||
let at = |time| KeyRef { layer: lid, prop: uid, time };
|
||||
if l.switches.locked {
|
||||
remapped.extend(times.iter().map(|t| (at(*t), at(*t))));
|
||||
continue;
|
||||
}
|
||||
let moves: Vec<(Tick, Tick)> = times.iter().map(|t| Ok((*t, to(l, *t)?))).collect::<Result<_>>()?;
|
||||
let Some(pr) = l.props.find_mut(uid) else { continue };
|
||||
// Take the moving keys out, then put them back at their new times.
|
||||
let mut moved = vec![];
|
||||
for (old, new) in &moves {
|
||||
if let Some(i) = key_at(&pr.keys, *old) {
|
||||
let mut k = pr.keys.remove(i);
|
||||
k.time = *new;
|
||||
moved.push((*old, k));
|
||||
}
|
||||
}
|
||||
// Target time -> the key's time before the move.
|
||||
let mut targets: std::collections::HashMap<Tick, Tick> = Default::default();
|
||||
for (old, k) in moved {
|
||||
targets.insert(k.time, old);
|
||||
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
|
||||
Ok(j) => pr.keys[j] = k,
|
||||
Err(j) => pr.keys.insert(j, k),
|
||||
}
|
||||
}
|
||||
// Resolve stored indices before roving keys change their times.
|
||||
let tracked: Vec<(Tick, usize)> = targets.into_iter().filter_map(|(t, old)| key_at(&pr.keys, t).map(|i| (old, i))).collect();
|
||||
effectcraft_keyframe::retime_roving(&mut pr.keys, pr.spatial);
|
||||
for (old, i) in tracked {
|
||||
if let Some(key) = pr.keys.get(i) {
|
||||
remapped.insert(at(old), at(key.time));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
Ok(from.iter().filter_map(|k| remapped.get(k).copied()).filter(|k| seen.insert(*k)).collect())
|
||||
}
|
||||
|
||||
/// A move of `d` in comp time as the move of `l`'s layer times (through its stretch, reversed
|
||||
/// too), without a round trip through comp time.
|
||||
pub(crate) fn layer_shift(l: &Layer, d: Tick) -> Tick {
|
||||
l.layer_time(l.start_time + d)
|
||||
}
|
||||
|
||||
/// Move the selected keys by `d` comp seconds, rounded to whole frames: the keys keep their
|
||||
/// spacing, subframe offsets (Quick Offset) included, and keys of time-stretched layers move with
|
||||
/// the pointer, not by the layer-time distance. Keys of locked layers stay. A key landing on
|
||||
/// another key of its property replaces it.
|
||||
pub(crate) fn shift_keys(s: &mut Session, label: &str, merge: Option<&str>, d: Tick) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
// A drag (steps with one merge key) starts again from the keys before it each step.
|
||||
let gesture = merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m)) && s.key_move.as_ref().map(|g| g.merge.as_str()) == merge;
|
||||
let (from, total, base) = match (&s.key_move, s.history.undo.last()) {
|
||||
(Some(g), Some((_, base))) if gesture => (g.from.clone(), g.total + d, Some(base.clone())),
|
||||
_ => (s.state.selected_keys.clone(), d, None),
|
||||
};
|
||||
s.key_move = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
|
||||
s.edit(label, merge, |proj, st| {
|
||||
let (from, total, base) = key_gesture(s, merge, d, false);
|
||||
let next = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
|
||||
let moved = s.edit(label, merge, |proj, st| {
|
||||
if let Some(b) = base {
|
||||
*proj = (*b).clone();
|
||||
}
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let fr = comp.frame_rate;
|
||||
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
|
||||
for k in &from {
|
||||
groups.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
let mut sel = vec![];
|
||||
for ((lid, uid), times) in groups {
|
||||
let Some(l) = comp.layer_mut(lid) else { continue };
|
||||
let to = |t: Tick| l.layer_time(fr.snap_nearest(l.comp_time(t) + total));
|
||||
let moves: Vec<(Tick, Tick)> = times.iter().map(|t| (*t, to(*t))).collect();
|
||||
if l.switches.locked {
|
||||
sel.extend(times.iter().map(|t| KeyRef { layer: lid, prop: uid, time: *t }));
|
||||
continue;
|
||||
}
|
||||
let Some(pr) = l.props.find_mut(uid) else { continue };
|
||||
// Take the moving keys out, then put them back at their new times.
|
||||
let mut moved = vec![];
|
||||
for (old, new) in &moves {
|
||||
if let Some(i) = key_at(&pr.keys, *old) {
|
||||
let mut k = pr.keys.remove(i);
|
||||
k.time = *new;
|
||||
moved.push(k);
|
||||
}
|
||||
}
|
||||
for k in moved {
|
||||
sel.push(KeyRef { layer: lid, prop: uid, time: k.time });
|
||||
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
|
||||
Ok(j) => pr.keys[j] = k,
|
||||
Err(j) => pr.keys.insert(j, k),
|
||||
}
|
||||
}
|
||||
// Roving keys follow their neighbours: keep the selection on them.
|
||||
let before: Vec<Tick> = pr.keys.iter().map(|k| k.time).collect();
|
||||
if effectcraft_keyframe::retime_roving(&mut pr.keys, pr.spatial) {
|
||||
for r in sel.iter_mut().filter(|r| r.layer == lid && r.prop == uid) {
|
||||
if let Some(i) = before.iter().position(|t| *t == r.time) {
|
||||
r.time = pr.keys[i].time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
st.selected_keys = sel;
|
||||
let d = comp.frame_rate.snap_nearest(total);
|
||||
st.selected_keys = move_key_refs(comp, &from, |l, t| Ok(t + layer_shift(l, d)))?;
|
||||
Ok(json!(st.selected_keys.len()))
|
||||
})
|
||||
})?;
|
||||
// Only a step that applied counts towards the drag.
|
||||
s.key_move = next;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn move_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1144,7 +1176,27 @@ fn velocity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.convertExpressionToKeyframes")?;
|
||||
const CMD: &str = "prop.convertExpressionToKeyframes";
|
||||
// Without a property (the menu item, a script's `app.executeCommand`) it converts the selected ones.
|
||||
if p.get("path").is_none() && p.get("prop").is_none() && p.get("layer").is_none() {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let sel: Vec<(LayerId, Uid)> =
|
||||
selected_leaf_props(s).into_iter().filter(|(l, u)| comp.layer(*l).and_then(|l| l.props.find(*u)).is_some_and(Property::has_expression)).collect();
|
||||
if sel.is_empty() {
|
||||
return Err(bad(CMD, "no `path` given and no selected property has an expression"));
|
||||
}
|
||||
let mut n = 0;
|
||||
for (lid, uid) in sel {
|
||||
n += convert_one_expr(s, cid, lid, uid)?.as_u64().unwrap_or(0);
|
||||
}
|
||||
return Ok(json!(n));
|
||||
}
|
||||
let (cid, lid, uid) = prop_ref(s, p, CMD)?;
|
||||
convert_one_expr(s, cid, lid, uid)
|
||||
}
|
||||
|
||||
fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result<Value> {
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone();
|
||||
let pr = layer.props.find(uid).ok_or_else(|| bad("prop.convertExpressionToKeyframes", "no property"))?.clone();
|
||||
@@ -1207,7 +1259,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Property",
|
||||
[],
|
||||
None,
|
||||
"{layer?, path|prop, default?} → removes keyframes and expression; the value becomes `default`, else the property's own (an effect parameter's, a Transform property's)",
|
||||
"{layer?, path|prop, default?} → removes the expression; the value becomes `default`, else the property's own (an effect parameter's, a Transform property's), as a keyframe at the current time when the property is animated",
|
||||
has_layers,
|
||||
reset
|
||||
),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! effect, mask, shape item or text animator (what scripting's `PropertyGroup.name`, `enabled`,
|
||||
//! `remove()`, `duplicate()` and `moveTo()` do, and what agents need without a UI selection).
|
||||
|
||||
use effectcraft_project::{GroupKind, ItemId, LayerId, LayerSource, Node, PropGroup, Uid};
|
||||
use effectcraft_project::{ItemId, LayerId, LayerSource, Node, PropGroup, Uid};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, has_layers, layer_mut, layer_p, layers_p, str_p};
|
||||
@@ -10,7 +10,7 @@ use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// Groups that can be renamed, removed, duplicated and reordered: instances in indexed lists.
|
||||
fn is_instance(g: &PropGroup) -> bool {
|
||||
matches!(g.kind, GroupKind::Indexed | GroupKind::Effect { .. } | GroupKind::Mask { .. } | GroupKind::Tracker { .. })
|
||||
g.is_instance()
|
||||
}
|
||||
|
||||
/// `{layer, prop: uid}` → (comp, layer, group uid), checking that the group is an instance.
|
||||
|
||||
@@ -221,7 +221,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_comp_selection,
|
||||
create_proxy
|
||||
),
|
||||
cmd!("file.setProxy", "File...", ["File", "Set Proxy"], None, "{path, items?|item?}", has_targets, set_proxy),
|
||||
cmd!("file.setProxy", "File...", ["File", "Set Proxy"], Some("Cmd+Alt+P"), "{path, items?|item?}", has_targets, set_proxy),
|
||||
cmd!("file.setProxyNone", "None", ["File", "Set Proxy"], None, "{items?|item?}", has_proxy, set_proxy_none),
|
||||
cmd!("file.useProxy", "Use Proxy", [], None, "{items?|item?, on?}", has_proxy, use_proxy),
|
||||
cmd!(
|
||||
|
||||
@@ -199,7 +199,7 @@ fn capabilities(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The headline of `docs/target-app-parity.md` (kept in sync by hand at each re-measure).
|
||||
const PARITY: &str = "≈91% feature breadth and ≈45% ready for real work (estimated parity with After Effects 2026 26.5, stage alpha); all After Effects effects present (306 registered)";
|
||||
const PARITY: &str = "≈91% feature breadth and ≈45% ready for real work (estimated parity with After Effects 2026 26.5, stage alpha); all After Effects effects present (307 registered)";
|
||||
|
||||
fn state(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(&s.state).unwrap_or_default())
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Quick Offset (After Effects 25.4): Ctrl/Cmd+Alt dragging selected layers or keyframes in the
|
||||
//! Timeline staggers them in the order they were selected. The first stays, the last moves by the
|
||||
//! whole drag and the ones between spread evenly, so they land on subframes; each layer's
|
||||
//! selected keys move together.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use effectcraft_project::LayerId;
|
||||
use effectcraft_time::{TICKS_PER_SECOND, Tick};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::prop::{key_gesture, layer_shift, move_key_refs};
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_keys, has_layers, layers_p, merge_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// `delta` (comp seconds) in ticks; out of range is an error, not a clamped drag.
|
||||
fn delta_p(p: &Value, name: &str) -> Result<Tick> {
|
||||
let d = f_p(p, "delta").ok_or_else(|| bad(name, "missing `delta` (comp seconds)"))?;
|
||||
let t = (d * TICKS_PER_SECOND as f64).round();
|
||||
if !t.is_finite() || t.abs() > Tick::MAX.0 as f64 {
|
||||
return Err(bad(name, "`delta` is out of range"));
|
||||
}
|
||||
Ok(Tick(t as i64))
|
||||
}
|
||||
|
||||
/// How far each of `n` layers moves, in order, when the last moves by `total`: `total × i / (n − 1)`
|
||||
/// to the nearest tick, so the steps between them are equal.
|
||||
fn shares(total: Tick, n: usize) -> Vec<Tick> {
|
||||
let last = n.saturating_sub(1).max(1) as i128;
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let x = total.0 as i128 * i as i128;
|
||||
Tick(((x + x.signum() * (last / 2)) / last) as i64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `t + d`, or an error (`what` names the time) when that leaves the range of times.
|
||||
fn shifted(t: Tick, d: Tick, name: &str, what: &str) -> Result<Tick> {
|
||||
let v = t.0 as i128 + d.0 as i128;
|
||||
if v < Tick::MIN.0 as i128 || v > Tick::MAX.0 as i128 {
|
||||
return Err(bad(name, format!("{what} would move out of range")));
|
||||
}
|
||||
Ok(Tick(v as i64))
|
||||
}
|
||||
|
||||
/// The layers to stagger, in order: unlocked, each once. At least two.
|
||||
fn order(name: &str, layers: impl IntoIterator<Item = LayerId>, unlocked: impl Fn(LayerId) -> bool) -> Result<Vec<LayerId>> {
|
||||
let mut out: Vec<LayerId> = vec![];
|
||||
for l in layers {
|
||||
if unlocked(l) && !out.contains(&l) {
|
||||
out.push(l);
|
||||
}
|
||||
}
|
||||
if out.len() < 2 {
|
||||
return Err(bad(name, "select at least two unlocked layers (or keys on two layers), in the order to offset them"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `layer.quickOffset`: move the layers (`layers`, else the selection, in that order) by their
|
||||
/// share of `delta`, the last layer's move. With `merge` and `fromStart`, `delta` is the whole drag
|
||||
/// and every step applies to the layers as they were before it.
|
||||
fn layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const NAME: &str = "layer.quickOffset";
|
||||
let d = delta_p(p, NAME)?;
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let merge = merge_p(p);
|
||||
let gesture = b_p(p, "fromStart").unwrap_or(false) && merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m));
|
||||
let base = s.history.undo.last().filter(|_| gesture).map(|(_, b)| b.clone());
|
||||
let start = base.clone().unwrap_or_else(|| s.project.clone());
|
||||
let comp = start.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let order = order(NAME, ids, |id| comp.layer(id).is_some_and(|l| !l.switches.locked))?;
|
||||
let moves: Vec<(LayerId, Tick)> = order.iter().copied().zip(shares(d, order.len())).collect();
|
||||
s.edit("Quick Offset", merge, |proj, _| {
|
||||
if let Some(b) = &base {
|
||||
*proj = (**b).clone();
|
||||
}
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for (id, d) in &moves {
|
||||
let l = comp.layer_mut(*id).ok_or(EngineError::NoComp)?;
|
||||
let what = format!("layer \"{}\"", l.name);
|
||||
let times = (shifted(l.start_time, *d, NAME, &what)?, shifted(l.in_point, *d, NAME, &what)?, shifted(l.out_point, *d, NAME, &what)?);
|
||||
(l.start_time, l.in_point, l.out_point) = times;
|
||||
}
|
||||
Ok(json!({"layers": moves.iter().map(|(id, d)| json!({"layer": id.0, "offset": d.seconds()})).collect::<Vec<_>>()}))
|
||||
})
|
||||
}
|
||||
|
||||
/// `keys.quickOffset`: the selected keys of each layer move together by the layer's share of
|
||||
/// `delta` (comp seconds, the last layer's move), the layers in the order their first key was
|
||||
/// selected. Like `keys.move`, steps sharing `merge` are one drag; with `fromStart`, `delta` is the
|
||||
/// whole drag.
|
||||
fn keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const NAME: &str = "keys.quickOffset";
|
||||
let d = delta_p(p, NAME)?;
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let merge = merge_p(p);
|
||||
let (from, total, base) = key_gesture(s, merge, d, b_p(p, "fromStart").unwrap_or(false));
|
||||
let start = base.clone().unwrap_or_else(|| s.project.clone());
|
||||
let comp = start.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let order = order(NAME, from.iter().map(|k| k.layer), |id| comp.layer(id).is_some_and(|l| !l.switches.locked))?;
|
||||
let by_layer: HashMap<LayerId, Tick> = order.iter().copied().zip(shares(total, order.len())).collect();
|
||||
let next = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
|
||||
let moved = s.edit("Quick Offset Keyframes", merge, |proj, st| {
|
||||
if let Some(b) = &base {
|
||||
*proj = (**b).clone();
|
||||
}
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
st.selected_keys = move_key_refs(comp, &from, |l, t| {
|
||||
let Some(d) = by_layer.get(&l.id) else { return Ok(t) };
|
||||
let what = format!("a key of \"{}\"", l.name);
|
||||
shifted(l.start_time, *d, NAME, &what)?;
|
||||
shifted(t, layer_shift(l, *d), NAME, &what)
|
||||
})?;
|
||||
Ok(json!({"keys": st.selected_keys.len(), "layers": order.iter().map(|id| json!({"layer": id.0, "offset": by_layer.get(id).copied().unwrap_or_default().seconds()})).collect::<Vec<_>>()}))
|
||||
})?;
|
||||
// Only a step that applied counts towards the drag (a refused one is as if never sent).
|
||||
s.key_move = next;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"layer.quickOffset",
|
||||
"Quick Offset",
|
||||
[],
|
||||
None,
|
||||
"{delta (comp s: the last layer's move), layers? (in order; default the selection), merge?, fromStart?: bool (with merge: delta is the whole drag)}",
|
||||
has_layers,
|
||||
layers
|
||||
),
|
||||
cmd!(
|
||||
"keys.quickOffset",
|
||||
"Quick Offset Keyframes",
|
||||
[],
|
||||
None,
|
||||
"{delta (comp s: the last layer's keys' move), merge?, fromStart?: bool (with merge: delta is the whole drag)}",
|
||||
has_keys,
|
||||
keys
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Relinking footage that moved together (gaps.md G4; After Effects' Replace Footage on a missing
|
||||
//! file, which then finds the other missing files in the same place). Searching a folder for
|
||||
//! compatible files is `file.relinkFootage` ([`super::relink`]).
|
||||
//!
|
||||
//! - `footage.relink {item, path}`: point a footage item at `path`, keeping its interpretation, and
|
||||
//! relink every other missing item that sits in the same place relative to it (the folder moved,
|
||||
//! or a drive was renamed). One undo step. Replace Footage on a missing item does the same.
|
||||
//! - `footage.missing`: the missing items.
|
||||
//! - When a project opens from a folder it wasn't saved in, the footage check ([`moved_candidates`])
|
||||
//! tries each missing file at the same place under the project's new folder.
|
||||
//!
|
||||
//! Paths are compared by their parts, split on `/` and `\`, so a project made on Windows relinks on
|
||||
//! macOS and the other way round.
|
||||
|
||||
use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, Project};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, str_p};
|
||||
use crate::{Result, Services, Session, cmd};
|
||||
|
||||
/// Trailing parts of a path tried under a moved project's folder.
|
||||
const MOVED_PARTS: usize = 4;
|
||||
|
||||
fn parts(path: &str) -> Vec<&str> {
|
||||
path.split(['/', '\\']).filter(|p| !p.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// The separator `path` uses (Windows paths keep theirs).
|
||||
fn sep_of(path: &str) -> char {
|
||||
if path.contains('\\') && !path.contains('/') { '\\' } else { '/' }
|
||||
}
|
||||
|
||||
fn file_name(path: &str) -> &str {
|
||||
parts(path).last().copied().unwrap_or("")
|
||||
}
|
||||
|
||||
/// `prefix` and `rest` joined with `prefix`'s separator.
|
||||
fn join(prefix: &str, rest: &[&str]) -> String {
|
||||
let sep = sep_of(prefix);
|
||||
let mut out = prefix.trim_end_matches(['/', '\\']).to_string();
|
||||
for p in rest {
|
||||
out.push(sep);
|
||||
out.push_str(p);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What moved: `old` became `new`. The parts they end with in common are the same file's place
|
||||
/// inside the moved folder; what comes before is the folder's old and new location.
|
||||
/// `("/a/b/shots/x.mov", "/c/shots/x.mov")` → `(["a", "b"], "/c")`.
|
||||
fn moved_root<'a>(old: &'a str, new: &str) -> Option<(Vec<&'a str>, String)> {
|
||||
let (o, n) = (parts(old), parts(new));
|
||||
let common = o.iter().rev().zip(n.iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
// At least the file name must match, else it's a different file (then only its folder moved).
|
||||
let common = common.max(1).min(o.len()).min(n.len());
|
||||
let old_root: Vec<&str> = o.get(..o.len() - common)?.to_vec();
|
||||
// The new root keeps a leading `/` or a drive letter as written.
|
||||
let new_parts = n.len() - common;
|
||||
let mut new_root = String::new();
|
||||
if new.starts_with('/') {
|
||||
new_root.push('/');
|
||||
} else if new.starts_with("\\\\") {
|
||||
new_root.push_str("\\\\");
|
||||
}
|
||||
let sep = sep_of(new);
|
||||
for (i, p) in n.iter().take(new_parts).enumerate() {
|
||||
if i > 0 {
|
||||
new_root.push(sep);
|
||||
}
|
||||
new_root.push_str(p);
|
||||
}
|
||||
Some((old_root, new_root))
|
||||
}
|
||||
|
||||
/// `path` under the moved root, when it was under the old one.
|
||||
fn remap(path: &str, old_root: &[&str], new_root: &str) -> Option<String> {
|
||||
let p = parts(path);
|
||||
if p.len() <= old_root.len() || p.get(..old_root.len())? != old_root {
|
||||
return None;
|
||||
}
|
||||
Some(join(new_root, p.get(old_root.len()..)?))
|
||||
}
|
||||
|
||||
/// The item's file and, for an image sequence, every frame, moved by `f`; `None` unless its main
|
||||
/// file maps.
|
||||
fn moved_footage(footage: &Footage, f: impl Fn(&str) -> Option<String>) -> Option<Footage> {
|
||||
let mut nf = footage.clone();
|
||||
nf.path = f(&footage.path)?;
|
||||
nf.sequence = footage.sequence.iter().map(|p| f(p).unwrap_or_else(|| p.clone())).collect();
|
||||
nf.missing = false;
|
||||
Some(nf)
|
||||
}
|
||||
|
||||
fn present(s: &dyn Services, f: &Footage) -> bool {
|
||||
!f.path.is_empty() && s.exists(&f.path)
|
||||
}
|
||||
|
||||
/// Footage items whose file is gone (flagged by the footage check, or not there now).
|
||||
fn missing_items(s: &Session) -> Vec<(ItemId, Footage)> {
|
||||
s.project
|
||||
.items
|
||||
.values()
|
||||
.filter_map(|i| match &i.kind {
|
||||
ItemKind::Footage(f) if f.kind != FootageKind::Data && !f.path.is_empty() && (f.missing || !present(s.services.as_ref(), f)) => {
|
||||
Some((i.id, f.clone()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where a file a moved project lost may be now: the same place under the project's new folder,
|
||||
/// trying the longest tail of its old path first (`/old/proj/shots/a.mov` with the project now in
|
||||
/// `/new/proj` → `/new/proj/old/proj/shots/a.mov`, …, `/new/proj/shots/a.mov`, `/new/proj/a.mov`).
|
||||
pub(crate) fn moved_candidates(project_dir: &str, path: &str) -> Vec<String> {
|
||||
let p = parts(path);
|
||||
(1..=MOVED_PARTS.min(p.len())).rev().filter_map(|k| p.get(p.len() - k..)).map(|tail| join(project_dir, tail)).collect()
|
||||
}
|
||||
|
||||
/// A missing item found again under a moved project's folder ([`moved_candidates`]), with its
|
||||
/// sequence frames moved alongside.
|
||||
pub(crate) fn find_moved(services: &dyn Services, project_dir: &str, f: &Footage) -> Option<Footage> {
|
||||
moved_candidates(project_dir, &f.path).into_iter().filter(|c| services.exists(c)).find_map(|hit| {
|
||||
let (old_root, new_root) = moved_root(&f.path, &hit)?;
|
||||
moved_footage(f, |q| if q == f.path { Some(hit.clone()) } else { remap(q, &old_root, &new_root) })
|
||||
})
|
||||
}
|
||||
|
||||
/// The folder a project file is in.
|
||||
pub(crate) fn project_dir(project_path: &str) -> Option<String> {
|
||||
let p = parts(project_path);
|
||||
if p.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut dir = join(if project_path.starts_with('/') { "/" } else { "" }, p.get(..p.len() - 1)?);
|
||||
if !project_path.starts_with('/') {
|
||||
dir = dir.trim_start_matches(['/', '\\']).to_string();
|
||||
}
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
/// Relink `found` in one undo step and say how many.
|
||||
fn apply(s: &mut Session, label: &str, found: Vec<(ItemId, Footage)>) -> Result<Value> {
|
||||
if found.is_empty() {
|
||||
return Ok(json!({"relinked": [], "stillMissing": missing_items(s).len()}));
|
||||
}
|
||||
let ids: Vec<u64> = found.iter().map(|(id, _)| id.0).collect();
|
||||
s.edit(label, None, |proj: &mut Project, _| {
|
||||
for (id, nf) in found {
|
||||
if let Some(it) = proj.item_mut(id) {
|
||||
it.kind = ItemKind::Footage(nf);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
s.events.push(crate::Event::PurgeCaches);
|
||||
let still = missing_items(s).len();
|
||||
s.toast(match still {
|
||||
0 => format!("Relinked {} footage item(s)", ids.len()),
|
||||
n => format!("Relinked {} footage item(s); {n} still missing", ids.len()),
|
||||
});
|
||||
Ok(json!({"relinked": ids, "stillMissing": still}))
|
||||
}
|
||||
|
||||
/// The other missing items that moved the way `item` did (`old_path` → `new_path`): the same place
|
||||
/// under the moved folder, else the same name in the new file's folder. Used by `footage.relink`
|
||||
/// and by Replace Footage on a missing item.
|
||||
pub(crate) fn moved_with(s: &Session, item: ItemId, old_path: &str, new_path: &str) -> Vec<(ItemId, Footage)> {
|
||||
let Some((old_root, new_root)) = moved_root(old_path, new_path) else { return vec![] };
|
||||
let services = s.services.clone();
|
||||
let new_dir = project_dir(new_path);
|
||||
let mut found = vec![];
|
||||
for (id, f) in missing_items(s) {
|
||||
if id == item {
|
||||
continue;
|
||||
}
|
||||
let same_place = moved_footage(&f, |q| remap(q, &old_root, &new_root)).filter(|nf| present(services.as_ref(), nf));
|
||||
let same_folder = || {
|
||||
let dir = new_dir.as_deref()?;
|
||||
let dir_parts = parts(dir);
|
||||
let old_dir_len = parts(&f.path).len().checked_sub(1)?;
|
||||
let old_dir: Vec<&str> = parts(&f.path).get(..old_dir_len)?.to_vec();
|
||||
moved_footage(&f, |q| remap(q, &old_dir, dir).or_else(|| Some(join(dir, &[file_name(q)])))).filter(|nf| {
|
||||
// Only frames in that one folder (a name match, not a guess deeper down).
|
||||
present(services.as_ref(), nf) && parts(&nf.path).len() == dir_parts.len() + 1
|
||||
})
|
||||
};
|
||||
if let Some(nf) = same_place.or_else(same_folder) {
|
||||
found.push((id, nf));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `footage.relink {item, path}`
|
||||
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "footage.relink";
|
||||
let path = str_p(p, "path").filter(|p| !p.trim().is_empty()).ok_or_else(|| bad(CMD, "missing `path` (the file's new location)"))?.to_string();
|
||||
let item = p.get("item").and_then(Value::as_u64).map(ItemId).ok_or_else(|| bad(CMD, "missing `item` (a footage item id)"))?;
|
||||
let Some(ItemKind::Footage(old)) = s.project.item(item).map(|i| &i.kind) else { return Err(bad(CMD, "`item` is not a footage item")) };
|
||||
let old = old.clone();
|
||||
if !s.services.exists(&path) {
|
||||
return Err(bad(CMD, format!("there is no file at {path}")));
|
||||
}
|
||||
let (old_root, new_root) = moved_root(&old.path, &path).ok_or_else(|| bad(CMD, "cannot compare the old and new paths"))?;
|
||||
// The item itself: its file is `path`; its sequence frames move with it.
|
||||
let main =
|
||||
moved_footage(&old, |q| if q == old.path { Some(path.clone()) } else { remap(q, &old_root, &new_root) }).ok_or_else(|| bad(CMD, "cannot relink"))?;
|
||||
let mut found = vec![(item, main)];
|
||||
found.extend(moved_with(s, item, &old.path, &path));
|
||||
apply(s, "Relink Footage", found)
|
||||
}
|
||||
|
||||
/// `footage.missing`: the missing footage items and where they were.
|
||||
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = missing_items(s)
|
||||
.into_iter()
|
||||
.map(|(id, f)| json!({"item": id.0, "name": s.project.item(id).map(|i| i.name.clone()).unwrap_or_default(), "path": f.path}))
|
||||
.collect();
|
||||
Ok(json!({"missing": list}))
|
||||
}
|
||||
|
||||
fn has_footage(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.project.items.values().any(|i| matches!(i.kind, ItemKind::Footage(_))) { Ok(()) } else { Err("the project has no footage".into()) }
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"footage.relink",
|
||||
"Relink Footage",
|
||||
[],
|
||||
None,
|
||||
"{item, path} — point a footage item at its file's new location (keeps the interpretation) and relink the other missing files found in the same place",
|
||||
has_footage,
|
||||
relink
|
||||
),
|
||||
crate::query!("footage.missing", "Missing Footage", "{} → {missing: [{item, name, path}]}", missing),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn moved_roots_and_remaps() {
|
||||
let (old, new) = moved_root("/a/b/shots/x.mov", "/c/shots/x.mov").unwrap();
|
||||
assert_eq!((old, new.as_str()), (vec!["a", "b"], "/c"));
|
||||
assert_eq!(remap("/a/b/shots/y.mov", &["a", "b"], "/c").as_deref(), Some("/c/shots/y.mov"));
|
||||
assert_eq!(remap("/a/z/y.mov", &["a", "b"], "/c"), None);
|
||||
// Windows to macOS.
|
||||
let (old, new) = moved_root("D:\\Work\\Job\\audio\\m.wav", "/Volumes/Work/Job/audio/m.wav").unwrap();
|
||||
assert_eq!((old, new.as_str()), (vec!["D:"], "/Volumes"));
|
||||
assert_eq!(remap("D:\\Work\\Job\\img\\a.png", &["D:"], "/Volumes").as_deref(), Some("/Volumes/Work/Job/img/a.png"));
|
||||
// A different file name: only the folder moved.
|
||||
let (old, new) = moved_root("/a/x.mov", "/b/y.mov").unwrap();
|
||||
assert_eq!((old, new.as_str()), (vec!["a"], "/b"));
|
||||
assert_eq!(
|
||||
moved_candidates("/new/p", "/old/p/shots/a.mov"),
|
||||
["/new/p/old/p/shots/a.mov", "/new/p/p/shots/a.mov", "/new/p/shots/a.mov", "/new/p/a.mov"]
|
||||
);
|
||||
assert_eq!(project_dir("/x/y/p.ecproj").as_deref(), Some("/x/y"));
|
||||
assert_eq!(project_dir("p.ecproj"), None);
|
||||
// Hostile input doesn't panic.
|
||||
for (a, b) in [("", ""), ("/", "/"), ("x", ""), ("\\\\", "//"), ("/a", "/a/b/c")] {
|
||||
let _ = moved_root(a, b);
|
||||
let _ = moved_candidates(b, a);
|
||||
let _ = project_dir(a);
|
||||
}
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("ec-relink-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, path: &str) -> ItemId {
|
||||
let f = Footage { path: path.into(), width: 8, height: 8, has_video: true, missing: true, ..Default::default() };
|
||||
std::sync::Arc::make_mut(&mut s.project).add_item(file_name(path), crate::color::Label::None, None, ItemKind::Footage(f))
|
||||
}
|
||||
|
||||
fn path_of(s: &Session, id: ItemId) -> String {
|
||||
match s.project.item(id).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => f.path.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_one_file_finds_the_others_that_moved_with_it() {
|
||||
let d = temp("one");
|
||||
let new = d.join("moved");
|
||||
std::fs::create_dir_all(new.join("shots")).unwrap();
|
||||
std::fs::create_dir_all(new.join("audio")).unwrap();
|
||||
for f in ["shots/a.mov", "shots/b.mov", "audio/m.wav"] {
|
||||
std::fs::write(new.join(f), b"x").unwrap();
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let a = add(&mut s, "/gone/proj/shots/a.mov");
|
||||
let b = add(&mut s, "/gone/proj/shots/b.mov");
|
||||
let m = add(&mut s, "/gone/proj/audio/m.wav");
|
||||
let other = add(&mut s, "/elsewhere/c.mov");
|
||||
let target = new.join("shots/a.mov").to_string_lossy().to_string();
|
||||
let r = s.execute("footage.relink", json!({"item": a.0, "path": target})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([a.0, b.0, m.0]), "{r}");
|
||||
assert_eq!(r["stillMissing"], 1);
|
||||
assert_eq!(path_of(&s, m), new.join("audio/m.wav").to_string_lossy());
|
||||
assert_eq!(path_of(&s, other), "/elsewhere/c.mov");
|
||||
// One undo step brings every path back.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(path_of(&s, b), "/gone/proj/shots/b.mov");
|
||||
// Errors: no such file, not footage.
|
||||
assert!(s.execute("footage.relink", json!({"item": a.0, "path": "/nope/a.mov"})).is_err());
|
||||
assert!(s.execute("footage.relink", json!({"item": 999_999, "path": target})).is_err());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
@@ -998,7 +998,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"renderQueue.add",
|
||||
"Add to Render Queue",
|
||||
["Composition"],
|
||||
Some("Cmd+M"),
|
||||
["Cmd+M", "Cmd+Shift+/"],
|
||||
"{comp?: id|name, template?: Render Settings template, format?: h264|hevc|av1|prores|uncompressed|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, profile?, level?, rateControl?, webmCodec?, audioBitrate?, opusApplication?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",
|
||||
can_add,
|
||||
add
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Roto Brush & Refine Edge commands: strokes (the Roto Brush and Refine Edge tools in the Layer
|
||||
//! panel), propagation, the segmentation span, Freeze / Unfreeze, tool options and status.
|
||||
//!
|
||||
//! `objectMatte.apply` adds an Object Matte effect (Effect ▸ Matte) from a point / box prompt on
|
||||
//! a frame; it segments with the same engine and model as Roto Brush.
|
||||
//!
|
||||
//! `roto.stroke` records a stroke into the layer's Roto Brush & Refine Edge effect (applying the
|
||||
//! effect on the first stroke, as After Effects does); the first foreground stroke sets the base
|
||||
//! frame and a span of 20 frames each side. Strokes on a frozen effect are refused (Unfreeze
|
||||
@@ -51,6 +54,32 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
options
|
||||
),
|
||||
cmd!(
|
||||
"objectMatte.apply",
|
||||
"Object Matte",
|
||||
[],
|
||||
None,
|
||||
"{layer?, effect? (uid: re-prompt this Object Matte instead of adding one), point: [x, y] (layer pixels: the object), box?: [x0, y0, x1, y1] (layer pixels, around the object), frame? (reference layer frame; default current), track?: follow the object from that frame (default true), before?, after? (frames to follow it; default 30, up to 600)}",
|
||||
has_comp,
|
||||
object_matte_apply
|
||||
),
|
||||
cmd!(
|
||||
"objectMatte.propagate",
|
||||
"Track Object Matte",
|
||||
[],
|
||||
None,
|
||||
"{layer?, effect?, direction?: forward|backward|both, wait?: block until done} (a background job like Roto Brush propagation; roto.cancel stops it)",
|
||||
has_comp,
|
||||
object_matte_propagate
|
||||
),
|
||||
cmd!("objectMatte.freeze", "Freeze Object Matte", [], None, "{layer?, effect?, wait?}", has_comp, object_matte_freeze),
|
||||
cmd!("objectMatte.unfreeze", "Unfreeze Object Matte", [], None, "{layer?, effect?}", has_comp, object_matte_unfreeze),
|
||||
query!(
|
||||
"objectMatte.status",
|
||||
"Object Matte Status",
|
||||
"{layer?, effect?}: the job's progress, whether the instance is frozen, its frames and which are computed",
|
||||
object_matte_status
|
||||
),
|
||||
query!(
|
||||
"roto.status",
|
||||
"Roto Brush Status",
|
||||
@@ -67,6 +96,16 @@ fn is_running(s: &Session) -> std::result::Result<(), String> {
|
||||
/// The Roto Brush instance targeted by `p`: `layer` / `effect` (uid, name or 1-based index),
|
||||
/// else a selected one, else the first on the selected (or any) layer.
|
||||
pub(crate) fn roto_p(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
|
||||
instance_lookup(s, p, cmd, is_roto)?.ok_or_else(|| bad(cmd, "no Roto Brush & Refine Edge effect found (paint a stroke with the Roto Brush tool first)"))
|
||||
}
|
||||
|
||||
/// The Object Matte instance targeted by `p` (as [`roto_p`]).
|
||||
fn object_matte_p(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
|
||||
instance_lookup(s, p, cmd, rt::is_object_matte)?.ok_or_else(|| bad(cmd, "no Object Matte effect found (click an object with the Object Matte tool first)"))
|
||||
}
|
||||
|
||||
/// The instance of a kind (`is`) targeted by `p`; `None` when there is none.
|
||||
fn instance_lookup(s: &Session, p: &Value, cmd: &str, is: fn(&PropGroup) -> bool) -> Result<Option<(ItemId, LayerId, Uid)>> {
|
||||
let cid = super::comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let candidates: Vec<LayerId> = match p.get("layer") {
|
||||
@@ -90,17 +129,17 @@ pub(crate) fn roto_p(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, Layer
|
||||
.state
|
||||
.selected_props
|
||||
.iter()
|
||||
.find_map(|(l, u)| (*l == lid).then(|| fxg.groups().find(|g| g.uid == *u && is_roto(g))).flatten())
|
||||
.or_else(|| fxg.groups().find(|g| is_roto(g))),
|
||||
.find_map(|(l, u)| (*l == lid).then(|| fxg.groups().find(|g| g.uid == *u && is(g))).flatten())
|
||||
.or_else(|| fxg.groups().find(|g| is(g))),
|
||||
};
|
||||
if let Some(g) = g.filter(|g| is_roto(g)) {
|
||||
return Ok((cid, lid, g.uid));
|
||||
if let Some(g) = g.filter(|g| is(g)) {
|
||||
return Ok(Some((cid, lid, g.uid)));
|
||||
}
|
||||
if p.get("layer").is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(bad(cmd, "no Roto Brush & Refine Edge effect found (paint a stroke with the Roto Brush tool first)"))
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn group(s: &Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result<(&Layer, &PropGroup)> {
|
||||
@@ -268,16 +307,22 @@ fn span(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "the Roto Brush is frozen: Unfreeze it to change the span"));
|
||||
}
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let lim = rt::frame_limits(comp, l);
|
||||
let [lo, hi] = rt::frame_limits(comp, l);
|
||||
let mut d = data_of(g);
|
||||
let base = d.base.ok_or_else(|| bad(cmd, "no strokes yet"))?;
|
||||
let first = d.strokes.iter().map(|s| s.frame).min().unwrap_or(base);
|
||||
let last = d.strokes.iter().map(|s| s.frame).max().unwrap_or(base);
|
||||
// Trimming or shortening the comp can leave saved strokes outside the layer. No span
|
||||
// inside its new bounds can contain those strokes; keep them for undo or a later untrim.
|
||||
if first < lo || last > hi {
|
||||
return Err(bad(cmd, "strokes outside the layer: restore the layer/comp timing or clear those strokes before changing the span"));
|
||||
}
|
||||
let [start, end] = &mut d.span;
|
||||
if let Some(a) = f_p(p, "start") {
|
||||
d.span[0] = (a.round() as i64).clamp(lim[0], first);
|
||||
*start = (a.round() as i64).clamp(lo, first);
|
||||
}
|
||||
if let Some(b) = f_p(p, "end") {
|
||||
d.span[1] = (b.round() as i64).clamp(last, lim[1]);
|
||||
*end = (b.round() as i64).clamp(last, hi);
|
||||
}
|
||||
write_data(s, "Segmentation Span", cid, lid, uid, &d)?;
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "span": d.span, "base": base}))
|
||||
@@ -422,3 +467,190 @@ fn status(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out["computed"] = json!(computed.iter().filter(|(_, c)| **c).map(|(f, _)| *f).collect::<Vec<_>>());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Two finite numbers.
|
||||
fn xy_p(p: &Value, k: &str, n: usize, cmd: &str) -> Result<Option<Vec<f64>>> {
|
||||
let Some(v) = p.get(k).filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let a = v.as_array().filter(|a| a.len() == n).ok_or_else(|| bad(cmd, format!("`{k}` is {n} numbers (layer pixels)")))?;
|
||||
let out: Vec<f64> = a.iter().filter_map(Value::as_f64).filter(|x| x.is_finite()).collect();
|
||||
if out.len() != n {
|
||||
return Err(bad(cmd, format!("`{k}` is {n} numbers (layer pixels)")));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
fn object_matte_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use effectcraft_effects::object_matte as om;
|
||||
let cmd = "objectMatte.apply";
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layer = comp.layer(lid).ok_or_else(|| bad(cmd, "no layer"))?;
|
||||
if !layer.has_video() || layer.switches.adjustment || layer.effects().is_none() {
|
||||
return Err(bad(cmd, "Object Matte works on footage, solid and composition layers"));
|
||||
}
|
||||
// Re-prompt an existing instance (the Object Matte tool on a layer that has one).
|
||||
let existing = match p.get("effect").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let uid = v.as_u64().ok_or_else(|| bad(cmd, "`effect` is an Object Matte effect's uid"))?;
|
||||
let g = layer
|
||||
.effects()
|
||||
.and_then(|f| f.groups().find(|g| g.uid == uid && rt::is_object_matte(g)))
|
||||
.ok_or_else(|| bad(cmd, format!("no Object Matte effect {uid} on this layer")))?;
|
||||
if frozen_of(g) {
|
||||
return Err(bad(cmd, "the Object Matte is frozen: Unfreeze it to change the prompt"));
|
||||
}
|
||||
Some(uid)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let size = rt::layer_size(&s.project, comp, layer);
|
||||
let point = xy_p(p, "point", 2, cmd)?.ok_or_else(|| bad(cmd, "missing `point` [x, y] (layer pixels)"))?;
|
||||
let inside = |x: f64, y: f64| (0.0..=size[0]).contains(&x) && (0.0..=size[1]).contains(&y);
|
||||
if !inside(point[0], point[1]) {
|
||||
return Err(bad(cmd, format!("`point` is outside the layer ({}×{})", size[0], size[1])));
|
||||
}
|
||||
let bx = xy_p(p, "box", 4, cmd)?;
|
||||
if let Some(b) = &bx {
|
||||
let (x0, x1, y0, y1) = (b[0].min(b[2]), b[0].max(b[2]), b[1].min(b[3]), b[1].max(b[3]));
|
||||
if !(point[0] > x0 && point[0] < x1 && point[1] > y0 && point[1] < y1) {
|
||||
return Err(bad(cmd, "`point` must be inside `box`"));
|
||||
}
|
||||
}
|
||||
let frame = frame_p(s, p, cid, layer);
|
||||
let limits = rt::frame_limits(comp, layer);
|
||||
if frame < limits[0] || frame > limits[1] {
|
||||
return Err(bad(cmd, format!("frame {frame} is outside the layer ({}–{})", limits[0], limits[1])));
|
||||
}
|
||||
// A new instance gets the defaults; a re-prompted one keeps what is not given.
|
||||
let track = b_p(p, "track").or(existing.is_none().then_some(true));
|
||||
let reach = |k: &str| {
|
||||
let v = f_p(p, k).filter(|v| v.is_finite());
|
||||
let v = if existing.is_none() { Some(v.unwrap_or(om::DEFAULT_REACH)) } else { v };
|
||||
v.map(|v| v.round().clamp(0.0, om::MAX_REACH))
|
||||
};
|
||||
let (before, after) = (reach("before"), reach("after"));
|
||||
let spec = effectcraft_effects::find(om::ID).ok_or_else(|| EngineError::Other("Object Matte effect missing".into()))?;
|
||||
let label = if existing.is_some() { "Object Matte Prompt" } else { "Object Matte" };
|
||||
let uid = s.edit(label, None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let fxg = l.props.sub_mut("effects").ok_or_else(|| bad(cmd, "this layer has no effects"))?;
|
||||
let mut fresh = None;
|
||||
let g = match existing {
|
||||
Some(u) => fxg.find_group_mut(u).ok_or_else(|| bad(cmd, "the Object Matte effect is gone"))?,
|
||||
None => {
|
||||
let n = fxg.groups().filter(|g| rt::is_object_matte(g)).count();
|
||||
let name = if n == 0 { spec.name.to_string() } else { format!("{} {}", spec.name, n + 1) };
|
||||
fresh.insert(effectcraft_effects::instantiate(spec, &mut Ids(&mut next), &name, size))
|
||||
}
|
||||
};
|
||||
let mut set = |path: &str, v: KV| {
|
||||
let (grp, leaf) = path.rsplit_once('/').map_or((None, path), |(a, b)| (Some(a), b));
|
||||
let target = match grp {
|
||||
Some(sub) => g.sub_mut(sub),
|
||||
None => Some(&mut *g),
|
||||
};
|
||||
// The prompt is static: a re-prompt replaces any keyframes.
|
||||
if let Some(pr) = target.and_then(|t| t.get_mut(leaf)) {
|
||||
pr.value = v;
|
||||
pr.keys.clear();
|
||||
}
|
||||
};
|
||||
set("objectPoint", KV::Vec2([point[0], point[1]]));
|
||||
set("useBox", KV::Bool(bx.is_some()));
|
||||
if let Some(b) = &bx {
|
||||
set("boxTopLeft", KV::Vec2([b[0].min(b[2]), b[1].min(b[3])]));
|
||||
set("boxBottomRight", KV::Vec2([b[0].max(b[2]), b[1].max(b[3])]));
|
||||
}
|
||||
if let Some(t) = track {
|
||||
set("objectTracking/trackObject", KV::Bool(t));
|
||||
}
|
||||
set("objectTracking/referenceFrame", KV::Scalar(frame as f64));
|
||||
if let Some(v) = before {
|
||||
set("objectTracking/framesBefore", KV::Scalar(v));
|
||||
}
|
||||
if let Some(v) = after {
|
||||
set("objectTracking/framesAfter", KV::Scalar(v));
|
||||
}
|
||||
let u = g.uid;
|
||||
if let Some(g) = fresh {
|
||||
fxg.children.push(g.into());
|
||||
}
|
||||
proj.next_id = proj.next_id.max(next);
|
||||
Ok(u)
|
||||
})?;
|
||||
s.state.selected_layers = vec![lid];
|
||||
let (track, before, after) = object_matte_reach(s, cid, lid, uid);
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "frame": frame, "track": track, "updated": existing.is_some(), "span": [frame - before, frame + after]}))
|
||||
}
|
||||
|
||||
/// Track Object and Frames Before / After of an Object Matte instance (static values).
|
||||
fn object_matte_reach(s: &Session, cid: ItemId, lid: LayerId, uid: Uid) -> (bool, i64, i64) {
|
||||
use effectcraft_effects::object_matte as om;
|
||||
let Ok((_, g)) = group(s, cid, lid, uid) else { return (true, 0, 0) };
|
||||
let ps = params_static(g);
|
||||
let [before, after] = om::reach(&ps);
|
||||
(om::tracks(&ps), before, after)
|
||||
}
|
||||
|
||||
fn object_matte_propagate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "objectMatte.propagate";
|
||||
let (cid, lid, uid) = object_matte_p(s, p, cmd)?;
|
||||
let dir = match str_p(p, "direction") {
|
||||
Some(d) => Direction::from_name(d).ok_or_else(|| bad(cmd, format!("unknown direction `{d}` (forward | backward | both)")))?,
|
||||
None => Direction::Both,
|
||||
};
|
||||
let wait = b_p(p, "wait").unwrap_or(false);
|
||||
let n = s.start_roto(cid, lid, uid, RotoTask::Propagate, dir, wait).map_err(|e| bad(cmd, e))?;
|
||||
let mut out = json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_roto_running(), "progress": s.roto_progress()});
|
||||
if wait {
|
||||
out["status"] = object_matte_status(s, &json!({"layer": lid.0, "effect": uid, "comp": cid.0}))?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn object_matte_freeze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "objectMatte.freeze";
|
||||
let (cid, lid, uid) = object_matte_p(s, p, cmd)?;
|
||||
let wait = b_p(p, "wait").unwrap_or(false);
|
||||
let n = s.start_roto(cid, lid, uid, RotoTask::Freeze, Direction::Both, wait).map_err(|e| bad(cmd, e))?;
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_roto_running(), "frozen": frozen_of(g), "progress": s.roto_progress()}))
|
||||
}
|
||||
|
||||
fn object_matte_unfreeze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "objectMatte.unfreeze";
|
||||
let (cid, lid, uid) = object_matte_p(s, p, cmd)?;
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
if frozen_of(g) {
|
||||
s.edit("Unfreeze", None, |proj, _| {
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| EngineError::Other("the effect is gone".into()))?;
|
||||
if let Some(pr) = g.get_mut(FROZEN) {
|
||||
pr.value = KV::Str(String::new());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "frozen": false}))
|
||||
}
|
||||
|
||||
fn object_matte_status(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.poll_roto(false);
|
||||
let running = s.is_roto_running();
|
||||
let mut out = json!({"running": running, "progress": s.roto_progress(), "banner": s.roto_progress().map(|p| p.banner())});
|
||||
let Ok((cid, lid, uid)) = object_matte_p(s, p, "objectMatte.status") else { return Ok(out) };
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
let frozen = frozen_of(g);
|
||||
let (track, before, after) = object_matte_reach(s, cid, lid, uid);
|
||||
let computed = s.roto_computed(cid, lid, uid);
|
||||
out["layer"] = json!(lid.0);
|
||||
out["effect"] = json!(uid);
|
||||
out["frozen"] = json!(frozen);
|
||||
out["track"] = json!(track);
|
||||
out["reach"] = json!([before, after]);
|
||||
out["mine"] = json!(running && s.roto_target().is_some_and(|(c, l, u, _)| (c, l, u) == (cid, lid, uid)));
|
||||
out["pending"] = json!(s.roto_pending.contains(&(cid, lid, uid)));
|
||||
out["frames"] = json!(computed.keys().collect::<Vec<_>>());
|
||||
out["computed"] = json!(computed.iter().filter(|(_, c)| **c).map(|(f, _)| *f).collect::<Vec<_>>());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("shortcuts.export", "Export Keyboard Shortcuts", [], None, "{preset?, path?}", always, sc_export),
|
||||
cmd!("shortcuts.import", "Import Keyboard Shortcuts", [], None, "{path? | preset?: exported document, name?}", always, sc_import),
|
||||
query!("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "{}", sc_conflicts),
|
||||
cmd!("file.openRecent", "Open Recent", [], None, "{index? | path?}", has_recent, open_recent),
|
||||
cmd!("file.openRecent", "Open Recent", [], Some("Cmd+Alt+Shift+P"), "{index? | path?}", has_recent, open_recent),
|
||||
cmd!("file.clearRecent", "Clear Recent Projects", ["File", "Open Recent"], None, "{}", has_recent, clear_recent),
|
||||
cmd!("file.autoSave", "Auto-Save Now", [], None, "{}", always, auto_save),
|
||||
query!("file.recoveryInfo", "Auto-Save Status", "{}", recovery_info),
|
||||
|
||||
@@ -100,6 +100,14 @@ fn go(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"workEnd" => comp.work_area.1 - comp.frame_duration(),
|
||||
"layerIn" => sel_layer.map(|l| l.in_point).unwrap_or(t),
|
||||
"layerOut" => sel_layer.map(|l| l.out_point - comp.frame_duration()).unwrap_or(t),
|
||||
"nextInOut" | "prevInOut" => {
|
||||
// In and Out points (its last frame) of the selected layers, of every layer with none
|
||||
// selected.
|
||||
let sel = &s.state.selected_layers;
|
||||
let times =
|
||||
comp.layers.iter().filter(|l| sel.is_empty() || sel.contains(&l.id)).flat_map(|l| [l.in_point, l.out_point - comp.frame_duration()]).collect();
|
||||
step_to(times, t, comp.frame_duration(), to == "nextInOut")
|
||||
}
|
||||
"nextKey" | "prevKey" if visible.is_some() => {
|
||||
// What the Timeline shows: keys of its revealed properties, layer and comp markers
|
||||
// and the work area (After Effects' "visible items").
|
||||
@@ -148,7 +156,7 @@ fn go(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
step_to(times, t, comp.frame_duration(), to == "nextKey")
|
||||
}
|
||||
_ => return Err(super::bad("time.go", "to: start|end|workStart|workEnd|layerIn|layerOut|nextKey|prevKey")),
|
||||
_ => return Err(super::bad("time.go", "to: start|end|workStart|workEnd|layerIn|layerOut|nextInOut|prevInOut|nextKey|prevKey")),
|
||||
};
|
||||
s.set_time(target);
|
||||
Ok(report(s))
|
||||
@@ -178,8 +186,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("time.forward10", "Forward 10 Frames", [], ["Shift+PageDown", "Cmd+Shift+ArrowRight"], "{}", has_comp, |s, _| step(s, &json!({"frames": 10}))),
|
||||
cmd!("time.back10", "Back 10 Frames", [], ["Shift+PageUp", "Cmd+Shift+ArrowLeft"], "{}", has_comp, |s, _| step(s, &json!({"frames": -10}))),
|
||||
cmd!("time.step", "Step Frames", [], None, "{frames}", has_comp, step),
|
||||
cmd!("time.start", "Go to Start", [], Some("Home"), "{}", has_comp, |s, _| go(s, &json!({"to": "start"}))),
|
||||
cmd!("time.end", "Go to End", [], Some("End"), "{}", has_comp, |s, _| go(s, &json!({"to": "end"}))),
|
||||
cmd!("time.start", "Go to Start", [], ["Home", "Cmd+Alt+ArrowLeft"], "{}", has_comp, |s, _| go(s, &json!({"to": "start"}))),
|
||||
cmd!("time.end", "Go to End", [], ["End", "Cmd+Alt+ArrowRight"], "{}", has_comp, |s, _| go(s, &json!({"to": "end"}))),
|
||||
cmd!("time.workAreaStart", "Go to Work Area Start", [], Some("Shift+Home"), "{}", has_comp, |s, _| go(s, &json!({"to": "workStart"}))),
|
||||
cmd!("time.workAreaEnd", "Go to Work Area End", [], Some("Shift+End"), "{}", has_comp, |s, _| go(s, &json!({"to": "workEnd"}))),
|
||||
cmd!("time.previousInOut", "Go to Previous In or Out Point", [], Some("Cmd+Alt+Shift+ArrowLeft"), "{}", has_comp, |s, _| go(
|
||||
s,
|
||||
&json!({"to": "prevInOut"})
|
||||
)),
|
||||
cmd!("time.nextInOut", "Go to Next In or Out Point", [], Some("Cmd+Alt+Shift+ArrowRight"), "{}", has_comp, |s, _| go(s, &json!({"to": "nextInOut"}))),
|
||||
cmd!("time.layerIn", "Go to Layer In Point", [], Some("I"), "{}", has_comp, |s, _| go(s, &json!({"to": "layerIn"}))),
|
||||
cmd!("time.layerOut", "Go to Layer Out Point", [], Some("O"), "{}", has_comp, |s, _| go(s, &json!({"to": "layerOut"}))),
|
||||
cmd!(
|
||||
@@ -200,7 +215,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Go To",
|
||||
[],
|
||||
None,
|
||||
"{to: start|end|workStart|workEnd|layerIn|layerOut|nextKey|prevKey, prop?: uid, visible?: [{layer, prop}]}",
|
||||
"{to: start|end|workStart|workEnd|layerIn|layerOut|nextInOut|prevInOut|nextKey|prevKey, prop?: uid, visible?: [{layer, prop}]}",
|
||||
has_comp,
|
||||
go
|
||||
),
|
||||
|
||||
@@ -20,15 +20,58 @@ fn add_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o => return Err(bad("view.addGuide", format!("orientation must be vertical or horizontal, not `{o}`"))),
|
||||
};
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let position = f_p(p, "position").unwrap_or(if vertical { comp.width as f64 / 2.0 } else { comp.height as f64 / 2.0 });
|
||||
let n = s.edit("Add Guide", None, |proj, _| {
|
||||
let percent = p.get("percent").and_then(Value::as_bool).unwrap_or(false);
|
||||
let default = if percent {
|
||||
50.0
|
||||
} else if vertical {
|
||||
comp.width as f64 / 2.0
|
||||
} else {
|
||||
comp.height as f64 / 2.0
|
||||
};
|
||||
let position = f_p(p, "position").filter(|v| v.is_finite()).unwrap_or(default);
|
||||
let n = s.edit(if percent { "Add Percentage Guide" } else { "Add Guide" }, None, |proj, _| {
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
c.guides.push(Guide { vertical, position });
|
||||
c.guides.push(Guide { vertical, position, percent });
|
||||
Ok(c.guides.len())
|
||||
})?;
|
||||
Ok(json!({"guides": n}))
|
||||
}
|
||||
|
||||
/// View ▸ Convert Guides to Percentage / Pixels: every guide (or just `index`) changes unit
|
||||
/// without moving on the comp.
|
||||
fn convert_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let percent = match str_p(p, "to").unwrap_or("percent") {
|
||||
"percent" | "percentage" => true,
|
||||
"pixels" | "px" => false,
|
||||
o => return Err(bad("view.convertGuides", format!("`to` must be percent or pixels, not `{o}`"))),
|
||||
};
|
||||
let only = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
|
||||
let n = s.project.comp(cid).ok_or(EngineError::NoComp)?.guides.len();
|
||||
if only.is_some_and(|i| i >= n) {
|
||||
return Err(bad("view.convertGuides", format!("no guide {} (the comp has {n})", only.unwrap_or(0))));
|
||||
}
|
||||
s.edit(if percent { "Convert Guides to Percentage" } else { "Convert Guides to Pixels" }, None, |proj, _| {
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let (w, h) = (c.width, c.height);
|
||||
for (i, g) in c.guides.iter_mut().enumerate() {
|
||||
if only.is_none_or(|o| o == i) {
|
||||
g.set_percent(percent, w, h);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"guides": n, "percent": percent}))
|
||||
}
|
||||
|
||||
fn add_percent_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut q = p.clone();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.insert("percent".into(), json!(true));
|
||||
}
|
||||
add_guide(s, &q)
|
||||
}
|
||||
|
||||
fn clear_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
s.edit("Clear Guides", None, |proj, _| {
|
||||
@@ -128,7 +171,25 @@ macro_rules! res {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("view.addGuide", "Add Guide...", ["View"], None, "{orientation?: vertical|horizontal, position? (comp px)}", has_comp, add_guide),
|
||||
cmd!(
|
||||
"view.addGuide",
|
||||
"Add Guide...",
|
||||
["View"],
|
||||
None,
|
||||
"{orientation?: vertical|horizontal, position? (comp px, or percent with percent: true), percent?: bool}",
|
||||
has_comp,
|
||||
add_guide
|
||||
),
|
||||
cmd!(
|
||||
"view.addPercentGuide",
|
||||
"Add Percentage Guide...",
|
||||
["View"],
|
||||
None,
|
||||
"{orientation?: vertical|horizontal, position? (percent of the comp)}",
|
||||
has_comp,
|
||||
add_percent_guide
|
||||
),
|
||||
cmd!("view.convertGuides", "Convert Guides to Percentage", ["View"], None, "{comp?, to?: percent|pixels, index?}", has_guides, convert_guides),
|
||||
cmd!("view.clearGuides", "Clear Guides", ["View"], None, "{comp?}", has_guides, clear_guides),
|
||||
cmd!("view.importGuides", "Import Guides...", ["View"], None, "{path}", has_comp, import_guides),
|
||||
cmd!("view.exportGuides", "Export Guides...", ["View"], None, "{path}", has_guides, export_guides),
|
||||
@@ -136,7 +197,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
res!("view.res.half", "Half", ["View", "Resolution"], Some("Cmd+Shift+J"), Half),
|
||||
res!("view.res.third", "Third", ["View", "Resolution"], None, Third),
|
||||
res!("view.res.quarter", "Quarter", ["View", "Resolution"], Some("Cmd+Alt+Shift+J"), Quarter),
|
||||
cmd!("view.res.custom", "Custom...", ["View", "Resolution"], None, "{factor?: 1..40 (render every n-th pixel), comp?}", has_comp, custom_resolution),
|
||||
cmd!(
|
||||
"view.res.custom",
|
||||
"Custom...",
|
||||
["View", "Resolution"],
|
||||
Some("Cmd+Alt+J"),
|
||||
"{factor?: 1..40 (render every n-th pixel), comp?}",
|
||||
has_comp,
|
||||
custom_resolution
|
||||
),
|
||||
// The Composition panel's Resolution popup (not in the View menu).
|
||||
res!("view.res.auto", "Resolution: Auto", [], None, Auto),
|
||||
cmd!("view.layout", "Switch View Layout", [], None, "{views: 1|2|4}", has_comp, view_layout),
|
||||
|
||||
@@ -127,8 +127,10 @@ fn snapping_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn channel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_p(p, "channel").unwrap_or("rgb");
|
||||
let c = Channel::from_name(name).ok_or_else(|| bad("view.channel", format!("unknown channel `{name}` (rgb|red|green|blue|alpha|rgbStraight)")))?;
|
||||
// Choosing the active single channel again returns to RGB, as in After Effects.
|
||||
let c = if c == s.state.viewer.channel && c != Channel::Rgb && b_p(p, "toggle").unwrap_or(false) { Channel::Rgb } else { c };
|
||||
// Choosing the active single channel again returns to RGB; not when that changes it between
|
||||
// grayscale and colorized.
|
||||
let same = c == s.state.viewer.channel && b_p(p, "colorized").is_none_or(|v| v == s.state.viewer.colorized);
|
||||
let c = if same && c != Channel::Rgb && b_p(p, "toggle").unwrap_or(false) { Channel::Rgb } else { c };
|
||||
s.state.viewer.channel = c;
|
||||
if let Some(v) = b_p(p, "colorized") {
|
||||
s.state.viewer.colorized = v;
|
||||
@@ -173,6 +175,20 @@ fn show_snapshot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!(s.state.viewer.show_snapshot))
|
||||
}
|
||||
|
||||
/// A `view.fastPreviews.*` command choosing one Fast Previews mode.
|
||||
macro_rules! fast {
|
||||
($id:literal, $label:literal, $sc:literal, $mode:literal) => {
|
||||
cmd!($id, $label, [], Some($sc), "{}", always, |s, _| fast_previews(s, &json!({"mode": $mode})))
|
||||
};
|
||||
}
|
||||
|
||||
/// A `view.channel.*` command showing one channel (again: back to RGB), in grayscale or colorized.
|
||||
macro_rules! chan {
|
||||
($id:literal, $label:literal, $sc:literal, $channel:literal, $colorized:literal) => {
|
||||
cmd!($id, $label, [], Some($sc), "{}", always, |s, _| channel(s, &json!({"channel": $channel, "colorized": $colorized, "toggle": true})))
|
||||
};
|
||||
}
|
||||
|
||||
fn fast_previews(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_p(p, "mode").unwrap_or("off");
|
||||
let m =
|
||||
@@ -194,8 +210,12 @@ fn guide_index(s: &Session, p: &Value, cmd: &str) -> Result<(effectcraft_project
|
||||
fn move_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, i) = guide_index(s, p, "view.moveGuide")?;
|
||||
let pos = f_p(p, "position").ok_or_else(|| bad("view.moveGuide", "missing `position` (comp px)"))?;
|
||||
let pos = if pos.is_finite() { pos } else { return Err(bad("view.moveGuide", "`position` must be a finite number")) };
|
||||
s.edit("Move Guide", merge_p(p), |proj, _| {
|
||||
proj.comp_mut(cid).ok_or(EngineError::NoComp)?.guides[i].position = pos;
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let (w, h) = (c.width, c.height);
|
||||
let g = c.guides.get_mut(i).ok_or(EngineError::NoComp)?;
|
||||
g.set_px(pos, w, h);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!(pos))
|
||||
@@ -504,6 +524,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("view.takeSnapshot", "Take Snapshot", [], Some("Shift+F5"), "{comp?, scale?: 0.05..1}", has_comp, take_snapshot),
|
||||
cmd!("view.showSnapshot", "Show Snapshot", [], None, "{value?}", has_snapshot, show_snapshot),
|
||||
cmd!("view.fastPreviewMode", "Fast Previews", [], None, "{mode: off|adaptive|draft|fastDraft|wireframe}", always, fast_previews),
|
||||
fast!("view.fastPreviews.off", "Fast Previews: Off (Final Quality)", "Cmd+Alt+1", "off"),
|
||||
fast!("view.fastPreviews.adaptive", "Fast Previews: Adaptive Resolution", "Cmd+Alt+2", "adaptive"),
|
||||
fast!("view.fastPreviews.draft", "Fast Previews: Draft", "Cmd+Alt+3", "draft"),
|
||||
fast!("view.fastPreviews.fastDraft", "Fast Previews: Fast Draft", "Cmd+Alt+4", "fastDraft"),
|
||||
fast!("view.fastPreviews.wireframe", "Fast Previews: Wireframe", "Cmd+Alt+5", "wireframe"),
|
||||
chan!("view.channel.red", "Show Channel: Red", "Alt+1", "red", false),
|
||||
chan!("view.channel.green", "Show Channel: Green", "Alt+2", "green", false),
|
||||
chan!("view.channel.blue", "Show Channel: Blue", "Alt+3", "blue", false),
|
||||
chan!("view.channel.alpha", "Show Channel: Alpha", "Alt+4", "alpha", false),
|
||||
chan!("view.channel.redColorized", "Show Channel: Red, Colorized", "Alt+Shift+1", "red", true),
|
||||
chan!("view.channel.greenColorized", "Show Channel: Green, Colorized", "Alt+Shift+2", "green", true),
|
||||
chan!("view.channel.blueColorized", "Show Channel: Blue, Colorized", "Alt+Shift+3", "blue", true),
|
||||
cmd!("view.channel.rgbStraight", "Show Channel: RGB Straight", [], Some("Alt+Shift+4"), "{}", always, |s, _| channel(
|
||||
s,
|
||||
&json!({"channel": "rgbStraight", "toggle": true})
|
||||
)),
|
||||
cmd!("view.moveGuide", "Move Guide", [], None, "{comp?, index, position (comp px), merge?}", has_comp, move_guide),
|
||||
cmd!("view.removeGuide", "Remove Guide", [], None, "{comp?, index}", has_comp, remove_guide),
|
||||
cmd!(
|
||||
|
||||
@@ -27,6 +27,8 @@ struct Job {
|
||||
enum Found {
|
||||
Missing(bool),
|
||||
Probed(Box<Footage>),
|
||||
/// Found again under the project's new folder (the project was moved with its footage).
|
||||
Moved(Box<Footage>),
|
||||
}
|
||||
|
||||
fn exists(s: &dyn crate::Services, path: &str) -> bool {
|
||||
@@ -52,6 +54,7 @@ pub fn start(s: &mut Session, items: Option<Vec<ItemId>>, wait: bool) -> crate::
|
||||
let services = s.services.clone();
|
||||
let importer = s.importer.clone();
|
||||
let rate = s.sequence_rate();
|
||||
let project_dir = s.path.as_deref().and_then(crate::commands::relink_moved::project_dir);
|
||||
let n = jobs.len();
|
||||
s.spawn_task("footageCheck", format!("Checking footage ({n} items)"), wait, move |ctl| {
|
||||
let mut found: Vec<(ItemId, Found)> = Vec::with_capacity(jobs.len());
|
||||
@@ -68,6 +71,14 @@ pub fn start(s: &mut Session, items: Option<Vec<ItemId>>, wait: bool) -> crate::
|
||||
// placeholders, as in After Effects).
|
||||
exists(services.as_ref(), &f.path) || f.sequence.iter().any(|p| exists(services.as_ref(), p))
|
||||
};
|
||||
// Moved with the project: the same place under the project's folder.
|
||||
if !present
|
||||
&& let Some(dir) = &project_dir
|
||||
&& let Some(nf) = crate::commands::relink_moved::find_moved(services.as_ref(), dir, f)
|
||||
{
|
||||
found.push((j.id, Found::Moved(Box::new(nf))));
|
||||
continue;
|
||||
}
|
||||
// Saved without metadata (a hand-written or converted project): probe it now.
|
||||
let needs_probe = present && f.width == 0 && f.height == 0 && f.kind != FootageKind::Audio;
|
||||
let probed = importer.as_ref().filter(|_| needs_probe).map(|imp| match f.kind {
|
||||
@@ -105,7 +116,7 @@ pub fn start(s: &mut Session, items: Option<Vec<ItemId>>, wait: bool) -> crate::
|
||||
/// not an edit (the same as After Effects marking footage missing at open).
|
||||
fn apply(s: &mut Session, found: Vec<(ItemId, Found)>) -> Value {
|
||||
let checked = found.len();
|
||||
let (mut missing, mut probed, mut changed) = (0, 0, false);
|
||||
let (mut missing, mut probed, mut moved, mut changed) = (0, 0, 0, false);
|
||||
let p = std::sync::Arc::make_mut(&mut s.project);
|
||||
for (id, f) in found {
|
||||
let Some(ItemKind::Footage(cur)) = p.item_mut(id).map(|i| &mut i.kind) else { continue };
|
||||
@@ -122,6 +133,11 @@ fn apply(s: &mut Session, found: Vec<(ItemId, Found)>) -> Value {
|
||||
*cur = *nf;
|
||||
changed = true;
|
||||
}
|
||||
Found::Moved(nf) => {
|
||||
moved += 1;
|
||||
*cur = *nf;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
@@ -133,10 +149,17 @@ fn apply(s: &mut Session, found: Vec<(ItemId, Found)>) -> Value {
|
||||
}
|
||||
s.events.push(crate::Event::PurgeCaches);
|
||||
}
|
||||
if missing > 0 {
|
||||
s.toast(format!("{missing} footage item(s) missing (File ▸ Dependencies ▸ Find Missing Footage)"));
|
||||
if moved > 0 {
|
||||
s.toast(format!("Found {moved} footage item(s) in the project's new folder"));
|
||||
}
|
||||
json!({"checked": checked, "missing": missing, "probed": probed})
|
||||
if missing > 0 {
|
||||
s.toast(format!("{missing} footage item(s) missing (File ▸ Dependencies ▸ Relink Missing Footage…)"));
|
||||
}
|
||||
let mut out = json!({"checked": checked, "missing": missing, "probed": probed});
|
||||
if moved > 0 {
|
||||
out["relinked"] = json!(moved);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn command(s: &mut Session, p: &Value) -> crate::Result<Value> {
|
||||
@@ -223,6 +246,34 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footage_moved_with_its_project_is_found_on_open() {
|
||||
let d = std::env::temp_dir().join(format!("ec-footage-moved-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("Job/shots")).unwrap();
|
||||
std::fs::write(d.join("Job/shots/a.png"), b"x").unwrap();
|
||||
// Saved on another machine: the footage sat next to the project in /Users/x/Job.
|
||||
let mut s = session_with(&["/Users/x/Job/shots/a.png", "/Users/x/elsewhere/b.png"]);
|
||||
let path = d.join("Job/p.ecproj");
|
||||
s.execute("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let mut o = Session::default();
|
||||
o.execute("file.open", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let r = o.execute("footage.check", json!({"wait": true})).unwrap();
|
||||
assert_eq!((r["relinked"].as_u64(), r["missing"].as_u64()), (Some(1), Some(1)), "{r}");
|
||||
let paths: Vec<String> = o
|
||||
.project
|
||||
.items
|
||||
.values()
|
||||
.filter_map(|i| match &i.kind {
|
||||
ItemKind::Footage(f) => Some(f.path.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(paths.contains(&d.join("Job/shots/a.png").to_string_lossy().to_string()), "{paths:?}");
|
||||
assert!(!o.is_dirty(), "finding the files is not an edit");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_starts_the_check_when_asked() {
|
||||
let mut s = session_with(&["/nonexistent/ec/a.mov"]);
|
||||
|
||||
+123
-9
@@ -194,15 +194,38 @@ pub struct VertexRef {
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
/// One composition's selection. The active comp's copy lives in [`EditorState::selected_layers`]
|
||||
/// (and the property, key, and vertex lists); every other comp keeps its own here (#1001).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CompSelection {
|
||||
pub layers: Vec<LayerId>,
|
||||
pub props: Vec<(LayerId, Uid)>,
|
||||
pub keys: Vec<KeyRef>,
|
||||
pub vertices: Vec<VertexRef>,
|
||||
}
|
||||
|
||||
impl CompSelection {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.layers.is_empty() && self.props.is_empty() && self.keys.is_empty() && self.vertices.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Editing state that commands depend on (headless-relevant, serde for agents).
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct EditorState {
|
||||
pub active_comp: Option<ItemId>,
|
||||
/// Open compositions (viewer/timeline tabs), in tab order.
|
||||
pub open_comps: Vec<ItemId>,
|
||||
/// Compositions that were active before the current one, most recent first (Shift+Esc).
|
||||
#[serde(default)]
|
||||
pub recent_comps: Vec<ItemId>,
|
||||
/// Current time per comp (the CTI).
|
||||
pub times: std::collections::BTreeMap<ItemId, Tick>,
|
||||
/// Layer selection of the active comp. Other comps' selections are in [`Self::comp_selections`].
|
||||
pub selected_layers: Vec<LayerId>,
|
||||
/// Selections of comps that are not active, keyed by comp id (#1001).
|
||||
#[serde(default)]
|
||||
pub comp_selections: std::collections::BTreeMap<ItemId, CompSelection>,
|
||||
/// Selected properties / groups (by uid) of selected layers.
|
||||
pub selected_props: Vec<(LayerId, Uid)>,
|
||||
pub selected_keys: Vec<KeyRef>,
|
||||
@@ -220,8 +243,8 @@ pub struct EditorState {
|
||||
/// Paste sets the same properties of the selected layers.
|
||||
#[serde(skip)]
|
||||
pub value_clipboard: Vec<(String, effectcraft_keyframe::Value)>,
|
||||
/// Copied effect instances (Edit ▸ Copy with effects selected); Paste adds them to the
|
||||
/// selected layers.
|
||||
/// Copied effect instances, with comp-time key offsets from the earliest copied key.
|
||||
/// Paste adds them to the selected layers at the destination comp's CTI.
|
||||
#[serde(skip)]
|
||||
pub effect_clipboard: Vec<effectcraft_project::PropGroup>,
|
||||
/// Copied shape items (Edit ▸ Copy with groups, paths, paints or path operations selected in
|
||||
@@ -757,12 +780,26 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Drop selections that no longer exist.
|
||||
/// Drop selections that no longer exist. Each comp keeps its own selection (#1001); a layer id
|
||||
/// counts only inside the comp that owns it, so the active comp never sees another comp's layers.
|
||||
pub fn sanitize_state(&mut self) {
|
||||
let p = self.project.clone();
|
||||
self.state.open_comps.retain(|c| p.comp(*c).is_some());
|
||||
self.state.comp_selections.retain(|cid, sel| {
|
||||
let Some(c) = p.comp(*cid) else { return false };
|
||||
let ids: Vec<LayerId> = c.layers.iter().map(|l| l.id).collect();
|
||||
sel.layers.retain(|l| ids.contains(l));
|
||||
sel.props.retain(|(l, _)| ids.contains(l));
|
||||
sel.keys.retain(|k| ids.contains(&k.layer));
|
||||
sel.vertices.retain(|v| ids.contains(&v.layer));
|
||||
!sel.is_empty()
|
||||
});
|
||||
if self.state.active_comp.is_some_and(|c| p.comp(c).is_none()) {
|
||||
self.clear_live_selection();
|
||||
self.state.active_comp = self.state.open_comps.first().copied();
|
||||
if let Some(id) = self.state.active_comp {
|
||||
self.recall_selection(id);
|
||||
}
|
||||
}
|
||||
if let Some(c) = self.active_comp() {
|
||||
let ids: Vec<LayerId> = c.layers.iter().map(|l| l.id).collect();
|
||||
@@ -870,6 +907,59 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `id` the active comp, parking the previous comp's selection and restoring this one's.
|
||||
pub fn activate_comp(&mut self, id: ItemId) {
|
||||
if self.project.comp(id).is_none() || self.state.active_comp == Some(id) {
|
||||
return;
|
||||
}
|
||||
self.remember_selection();
|
||||
self.state.active_comp = Some(id);
|
||||
self.recall_selection(id);
|
||||
self.state.current_track = None;
|
||||
}
|
||||
|
||||
/// Leave no comp active, keeping the one that was active in [`EditorState::comp_selections`].
|
||||
pub fn activate_comp_none(&mut self) {
|
||||
self.remember_selection();
|
||||
self.state.active_comp = None;
|
||||
self.clear_live_selection();
|
||||
self.state.current_track = None;
|
||||
}
|
||||
|
||||
fn remember_selection(&mut self) {
|
||||
let Some(id) = self.state.active_comp else { return };
|
||||
let sel = CompSelection {
|
||||
layers: self.state.selected_layers.clone(),
|
||||
props: self.state.selected_props.clone(),
|
||||
keys: self.state.selected_keys.clone(),
|
||||
vertices: self.state.selected_vertices.clone(),
|
||||
};
|
||||
if sel.is_empty() {
|
||||
self.state.comp_selections.remove(&id);
|
||||
} else {
|
||||
self.state.comp_selections.insert(id, sel);
|
||||
}
|
||||
}
|
||||
|
||||
fn recall_selection(&mut self, id: ItemId) {
|
||||
match self.state.comp_selections.remove(&id) {
|
||||
Some(sel) => {
|
||||
self.state.selected_layers = sel.layers;
|
||||
self.state.selected_props = sel.props;
|
||||
self.state.selected_keys = sel.keys;
|
||||
self.state.selected_vertices = sel.vertices;
|
||||
}
|
||||
None => self.clear_live_selection(),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_live_selection(&mut self) {
|
||||
self.state.selected_layers.clear();
|
||||
self.state.selected_props.clear();
|
||||
self.state.selected_keys.clear();
|
||||
self.state.selected_vertices.clear();
|
||||
}
|
||||
|
||||
/// Open a comp in the viewer/timeline and make it active.
|
||||
pub fn open_comp(&mut self, id: ItemId) {
|
||||
if self.project.comp(id).is_none() {
|
||||
@@ -879,13 +969,14 @@ impl Session {
|
||||
self.state.open_comps.push(id);
|
||||
}
|
||||
if self.state.active_comp != Some(id) {
|
||||
self.state.active_comp = Some(id);
|
||||
self.state.selected_layers.clear();
|
||||
self.state.selected_props.clear();
|
||||
self.state.selected_keys.clear();
|
||||
self.state.selected_vertices.clear();
|
||||
self.state.current_track = None;
|
||||
let previous = self.state.active_comp;
|
||||
self.state.recent_comps.retain(|c| *c != id && Some(*c) != previous);
|
||||
if let Some(previous) = previous {
|
||||
self.state.recent_comps.insert(0, previous);
|
||||
self.state.recent_comps.truncate(32);
|
||||
}
|
||||
}
|
||||
self.activate_comp(id);
|
||||
self.events.push(Event::OpenComp(id));
|
||||
}
|
||||
|
||||
@@ -1016,6 +1107,15 @@ impl Session {
|
||||
Ok((img.width, img.height, img.to_rgba8()))
|
||||
}
|
||||
|
||||
/// Make the media layer and the layer cache let go of what they decoded from `footage`'s
|
||||
/// files (it keys frames by path, so an overwritten file would keep showing its old pixels).
|
||||
pub(crate) fn forget_decoded(&self, footage: &effectcraft_project::Footage) {
|
||||
for p in std::iter::once(&footage.path).chain(&footage.sequence) {
|
||||
self.footage.forget(p);
|
||||
}
|
||||
self.layer_cache.clear();
|
||||
}
|
||||
|
||||
/// Replace the whole project (open/new), resetting history and state.
|
||||
pub fn replace_project(&mut self, mut p: Project, path: Option<String>) {
|
||||
if self.stop_render()
|
||||
@@ -1042,6 +1142,14 @@ impl Session {
|
||||
self.script_ui.project_epoch = self.script_ui.project_epoch.wrapping_add(1);
|
||||
p.fix_next_id();
|
||||
upgrade_effects(&mut p);
|
||||
// The media layer keys decoded frames by path: files of the new project may have changed
|
||||
// since an earlier project decoded them (#1070).
|
||||
for it in p.items.values() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &it.kind {
|
||||
self.forget_decoded(f);
|
||||
}
|
||||
}
|
||||
self.layer_cache.clear();
|
||||
self.project = Arc::new(p);
|
||||
self.history = History::default();
|
||||
self.state = EditorState { snapping: true, view_layout: 1, ..Default::default() };
|
||||
@@ -1132,6 +1240,8 @@ mod tests_frame_export;
|
||||
#[cfg(test)]
|
||||
mod tests_fuzz_open;
|
||||
#[cfg(test)]
|
||||
mod tests_import_project;
|
||||
#[cfg(test)]
|
||||
mod tests_key_metadata_order;
|
||||
#[cfg(test)]
|
||||
mod tests_keylight;
|
||||
@@ -1158,12 +1268,16 @@ mod tests_project_items;
|
||||
#[cfg(test)]
|
||||
mod tests_proxy;
|
||||
#[cfg(test)]
|
||||
mod tests_quick_offset;
|
||||
#[cfg(test)]
|
||||
mod tests_rig3d;
|
||||
#[cfg(test)]
|
||||
mod tests_sequence;
|
||||
#[cfg(test)]
|
||||
mod tests_settings;
|
||||
#[cfg(test)]
|
||||
mod tests_shortcut_cmds;
|
||||
#[cfg(test)]
|
||||
mod tests_stubs;
|
||||
#[cfg(test)]
|
||||
mod tests_styles;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Community and project links (shown in Help ▸, the About dialog, the start screen and the
|
||||
//! header's Discord button).
|
||||
|
||||
pub const APP_NAME: &str = "EffectCraft";
|
||||
use effectcraft_rustmotion_common::APP_NAME;
|
||||
|
||||
pub const APP_SLUG: &str = "effectcraft";
|
||||
pub const DISCORD: &str = "https://discord.gg/artcraft";
|
||||
pub const WEBSITE: &str = "https://getartcraft.com";
|
||||
|
||||
+28
-14
@@ -18,10 +18,11 @@
|
||||
//! ```
|
||||
//!
|
||||
//! An entry's shortcut is the command's default shortcut unless the line gives one (needed for
|
||||
//! entries with bound parameters). Adobe-service entries (Team Projects, Libraries, Bridge, Media
|
||||
//! Encoder, Behance, Creative Cloud…) are intentionally absent; the Essential Graphics workspace
|
||||
//! uses the Properties panel and the Essential Graphics panel, whose templates use EffectCraft's
|
||||
//! own open `.ectemplate` format.
|
||||
//! entries with bound parameters). A line can give further default keys after a comma
|
||||
//! (`| F3, Cmd+Shift+T`); the menus show the first. Adobe-service entries (Team Projects,
|
||||
//! Libraries, Bridge, Media Encoder, Behance, Creative Cloud…) are intentionally absent; the
|
||||
//! Essential Graphics workspace uses the Properties panel and the Essential Graphics panel, whose
|
||||
//! templates use EffectCraft's own open `.ectemplate` format.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -61,7 +62,7 @@ fn file_name(p: &str) -> String {
|
||||
}
|
||||
|
||||
fn dyn_entry(label: String, command: &str, params: Value) -> MenuEntry {
|
||||
MenuEntry { label, command: command.into(), params, shortcut: None }
|
||||
MenuEntry { label, command: command.into(), params, shortcut: None, alt_shortcuts: vec![] }
|
||||
}
|
||||
|
||||
/// The bindable holding shortcut `keys` in the active preset (its label).
|
||||
@@ -175,6 +176,9 @@ pub struct MenuEntry {
|
||||
#[serde(skip_serializing_if = "Value::is_null")]
|
||||
pub params: Value,
|
||||
pub shortcut: Option<String>,
|
||||
/// Further default shortcuts (the menus show `shortcut`).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub alt_shortcuts: Vec<String>,
|
||||
}
|
||||
|
||||
impl MenuEntry {
|
||||
@@ -434,8 +438,9 @@ pub fn parse(text: &str, mac: bool) -> Result<Vec<MenuNode>, String> {
|
||||
};
|
||||
// Entries with bound params state their own shortcut; plain entries use the command's.
|
||||
let inherited = if params.is_null() { commands::find(&command).and_then(|c| c.shortcut).map(str::to_string) } else { None };
|
||||
let shortcut = parts.next().map(|s| s.trim().to_string()).or(inherited);
|
||||
out.push(MenuNode::Item(MenuEntry { label, command, params, shortcut }));
|
||||
let mut keys = parts.next().into_iter().flat_map(|s| s.split(", ")).map(|s| s.trim().to_string());
|
||||
let shortcut = keys.next().or(inherited);
|
||||
out.push(MenuNode::Item(MenuEntry { label, command, params, shortcut, alt_shortcuts: keys.collect() }));
|
||||
}
|
||||
None => {
|
||||
let children = build(lines, i, depth + 1, mac)?;
|
||||
@@ -456,8 +461,13 @@ pub fn parse(text: &str, mac: bool) -> Result<Vec<MenuNode>, String> {
|
||||
fn effect_categories() -> Vec<MenuNode> {
|
||||
let mut cats: Vec<(&str, Vec<MenuNode>)> = vec![];
|
||||
for e in crate::effects::all() {
|
||||
let entry =
|
||||
MenuNode::Item(MenuEntry { label: e.name.into(), command: "effect.apply".into(), params: serde_json::json!({"effect": e.id}), shortcut: None });
|
||||
let entry = MenuNode::Item(MenuEntry {
|
||||
label: e.name.into(),
|
||||
command: "effect.apply".into(),
|
||||
params: serde_json::json!({"effect": e.id}),
|
||||
shortcut: None,
|
||||
alt_shortcuts: vec![],
|
||||
});
|
||||
match cats.iter_mut().find(|(c, _)| *c == e.category) {
|
||||
Some((_, v)) => v.push(entry),
|
||||
None => cats.push((e.category, vec![entry])),
|
||||
@@ -528,6 +538,7 @@ File
|
||||
File... | file.import
|
||||
Multiple Files... | file.importMultiple
|
||||
Adobe Premiere Pro Project... | file.importTimeline
|
||||
EffectCraft Project... | file.importProject
|
||||
Placeholder... | file.importPlaceholder
|
||||
Solid... | file.importSolid
|
||||
Lottie... | file.importLottie
|
||||
@@ -650,7 +661,7 @@ Edit
|
||||
All 3D Cache... | edit.purge {"what":"3d"}
|
||||
Undo | edit.purgeUndo
|
||||
Image Cache Memory | edit.purge {"what":"image"}
|
||||
Snapshot | edit.purge {"what":"snapshot"}
|
||||
Snapshot | edit.purge {"what":"snapshot"} | Cmd+Shift+F5
|
||||
---
|
||||
Edit Original... | edit.editOriginal
|
||||
---
|
||||
@@ -775,8 +786,8 @@ Layer
|
||||
Draft | layer.quality {"quality":"draft"} | Cmd+Shift+U
|
||||
Wireframe | layer.quality {"quality":"wireframe"} | Cmd+Alt+Shift+U
|
||||
---
|
||||
Bilinear | layer.sampling {"sampling":"bilinear"}
|
||||
Bicubic | layer.sampling {"sampling":"bicubic"}
|
||||
Bilinear | layer.sampling {"sampling":"bilinear","toggle":true} | Alt+B
|
||||
Bicubic | layer.sampling {"sampling":"bicubic","toggle":true} | Alt+Shift+B
|
||||
Switches
|
||||
Hide Other Video | layer.hideOtherVideo
|
||||
Show All Video | layer.showAllVideo
|
||||
@@ -954,7 +965,7 @@ Layer
|
||||
Pre-compose... | layer.precompose
|
||||
Scene Edit Detection... | layer.sceneEditDetection
|
||||
Effect
|
||||
Effect Controls | window.panel {"panel":"effectControls"} | F3
|
||||
Effect Controls | window.panel {"panel":"effectControls"} | F3, Cmd+Shift+T
|
||||
Last Effect | effect.applyLast
|
||||
Remove All | effect.removeAll
|
||||
---
|
||||
@@ -1106,6 +1117,9 @@ View
|
||||
Snap to Guides | view.snapToGuides
|
||||
Lock Guides | view.lockGuides
|
||||
Add Guide... | view.addGuide
|
||||
Add Percentage Guide... | view.addPercentGuide
|
||||
Convert Guides to Percentage | view.convertGuides {"to":"percent"}
|
||||
Convert Guides to Pixels | view.convertGuides {"to":"pixels"}
|
||||
Clear Guides | view.clearGuides
|
||||
Import Guides... | view.importGuides
|
||||
Export Guides... | view.exportGuides
|
||||
@@ -1203,7 +1217,7 @@ Window
|
||||
Wiggler | window.panel {"panel":"wiggler"}
|
||||
---
|
||||
Composition | window.panel {"panel":"composition"}
|
||||
Effect Controls | window.panel {"panel":"effectControls"} | F3
|
||||
Effect Controls | window.panel {"panel":"effectControls"} | F3, Cmd+Shift+T
|
||||
Flowchart | window.panel {"panel":"flowchart"} | Cmd+F11
|
||||
Footage | window.panel {"panel":"footage"}
|
||||
Layer | window.panel {"panel":"layer"}
|
||||
|
||||
@@ -561,7 +561,8 @@ async fn fill(s: &mut Session, plan: crate::commands::content_fill::FillPlan, po
|
||||
/// Roto Brush propagation in a worker: the segmentations stream back (at most every 250 ms)
|
||||
/// as they are computed, so stopping the job keeps what was propagated.
|
||||
async fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: crate::roto::Direction, post: Post) -> Result<(), String> {
|
||||
let keys: Vec<u64> = s.roto_chain(comp, layer, effect).map(|c| c.keys.values().copied().collect()).ok_or("no Roto Brush strokes")?;
|
||||
let keys: Vec<u64> =
|
||||
s.roto_keys(comp, layer, effect).map(|k| k.into_iter().map(|(_, k)| k).collect()).ok_or("no Roto Brush strokes or Object Matte prompt")?;
|
||||
let sent = Rc::new(RefCell::new(std::collections::HashSet::new()));
|
||||
let (p, k2, s2) = (post.clone(), keys.clone(), sent.clone());
|
||||
let mut last = None::<web_time::Instant>;
|
||||
|
||||
@@ -205,9 +205,8 @@ impl PreviewPreset {
|
||||
pub fn default_for(s: PreviewShortcut) -> Self {
|
||||
let d = PreviewPreset::default();
|
||||
match s {
|
||||
PreviewShortcut::Spacebar => d,
|
||||
// A lighter preview: every other frame.
|
||||
PreviewShortcut::ShiftSpacebar => PreviewPreset { skip: 1, ..d },
|
||||
// Frame skipping is off by default; set Skip to play fewer frames.
|
||||
PreviewShortcut::Spacebar | PreviewShortcut::ShiftSpacebar => d,
|
||||
PreviewShortcut::Numpad0 => PreviewPreset { range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, ..d },
|
||||
PreviewShortcut::ShiftNumpad0 => {
|
||||
PreviewPreset { range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, skip: 1, resolution: PreviewResolution::Half, ..d }
|
||||
@@ -509,6 +508,13 @@ mod tests {
|
||||
assert_eq!(pl.frame_after(237, 1), None);
|
||||
}
|
||||
|
||||
/// #551: Shift+Spacebar used to skip every other frame out of the box.
|
||||
#[test]
|
||||
fn shift_spacebar_plays_every_frame_by_default() {
|
||||
assert_eq!(PreviewPreset::default_for(PreviewShortcut::ShiftSpacebar).skip, 0);
|
||||
assert_eq!(PreviewPreset::default_for(PreviewShortcut::ShiftSpacebar), PreviewPreset::default_for(PreviewShortcut::Spacebar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_commands_round_trip() {
|
||||
let mut s = comp_session();
|
||||
|
||||
@@ -111,10 +111,46 @@ struct Ctx<'a> {
|
||||
pub fn import(proj: &mut Project, psd: &Psd, path: &str, name: &str, retain: bool, rate: FrameRate, duration: Tick) -> PsdImport {
|
||||
let folder = proj.add_item(&format!("{name} Layers"), Label::Yellow, None, ItemKind::Folder);
|
||||
let mut cx = Ctx { psd, path, retain, folder, rate, duration, items: vec![], warnings: vec![] };
|
||||
let comp = build_comp(proj, &mut cx, name, &psd.tree(), None);
|
||||
cx.warnings.extend(psd.warnings.iter().cloned());
|
||||
let (tree, flattened) = psd.tree_report();
|
||||
if flattened > 0 {
|
||||
cx.warnings.push(format!("{flattened} group(s) nested deeper than {} levels were flattened into their parent", effectcraft_psd::MAX_GROUP_DEPTH));
|
||||
}
|
||||
let comp =
|
||||
if psd.layers.is_empty() && !psd.warnings.is_empty() { flattened_comp(proj, &mut cx, name) } else { build_comp(proj, &mut cx, name, &tree, None) };
|
||||
PsdImport { comp, folder, items: cx.items, warnings: cx.warnings }
|
||||
}
|
||||
|
||||
/// The layers could not be read: the merged image as the composition's only layer.
|
||||
fn flattened_comp(proj: &mut Project, cx: &mut Ctx, name: &str) -> ItemId {
|
||||
let cid = proj.add_item(name, Label::Sandstone, None, ItemKind::Comp(Arc::new(new_comp(cx))));
|
||||
cx.items.push(cid);
|
||||
let mut comp = new_comp(cx);
|
||||
let file = std::path::Path::new(cx.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let f = Footage {
|
||||
path: cx.path.to_string(),
|
||||
kind: FootageKind::Still,
|
||||
width: cx.psd.width,
|
||||
height: cx.psd.height,
|
||||
pixel_aspect: 1.0,
|
||||
frame_rate: cx.rate,
|
||||
has_video: true,
|
||||
alpha: if cx.psd.merged_alpha { AlphaMode::Straight } else { AlphaMode::Ignore },
|
||||
loop_count: 1,
|
||||
codec: "PSD".into(),
|
||||
layer: None,
|
||||
..Default::default()
|
||||
};
|
||||
let id = proj.add_item(&file, Label::Lavender, Some(cx.folder), ItemKind::Footage(f));
|
||||
cx.items.push(id);
|
||||
let l = build::layer(proj, &comp, name, LayerSource::Footage { item: id }, (cx.psd.width, cx.psd.height), None);
|
||||
comp.layers.push(l);
|
||||
if let Some(item) = proj.item_mut(cid) {
|
||||
item.kind = ItemKind::Comp(Arc::new(comp));
|
||||
}
|
||||
cid
|
||||
}
|
||||
|
||||
fn new_comp(cx: &Ctx) -> Comp {
|
||||
// A PSB can be 300,000 px a side; a composition is at most 30,000 (#788).
|
||||
let size = |v: u32| effectcraft_project::limits::size(v.into());
|
||||
@@ -202,7 +238,8 @@ fn smart_object_layer(proj: &mut Project, cx: &mut Ctx, comp: &Comp, index: usiz
|
||||
let bb = so.placed_bounds(cw as f64, ch as f64);
|
||||
let area = ((bb[2] - bb[0]) * (bb[3] - bb[1])).max(1.0);
|
||||
let k = ((cw as f64 * ch as f64) / area).sqrt().clamp(1.0, 4.0);
|
||||
let (w, h) = so.placed_size(cw as f64, ch as f64, k);
|
||||
// At most 4× the document across and 2^24 pixels, however far the file moves a corner.
|
||||
let (k, (w, h)) = so.bake_scale(cw as f64, ch as f64, k, (cx.psd.width, cx.psd.height));
|
||||
(w, h, k, bb)
|
||||
} else {
|
||||
(cw, ch, 1.0, [0.0; 4])
|
||||
@@ -333,13 +370,21 @@ fn layer_origin(pl: &effectcraft_psd::Layer, retain: bool, layer: &Layer) -> [f6
|
||||
[0.0, 0.0]
|
||||
}
|
||||
|
||||
/// Sets a scalar property; a non-finite value (from corrupt transforms) keeps the default.
|
||||
fn set_scalar(l: &mut Layer, path: &str, v: f64) {
|
||||
if !v.is_finite() {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = l.props.prop_mut(path) {
|
||||
p.value = Value::Scalar(v);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a 2D property; a non-finite component (from corrupt transforms) keeps the default.
|
||||
fn set_vec2(l: &mut Layer, path: &str, v: [f64; 2]) {
|
||||
if !v.iter().all(|c| c.is_finite()) {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = l.props.prop_mut(path) {
|
||||
p.value = match p.value {
|
||||
Value::Vec3(o) => Value::Vec3([v[0], v[1], o[2]]),
|
||||
@@ -361,8 +406,10 @@ fn text_doc(t: &effectcraft_psd::TextInfo) -> TextDoc {
|
||||
d.set_text(&t.text);
|
||||
let [xx, xy, yx, yy, _, _] = t.transform;
|
||||
let scale = (xx * yy - xy * yx).abs().sqrt().max(1e-6);
|
||||
if let Some(s) = t.style.size {
|
||||
d.size = s * scale;
|
||||
// A transform too large to multiply (inf) falls back to 1×; products below stay finite.
|
||||
let scale = if scale.is_finite() { scale } else { 1.0 };
|
||||
if let Some(s) = t.style.size.map(|s| s * scale).filter(|s| s.is_finite() && *s > 0.0) {
|
||||
d.size = s;
|
||||
}
|
||||
if let Some(f) = &t.style.font {
|
||||
let (fam, style) = font_names(f);
|
||||
@@ -381,19 +428,20 @@ fn text_doc(t: &effectcraft_psd::TextInfo) -> TextDoc {
|
||||
Some(6) => Justify::JustifyAll,
|
||||
_ => Justify::Left,
|
||||
};
|
||||
if let Some(tr) = t.style.tracking {
|
||||
if let Some(tr) = t.style.tracking.filter(|v| v.is_finite()) {
|
||||
d.tracking = tr;
|
||||
}
|
||||
if let Some(l) = t.style.leading {
|
||||
d.leading = Some(l * scale);
|
||||
}
|
||||
d.leading = t.style.leading.map(|l| l * scale).filter(|l| l.is_finite());
|
||||
d.faux_bold = t.style.faux_bold;
|
||||
d.faux_italic = t.style.faux_italic;
|
||||
if t.style.box_text
|
||||
&& let Some([l, top, r, b]) = t.bounds
|
||||
{
|
||||
d.box_size = Some([(r - l) * scale, (b - top) * scale]);
|
||||
d.box_pos = [l * scale, top * scale];
|
||||
let (size, pos) = ([(r - l) * scale, (b - top) * scale], [l * scale, top * scale]);
|
||||
if size.iter().chain(&pos).all(|v| v.is_finite()) {
|
||||
d.box_size = Some(size);
|
||||
d.box_pos = pos;
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
@@ -716,4 +764,32 @@ mod tests {
|
||||
assert_eq!(desc_blend(Some("linearDodge")), Some(BlendMode::LinearDodge));
|
||||
assert_eq!(font_names("Inter-Bold"), ("Inter".into(), "Bold".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_text_values_never_reach_the_layer() {
|
||||
let style = effectcraft_psd::engine_data::TextStyle {
|
||||
size: Some(f64::NAN),
|
||||
tracking: Some(f64::INFINITY),
|
||||
leading: Some(f64::NEG_INFINITY),
|
||||
..Default::default()
|
||||
};
|
||||
let t = effectcraft_psd::TextInfo {
|
||||
text: "x".into(),
|
||||
transform: [f64::INFINITY, 0.0, 0.0, 1.0, f64::NAN, 1.0],
|
||||
style,
|
||||
bounds: Some([0.0, 0.0, f64::INFINITY, 1.0]),
|
||||
};
|
||||
let d = text_doc(&t);
|
||||
assert!(d.size.is_finite() && d.tracking.is_finite());
|
||||
assert!(d.leading.is_none_or(f64::is_finite));
|
||||
assert!(d.box_size.is_none_or(|b| b.iter().all(|v| v.is_finite())));
|
||||
let mut proj = Project::default();
|
||||
let comp = Comp::new(64, 64, FrameRate::FPS_24, Tick::ZERO);
|
||||
let l = text_layer(&mut proj, &comp, "t", &t);
|
||||
match l.props.prop("transform/position").map(|p| &p.value) {
|
||||
Some(Value::Vec2(v)) => assert!(v.iter().all(|c| c.is_finite())),
|
||||
Some(Value::Vec3(v)) => assert!(v.iter().all(|c| c.is_finite())),
|
||||
other => panic!("unexpected position {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,10 +610,17 @@ impl Session {
|
||||
let _ = t.join();
|
||||
}
|
||||
let st = job.shared.snapshot();
|
||||
let failed = updates.iter().filter(|u| matches!(u, ItemUpdate::Finished { status: RenderStatus::Failed(_), .. })).count();
|
||||
let failures: Vec<&str> = updates
|
||||
.iter()
|
||||
.filter_map(|u| if let ItemUpdate::Finished { status: RenderStatus::Failed(e), .. } = u { Some(e.as_str()) } else { None })
|
||||
.collect();
|
||||
let failed = failures.len();
|
||||
let stopped = updates.iter().any(|u| matches!(u, ItemUpdate::Finished { status: RenderStatus::UserStopped, .. }));
|
||||
let msg = if failed > 0 {
|
||||
format!("Render finished with {failed} failed item(s)")
|
||||
// The reason is otherwise only in the Status column's tooltip (#568).
|
||||
let msg = if let [only] = failures.as_slice() {
|
||||
format!("Render finished with 1 failed item(s): {only}")
|
||||
} else if let Some(first) = failures.first() {
|
||||
format!("Render finished with {failed} failed item(s), first: {first}")
|
||||
} else if stopped {
|
||||
"Render stopped".to_string()
|
||||
} else {
|
||||
|
||||
+148
-33
@@ -10,12 +10,18 @@
|
||||
//! edit, keeps each instance's hidden Input Key equal to a signature of what its frames are made
|
||||
//! of (the layer's source and timing, its masks and the effects above it) and drops frozen
|
||||
//! mattes made from other frames.
|
||||
//!
|
||||
//! Object Matte instances run through the same jobs (`objectMatte.propagate` / `.freeze`): the
|
||||
//! frames are [`om::job_frames`] around the reference frame, each segmented through
|
||||
//! [`om::ensure`]; Freeze stores [`om::frame_matte`]'s mattes under [`om::frozen_key`]. An edit
|
||||
//! to an instance's frames or prompt queues it for background tracking like a Roto Brush.
|
||||
|
||||
use crate::offload::JobKind;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_effects::object_matte as om;
|
||||
use effectcraft_effects::roto::{self as fx, FROZEN, FrozenCache, INPUT_KEY};
|
||||
use effectcraft_effects::{Params, flatten_params};
|
||||
use effectcraft_keyframe::Value;
|
||||
@@ -104,14 +110,18 @@ pub struct RotoProgress {
|
||||
pub finished: bool,
|
||||
pub cancelled: bool,
|
||||
pub error: Option<String>,
|
||||
/// The job works on an Object Matte (else a Roto Brush & Refine Edge).
|
||||
pub object_matte: bool,
|
||||
}
|
||||
|
||||
impl RotoProgress {
|
||||
pub fn banner(&self) -> String {
|
||||
let pc = (100 * self.done).checked_div(self.total).unwrap_or(0);
|
||||
match self.task {
|
||||
Some(RotoTask::Freeze) => format!("Freezing Roto Brush & Refine Edge: {pc}%"),
|
||||
_ => format!("Propagating Roto Brush: {pc}%"),
|
||||
match (self.task, self.object_matte) {
|
||||
(Some(RotoTask::Freeze), false) => format!("Freezing Roto Brush & Refine Edge: {pc}%"),
|
||||
(Some(RotoTask::Freeze), true) => format!("Freezing Object Matte: {pc}%"),
|
||||
(_, false) => format!("Propagating Roto Brush: {pc}%"),
|
||||
(_, true) => format!("Tracking Object Matte: {pc}%"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,8 +140,11 @@ pub struct RotoJob {
|
||||
pub layer: LayerId,
|
||||
pub effect: Uid,
|
||||
pub task: RotoTask,
|
||||
/// The strokes the job was started with (a Freeze result is dropped when they changed).
|
||||
/// What the job was started from: the strokes (Roto Brush) or the prompt (Object Matte); a
|
||||
/// Freeze result is dropped when it changed.
|
||||
strokes: String,
|
||||
/// The job works on an Object Matte.
|
||||
pub object_matte: bool,
|
||||
}
|
||||
|
||||
impl RotoJob {
|
||||
@@ -147,6 +160,26 @@ pub(crate) fn is_roto(g: &PropGroup) -> bool {
|
||||
matches!(&g.kind, GroupKind::Effect { effect } if effect == fx::ID)
|
||||
}
|
||||
|
||||
/// An Object Matte instance (its Input Key is kept current like Roto Brush's; it segments on
|
||||
/// demand while rendering).
|
||||
pub(crate) fn is_object_matte(g: &PropGroup) -> bool {
|
||||
matches!(&g.kind, GroupKind::Effect { effect } if effect == effectcraft_effects::object_matte::ID)
|
||||
}
|
||||
|
||||
/// What an Object Matte's segmentation is made from besides its frames: the prompt and tracking
|
||||
/// parameters (static values), for queueing it after edits and guarding a Freeze.
|
||||
pub(crate) fn om_prompt(g: &PropGroup) -> String {
|
||||
let ps = params_static(g);
|
||||
let mut keys: Vec<&String> = ps.values.keys().filter(|k| ["objectPoint", "useBox", "box", "objectTracking/"].iter().any(|p| k.starts_with(p))).collect();
|
||||
keys.sort();
|
||||
keys.iter().map(|k| format!("{k}={:?};", ps.values.get(*k))).collect()
|
||||
}
|
||||
|
||||
/// The job-relevant guard of an instance: its strokes (Roto Brush) or prompt (Object Matte).
|
||||
fn guard_of(g: &PropGroup) -> String {
|
||||
if is_object_matte(g) { om_prompt(g) } else { str_of(g, fx::STROKES) }
|
||||
}
|
||||
|
||||
fn str_of(g: &PropGroup, m: &str) -> String {
|
||||
match g.get(m).map(|p| &p.value) {
|
||||
Some(Value::Str(s)) => s.clone(),
|
||||
@@ -188,8 +221,9 @@ pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
|
||||
/// After an edit: refresh Input Keys; frozen mattes made from other frames are dropped.
|
||||
/// Returns the instances whose segmentation changed (to propagate again).
|
||||
/// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from
|
||||
/// other frames are dropped. Returns the instances whose segmentation changed (to propagate
|
||||
/// again): new frames, strokes (Roto Brush) or prompt (Object Matte).
|
||||
pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerId, Uid)> {
|
||||
let mut todo = vec![];
|
||||
let mut set = vec![];
|
||||
@@ -197,13 +231,13 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI
|
||||
let ItemKind::Comp(c) = &it.kind else { continue };
|
||||
for l in &c.layers {
|
||||
let Some(fxg) = l.effects() else { continue };
|
||||
for g in fxg.groups().filter(|g| is_roto(g)) {
|
||||
for g in fxg.groups().filter(|g| is_roto(g) || is_object_matte(g)) {
|
||||
let key = input_key(after, *cid, l, g.uid);
|
||||
let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid));
|
||||
if str_of(g, INPUT_KEY) != key {
|
||||
set.push((*cid, l.id, g.uid, key));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if old.is_none_or(|o| str_of(o, fx::STROKES) != str_of(g, fx::STROKES)) {
|
||||
} else if old.is_none_or(|o| guard_of(o) != guard_of(g)) {
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
}
|
||||
}
|
||||
@@ -219,7 +253,11 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI
|
||||
}
|
||||
}
|
||||
todo.retain(|(c, l, u)| {
|
||||
after.comp(*c).and_then(|c| c.layer(*l)).and_then(|l| l.props.find_group(*u)).is_some_and(|g| !fx::data(¶ms_static(g)).is_empty())
|
||||
after
|
||||
.comp(*c)
|
||||
.and_then(|c| c.layer(*l))
|
||||
.and_then(|l| l.props.find_group(*u))
|
||||
.is_some_and(|g| is_object_matte(g) || !fx::data(¶ms_static(g)).is_empty())
|
||||
});
|
||||
todo
|
||||
}
|
||||
@@ -274,6 +312,7 @@ struct Work {
|
||||
fps: f64,
|
||||
frames: Vec<i64>,
|
||||
task: RotoTask,
|
||||
object_matte: bool,
|
||||
}
|
||||
|
||||
/// Renders the effect's input frames for a worker, keeping the last few. With a browser job
|
||||
@@ -390,10 +429,13 @@ async fn run_work(w: Work, shared: &RotoShared) {
|
||||
let mut s = lock(&shared.state);
|
||||
s.task = Some(w.task);
|
||||
s.total = w.frames.len() as u64;
|
||||
s.object_matte = w.object_matte;
|
||||
}
|
||||
let cancel = || shared.cancel.load(Ordering::Relaxed);
|
||||
let chain = fx::Chain::new(&w.params, w.size, w.fps, 1.0);
|
||||
let mut frozen = FrozenCache { key: fx::frozen_key(&w.params, w.size, w.fps), ..Default::default() };
|
||||
let model = fx::installed_model();
|
||||
let key = if w.object_matte { om::frozen_key(&w.params, w.size, w.fps, model.as_deref()) } else { fx::frozen_key(&w.params, w.size, w.fps) };
|
||||
let mut frozen = FrozenCache { key, ..Default::default() };
|
||||
for (k, f) in w.frames.iter().enumerate() {
|
||||
if cancel() {
|
||||
let mut s = lock(&shared.state);
|
||||
@@ -404,9 +446,21 @@ async fn run_work(w: Work, shared: &RotoShared) {
|
||||
// The frame and its neighbours (what a step reads), on the GPU.
|
||||
src.prefetch(&[*f, f - 1, f + 1]).await;
|
||||
let mut get = |g: i64| src.get(g);
|
||||
let ok = match w.task {
|
||||
RotoTask::Propagate => chain.ensure(*f, &mut get, &cancel).is_some(),
|
||||
RotoTask::Freeze => match fx::frame_matte(&w.params, w.size, w.fps, *f, &mut get, &cancel) {
|
||||
let ok = match (w.task, w.object_matte) {
|
||||
(RotoTask::Propagate, true) => om::ensure(&w.params, w.size, w.fps, *f, model.clone(), &mut get, &cancel).is_some(),
|
||||
(RotoTask::Freeze, true) => {
|
||||
let img = get(*f);
|
||||
match img.map(|img| (om::frame_matte(&w.params, w.size, w.fps, *f, 1.0, &img, model.clone(), &mut get, &cancel), img)) {
|
||||
Some((om::FrameMatte::Alpha(a), img)) => {
|
||||
frozen.size = [img.width as usize, img.height as usize];
|
||||
frozen.frames.insert(*f, fx::freeze_frame(&a, &[]));
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(RotoTask::Propagate, false) => chain.ensure(*f, &mut get, &cancel).is_some(),
|
||||
(RotoTask::Freeze, false) => match fx::frame_matte(&w.params, w.size, w.fps, *f, &mut get, &cancel) {
|
||||
Some((a, b)) => {
|
||||
if let Some(img) = src.get(*f) {
|
||||
frozen.size = [img.width as usize, img.height as usize];
|
||||
@@ -461,12 +515,15 @@ impl Session {
|
||||
self.roto_job.as_ref().map(|j| j.progress()).or_else(|| {
|
||||
self.offloaded_roto().map(|(j, task)| {
|
||||
let p = &j.progress;
|
||||
let object_matte =
|
||||
self.project.comp(j.comp).and_then(|c| c.layer(j.layer)).and_then(|l| l.props.find_group(j.uid)).is_some_and(is_object_matte);
|
||||
RotoProgress {
|
||||
task: Some(task),
|
||||
done: p.done,
|
||||
total: p.total,
|
||||
elapsed: p.elapsed,
|
||||
fps: crate::offload::rate(p.done, p.elapsed),
|
||||
object_matte,
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
@@ -478,7 +535,8 @@ impl Session {
|
||||
self.roto_job.as_ref().map(|j| (j.comp, j.layer, j.effect, j.task)).or_else(|| self.offloaded_roto().map(|(j, task)| (j.comp, j.layer, j.uid, task)))
|
||||
}
|
||||
|
||||
/// The segmentation chain a propagation of `effect` computes (its frames' cache keys).
|
||||
/// The segmentation chain a propagation of Roto Brush `effect` computes (its frames' cache
|
||||
/// keys).
|
||||
pub fn roto_chain(&self, comp: ItemId, layer: LayerId, effect: Uid) -> Option<fx::Chain> {
|
||||
let c = self.project.comp(comp)?;
|
||||
let l = c.layer(layer)?;
|
||||
@@ -489,6 +547,27 @@ impl Session {
|
||||
Some(fx::Chain::new(¶ms, layer_size(&self.project, c, l), c.frame_rate.as_f64(), 1.0))
|
||||
}
|
||||
|
||||
/// The cache keys of the segmentations a propagation of `effect` (Roto Brush or Object
|
||||
/// Matte) computes, by layer frame.
|
||||
pub fn roto_keys(&self, comp: ItemId, layer: LayerId, effect: Uid) -> Option<Vec<(i64, u64)>> {
|
||||
if let Some(ch) = self.roto_chain(comp, layer, effect) {
|
||||
return Some(ch.keys.into_iter().collect());
|
||||
}
|
||||
let c = self.project.comp(comp)?;
|
||||
let l = c.layer(layer)?;
|
||||
let g = l.effects()?.groups().find(|g| g.uid == effect && is_object_matte(g))?;
|
||||
let params = self.om_params(comp, l, g)?;
|
||||
let frames = om::job_frames(¶ms, frame_limits(c, l));
|
||||
Some(om::frame_keys(¶ms, layer_size(&self.project, c, l), c.frame_rate.as_f64(), &frames, fx::installed_model()))
|
||||
}
|
||||
|
||||
/// An Object Matte's parameters at its reference frame (what its jobs segment with).
|
||||
fn om_params(&self, comp: ItemId, l: &Layer, g: &PropGroup) -> Option<Params> {
|
||||
let c = self.project.comp(comp)?;
|
||||
let t = comp_time_of(c, l, om::reference_frame(¶ms_static(g)));
|
||||
Some(params_at(&self.project, comp, l, g, t, self.expr.as_deref()))
|
||||
}
|
||||
|
||||
pub fn stop_roto(&mut self) -> bool {
|
||||
if self.cancel_offloaded(JobKind::RotoFreeze) || self.cancel_offloaded(JobKind::RotoPropagate) {
|
||||
return true;
|
||||
@@ -522,17 +601,36 @@ impl Session {
|
||||
let l = c.layer(layer).ok_or("no layer")?;
|
||||
let fxg = l.effects().ok_or("the layer has no effects")?;
|
||||
let index = fxg.groups().position(|g| g.uid == effect).ok_or("no such effect")?;
|
||||
let g = fxg.groups().nth(index).filter(|g| is_roto(g)).ok_or("not a Roto Brush & Refine Edge effect")?;
|
||||
let g = fxg.groups().nth(index).filter(|g| is_roto(g) || is_object_matte(g)).ok_or("not a Roto Brush & Refine Edge or Object Matte effect")?;
|
||||
let object_matte = is_object_matte(g);
|
||||
let size = layer_size(&self.project, c, l);
|
||||
let fps = c.frame_rate.as_f64();
|
||||
let pstat = params_static(g);
|
||||
let d = fx::data(&pstat);
|
||||
if d.is_empty() {
|
||||
return Err("draw a foreground stroke with the Roto Brush tool first".into());
|
||||
}
|
||||
let t = comp_time_of(c, l, d.base.unwrap_or(0));
|
||||
let params = params_at(&self.project, comp, l, g, t, self.expr.as_deref());
|
||||
let frames = job_frames(&d, if task == RotoTask::Freeze { Direction::Both } else { dir });
|
||||
let (params, frames) = if object_matte {
|
||||
let params = self.om_params(comp, l, g).ok_or("no composition")?;
|
||||
let base = om::reference_frame(¶ms);
|
||||
if om::roto_data(¶ms, size, base, fx::installed_model().is_some()).is_none() {
|
||||
return Err("set the object first: click it with the Object Matte tool (its point is off the layer or outside its box)".into());
|
||||
}
|
||||
let all = om::job_frames(¶ms, frame_limits(c, l));
|
||||
if all.is_empty() {
|
||||
return Err(format!("the reference frame {base} is outside the layer"));
|
||||
}
|
||||
// Forward / backward from the reference frame, as for a Roto Brush.
|
||||
let frames = all
|
||||
.into_iter()
|
||||
.filter(|f| task == RotoTask::Freeze || dir == Direction::Both || *f == base || (*f > base) == (dir == Direction::Forward))
|
||||
.collect();
|
||||
(params, frames)
|
||||
} else {
|
||||
let pstat = params_static(g);
|
||||
let d = fx::data(&pstat);
|
||||
if d.is_empty() {
|
||||
return Err("draw a foreground stroke with the Roto Brush tool first".into());
|
||||
}
|
||||
let t = comp_time_of(c, l, d.base.unwrap_or(0));
|
||||
let params = params_at(&self.project, comp, l, g, t, self.expr.as_deref());
|
||||
(params, job_frames(&d, if task == RotoTask::Freeze { Direction::Both } else { dir }))
|
||||
};
|
||||
let n = frames.len();
|
||||
let work = Work {
|
||||
project: self.project.clone(),
|
||||
@@ -547,8 +645,9 @@ impl Session {
|
||||
fps,
|
||||
frames,
|
||||
task,
|
||||
object_matte,
|
||||
};
|
||||
let strokes = str_of(g, fx::STROKES);
|
||||
let strokes = guard_of(g);
|
||||
if !wait && self.offloads() {
|
||||
drop(work);
|
||||
self.offload_analysis(match task {
|
||||
@@ -559,6 +658,13 @@ impl Session {
|
||||
}
|
||||
let wait = wait || cfg!(target_arch = "wasm32");
|
||||
let shared = Arc::new(RotoShared::default());
|
||||
{
|
||||
// Known before the worker starts (the progress shows at once).
|
||||
let mut st = lock(&shared.state);
|
||||
st.task = Some(task);
|
||||
st.total = n as u64;
|
||||
st.object_matte = object_matte;
|
||||
}
|
||||
let thread = if wait {
|
||||
crate::offload::run_or_queue({
|
||||
let sh = shared.clone();
|
||||
@@ -574,7 +680,7 @@ impl Session {
|
||||
.map_err(|e| e.to_string())?,
|
||||
)
|
||||
};
|
||||
self.roto_job = Some(RotoJob { shared, thread, comp, layer, effect, task, strokes });
|
||||
self.roto_job = Some(RotoJob { shared, thread, comp, layer, effect, task, strokes, object_matte });
|
||||
self.events.push(Event::ProjectChanged { revision: self.revision });
|
||||
self.poll_roto_job();
|
||||
Ok(n)
|
||||
@@ -591,40 +697,43 @@ impl Session {
|
||||
let _ = t.join();
|
||||
}
|
||||
let st = job.progress();
|
||||
let name = if job.object_matte { "Object Matte" } else { "Roto Brush" };
|
||||
if let Some(e) = &st.error {
|
||||
self.events.push(Event::Toast { message: format!("Roto Brush: {e}"), error: true });
|
||||
self.events.push(Event::Toast { message: format!("{name}: {e}"), error: true });
|
||||
self.bump();
|
||||
return true;
|
||||
}
|
||||
if st.cancelled {
|
||||
self.events.push(Event::Toast { message: "Roto Brush: stopped".into(), error: false });
|
||||
self.events.push(Event::Toast { message: format!("{name}: stopped"), error: false });
|
||||
self.bump();
|
||||
return true;
|
||||
}
|
||||
match job.task {
|
||||
RotoTask::Propagate => {
|
||||
self.events.push(Event::Toast { message: format!("Roto Brush: propagated {} frame(s) in {:.1} s", st.done, st.elapsed), error: false });
|
||||
let verb = if job.object_matte { "tracked" } else { "propagated" };
|
||||
self.events.push(Event::Toast { message: format!("{name}: {verb} {} frame(s) in {:.1} s", st.done, st.elapsed), error: false });
|
||||
// Rendered frames depend on the cache: redraw.
|
||||
self.bump();
|
||||
}
|
||||
RotoTask::Freeze => {
|
||||
let Some(fc) = lock(&job.shared.frozen).take() else { return true };
|
||||
let (cid, lid, uid, strokes) = (job.comp, job.layer, job.effect, job.strokes.clone());
|
||||
let what = if job.object_matte { "prompt" } else { "strokes" };
|
||||
let r = self.edit("Freeze", None, |p, _| {
|
||||
let g = p
|
||||
.comp_mut(cid)
|
||||
.and_then(|c| c.layer_mut(lid))
|
||||
.and_then(|l| l.props.find_group_mut(uid))
|
||||
.ok_or_else(|| crate::EngineError::Other("the Roto Brush effect was removed".into()))?;
|
||||
if str_of(g, fx::STROKES) != strokes {
|
||||
return Err(crate::EngineError::Other("the strokes changed while freezing".into()));
|
||||
.ok_or_else(|| crate::EngineError::Other(format!("the {name} effect was removed")))?;
|
||||
if guard_of(g) != strokes {
|
||||
return Err(crate::EngineError::Other(format!("the {what} changed while freezing")));
|
||||
}
|
||||
set_str(g, FROZEN, fc.to_json());
|
||||
Ok(())
|
||||
});
|
||||
let msg = match r {
|
||||
Ok(()) => format!("Roto Brush: froze {} frame(s) in {:.1} s", fc.frames.len(), st.elapsed),
|
||||
Err(e) => format!("Roto Brush: {e}"),
|
||||
Ok(()) => format!("{name}: froze {} frame(s) in {:.1} s", fc.frames.len(), st.elapsed),
|
||||
Err(e) => format!("{name}: {e}"),
|
||||
};
|
||||
self.events.push(Event::Toast { message: msg, error: false });
|
||||
}
|
||||
@@ -654,6 +763,12 @@ impl Session {
|
||||
let Some(c) = self.project.comp(comp) else { return out };
|
||||
let Some(l) = c.layer(layer) else { return out };
|
||||
let Some(g) = l.props.find_group(effect) else { return out };
|
||||
if is_object_matte(g) {
|
||||
for (f, k) in self.roto_keys(comp, layer, effect).unwrap_or_default() {
|
||||
out.insert(f, fx::cached(k, 1.0).is_some());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let ps = params_static(g);
|
||||
let ch = fx::Chain::new(&ps, layer_size(&self.project, c, l), c.frame_rate.as_f64(), 1.0);
|
||||
for f in ch.keys.keys() {
|
||||
|
||||
@@ -87,7 +87,9 @@ fn add_configure_render() {
|
||||
assert_eq!(std::path::Path::new(q[0].last_output.as_deref().unwrap()), std::path::PathBuf::from(crate::tests_stubs::tmp_out("rq/out.mov")));
|
||||
assert_eq!(q[1].status, RenderStatus::Failed("boom".into()));
|
||||
assert_eq!(q[2].status.label(), "Unqueued");
|
||||
assert!(s.drain_events().iter().any(|e| matches!(e, Event::Toast { error: true, .. })));
|
||||
let events = s.drain_events();
|
||||
let toast = events.iter().find_map(|e| if let Event::Toast { message, error: true } = e { Some(message.as_str()) } else { None });
|
||||
assert_eq!(toast, Some("Render finished with 1 failed item(s): boom"), "the toast says why (#568)");
|
||||
// Reorder, duplicate, remove, undo.
|
||||
s.execute("renderQueue.move", json!({"item": b["item"], "to": 1})).unwrap();
|
||||
assert_eq!(s.project.render_queue[0].id, b["item"].as_u64().unwrap());
|
||||
@@ -114,6 +116,28 @@ fn persists_in_project_file() {
|
||||
assert!(effectcraft_project::Project::from_json(&old).unwrap().render_queue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_toast_names_the_first_reason() {
|
||||
struct Failing;
|
||||
impl Exporter for Failing {
|
||||
fn formats(&self) -> Vec<OutputFormat> {
|
||||
OutputFormat::ALL.to_vec()
|
||||
}
|
||||
fn export(&self, job: &ExportJob, _: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
|
||||
let name = std::path::Path::new(job.path).file_name().unwrap().to_string_lossy().into_owned();
|
||||
Err(format!("cannot write {name}"))
|
||||
}
|
||||
}
|
||||
let mut s = demo();
|
||||
s.exporter = Some(Arc::new(Failing));
|
||||
s.execute("renderQueue.add", json!({"format": "gif", "output": crate::tests_stubs::tmp_out("rq/first.gif")})).unwrap();
|
||||
s.execute("renderQueue.add", json!({"format": "gif", "output": crate::tests_stubs::tmp_out("rq/second.gif")})).unwrap();
|
||||
s.execute("renderQueue.render", json!({})).unwrap();
|
||||
let events = s.drain_events();
|
||||
let toast = events.iter().find_map(|e| if let Event::Toast { message, error: true } = e { Some(message.as_str()) } else { None });
|
||||
assert_eq!(toast, Some("Render finished with 2 failed item(s), first: cannot write first.gif"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_render_and_stop() {
|
||||
struct Slow;
|
||||
|
||||
@@ -132,6 +132,10 @@ impl Session {
|
||||
},
|
||||
};
|
||||
self.layer_cache.set_disk(Some((dc.clone(), footage_salt(&self.project))));
|
||||
// Roto Brush / Object Matte segmentations persist there too (held weakly: switching the
|
||||
// disk cache off drops it).
|
||||
let store: std::sync::Arc<dyn effectcraft_effects::roto::SegStore> = dc.clone();
|
||||
effectcraft_effects::roto::set_seg_store(Some(std::sync::Arc::downgrade(&store)));
|
||||
self.disk_cache = Some(dc);
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,8 @@ pub fn bindables(ui: &[UiCommand]) -> Vec<Bindable> {
|
||||
let key = binding_key(&e.command, &e.params);
|
||||
// A plain entry also gets its command's further default keys.
|
||||
let alt = if e.params.is_null() { crate::commands::find(&e.command).map_or(&[][..], |c| c.alt_shortcuts) } else { &[] };
|
||||
let defaults = e.shortcut.as_deref().into_iter().chain(alt.iter().copied()).filter_map(normalize).collect();
|
||||
let defaults =
|
||||
e.shortcut.as_deref().into_iter().chain(e.alt_shortcuts.iter().map(String::as_str)).chain(alt.iter().copied()).filter_map(normalize).collect();
|
||||
push(
|
||||
Bindable {
|
||||
key,
|
||||
@@ -150,6 +151,7 @@ pub fn normalize(s: &str) -> Option<String> {
|
||||
}
|
||||
let (mut ctrl, mut cmd, mut alt, mut shift) = (false, false, false, false);
|
||||
let mut key: Option<String> = None;
|
||||
let mut physical = false;
|
||||
// `Cmd++` / `+` name the plus key.
|
||||
let (head, plus) = match s.strip_suffix("++") {
|
||||
Some(h) => (h, true),
|
||||
@@ -176,6 +178,7 @@ pub fn normalize(s: &str) -> Option<String> {
|
||||
}
|
||||
for p in parts {
|
||||
match p.to_ascii_lowercase().as_str() {
|
||||
"physical" => physical = true,
|
||||
"cmd" | "command" | "meta" | "super" | "win" => cmd = true,
|
||||
"ctrl" | "control" => ctrl = true,
|
||||
"alt" | "opt" | "option" => alt = true,
|
||||
@@ -187,7 +190,7 @@ pub fn normalize(s: &str) -> Option<String> {
|
||||
key = Some("+".into());
|
||||
}
|
||||
let key = key?;
|
||||
let mut out = String::new();
|
||||
let mut out = if physical { "Physical+".to_string() } else { String::new() };
|
||||
for (on, m) in [(ctrl, "Ctrl+"), (cmd, "Cmd+"), (alt, "Alt+"), (shift, "Shift+")] {
|
||||
if on {
|
||||
out.push_str(m);
|
||||
|
||||
@@ -27,7 +27,7 @@ fn every_transition_preset_applies_and_transitions() {
|
||||
let list = s.execute("anim.builtinPresets", json!({"category": "Transitions"})).unwrap();
|
||||
let list = list.as_array().unwrap().clone();
|
||||
assert!(list.len() >= 20, "{}", list.len());
|
||||
assert_eq!(crate::animation_presets().len(), list.len());
|
||||
assert_eq!(crate::animation_presets().iter().filter(|(_, _, c)| c == "Transitions").count(), list.len());
|
||||
let start = 0.5;
|
||||
for p in &list {
|
||||
let id = p["id"].as_str().unwrap();
|
||||
@@ -72,3 +72,57 @@ fn transition_preset_by_name_and_bad_input() {
|
||||
let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
assert!(s.execute("anim.applyBuiltinPreset", json!({"layers": [cam], "preset": "clockReveal"})).is_err());
|
||||
}
|
||||
|
||||
/// Every preset's id and name are unique across the whole library (ids key the panel's
|
||||
/// automation ids), each sits in a known category, and Text ids don't clash with them.
|
||||
#[test]
|
||||
fn preset_catalogue_is_unique_and_categorised() {
|
||||
let all = crate::animation_presets();
|
||||
let known = ["Transitions", "Backgrounds"];
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for (id, name, cat) in &all {
|
||||
assert!(known.contains(&cat.as_str()), "{id}: unknown category {cat}");
|
||||
assert!(ids.insert(id.to_lowercase()), "duplicate id {id}");
|
||||
assert!(names.insert(name.to_lowercase()), "duplicate name {name}");
|
||||
}
|
||||
for (id, name) in crate::text_presets() {
|
||||
assert!(!ids.contains(&id.to_lowercase()) && !names.contains(&name.to_lowercase()), "text preset {id} clashes");
|
||||
}
|
||||
let n = |c: &str| all.iter().filter(|(_, _, k)| k == c).count();
|
||||
assert!(n("Backgrounds") >= 15 && n("Transitions") >= 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_background_preset_applies_and_undoes() {
|
||||
let (mut s, solid) = session();
|
||||
let list = s.execute("anim.builtinPresets", json!({"category": "Backgrounds"})).unwrap();
|
||||
let list = list.as_array().unwrap().clone();
|
||||
assert!(list.len() >= 15, "{}", list.len());
|
||||
for p in &list {
|
||||
let id = p["id"].as_str().unwrap();
|
||||
let r = s.execute("anim.applyBuiltinPreset", json!({"layers": [solid], "preset": id})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]), "{id}: every path and expression in the preset applies");
|
||||
let n = r["effects"].as_array().unwrap().len();
|
||||
assert!(n >= 1, "{id}");
|
||||
assert_eq!(s.active_comp().unwrap().layers[0].effects().unwrap().groups().count(), n, "{id}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let l = &s.active_comp().unwrap().layers[0];
|
||||
assert_eq!(l.effects().map_or(0, |fx| fx.groups().count()), 0, "{id}: undo removes the effects");
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_expressions_and_point_fractions() {
|
||||
let (mut s, solid) = session();
|
||||
s.execute("anim.applyBuiltinPreset", json!({"layers": [solid], "preset": "Spotlight Floor"})).unwrap();
|
||||
let fx = s.active_comp().unwrap().layers[0].effects().unwrap().groups().next().unwrap().clone();
|
||||
assert!(fx.prop("start").unwrap().has_expression());
|
||||
// A point written as a fraction of the layer: Sunrise-style presets keep their defaults at 160x90.
|
||||
s.execute("anim.applyBuiltinPreset", json!({"layers": [solid], "preset": "dawnSky"})).unwrap();
|
||||
let ramp = s.active_comp().unwrap().layers[0].effects().unwrap().groups().nth(2).unwrap().clone();
|
||||
assert_eq!(ramp.prop("end").unwrap().value, effectcraft_keyframe::Value::Vec2([80.0, 90.0]));
|
||||
assert_eq!(ramp.prop("startColor").unwrap().keys.len(), 2);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Effect Controls operations: copy/paste, duplicate, reorder, remove (Delete), reset, and the
|
||||
//! Edit menu routing to them when effects are selected, all with undo.
|
||||
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::{Layer, LayerId};
|
||||
use effectcraft_keyframe::{Ease, Interp, Value as KV};
|
||||
use effectcraft_project::{Layer, LayerId, PropGroup};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
@@ -32,6 +33,24 @@ fn select_effect(s: &mut Session, lid: u64, uid: u64) {
|
||||
s.state.selected_props = vec![(LayerId(lid), uid)];
|
||||
}
|
||||
|
||||
fn effect_group(s: &Session, lid: u64, uid: u64) -> PropGroup {
|
||||
layer(s, lid).effects().unwrap().groups().find(|g| g.uid == uid).unwrap().clone()
|
||||
}
|
||||
|
||||
fn animate_effect(s: &mut Session, lid: u64, uid: u64, path: &str, keys: &[(f64, f64)]) {
|
||||
let prop = effect_group(s, lid, uid).prop(path).unwrap().uid;
|
||||
for &(time, value) in keys {
|
||||
s.execute("prop.addKey", json!({"layer": lid, "prop": prop, "time": time, "timeBase": "comp", "value": value})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_layer_clock(s: &mut Session, lid: u64, start: f64, stretch: f64) {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let l = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap();
|
||||
l.start_time = Tick::from_seconds_f64(start);
|
||||
l.stretch = stretch;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_paste_effects_between_layers_with_undo() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
@@ -62,6 +81,233 @@ fn copy_paste_effects_between_layers_with_undo() {
|
||||
assert_eq!(fx_names(&s, a), vec!["Gaussian Blur"]);
|
||||
}
|
||||
|
||||
/// #989: copying an animated effect aligns its first key to the destination CTI.
|
||||
#[test]
|
||||
fn pasted_effect_keys_start_at_the_playhead() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
let uid = layer(&s, a).effects().unwrap().groups().next().unwrap().get("blurriness").unwrap().uid;
|
||||
for (time, value) in [(1.0, 10.0), (3.0, 30.0)] {
|
||||
s.execute("prop.addKey", json!({"layer": a, "prop": uid, "time": time, "value": value})).unwrap();
|
||||
}
|
||||
let source = layer(&s, a);
|
||||
select_effect(&mut s, a, blur);
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
s.execute("time.set", json!({"time": 5.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layers": [b]})).unwrap();
|
||||
let undo = s.history.undo.len();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
let pasted = layer(&s, b);
|
||||
let keys = &pasted.effects().unwrap().groups().next().unwrap().get("blurriness").unwrap().keys;
|
||||
assert_eq!(keys.iter().map(|k| pasted.comp_time(k.time).seconds()).collect::<Vec<_>>(), vec![5.0, 7.0]);
|
||||
assert_eq!(keys.iter().map(|k| k.value.as_f64()).collect::<Vec<_>>(), vec![10.0, 30.0]);
|
||||
assert_eq!(layer(&s, a), source, "copy and paste do not edit the source");
|
||||
assert_eq!(s.history.undo.len(), undo + 1, "the whole paste is one undo step");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(fx_names(&s, b).is_empty());
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(layer(&s, b), pasted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_effects_share_one_anchor_including_nested_parameters() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
let fractal = apply(&mut s, a, "Fractal");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(1.0, 10.0), (3.0, 30.0)]);
|
||||
animate_effect(&mut s, a, fractal, "mandelbrot/mandelbrotX", &[(2.0, 1.25), (4.0, 2.5)]);
|
||||
animate_effect(&mut s, a, fractal, "mandelbrot/mandelbrotY", &[(3.0, 0.5), (5.0, 2.0)]);
|
||||
let static_value = effect_group(&s, a, fractal).get("setChoice").unwrap().value.clone();
|
||||
s.state.selected_props = vec![(LayerId(a), blur), (LayerId(a), fractal)];
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
s.execute("time.set", json!({"time": 5.0})).unwrap();
|
||||
let reply = s.execute("effect.paste", json!({"layers": [b]})).unwrap();
|
||||
for (index, path, times) in
|
||||
[(0, "blurriness", vec![5.0, 7.0]), (1, "mandelbrot/mandelbrotX", vec![6.0, 8.0]), (1, "mandelbrot/mandelbrotY", vec![7.0, 9.0])]
|
||||
{
|
||||
let group = effect_group(&s, b, reply["effects"][index].as_u64().unwrap());
|
||||
assert_eq!(group.prop(path).unwrap().keys.iter().map(|k| k.time.seconds()).collect::<Vec<_>>(), times, "{path}");
|
||||
}
|
||||
let group = effect_group(&s, b, reply["effects"][1].as_u64().unwrap());
|
||||
assert_eq!(group.get("setChoice").unwrap().value, static_value, "unanimated controls stay unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_effects_preserve_comp_timing_and_eased_values_on_stretched_layers() {
|
||||
for (source_start, source_stretch) in [(2.0, 100.0), (1.0, 200.0), (8.0, -200.0)] {
|
||||
for (target_start, target_stretch) in [(0.0, 100.0), (3.0, 200.0), (8.0, -100.0)] {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
set_layer_clock(&mut s, a, source_start, source_stretch);
|
||||
set_layer_clock(&mut s, b, target_start, target_stretch);
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(3.0, 10.0), (5.0, 30.0)]);
|
||||
let uid = effect_group(&s, a, blur).get("blurriness").unwrap().uid;
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let pr = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(a)).unwrap().props.find_mut(uid).unwrap();
|
||||
for key in &mut pr.keys {
|
||||
key.in_interp = Interp::Bezier;
|
||||
key.out_interp = Interp::Bezier;
|
||||
key.in_ease = vec![Ease { speed: 7.0, influence: 0.25 }];
|
||||
key.out_ease = vec![Ease { speed: 3.0, influence: 0.6 }];
|
||||
key.label = 4;
|
||||
}
|
||||
let source = layer(&s, a);
|
||||
let source_pr = source.props.find(uid).unwrap();
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
s.execute("time.set", json!({"time": 5.0})).unwrap();
|
||||
let pasted = s.execute("effect.paste", json!({"layers": [b]})).unwrap()["effects"][0].as_u64().unwrap();
|
||||
let target = layer(&s, b);
|
||||
let target_group = target.effects().unwrap().groups().find(|g| g.uid == pasted).unwrap();
|
||||
let target_pr = target_group.get("blurriness").unwrap();
|
||||
let mut times: Vec<Tick> = target_pr.keys.iter().map(|k| target.comp_time(k.time)).collect();
|
||||
times.sort();
|
||||
assert_eq!(times, vec![Tick::from_seconds_f64(5.0), Tick::from_seconds_f64(7.0)]);
|
||||
for offset in [0.0, 0.25, 0.75, 1.5, 2.0] {
|
||||
let expected = source_pr.value_at(source.layer_time(Tick::from_seconds_f64(3.0 + offset))).as_f64();
|
||||
let actual = target_pr.value_at(target.layer_time(Tick::from_seconds_f64(5.0 + offset))).as_f64();
|
||||
assert!((expected - actual).abs() < 1e-8, "source {source_stretch} %, target {target_stretch} %, t={offset}: {expected} != {actual}");
|
||||
}
|
||||
assert!(target_pr.keys.iter().all(|k| k.label == 4));
|
||||
assert_eq!(layer(&s, a), source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_spatial_effect_keys_preserve_the_eased_path_on_reversed_layers() {
|
||||
for (source_stretch, target_stretch) in [(200.0, 100.0), (-200.0, 100.0), (100.0, -200.0)] {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
set_layer_clock(&mut s, a, if source_stretch < 0.0 { 8.0 } else { 1.0 }, source_stretch);
|
||||
set_layer_clock(&mut s, b, if target_stretch < 0.0 { 8.0 } else { 0.0 }, target_stretch);
|
||||
let ramp = apply(&mut s, a, "Gradient Ramp");
|
||||
let uid = effect_group(&s, a, ramp).get("start").unwrap().uid;
|
||||
for (time, value) in [(3.0, [50.0, 25.0]), (5.0, [180.0, 75.0])] {
|
||||
s.execute("prop.addKey", json!({"layer": a, "prop": uid, "time": time, "timeBase": "comp", "value": value})).unwrap();
|
||||
}
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let pr = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(a)).unwrap().props.find_mut(uid).unwrap();
|
||||
pr.spatial = true;
|
||||
for key in &mut pr.keys {
|
||||
key.in_interp = Interp::Bezier;
|
||||
key.out_interp = Interp::Bezier;
|
||||
key.in_ease = vec![Ease { speed: 15.0, influence: 0.25 }];
|
||||
key.out_ease = vec![Ease { speed: 30.0, influence: 0.6 }];
|
||||
key.spatial_auto = false;
|
||||
key.spatial_in = [-10.0, -20.0, 0.0];
|
||||
key.spatial_out = [20.0, 5.0, 0.0];
|
||||
}
|
||||
let source = layer(&s, a);
|
||||
let source_pr = source.props.find(uid).unwrap();
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": ramp})).unwrap();
|
||||
s.execute("time.set", json!({"time": 5.0})).unwrap();
|
||||
let pasted = s.execute("effect.paste", json!({"layers": [b]})).unwrap()["effects"][0].as_u64().unwrap();
|
||||
let target = layer(&s, b);
|
||||
let group = target.effects().unwrap().groups().find(|g| g.uid == pasted).unwrap();
|
||||
let target_pr = group.get("start").unwrap();
|
||||
for offset in [0.0, 0.25, 0.75, 1.5, 2.0] {
|
||||
let expected = source_pr.value_at(source.layer_time(Tick::from_seconds_f64(3.0 + offset))).components();
|
||||
let actual = target_pr.value_at(target.layer_time(Tick::from_seconds_f64(5.0 + offset))).components();
|
||||
assert_eq!(expected.len(), actual.len());
|
||||
assert!(expected.iter().zip(&actual).all(|(a, b)| (a - b).abs() < 0.05), "path at {offset}: {expected:?} != {actual:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_clipboard_is_a_snapshot_and_repeated_paste_uses_the_target_comps_cti() {
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
let original_comp = s.active_comp_id().unwrap();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(1.0, 10.0), (3.0, 30.0)]);
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
let clipboard = s.state.effect_clipboard.clone();
|
||||
// Changing the source after Copy must not change what the clipboard will paste.
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(4.0, 99.0)]);
|
||||
s.execute("time.set", json!({"time": 9.0})).unwrap();
|
||||
let destination = s.execute("comp.new", json!({"name": "Destination", "frameRate": 24, "duration": 10})).unwrap()["comp"].as_u64().unwrap();
|
||||
let b = s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("time.set", json!({"time": 4.0})).unwrap();
|
||||
s.open_comp(original_comp);
|
||||
for (cti, expected) in [(4.0, vec![4.0, 6.0]), (2.0, vec![2.0, 4.0])] {
|
||||
s.state.times.insert(effectcraft_project::ItemId(destination), Tick::from_seconds_f64(cti));
|
||||
let uid = s.execute("effect.paste", json!({"comp": destination, "layers": [b]})).unwrap()["effects"][0].as_u64().unwrap();
|
||||
let l = s.project.comp(effectcraft_project::ItemId(destination)).unwrap().layer(LayerId(b)).unwrap();
|
||||
let pr = l.effects().unwrap().groups().find(|g| g.uid == uid).unwrap().get("blurriness").unwrap();
|
||||
assert_eq!(pr.keys.iter().map(|k| l.comp_time(k.time).seconds()).collect::<Vec<_>>(), expected);
|
||||
assert_eq!(pr.keys.iter().map(|k| k.value.as_f64()).collect::<Vec<_>>(), vec![10.0, 30.0]);
|
||||
assert_eq!(s.state.effect_clipboard, clipboard);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_effect_paste_timing_leaves_every_target_and_history_unchanged() {
|
||||
for stretch in [0.0, f64::NAN, f64::INFINITY, 1e-300, 1e300] {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(1.0, 10.0), (3.0, 30.0)]);
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
set_layer_clock(&mut s, b, 0.0, stretch);
|
||||
s.execute("time.set", json!({"time": 5.0})).unwrap();
|
||||
let project = s.project.clone();
|
||||
let clipboard = s.state.effect_clipboard.clone();
|
||||
let undo = s.history.undo.len();
|
||||
// A is valid and comes first; failure on B must roll back A's new effect too.
|
||||
assert!(s.execute("effect.paste", json!({"layers": [a, b]})).is_err(), "{stretch}");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.project, &project));
|
||||
assert_eq!(s.state.effect_clipboard, clipboard);
|
||||
assert_eq!(s.history.undo.len(), undo);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_effect_copy_keeps_the_previous_clipboard() {
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(1.0, 10.0), (3.0, 30.0)]);
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
let clipboard = s.state.effect_clipboard.clone();
|
||||
set_layer_clock(&mut s, a, 0.0, 0.0);
|
||||
assert!(s.execute("effect.copy", json!({"layer": a, "effect": blur})).is_err());
|
||||
assert_eq!(s.state.effect_clipboard, clipboard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_paste_keeps_exact_ntsc_frame_offsets() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let frame = effectcraft_time::FrameRate::new(30000, 1001).frame_duration();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
let uid = effect_group(&s, a, blur).get("blurriness").unwrap().uid;
|
||||
let pr = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(a)).unwrap().props.find_mut(uid).unwrap();
|
||||
pr.keys = vec![
|
||||
effectcraft_keyframe::Keyframe::new(frame.mul_ratio(11, 1), KV::Scalar(10.0)),
|
||||
effectcraft_keyframe::Keyframe::new(frame.mul_ratio(43, 1), KV::Scalar(30.0)),
|
||||
];
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
let cti = frame.mul_ratio(71, 1);
|
||||
s.state.times.insert(cid, cti);
|
||||
let pasted = s.execute("effect.paste", json!({"layers": [b]})).unwrap()["effects"][0].as_u64().unwrap();
|
||||
let group = effect_group(&s, b, pasted);
|
||||
assert_eq!(group.get("blurriness").unwrap().keys.iter().map(|k| k.time).collect::<Vec<_>>(), vec![cti, cti + frame.mul_ratio(32, 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflowing_effect_paste_times_return_an_error_without_an_edit() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
animate_effect(&mut s, a, blur, "blurriness", &[(1.0, 10.0), (3.0, 30.0)]);
|
||||
s.execute("effect.copy", json!({"layer": a, "effect": blur})).unwrap();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
for cti in [Tick::MAX, Tick(i64::MAX)] {
|
||||
s.state.times.insert(cid, cti);
|
||||
let project = s.project.clone();
|
||||
let undo = s.history.undo.len();
|
||||
assert!(s.execute("effect.paste", json!({"layers": [b]})).is_err());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.project, &project));
|
||||
assert_eq!(s.history.undo.len(), undo);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_reorder_and_delete_selected_effect() {
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
@@ -147,6 +393,100 @@ fn reset_keys_animated_params_at_the_cti() {
|
||||
assert_eq!(pr.keys[1].value, KV::Scalar(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_swaps_only_its_colors_in_one_undo_step() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
let first = apply(&mut s, a, "Tint");
|
||||
let target = apply(&mut s, a, "Tint");
|
||||
let other = apply(&mut s, b, "Tint");
|
||||
for (path, value) in [("black", json!([1.0, 0.0, 0.0, 1.0])), ("white", json!([0.0, 0.25, 1.0, 1.0])), ("amount", json!(45.0))] {
|
||||
s.execute("prop.set", json!({"layer": a, "path": format!("effects/#2/{path}"), "value": value})).unwrap();
|
||||
}
|
||||
let before_a = layer(&s, a);
|
||||
let before_b = layer(&s, b);
|
||||
let n = s.history.undo.len();
|
||||
s.execute("effect.swapTintColors", json!({"layer": a, "effect": target})).unwrap();
|
||||
let swapped = layer(&s, a);
|
||||
let g = swapped.props.find_group(target).unwrap();
|
||||
assert_eq!(g.prop("black").unwrap().value, KV::Color([0.0, 0.25, 1.0, 1.0]));
|
||||
assert_eq!(g.prop("white").unwrap().value, KV::Color([1.0, 0.0, 0.0, 1.0]));
|
||||
assert_eq!(g.prop("amount").unwrap().value, KV::Scalar(45.0));
|
||||
assert_eq!(swapped.props.find_group(first), before_a.props.find_group(first));
|
||||
assert_eq!(layer(&s, b).props.find_group(other), before_b.props.find_group(other));
|
||||
assert_eq!(s.history.undo.len(), n + 1);
|
||||
assert!(s.undo());
|
||||
assert_eq!(layer(&s, a).props, before_a.props);
|
||||
assert!(s.redo());
|
||||
assert_eq!(layer(&s, a).props, swapped.props);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_swap_keys_animated_colors_at_layer_time() {
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
let target = apply(&mut s, a, "Tint");
|
||||
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/black", "value": [1.0, 0.0, 0.0, 1.0]})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/white", "value": [0.0, 0.0, 1.0, 1.0]})).unwrap();
|
||||
s.execute("prop.toggleAnimation", json!({"layer": a, "path": "effects/#1/black"})).unwrap();
|
||||
s.execute("time.set", json!({"time": 2.0})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/black", "value": [0.0, 1.0, 0.0, 1.0]})).unwrap();
|
||||
s.execute("layer.timeStretch", json!({"layers": [a], "percent": 200.0})).unwrap();
|
||||
// At comp time 2s the stretched layer is at 1s, between its unchanged 0s and 2s keys.
|
||||
let before = layer(&s, a);
|
||||
let g = before.props.find_group(target).unwrap();
|
||||
let lt = before.layer_time(s.time());
|
||||
let expected = g.prop("black").unwrap().value_at(lt);
|
||||
let keys = g.prop("black").unwrap().keys.clone();
|
||||
select_effect(&mut s, a, target);
|
||||
s.execute("effect.swapTintColors", json!({})).unwrap();
|
||||
let after = layer(&s, a);
|
||||
let g = after.props.find_group(target).unwrap();
|
||||
let black = g.prop("black").unwrap();
|
||||
assert_eq!(black.keys.len(), 3);
|
||||
assert_eq!(black.keys[0], keys[0]);
|
||||
assert_eq!(black.keys[2], keys[1]);
|
||||
assert_eq!(black.keys[1].time, lt);
|
||||
assert_eq!(black.keys[1].value, KV::Color([0.0, 0.0, 1.0, 1.0]));
|
||||
assert_eq!(g.prop("white").unwrap().value, expected);
|
||||
assert!(g.prop("white").unwrap().keys.is_empty());
|
||||
assert!(s.undo());
|
||||
assert_eq!(layer(&s, a).props, before.props);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_swap_rejects_invalid_targets_without_editing() {
|
||||
let mut empty = Session::default();
|
||||
assert!(empty.execute("effect.swapTintColors", json!({})).is_err());
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
let tint = apply(&mut s, a, "Tint");
|
||||
for params in [
|
||||
json!({"layer": a, "effect": blur}),
|
||||
json!({"layer": a, "effect": "missing"}),
|
||||
json!({"layer": a, "effect": []}),
|
||||
json!({"layer": a, "effect": 1.5}),
|
||||
json!({"layer": a, "effect": 0}),
|
||||
json!(false),
|
||||
] {
|
||||
let before = layer(&s, a);
|
||||
let n = s.history.undo.len();
|
||||
assert!(s.execute("effect.swapTintColors", params).is_err());
|
||||
assert_eq!(layer(&s, a).props, before.props);
|
||||
assert_eq!(s.history.undo.len(), n);
|
||||
}
|
||||
// A damaged project's colour parameter must also fail atomically.
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("Break Tint", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layer_mut(LayerId(a)).unwrap().props.find_group_mut(tint).unwrap().prop_mut("white").unwrap().value = KV::Scalar(1.0);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = layer(&s, a);
|
||||
let n = s.history.undo.len();
|
||||
assert!(s.execute("effect.swapTintColors", json!({"layer": a, "effect": tint})).is_err());
|
||||
assert_eq!(layer(&s, a).props, before.props);
|
||||
assert_eq!(s.history.undo.len(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_layers_clears_effect_clipboard() {
|
||||
let (mut s, a, b) = comp_with_two_solids();
|
||||
@@ -369,3 +709,35 @@ fn ocio_effect_warns_about_unsupported_config_transforms() {
|
||||
set(&mut s, "configFile", json!("/no/such/config.ocio"));
|
||||
assert!(warning(&mut s).as_str().is_some_and(|w| w.starts_with("Can't read the OCIO config")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_colour_labels_set_clear_undo_and_round_trip() {
|
||||
let (mut s, a, _) = comp_with_two_solids();
|
||||
let blur = apply(&mut s, a, "Gaussian Blur");
|
||||
let label = |s: &Session| layer(s, a).effects().unwrap().groups().next().unwrap().label;
|
||||
assert_eq!(label(&s), None);
|
||||
s.execute("effect.setLabel", json!({"layer": a, "effect": blur, "label": "Blue"})).unwrap();
|
||||
assert_eq!(label(&s), Some(effectcraft_color::Label::Blue));
|
||||
// Duplicates keep the label.
|
||||
s.execute("effect.duplicate", json!({"layer": a, "effect": blur})).unwrap();
|
||||
assert_eq!(layer(&s, a).effects().unwrap().groups().filter(|g| g.label.is_some()).count(), 2);
|
||||
s.undo();
|
||||
// It saves with the project and survives a reload.
|
||||
let json = s.project.to_file_json().unwrap();
|
||||
let back = effectcraft_project::Project::from_json(&json).unwrap();
|
||||
let l = back.comp(s.active_comp_id().unwrap()).unwrap().layer(LayerId(a)).unwrap().clone();
|
||||
assert_eq!(l.effects().unwrap().groups().next().unwrap().label, Some(effectcraft_color::Label::Blue));
|
||||
// None (or index 0) clears it; the change undoes.
|
||||
s.execute("effect.setLabel", json!({"layer": a, "effect": blur, "label": 0})).unwrap();
|
||||
assert_eq!(label(&s), None);
|
||||
s.undo();
|
||||
assert_eq!(label(&s), Some(effectcraft_color::Label::Blue));
|
||||
assert!(s.execute("effect.setLabel", json!({"layer": a, "effect": blur, "label": "Chartreuse"})).is_err());
|
||||
assert!(s.execute("effect.setLabel", json!({"layer": a, "effect": blur, "label": 99})).is_err());
|
||||
// A project saved before labels existed has none.
|
||||
let old = json.replace("\"label\":\"Blue\"", "\"x\":0").replace("\"label\": \"Blue\"", "\"x\": 0");
|
||||
assert_ne!(old, json, "the replace removed the effect's label");
|
||||
let old = effectcraft_project::Project::from_json(&old).unwrap();
|
||||
let l = old.comp(s.active_comp_id().unwrap()).unwrap().layer(LayerId(a)).unwrap().clone();
|
||||
assert_eq!(l.effects().unwrap().groups().next().unwrap().label, None);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ fn slip_moves_the_source_under_fixed_in_and_out() {
|
||||
let r = s.execute("layer.slip", json!({"layers": [id], "delta": 5.0})).unwrap();
|
||||
assert_eq!(get(&s).start_time.seconds(), 1.0);
|
||||
assert_eq!(r["slipped"][0]["delta"], json!(0.5));
|
||||
// Alt+PageUp / Alt+PageDown nudge by a frame.
|
||||
// Slip by a frame.
|
||||
s.execute("layer.slipBack", json!({"layers": [id]})).unwrap();
|
||||
assert!((get(&s).start_time.seconds() - (1.0 - 1.0 / 30.0)).abs() < 1e-9);
|
||||
s.execute("layer.slipForward", json!({"layers": [id]})).unwrap();
|
||||
@@ -75,8 +75,9 @@ fn slip_moves_the_source_under_fixed_in_and_out() {
|
||||
// Undo walks back through the slips.
|
||||
assert!(s.undo() && s.undo() && s.undo() && s.undo());
|
||||
assert_eq!(get(&s).start_time, Tick::ZERO);
|
||||
assert_eq!(crate::find_command("layer.slipBack").and_then(|c| c.shortcut), Some("Alt+PageUp"));
|
||||
assert_eq!(crate::find_command("layer.slipForward").and_then(|c| c.shortcut), Some("Alt+PageDown"));
|
||||
// Alt+PageUp / Alt+PageDown move the layer; the one-frame slips have no default key.
|
||||
assert_eq!(crate::find_command("layer.slipBack").and_then(|c| c.shortcut), None);
|
||||
assert_eq!(crate::find_command("layer.slipForward").and_then(|c| c.shortcut), None);
|
||||
// Layers without a source duration can't slip.
|
||||
s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
|
||||
assert!(s.execute("layer.slip", json!({"delta": 0.5})).is_err());
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! File ▸ Import ▸ EffectCraft Project: another project merges into the open one with fresh ids,
|
||||
//! its references intact, in one undo step.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, LayerSource, Project};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn out_dir(name: &str) -> std::path::PathBuf {
|
||||
let d = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out").join(name);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Every item, layer and property uid of `p` (they share one counter).
|
||||
fn all_ids(p: &Project) -> Vec<u64> {
|
||||
let mut v = vec![];
|
||||
for (id, it) in &p.items {
|
||||
v.push(id.0);
|
||||
if let ItemKind::Comp(c) = &it.kind {
|
||||
for l in &c.layers {
|
||||
v.push(l.id.0);
|
||||
fn uids(g: &effectcraft_project::PropGroup, v: &mut Vec<u64>) {
|
||||
v.push(g.uid);
|
||||
for c in &g.children {
|
||||
match c {
|
||||
effectcraft_project::Node::Prop(p) => v.push(p.uid),
|
||||
effectcraft_project::Node::Group(g) => uids(g, v),
|
||||
}
|
||||
}
|
||||
}
|
||||
uids(&l.props, &mut v);
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// A project with "Main" nesting "Inner" under a parented null, a data file next to it by a
|
||||
/// relative path and a footage file that's gone. Saved as `<dir>/Library Card.ecproj`.
|
||||
fn source_project(dir: &std::path::Path) -> String {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Inner", "width": 64, "height": 64, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let inner = s.active_comp_id().unwrap();
|
||||
s.execute("layer.newSolid", json!({"name": "Fill", "color": "#ff0000"})).unwrap();
|
||||
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 64, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let main = s.active_comp_id().unwrap();
|
||||
let nest = s.execute("layer.addItem", json!({"comp": main.0, "item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap();
|
||||
let rig = s.execute("layer.newNull", json!({"name": "Rig"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setParent", json!({"layers": [nest], "parent": rig})).unwrap();
|
||||
std::fs::write(dir.join("data.json"), b"{\"v\": 1}").unwrap();
|
||||
let p = std::sync::Arc::make_mut(&mut s.project);
|
||||
p.add_item("data.json", Default::default(), None, ItemKind::Footage(Footage { path: "data.json".into(), kind: FootageKind::Data, ..Default::default() }));
|
||||
p.add_item(
|
||||
"gone.mov",
|
||||
Default::default(),
|
||||
None,
|
||||
ItemKind::Footage(Footage { path: "/offline/gone.mov".into(), kind: FootageKind::Video, ..Default::default() }),
|
||||
);
|
||||
let path = dir.join("Library Card.ecproj").to_string_lossy().to_string();
|
||||
s.execute("file.saveAs", json!({"path": path})).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_merges_with_fresh_ids_and_one_undo() {
|
||||
let dir = out_dir("import-project");
|
||||
let path = source_project(&dir);
|
||||
|
||||
let mut t = Session::default();
|
||||
t.execute("comp.new", json!({"name": "Show", "width": 64, "height": 64, "frameRate": 30, "duration": 2})).unwrap();
|
||||
t.execute("layer.newSolid", json!({"name": "Back", "color": "#00ff00"})).unwrap();
|
||||
let before = t.project.items.len();
|
||||
let before_ids: HashSet<u64> = all_ids(&t.project).into_iter().collect();
|
||||
|
||||
let r = t.execute("file.importProject", json!({"path": path})).unwrap();
|
||||
let folder = ItemId(r["folder"].as_u64().unwrap());
|
||||
assert_eq!(t.project.item(folder).unwrap().name, "Library Card.ecproj");
|
||||
// Inner, Main, the Solids folder and its solid, two footage items, and the new folder.
|
||||
assert_eq!(t.project.items.len(), before + 7);
|
||||
let imported: Vec<ItemId> = r["items"].as_array().unwrap().iter().map(|v| ItemId(v.as_u64().unwrap())).collect();
|
||||
// Everything lands in the folder (the Solids folder keeps its solid).
|
||||
let top = |mut id: ItemId| {
|
||||
while let Some(up) = t.project.item(id).and_then(|i| i.parent).filter(|p| *p != folder) {
|
||||
id = up;
|
||||
}
|
||||
t.project.item(id).and_then(|i| i.parent)
|
||||
};
|
||||
assert!(imported.iter().all(|id| top(*id) == Some(folder)), "everything lands in the folder");
|
||||
|
||||
// No id is taken twice, and none of the open project's ids moved.
|
||||
let ids = all_ids(&t.project);
|
||||
let unique: HashSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!(ids.len(), unique.len(), "ids collide");
|
||||
assert!(before_ids.is_subset(&unique));
|
||||
assert!(t.project.next_id > *ids.iter().max().unwrap());
|
||||
|
||||
// References follow the new ids: Main nests the imported Inner, under the imported null.
|
||||
let main = ItemId(r["primaryComp"].as_u64().unwrap());
|
||||
assert_eq!(t.project.item(main).unwrap().name, "Main");
|
||||
assert_eq!(r["rootComps"], json!([main.0]));
|
||||
let comp = t.project.comp(main).unwrap();
|
||||
let nest = comp.layers.iter().find(|l| matches!(l.source, LayerSource::Comp { .. })).unwrap();
|
||||
let LayerSource::Comp { item } = nest.source else { panic!("a precomp layer") };
|
||||
assert_eq!(t.project.item(item).unwrap().name, "Inner");
|
||||
assert!(imported.contains(&item));
|
||||
let parent = nest.parent.unwrap();
|
||||
assert_eq!(comp.layer(parent).unwrap().name, "Rig");
|
||||
|
||||
// A relative footage path resolves next to the imported project; a missing one is reported.
|
||||
let data = t.project.items.values().find(|i| i.name == "data.json").unwrap();
|
||||
let ItemKind::Footage(f) = &data.kind else { panic!("footage") };
|
||||
assert_eq!(std::path::Path::new(&f.path), dir.join("data.json"));
|
||||
assert_eq!(r["missingMedia"], json!(["/offline/gone.mov"]));
|
||||
|
||||
// One undo step removes all of it; redo brings it back.
|
||||
t.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(t.project.items.len(), before);
|
||||
t.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(t.project.items.len(), before + 7);
|
||||
|
||||
// Importing again keeps the copies apart, and File ▸ Import routes .ecproj here.
|
||||
let r2 = t.execute("file.import", json!({"paths": [path]})).unwrap();
|
||||
let again = &r2["projects"][0];
|
||||
assert_ne!(again["primaryComp"], r["primaryComp"]);
|
||||
assert!(r2["items"].as_array().unwrap().is_empty(), "a project is not footage");
|
||||
let ids = all_ids(&t.project);
|
||||
assert_eq!(ids.len(), ids.iter().copied().collect::<HashSet<_>>().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_rejects_bad_files_and_leaves_the_project() {
|
||||
let dir = out_dir("import-project-bad");
|
||||
let mut t = Session::default();
|
||||
t.execute("comp.new", json!({"name": "Show", "width": 64, "height": 64, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let before = t.project.items.len();
|
||||
|
||||
std::fs::write(dir.join("junk.ecproj"), b"not a project").unwrap();
|
||||
assert!(t.execute("file.importProject", json!({"path": dir.join("junk.ecproj").to_string_lossy()})).is_err());
|
||||
assert!(t.execute("file.importProject", json!({"path": dir.join("absent.ecproj").to_string_lossy()})).is_err());
|
||||
|
||||
// Regression: an id at the top of the range saturated instead of overflowing (opening and
|
||||
// importing must not panic), and the import refuses it.
|
||||
let mut p = Project::default();
|
||||
let id = p.add_item("Huge", Default::default(), None, ItemKind::Folder);
|
||||
let mut it = p.items.remove(&id).unwrap();
|
||||
it.id = ItemId(u64::MAX);
|
||||
p.items.insert(it.id, it);
|
||||
let huge = dir.join("huge.ecproj");
|
||||
std::fs::write(&huge, p.to_json()).unwrap();
|
||||
assert_eq!(Project::from_json(&p.to_json()).unwrap().next_id, u64::MAX);
|
||||
let e = t.execute("file.importProject", json!({"path": huge.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.to_string().contains("out of range"), "{e}");
|
||||
assert_eq!(t.project.items.len(), before);
|
||||
}
|
||||
@@ -111,3 +111,16 @@ fn attribute_edit_deduplicates_legacy_refs_and_drops_stale_refs_without_snapping
|
||||
let opacity = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.find(prop).unwrap();
|
||||
assert!(opacity.keys.iter().all(|k| k.out_interp == Interp::Linear));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_keys_keeps_the_selection_order() {
|
||||
let (mut s, first) = setup();
|
||||
let second = s.execute_checked("layer.newSolid", json!({"name": "Other", "color": "#fff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
for layer in [first, second] {
|
||||
add(&mut s, layer, "transform/opacity", 0, json!(0));
|
||||
}
|
||||
let (a, b) = (uid(&s, first, "transform/opacity"), uid(&s, second, "transform/opacity"));
|
||||
s.execute_checked("keys.select", json!({"keys": [{"layer": second, "prop": b, "time": 0}, {"layer": first, "prop": a, "time": 0}]})).unwrap();
|
||||
s.execute_checked("keys.move", json!({"delta": 2.0 / 30.0})).unwrap();
|
||||
assert_eq!(s.state.selected_keys, vec![key(second, b, 2), key(first, a, 2)], "not sorted by layer");
|
||||
}
|
||||
|
||||
@@ -661,7 +661,13 @@ fn dynamic_menus_and_window_viewer_labels() {
|
||||
assert_eq!(crate::menus::dynamic(&s, "history", &Default::default()).0.len(), s.history.undo.len());
|
||||
let a = solid(&mut s, "#ff0000");
|
||||
s.state.selected_layers = vec![LayerId(a)];
|
||||
let entry = |cmd: &str, panel: &str| crate::menus::MenuEntry { label: "x".into(), command: cmd.into(), params: json!({"panel": panel}), shortcut: None };
|
||||
let entry = |cmd: &str, panel: &str| crate::menus::MenuEntry {
|
||||
label: "x".into(),
|
||||
command: cmd.into(),
|
||||
params: json!({"panel": panel}),
|
||||
shortcut: None,
|
||||
alt_shortcuts: vec![],
|
||||
};
|
||||
assert_eq!(crate::menus::entry_label(&s, &entry("window.panel", "composition")), "Composition: Main");
|
||||
assert_eq!(crate::menus::entry_label(&s, &entry("window.panel", "timeline")), "Timeline: Main");
|
||||
assert!(crate::menus::entry_label(&s, &entry("window.panel", "layer")).starts_with("Layer: "));
|
||||
@@ -701,3 +707,44 @@ fn unsaved_project_renders_to_movies_or_home_not_the_working_directory() {
|
||||
assert_eq!(crate::render_queue::default_output_base(Some(home.clone())), Some(home.join("Movies")));
|
||||
assert_eq!(crate::render_queue::default_output_base(None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_with_precomp_swaps_every_use_of_the_item_for_one_new_comp() {
|
||||
let mut s = session();
|
||||
let main = s.active_comp_id().unwrap();
|
||||
let l = solid(&mut s, "#ff0000");
|
||||
s.execute("prop.set", json!({"layer": l, "path": "transform/position", "value": [10.0, 20.0]})).unwrap();
|
||||
let item = layer(&s, l).source.item().unwrap();
|
||||
let in_main = |s: &Session| s.project.comp(main).unwrap().layer(LayerId(l)).unwrap().clone();
|
||||
let props = in_main(&s).props;
|
||||
// A second comp uses the same solid for its whole 4 s (longer than Main).
|
||||
let other =
|
||||
ItemId(s.execute("comp.new", json!({"name": "Other", "width": 64, "height": 48, "duration": 4, "frameRate": 10})).unwrap()["comp"].as_u64().unwrap());
|
||||
s.execute("layer.addItem", json!({"comp": other.0, "item": item.0, "time": 0.0})).unwrap();
|
||||
let undo_before = s.history.undo.len();
|
||||
|
||||
let r = s.execute("file.replaceWithPrecomp", json!({"item": item.0})).unwrap();
|
||||
assert_eq!(r["replaced"], 2);
|
||||
let pre = ItemId(r["comp"].as_u64().unwrap());
|
||||
let pc = s.project.comp(pre).unwrap();
|
||||
assert_eq!((pc.width, pc.height), (32, 24));
|
||||
assert_eq!(pc.duration, Tick::from_seconds_f64(4.0));
|
||||
assert_eq!(pc.layers.len(), 1);
|
||||
assert_eq!(pc.layers[0].source.item(), Some(item));
|
||||
assert_eq!(s.project.item(pre).unwrap().name, format!("{} Comp", s.project.item(item).unwrap().name));
|
||||
for cid in [main, other] {
|
||||
let c = s.project.comp(cid).unwrap();
|
||||
assert!(c.layers.iter().all(|l| matches!(l.source, effectcraft_project::LayerSource::Comp { item } if item == pre)));
|
||||
}
|
||||
// The layer keeps its transform; the item stays in the project; one undo step.
|
||||
assert_eq!(in_main(&s).props, props);
|
||||
assert!(s.project.item(item).is_some());
|
||||
assert_eq!(s.history.undo.len(), undo_before + 1);
|
||||
s.undo();
|
||||
assert!(s.project.item(pre).is_none());
|
||||
assert_eq!(in_main(&s).source.item(), Some(item));
|
||||
|
||||
// Compositions and folders can't be precomposed this way.
|
||||
assert!(s.execute("file.replaceWithPrecomp", json!({"item": other.0})).is_err());
|
||||
assert!(s.execute("file.replaceWithPrecomp", json!({"item": 999_999})).is_err());
|
||||
}
|
||||
|
||||
@@ -181,3 +181,16 @@ fn nested_comp_markers_follow_the_precomp_layers_timing() {
|
||||
let solid = s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
assert!(s.execute("markers.nested", json!({"layer": solid})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_add_marker_without_selection_adds_comp_marker() {
|
||||
let (mut s, _) = setup();
|
||||
s.execute("time.set", json!({"time": 1.5})).unwrap();
|
||||
s.execute("edit.deselectAll", json!({})).unwrap();
|
||||
assert!(s.state.selected_layers.is_empty());
|
||||
s.execute("layer.addMarker", json!({"comment": "timeline marker"})).unwrap();
|
||||
let comp = s.active_comp().unwrap();
|
||||
assert_eq!(comp.markers.len(), 1);
|
||||
assert!((comp.markers[0].time.seconds() - 1.5).abs() < 1e-9);
|
||||
assert_eq!(comp.markers[0].comment, "timeline marker");
|
||||
}
|
||||
|
||||
@@ -52,6 +52,30 @@ fn layer_quality_sampling_frame_blending_and_undo() {
|
||||
assert!(s.execute("layer.quality", json!({"quality": "fancy"})).is_err());
|
||||
}
|
||||
|
||||
/// `layer.sampling {toggle}` (Alt+B, Alt+Shift+B): layers that all have the sampling already get
|
||||
/// the other one; without `toggle` it is only set.
|
||||
#[test]
|
||||
fn layer_sampling_toggles_when_every_layer_has_it() {
|
||||
let mut s = comp();
|
||||
let a = solid(&mut s, "#ff0000");
|
||||
let b = solid(&mut s, "#00ff00");
|
||||
let sampling = |s: &Session| [layer(s, a).switches.sampling, layer(s, b).switches.sampling];
|
||||
let bicubic = json!({"layers": [a, b], "sampling": "bicubic", "toggle": true});
|
||||
s.execute("layer.sampling", bicubic.clone()).unwrap();
|
||||
assert_eq!(sampling(&s), [Sampling::Bicubic; 2]);
|
||||
s.execute("layer.sampling", bicubic.clone()).unwrap();
|
||||
assert_eq!(sampling(&s), [Sampling::Bilinear; 2]);
|
||||
s.execute("layer.sampling", json!({"layers": [a, b], "sampling": "bilinear", "toggle": true})).unwrap();
|
||||
assert_eq!(sampling(&s), [Sampling::Bicubic; 2]);
|
||||
// Mixed layers all get the one asked for.
|
||||
s.execute("layer.sampling", json!({"layers": [a], "sampling": "bilinear"})).unwrap();
|
||||
s.execute("layer.sampling", bicubic).unwrap();
|
||||
assert_eq!(sampling(&s), [Sampling::Bicubic; 2]);
|
||||
// Without `toggle` it stays.
|
||||
s.execute("layer.sampling", json!({"layers": [a, b], "sampling": "bicubic"})).unwrap();
|
||||
assert_eq!(sampling(&s), [Sampling::Bicubic; 2]);
|
||||
}
|
||||
|
||||
/// `layer.setSwitch {others: true}` (Alt-click on an A/V feature): the layer stands alone, the
|
||||
/// other layers come back the next time.
|
||||
#[test]
|
||||
@@ -1069,6 +1093,57 @@ fn new_comp_from_selection_is_one_undo_step_with_the_dialog_options() {
|
||||
assert!(s.execute("file.newCompFromSelection", json!({"single": true, "dimensionsFrom": 2})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comps_made_from_the_same_footage_get_numbered_names_as_duplicate_does() {
|
||||
let mut s = Session::default();
|
||||
let add = |s: &mut Session, name: &str, kind: ItemKind| std::sync::Arc::make_mut(&mut s.project).add_item(name, effectcraft_color::Label::None, None, kind);
|
||||
let still = || {
|
||||
ItemKind::Footage(effectcraft_project::Footage {
|
||||
kind: effectcraft_project::FootageKind::Still,
|
||||
width: 200,
|
||||
height: 100,
|
||||
has_video: true,
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
let clip = add(&mut s, "clip.png", still());
|
||||
let other = add(&mut s, "other.png", still());
|
||||
let make = |s: &mut Session, sel: Vec<effectcraft_project::ItemId>, p: Value| -> Vec<String> {
|
||||
s.state.project_selection = sel;
|
||||
let r = s.execute("file.newCompFromSelection", p).unwrap();
|
||||
r["comps"].as_array().unwrap().iter().map(|c| s.project.item(effectcraft_project::ItemId(c.as_u64().unwrap())).unwrap().name.clone()).collect()
|
||||
};
|
||||
// The same footage again and again: "clip", "clip 2", "clip 3".
|
||||
assert_eq!(make(&mut s, vec![clip], json!({})), ["clip"]);
|
||||
assert_eq!(make(&mut s, vec![clip], json!({})), ["clip 2"]);
|
||||
assert_eq!(make(&mut s, vec![clip], json!({})), ["clip 3"]);
|
||||
// Several items at once (one comp each): every new comp has a name of its own.
|
||||
assert_eq!(make(&mut s, vec![clip, other, clip], json!({})), ["clip 4", "other", "clip 5"]);
|
||||
// One comp for all, named after the item it takes its settings from.
|
||||
assert_eq!(make(&mut s, vec![clip, other], json!({"single": true})), ["clip 6"]);
|
||||
assert_eq!(make(&mut s, vec![clip, other], json!({"single": true, "dimensionsFrom": 1})), ["other 2"]);
|
||||
// Undo removes the latest comp and frees its name for the next one.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.find_by_name("other 2").is_none());
|
||||
assert_eq!(make(&mut s, vec![other], json!({})), ["other 2"]);
|
||||
// A solid or extensionless footage still names its own first comp; the second is numbered.
|
||||
let red = add(&mut s, "Red Solid 1", ItemKind::Solid(effectcraft_project::Solid { color: [1.0, 0.0, 0.0], width: 100, height: 100, pixel_aspect: 1.0 }));
|
||||
assert_eq!(make(&mut s, vec![red], json!({})), ["Red Solid 1"]);
|
||||
assert_eq!(make(&mut s, vec![red], json!({})), ["Red Solid 2"]);
|
||||
// Duplicate numbers its copies the same way, from the same helper.
|
||||
let first = s.project.find_by_name("clip").unwrap().id;
|
||||
s.state.project_selection = vec![first];
|
||||
let r = s.execute("project.duplicate", json!({})).unwrap();
|
||||
assert_eq!(s.project.item(effectcraft_project::ItemId(r["items"][0].as_u64().unwrap())).unwrap().name, "clip 7");
|
||||
// A comp made from a comp doesn't take its source comp's name.
|
||||
assert_eq!(make(&mut s, vec![first], json!({})), ["clip 8"]);
|
||||
// Several comps at once are one undo step; undoing frees all their names.
|
||||
assert_eq!(make(&mut s, vec![clip, other], json!({})), ["clip 9", "other 3"]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.find_by_name("clip 9").is_none() && s.project.find_by_name("other 3").is_none());
|
||||
assert_eq!(make(&mut s, vec![other, clip], json!({})), ["other 3", "clip 9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_files_keep_their_format_warn_about_newer_versions_and_never_save_unreadable() {
|
||||
let mut s = comp();
|
||||
@@ -1464,3 +1539,69 @@ fn interpret_footage_loop_from_form_float() {
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Looped video footage lasts its loops: a 2 s clip looped 3 times is a 6 s layer, and a layer
|
||||
/// that ran to the clip's end is re-timed when the loop count changes (#1045).
|
||||
#[test]
|
||||
fn interpret_footage_loop_extends_video_layers() {
|
||||
let mut s = comp();
|
||||
let p = s.execute("file.importPlaceholder", json!({"name": "Clip", "width": 320, "height": 240, "duration": 2})).unwrap()["item"].as_u64().unwrap();
|
||||
let before = s.execute("layer.addItem", json!({"item": p})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.state.project_selection = vec![effectcraft_project::ItemId(p)];
|
||||
s.execute("file.interpretFootage", json!({"loop": 3.0})).unwrap();
|
||||
let after = s.execute("layer.addItem", json!({"item": p})).unwrap()["layer"].as_u64().unwrap();
|
||||
let out = |s: &Session, l: u64| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().out_point.seconds();
|
||||
assert_eq!(out(&s, after), 6.0, "a new layer plays every loop");
|
||||
assert_eq!(out(&s, before), 6.0, "a layer that ran to the clip's end still does");
|
||||
assert_eq!(s.project.item(effectcraft_project::ItemId(p)).unwrap().duration(), Some(Tick::from_seconds_f64(6.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentage_guides_follow_the_comp_size() {
|
||||
let mut s = comp();
|
||||
s.execute("view.addGuide", json!({"orientation": "vertical", "position": 25, "percent": true})).unwrap();
|
||||
s.execute("view.addPercentGuide", json!({"orientation": "horizontal"})).unwrap();
|
||||
s.execute("view.addGuide", json!({"orientation": "vertical", "position": 100})).unwrap();
|
||||
let c = s.active_comp().unwrap().clone();
|
||||
assert!(c.guides[0].percent && c.guides[1].percent && !c.guides[2].percent);
|
||||
assert_eq!((c.guides[0].px(c.width, c.height), c.guides[1].px(c.width, c.height)), (160.0, 180.0));
|
||||
// A comp resize moves percentage guides with it and leaves pixel guides alone.
|
||||
s.execute("comp.settings", json!({"width": 1280, "height": 720})).unwrap();
|
||||
let c = s.active_comp().unwrap().clone();
|
||||
assert_eq!((c.guides[0].px(c.width, c.height), c.guides[1].px(c.width, c.height), c.guides[2].px(c.width, c.height)), (320.0, 360.0, 100.0));
|
||||
// Dragging keeps the unit: the position arrives in comp pixels.
|
||||
s.execute("view.moveGuide", json!({"index": 0, "position": 640})).unwrap();
|
||||
assert_eq!(s.active_comp().unwrap().guides[0].position, 50.0);
|
||||
// Snapping sees the pixel position.
|
||||
let c = s.active_comp().unwrap().clone();
|
||||
assert!(c.guides.iter().any(|g| g.percent && g.vertical && g.px(c.width, c.height) == 640.0));
|
||||
// Converting keeps the guide where it is, and undoes in one step.
|
||||
s.execute("view.convertGuides", json!({"to": "pixels"})).unwrap();
|
||||
let g = s.active_comp().unwrap().guides.clone();
|
||||
assert!(g.iter().all(|g| !g.percent));
|
||||
assert_eq!((g[0].position, g[1].position), (640.0, 360.0));
|
||||
s.execute("view.convertGuides", json!({"to": "percent", "index": 2})).unwrap();
|
||||
assert_eq!(s.active_comp().unwrap().guides[2].position, 100.0 / 1280.0 * 100.0);
|
||||
s.undo();
|
||||
assert!(!s.active_comp().unwrap().guides[2].percent);
|
||||
assert!(s.execute("view.convertGuides", json!({"to": "furlongs"})).is_err());
|
||||
assert!(s.execute("view.convertGuides", json!({"index": 9})).is_err());
|
||||
// A crop keeps percentage guides where they were on the image.
|
||||
s.execute("view.convertGuides", json!({"to": "percent"})).unwrap();
|
||||
s.execute("view.setRegionOfInterest", json!({"rect": [320, 0, 640, 720]})).unwrap();
|
||||
s.execute("comp.cropToRegionOfInterest", json!({})).unwrap();
|
||||
let c = s.active_comp().unwrap();
|
||||
assert!((c.guides[0].px(c.width, c.height) - 320.0).abs() < 1e-9, "640 - 320 crop offset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_guides_load_as_pixel_guides_and_percent_round_trips() {
|
||||
let old: effectcraft_project::Guide = serde_json::from_str(r#"{"vertical":true,"position":12.5}"#).unwrap();
|
||||
assert!(!old.percent);
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("percent"), "pixel guides stay in the old shape");
|
||||
let g = effectcraft_project::Guide { vertical: false, position: 10.0, percent: true };
|
||||
let back: effectcraft_project::Guide = serde_json::from_str(&serde_json::to_string(&g).unwrap()).unwrap();
|
||||
assert_eq!(back, g);
|
||||
// A zero-sized comp never divides by zero.
|
||||
assert!(g.px(0, 0).is_finite());
|
||||
}
|
||||
|
||||
@@ -167,3 +167,47 @@ fn delete_removes_selected_groups_not_their_layer() {
|
||||
delete(&mut s);
|
||||
assert!(s.active_comp().unwrap().layer(LayerId(t)).is_none(), "a fixed group selected: the layer goes");
|
||||
}
|
||||
|
||||
/// #1061: text animators, masks and shape groups rename like effects, with undo; fixed groups and
|
||||
/// empty names are refused.
|
||||
#[test]
|
||||
fn text_animators_masks_and_shape_groups_rename() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "C", "width": 64, "height": 64, "duration": 1})).unwrap();
|
||||
let t = s.execute("layer.newText", json!({"text": "ABCD"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.addTextAnimator", json!({"layer": t, "properties": ["tracking"]})).unwrap();
|
||||
let sh = s.execute("layer.newShape", json!({"kind": "star"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.addMask", json!({"layer": sh, "shape": "ellipse"})).unwrap();
|
||||
let uid = |s: &Session, l: u64, path: &str| s.active_comp().unwrap().layer(LayerId(l)).unwrap().props.group(path).unwrap().groups().next().unwrap().uid;
|
||||
let name = |s: &Session, l: u64, u: u64| s.active_comp().unwrap().layer(LayerId(l)).unwrap().props.find_group(u).unwrap().name.clone();
|
||||
for (l, path, new) in [(t, "text/animators", "Wiggle In"), (sh, "masks", "Reveal"), (sh, "contents", "Star Body")] {
|
||||
let u = uid(&s, l, path);
|
||||
let old = name(&s, l, u);
|
||||
s.execute("prop.renameGroup", json!({"layer": l, "prop": u, "name": new})).unwrap();
|
||||
assert_eq!(name(&s, l, u), new, "{path}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(name(&s, l, u), old, "{path} undone");
|
||||
assert!(s.execute("prop.renameGroup", json!({"layer": l, "prop": u, "name": " "})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// `project.usedIn`: the Project panel's "used N times" and its ▾ list of comps, by name.
|
||||
#[test]
|
||||
fn used_in_counts_layers_across_comps() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Inner", "width": 64, "height": 64, "duration": 1})).unwrap();
|
||||
let inner = s.active_comp_id().unwrap();
|
||||
s.execute("comp.new", json!({"name": "Outer", "width": 64, "height": 64, "duration": 1})).unwrap();
|
||||
let outer = s.active_comp_id().unwrap();
|
||||
s.execute("layer.addItem", json!({"item": inner.0})).unwrap();
|
||||
s.execute("layer.addItem", json!({"item": inner.0})).unwrap();
|
||||
let r = s.execute("project.usedIn", json!({"item": "Inner"})).unwrap();
|
||||
assert_eq!(r["count"], 2);
|
||||
assert_eq!(r["comps"], json!([{"id": outer.0, "name": "Outer", "layers": 2}]));
|
||||
// Default: the selected item; an unused one is used 0 times.
|
||||
s.execute("project.select", json!({"items": [outer.0]})).unwrap();
|
||||
let r = s.execute("project.usedIn", json!({})).unwrap();
|
||||
assert_eq!((r["item"].as_u64(), r["count"].as_u64()), (Some(outer.0), Some(0)));
|
||||
assert_eq!(r["comps"], json!([]));
|
||||
assert!(s.execute("project.usedIn", json!({"item": "Nope"})).is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Quick Offset (#1012): `layer.quickOffset` and `keys.quickOffset` stagger layers and each layer's
|
||||
//! selected keys in selection order, onto subframes, as one undo step.
|
||||
|
||||
use effectcraft_keyframe::Interp;
|
||||
use effectcraft_project::{Layer, LayerId};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{KeyRef, Session};
|
||||
|
||||
/// One frame at 30 fps.
|
||||
const F: i64 = 8_467_200_000;
|
||||
|
||||
fn setup(n: usize) -> (Session, Vec<u64>) {
|
||||
let mut s = Session::default();
|
||||
s.execute_checked("comp.new", json!({"width": 64, "height": 64, "frameRate": 30, "duration": 10})).unwrap();
|
||||
let ids =
|
||||
(0..n).map(|i| s.execute_checked("layer.newSolid", json!({"name": format!("L{i}"), "color": "#fff"})).unwrap()["layer"].as_u64().unwrap()).collect();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
fn layer(s: &Session, id: u64) -> &Layer {
|
||||
s.active_comp().unwrap().layer(LayerId(id)).unwrap()
|
||||
}
|
||||
|
||||
/// (start, in, out) in ticks.
|
||||
fn timing(s: &Session, id: u64) -> (i64, i64, i64) {
|
||||
let l = layer(s, id);
|
||||
(l.start_time.0, l.in_point.0, l.out_point.0)
|
||||
}
|
||||
|
||||
/// Click the first, Ctrl/Cmd-click the rest.
|
||||
fn select(s: &mut Session, ids: &[u64]) {
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
s.execute_checked("layer.select", json!({"layers": [id], "add": i > 0})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn add_key(s: &mut Session, id: u64, path: &str, seconds: f64, value: Value) {
|
||||
s.execute_checked("prop.addKey", json!({"layer": id, "path": path, "time": seconds, "value": value})).unwrap();
|
||||
}
|
||||
|
||||
fn select_keys(s: &mut Session, keys: &[(u64, &str, f64)]) {
|
||||
for (i, (id, path, t)) in keys.iter().enumerate() {
|
||||
s.execute_checked("keys.select", json!({"keys": [{"layer": id, "path": path, "time": t}], "add": i > 0})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored key times (ticks) of a property.
|
||||
fn key_times(s: &Session, id: u64, path: &str) -> Vec<i64> {
|
||||
layer(s, id).props.prop(path).unwrap().keys.iter().map(|k| k.time.0).collect()
|
||||
}
|
||||
|
||||
fn uid(s: &Session, id: u64, path: &str) -> u64 {
|
||||
layer(s, id).props.prop(path).unwrap().uid
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_stagger_in_selection_order_onto_subframes_as_one_undo() {
|
||||
let (mut s, ids) = setup(4);
|
||||
let order = [ids[2], ids[0], ids[3], ids[1]];
|
||||
select(&mut s, &order);
|
||||
let before = s.project.clone();
|
||||
let reply = s.execute_checked("layer.quickOffset", json!({"delta": 1.0 / 30.0})).unwrap();
|
||||
// The first selected stays, the last moves the whole frame, the ones between a third each.
|
||||
for (i, id) in order.iter().enumerate() {
|
||||
let d = F * i as i64 / 3;
|
||||
let (st, inp, out) = timing(&s, *id);
|
||||
assert_eq!((st, inp, out - inp), (d, d, 10 * 30 * F), "layer {i} in selection order");
|
||||
}
|
||||
assert_eq!(reply["layers"].as_array().unwrap().len(), 4);
|
||||
// Negative drags mirror it.
|
||||
s.execute_checked("layer.quickOffset", json!({"delta": -2.0 / 30.0})).unwrap();
|
||||
for (i, id) in order.iter().enumerate() {
|
||||
assert_eq!(timing(&s, *id).0, -F * i as i64 / 3, "layer {i} after dragging back two frames");
|
||||
}
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.same_content(&before), "two offsets, two undo steps");
|
||||
s.execute_checked("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(timing(&s, order[3]).0, F);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_restarts_from_the_layers_before_it_and_is_one_undo_step() {
|
||||
let (mut s, ids) = setup(3);
|
||||
select(&mut s, &ids);
|
||||
// An offset layer, a stretched one and a reversed one move their whole timing; their keys
|
||||
// (in layer time) come along untouched.
|
||||
s.execute_checked("layer.timing", json!({"layers": [ids[0]], "start": 1.0})).unwrap();
|
||||
s.execute_checked("layer.timeStretch", json!({"layers": [ids[1]], "percent": 200})).unwrap();
|
||||
s.execute_checked("layer.timeStretch", json!({"layers": [ids[2]], "op": "reverse"})).unwrap();
|
||||
add_key(&mut s, ids[2], "transform/opacity", 1.0, json!(50));
|
||||
let keys = key_times(&s, ids[2], "transform/opacity");
|
||||
let start: Vec<_> = ids.iter().map(|id| timing(&s, *id)).collect();
|
||||
let before = s.project.clone();
|
||||
for frames in [2.0, 5.0, -3.0, 2.0] {
|
||||
s.execute_checked("layer.quickOffset", json!({"delta": frames / 30.0, "merge": "qo", "fromStart": true})).unwrap();
|
||||
}
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let d = 2 * F * i as i64 / 2;
|
||||
let (a, b, c) = start[i];
|
||||
assert_eq!(timing(&s, *id), (a + d, b + d, c + d), "layer {i}: only the last step's whole drag counts");
|
||||
}
|
||||
assert_eq!(key_times(&s, ids[2], "transform/opacity"), keys);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.same_content(&before), "the drag is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_layers_bad_arguments_and_out_of_range_moves_change_nothing() {
|
||||
let (mut s, ids) = setup(3);
|
||||
select(&mut s, &ids);
|
||||
// A locked layer is skipped: the other two are first and last.
|
||||
s.execute_checked("layer.setSwitch", json!({"layers": [ids[1]], "switch": "locked", "value": true})).unwrap();
|
||||
s.execute_checked("layer.quickOffset", json!({"layers": ids, "delta": 0.1})).unwrap();
|
||||
assert_eq!((timing(&s, ids[0]).0, timing(&s, ids[1]).0), (0, 0));
|
||||
assert_eq!(timing(&s, ids[2]).0, Tick::from_seconds_f64(0.1).0);
|
||||
let before = (s.project.clone(), s.revision);
|
||||
for p in [
|
||||
json!({"layers": [ids[0]], "delta": 0.1}),
|
||||
json!({"layers": [ids[0], ids[1]], "delta": 0.1}),
|
||||
json!({"layers": ids}),
|
||||
json!({"layers": ids, "delta": "far"}),
|
||||
json!({"layers": ids, "delta": 1e12}),
|
||||
json!({"layers": [ids[0], 999], "delta": 0.1}),
|
||||
] {
|
||||
assert!(s.execute_checked("layer.quickOffset", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.project.same_content(&before.0) && s.revision == before.1, "refused calls change nothing");
|
||||
// The last layer's destination is past the end of time: nothing moves.
|
||||
s.execute_checked("layer.timing", json!({"layers": [ids[2]], "start": 9.0e6})).unwrap();
|
||||
let before = s.project.clone();
|
||||
assert!(s.execute_checked("layer.quickOffset", json!({"layers": [ids[0], ids[2]], "delta": 1.0e5})).is_err());
|
||||
assert!(s.project.same_content(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_stagger_per_layer_in_the_order_their_layers_were_selected() {
|
||||
let (mut s, ids) = setup(3);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 0.0, json!(0));
|
||||
add_key(&mut s, *id, "transform/opacity", 1.0, json!(100));
|
||||
}
|
||||
add_key(&mut s, ids[0], "transform/position", 0.5, json!([10, 20]));
|
||||
s.execute_checked("keys.select", json!({"keys": [{"layer": ids[0], "path": "transform/opacity", "time": 1.0}]})).unwrap();
|
||||
s.execute_checked("keys.interpolation", json!({"interpolation": "hold"})).unwrap();
|
||||
// Layer 1's keys first, then layer 0's two properties, then layer 2's.
|
||||
let picks = [
|
||||
(ids[1], "transform/opacity", 0.0),
|
||||
(ids[0], "transform/opacity", 1.0),
|
||||
(ids[1], "transform/opacity", 1.0),
|
||||
(ids[0], "transform/position", 0.5),
|
||||
(ids[2], "transform/opacity", 1.0),
|
||||
];
|
||||
select_keys(&mut s, &picks);
|
||||
let before = s.project.clone();
|
||||
let reply = s.execute_checked("keys.quickOffset", json!({"delta": 3.0 / 30.0})).unwrap();
|
||||
assert_eq!(reply["keys"], 5);
|
||||
let sec = |t: f64| Tick::from_seconds_f64(t).0;
|
||||
assert_eq!(key_times(&s, ids[1], "transform/opacity"), vec![0, sec(1.0)], "the first layer stays");
|
||||
assert_eq!(key_times(&s, ids[0], "transform/opacity"), vec![0, sec(1.0) + 3 * F / 2], "the middle layer: 1.5 frames");
|
||||
assert_eq!(key_times(&s, ids[0], "transform/position"), vec![sec(0.5) + 3 * F / 2], "both its properties move as one group");
|
||||
assert_eq!(key_times(&s, ids[2], "transform/opacity"), vec![0, sec(1.0) + 3 * F], "the last layer: the whole drag");
|
||||
// The keys keep their values and interpolation, and the selection its order.
|
||||
let moved = layer(&s, ids[0]).props.prop("transform/opacity").unwrap().keys[1].clone();
|
||||
assert_eq!((moved.value.components(), moved.out_interp), (vec![100.0], Interp::Hold));
|
||||
let order: Vec<(u64, u64)> = s.state.selected_keys.iter().map(|k| (k.layer.0, k.prop)).collect();
|
||||
let want: Vec<(u64, u64)> = picks.iter().map(|(id, path, _)| (*id, uid(&s, *id, path))).collect();
|
||||
assert_eq!(order, want);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.same_content(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_of_stretched_and_reversed_layers_follow_the_comp_time_offset() {
|
||||
let (mut s, ids) = setup(3);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 1.0, json!(10));
|
||||
}
|
||||
s.execute_checked("layer.timeStretch", json!({"layers": [ids[1]], "percent": 200})).unwrap();
|
||||
s.execute_checked("layer.timeStretch", json!({"layers": [ids[2]], "op": "reverse"})).unwrap();
|
||||
let comp_time = |s: &Session, id: u64| {
|
||||
let l = layer(s, id);
|
||||
l.comp_time(l.props.prop("transform/opacity").unwrap().keys[0].time).0
|
||||
};
|
||||
let before: Vec<i64> = ids.iter().map(|id| comp_time(&s, *id)).collect();
|
||||
select_keys(&mut s, &ids.iter().map(|id| (*id, "transform/opacity", 1.0)).collect::<Vec<_>>());
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 4.0 / 30.0})).unwrap();
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let moved = comp_time(&s, *id) - before[i];
|
||||
assert!((moved - 2 * F * i as i64).abs() <= 1, "layer {i}: moved {moved} ticks in comp time");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_drag_over_another_key_and_back_keeps_it() {
|
||||
let (mut s, ids) = setup(2);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 0.0, json!(0));
|
||||
}
|
||||
add_key(&mut s, ids[1], "transform/opacity", 0.5, json!(50));
|
||||
select_keys(&mut s, &[(ids[0], "transform/opacity", 0.0), (ids[1], "transform/opacity", 0.0)]);
|
||||
let before = s.project.clone();
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 0.5, "merge": "qk", "fromStart": true})).unwrap();
|
||||
assert_eq!(key_times(&s, ids[1], "transform/opacity").len(), 1, "the dragged key replaces the one it lands on");
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 0.0, "merge": "qk", "fromStart": true})).unwrap();
|
||||
assert!(s.project.same_content(&before), "dragged back, the key passed over is there again");
|
||||
assert_eq!(s.state.selected_keys.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_need_two_unlocked_layers() {
|
||||
let (mut s, ids) = setup(3);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 0.0, json!(0));
|
||||
add_key(&mut s, *id, "transform/opacity", 1.0, json!(100));
|
||||
}
|
||||
select_keys(&mut s, &[(ids[0], "transform/opacity", 0.0), (ids[0], "transform/opacity", 1.0)]);
|
||||
let before = s.project.clone();
|
||||
assert!(s.execute_checked("keys.quickOffset", json!({"delta": 0.1})).is_err(), "keys on one layer");
|
||||
// Locked after selecting: that layer's keys stay; the other two still stagger.
|
||||
select_keys(&mut s, &ids.iter().map(|id| (*id, "transform/opacity", 1.0)).collect::<Vec<_>>());
|
||||
s.execute_checked("layer.setSwitch", json!({"layers": [ids[1]], "switch": "locked", "value": true})).unwrap();
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 0.1})).unwrap();
|
||||
let sec = |t: f64| Tick::from_seconds_f64(t).0;
|
||||
assert_eq!(key_times(&s, ids[0], "transform/opacity")[1], sec(1.0));
|
||||
assert_eq!(key_times(&s, ids[1], "transform/opacity")[1], sec(1.0));
|
||||
assert_eq!(key_times(&s, ids[2], "transform/opacity")[1], sec(1.1));
|
||||
assert!(s.state.selected_keys.contains(&KeyRef { layer: LayerId(ids[1]), prop: uid(&s, ids[1], "transform/opacity"), time: Tick(sec(1.0)) }));
|
||||
assert!(!before.same_content(&s.project));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roving_keys_follow_and_the_selection_stays_on_the_moved_keys() {
|
||||
let (mut s, ids) = setup(2);
|
||||
for (t, x) in [(0.0, 0), (1.0, 50), (2.0, 100)] {
|
||||
add_key(&mut s, ids[0], "transform/position", t, json!([x, 0]));
|
||||
}
|
||||
add_key(&mut s, ids[1], "transform/position", 2.0, json!([0, 0]));
|
||||
s.execute_checked("keys.select", json!({"keys": [{"layer": ids[0], "path": "transform/position", "time": 1.0}]})).unwrap();
|
||||
s.execute_checked("keys.interpolation", json!({"roving": true})).unwrap();
|
||||
// Only the last key of the roving layer is selected, with a key on the other layer first.
|
||||
select_keys(&mut s, &[(ids[1], "transform/position", 2.0), (ids[0], "transform/position", 2.0)]);
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 1.0})).unwrap();
|
||||
let pos = layer(&s, ids[0]).props.prop("transform/position").unwrap();
|
||||
let times: Vec<i64> = pos.keys.iter().map(|k| k.time.0).collect();
|
||||
assert_eq!((times[0], times[2]), (0, Tick::from_seconds_f64(3.0).0));
|
||||
assert!(times[1] > 0 && times[1] < times[2], "the roving key retimed between its neighbours: {times:?}");
|
||||
for k in &s.state.selected_keys {
|
||||
assert!(layer(&s, k.layer.0).props.find(k.prop).unwrap().keys.iter().any(|x| x.time == k.time), "{k:?} points at a key");
|
||||
}
|
||||
assert_eq!(s.state.selected_keys.iter().map(|k| k.layer.0).collect::<Vec<_>>(), vec![ids[1], ids[0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_staggered_keys_keeps_their_subframe_spacing() {
|
||||
let (mut s, ids) = setup(4);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 0.0, json!(0));
|
||||
}
|
||||
select_keys(&mut s, &ids.iter().map(|id| (*id, "transform/opacity", 0.0)).collect::<Vec<_>>());
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 1.0 / 30.0})).unwrap();
|
||||
// A plain move (and a nudge) translates them: it used to put each key on its nearest frame.
|
||||
s.execute_checked("keys.move", json!({"delta": 1.0 / 30.0})).unwrap();
|
||||
s.execute_checked("keys.nudgeForward", json!({})).unwrap();
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
assert_eq!(key_times(&s, *id, "transform/opacity"), vec![2 * F + F * i as i64 / 3], "layer {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_step_does_not_count_towards_the_drag() {
|
||||
let (mut s, ids) = setup(2);
|
||||
for id in &ids {
|
||||
add_key(&mut s, *id, "transform/opacity", 1.0, json!(0));
|
||||
}
|
||||
select_keys(&mut s, &ids.iter().map(|id| (*id, "transform/opacity", 1.0)).collect::<Vec<_>>());
|
||||
let before = s.project.clone();
|
||||
// The second step's last key would land past the end of time (one second short of it, its
|
||||
// own delta isn't); with it counted, the third would still move the key that far.
|
||||
let far = (Tick::MAX.seconds() - 1.0).floor();
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": 1.0, "merge": "steps"})).unwrap();
|
||||
assert!(s.execute_checked("keys.quickOffset", json!({"delta": far, "merge": "steps"})).is_err());
|
||||
s.execute_checked("keys.quickOffset", json!({"delta": -1.0, "merge": "steps"})).unwrap();
|
||||
assert!(s.project.same_content(&before), "only the steps that applied count: {:?}", key_times(&s, ids[1], "transform/opacity"));
|
||||
}
|
||||
@@ -27,6 +27,35 @@ pub(crate) fn hold_roto_cache_test_lock() {
|
||||
}
|
||||
const R: f64 = 40.0;
|
||||
|
||||
fn span_after_trimming_strokes(trim: Value, span: Value, expected: [i64; 2]) {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"width": 64, "height": 64, "frameRate": 25, "duration": 1})).unwrap();
|
||||
let layer = s.execute("layer.newSolid", json!({"width": 64, "height": 64})).unwrap()["layer"].as_u64().unwrap();
|
||||
for frame in [0, 20] {
|
||||
s.execute("roto.stroke", json!({"layer": layer, "frame": frame, "points": [[32, 32]], "radius": 4})).unwrap();
|
||||
}
|
||||
s.execute("layer.timing", trim).unwrap();
|
||||
let before = s.project.to_json();
|
||||
let error = s.execute("roto.span", span.clone()).unwrap_err().to_string();
|
||||
assert!(error.contains("strokes outside the layer"), "{error}");
|
||||
assert_eq!(s.project.to_json(), before, "refusing the span must preserve strokes and project state");
|
||||
assert!(s.undo(), "the failed command must not add an undo step");
|
||||
let result = s.execute("roto.span", span).unwrap();
|
||||
assert_eq!(result["span"], json!(expected));
|
||||
let status = s.execute("roto.status", json!({"layer": layer})).unwrap();
|
||||
assert_eq!(status["strokeFrames"], json!([0, 20]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roto_span_rejects_strokes_before_trimmed_in_point() {
|
||||
span_after_trimming_strokes(json!({"in": 0.2}), json!({"start": 0}), [0, 20]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roto_span_rejects_strokes_after_trimmed_out_point() {
|
||||
span_after_trimming_strokes(json!({"out": 0.5}), json!({"end": 24}), [0, 24]);
|
||||
}
|
||||
|
||||
fn noise(x: f64, y: f64, seed: u32) -> f64 {
|
||||
fn h(i: i64, j: i64, s: u32) -> f64 {
|
||||
let mut v = (i.wrapping_mul(73856093) ^ j.wrapping_mul(19349663) ^ (s as i64).wrapping_mul(83492791)) as u64;
|
||||
@@ -351,3 +380,264 @@ fn offloaded_propagation_streams_segmentations_back() {
|
||||
s.execute("roto.propagate", json!({"layer": clip.0, "wait": true})).unwrap();
|
||||
assert!(s.offloaded.is_empty());
|
||||
}
|
||||
|
||||
/// Object Matte: one click on the disk on frame 0 isolates it there and on the frames it is
|
||||
/// followed to; the Input Key follows the layer's frames; bad prompts are refused.
|
||||
#[test]
|
||||
fn object_matte_from_a_click() {
|
||||
hold_roto_cache_test_lock();
|
||||
let (mut s, clip, solid) = setup(|f| draw(center(f)));
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("remove solid", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
for it in p.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
f.path = "object-matte.mov".into();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("time.set", json!({"time": 0})).unwrap();
|
||||
let c = center(0);
|
||||
let r = s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "point": c, "after": 6})).unwrap();
|
||||
assert_eq!(r["frame"], 0);
|
||||
assert_eq!(r["span"], json!([-30, 6]));
|
||||
let uid = r["effect"].as_u64().unwrap();
|
||||
let key = |s: &Session| {
|
||||
let g = s.active_comp().unwrap().layer(clip).unwrap().props.find_group(uid).unwrap().clone();
|
||||
crate::roto::params_static(&g).get(effectcraft_effects::roto::INPUT_KEY).cloned()
|
||||
};
|
||||
let k0 = key(&s);
|
||||
assert!(matches!(&k0, Some(effectcraft_keyframe::Value::Str(k)) if !k.is_empty()), "{k0:?}");
|
||||
let wrong = |s: &Session, f: u32| {
|
||||
let c = center(f);
|
||||
alpha_at(s, f)
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, v)| {
|
||||
let d = (((*i as u32 % W) as f64 + 0.5 - c[0]).hypot((*i as u32 / W) as f64 + 0.5 - c[1])) - R;
|
||||
(d < -3.0 && **v < 0.5) || (d > 3.0 && **v > 0.5)
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let w0 = wrong(&s, 0);
|
||||
assert!(w0 < 40, "{w0} wrong pixels on the reference frame");
|
||||
let w4 = wrong(&s, 4);
|
||||
assert!(w4 < 60, "{w4} wrong pixels on frame 4");
|
||||
// Past Frames After: transparent.
|
||||
assert!(alpha_at(&s, 8).iter().all(|v| *v == 0.0));
|
||||
// Other frames under the effect: a new Input Key (the mattes are recomputed).
|
||||
s.edit("swap clip", None, |p, _| {
|
||||
for it in p.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
f.path = "object-matte-2.mov".into();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_ne!(key(&s), k0);
|
||||
// Bad prompts are refused.
|
||||
for bad in [
|
||||
json!({"layer": clip.0}),
|
||||
json!({"layer": clip.0, "point": [-10, 5]}),
|
||||
json!({"layer": clip.0, "point": [10, "x"]}),
|
||||
json!({"layer": clip.0, "point": c, "box": [0, 0, 10, 10]}),
|
||||
json!({"layer": clip.0, "point": c, "frame": 999}),
|
||||
] {
|
||||
assert!(s.execute_checked("objectMatte.apply", bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
// A box and a static prompt are accepted; the second instance is numbered.
|
||||
let r = s
|
||||
.execute_checked("objectMatte.apply", json!({"layer": clip.0, "point": c, "box": [c[0] + 50.0, c[1] + 50.0, c[0] - 50.0, c[1] - 50.0], "track": false}))
|
||||
.unwrap();
|
||||
let g = s.active_comp().unwrap().layer(clip).unwrap().props.find_group(r["effect"].as_u64().unwrap()).unwrap().clone();
|
||||
assert_eq!(g.name, "Object Matte 2");
|
||||
}
|
||||
|
||||
/// `objectMatte.apply` with `effect` re-prompts that instance in one undo step: the new point and
|
||||
/// box, the box dropped when none is given, the reach kept unless given.
|
||||
#[test]
|
||||
fn object_matte_reprompt_updates_the_instance() {
|
||||
let (mut s, clip, solid) = setup(|f| draw(center(f)));
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("remove solid", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let c = center(0);
|
||||
let r = s
|
||||
.execute_checked(
|
||||
"objectMatte.apply",
|
||||
json!({"layer": clip.0, "point": c, "box": [c[0] - 50.0, c[1] - 50.0, c[0] + 50.0, c[1] + 50.0], "after": 6, "frame": 0}),
|
||||
)
|
||||
.unwrap();
|
||||
let uid = r["effect"].as_u64().unwrap();
|
||||
let count = |s: &Session| s.active_comp().unwrap().layer(clip).unwrap().effects().unwrap().groups().count();
|
||||
let ps = |s: &Session| crate::roto::params_static(s.active_comp().unwrap().layer(clip).unwrap().props.find_group(uid).unwrap());
|
||||
let undo0 = s.history.undo.len();
|
||||
let r = s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "effect": uid, "point": [c[0] + 4.0, c[1]], "frame": 2})).unwrap();
|
||||
assert_eq!((r["effect"].as_u64(), r["updated"].as_bool()), (Some(uid), Some(true)));
|
||||
assert_eq!(r["span"], json!([-28, 8]));
|
||||
assert_eq!(count(&s), 1);
|
||||
assert_eq!(s.history.undo.len(), undo0 + 1);
|
||||
let p = ps(&s);
|
||||
assert_eq!(p.get("objectPoint"), Some(&effectcraft_keyframe::Value::Vec2([c[0] + 4.0, c[1]])));
|
||||
assert_eq!(p.get("useBox"), Some(&effectcraft_keyframe::Value::Bool(false)));
|
||||
assert_eq!(effectcraft_effects::object_matte::reference_frame(&p), 2);
|
||||
assert_eq!(effectcraft_effects::object_matte::reach(&p), [30, 6]);
|
||||
// Undo restores the first prompt.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(ps(&s).get("useBox"), Some(&effectcraft_keyframe::Value::Bool(true)));
|
||||
// An unknown or non-Object Matte effect is refused.
|
||||
assert!(s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "effect": 999_999, "point": c})).is_err());
|
||||
}
|
||||
|
||||
/// Object Matte runs in the background like Roto Brush propagation: queued by the edit, a job
|
||||
/// that returns at once and reports progress, stops when cancelled (keeping what it computed),
|
||||
/// computes the tracked frames when left to run, and Freeze stores mattes that renders then use
|
||||
/// without segmenting again.
|
||||
#[test]
|
||||
fn object_matte_background_job_cancel_and_freeze() {
|
||||
hold_roto_cache_test_lock();
|
||||
let (mut s, clip, solid) = setup(|f| draw(center(f)));
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("remove solid", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
for it in p.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
f.path = "object-matte-job.mov".into();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let c = center(0);
|
||||
let r = s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "point": c, "before": 0, "after": 24, "frame": 0})).unwrap();
|
||||
let uid = r["effect"].as_u64().unwrap();
|
||||
assert!(s.roto_pending.contains(&(cid, clip, uid)), "the new prompt is queued for tracking");
|
||||
let wait_done = |s: &mut Session| {
|
||||
let t = std::time::Instant::now();
|
||||
while s.is_roto_running() {
|
||||
assert!(t.elapsed().as_secs() < 120, "the job never finished");
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
s.poll_roto(false);
|
||||
}
|
||||
s.poll_roto(false);
|
||||
};
|
||||
let toast = |s: &Session, m: &str| s.events.iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message.starts_with(m)));
|
||||
let status = |s: &mut Session| s.execute("objectMatte.status", json!({"layer": clip.0, "effect": uid})).unwrap();
|
||||
|
||||
// Cancelled at once: it stops early, and says so.
|
||||
let r = s.execute_checked("objectMatte.propagate", json!({"layer": clip.0, "effect": uid})).unwrap();
|
||||
assert_eq!(r["frames"], 25);
|
||||
assert!(!s.roto_pending.contains(&(cid, clip, uid)));
|
||||
let _ = s.execute("roto.cancel", json!({}));
|
||||
wait_done(&mut s);
|
||||
assert!(toast(&s, "Object Matte: stopped"), "{:?}", s.events);
|
||||
let st = status(&mut s);
|
||||
assert_eq!(st["frames"].as_array().unwrap().len(), 25, "{st}");
|
||||
let early = st["computed"].as_array().unwrap().len();
|
||||
assert!(early < 25, "{st}");
|
||||
|
||||
// Left to run: the call returns while the job works (progress visible), then every tracked
|
||||
// frame is computed.
|
||||
let r = s.execute_checked("objectMatte.propagate", json!({"layer": clip.0, "effect": uid})).unwrap();
|
||||
assert_eq!(r["running"], true, "{r}");
|
||||
let pr = s.roto_progress().unwrap();
|
||||
assert!(pr.object_matte && pr.banner().starts_with("Tracking Object Matte"), "{pr:?}");
|
||||
// One job at a time.
|
||||
assert!(s.execute_checked("objectMatte.propagate", json!({"layer": clip.0, "effect": uid})).is_err());
|
||||
wait_done(&mut s);
|
||||
assert!(toast(&s, "Object Matte: tracked"), "{:?}", s.events);
|
||||
assert_eq!(status(&mut s)["computed"].as_array().unwrap().len(), 25);
|
||||
let before = alpha_at(&s, 4);
|
||||
|
||||
// Freeze, then drop the segmentations: renders use the frozen mattes and compute nothing.
|
||||
let r = s.execute_checked("objectMatte.freeze", json!({"layer": clip.0, "effect": uid, "wait": true})).unwrap();
|
||||
assert_eq!(r["frozen"], true, "{r}");
|
||||
let keys: Vec<u64> = s.roto_keys(cid, clip, uid).unwrap().into_iter().map(|(_, k)| k).collect();
|
||||
assert_eq!(keys.len(), 25);
|
||||
effectcraft_effects::roto::forget(keys.iter().copied());
|
||||
let frozen = alpha_at(&s, 4);
|
||||
let diff = before.iter().zip(&frozen).filter(|(a, b)| (**a - **b).abs() > 0.02).count();
|
||||
assert!(diff < 30, "{diff} pixels differ from the computed matte");
|
||||
assert!(status(&mut s)["computed"].as_array().unwrap().is_empty(), "a frozen frame was segmented again");
|
||||
assert_eq!(status(&mut s)["frozen"], true);
|
||||
// A frozen prompt is refused; Unfreeze computes again.
|
||||
assert!(s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "effect": uid, "point": c})).is_err());
|
||||
s.execute_checked("objectMatte.unfreeze", json!({"layer": clip.0, "effect": uid})).unwrap();
|
||||
let _ = alpha_at(&s, 4);
|
||||
assert!(status(&mut s)["computed"].as_array().unwrap().iter().any(|f| f == 4));
|
||||
// Undo brings the frozen mattes back.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(status(&mut s)["frozen"], true);
|
||||
}
|
||||
|
||||
/// Computed Object Matte segmentations go to the persistent disk cache: a second session on the
|
||||
/// same folder and project gets them back without segmenting (its frames cannot even be read
|
||||
/// here), and another prompt (other keys) finds nothing.
|
||||
#[test]
|
||||
fn object_matte_mattes_persist_in_the_disk_cache() {
|
||||
use effectcraft_effects::object_matte as om;
|
||||
use effectcraft_render::disk_cache::Kind;
|
||||
hold_roto_cache_test_lock();
|
||||
let dir = std::env::temp_dir().join(format!("effectcraft-om-disk-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let enable = |s: &mut Session| {
|
||||
s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap();
|
||||
};
|
||||
let (mut s, clip, solid) = setup(|f| draw(center(f)));
|
||||
enable(&mut s);
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("remove solid", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
for it in p.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
f.path = "object-matte-disk.mov".into();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let c = center(0);
|
||||
let r = s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "point": c, "before": 0, "after": 5, "frame": 0})).unwrap();
|
||||
let uid = r["effect"].as_u64().unwrap();
|
||||
s.execute_checked("objectMatte.propagate", json!({"layer": clip.0, "effect": uid, "wait": true})).unwrap();
|
||||
let keys = s.roto_keys(cid, clip, uid).unwrap();
|
||||
assert_eq!(keys.len(), 6);
|
||||
let dc = s.disk_cache.clone().unwrap();
|
||||
dc.flush();
|
||||
assert!(dc.keys(Kind::Matte).len() >= 6, "{:?}", dc.stats());
|
||||
let before = alpha_at(&s, 3);
|
||||
let saved = s.project.clone();
|
||||
drop(dc);
|
||||
drop(s);
|
||||
effectcraft_effects::roto::forget(keys.iter().map(|(_, k)| *k));
|
||||
|
||||
// "Reopen": a new session on the same folder and project.
|
||||
let (mut s2, _, _) = setup(|f| draw(center(f)));
|
||||
enable(&mut s2);
|
||||
s2.project = saved;
|
||||
s2.bump();
|
||||
s2.open_comp(cid);
|
||||
assert_eq!(s2.roto_keys(cid, clip, uid).unwrap(), keys, "the same input key, so the same keys");
|
||||
let comp = s2.active_comp().unwrap().clone();
|
||||
let l = comp.layer(clip).unwrap();
|
||||
let ps = crate::roto::params_static(l.props.find_group(uid).unwrap());
|
||||
let size = crate::roto::layer_size(&s2.project, &comp, l);
|
||||
// No frames to segment from: whatever comes back was read from disk.
|
||||
for (f, _) in &keys {
|
||||
assert!(om::ensure(&ps, size, 25.0, *f, None, &mut |_| None, &|| false).is_some(), "frame {f} not reused from disk");
|
||||
}
|
||||
assert!(s2.disk_cache.as_ref().unwrap().stats().hits >= 6);
|
||||
let again = alpha_at(&s2, 3);
|
||||
assert_eq!(again, before, "the disk-cached matte renders the same");
|
||||
// Another prompt: other keys, nothing on disk.
|
||||
let mut moved = ps.clone();
|
||||
moved.values.insert("objectPoint".into(), effectcraft_keyframe::Value::Vec2([c[0] + 3.0, c[1]]));
|
||||
assert!(om::ensure(&moved, size, 25.0, 0, None, &mut |_| None, &|| false).is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -375,6 +375,89 @@ fn defaults_have_no_conflicts_and_match_the_menus() {
|
||||
assert!(t.bindables.len() > 500);
|
||||
}
|
||||
|
||||
/// Each Fast Previews and Show Channel mode is a command with a default key.
|
||||
#[test]
|
||||
fn fast_previews_and_show_channel_modes_have_default_keys() {
|
||||
let s = Session::default();
|
||||
let t = s.shortcuts();
|
||||
for (id, key) in [
|
||||
("view.fastPreviews.off", "Cmd+Alt+1"),
|
||||
("view.fastPreviews.adaptive", "Cmd+Alt+2"),
|
||||
("view.fastPreviews.draft", "Cmd+Alt+3"),
|
||||
("view.fastPreviews.fastDraft", "Cmd+Alt+4"),
|
||||
("view.fastPreviews.wireframe", "Cmd+Alt+5"),
|
||||
("view.channel.red", "Alt+1"),
|
||||
("view.channel.green", "Alt+2"),
|
||||
("view.channel.blue", "Alt+3"),
|
||||
("view.channel.alpha", "Alt+4"),
|
||||
("view.channel.redColorized", "Alt+Shift+1"),
|
||||
("view.channel.greenColorized", "Alt+Shift+2"),
|
||||
("view.channel.blueColorized", "Alt+Shift+3"),
|
||||
("view.channel.rgbStraight", "Alt+Shift+4"),
|
||||
] {
|
||||
assert_eq!(t.shortcut_of(id, &json!(null)), Some(key), "{id}");
|
||||
}
|
||||
assert!(t.all_conflicts().is_empty(), "{:?}", t.all_conflicts());
|
||||
// The commands set their mode; a channel's key again is RGB.
|
||||
let mut s = Session::default();
|
||||
s.execute("view.fastPreviews.fastDraft", json!({})).unwrap();
|
||||
assert_eq!(s.state.viewer.fast_previews.id(), "fastDraft");
|
||||
s.execute("view.channel.redColorized", json!({})).unwrap();
|
||||
assert_eq!((s.state.viewer.channel.id(), s.state.viewer.colorized), ("red", true));
|
||||
s.execute("view.channel.green", json!({})).unwrap();
|
||||
assert_eq!((s.state.viewer.channel.id(), s.state.viewer.colorized), ("green", false));
|
||||
s.execute("view.channel.green", json!({})).unwrap();
|
||||
assert_eq!(s.state.viewer.channel.id(), "rgb");
|
||||
// Grayscale and colorized of one channel replace each other; the same again is RGB.
|
||||
s.execute("view.channel.redColorized", json!({})).unwrap();
|
||||
s.execute("view.channel.red", json!({})).unwrap();
|
||||
assert_eq!((s.state.viewer.channel.id(), s.state.viewer.colorized), ("red", false));
|
||||
s.execute("view.channel.redColorized", json!({})).unwrap();
|
||||
assert_eq!((s.state.viewer.channel.id(), s.state.viewer.colorized), ("red", true));
|
||||
s.execute("view.channel.redColorized", json!({})).unwrap();
|
||||
assert_eq!(s.state.viewer.channel.id(), "rgb");
|
||||
}
|
||||
|
||||
/// Default keys for commands and menu entries that had none.
|
||||
#[test]
|
||||
fn default_keys_for_commands_that_had_none() {
|
||||
let s = Session::default();
|
||||
let t = s.shortcuts();
|
||||
for (id, params, key) in [
|
||||
("edit.pasteReversedKeyframes", json!(null), "Cmd+Shift+V"),
|
||||
("edit.purge", json!({"what": "snapshot"}), "Cmd+Shift+F5"),
|
||||
("layer.sampling", json!({"sampling": "bilinear", "toggle": true}), "Alt+B"),
|
||||
("layer.sampling", json!({"sampling": "bicubic", "toggle": true}), "Alt+Shift+B"),
|
||||
("view.res.custom", json!(null), "Cmd+Alt+J"),
|
||||
("file.setProxy", json!(null), "Cmd+Alt+P"),
|
||||
("file.openRecent", json!(null), "Cmd+Alt+Shift+P"),
|
||||
("anim.applyRecentPreset", json!(null), "Cmd+Alt+Shift+F"),
|
||||
] {
|
||||
assert_eq!(t.shortcut_of(id, ¶ms), Some(key), "{id} {params}");
|
||||
}
|
||||
assert!(t.all_conflicts().is_empty(), "{:?}", t.all_conflicts());
|
||||
}
|
||||
|
||||
/// Second default keys: on the command, or after a comma in a menu line with bound parameters.
|
||||
#[test]
|
||||
fn second_default_keys() {
|
||||
let s = Session::default();
|
||||
let t = s.shortcuts();
|
||||
for (key, want) in [
|
||||
("edit.deselectAll", ["Cmd+Shift+A", "F2"]),
|
||||
("time.start", ["Home", "Cmd+Alt+ArrowLeft"]),
|
||||
("time.end", ["End", "Cmd+Alt+ArrowRight"]),
|
||||
("renderQueue.add", ["Cmd+M", "Cmd+Shift+/"]),
|
||||
(r#"window.panel {"panel":"effectControls"}"#, ["F3", "Cmd+Shift+T"]),
|
||||
] {
|
||||
assert_eq!(t.keys.get(key).map(Vec::as_slice), Some(want.map(String::from).as_slice()), "{key}");
|
||||
}
|
||||
// The menus keep showing the first key.
|
||||
assert_eq!(t.shortcut_of("window.panel", &json!({"panel": "effectControls"})), Some("F3"));
|
||||
assert_eq!(t.shortcut_of("edit.deselectAll", &json!(null)), Some("Cmd+Shift+A"));
|
||||
assert!(t.all_conflicts().is_empty(), "{:?}", t.all_conflicts());
|
||||
}
|
||||
|
||||
/// Cmd+Left / Cmd+Right Arrow step a frame like Page Up / Page Down (Shift: 10 frames).
|
||||
#[test]
|
||||
fn cmd_arrows_step_frames_like_page_keys() {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! The keyboard-only commands: time navigation, the work area, selection and layer timing.
|
||||
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A 10 s, 30 fps comp with three solids (#1 on top), each trimmed to `spans` (seconds).
|
||||
fn session(spans: [(f64, f64); 3]) -> (Session, Vec<u64>) {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Main", "width": 100, "height": 100, "frameRate": 30, "duration": 10})).unwrap();
|
||||
for _ in 0..3 {
|
||||
s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
|
||||
}
|
||||
let ids: Vec<u64> = s.active_comp().unwrap().layers.iter().map(|l| l.id.0).collect();
|
||||
for (id, (a, b)) in ids.iter().zip(spans) {
|
||||
s.execute("layer.timing", json!({"layers": [id], "in": a, "out": b})).unwrap();
|
||||
}
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
fn secs(s: &Session) -> f64 {
|
||||
s.time().seconds()
|
||||
}
|
||||
|
||||
fn span(s: &Session, id: u64) -> (f64, f64) {
|
||||
let c = s.active_comp().unwrap();
|
||||
let l = c.layers.iter().find(|l| l.id.0 == id).unwrap();
|
||||
(l.in_point.seconds(), l.out_point.seconds())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_goes_to_the_work_area_and_to_in_and_out_points() {
|
||||
let (mut s, ids) = session([(1.0, 3.0), (2.0, 6.0), (0.0, 10.0)]);
|
||||
s.execute("comp.workArea", json!({"start": 2.0, "end": 4.0})).unwrap();
|
||||
s.execute("time.workAreaStart", json!({})).unwrap();
|
||||
assert_eq!(secs(&s), 2.0);
|
||||
s.execute("time.workAreaEnd", json!({})).unwrap();
|
||||
let frame = 1.0 / 30.0;
|
||||
assert!((secs(&s) - (4.0 - frame)).abs() < 1e-9);
|
||||
// In and Out points of the selected layers (an Out point is the layer's last frame).
|
||||
s.execute("layer.select", json!({"layers": [ids[0], ids[1]]})).unwrap();
|
||||
s.execute("time.set", json!({"time": 0.0})).unwrap();
|
||||
let mut seen = vec![];
|
||||
for _ in 0..5 {
|
||||
s.execute("time.nextInOut", json!({})).unwrap();
|
||||
seen.push(secs(&s));
|
||||
}
|
||||
let want = [1.0, 2.0, 3.0 - frame, 6.0 - frame, 6.0 - frame];
|
||||
assert!(seen.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{seen:?}");
|
||||
s.execute("time.previousInOut", json!({})).unwrap();
|
||||
assert!((secs(&s) - (3.0 - frame)).abs() < 1e-9);
|
||||
// With no layer selected: every layer's points.
|
||||
s.execute("edit.deselectAll", json!({})).unwrap();
|
||||
s.execute("time.set", json!({"time": 8.0})).unwrap();
|
||||
s.execute("time.nextInOut", json!({})).unwrap();
|
||||
assert!((secs(&s) - (10.0 - frame)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_area_follows_the_selected_layers() {
|
||||
let (mut s, ids) = session([(1.0, 3.0), (2.0, 6.0), (0.0, 10.0)]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0], ids[1]]})).unwrap();
|
||||
s.execute("comp.workAreaToSelection", json!({})).unwrap();
|
||||
let wa = s.active_comp().unwrap().work_area;
|
||||
assert_eq!((wa.0.seconds(), wa.1.seconds()), (1.0, 6.0));
|
||||
// With nothing selected: the whole composition.
|
||||
s.execute("edit.deselectAll", json!({})).unwrap();
|
||||
s.execute("comp.workAreaToSelection", json!({})).unwrap();
|
||||
let wa = s.active_comp().unwrap().work_area;
|
||||
assert_eq!((wa.0, wa.1.seconds()), (Tick::ZERO, 10.0));
|
||||
// One undo step each.
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.active_comp().unwrap().work_area.1.seconds(), 6.0);
|
||||
// Layers reaching outside the comp don't take the work area with them.
|
||||
s.execute("layer.timing", json!({"layers": [ids[0]], "delta": -5.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layers": [ids[0]]})).unwrap();
|
||||
s.execute("comp.workAreaToSelection", json!({})).unwrap();
|
||||
let wa = s.active_comp().unwrap().work_area;
|
||||
assert!(wa.0 == Tick::ZERO && wa.1 > wa.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_most_recent_comp_of_the_hierarchy_comes_back() {
|
||||
let mut s = Session::default();
|
||||
let new = |s: &mut Session, name: &str| s.execute("comp.new", json!({"name": name, "duration": 4})).unwrap()["comp"].as_u64().unwrap();
|
||||
let main = new(&mut s, "Main");
|
||||
let nested = new(&mut s, "Nested");
|
||||
let other = new(&mut s, "Other");
|
||||
// Main contains Nested; Other stands alone.
|
||||
s.execute("comp.open", json!({"comp": main})).unwrap();
|
||||
s.execute("layer.addItem", json!({"item": nested})).unwrap();
|
||||
s.execute("comp.open", json!({"comp": nested})).unwrap();
|
||||
s.execute("comp.open", json!({"comp": other})).unwrap();
|
||||
// Other has no related comp to go back to.
|
||||
assert!(s.execute("comp.activateRecent", json!({})).unwrap().is_null());
|
||||
s.execute("comp.open", json!({"comp": main})).unwrap();
|
||||
// From Main: Other was active last, but Nested is the one in Main's hierarchy.
|
||||
s.execute("comp.activateRecent", json!({})).unwrap();
|
||||
assert_eq!(s.state.active_comp.map(|c| c.0), Some(nested));
|
||||
s.execute("comp.activateRecent", json!({})).unwrap();
|
||||
assert_eq!(s.state.active_comp.map(|c| c.0), Some(main));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframes_and_properties_deselect_but_layers_stay() {
|
||||
let (mut s, ids) = session([(0.0, 10.0); 3]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0]]})).unwrap();
|
||||
s.execute("prop.addKey", json!({"layer": ids[0], "path": "transform/opacity", "time": 1.0, "value": 50.0})).unwrap();
|
||||
s.execute("keys.selectAll", json!({})).unwrap();
|
||||
assert!(!s.state.selected_keys.is_empty());
|
||||
s.execute("keys.deselectAll", json!({})).unwrap();
|
||||
assert!(s.state.selected_keys.is_empty() && s.state.selected_props.is_empty());
|
||||
assert_eq!(s.state.selected_layers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_extends_through_the_stack() {
|
||||
let (mut s, ids) = session([(0.0, 10.0); 3]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0]]})).unwrap();
|
||||
s.execute("layer.extendSelectionNext", json!({})).unwrap();
|
||||
s.execute("layer.extendSelectionNext", json!({})).unwrap();
|
||||
let mut sel: Vec<u64> = s.state.selected_layers.iter().map(|l| l.0).collect();
|
||||
sel.sort();
|
||||
let mut all = ids.clone();
|
||||
all.sort();
|
||||
assert_eq!(sel, all);
|
||||
// At the end of the stack the selection stays.
|
||||
s.execute("layer.extendSelectionNext", json!({})).unwrap();
|
||||
assert_eq!(s.state.selected_layers.len(), 3);
|
||||
s.execute("layer.select", json!({"layers": [ids[2]]})).unwrap();
|
||||
s.execute("layer.extendSelectionPrevious", json!({})).unwrap();
|
||||
assert_eq!(s.state.selected_layers.len(), 2);
|
||||
assert!(s.state.selected_layers.iter().any(|l| l.0 == ids[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_move_to_the_comp_ends_and_by_ten_frames() {
|
||||
let (mut s, ids) = session([(1.0, 3.0), (2.0, 6.0), (0.0, 10.0)]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0], ids[1]]})).unwrap();
|
||||
s.execute("layer.moveInToStart", json!({})).unwrap();
|
||||
assert_eq!((span(&s, ids[0]), span(&s, ids[1])), ((0.0, 2.0), (0.0, 4.0)));
|
||||
s.execute("layer.moveOutToEnd", json!({})).unwrap();
|
||||
assert_eq!((span(&s, ids[0]), span(&s, ids[1])), ((8.0, 10.0), (6.0, 10.0)));
|
||||
s.execute("layer.moveEarlier10", json!({})).unwrap();
|
||||
let (a, b) = span(&s, ids[0]);
|
||||
assert!((a - (8.0 - 10.0 / 30.0)).abs() < 1e-9 && (b - (10.0 - 10.0 / 30.0)).abs() < 1e-9);
|
||||
s.execute("layer.moveLater10", json!({})).unwrap();
|
||||
assert_eq!(span(&s, ids[0]), (8.0, 10.0));
|
||||
s.execute("layer.moveLater", json!({})).unwrap();
|
||||
s.execute("layer.moveEarlier", json!({})).unwrap();
|
||||
assert_eq!(span(&s, ids[0]), (8.0, 10.0));
|
||||
// The unselected layer never moved.
|
||||
assert_eq!(span(&s, ids[2]), (0.0, 10.0));
|
||||
for (id, keys) in [
|
||||
("layer.moveEarlier", "Alt+PageUp"),
|
||||
("layer.moveLater", "Alt+PageDown"),
|
||||
("layer.moveEarlier10", "Alt+Shift+PageUp"),
|
||||
("layer.moveLater10", "Alt+Shift+PageDown"),
|
||||
] {
|
||||
assert_eq!(crate::find_command(id).and_then(|c| c.shortcut), Some(keys));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_and_out_points_stretch_to_the_current_time() {
|
||||
let (mut s, ids) = session([(2.0, 4.0), (0.0, 10.0), (0.0, 10.0)]);
|
||||
let stretch = |s: &Session| s.active_comp().unwrap().layers.iter().find(|l| l.id.0 == ids[0]).unwrap().stretch;
|
||||
s.execute("layer.select", json!({"layers": [ids[0]]})).unwrap();
|
||||
// In point to 1 s: the Out point holds, the layer is 3 s long at 150 %.
|
||||
s.execute("time.set", json!({"time": 1.0})).unwrap();
|
||||
s.execute("layer.stretchInToTime", json!({})).unwrap();
|
||||
assert_eq!(span(&s, ids[0]), (1.0, 4.0));
|
||||
assert!((stretch(&s) - 150.0).abs() < 1e-6);
|
||||
// Out point to 7 s: the In point holds, 6 s at 300 %.
|
||||
s.execute("time.set", json!({"time": 7.0})).unwrap();
|
||||
s.execute("layer.stretchOutToTime", json!({})).unwrap();
|
||||
assert_eq!(span(&s, ids[0]), (1.0, 7.0));
|
||||
assert!((stretch(&s) - 300.0).abs() < 1e-6);
|
||||
// A current time before the In point can't be the Out point: the layer is left alone.
|
||||
s.execute("time.set", json!({"time": 0.5})).unwrap();
|
||||
s.execute("layer.stretchOutToTime", json!({})).unwrap();
|
||||
assert_eq!(span(&s, ids[0]), (1.0, 7.0));
|
||||
assert!(s.execute("layer.timeStretch", json!({"to": "middle"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_are_stepped_through_and_wrap() {
|
||||
let (mut s, ids) = session([(0.0, 10.0); 3]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0]]})).unwrap();
|
||||
assert!(s.execute("layer.mask.selectNext", json!({})).is_err());
|
||||
for _ in 0..3 {
|
||||
s.execute("layer.addMask", json!({"shape": "rect"})).unwrap();
|
||||
}
|
||||
s.execute("keys.deselectAll", json!({})).unwrap();
|
||||
let step = |s: &mut Session, cmd: &str| s.execute(cmd, json!({})).unwrap()["index"].as_u64().unwrap();
|
||||
assert_eq!(step(&mut s, "layer.mask.selectNext"), 1);
|
||||
assert_eq!(step(&mut s, "layer.mask.selectNext"), 2);
|
||||
assert_eq!(step(&mut s, "layer.mask.selectNext"), 3);
|
||||
assert_eq!(step(&mut s, "layer.mask.selectNext"), 1);
|
||||
assert_eq!(step(&mut s, "layer.mask.selectPrevious"), 3);
|
||||
assert_eq!(s.state.selected_props.len(), 1);
|
||||
s.execute("keys.deselectAll", json!({})).unwrap();
|
||||
assert_eq!(step(&mut s, "layer.mask.selectPrevious"), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn casts_shadows_toggles_on_3d_layers_only() {
|
||||
let (mut s, ids) = session([(0.0, 10.0); 3]);
|
||||
s.execute("layer.select", json!({"layers": [ids[0], ids[1]]})).unwrap();
|
||||
assert!(s.execute("layer.castsShadows", json!({})).is_err());
|
||||
s.execute("layer.setSwitch", json!({"layers": [ids[0]], "switch": "threeD", "value": true})).unwrap();
|
||||
let before = s.execute("layer.castsShadows", json!({})).unwrap();
|
||||
assert_eq!(before["layers"], json!([ids[0]]));
|
||||
let after = s.execute("layer.castsShadows", json!({})).unwrap();
|
||||
assert_ne!(before["castsShadows"], after["castsShadows"]);
|
||||
assert_eq!(s.execute("layer.castsShadows", json!({"value": true})).unwrap()["castsShadows"], json!(true));
|
||||
}
|
||||
@@ -436,3 +436,13 @@ fn numeric_string_resolves_as_id() {
|
||||
let r = s.execute("layer.tree", json!({"layer": l.to_string(), "comp": cid.0.to_string()})).unwrap();
|
||||
assert_eq!(r["id"].as_u64(), Some(l), "{r}");
|
||||
}
|
||||
|
||||
/// Go to Work Area Start / End have After Effects' default keys (Shift+Home / Shift+End).
|
||||
#[test]
|
||||
fn work_area_navigation_has_after_effects_default_keys() {
|
||||
let s = Session::default();
|
||||
for (id, key) in [("time.workAreaStart", "Shift+Home"), ("time.workAreaEnd", "Shift+End")] {
|
||||
let b = s.shortcuts().find(id).unwrap_or_else(|| panic!("{id} is bindable"));
|
||||
assert_eq!(b.defaults, [key.to_string()], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,8 +597,10 @@ fn reset_gives_a_property_its_default() {
|
||||
assert_eq!(v(&s, "transform/anchor"), KV::Vec3([50.0, 50.0, 0.0]), "the solid's centre");
|
||||
assert_eq!(v(&s, "transform/position"), KV::Vec3([200.0, 150.0, 0.0]), "the comp's centre");
|
||||
assert_eq!(v(&s, "transform/scale"), KV::Vec3([100.0; 3]));
|
||||
assert_eq!(v(&s, "transform/rotation"), KV::Scalar(0.0));
|
||||
assert!(!prop(&s, l, "transform/rotation").is_animated());
|
||||
// Animated: the default becomes the key at the current time (0 s), the 1 s key stays (#1078).
|
||||
let rot = prop(&s, l, "transform/rotation");
|
||||
assert_eq!(rot.keys.len(), 2);
|
||||
assert_eq!(rot.value_at(effectcraft_time::Tick::ZERO), KV::Scalar(0.0));
|
||||
assert_eq!(v(&s, "transform/opacity"), KV::Scalar(100.0));
|
||||
assert!(prop(&s, l, "transform/opacity").expr.is_none());
|
||||
assert_eq!(v(&s, "effects/#1/blurriness"), blur);
|
||||
@@ -607,6 +609,31 @@ fn reset_gives_a_property_its_default() {
|
||||
assert_eq!(v(&s, "transform/opacity"), KV::Scalar(30.0));
|
||||
}
|
||||
|
||||
/// #1078: resetting an animated property keeps its keyframes and keys the default at the
|
||||
/// current time, as in After Effects; undo brings the old keys back.
|
||||
#[test]
|
||||
fn reset_keys_the_default_on_an_animated_property() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/scale", &[(0.0, json!([50, 50, 100])), (2.0, json!([150, 150, 100]))]);
|
||||
s.execute("time.set", json!({"time": 1})).unwrap();
|
||||
s.execute("prop.reset", json!({"layer": l, "path": "transform/scale"})).unwrap();
|
||||
let pr = prop(&s, l, "transform/scale");
|
||||
let at = |sec: f64| pr.value_at(effectcraft_time::Tick::from_seconds_f64(sec));
|
||||
assert_eq!(pr.keys.len(), 3, "the 0 s and 2 s keys stay, one is added at 1 s");
|
||||
assert_eq!(at(0.0), KV::Vec3([50.0, 50.0, 100.0]));
|
||||
assert_eq!(at(1.0), KV::Vec3([100.0; 3]));
|
||||
assert_eq!(at(2.0), KV::Vec3([150.0, 150.0, 100.0]));
|
||||
// On a key, the key takes the default.
|
||||
s.execute("time.set", json!({"time": 2})).unwrap();
|
||||
s.execute("prop.reset", json!({"layer": l, "path": "transform/scale"})).unwrap();
|
||||
let pr = prop(&s, l, "transform/scale");
|
||||
assert_eq!(pr.keys.len(), 3);
|
||||
assert_eq!(pr.value_at(effectcraft_time::Tick::from_seconds_f64(2.0)), KV::Vec3([100.0; 3]));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/scale").keys.len(), 2);
|
||||
}
|
||||
|
||||
/// #363: dropped on one of the target's values the pick whip picks that dimension
|
||||
/// (`position[0]`), as in After Effects; a multi-dimension property follows it on every axis.
|
||||
#[test]
|
||||
@@ -750,6 +777,31 @@ fn reveal_shortcuts_take_in_time_remap() {
|
||||
}
|
||||
}
|
||||
|
||||
/// U (and the animation reveal) still show Time Remap after its keys are gone: enabling
|
||||
/// remapping is itself the modification, so a keyless remap must not vanish from U (#990).
|
||||
#[test]
|
||||
fn reveal_shortcuts_take_in_keyless_time_remap() {
|
||||
let (mut s, l) = precomp_setup();
|
||||
let revealed = |s: &mut Session, kind: &str| -> Vec<u64> {
|
||||
let r = s.execute("anim.reveal", json!({"kind": kind})).unwrap();
|
||||
r["props"].as_array().unwrap().iter().filter(|p| p["layer"] == l).filter_map(|p| p["prop"].as_u64()).collect()
|
||||
};
|
||||
s.execute("layer.enableTimeRemap", json!({})).unwrap();
|
||||
let uid = prop(&s, l, "timeRemap").uid;
|
||||
assert_eq!(prop(&s, l, "timeRemap").keys.len(), 2);
|
||||
// Delete both keys one at a time; remapping stays enabled.
|
||||
for _ in 0..2 {
|
||||
let t = prop(&s, l, "timeRemap").keys[0].time.seconds();
|
||||
s.execute("keys.select", json!({"keys": [{"layer": l, "prop": uid, "time": t}]})).unwrap();
|
||||
s.execute("edit.clear", json!({})).unwrap();
|
||||
}
|
||||
let tr = prop(&s, l, "timeRemap");
|
||||
assert!(tr.keys.is_empty(), "remapping is still enabled, with no keys");
|
||||
for kind in ["keyframes", "animation", "modified"] {
|
||||
assert_eq!(revealed(&mut s, kind), vec![uid], "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// UU on a layer nothing was changed on shows nothing, whatever its kind: cameras, lights, text
|
||||
/// and nulls have their own Transform defaults, and Separate Dimensions keeps the comp centre.
|
||||
#[test]
|
||||
@@ -814,6 +866,27 @@ fn modified_reveal_takes_in_options_and_layer_styles() {
|
||||
assert_eq!(modified(&mut s, light), ["/lightOptions/intensity"]);
|
||||
}
|
||||
|
||||
/// UU shows the parameters of an effect that differ from a new instance's, not the whole effect:
|
||||
/// a just-applied effect shows nothing, and a reset parameter goes again.
|
||||
#[test]
|
||||
fn modified_reveal_shows_changed_effect_parameters_only() {
|
||||
let (mut s, l) = setup();
|
||||
s.execute("layer.select", json!({"layers": [l]})).unwrap();
|
||||
s.execute("effect.apply", json!({"effect": "ec.blur.gaussian"})).unwrap();
|
||||
let modified = |s: &mut Session| -> Vec<String> {
|
||||
let r = s.execute("anim.reveal", json!({"kind": "modified"})).unwrap();
|
||||
r["props"].as_array().unwrap().iter().filter_map(|p| p["prop"].as_u64()).map(|u| path_of(s, l, u)).collect()
|
||||
};
|
||||
assert!(modified(&mut s).is_empty(), "{:?}", modified(&mut s));
|
||||
s.execute("prop.set", json!({"layer": l, "path": "effects/#1/blurriness", "value": 12})).unwrap();
|
||||
assert_eq!(modified(&mut s), ["/effects/ec.blur.gaussian/blurriness"]);
|
||||
// Keyframed at its default value: animated, so still shown.
|
||||
s.execute("prop.set", json!({"layer": l, "path": "effects/#1/blurriness", "value": 0})).unwrap();
|
||||
assert!(modified(&mut s).is_empty(), "{:?}", modified(&mut s));
|
||||
s.execute("prop.toggleAnimation", json!({"layer": l, "path": "effects/#1/blurriness"})).unwrap();
|
||||
assert_eq!(modified(&mut s), ["/effects/ec.blur.gaussian/blurriness"]);
|
||||
}
|
||||
|
||||
/// Enable Time Remapping on a layer extended past its source's end (its last frame frozen) puts
|
||||
/// the end key at the source's end, not at the extended out point (#290).
|
||||
#[test]
|
||||
|
||||
@@ -283,3 +283,57 @@ fn paste_svg_rejects_text_that_is_not_usable_svg() {
|
||||
assert!(s.execute_checked("edit.pasteSvg", json!({})).is_err());
|
||||
assert_eq!(s.active_comp().unwrap().layers.len(), 1, "nothing pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_with_thousands_of_nested_groups_imports_on_a_small_stack() {
|
||||
let mut d = WDoc::new(8, 8);
|
||||
let n = 5000;
|
||||
d.layers = (0..n).map(|_| WLayer::group_end()).collect();
|
||||
for i in 0..n {
|
||||
d.layers.push(WLayer::solid(&format!("L{i}"), Rect::new(0, 0, 2, 2), [1.0; 4]));
|
||||
d.layers.push(WLayer::group(&format!("G{i}"), true, *b"norm"));
|
||||
}
|
||||
let path = tmp("nested.psd");
|
||||
std::fs::write(&path, effectcraft_psd::write::write(&d)).unwrap();
|
||||
let h = std::thread::Builder::new()
|
||||
.stack_size(2 << 20)
|
||||
.spawn(move || {
|
||||
let mut s = Session::default();
|
||||
let r = s.execute_checked("file.import", json!({"paths": [path], "importAs": "composition"})).unwrap();
|
||||
let warned = r["errors"].as_array().is_some_and(|e| e.len() == 1 && e[0].as_str().is_some_and(|m| m.contains("flattened")));
|
||||
// 64 nested group comps plus the root comp.
|
||||
let comps = s.project.items.values().filter(|i| matches!(i.kind, ItemKind::Comp(_))).count();
|
||||
(warned, comps)
|
||||
})
|
||||
.unwrap();
|
||||
let (warned, comps) = h.join().unwrap();
|
||||
assert_eq!(comps, 65);
|
||||
assert!(warned);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_with_damaged_layer_section_imports_the_flattened_image() {
|
||||
let mut d = WDoc::new(30, 20);
|
||||
d.layers = vec![
|
||||
WLayer::solid("Back", Rect::new(0, 0, 30, 20), [0.0, 0.0, 1.0, 1.0]),
|
||||
WLayer::solid("Box", Rect::new(2, 2, 8, 8), [1.0, 0.0, 0.0, 1.0]).with_blend(b"mul "),
|
||||
];
|
||||
let mut bytes = write(&d);
|
||||
let at = bytes.windows(8).position(|w| w == b"8BIMmul ").unwrap();
|
||||
bytes[at] = b'X';
|
||||
let path = tmp("damaged.psd");
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let mut s = Session::default();
|
||||
let r = s.execute_checked("file.import", json!({"paths": [path], "importAs": "composition"})).unwrap();
|
||||
// Photoshop import warnings are reported with the import's `errors` (as for adjustment layers).
|
||||
let warnings = r["errors"].as_array().unwrap();
|
||||
assert_eq!(warnings.len(), 1, "{r}");
|
||||
assert!(warnings[0].as_str().unwrap().contains("Layers could not be read"), "{r}");
|
||||
let cid = effectcraft_project::ItemId(r["comps"][0].as_u64().unwrap());
|
||||
let c = s.project.comp(cid).unwrap().clone();
|
||||
assert_eq!((c.width, c.height), (30, 20));
|
||||
assert_eq!(c.layers.len(), 1);
|
||||
let LayerSource::Footage { item } = c.layers[0].source else { panic!("footage") };
|
||||
let ItemKind::Footage(f) = &s.project.item(item).unwrap().kind else { panic!() };
|
||||
assert!(f.layer.is_none(), "the merged image, not a Photoshop layer");
|
||||
}
|
||||
|
||||
@@ -335,11 +335,8 @@ fn targets_in(ctx: &EvalCtx, exclude: &[LayerId], opts: SnapOptions) -> Vec<Snap
|
||||
}
|
||||
if opts.guides {
|
||||
for g in &comp.guides {
|
||||
out.push(if g.vertical {
|
||||
SnapTarget::vline(g.position, PRI_GUIDE, SnapSource::Guide)
|
||||
} else {
|
||||
SnapTarget::hline(g.position, PRI_GUIDE, SnapSource::Guide)
|
||||
});
|
||||
let pos = g.px(comp.width, comp.height);
|
||||
out.push(if g.vertical { SnapTarget::vline(pos, PRI_GUIDE, SnapSource::Guide) } else { SnapTarget::hline(pos, PRI_GUIDE, SnapSource::Guide) });
|
||||
}
|
||||
}
|
||||
if opts.grid && opts.grid_spacing >= 1.0 {
|
||||
|
||||
@@ -383,6 +383,29 @@ fn parenting_static_orientation_handles_signed_uniform_scale_and_gimbal_order()
|
||||
assert!(max_corners < 1e-8 && max_pixels < 2e-5, "static uniform pose must use the existing Euler order including signed scale and gimbal angles");
|
||||
}
|
||||
|
||||
/// A static Orientation just off gimbal lock (Y within 1e-6 degrees of ±90) keeps its world pose
|
||||
/// under a uniform parent. Recovering Euler angles from the matrix must not lose precision there.
|
||||
#[test]
|
||||
fn parenting_static_orientation_is_exact_just_off_gimbal_lock() {
|
||||
let mut max_corners = 0.0f64;
|
||||
for factor in [120.0, -120.0] {
|
||||
for y in [90.0 - 1e-6, -90.0 + 1e-6] {
|
||||
let (mut s, p, c) = fixture(true, true);
|
||||
set(&mut s, p, "transform/orientation", json!([0.0, 0.0, 0.0]));
|
||||
set(&mut s, p, "transform/rotationX", json!(0.0));
|
||||
set(&mut s, p, "transform/rotationY", json!(0.0));
|
||||
set(&mut s, p, "transform/rotation", json!(42.0));
|
||||
set(&mut s, p, "transform/scale", json!([factor, factor, factor]));
|
||||
set(&mut s, c, "transform/orientation", json!([23.0, y, -37.0]));
|
||||
set(&mut s, c, "transform/scale", json!([200.0, 160.0, 150.0]));
|
||||
let before = world(&s, c, Tick::ZERO);
|
||||
parent(&mut s, c, Some(p), true);
|
||||
max_corners = max_corners.max(displacement(before, world(&s, c, Tick::ZERO)));
|
||||
}
|
||||
}
|
||||
assert!(max_corners < 1e-9, "a static Orientation near gimbal lock must keep its world pose: corners {max_corners}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parenting_animated_orientation_and_nonuniform_parent_keep_authored_pose_boundary() {
|
||||
for animated in [true, false] {
|
||||
@@ -462,3 +485,41 @@ fn parenting_uniform_parent_preserves_eased_position_at_quarter_times_and_undo()
|
||||
}
|
||||
assert!(maximum_error < 1e-8, "3D uniform parent compensation must preserve eased Position at quarter and three-quarter times");
|
||||
}
|
||||
|
||||
/// Parenting a two-node camera to a default null keeps its world frame (eye, forward, down):
|
||||
/// Position and Point of Interest are re-expressed in the null's space (#1010, #1020).
|
||||
#[test]
|
||||
fn parenting_camera_to_default_null_preserves_framing() {
|
||||
use effectcraft_engine::render::three_d::camera::layer_frame;
|
||||
let mut s = Session::default();
|
||||
command(&mut s, "comp.new", json!({"name":"Camera","width":640,"height":360,"duration":2,"frameRate":24}));
|
||||
let cam = command(&mut s, "layer.newCamera", json!({"name":"Camera 1"}))["layer"].as_u64().unwrap();
|
||||
let null = command(&mut s, "layer.newNull", json!({"name":"Null 1"}))["layer"].as_u64().unwrap();
|
||||
let frame = |s: &Session| {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let c = s.project.comp(cid).unwrap();
|
||||
let ctx = EvalCtx::new(&s.project, cid, c, Tick::ZERO);
|
||||
layer_frame(&ctx, c.layer(LayerId(cam)).unwrap())
|
||||
};
|
||||
let authored = |s: &Session, path: &str| {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.project.comp(cid).unwrap().layer(LayerId(cam)).unwrap().props.prop(path).unwrap().value.as_vec3()
|
||||
};
|
||||
let (eye0, fwd0, down0) = frame(&s);
|
||||
let (pos0, poi0) = (authored(&s, "transform/position"), authored(&s, "transform/poi"));
|
||||
let frame_error = |(a0, b0, c0): (Vec3, Vec3, Vec3), (a1, b1, c1): (Vec3, Vec3, Vec3)| {
|
||||
[(a0 - a1).length(), (b0 - b1).length(), (c0 - c1).length()].into_iter().fold(0.0, f64::max)
|
||||
};
|
||||
let undo = s.history.undo.len();
|
||||
parent(&mut s, cam, Some(null), true);
|
||||
assert!(frame_error(frame(&s), (eye0, fwd0, down0)) < 1e-9, "the camera frame must not move");
|
||||
// Compensation rewrote the authored values, not just the parent pointer.
|
||||
assert!((authored(&s, "transform/position")[0] - pos0[0]).abs() > 1.0, "position is re-expressed in the null's space");
|
||||
assert!((authored(&s, "transform/poi")[0] - poi0[0]).abs() > 1.0, "point of interest follows it");
|
||||
assert_eq!(s.history.undo.len(), undo + 1, "parent compensation is one undo action");
|
||||
// Unparenting restores the authored transform and the same frame.
|
||||
parent(&mut s, cam, None, true);
|
||||
assert!(frame_error(frame(&s), (eye0, fwd0, down0)) < 1e-9);
|
||||
assert_eq!(authored(&s, "transform/position"), pos0, "unparenting restores position");
|
||||
assert_eq!(authored(&s, "transform/poi"), poi0, "unparenting restores point of interest");
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-rustmotion-common = { workspace = true }
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
effectcraft-raster = { workspace = true }
|
||||
|
||||
@@ -28,10 +28,12 @@
|
||||
//! (plan ADR 0001); nothing outside this crate touches them.
|
||||
//!
|
||||
//! H.264 requires even dimensions: odd output sizes are cropped by one pixel (padded when the
|
||||
//! output is a single pixel wide/high).
|
||||
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use effectcraft_rustmotion_common::APP_NAME;
|
||||
|
||||
mod encode;
|
||||
mod hevc_av1;
|
||||
mod out;
|
||||
|
||||
@@ -15,6 +15,61 @@ use web_time::Instant;
|
||||
|
||||
use crate::{Job, RenderQuality, out};
|
||||
|
||||
/// GPU frames rendered at once by default: one, as the export scheduler's single GPU worker
|
||||
/// renders image sequences (#898: frames in flight beyond one only with asynchronous YUV
|
||||
/// readback). Measured on the #879 project at 1080p on an 8 GB card: 6.3 GB peak with one,
|
||||
/// 7.0 to 7.8 GB with two, and the whole card with three, where main fell back to the CPU.
|
||||
/// Not sized from free VRAM: the GPU backend reports no free or total device memory on every
|
||||
/// platform, so a portable estimate is not available here.
|
||||
pub(crate) const GPU_INFLIGHT_DEFAULT: usize = 1;
|
||||
/// Overrides [`GPU_INFLIGHT_DEFAULT`]: a whole number of frames, at least 1.
|
||||
pub(crate) const GPU_INFLIGHT_ENV: &str = "EFFECTCRAFT_GPU_INFLIGHT";
|
||||
|
||||
/// GPU frames in flight from the `EFFECTCRAFT_GPU_INFLIGHT` value: a positive whole number, or
|
||||
/// the default (with a warning when a value was given) when it is 0, negative, not a number or
|
||||
/// too large.
|
||||
pub(crate) fn gpu_inflight(var: Option<&str>) -> usize {
|
||||
let Some(v) = var else { return GPU_INFLIGHT_DEFAULT };
|
||||
match v.trim().parse::<usize>() {
|
||||
Ok(n) if n >= 1 => n,
|
||||
_ => {
|
||||
log::warn!(target: "effectcraft_export", "{GPU_INFLIGHT_ENV}={v:?} is not a whole number of frames of at least 1: using {GPU_INFLIGHT_DEFAULT}");
|
||||
GPU_INFLIGHT_DEFAULT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `render` then `encode` over the frames `ks`, results in `ks` order.
|
||||
///
|
||||
/// Without `cap` every frame renders and encodes in one parallel batch (the CPU path, as
|
||||
/// before). With `cap` (GPU frames in flight), the frames go in windows of
|
||||
/// `max(cap, threads)`: each window renders in consecutive chunks of `cap` (at most `cap`
|
||||
/// renders at once), then encodes in parallel, so only the render is serialised and at most
|
||||
/// one window of rendered images is held in memory. Chunks hold no lock or slot, so a failing
|
||||
/// or panicking frame cannot leak one, and nested parallelism (or a single thread) cannot
|
||||
/// deadlock.
|
||||
pub(crate) fn map_frames<I: Send, T: Send>(
|
||||
ks: Vec<u64>,
|
||||
cap: Option<usize>,
|
||||
render: impl Fn(u64) -> I + Sync + Send,
|
||||
encode: impl Fn(u64, I) -> T + Sync + Send,
|
||||
) -> Vec<T> {
|
||||
use rayon::prelude::*;
|
||||
let Some(n) = cap.map(|n| n.max(1)) else {
|
||||
return ks.into_par_iter().map(|k| encode(k, render(k))).collect();
|
||||
};
|
||||
let window = n.max(rayon::current_num_threads());
|
||||
let mut out = Vec::with_capacity(ks.len());
|
||||
for win in ks.chunks(window) {
|
||||
let mut imgs = Vec::with_capacity(win.len());
|
||||
for chunk in win.chunks(n) {
|
||||
imgs.par_extend(chunk.par_iter().map(|&k| render(k)));
|
||||
}
|
||||
out.par_extend(win.par_iter().copied().zip(imgs.into_par_iter()).map(|(k, img)| encode(k, img)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A job being exported: the job, the project with the Render Settings overrides applied, the
|
||||
/// job's layer cache and per-frame timing for the render log.
|
||||
pub(crate) struct Cx<'a> {
|
||||
@@ -132,8 +187,15 @@ impl<'a> Cx<'a> {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
use rayon::prelude::*;
|
||||
ks.into_par_iter().map(|k| f(k, self.frame(comp, k))).collect()
|
||||
map_frames(ks, self.gpu_cap(), |k| self.frame(comp, k), f)
|
||||
}
|
||||
|
||||
/// GPU frames rendered at once (#879), decided once per batch: with a GPU accelerator every
|
||||
/// frame in flight holds its own working textures, so a whole batch rendered at once can
|
||||
/// exhaust VRAM (or shared memory, which crashes instead of falling back). `None` when the
|
||||
/// frames render on the CPU: no accelerator, or a Software Only project.
|
||||
fn gpu_cap(&self) -> Option<usize> {
|
||||
(self.job.accel.is_some() && self.project.settings.gpu_acceleration).then(|| gpu_inflight(std::env::var(GPU_INFLIGHT_ENV).ok().as_deref()))
|
||||
}
|
||||
|
||||
/// Output frame `i`: sampled (fields, pulldown), at the colour depth, cropped and resized.
|
||||
@@ -367,6 +429,178 @@ fn premultiplied8(img: &Image) -> Vec<u8> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// Frames `0..n` through [`map_frames`] with `cap`, recording the most running at once.
|
||||
fn run_capped(n: u64, cap: Option<usize>) -> (Vec<u64>, usize) {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let (now, max) = (AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let out = map_frames(
|
||||
(0..n).collect(),
|
||||
cap,
|
||||
|k| {
|
||||
let c = now.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
max.fetch_max(c, Ordering::SeqCst);
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
now.fetch_sub(1, Ordering::SeqCst);
|
||||
k
|
||||
},
|
||||
|k, img| {
|
||||
assert_eq!(k, img);
|
||||
k * 10
|
||||
},
|
||||
);
|
||||
(out, max.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capped_frames_keep_their_order() {
|
||||
let want: Vec<u64> = (0..40).map(|k| k * 10).collect();
|
||||
for cap in [None, Some(1), Some(3), Some(7)] {
|
||||
assert_eq!(run_capped(40, cap).0, want, "cap {cap:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_frames_in_flight_respect_the_cap() {
|
||||
// #879: every frame of a batch rendered on the GPU at once and exhausted VRAM.
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap();
|
||||
pool.install(|| {
|
||||
for cap in [1, 2, 3] {
|
||||
let (out, max) = run_capped(30, Some(cap));
|
||||
assert_eq!(out.len(), 30);
|
||||
assert!(max <= cap, "cap {cap}: {max} frames ran at once");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_above_the_frame_count_renders_them_all() {
|
||||
let (out, max) = run_capped(2, Some(8));
|
||||
assert_eq!(out, vec![0, 10]);
|
||||
assert!(max <= 2);
|
||||
assert!(run_capped(0, Some(3)).0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_one_on_a_single_thread_does_not_deadlock() {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
|
||||
let (out, max) = pool.install(|| run_capped(10, Some(1)));
|
||||
assert_eq!(out.len(), 10);
|
||||
assert_eq!(max, 1);
|
||||
// Nested parallelism inside a frame (as the renderer has) on one thread.
|
||||
let out = pool.install(|| map_frames((0..6).collect(), Some(2), |k| (0..4u64).into_par_iter().map(|i| i + k).sum::<u64>(), |_, v| v));
|
||||
assert_eq!(out, (0..6).map(|k| 6 + 4 * k).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_frame_does_not_hold_up_the_rest() {
|
||||
let out = map_frames((0..9).collect(), Some(1), |k| if k == 3 { Err(k) } else { Ok(k) }, |_, r| r);
|
||||
assert_eq!(out.iter().filter(|r| r.is_err()).count(), 1);
|
||||
assert_eq!(out.len(), 9);
|
||||
assert_eq!(out[8], Ok(8));
|
||||
// A panicking frame propagates once and leaves no slot behind: the next batch runs.
|
||||
let r = std::panic::catch_unwind(|| map_frames((0..6).collect(), Some(2), |k| if k == 2 { panic!("frame {k}") } else { k }, |_, k| k));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(run_capped(6, Some(2)).0.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_is_not_capped_with_the_render() {
|
||||
// Only the GPU render is serialised: a window of frames encodes in parallel.
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
|
||||
let (now, max) = (AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let out = pool.install(|| {
|
||||
map_frames(
|
||||
(0..8).collect(),
|
||||
Some(1),
|
||||
|k| k,
|
||||
|k, _| {
|
||||
let c = now.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
max.fetch_max(c, Ordering::SeqCst);
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
now.fetch_sub(1, Ordering::SeqCst);
|
||||
k
|
||||
},
|
||||
)
|
||||
});
|
||||
assert_eq!(out, (0..8).collect::<Vec<_>>());
|
||||
assert!(max.load(Ordering::SeqCst) > 1, "encodes ran one at a time");
|
||||
}
|
||||
|
||||
/// An accelerator that renders nothing itself (the tests only check whether frames are capped).
|
||||
struct NoAccel;
|
||||
impl effectcraft_render::Accelerator for NoAccel {
|
||||
fn name(&self) -> String {
|
||||
"none".into()
|
||||
}
|
||||
fn comp_frame(&self, _r: &Renderer, _comp: effectcraft_project::ItemId, _t: Tick) -> Option<Image> {
|
||||
None
|
||||
}
|
||||
fn supports_effect(&self, _id: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn effects(&self, _chain: &[effectcraft_render::FxStep], _buf: &effectcraft_effects::Buf, _levels: Option<f32>) -> Option<effectcraft_effects::Buf> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn software_only_projects_are_not_capped() {
|
||||
// Review of #879: an accelerator alone capped Software Only projects, which render on the CPU.
|
||||
use effectcraft_project::render_queue::{OutputFormat, OutputModule, RenderSettings};
|
||||
use effectcraft_render::NoFootage;
|
||||
let (settings, output) = (RenderSettings::default(), OutputModule::for_format(OutputFormat::PngSequence));
|
||||
let accel = NoAccel;
|
||||
for (gpu, want) in [(false, None), (true, Some(GPU_INFLIGHT_DEFAULT))] {
|
||||
let mut p = Project::default();
|
||||
p.settings.gpu_acceleration = gpu;
|
||||
let job = Job {
|
||||
project: &p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: Some(&accel),
|
||||
comp: effectcraft_project::ItemId(0),
|
||||
settings: &settings,
|
||||
output: &output,
|
||||
path: "/c/f_[#####].png",
|
||||
sink: None,
|
||||
nested_switches: true,
|
||||
options: Default::default(),
|
||||
};
|
||||
if std::env::var_os(GPU_INFLIGHT_ENV).is_none() {
|
||||
assert_eq!(Cx::new(&job).gpu_cap(), want, "gpu acceleration {gpu}");
|
||||
} else {
|
||||
assert_eq!(Cx::new(&job).gpu_cap().is_some(), gpu);
|
||||
}
|
||||
}
|
||||
let p = Project::default();
|
||||
let job = Job {
|
||||
project: &p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: effectcraft_project::ItemId(0),
|
||||
settings: &settings,
|
||||
output: &output,
|
||||
path: "/c/f_[#####].png",
|
||||
sink: None,
|
||||
nested_switches: true,
|
||||
options: Default::default(),
|
||||
};
|
||||
assert_eq!(Cx::new(&job).gpu_cap(), None, "no accelerator");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_inflight_override_is_a_positive_number_or_the_default() {
|
||||
assert_eq!(gpu_inflight(None), GPU_INFLIGHT_DEFAULT);
|
||||
assert_eq!(gpu_inflight(Some("3")), 3);
|
||||
assert_eq!(gpu_inflight(Some(" 5 ")), 5);
|
||||
for bad in ["0", "", "-2", "three", "2.5", "99999999999999999999999"] {
|
||||
assert_eq!(gpu_inflight(Some(bad)), GPU_INFLIGHT_DEFAULT, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_render_once_per_job() {
|
||||
|
||||
@@ -182,8 +182,8 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
|
||||
let mut info = vec![];
|
||||
el_uint(&mut info, 0x2AD7B1, 1_000_000);
|
||||
el_float(&mut info, 0x4489, duration_ms);
|
||||
el_str(&mut info, 0x4D80, "EffectCraft");
|
||||
el_str(&mut info, 0x5741, "EffectCraft");
|
||||
el_str(&mut info, 0x4D80, crate::APP_NAME);
|
||||
el_str(&mut info, 0x5741, crate::APP_NAME);
|
||||
el(&mut head, INFO, &info);
|
||||
let mut tracks = vec![];
|
||||
let mut v = vec![];
|
||||
|
||||
@@ -69,8 +69,8 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
|
||||
let mut info = vec![];
|
||||
el_uint(&mut info, 0x2AD7B1, 1_000_000);
|
||||
el_float(&mut info, 0x4489, duration_ms);
|
||||
el_str(&mut info, 0x4D80, "EffectCraft");
|
||||
el_str(&mut info, 0x5741, "EffectCraft");
|
||||
el_str(&mut info, 0x4D80, crate::APP_NAME);
|
||||
el_str(&mut info, 0x5741, crate::APP_NAME);
|
||||
el(&mut head, INFO, &info);
|
||||
let mut tracks = vec![];
|
||||
let mut v = vec![];
|
||||
|
||||
@@ -63,6 +63,10 @@ pub enum Req {
|
||||
Sample { comp: u64, layer: u64, x: Secs, y: Secs, rx: Secs, ry: Secs, post: bool, t: Secs },
|
||||
/// `thisProject`: `[bitsPerChannel, linearBlending, workingSpace]`.
|
||||
Project,
|
||||
/// A layer's source item (AE's `Layer.source`): `[kind, id, name, width, height, duration,
|
||||
/// frameDuration, pixelAspect]`, kind `"comp"` (id = the precomp's composition) or `"footage"`
|
||||
/// (footage, solids and models), or null for layers without an item (text, shape, null…).
|
||||
SourceInfo { comp: u64, layer: u64 },
|
||||
}
|
||||
|
||||
/// Parse CSV/TSV text (RFC 4180 quoting) into rows of cells.
|
||||
@@ -457,6 +461,28 @@ impl<'a> Resolver<'a> {
|
||||
Resp::Bool(project.settings.blend_linear || project.settings.linearize),
|
||||
Resp::Str(project.settings.working_space.map(|w| format!("{w:?}")).unwrap_or_default()),
|
||||
]),
|
||||
Req::SourceInfo { comp, layer } => {
|
||||
let c = self.comp(*comp)?;
|
||||
let l = self.layer(*comp, *layer)?;
|
||||
let it = project.item(l.source.item()?)?;
|
||||
let (kind, aspect, frame, duration) = match &it.kind {
|
||||
ItemKind::Comp(nc) => ("comp", nc.pixel_aspect, nc.frame_duration().seconds(), nc.duration.seconds()),
|
||||
ItemKind::Footage(f) => ("footage", f.pixel_aspect, f.frame_rate.frame_duration().seconds(), f.duration.seconds()),
|
||||
ItemKind::Solid(s) => ("footage", s.pixel_aspect, c.frame_duration().seconds(), c.duration.seconds()),
|
||||
ItemKind::Folder => return None,
|
||||
};
|
||||
let (w, h) = it.dimensions().unwrap_or((0, 0));
|
||||
Resp::List(vec![
|
||||
Resp::Str(kind.into()),
|
||||
Resp::Num(it.id.0 as f64),
|
||||
Resp::Str(it.name.clone()),
|
||||
Resp::Num(w as f64),
|
||||
Resp::Num(h as f64),
|
||||
Resp::Num(duration),
|
||||
Resp::Num(frame),
|
||||
Resp::Num(aspect),
|
||||
])
|
||||
}
|
||||
Req::Sample { comp, layer, x, y, rx, ry, post, t } => {
|
||||
let l = self.layer(*comp, *layer)?;
|
||||
let f = |b: &Secs| f64::from_bits(*b);
|
||||
|
||||
@@ -18,7 +18,7 @@ var selectorValue = [100, 100, 100];
|
||||
|
||||
// Request ops (must match runtime.rs).
|
||||
var __COMP = 0, __COMPNAME = 1, __LAYER = 2, __LINFO = 3, __CHILD = 4, __PINFO = 5, __VALUE = 6, __XFORM = 7, __RECT = 8, __MARKERS = 9, __DOC = 10;
|
||||
var __FOOT = 11, __FDATA = 12, __SAMPLE = 13, __PROJ = 14;
|
||||
var __FOOT = 11, __FDATA = 12, __SAMPLE = 13, __PROJ = 14, __SOURCE = 15;
|
||||
|
||||
function __begin(t, v, c, l, path, uid, idx, fd, ti, tt, sv) {
|
||||
time = t;
|
||||
@@ -569,6 +569,14 @@ Layer.prototype = {
|
||||
get enabled() { return this.__info[11]; },
|
||||
get active() { return this.__info[11] && time >= this.inPoint && time < this.outPoint; },
|
||||
get containingComp() { return new Comp(this.__c); },
|
||||
// The source item (AE's Layer.source): a Comp for a precomp layer, a Footage for footage, solid
|
||||
// and model layers, null for text, shape, null, camera and light layers (#809).
|
||||
get source() {
|
||||
var s = __h(__SOURCE, this.__c, this.__l);
|
||||
if (s === null) return null;
|
||||
if (s[0] === 'comp') return new Comp(s[1]);
|
||||
return new Footage([s[2], s[3], s[4], s[5], s[6], s[7], s[0], null, null]);
|
||||
},
|
||||
__group: function (k) {
|
||||
var g = __child(this.__c, this.__l, '', k);
|
||||
if (g === undefined) __err('Layer "' + this.name + '" has no property "' + k + '"');
|
||||
@@ -810,10 +818,18 @@ Prop.prototype = {
|
||||
|
||||
var __propHandler = {
|
||||
get: function (t, k) {
|
||||
if (typeof k !== 'string' || k in t) return t[k];
|
||||
if (typeof k !== 'string') return t[k];
|
||||
// A layer-valued property (a Layer Control's Layer) is named as its layer (#809).
|
||||
if (k === 'name' && t.__info[2] === 'layer') {
|
||||
var lv = t.value;
|
||||
if (lv !== null && lv !== undefined && lv.__isLayer) return lv.name;
|
||||
}
|
||||
if (k in t) return t[k];
|
||||
var v = t.value;
|
||||
if (v === null || v === undefined) return undefined;
|
||||
var x = v[k];
|
||||
// Property groups are callable proxies: hand them over as they are, not bound like methods (#809).
|
||||
if (x !== null && x !== undefined && x.__isGroup) return x;
|
||||
return typeof x === 'function' ? x.bind(v) : x;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -185,6 +185,7 @@ fn native_host(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsV
|
||||
t: secs(num(args, 8, ctx)?),
|
||||
},
|
||||
14 => Req::Project,
|
||||
15 => Req::SourceInfo { comp: id(args, 1, ctx)?, layer: id(args, 2, ctx)? },
|
||||
_ => return Err(JsNativeError::typ().with_message("unknown host request").into()),
|
||||
};
|
||||
let found = FRAMES.with(|f| {
|
||||
|
||||
@@ -1251,3 +1251,37 @@ fn pending_text_style_baseline_setters_are_visible_to_expression_getters() {
|
||||
assert_eq!(x.num("thisComp.layer('Title').text.sourceText.style.setBaselineOption('superscript').isSuperscript ? 1 : 0", 0.0), 1.0);
|
||||
assert_eq!(x.text("var s = text.sourceText.style.setSuperscript(true); s.setText(s.isSuperscript ? 'super' : 'normal')", 0.0), "super");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_source_is_the_layers_source_item() {
|
||||
let mut f = fx();
|
||||
// A solid's source is an item of the solid's size and name (#809).
|
||||
assert_close!(f.num("thisComp.layer('A').source.width", 0.0), 20.0);
|
||||
assert_close!(f.num("thisComp.layer('A').source.height", 0.0), 20.0);
|
||||
assert_close!(f.num("thisComp.layer('A').source.name == 'A' ? 1 : 0", 0.0), 1.0);
|
||||
// Text and shape layers have no source item.
|
||||
assert_close!(f.num("thisComp.layer('Title').source == null ? 1 : 0", 0.0), 1.0);
|
||||
// A precomp layer's source is its composition.
|
||||
let main = f.p.comp(f.cid).unwrap().clone();
|
||||
let other = f.p.items.values().find(|i| i.name == "Other").unwrap().id;
|
||||
let pre = build::layer(&mut f.p, &main, "Pre", LayerSource::Comp { item: other }, (64, 32), None);
|
||||
f.p.comp_mut(f.cid).unwrap().layers.push(pre);
|
||||
assert_close!(f.num("thisComp.layer('Pre').source.width", 0.0), 64.0);
|
||||
assert_close!(f.num("thisComp.layer('Pre').source.numLayers", 0.0), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_control_property_stands_for_its_layer() {
|
||||
let mut f = fx();
|
||||
// Layer A gets a Layer Control ("Map") that points at layer B (#809).
|
||||
let spec = effectcraft_effects::find("ec.control.layer").unwrap();
|
||||
let mut map = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Map", [20.0, 20.0]));
|
||||
map.prop_mut("layer").unwrap().value = Value::Layer(Some(f.b.0));
|
||||
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(map.into());
|
||||
// effect("Map")(1) is the layer itself: its name, index, transform and value.
|
||||
assert_close!(f.num("effect('Map')(1).name == 'B' ? 1 : 0", 0.0), 1.0);
|
||||
assert_close!(f.num("effect('Map')(1).index", 0.0), 2.0);
|
||||
assert_close!(f.num("effect('Map')(1).transform.position[0]", 0.0), 100.0);
|
||||
assert_close!(f.num("effect('Map')(1).transform.scale[0]", 0.0), 100.0);
|
||||
assert_close!(f.num("effect('Map')(1).value.name == 'B' ? 1 : 0", 0.0), 1.0);
|
||||
}
|
||||
|
||||
+84
-14
@@ -37,7 +37,7 @@ const EXT_ENTRIES: &[&str] = &["classic3d"];
|
||||
/// 8/16 bpc are emulated by clamping and quantising, as on the CPU).
|
||||
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
|
||||
|
||||
/// Uploaded layer buffers kept on the GPU (bytes).
|
||||
/// Uploaded layer buffers kept on the GPU by default (bytes; [`GpuContext::set_upload_budget`]).
|
||||
const UPLOAD_BUDGET: usize = 1536 << 20;
|
||||
|
||||
/// Working textures kept for reuse once their last image is dropped (bytes).
|
||||
@@ -71,6 +71,8 @@ impl GpuImage {
|
||||
struct Lease {
|
||||
texture: wgpu::Texture,
|
||||
pool: Weak<Mutex<Pool>>,
|
||||
/// The [`Enc`] that took it (see [`Pool::owned`]).
|
||||
owner: u64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Lease {
|
||||
@@ -84,7 +86,7 @@ impl Drop for Lease {
|
||||
if let Some(pool) = self.pool.upgrade()
|
||||
&& let Ok(mut p) = pool.lock()
|
||||
{
|
||||
p.release(self.texture.clone());
|
||||
p.release_owned(self.texture.clone(), self.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,8 +110,18 @@ pub(crate) struct Pool {
|
||||
/// Working textures reused / newly allocated (diagnostics, tests).
|
||||
hits: u64,
|
||||
misses: u64,
|
||||
/// Textures released while the [`Enc`] that took them is alive, kept for that `Enc` only.
|
||||
/// Its later commands run after everything it recorded or submitted before (one queue,
|
||||
/// recording order), so it can overwrite them at once instead of allocating a new texture
|
||||
/// for every intermediate of a frame (a 4K frame holds dozens). Other encoders never see a
|
||||
/// working texture of another `Enc` before it is gone.
|
||||
owned: HashMap<u64, HashMap<(u32, u32), Vec<wgpu::Texture>>>,
|
||||
next_owner: u64,
|
||||
}
|
||||
|
||||
/// In-`Enc` texture reuse ([`Pool::owned`]); tests turn it off to compare.
|
||||
pub(crate) static TEXTURE_REUSE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
|
||||
|
||||
/// Counts of uploads (CPU → GPU) and readbacks (GPU → CPU).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Transfers {
|
||||
@@ -178,6 +190,37 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
fn register(&mut self) -> u64 {
|
||||
self.next_owner += 1;
|
||||
if TEXTURE_REUSE.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
self.owned.insert(self.next_owner, HashMap::new());
|
||||
}
|
||||
self.next_owner
|
||||
}
|
||||
|
||||
/// `Enc` `owner` is gone: its kept textures go through the shared pool.
|
||||
fn unregister(&mut self, owner: u64) {
|
||||
if let Some(m) = self.owned.remove(&owner) {
|
||||
for t in m.into_values().flatten() {
|
||||
self.release(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn release_owned(&mut self, t: wgpu::Texture, owner: u64) {
|
||||
if let Some(m) = self.owned.get_mut(&owner) {
|
||||
m.entry((t.width(), t.height())).or_default().push(t);
|
||||
return;
|
||||
}
|
||||
self.release(t);
|
||||
}
|
||||
|
||||
fn take_owned(&mut self, owner: u64, w: u32, h: u32) -> Option<wgpu::Texture> {
|
||||
let t = self.owned.get_mut(&owner)?.get_mut(&(w, h))?.pop()?;
|
||||
self.hits += 1;
|
||||
Some(t)
|
||||
}
|
||||
|
||||
fn take(&mut self, w: u32, h: u32) -> Option<wgpu::Texture> {
|
||||
let t = self.free.get_mut(&(w, h)).and_then(Vec::pop);
|
||||
match &t {
|
||||
@@ -253,6 +296,8 @@ pub struct GpuContext {
|
||||
dummy_tex: wgpu::TextureView,
|
||||
dummy_buf: wgpu::Buffer,
|
||||
uploads: Mutex<Uploads>,
|
||||
upload_budget: std::sync::atomic::AtomicUsize,
|
||||
upload_full_warned: std::sync::atomic::AtomicBool,
|
||||
pool: Arc<Mutex<Pool>>,
|
||||
/// CPU ↔ GPU traffic (diagnostics: `bench --gpu`).
|
||||
pub(crate) transfers: Transfers,
|
||||
@@ -598,6 +643,8 @@ impl GpuContext {
|
||||
dummy,
|
||||
dummy_buf,
|
||||
uploads: Mutex::new(Uploads::default()),
|
||||
upload_budget: std::sync::atomic::AtomicUsize::new(UPLOAD_BUDGET),
|
||||
upload_full_warned: Default::default(),
|
||||
pool: Default::default(),
|
||||
staging: Default::default(),
|
||||
transfers: Default::default(),
|
||||
@@ -817,15 +864,26 @@ impl GpuContext {
|
||||
|
||||
/// A pooled working texture: (image, reused). A reused texture holds old pixels; a new
|
||||
/// one is zeroed.
|
||||
fn pooled(&self, w: u32, h: u32) -> (GpuImage, bool) {
|
||||
fn pooled(&self, w: u32, h: u32, owner: u64) -> (GpuImage, bool) {
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
let reused = self.pool.lock().ok().and_then(|mut p| p.take(w, h));
|
||||
let reused = self.pool.lock().ok().and_then(|mut p| p.take_owned(owner, w, h).or_else(|| p.take(w, h)));
|
||||
let was_reused = reused.is_some();
|
||||
let texture = reused.unwrap_or_else(|| self.texture(w, h));
|
||||
let lease = Arc::new(Lease { texture: texture.clone(), pool: Arc::downgrade(&self.pool) });
|
||||
let lease = Arc::new(Lease { texture: texture.clone(), pool: Arc::downgrade(&self.pool), owner });
|
||||
(GpuImage { texture, width: w, height: h, _lease: Some(lease), levels: None }, was_reused)
|
||||
}
|
||||
|
||||
/// Bytes of uploaded layer textures the context keeps (default 1536 MB). An application that
|
||||
/// knows the device's memory can raise it (static layers of a big frame upload once) or lower
|
||||
/// it (a small GPU); the least recently used textures go first.
|
||||
pub fn set_upload_budget(&self, bytes: usize) {
|
||||
self.upload_budget.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn upload_budget(&self) -> usize {
|
||||
self.upload_budget.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Uploads and readbacks so far (images; uploads of cached layers count once).
|
||||
pub fn transfer_stats(&self) -> TransferStats {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
@@ -882,7 +940,8 @@ impl GpuContext {
|
||||
}
|
||||
u.bytes += bytes;
|
||||
// Drop textures of freed buffers, then the least recently used over budget.
|
||||
if u.bytes > UPLOAD_BUDGET {
|
||||
let budget = self.upload_budget();
|
||||
if u.bytes > budget {
|
||||
let dead: Vec<usize> = u.map.iter().filter(|(_, e)| e.buf.strong_count() == 0).map(|(k, _)| *k).collect();
|
||||
for k in dead {
|
||||
if let Some(e) = u.map.remove(&k) {
|
||||
@@ -890,7 +949,14 @@ impl GpuContext {
|
||||
}
|
||||
}
|
||||
}
|
||||
while u.bytes > UPLOAD_BUDGET {
|
||||
if u.bytes > budget && !self.upload_full_warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
log::warn!(
|
||||
target: "effectcraft_gpu",
|
||||
"GPU upload cache full ({} MB): evicting layer textures, which upload again when next used; a frame whose static layers exceed it re-uploads them every frame",
|
||||
budget >> 20
|
||||
);
|
||||
}
|
||||
while u.bytes > budget {
|
||||
let Some(k) = u.map.iter().min_by_key(|(_, e)| e.last_use).map(|(k, _)| *k) else { break };
|
||||
if let Some(e) = u.map.remove(&k) {
|
||||
u.bytes -= e.bytes;
|
||||
@@ -923,22 +989,26 @@ pub(crate) struct Enc<'g> {
|
||||
pending: usize,
|
||||
/// A dispatch named a kernel the device doesn't have (see [`Enc::take_missing`]).
|
||||
missing: bool,
|
||||
/// This `Enc`'s id in the texture pool (textures it may reuse at once).
|
||||
owner: u64,
|
||||
}
|
||||
|
||||
impl Drop for Enc<'_> {
|
||||
fn drop(&mut self) {
|
||||
// Unsubmitted work is discarded, so nothing recorded will read pooled textures.
|
||||
if let Some((_, id)) = self.enc.take()
|
||||
&& let Ok(mut p) = self.g.pool.lock()
|
||||
{
|
||||
p.close(id);
|
||||
if let Ok(mut p) = self.g.pool.lock() {
|
||||
if let Some((_, id)) = self.enc.take() {
|
||||
p.close(id);
|
||||
}
|
||||
p.unregister(self.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'g> Enc<'g> {
|
||||
pub fn new(g: &'g GpuContext) -> Enc<'g> {
|
||||
Enc { g, enc: None, pending: 0, missing: false }
|
||||
let owner = g.pool.lock().map(|mut p| p.register()).unwrap_or(0);
|
||||
Enc { g, enc: None, pending: 0, missing: false, owner }
|
||||
}
|
||||
|
||||
/// Whether a dispatch since the last call named a kernel the device doesn't have (one
|
||||
@@ -960,7 +1030,7 @@ impl<'g> Enc<'g> {
|
||||
|
||||
/// A new zeroed image (pooled; a reused texture is cleared by a kernel).
|
||||
pub fn image(&mut self, w: u32, h: u32) -> GpuImage {
|
||||
let (img, reused) = self.g.pooled(w, h);
|
||||
let (img, reused) = self.g.pooled(w, h, self.owner);
|
||||
if reused {
|
||||
self.fill(&img, 0.0);
|
||||
}
|
||||
@@ -970,7 +1040,7 @@ impl<'g> Enc<'g> {
|
||||
/// A new image for a kernel that writes every pixel of it (pooled; contents undefined).
|
||||
/// Under test it starts out as NaNs, so a kernel that skips pixels fails the CPU oracle.
|
||||
pub fn scratch(&mut self, w: u32, h: u32) -> GpuImage {
|
||||
let (img, _) = self.g.pooled(w, h);
|
||||
let (img, _) = self.g.pooled(w, h, self.owner);
|
||||
if cfg!(test) {
|
||||
self.fill(&img, f32::NAN);
|
||||
}
|
||||
|
||||
@@ -276,21 +276,9 @@ fn cryptomatte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option
|
||||
let layer = layers.iter().find(|l| l.as_str() == want || l.ends_with(want)).unwrap_or(&layers[0]).clone();
|
||||
let manifest = a.manifests.iter().find(|(l, _)| *l == layer).map(|(_, m)| m.as_slice());
|
||||
let sel = effectcraft_effects::selection_hashes(pr.s("selection"), manifest);
|
||||
// Per aux pixel: coverage-weighted ID colours (RGB) and the selection's coverage (A).
|
||||
let n = (a.width * a.height) as usize;
|
||||
let mut img = Image::new(a.width, a.height);
|
||||
for (i, px) in img.data.iter_mut().enumerate().take(n) {
|
||||
let ranks = a.crypto_ranks(&layer, i);
|
||||
let m: f32 = ranks.iter().filter(|(id, c)| *c > 0.0 && sel.contains(&id.to_bits())).map(|(_, c)| *c).sum::<f32>().clamp(0.0, 1.0);
|
||||
let mut c = [0.0f32; 3];
|
||||
for (id, cov) in &ranks {
|
||||
let k = effectcraft_effects::id_color(*id);
|
||||
for j in 0..3 {
|
||||
c[j] += k[j] * cov;
|
||||
}
|
||||
}
|
||||
*px = [c[0], c[1], c[2], m];
|
||||
}
|
||||
// Per aux pixel: coverage-weighted ID colours (RGB) and the selection's coverage (A), on all
|
||||
// cores with the rank planes resolved once.
|
||||
let img = effectcraft_effects::crypto_aux_image(a, &layer, &sel);
|
||||
let tex = e.g.upload_image(&img)?;
|
||||
let plane = lookup(e, &b, a, &tex, [0.5, 0.5], [0.0; 4]);
|
||||
let mut p = op(7);
|
||||
|
||||
@@ -806,7 +806,8 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
t = clamp(t, 0.0, 1.0);
|
||||
let c0 = P.f[1].xyz;
|
||||
let c1 = P.f[2].xyz;
|
||||
px = put(px, c0 + (c1 - c0) * t, 1.0, P.f[3].z);
|
||||
// Keep the source alpha, as the CPU path does (#1063): the ramp fills only the shape.
|
||||
px = put(px, c0 + (c1 - c0) * t, px.w, P.f[3].z);
|
||||
}
|
||||
case 10u: {
|
||||
let contrast = P.f[0].x;
|
||||
|
||||
@@ -857,3 +857,190 @@ fn readback_staging_stays_bounded_across_sizes() {
|
||||
let held = g.ctx.staging_bytes();
|
||||
assert!(held <= (256 << 20) + 2 * 1024 * 16 * 376, "staging buffers hold {held} bytes");
|
||||
}
|
||||
|
||||
/// A static adjustment layer with a time-dependent effect (Noise) keeps its footprint key
|
||||
/// across frames (the footprint is the source through the masks, not the effects), so the GPU
|
||||
/// uploads nothing after the first frame; matches the CPU.
|
||||
#[test]
|
||||
fn adjustment_footprint_uploads_once_under_time_dependent_effects() {
|
||||
let mut s = Scene::new(BitDepth::Bpc8);
|
||||
let bg = s.solid([0.3, 0.5, 0.7], 96, 64);
|
||||
s.push(bg);
|
||||
let mut adj = s.solid([1.0, 1.0, 1.0], 80, 50);
|
||||
adj.switches.adjustment = true;
|
||||
s.effect(&mut adj, "ec.noise.noise", &[("amount", n(30.0))]);
|
||||
s.push(adj);
|
||||
// The key itself (no GPU needed): stable across time.
|
||||
let comp = s.p.comp(s.cid).expect("the scene's comp");
|
||||
let adj = comp.layers.last().expect("the adjustment layer");
|
||||
let key = |k: f64| {
|
||||
effectcraft_render::cache::footprint_key(&effectcraft_render::EvalCtx::new(&s.p, s.cid, comp, Tick::from_seconds_f64(k)), adj, 1.0, false, false)
|
||||
};
|
||||
assert!(key(0.0).is_some());
|
||||
assert_eq!(key(0.0), key(0.5), "the footprint key changes with time");
|
||||
let Some(g) = gpu() else { return };
|
||||
let cache = effectcraft_render::cache::LayerCache::new(64 << 20);
|
||||
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() });
|
||||
r.accel = Some(g);
|
||||
r.cache = Some(&cache);
|
||||
let t = |k: u64| Tick::from_seconds_f64(k as f64 / 30.0);
|
||||
let mut prev = None;
|
||||
for k in 0..4 {
|
||||
let before = g.ctx.transfer_stats().upload_bytes;
|
||||
let img = g.render(&r, s.cid, t(k)).expect("the GPU renders the frame");
|
||||
let up = g.ctx.transfer_stats().upload_bytes - before;
|
||||
if k >= 2 {
|
||||
assert_eq!(up, 0, "frame {k} uploaded {up} bytes: the footprint was re-keyed");
|
||||
}
|
||||
// Noise changes every frame: the frames differ.
|
||||
assert!(prev.as_ref() != Some(&img.data), "frame {k} repeats the previous one");
|
||||
prev = Some(img.data);
|
||||
check(&format!("noise adjustment frame {k}"), compare_at(&s, opts(), t(k)), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// An `Enc` reuses a working texture it released at once (`Pool::owned`); another `Enc` does
|
||||
/// not get it while the first is alive.
|
||||
#[test]
|
||||
fn enc_reuses_its_own_released_textures() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let mut e = crate::context::Enc::new(&g.ctx);
|
||||
let a = e.image(37, 23);
|
||||
let ta = a.texture.clone();
|
||||
drop(a);
|
||||
let mut other = crate::context::Enc::new(&g.ctx);
|
||||
let o = other.image(37, 23);
|
||||
assert!(o.texture != ta, "another Enc got a texture the first may still be using");
|
||||
let b = e.image(37, 23);
|
||||
assert!(b.texture == ta, "the Enc allocated a new texture instead of reusing its own");
|
||||
}
|
||||
|
||||
/// In-`Enc` texture reuse changes no pixel: a busy frame (layers, effects, adjustment layer,
|
||||
/// nested comp) renders bit-identically with reuse on and off, and matches the CPU.
|
||||
#[test]
|
||||
fn texture_reuse_does_not_change_output() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let mut s = Scene::new(BitDepth::Bpc32);
|
||||
for i in 0..4 {
|
||||
let mut l = s.footage(90 - i * 7, 60 - i * 5);
|
||||
s.effect(&mut l, "ec.blur.gaussian", &[("blurriness", n(2.0 + i as f64))]);
|
||||
set(&mut l, "transform/rotation", Value::Scalar(10.0 * i as f64));
|
||||
l.blend_mode = if i % 2 == 0 { BlendMode::Screen } else { BlendMode::Multiply };
|
||||
s.push(l);
|
||||
}
|
||||
let mut adj = s.solid([1.0, 1.0, 1.0], 80, 50);
|
||||
adj.switches.adjustment = true;
|
||||
s.effect(&mut adj, "ec.color.levels", &[("gamma", n(1.2))]);
|
||||
s.push(adj);
|
||||
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() });
|
||||
r.accel = Some(g);
|
||||
let t = Tick::from_seconds_f64(0.3);
|
||||
let on = g.render(&r, s.cid, t).expect("the GPU renders the frame");
|
||||
crate::context::TEXTURE_REUSE.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||
let off = g.render(&r, s.cid, t);
|
||||
crate::context::TEXTURE_REUSE.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
assert!(off.is_some_and(|off| off.data == on.data), "texture reuse changed the frame");
|
||||
check("texture reuse vs CPU", compare_at(&s, opts(), t), 0.0);
|
||||
}
|
||||
|
||||
/// Static layer buffers (here adjustment-layer footprints) upload once while they fit the upload budget, and upload again every frame
|
||||
/// when they do not (least recently used first); the frame is the same either way.
|
||||
#[test]
|
||||
fn upload_budget_bounds_the_layer_textures_kept() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let mut s = Scene::new(BitDepth::Bpc8);
|
||||
for (i, c) in [[0.8, 0.2, 0.1], [0.1, 0.3, 0.9]].into_iter().enumerate() {
|
||||
let mut l = s.solid(c, 200, 200);
|
||||
set(&mut l, "transform/position", v3(60.0 + 30.0 * i as f64, 40.0));
|
||||
// Adjustment layers: their footprints are cached layer buffers the GPU uploads.
|
||||
l.switches.adjustment = true;
|
||||
s.effect(&mut l, "ec.color.levels", &[("gamma", n(1.1 + 0.2 * i as f64))]);
|
||||
s.push(l);
|
||||
}
|
||||
let frame = |cache: &effectcraft_render::cache::LayerCache, k: u64| {
|
||||
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() });
|
||||
r.accel = Some(g);
|
||||
r.cache = Some(cache);
|
||||
let before = g.ctx.transfer_stats().upload_bytes;
|
||||
let img = g.render(&r, s.cid, Tick::from_seconds_f64(k as f64 / 30.0)).expect("the GPU renders the frame");
|
||||
(img.data, g.ctx.transfer_stats().upload_bytes - before)
|
||||
};
|
||||
let fits = effectcraft_render::cache::LayerCache::new(64 << 20);
|
||||
let (a, _) = frame(&fits, 0);
|
||||
let (b, up) = frame(&fits, 1);
|
||||
assert_eq!(up, 0, "static layers re-uploaded within the default budget");
|
||||
// A budget smaller than the two 640 KB footprints: each upload evicts the other.
|
||||
let default = g.ctx.upload_budget();
|
||||
g.ctx.set_upload_budget(1 << 20);
|
||||
let tight = effectcraft_render::cache::LayerCache::new(64 << 20);
|
||||
let _ = frame(&tight, 0);
|
||||
let (c, up) = frame(&tight, 1);
|
||||
g.ctx.set_upload_budget(default);
|
||||
assert!(up > 0, "over budget, the footprints must upload again");
|
||||
assert!(a == b && b == c, "the upload budget changed the frame");
|
||||
}
|
||||
|
||||
/// Layers with effect stacks run them resident on the GPU (`walk::draw_resident_fx`): GPU
|
||||
/// effects, a CPU-only effect in the middle (read back, run, upload), opacity and a blend mode,
|
||||
/// a shape layer whose effects run in effect space from its bounds' corner; 8 and 32 bpc, full
|
||||
/// and half resolution; all match the CPU.
|
||||
#[test]
|
||||
fn effect_stacks_render_resident() {
|
||||
for depth in [BitDepth::Bpc8, BitDepth::Bpc32] {
|
||||
let mut s = Scene::new(depth);
|
||||
let bg = s.footage(97, 61);
|
||||
s.push(bg);
|
||||
let mut a = s.footage(70, 44);
|
||||
s.effect(&mut a, "ec.blur.gaussian", &[("blurriness", n(4.0))]);
|
||||
s.effect(&mut a, "ec.generate.fractal", &[]);
|
||||
s.effect(&mut a, "ec.color.levels", &[("gamma", n(1.4))]);
|
||||
set(&mut a, "transform/rotation", Value::Scalar(20.0));
|
||||
set(&mut a, "transform/opacity", Value::Scalar(70.0));
|
||||
a.blend_mode = BlendMode::Overlay;
|
||||
s.push(a);
|
||||
let mut l = build::layer(&mut s.p, &s.comp, "Shape", LayerSource::Shape, (97, 61), None);
|
||||
let mut next = s.p.next_id;
|
||||
let mut ids = Ids(&mut next);
|
||||
let rect = build::shape_rect(&mut ids, [50.0, 30.0], [5.0, -4.0], 0.0);
|
||||
let fill = build::shape_fill(&mut ids, [0.2, 0.8, 0.3, 1.0]);
|
||||
let g = build::shape_group(&mut ids, "Rectangle 1", vec![rect, fill]);
|
||||
s.p.next_id = next;
|
||||
l.props.sub_mut("contents").expect("a shape layer has contents").children.push(g.into());
|
||||
s.effect(&mut l, "ec.blur.gaussian", &[("blurriness", n(3.0))]);
|
||||
s.effect(&mut l, "ec.stylize.mosaic", &[]);
|
||||
s.push(l);
|
||||
let t = Tick::from_seconds_f64(0.2);
|
||||
check(&format!("effect stacks {depth:?}"), compare_at(&s, opts(), t), 0.0);
|
||||
check(&format!("effect stacks half {depth:?}"), compare_at(&s, RenderOpts { scale: 0.5, ..opts() }, t), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer whose effects give the same result as last frame draws from the layer cache (its
|
||||
/// processed buffer uploads once) instead of re-running the stack on the GPU every frame.
|
||||
#[test]
|
||||
fn static_effect_layers_draw_from_the_cache() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let mut s = Scene::new(BitDepth::Bpc8);
|
||||
let mut l = s.solid([0.6, 0.4, 0.2], 80, 50);
|
||||
s.effect(&mut l, "ec.blur.gaussian", &[("blurriness", n(3.0))]);
|
||||
s.push(l);
|
||||
let cache = effectcraft_render::cache::LayerCache::new(64 << 20);
|
||||
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() });
|
||||
r.accel = Some(g);
|
||||
r.cache = Some(&cache);
|
||||
let comp = s.p.comp(s.cid).expect("the scene's comp");
|
||||
let layer = comp.layers.last().expect("the layer");
|
||||
let t = |k: u64| Tick::from_seconds_f64(k as f64 / 30.0);
|
||||
assert!(r.layer_is_static(&effectcraft_render::EvalCtx::new(&s.p, s.cid, comp, t(2)), layer));
|
||||
let mut frames = Vec::new();
|
||||
for k in 0..3 {
|
||||
let before = g.ctx.transfer_stats().upload_bytes;
|
||||
frames.push(g.render(&r, s.cid, t(k)).expect("the GPU renders the frame").data);
|
||||
let up = g.ctx.transfer_stats().upload_bytes - before;
|
||||
if k == 2 {
|
||||
assert_eq!(up, 0, "the cached layer uploaded again");
|
||||
}
|
||||
}
|
||||
assert!(frames[1] == frames[2]);
|
||||
check("static effect layer vs CPU", compare_at(&s, opts(), t(2)), 0.0);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use effectcraft_keyframe::{ShapePath, Value};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{BitDepth, ColorSpace, MaskMode};
|
||||
use effectcraft_project::{BitDepth, ColorSpace, MaskMode, MatteKind, TrackMatte};
|
||||
use effectcraft_render::{Backend, FxStep, FxTarget, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
@@ -72,6 +72,24 @@ fn mixed_adjustment_chains_fall_back_per_effect() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A track matte limits where the adjustment shows, as on the CPU (#1201).
|
||||
#[test]
|
||||
fn track_mattes_limit_gpu_adjustments_like_the_cpu() {
|
||||
for depth in [BitDepth::Bpc8, BitDepth::Bpc32] {
|
||||
for kind in [MatteKind::Alpha, MatteKind::AlphaInverted, MatteKind::Luma, MatteKind::LumaInverted] {
|
||||
let mut s = adjustment_scene(depth, &gpu_stack(), false);
|
||||
let mut matte = s.footage(50, 30);
|
||||
matte.switches.video = false;
|
||||
set(&mut matte, "transform/rotation", Value::Scalar(10.0));
|
||||
let mid = s.push(matte);
|
||||
let c = s.p.comp_mut(s.cid).unwrap();
|
||||
let adj = c.layers.iter_mut().find(|l| l.switches.adjustment).unwrap();
|
||||
adj.track_matte = Some(TrackMatte { layer: mid, kind });
|
||||
check(&format!("matted adjustment {kind:?} {depth:?}"), compare_at(&s, opts(), Tick::ZERO), 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts where each run of the stack goes.
|
||||
#[derive(Default)]
|
||||
struct Probe {
|
||||
|
||||
@@ -183,3 +183,8 @@ fn color_stabilizer() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_ramp_matches_the_cpu() {
|
||||
effect_case("ec.generate.gradientramp", &[]);
|
||||
}
|
||||
|
||||
+65
-17
@@ -217,6 +217,9 @@ fn draw_layer(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, canvas: &
|
||||
if let Some(done) = draw_precomp(e, r, ctx, layer, canvas, opacity) {
|
||||
return done;
|
||||
}
|
||||
if let Some(done) = draw_resident_fx(e, r, ctx, layer, canvas, opacity) {
|
||||
return done;
|
||||
}
|
||||
let Some(st) = r.styled_layer(ctx, layer) else { return Some(()) };
|
||||
if st.plain {
|
||||
return composite_layer(e, r, ctx, layer, &st.body, canvas, opacity);
|
||||
@@ -246,6 +249,44 @@ fn draw_layer(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, canvas: &
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// A plain layer with effects, its effect stack run on the GPU: the source (+ masks, from the
|
||||
/// layer cache) uploads once while unchanged, the effects stay resident and the result is
|
||||
/// placed directly; the CPU path instead runs each GPU-capable effect run through an
|
||||
/// upload → kernels → readback, then uploads the result again to place it. `None`: not this
|
||||
/// kind of layer (draw it the usual way); `Some(None)`: the GPU failed.
|
||||
fn draw_resident_fx(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, canvas: &mut GpuImage, opacity: f32) -> Option<Option<()>> {
|
||||
if !layer.switches.effects
|
||||
|| layer.effects().is_none_or(|f| f.children.is_empty())
|
||||
|| styles::active(ctx, layer)
|
||||
|| layer.preserve_transparency
|
||||
|| r.track_matte(ctx, layer).is_some()
|
||||
// Unchanged since the last frame: the cached result uploads once (the usual path).
|
||||
|| r.layer_is_static(ctx, layer)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let input = r.layer_input(ctx, layer, 0)?;
|
||||
if input.img.is_empty() {
|
||||
return Some(Some(()));
|
||||
}
|
||||
let Some(src) = e.g.upload_buf(&input) else { return Some(None) };
|
||||
let pipe = r.pipe();
|
||||
// `layer_input` is in effect space: run the stack there, then back to layer space.
|
||||
let mut fx = crate::effects::GpuFx::new(e, src, input.offset, input.scale, pipe.levels);
|
||||
let origin = r.run_layer_effects_on(ctx, layer, &mut fx);
|
||||
let Some((mut img, mut offset, scale)) = fx.finish() else { return Some(None) };
|
||||
offset = [offset[0] - origin[0] * scale, offset[1] - origin[1] * scale];
|
||||
if img.width == 0 || img.height == 0 {
|
||||
return Some(Some(()));
|
||||
}
|
||||
if let Some(c) = pipe.to_blend() {
|
||||
img = ops::convert(e, &img, &c);
|
||||
}
|
||||
// The placement only reads the buffer's size, offset and scale.
|
||||
let shape = Buf { img: Image { width: img.width, height: img.height, data: Vec::new() }, offset, scale };
|
||||
Some(place_src(e, r, ctx, layer, &shape, img, canvas, layer.blend_mode, opacity, pipe.levels).map(|c| *canvas = c))
|
||||
}
|
||||
|
||||
/// A 2D precomp layer, its nested comp rendered resident on the GPU (`walk::render` one level
|
||||
/// down) instead of by the CPU compositor and uploaded every frame (`Renderer::layer_source`
|
||||
/// renders nested comps on the CPU: depth > 0). Then the layer's effects (resident), its
|
||||
@@ -297,12 +338,14 @@ fn draw_precomp(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, canvas:
|
||||
|
||||
/// Adjustment layer (`Renderer::draw_adjustment`): the effect stack runs on the comp below,
|
||||
/// resident on the GPU (non-GPU effects read back, run on the CPU and upload), and the result
|
||||
/// replaces the canvas inside the layer's footprint × opacity. `None` = draw it on the CPU.
|
||||
/// replaces the canvas inside the layer's footprint × track matte × opacity. `None` = draw it
|
||||
/// on the CPU.
|
||||
fn draw_adjustment(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, canvas: &mut GpuImage) -> Option<()> {
|
||||
let opacity = r.layer_opacity(ctx, layer);
|
||||
let Some(foot) = r.adjustment_footprint(ctx, layer) else { return Some(()) };
|
||||
let (w, h) = (canvas.width, canvas.height);
|
||||
let matte = place(e, r, ctx, layer, &foot, &e.zeros(w, h), BlendMode::Normal, 1.0, None)?;
|
||||
let matte = track_matte(e, r, ctx, layer, matte, None)?;
|
||||
let pipe = r.pipe();
|
||||
// Effects run in the working space, not the linear blending space.
|
||||
let below = match pipe.from_blend() {
|
||||
@@ -353,22 +396,7 @@ fn composite_iso_with(
|
||||
matte_img: Option<GpuImage>,
|
||||
levels: Option<f32>,
|
||||
) -> Option<()> {
|
||||
if let Some((m, kind)) = r.track_matte(ctx, layer) {
|
||||
let mimg = match matte_img.filter(|i| (i.width, i.height) == (canvas.width, canvas.height)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let mut mimg = e.zeros(canvas.width, canvas.height);
|
||||
if m.is_active_at(ctx.time)
|
||||
&& let Some(mb) = r.layer_buf(ctx, m)
|
||||
{
|
||||
let mo = ctx.opacity(m) as f32;
|
||||
mimg = place(e, r, ctx, m, &mb, &mimg, BlendMode::Normal, mo, None)?;
|
||||
}
|
||||
mimg
|
||||
}
|
||||
};
|
||||
iso = ops::matte(e, &iso, &mimg, kind);
|
||||
}
|
||||
iso = track_matte(e, r, ctx, layer, iso, matte_img)?;
|
||||
if layer.preserve_transparency {
|
||||
iso = ops::preserve(e, &iso, canvas);
|
||||
}
|
||||
@@ -376,6 +404,26 @@ fn composite_iso_with(
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `Renderer::apply_track_matte`: `img` (comp-sized) times the layer's track matte, if it has
|
||||
/// one; `matte_img` as in [`composite_iso_with`].
|
||||
fn track_matte(e: &mut Enc, r: &Renderer, ctx: &EvalCtx, layer: &Layer, img: GpuImage, matte_img: Option<GpuImage>) -> Option<GpuImage> {
|
||||
let Some((m, kind)) = r.track_matte(ctx, layer) else { return Some(img) };
|
||||
let mimg = match matte_img.filter(|i| (i.width, i.height) == (img.width, img.height)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let mut mimg = e.zeros(img.width, img.height);
|
||||
if m.is_active_at(ctx.time)
|
||||
&& let Some(mb) = r.layer_buf(ctx, m)
|
||||
{
|
||||
let mo = ctx.opacity(m) as f32;
|
||||
mimg = place(e, r, ctx, m, &mb, &mimg, BlendMode::Normal, mo, None)?;
|
||||
}
|
||||
mimg
|
||||
}
|
||||
};
|
||||
Some(ops::matte(e, &img, &mimg, kind))
|
||||
}
|
||||
|
||||
/// Draw a processed layer buffer onto `target` (transform, motion blur sub-samples), quantising
|
||||
/// the result to `levels` when set.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
@@ -12,6 +12,7 @@ workspace = true
|
||||
[dependencies]
|
||||
effectcraft-engine = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
log = { workspace = true }
|
||||
effectcraft-media = { workspace = true }
|
||||
effectcraft-expr = { workspace = true }
|
||||
effectcraft-script = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Where EffectCraft keeps its per-user data (settings, shortcuts, crash recovery, logs, models,
|
||||
//! plug-ins): the one directory [`config_dir`](crate::config_dir) returns.
|
||||
//!
|
||||
//! In order:
|
||||
//! 1. `EFFECTCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups).
|
||||
//! 2. **Portable mode** (#993): a marker file ([`PORTABLE_MARKERS`]) beside the executable puts
|
||||
//! everything in `<exe dir>/EffectCraftData`, so a portable copy on a USB stick leaves nothing in
|
||||
//! `%APPDATA%`. The Windows portable zip ships with `portable.txt`; the MSI doesn't. If that
|
||||
//! folder can't be written (read-only medium, Program Files), a warning is logged and the
|
||||
//! platform folder is used.
|
||||
//! 3. The platform convention: macOS `~/Library/Application Support/EffectCraft`, Windows
|
||||
//! `%APPDATA%\EffectCraft`, Linux `$XDG_CONFIG_HOME/effectcraft` or `~/.config/effectcraft`.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Files beside the executable that switch on portable mode (either one; contents are ignored).
|
||||
pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "EffectCraft.portable"];
|
||||
/// The data folder created beside the executable in portable mode.
|
||||
pub const PORTABLE_DATA_DIR: &str = "EffectCraftData";
|
||||
|
||||
/// How [`DataDir::dir`] was chosen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// `EFFECTCRAFT_CONFIG_DIR`.
|
||||
Override,
|
||||
/// `<exe dir>/EffectCraftData`.
|
||||
Portable,
|
||||
/// The platform's per-user config directory.
|
||||
Platform,
|
||||
}
|
||||
|
||||
/// The resolved data directory.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DataDir {
|
||||
/// `None` only when no platform directory is known either (no `HOME`/`APPDATA`).
|
||||
pub dir: Option<PathBuf>,
|
||||
pub mode: Mode,
|
||||
/// Set when a portable marker was found but its data folder isn't writable.
|
||||
pub warning: Option<String>,
|
||||
}
|
||||
|
||||
/// The data directory for this process, resolved once (the portable check probes the disk).
|
||||
pub fn current() -> &'static DataDir {
|
||||
static DIR: OnceLock<DataDir> = OnceLock::new();
|
||||
DIR.get_or_init(|| {
|
||||
let exe = std::env::current_exe().ok();
|
||||
let d = resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent));
|
||||
if let Some(w) = &d.warning {
|
||||
log::warn!("{w}");
|
||||
}
|
||||
d
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve the data directory from the environment (`env`) and the executable's folder.
|
||||
pub fn resolve(env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> DataDir {
|
||||
if let Some(d) = env("EFFECTCRAFT_CONFIG_DIR") {
|
||||
return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None };
|
||||
}
|
||||
let platform = platform_dir(&env);
|
||||
let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else {
|
||||
return DataDir { dir: platform, mode: Mode::Platform, warning: None };
|
||||
};
|
||||
let data = exe_dir.join(PORTABLE_DATA_DIR);
|
||||
match ensure_writable(&data) {
|
||||
Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None },
|
||||
Err(e) => {
|
||||
let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string());
|
||||
let warning =
|
||||
format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display());
|
||||
DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`).
|
||||
pub fn platform_dir(env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
let home = || env("HOME").map(PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
return home().map(|h| h.join("Library/Application Support/EffectCraft"));
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
return env("APPDATA").map(|a| PathBuf::from(a).join("EffectCraft"));
|
||||
}
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home().map(|h| h.join(".config"))).map(|c| c.join("effectcraft"))
|
||||
}
|
||||
|
||||
/// The first portable marker file in `exe_dir`, if any.
|
||||
pub fn portable_marker(exe_dir: &Path) -> Option<PathBuf> {
|
||||
PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only).
|
||||
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let probe = dir.join(format!(".write-test-{}", std::process::id()));
|
||||
std::fs::write(&probe, b"")?;
|
||||
// A leftover probe is harmless; don't fail portable mode over it.
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("effectcraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let m: HashMap<String, OsString> = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect();
|
||||
move |k| m.get(k).cloned()
|
||||
}
|
||||
|
||||
/// A fake user folder that every platform's convention resolves under.
|
||||
fn fake_home(root: &Path) -> impl Fn(&str) -> Option<OsString> + use<> {
|
||||
let home = root.join("home");
|
||||
let appdata = root.join("appdata");
|
||||
env_of(&[("HOME", &home), ("APPDATA", &appdata)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_marker_uses_the_platform_dir() {
|
||||
let root = temp("platform");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
let d = resolve(fake_home(&root), Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(dir, root.join("home/Library/Application Support/EffectCraft"));
|
||||
} else if cfg!(target_os = "windows") {
|
||||
assert_eq!(dir, root.join("appdata").join("EffectCraft"));
|
||||
} else {
|
||||
assert_eq!(dir, root.join("home/.config/effectcraft"));
|
||||
}
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_marker_keeps_everything_beside_the_exe() {
|
||||
for marker in PORTABLE_MARKERS {
|
||||
let root = temp("portable");
|
||||
let exe = root.join("EffectCraft");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join(marker), b"").unwrap();
|
||||
let d = resolve(fake_home(&root), Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Portable, "{marker}");
|
||||
assert!(d.warning.is_none());
|
||||
let dir = d.dir.unwrap();
|
||||
assert_eq!(dir, exe.join("EffectCraftData"));
|
||||
assert!(dir.is_dir(), "the data folder is created");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed");
|
||||
assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_folder_is_not_a_marker() {
|
||||
let root = temp("dir-marker");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(exe.join("portable.txt")).unwrap();
|
||||
assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform);
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritable_portable_folder_falls_back_with_a_warning() {
|
||||
let root = temp("unwritable");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
// A file where the data folder should go: it can't be created, on every platform.
|
||||
std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap();
|
||||
let env = fake_home(&root);
|
||||
let d = resolve(&env, Some(&exe));
|
||||
assert_eq!(d.mode, Mode::Platform);
|
||||
assert_eq!(d.dir, platform_dir(&env));
|
||||
assert!(d.dir.is_some());
|
||||
let w = d.warning.unwrap();
|
||||
assert!(w.contains("portable") && w.contains("isn't writable"), "{w}");
|
||||
// No user folder at all: still no panic, just no directory.
|
||||
let d = resolve(|_| None, Some(&exe));
|
||||
assert!(d.dir.is_none() && d.warning.is_some());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_wins_over_portable() {
|
||||
let root = temp("override");
|
||||
let exe = root.join("bin");
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
let custom = root.join("custom");
|
||||
let d = resolve(env_of(&[("EFFECTCRAFT_CONFIG_DIR", &custom)]), Some(&exe));
|
||||
assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom)));
|
||||
assert!(!exe.join(PORTABLE_DATA_DIR).exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_exe_dir_or_env_never_panics() {
|
||||
let d = resolve(|_| None, None);
|
||||
assert_eq!((d.mode, d.dir), (Mode::Platform, None));
|
||||
}
|
||||
}
|
||||
+5
-13
@@ -12,6 +12,8 @@ use effectcraft_engine::{ExportJob, ExportResult, Exporter, Importer, Session};
|
||||
use effectcraft_project::Footage;
|
||||
pub use effectcraft_script as script;
|
||||
|
||||
pub mod app_dirs;
|
||||
|
||||
struct MediaImporter;
|
||||
|
||||
impl Importer for MediaImporter {
|
||||
@@ -97,20 +99,10 @@ pub fn session() -> Session {
|
||||
|
||||
/// The platform config directory for EffectCraft (`EFFECTCRAFT_CONFIG_DIR` overrides):
|
||||
/// `~/Library/Application Support/EffectCraft` (macOS), `%APPDATA%\EffectCraft` (Windows),
|
||||
/// `$XDG_CONFIG_HOME/effectcraft` or `~/.config/effectcraft` (Linux and others).
|
||||
/// `$XDG_CONFIG_HOME/effectcraft` or `~/.config/effectcraft` (Linux and others). A `portable.txt`
|
||||
/// beside the executable puts it in `EffectCraftData` there instead ([`app_dirs`]).
|
||||
pub fn config_dir() -> Option<std::path::PathBuf> {
|
||||
use std::path::PathBuf;
|
||||
if let Some(d) = std::env::var_os("EFFECTCRAFT_CONFIG_DIR") {
|
||||
return Some(PathBuf::from(d));
|
||||
}
|
||||
let home = || std::env::var_os("HOME").map(PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
return home().map(|h| h.join("Library/Application Support/EffectCraft"));
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
return std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("EffectCraft"));
|
||||
}
|
||||
std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home().map(|h| h.join(".config"))).map(|c| c.join("effectcraft"))
|
||||
app_dirs::current().dir.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! The Backgrounds animation presets through the wired session (with the expression engine):
|
||||
//! each one renders a non-flat, finite, deterministic frame that keeps moving, and undoes.
|
||||
|
||||
use effectcraft_engine::render::RenderOpts;
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::json;
|
||||
|
||||
type Frame = Vec<[f32; 4]>;
|
||||
|
||||
/// The frame at `secs`, its mean luma, luma standard deviation and whether any channel is not finite.
|
||||
fn frame(s: &effectcraft_engine::Session, secs: f64) -> (Frame, f64, f64, bool) {
|
||||
let Some(cid) = s.active_comp_id() else { panic!("no active comp") };
|
||||
let img = s.render(cid, Tick::from_seconds_f64(secs), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let bad = img.data.iter().any(|p| p.iter().any(|c| !c.is_finite()));
|
||||
let l: Vec<f64> = img.data.iter().map(|p| 0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64).collect();
|
||||
let n = l.len().max(1) as f64;
|
||||
let mean = l.iter().sum::<f64>() / n;
|
||||
let sd = (l.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n).sqrt();
|
||||
(img.data.clone(), mean, sd, bad)
|
||||
}
|
||||
|
||||
fn diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f64 {
|
||||
a.iter().zip(b).map(|(p, q)| (0..3).map(|i| (p[i] - q[i]).abs() as f64).sum::<f64>()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_background_preset_renders_moves_and_undoes() {
|
||||
let mut s = effectcraft_host::session();
|
||||
s.execute("comp.new", json!({"name": "BG", "width": 640, "height": 360, "frameRate": 30, "duration": 8})).unwrap();
|
||||
let solid = s.execute("layer.newSolid", json!({"name": "S", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let list = s.execute("anim.builtinPresets", json!({"category": "Backgrounds"})).unwrap();
|
||||
let list = list.as_array().unwrap().clone();
|
||||
assert!(list.len() >= 15, "{}", list.len());
|
||||
for p in &list {
|
||||
let id = p["id"].as_str().unwrap();
|
||||
s.execute("time.set", json!({"time": 0.0})).unwrap();
|
||||
let r = s.execute("anim.applyBuiltinPreset", json!({"layers": [solid], "preset": id})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]), "{id}");
|
||||
let mut frames = Vec::new();
|
||||
for t in [0.0, 1.3, 3.7] {
|
||||
let (px, mean, sd, nan) = frame(&s, t);
|
||||
if let Some(dir) = std::env::var_os("EC_PRESET_DUMP") {
|
||||
// Contact-sheet helper for reviewing the looks by eye (not part of the check).
|
||||
let mut ppm = b"P6\n640 360\n255\n".to_vec();
|
||||
ppm.extend(px.iter().flat_map(|p| (0..3).map(|i| (p[i].clamp(0.0, 1.0) * 255.0) as u8)));
|
||||
let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{id}_{t}.ppm")), ppm);
|
||||
}
|
||||
assert!(!nan, "{id} @ {t}: NaN or infinite pixel");
|
||||
assert!(sd > 0.015, "{id} @ {t}: flat frame (mean {mean:.3}, sd {sd:.4})");
|
||||
let (again, ..) = frame(&s, t);
|
||||
assert!(px == again, "{id} @ {t}: render is not deterministic");
|
||||
frames.push(px);
|
||||
}
|
||||
assert!(diff(&frames[0], &frames[1]) > 100.0, "{id}: frame does not move between 0 s and 1.3 s");
|
||||
assert!(diff(&frames[1], &frames[2]) > 100.0, "{id}: frame does not move between 1.3 s and 3.7 s");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let fx = s.active_comp().map_or(1, |c| c.layers[0].effects().map_or(0, |fx| fx.groups().count()));
|
||||
assert_eq!(fx, 0, "{id}: undo removes the effects");
|
||||
}
|
||||
}
|
||||
@@ -194,3 +194,22 @@ fn image_sequences_reload_by_themselves_only_with_all_footage() {
|
||||
png(&b, 128);
|
||||
assert_eq!(s.execute_checked("footage.reloadChanged", json!({})).unwrap()["files"], json!(1));
|
||||
}
|
||||
|
||||
/// #1070: a file decoded in one project and overwritten with one of the same size is read again
|
||||
/// when a new project imports it (neither File ▸ Reload Footage nor the change watcher knows it).
|
||||
#[test]
|
||||
fn a_new_project_importing_an_overwritten_file_shows_the_new_pixels() {
|
||||
let path = tmp("overwritten.psd");
|
||||
std::fs::write(&path, flat(RED, false)).unwrap();
|
||||
let (mut s, _item, cid) = flat_in_comp(&path);
|
||||
assert!(near(pixel(&s, cid, 32, 24), RED));
|
||||
// Another app overwrites the file with the same number of bytes.
|
||||
save(&path, &flat(BLUE, false));
|
||||
s.execute_checked("file.newProject", json!({})).unwrap();
|
||||
let r = s.execute_checked("file.import", json!({"paths": [path.clone()]})).unwrap();
|
||||
let item = r["items"][0].as_u64().unwrap();
|
||||
s.execute_checked("comp.new", json!({"name": "C", "width": 64, "height": 48, "frameRate": 30, "duration": 1})).unwrap();
|
||||
s.execute_checked("layer.addItem", json!({"item": item})).unwrap();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
assert!(near(pixel(&s, cid, 32, 24), BLUE), "stale pixels from the earlier project: {:?}", pixel(&s, cid, 32, 24));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user