mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-26 17:17:44 +00:00
Merge remote-tracking branch 'origin/main' into codex/778-effect-migration
# Conflicts: # crates/aep/src/container.rs # crates/aep/src/container/footage.rs # crates/aep/tests/it/container/robustness.rs # crates/model/src/fbx.rs # crates/model/src/gltf.rs # crates/model/src/obj.rs
This commit is contained in:
+3
-1
@@ -64,7 +64,7 @@ and licence texts are in [`NOTICE`](NOTICE).
|
||||
| `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 |
|
||||
| `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 |
|
||||
|
||||
Two small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with the `stubicc` example of `craft-aep` (storytold/craft-libs; formerly `crates/aep/examples/stubicc.rs`); MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with the `stubicc` example of `craft-aep` (storytold/craft-libs; formerly `crates/aep/examples/stubicc.rs`) (a header and a description, no colour data), so no vendor profile data is in them.
|
||||
Three small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar), `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with `crates/aep/examples/stubicc.rs`; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/text-synthetic.aep` (original work, made with After Effects 2026 by script from own data, working space None, no colour profile embedded, nothing changed after the save; MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with `crates/aep/examples/stubicc.rs` (a header and a description, no colour data), so no vendor profile data is in them.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -133,7 +133,9 @@ configuration from these Apache-2.0 projects:
|
||||
|
||||
| Asset | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 |
|
||||
| `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 |
|
||||
| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 |
|
||||
|
||||
## First-party brand marks
|
||||
|
||||
|
||||
Generated
+30
-29
@@ -1092,26 +1092,26 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-aep"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
|
||||
[[package]]
|
||||
name = "craft-audio"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dpx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1119,7 +1119,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1129,12 +1129,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
|
||||
[[package]]
|
||||
name = "craft-exr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1142,17 +1142,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1175,7 +1175,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-lottie"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1184,7 +1184,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-media"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1200,7 +1200,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mesh"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"miniz_oxide 0.9.1",
|
||||
"serde_json",
|
||||
@@ -1209,7 +1209,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1218,7 +1218,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1229,7 +1229,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1240,7 +1240,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -1252,7 +1252,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1273,7 +1273,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1300,9 +1300,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-video"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1310,7 +1310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-webp"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1318,7 +1318,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1558,6 +1558,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sysinfo",
|
||||
"tempfile",
|
||||
"winit",
|
||||
"winresource",
|
||||
"zbus",
|
||||
@@ -1681,7 +1682,7 @@ name = "effectcraft-export"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)",
|
||||
"craft-video",
|
||||
"effectcraft-color",
|
||||
"effectcraft-effects",
|
||||
@@ -1850,7 +1851,7 @@ dependencies = [
|
||||
"craft-dpx",
|
||||
"craft-exr",
|
||||
"craft-gif",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5)",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58)",
|
||||
"craft-webp",
|
||||
"effectcraft-color",
|
||||
"effectcraft-effects",
|
||||
@@ -3420,7 +3421,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
@@ -3434,7 +3435,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=091863e4a615f38743bfd5d6dc62a2e8f37cd5d5#091863e4a615f38743bfd5d6dc62a2e8f37cd5d5"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ddd0864d57503fb861c727d4f2336b04fa48f58#7ddd0864d57503fb861c727d4f2336b04fa48f58"
|
||||
dependencies = [
|
||||
"hayro-jbig2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -4753,7 +4754,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+21
-21
@@ -11,22 +11,22 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/effectcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.1.0", default-features = false, features = ["read"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
|
||||
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.1.0", default-features = false, features = ["read"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
|
||||
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["egui"] }
|
||||
# internal
|
||||
effectcraft-time = { path = "crates/time" }
|
||||
effectcraft-geom = { path = "crates/geom" }
|
||||
@@ -90,9 +90,9 @@ same-file = "1.0"
|
||||
tempfile = "3.27"
|
||||
|
||||
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev.
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["isobmff", "matroska"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["isobmff", "matroska"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
|
||||
|
||||
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
|
||||
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
|
||||
@@ -122,7 +122,7 @@ half = "2.7"
|
||||
# ui
|
||||
# Shared frontend components; keep this dependency above the engine boundary.
|
||||
# Shared UI and the complete egui family select reviewed immutable commits below.
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", features = ["serde"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", features = ["serde"] }
|
||||
# `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
|
||||
# and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
@@ -231,8 +231,8 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "091863e4a615f38743bfd5d6dc62a2e8f37cd5d5", version = "=0.3.0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7ddd0864d57503fb861c727d4f2336b04fa48f58", version = "=0.3.0" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -41,6 +41,9 @@ zbus = "5.19"
|
||||
# Icon + VERSIONINFO for effectcraft.exe; build.rs only uses it when targeting Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Keep the control channel responsive when the window is covered (App Nap / occlusion throttling).
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSProcessInfo", "NSString", "NSObject"] }
|
||||
|
||||
@@ -426,6 +426,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn helper_mode(dir: &Path, id: &str, interactive: bool) -> Reporter {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("reporter_process"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "reporter")
|
||||
@@ -550,6 +551,7 @@ mod tests {
|
||||
#[test]
|
||||
fn accepted_native_close_finishes_before_process_termination() {
|
||||
let dir = folder();
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let status = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "native-close")
|
||||
@@ -595,6 +597,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_aborting_parent_leaves_one_diagnostic_report() {
|
||||
let dir = folder();
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let status = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "abort")
|
||||
@@ -616,6 +619,7 @@ mod tests {
|
||||
fn an_unrelated_child_does_not_keep_the_control_pipe_open() {
|
||||
let dir = folder();
|
||||
let r = helper(&dir, "5-1");
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let mut unrelated = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "linger")
|
||||
@@ -632,6 +636,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_unresponsive_helper_cannot_hang_clean_shutdown() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "linger")
|
||||
@@ -704,6 +709,7 @@ mod tests {
|
||||
#[cfg(windows)]
|
||||
fn windows_report_preserves_real_unsigned_exit_bits() {
|
||||
let dir = folder();
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let status = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"])
|
||||
.env(ROLE, "windows-status")
|
||||
|
||||
@@ -214,8 +214,8 @@ mod tests {
|
||||
/// A launch that never drew switches the next one to OpenGL, which then stays (#243).
|
||||
#[test]
|
||||
fn a_launch_that_never_drew_switches_the_next_to_opengl() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("never-drew");
|
||||
// A first launch that draws: nothing changes. Its first frames don't settle it (a driver
|
||||
// may still crash as the window is shown); frames for `SETTLE` do.
|
||||
let mut l = Launch::begin(Some(&dir), false);
|
||||
@@ -259,8 +259,8 @@ mod tests {
|
||||
/// normal quit in that time doesn't.
|
||||
#[test]
|
||||
fn a_launch_that_stops_after_its_first_frame_switches_the_next_to_opengl() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-3-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("first-frame");
|
||||
let mut l = Launch::begin(Some(&dir), false);
|
||||
assert!(l.frame_drawn().is_some());
|
||||
drop(l);
|
||||
@@ -286,8 +286,8 @@ mod tests {
|
||||
/// open a window either goes back to Automatic instead of failing every launch.
|
||||
#[test]
|
||||
fn a_second_copy_or_failed_opengl_doesnt_strand_window_graphics() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-copy");
|
||||
let _first = Launch::begin(Some(&dir), false);
|
||||
assert_eq!(Launch::begin(Some(&dir), false).backends, None);
|
||||
assert_eq!(window_graphics(&dir), "auto");
|
||||
@@ -303,10 +303,7 @@ mod tests {
|
||||
|
||||
/// A fresh settings folder for one test.
|
||||
fn fresh_dir(case: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("ec-launch-guard-{case}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
tempfile::Builder::new().prefix(&format!("ec-launch-guard-{case}-")).tempdir().unwrap().keep()
|
||||
}
|
||||
|
||||
/// Window Graphics saved as OpenGL.
|
||||
@@ -318,6 +315,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_second_copy_reports_the_saved_backend_without_owning_the_guard() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-source");
|
||||
save_opengl(&dir);
|
||||
let mut first = Launch::begin(Some(&dir), false);
|
||||
@@ -333,6 +331,7 @@ mod tests {
|
||||
/// one's marker (#477).
|
||||
#[test]
|
||||
fn a_second_copy_quitting_leaves_the_running_launchs_marker() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-quits");
|
||||
let mut first = Launch::begin(Some(&dir), false);
|
||||
let mut second = Launch::begin(Some(&dir), false);
|
||||
@@ -346,6 +345,7 @@ mod tests {
|
||||
/// A second copy whose OpenGL window fails doesn't remove a running launch's marker.
|
||||
#[test]
|
||||
fn failed_opengl_in_a_second_copy_leaves_the_running_launchs_marker() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-gl-fails");
|
||||
let mut first = Launch::begin(Some(&dir), false);
|
||||
let second = Launch::begin(Some(&dir), false);
|
||||
@@ -360,6 +360,7 @@ mod tests {
|
||||
/// With `WGPU_BACKEND` set, a stale marker and a saved OpenGL choice are left as they are.
|
||||
#[test]
|
||||
fn wgpu_backend_leaves_a_stale_marker_and_saved_opengl_alone() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("env-override");
|
||||
save_opengl(&dir);
|
||||
std::fs::write(dir.join(MARKER), b"stale-marker").unwrap();
|
||||
@@ -376,6 +377,7 @@ mod tests {
|
||||
/// After OpenGL fails to open a window, the next launch is back on Automatic, without a notice.
|
||||
#[test]
|
||||
fn failed_opengl_puts_the_next_launch_back_on_automatic() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("gl-recovers");
|
||||
save_opengl(&dir);
|
||||
let l = Launch::begin(Some(&dir), false);
|
||||
@@ -396,6 +398,7 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_guard_file_stays_the_same_file_across_launches() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let dir = fresh_dir("guard-identity");
|
||||
let mut a = Launch::begin(Some(&dir), false);
|
||||
@@ -417,6 +420,7 @@ mod tests {
|
||||
/// A second copy's frames and quit neither settle nor unlock the running launch.
|
||||
#[test]
|
||||
fn a_second_copys_frames_dont_settle_the_running_launch() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("second-frames");
|
||||
let mut a = Launch::begin(Some(&dir), false);
|
||||
std::fs::write(dir.join(MARKER), b"owner-marker").unwrap();
|
||||
@@ -438,6 +442,7 @@ mod tests {
|
||||
/// once it has stopped without settling the next launch still switches to OpenGL.
|
||||
#[test]
|
||||
fn a_running_older_version_holding_the_marker_is_left_alone() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("older-version");
|
||||
std::fs::write(dir.join(MARKER), b"old-owner").unwrap();
|
||||
std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap();
|
||||
@@ -468,6 +473,7 @@ mod tests {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn an_unopenable_marker_leaves_settings_and_marker_alone() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
|
||||
let dir = fresh_dir("marker-unopenable");
|
||||
@@ -491,6 +497,7 @@ mod tests {
|
||||
/// A guard file that can't be opened leaves Window Graphics and the marker as they are.
|
||||
#[test]
|
||||
fn an_unusable_guard_file_leaves_settings_and_marker_alone() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("guard-unusable");
|
||||
std::fs::create_dir(dir.join(LOCK)).unwrap();
|
||||
std::fs::write(dir.join(MARKER), b"stale-marker").unwrap();
|
||||
@@ -512,6 +519,7 @@ mod tests {
|
||||
/// Window Graphics to Automatic and removes the marker.
|
||||
#[test]
|
||||
fn failed_opengl_cleanup_waits_for_the_running_launch() {
|
||||
let _spawn_lock = crate::test_child_spawn_lock();
|
||||
let dir = fresh_dir("gl-cleanup-waits");
|
||||
save_opengl(&dir);
|
||||
let launch = Launch::begin(Some(&dir), false);
|
||||
|
||||
@@ -35,6 +35,17 @@ mod window;
|
||||
use effectcraft_ui_egui::EffectcraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
// On Unix, a subprocess briefly inherits every non-CLOFORK descriptor between fork and exec.
|
||||
// The app's guard-lock tests hold an advisory lock while crash-reporter tests spawn child
|
||||
// processes; coordinate just those intervals so an unrelated test child cannot extend a lock.
|
||||
#[cfg(test)]
|
||||
static TEST_CHILD_SPAWN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
fn test_child_spawn_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
TEST_CHILD_SPAWN_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// 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).
|
||||
|
||||
@@ -77,6 +77,10 @@ solid, a folder, a Levels and a Glow effect with expressions). Every After Effec
|
||||
the working space's ICC profile (HP sRGB IEC61966-2.1 for the default) in a JSON settings chunk;
|
||||
the one `Utf8` chunk of this file that held a profile was replaced by `{}`, and nothing else was
|
||||
changed. The tests in `tests/it/import/synthetic.rs` damage copies of it and need no other file.
|
||||
`tests/fixtures/text-synthetic.aep` is the other: made in After Effects 2026 the same way (working
|
||||
space None, nothing changed after the save), one composition with two text layers that hold a
|
||||
text animator's Stroke Opacity (static and keyed) and Source Text expressions (enabled and
|
||||
disabled); `tests/it/import/text_synthetic.rs` reads it (#3170).
|
||||
|
||||
`tests/fixtures/ai-mask-3099.aep` (131 KB, #3099) is the second: four hand-written one-page PDFs
|
||||
named `.ai` with distinct page boxes, placed in a composition, one of them with two masks under a
|
||||
|
||||
@@ -38,6 +38,19 @@ pub enum Conv {
|
||||
Skip,
|
||||
}
|
||||
|
||||
impl Conv {
|
||||
/// For a number (`Percent`, `Plain`, `Factor`): what a stored value is multiplied by to give
|
||||
/// the value here. `None` for every other conversion.
|
||||
pub fn number_scale(self) -> Option<f64> {
|
||||
match self {
|
||||
Conv::Percent { valid_max } => Some(100.0 / valid_max),
|
||||
Conv::Plain { .. } => Some(1.0),
|
||||
Conv::Factor { factor, .. } => Some(factor),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// After Effects' popup items as the corpus stores them (`pdnm`).
|
||||
/// 368.
|
||||
pub const RAMP_SHAPE: &[&str] = &["Linear Ramp", "Radial Ramp"];
|
||||
|
||||
@@ -707,3 +707,99 @@ pub(crate) static FX_DEFS: &[FxDef] = &[
|
||||
p(BUILT_IN, 9, &[], None, None, None, 0x00000000),
|
||||
]),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::container::effect_map::by_match_name;
|
||||
use effectcraft_project::ParamUi;
|
||||
|
||||
/// Effect parameters whose hard range (`ParamUi::Slider` min..max, which `prop.set` and the
|
||||
/// value editors clamp to) is still narrower than After Effects' recorded valid range, each
|
||||
/// with the open issue that tracks it: (effect, parameter, issue). Remove a row when its
|
||||
/// issue is fixed; the test fails on a row that is no longer needed.
|
||||
#[rustfmt::skip]
|
||||
const KNOWN_NARROWER: &[(&str, &str, u32)] = &[
|
||||
("ec.blur.gaussian", "blurriness", 3460),
|
||||
("ec.blur.fastbox", "radius", 3461),
|
||||
("ec.blur.channel", "redBlurriness", 3462),
|
||||
("ec.blur.channel", "greenBlurriness", 3462),
|
||||
("ec.blur.channel", "blueBlurriness", 3462),
|
||||
("ec.blur.channel", "alphaBlurriness", 3462),
|
||||
("ec.obsolete.gaussianlegacy", "blurriness", 3463),
|
||||
("ec.perspective.dropshadow", "softness", 3464),
|
||||
("ec.blur.compound", "maximumBlur", 3465),
|
||||
("ec.blur.sharpen", "amount", 3466),
|
||||
("ec.blur.radial", "amount", 3467),
|
||||
("ec.blur.ccradial", "amount", 3468),
|
||||
("ec.distort.turbulentdisplace", "amount", 3469),
|
||||
("ec.time.pixelmotionblur", "shutterAngle", 3481),
|
||||
("ec.time.pixelmotionblur", "shutterSamples", 3482),
|
||||
("ec.noise.fractal", "subSettings/subInfluence", 3485),
|
||||
("ec.noise.fractal", "subSettings/subScaling", 3486),
|
||||
("ec.distort.ccpowerpin", "expandTop", 3492),
|
||||
("ec.distort.ccpowerpin", "expandLeft", 3492),
|
||||
("ec.distort.ccpowerpin", "expandRight", 3492),
|
||||
("ec.distort.ccpowerpin", "expandBottom", 3492),
|
||||
];
|
||||
|
||||
/// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from.
|
||||
fn at_most(a: f64, b: f64) -> bool {
|
||||
a <= b + 1e-6 * a.abs().max(b.abs()).max(1.0)
|
||||
}
|
||||
|
||||
/// Every effect parameter the .aep table maps to a recorded After Effects definition accepts
|
||||
/// at least After Effects' valid range, converted to EffectCraft's units the way the importer
|
||||
/// converts values (`Conv::number_scale`). Only `ParamUi::Slider` limits values (`prop.set`,
|
||||
/// the Effect Controls and Timeline editors); other controls take any number. A mapping with
|
||||
/// a declared narrower range (`ParamMap::limit`) must match the effect's range instead.
|
||||
#[test]
|
||||
fn effect_hard_ranges_cover_recorded_after_effects_ranges() {
|
||||
let mut problems = Vec::new();
|
||||
let mut narrower = Vec::new();
|
||||
for fx in FX_DEFS {
|
||||
let Some(map) = by_match_name(fx.match_name) else { continue };
|
||||
let Some(spec) = effectcraft_effects::find(map.effect) else {
|
||||
problems.push(format!("{}: no effect {}", fx.match_name, map.effect));
|
||||
continue;
|
||||
};
|
||||
for pm in map.params {
|
||||
let Some(scale) = pm.conv.number_scale() else { continue };
|
||||
let at = format!("{} {}", map.effect, pm.target);
|
||||
let Some(ps) = spec.params.iter().find(|p| p.id == pm.target) else {
|
||||
problems.push(format!("{at}: not a parameter of the effect"));
|
||||
continue;
|
||||
};
|
||||
// Other controls take any number.
|
||||
let ParamUi::Slider { min, max, .. } = &ps.ui else { continue };
|
||||
let Some(def) = fx.params.get(pm.index) else {
|
||||
problems.push(format!("{at}: no recorded definition at parT {}", pm.index));
|
||||
continue;
|
||||
};
|
||||
let (Some(lo), Some(hi)) = (def.valid_min, def.valid_max) else {
|
||||
problems.push(format!("{at}: no recorded valid range"));
|
||||
continue;
|
||||
};
|
||||
let (lo, hi) = (lo * scale, hi * scale);
|
||||
if let Some(limit) = pm.limit {
|
||||
if limit != (*min, *max) {
|
||||
problems.push(format!("{at}: declared limit {limit:?} is not the effect's range {min}..{max}"));
|
||||
}
|
||||
} else if !(at_most(*min, lo) && at_most(hi, *max)) {
|
||||
narrower.push((map.effect, pm.target, format!("{at}: {min}..{max} excludes After Effects' {lo}..{hi}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (effect, param, why) in &narrower {
|
||||
if !KNOWN_NARROWER.iter().any(|(e, p, _)| e == effect && p == param) {
|
||||
problems.push(why.clone());
|
||||
}
|
||||
}
|
||||
for (effect, param, issue) in KNOWN_NARROWER {
|
||||
if !narrower.iter().any(|(e, p, _)| e == effect && p == param) {
|
||||
problems.push(format!("{effect} {param}: covers After Effects' range now (or is not mapped); remove it from KNOWN_NARROWER (#{issue})"));
|
||||
}
|
||||
}
|
||||
assert!(problems.is_empty(), "{}", problems.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +89,8 @@ pub(crate) struct TextPlan {
|
||||
pub frame: Option<[f64; 4]>,
|
||||
/// The text animators (planned with the layer's time base, `textanim.rs`).
|
||||
pub animators: Vec<crate::export::textanim::AnimPlan>,
|
||||
/// The Source Text expression and its enable switch.
|
||||
pub expr: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
/// Where a text value is written, for the loss report.
|
||||
@@ -133,16 +135,19 @@ pub(crate) fn plan_text(layer: &Layer, comp_name: &str, col: &mut Collector) ->
|
||||
if !st.keys.is_empty() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not written (the first key's text is)"));
|
||||
}
|
||||
if st.has_expression() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not written"));
|
||||
}
|
||||
let value = st.keys.first().map(|k| &k.value).unwrap_or(&st.value);
|
||||
let Value::Text(doc) = value else {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text holds no text document"));
|
||||
return None;
|
||||
};
|
||||
report_extras(text, &what, col);
|
||||
Some(plan_doc(doc, &what, col))
|
||||
let mut plan = plan_doc(doc, &what, col);
|
||||
// Written enabled or disabled, as on any other property.
|
||||
plan.expr = st.expr.as_ref().filter(|e| !e.text.is_empty()).map(|e| (e.text.clone(), e.enabled));
|
||||
if plan.expr.is_some() {
|
||||
col.exported.expressions = col.exported.expressions.saturating_add(1);
|
||||
}
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
/// Path / More Options that hold anything other than a new text layer's defaults are not
|
||||
@@ -190,6 +195,8 @@ fn differs(g: &PropGroup, def: Option<&PropGroup>, depth: usize) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The text document `doc` in the file's terms (text, style runs, paragraphs, box); what the file
|
||||
/// cannot hold is reported for `what`.
|
||||
fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan {
|
||||
let base = doc.base_style();
|
||||
let runs = doc.runs();
|
||||
@@ -288,7 +295,7 @@ fn plan_doc(doc: &TextDoc, what: &str, col: &mut Collector) -> TextPlan {
|
||||
at.fit(h, (1.0, 1e6), 1.0, "box height"),
|
||||
]
|
||||
});
|
||||
TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new() }
|
||||
TextPlan { text, runs: out_runs, paras, frame, animators: Vec::new(), expr: None }
|
||||
}
|
||||
|
||||
fn style_out(s: &effectcraft_keyframe::text_doc::CharStyle, what: &str, col: &mut Collector) -> StyleOut {
|
||||
@@ -518,11 +525,47 @@ pub(crate) fn build_doc(proto: &TNode, tp: &TextPlan) -> Option<TNode> {
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
/// Rewrites the text document of a text layer block's `Layr` for `tp` and gives the document a
|
||||
/// fresh `btgu/pgui`.
|
||||
/// The Source Text expression into the `tdbs` of `btds` (`docs/aep-format.md` 3.10, read back from
|
||||
/// `tests/fixtures/text-synthetic.aep`): `tdb4` byte 120 = 1, byte 119 = 1 when disabled, and the
|
||||
/// text as a `Utf8` after the record's `cdat`.
|
||||
fn put_source_text_expression(layr: &mut crate::Chunk<'static>, text: &str, enabled: bool) -> crate::export::tree::R<()> {
|
||||
use crate::Body;
|
||||
use crate::export::tree::tpl;
|
||||
/// The `tdbs` of the first `btds` below `c`, at most 32 levels down.
|
||||
fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
}
|
||||
if c.is_list(b"btds") {
|
||||
return match &mut c.body {
|
||||
Body::List { children, .. } => children.iter_mut().find(|k| k.is_list(b"tdbs")),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
match &mut c.body {
|
||||
Body::List { children, .. } | Body::Chunks(children) => children.iter_mut().find_map(|k| find(k, depth + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let tdbs = find(layr, 0).ok_or_else(|| tpl("text prototype without a Source Text record"))?;
|
||||
let Body::List { children, .. } = &mut tdbs.body else { return Err(tpl("text prototype without a Source Text record")) };
|
||||
let tdb4 = children.iter_mut().find(|k| k.is(b"tdb4")).ok_or_else(|| tpl("Source Text record without tdb4"))?;
|
||||
let Body::Data(d) = &mut tdb4.body else { return Err(tpl("Source Text record without tdb4")) };
|
||||
let d = d.to_mut();
|
||||
*d.get_mut(120).ok_or_else(|| tpl("short Source Text tdb4"))? = 1;
|
||||
*d.get_mut(119).ok_or_else(|| tpl("short Source Text tdb4"))? = u8::from(!enabled);
|
||||
children.retain(|k| !k.is(b"Utf8"));
|
||||
let at = children.iter().position(|k| k.is(b"tdum")).unwrap_or(children.len());
|
||||
children.insert(at, crate::Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites the text document of a text layer block's `Layr` for `tp`, writes its Source Text
|
||||
/// expression and gives the document a fresh `btgu/pgui`.
|
||||
pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8; 16]) -> crate::export::tree::R<()> {
|
||||
use crate::Body;
|
||||
use crate::export::tree::tpl;
|
||||
/// The first `LIST btdk` below `c`, at most 32 levels down.
|
||||
fn find<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
@@ -535,6 +578,7 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The first `pgui` of the first `btgu` below `c`, at most 32 levels down.
|
||||
fn find_pgui<'c>(c: &'c mut crate::Chunk<'static>, depth: usize) -> Option<&'c mut crate::Chunk<'static>> {
|
||||
if depth > 32 {
|
||||
return None;
|
||||
@@ -555,6 +599,9 @@ pub(crate) fn put_doc(layr: &mut crate::Chunk<'static>, tp: &TextPlan, guid: [u8
|
||||
let proto = crate::export::textdoc::parse(data.as_ref()).ok_or_else(|| tpl("the text prototype's document does not parse"))?;
|
||||
let doc = build_doc(&proto, tp).ok_or_else(|| tpl("the text prototype's document has another shape"))?;
|
||||
*data = std::borrow::Cow::Owned(crate::export::textdoc::write(&doc));
|
||||
if let Some((text, enabled)) = &tp.expr {
|
||||
put_source_text_expression(layr, text, *enabled)?;
|
||||
}
|
||||
if let Some(p) = find_pgui(layr, 0) {
|
||||
*p = crate::Chunk::data(*b"pgui", guid.to_vec());
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ const PROPS: &[(&str, &str, Conv, Layout)] = &[
|
||||
("opacity", "ADBE Text Opacity", c_scalar, Layout::One),
|
||||
("fillColor", "ADBE Text Fill Color", c_color, Layout::Color),
|
||||
("strokeColor", "ADBE Text Stroke Color", c_color, Layout::Color),
|
||||
("strokeOpacity", "ADBE Text Stroke Opacity", c_scalar, Layout::One),
|
||||
("strokeWidth", "ADBE Text Stroke Width", c_scalar, Layout::One),
|
||||
("tracking", "ADBE Text Tracking Amount", c_scalar, Layout::One),
|
||||
("lineSpacing", "ADBE Text Line Spacing", c_vec2, Layout::Size),
|
||||
|
||||
@@ -264,6 +264,8 @@ pub(crate) static TEXT_ANIMATOR_RECORDS: &[Node] = &[
|
||||
R("ADBE Text Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[37.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Fill Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
R("ADBE Text Stroke Color", Rec { state: 1, label: "-_0_/-", dims: 4, template: 0, class: 0x0002ffff, byte5: 0x07, header: &[(79, 1)], cdat_len: 96, cdat: &[255.0, 0.0, 0.0, 255.0], key_size: 0, limits: None, tdpi: None }),
|
||||
// text-synthetic.aep (#3170): the record After Effects wrote for Stroke Opacity 40 %.
|
||||
R("ADBE Text Stroke Opacity", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[40.0], key_size: 0, limits: Some((0.0, 100.0)), tdpi: None }),
|
||||
R("ADBE Text Stroke Width", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[3.0], key_size: 0, limits: Some((-1000.0, 1000.0)), tdpi: None }),
|
||||
R("ADBE Text Tracking Amount", Rec { state: 1, label: "-_0_/-", dims: 1, template: 0, class: 0xffffffff, byte5: 0x01, header: &[], cdat_len: 40, cdat: &[20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
R("ADBE Text Line Spacing", Rec { state: 1, label: "-_0_/-", dims: 2, template: 0, class: 0x0002ffff, byte5: 0x01, header: &[], cdat_len: 80, cdat: &[10.0, 20.0], key_size: 0, limits: Some((-32000.0, 32000.0)), tdpi: None }),
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
//! missing-footage placeholders). `docs/aep-import.md` has the full list.
|
||||
//!
|
||||
//! What does not arrive is **reported**, never dropped silently: [`ImportReport`] counts other
|
||||
//! effects (by match name) and unimported effect parameters, unusable masks, layer style
|
||||
//! effects (by match name; they arrive as placeholders that render nothing, with their parameters
|
||||
//! for expressions) and unimported effect parameters, unusable masks, layer style
|
||||
//! features, text layer features, shape items, unsupported blend modes and transform
|
||||
//! properties, simplified keyframes and unreadable data per [`LossCategory`]. By default the import
|
||||
//! is refused when anything would be lost ([`ImportOptions::allow_losses`] lifts that); a refusal
|
||||
@@ -30,6 +31,7 @@ mod effects;
|
||||
mod lumetri;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod placeholder;
|
||||
mod props;
|
||||
mod puppet;
|
||||
mod report;
|
||||
|
||||
@@ -12,7 +12,8 @@ use effectcraft_color::{BlendMode, Label};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{
|
||||
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, TrackMatte,
|
||||
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, SourceLayer,
|
||||
TrackMatte,
|
||||
};
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
@@ -25,7 +26,7 @@ use crate::import::props::{AnchorUnit, import_transform};
|
||||
use crate::import::report::{Collector, ImportReport, LossCategory};
|
||||
use crate::import::shapes::import_shapes;
|
||||
use crate::import::styles::import_layer_styles;
|
||||
use crate::import::text::{report_text_extras, text_doc};
|
||||
use crate::import::text::{import_source_text_expression, report_text_extras, text_doc};
|
||||
use crate::import::text_anim::import_animators;
|
||||
use crate::import::time::{TimeMap, frame_rate};
|
||||
|
||||
@@ -216,7 +217,17 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
let aep_id = item.id();
|
||||
// An item without a stored name shows its file's name, a sequence `shot_[0101-0103].exr`
|
||||
// (126, 603-607).
|
||||
let name = if name.is_empty() { default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()) } else { name };
|
||||
// One layer of a Photoshop file is `<layer>/<file>`, as EffectCraft's own Photoshop import
|
||||
// names it (#3087).
|
||||
let name = if name.is_empty() {
|
||||
let file = default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string());
|
||||
match &f.psd_layer {
|
||||
Some(l) if !l.name.is_empty() => format!("{}/{file}", l.name),
|
||||
_ => file,
|
||||
}
|
||||
} else {
|
||||
name
|
||||
};
|
||||
if f.is_solid {
|
||||
// A null object's placeholder solid is not an item here.
|
||||
if aep_id.is_some_and(|i| null_only.contains(&i)) {
|
||||
@@ -299,6 +310,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
|
||||
missing: !present,
|
||||
placed_page,
|
||||
sequence,
|
||||
layer: source_layer(&f, &name, &mut cx.col),
|
||||
..Footage::default()
|
||||
};
|
||||
// The native frame rate and the stored duration of sequences and clips (352, 603, 606).
|
||||
@@ -338,6 +350,34 @@ fn is_placed_page_path(path: &str) -> bool {
|
||||
matches!(ext.as_deref(), Some("pdf" | "ai"))
|
||||
}
|
||||
|
||||
/// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big
|
||||
/// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment
|
||||
/// layer) keeps the merged image and is reported. So is a layer as big as the document but not at
|
||||
/// its corner (the item's size fits both framings; its bounds are used), and an item as big as
|
||||
/// neither (the document is used).
|
||||
fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option<SourceLayer> {
|
||||
let l = f.psd_layer.as_ref()?;
|
||||
let Some(size) = l.size() else {
|
||||
col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used"));
|
||||
return None;
|
||||
};
|
||||
let layer_size = size == (f.width, f.height);
|
||||
if !layer_size && l.document.iter().all(|side| *side > 0) && !l.document_is((f.width, f.height)) {
|
||||
col.lose(
|
||||
LossCategory::UnsupportedItems,
|
||||
format!("footage '{name}': {} x {} is neither the Photoshop layer's size nor the document's, shown on the document", f.width, f.height),
|
||||
);
|
||||
}
|
||||
let [top, left, ..] = l.bounds;
|
||||
if layer_size && (top, left) != (0, 0) && l.document_is(size) {
|
||||
col.lose(
|
||||
LossCategory::UnsupportedItems,
|
||||
format!("footage '{name}': a Photoshop layer as big as the document but at ({left}, {top}), shown at its own bounds (Retain Layer Sizes assumed)"),
|
||||
);
|
||||
}
|
||||
Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size, ..SourceLayer::default() })
|
||||
}
|
||||
|
||||
/// The name After Effects shows for a footage item that stores none: the file's name, or for a
|
||||
/// sequence the name with the frame range (`shot_[0101-0103].exr`).
|
||||
fn default_footage_name(item: &AepItem<'_, '_>, f: &crate::Footage) -> Option<String> {
|
||||
@@ -667,8 +707,8 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
|
||||
}
|
||||
}
|
||||
|
||||
/// The Source Text of a text layer from its text document, and the reports of what is not
|
||||
/// imported.
|
||||
/// The Source Text of a text layer from its text document and its expression, and the reports
|
||||
/// of what is not imported.
|
||||
fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &mut Ctx<'_>) {
|
||||
match layer.text_document() {
|
||||
Some(doc) => {
|
||||
@@ -680,6 +720,7 @@ fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &
|
||||
}
|
||||
None => cx.col.lose(LossCategory::DamagedData, format!("{what}: the text document is unreadable, the layer is imported with empty text")),
|
||||
}
|
||||
import_source_text_expression(layer, l.props.prop_mut("text/sourceText"), what, &mut cx.col);
|
||||
report_text_extras(layer, what, &mut cx.col);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Effects: a table maps an After Effects effect (its match name) and its parameters (by their
|
||||
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Effects and
|
||||
//! parameters outside the table are reported in [`LossCategory::Effects`] by match name, never
|
||||
//! dropped silently.
|
||||
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Parameters
|
||||
//! outside the table are reported in [`LossCategory::Effects`] by match name, never dropped
|
||||
//! silently. An effect outside it arrives as a placeholder holding its parameters (`placeholder.rs`)
|
||||
//! and is reported too.
|
||||
//!
|
||||
//! Every conversion is backed by the corpus (`docs/aep-format.md` 3.7, cases 356-450, 511-516):
|
||||
//!
|
||||
@@ -82,44 +83,37 @@ pub(crate) fn import_effects<'f, 'a>(
|
||||
continue;
|
||||
}
|
||||
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
|
||||
let Some(map) = EFFECTS.iter().find(|m| m.match_name == fx.match_name()) else {
|
||||
col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
|
||||
continue;
|
||||
};
|
||||
let Some(spec) = effectcraft_effects::find(map.effect) else {
|
||||
col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
|
||||
continue;
|
||||
};
|
||||
let found = EFFECTS.iter().find(|m| m.match_name == fx.match_name()).and_then(|m| Some((m, effectcraft_effects::find(m.effect)?)));
|
||||
let lost = format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
if defs.source(&fx) == DefinitionSource::Missing {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()),
|
||||
);
|
||||
match found {
|
||||
Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")),
|
||||
None => col.lose_unmapped_effect(fx.match_name(), lost),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
|
||||
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
|
||||
match fx.enabled() {
|
||||
Some(on) => group.enabled = on,
|
||||
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
|
||||
if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST {
|
||||
// The import's placeholder budget is spent: the definitions (shared by many instances)
|
||||
// are not read again. Named like any effect without a counterpart, in a group of its
|
||||
// own (with the kept instances it would read as kept).
|
||||
let key = format!("{} (not kept)", fx.match_name());
|
||||
col.lose_unmapped_effect(&key, format!("{lost}, not kept (past the import's placeholder parameters)"));
|
||||
continue;
|
||||
}
|
||||
let params = defs.params(&fx);
|
||||
// Borrowed definitions (another instance's or the project copy) may not name every value
|
||||
// record this instance has: such a record has nothing to import into, so it is reported.
|
||||
if params.first().is_some_and(|p| p.borrowed_definition) {
|
||||
let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect();
|
||||
for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!(
|
||||
"{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported",
|
||||
cx.comp,
|
||||
cx.layer,
|
||||
fx.match_name()
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
report_records_without_definition(&fx, ¶ms, cx, &shown, col);
|
||||
let Some((map, spec)) = found else {
|
||||
// No counterpart: kept as a placeholder that renders nothing, for expressions (#3087).
|
||||
let mut group = crate::import::placeholder::placeholder(&fx, ¶ms, cx, &shown, ids, refs, col);
|
||||
set_enabled(&fx, &mut group, cx, &shown, col);
|
||||
col.lose_unmapped_effect(fx.match_name(), format!("{lost}, kept without rendering"));
|
||||
col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1);
|
||||
target.children.push(Node::Group(group));
|
||||
continue;
|
||||
};
|
||||
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
|
||||
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
|
||||
set_enabled(&fx, &mut group, cx, &shown, col);
|
||||
if map.extra == Extra::Lumetri {
|
||||
crate::import::lumetri::import_lumetri(&fx, ¶ms, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
} else if map.extra == Extra::Cryptomatte {
|
||||
@@ -134,6 +128,29 @@ pub(crate) fn import_effects<'f, 'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect's fx switch.
|
||||
fn set_enabled(fx: &AepEffect<'_, '_>, group: &mut PropGroup, cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
|
||||
match fx.enabled() {
|
||||
Some(on) => group.enabled = on,
|
||||
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed definitions (another instance's or the project copy) may not name every value record
|
||||
/// this instance has: such a record has nothing to import into, so it is reported.
|
||||
fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
|
||||
if !params.first().is_some_and(|p| p.borrowed_definition) {
|
||||
return;
|
||||
}
|
||||
let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect();
|
||||
for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) {
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters that never carry a value to import.
|
||||
pub(crate) fn carries_nothing(p: &EffectParam<'_, '_>) -> bool {
|
||||
matches!(p.kind, ParamKind::Button | ParamKind::NoData | ParamKind::GroupStart | ParamKind::GroupEnd) || (p.index == 0 && p.kind == ParamKind::Layer)
|
||||
@@ -242,23 +259,12 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
|
||||
Conv::Checkbox => Kind::EffectBool,
|
||||
// Handled above.
|
||||
Conv::LayerRef { .. } | Conv::Skip => return,
|
||||
Conv::Percent { valid_max } => {
|
||||
Conv::Percent { valid_max } | Conv::Plain { valid_max } | Conv::Factor { valid_max, .. } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(100.0 / valid_max)
|
||||
}
|
||||
Conv::Plain { valid_max } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(1.0)
|
||||
}
|
||||
Conv::Factor { valid_max, factor } => {
|
||||
if !checked(valid_max, col) {
|
||||
return;
|
||||
}
|
||||
Kind::EffectNumber(factor)
|
||||
let Some(scale) = m.conv.number_scale() else { return };
|
||||
Kind::EffectNumber(scale)
|
||||
}
|
||||
};
|
||||
// Grouped parameters are addressed by path (`master/exposure`).
|
||||
@@ -364,7 +370,7 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator<Item
|
||||
/// A layer parameter: None stays unset, the owning layer is itself (`own`) or unset, another layer
|
||||
/// is resolved by [`resolve_layer_refs`] once the composition's layers exist.
|
||||
/// `names` is `(here, label)`, the effect and the parameter for the report.
|
||||
fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
|
||||
pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
|
||||
let (here, label) = names;
|
||||
let ParamOut { group, refs, col } = out;
|
||||
// After Effects hands the named layer's source to the effect, without its masks and effects
|
||||
@@ -804,7 +810,7 @@ fn px(v: f64) -> String {
|
||||
|
||||
/// A decoded value in EffectCraft's units, `None` when it does not fit the kind or is not a valid
|
||||
/// number.
|
||||
fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
|
||||
pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
|
||||
let raw = match (value, kind) {
|
||||
// The reader gives colours as ARGB fractions; `Kind` takes the stored 0..255.
|
||||
(ParamValue::Argb(c), Kind::EffectColor) => c.map(|x| x * 255.0).to_vec(),
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Placeholders: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect
|
||||
//! of expression controls) arrives as an effect group that renders nothing, as a missing plug-in
|
||||
//! does. Its effect id is the After Effects match name, so Find Missing Effects lists it. It holds
|
||||
//! the effect's parameters, flat and named as in After Effects, each with its value, keys and
|
||||
//! expression, so expressions that read them (`effect("Settings")("Speed")`) keep working. It is
|
||||
//! still reported, once per match name.
|
||||
//!
|
||||
//! The values keep After Effects' units, the ones its expressions read: sliders and angles as
|
||||
//! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's
|
||||
//! 0-based items over the file's items in order (expressions read them 1-based, as After Effects
|
||||
//! does). Layer parameters name their layer (their keys and expression are reported). Paths and
|
||||
//! arbitrary data are not kept (reported when they hold something).
|
||||
//!
|
||||
//! The parameters placeholders walk, kept or not, and their popup items (by name length) are
|
||||
//! bounded per import ([`MAX_COST`]): definitions can be shared by many instances, so a small file
|
||||
//! could otherwise ask for very many properties. Once
|
||||
//! the budget is spent, later effects without a counterpart are reported without a placeholder.
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, Node, ParamUi, PropGroup, Property};
|
||||
|
||||
use crate::import::effects::{LayerCtx, ParamOut, PendingLayerRef, carries_nothing, convert, import_layer_ref, param_label};
|
||||
use crate::import::props::{Kind, import_expression, import_keys};
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue};
|
||||
|
||||
/// Most placeholder parameters (kept or not) and popup items one import walks.
|
||||
pub(crate) const MAX_COST: usize = 200_000;
|
||||
|
||||
/// Most items read from one placeholder popup.
|
||||
const MAX_POPUP_ITEMS: usize = 1024;
|
||||
|
||||
/// A popup item costs one more for each of these bytes in its name, so the names kept stay
|
||||
/// bounded too.
|
||||
const NAME_BYTES: usize = 16;
|
||||
|
||||
/// The placeholder of `fx`, with `params` (its parameter definitions) as properties.
|
||||
pub(crate) fn placeholder(
|
||||
fx: &AepEffect<'_, '_>,
|
||||
params: &[EffectParam<'_, '_>],
|
||||
cx: &LayerCtx<'_>,
|
||||
shown: &str,
|
||||
ids: &mut Ids<'_>,
|
||||
refs: &mut Vec<PendingLayerRef>,
|
||||
col: &mut Collector,
|
||||
) -> PropGroup {
|
||||
// The effect id is the match name; the group's match id is one segment of a property path
|
||||
// (a pseudo effect's `Pseudo/0.25` would be cut apart), so match paths find its parameters.
|
||||
let mut group = ids.group(&segment(fx.match_name()), shown);
|
||||
group.kind = GroupKind::Effect { effect: fx.match_name().to_string() };
|
||||
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
|
||||
for p in params {
|
||||
// Every parameter walked counts, kept or not: a definition shared by many instances is
|
||||
// otherwise walked again for each one.
|
||||
if carries_nothing(p) {
|
||||
col.placeholder_cost = col.placeholder_cost.saturating_add(1).min(MAX_COST);
|
||||
continue;
|
||||
}
|
||||
if col.placeholder_cost >= MAX_COST {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept"));
|
||||
break;
|
||||
}
|
||||
let label = param_label(p);
|
||||
let Some((kind, ui, default)) = shape(p, cx.size) else {
|
||||
col.placeholder_cost = col.placeholder_cost.saturating_add(1);
|
||||
if p.stored().is_some() {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let (items, names) = match &ui {
|
||||
ParamUi::Popup { options } => (options.len(), options.iter().map(|o| 1 + o.len() / NAME_BYTES).fold(0, usize::saturating_add)),
|
||||
_ => (0, 0),
|
||||
};
|
||||
if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept"));
|
||||
}
|
||||
let cost = col.placeholder_cost.saturating_add(names).saturating_add(1);
|
||||
if cost > MAX_COST {
|
||||
// The budget is spent: nothing more is built, here or in later effects (definitions
|
||||
// shared by many instances would otherwise still be walked item by item).
|
||||
col.lose(
|
||||
LossCategory::Effects,
|
||||
format!("{here}: parameter {label} and the ones after it not kept (past the import's {MAX_COST} placeholder parameters)"),
|
||||
);
|
||||
col.placeholder_cost = MAX_COST;
|
||||
break;
|
||||
}
|
||||
col.placeholder_cost = cost;
|
||||
let mut prop = Property::new(ids.alloc(), ¶m_id(p), p.name.trim(), default).with_ui(ui);
|
||||
prop.spatial = p.kind == ParamKind::Point;
|
||||
prop.hold_only = matches!(p.kind, ParamKind::Checkbox | ParamKind::Popup | ParamKind::Layer);
|
||||
match kind {
|
||||
Some(kind) => {
|
||||
fill(p, &mut prop, kind, cx, (&here, &label), col);
|
||||
group.children.push(Node::Prop(prop));
|
||||
}
|
||||
// A layer parameter: the layer it names (set once every layer exists, by its uid).
|
||||
None => {
|
||||
let id = format!("@{}", prop.uid);
|
||||
group.children.push(Node::Prop(prop));
|
||||
import_layer_ref(p, &id, true, cx, (&here, &label), ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
|
||||
}
|
||||
}
|
||||
}
|
||||
group
|
||||
}
|
||||
|
||||
/// How parameter `p` is held on a layer `size` big: its unit conversion (`None` for a layer
|
||||
/// parameter), its control and its value until one is read. `None` for a type that is not kept.
|
||||
fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option<Kind>, ParamUi, Value)> {
|
||||
let (kind, ui, default) = match p.kind {
|
||||
ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), slider_ui(p), Value::Scalar(0.0)),
|
||||
ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)),
|
||||
ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)),
|
||||
ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])),
|
||||
ParamKind::Point => (Kind::EffectPoint(f64::from(size.0), f64::from(size.1)), ParamUi::Point, Value::Vec2([0.0, 0.0])),
|
||||
ParamKind::Layer => return Some((None, ParamUi::Layer, Value::Layer(None))),
|
||||
ParamKind::Popup => {
|
||||
// The file's items, separators (`(-`) included: After Effects counts them.
|
||||
let options: Vec<String> = match &p.items {
|
||||
Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(),
|
||||
None => (1..=popup_len(p)?.min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(),
|
||||
};
|
||||
let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?;
|
||||
(Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((Some(kind), ui, default))
|
||||
}
|
||||
|
||||
/// A slider's control: a float slider's valid range and drag range when they are ranges (only a
|
||||
/// float slider's are decoded), else a plain number.
|
||||
fn slider_ui(p: &EffectParam<'_, '_>) -> ParamUi {
|
||||
match (p.valid_min(), p.valid_max(), p.slider_range()) {
|
||||
(Some(min), Some(max), Some((smin, smax))) if [min, max, smin, smax].iter().all(|v| v.is_finite()) && min <= max && smin <= smax => {
|
||||
ParamUi::Slider { min, max, slider_min: smin.clamp(min, max), slider_max: smax.clamp(min, max), decimals: 2 }
|
||||
}
|
||||
_ => ParamUi::Number,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many items a popup has: the file's names, else the count in its definition.
|
||||
fn popup_len(p: &EffectParam<'_, '_>) -> Option<usize> {
|
||||
p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from))
|
||||
}
|
||||
|
||||
/// The property id of `p`: its match name when that is one segment of a property path (a
|
||||
/// third-party effect's `CC Cylinder-0003`), else `param<index>` (a pseudo effect's
|
||||
/// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name.
|
||||
fn param_id(p: &EffectParam<'_, '_>) -> String {
|
||||
if !p.match_name.is_empty() && p.match_name.chars().all(plain) { p.match_name.clone() } else { format!("param{}", p.index) }
|
||||
}
|
||||
|
||||
/// Whether `c` can stand in one segment of a property path (`/`, `.`, `#` and `@` mean more).
|
||||
fn plain(c: char) -> bool {
|
||||
c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')
|
||||
}
|
||||
|
||||
/// `name` as one segment of a property path: other characters become `_` (`Pseudo/0.25` is
|
||||
/// `Pseudo_0_25`).
|
||||
fn segment(name: &str) -> String {
|
||||
name.chars().map(|c| if plain(c) { c } else { '_' }).collect()
|
||||
}
|
||||
|
||||
/// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard`
|
||||
/// default). `names` is `(here, label)` for the report.
|
||||
fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx<'_>, names: (&str, &str), col: &mut Collector) {
|
||||
let (here, label) = names;
|
||||
if let Some(stored) = p.stored() {
|
||||
import_expression(&stored, prop, col);
|
||||
}
|
||||
if p.is_animated() {
|
||||
let Some(stored) = p.stored() else { return };
|
||||
if kind == Kind::EffectBool {
|
||||
// Keys on a checkbox are not sampled by the corpus.
|
||||
col.lose(LossCategory::Effects, format!("{here}: the keyframes of parameter {label} are not kept (not decoded)"));
|
||||
return;
|
||||
}
|
||||
let before = prop.keys.len();
|
||||
import_keys(&stored, kind, cx.layer, &p.match_name, cx.tm, prop, col);
|
||||
if prop.keys.len() == before {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let value = match (p.stored(), p.recorded_value()) {
|
||||
(Some(_), Some(v)) => v,
|
||||
(Some(_), None) => {
|
||||
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value"));
|
||||
return;
|
||||
}
|
||||
// A borrowed popup's default slot holds another copy's selection (docs/aep-format.md 3.7).
|
||||
(None, _) if p.kind == ParamKind::Popup && p.borrowed_definition => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not known (shared definition), the first item used"));
|
||||
return;
|
||||
}
|
||||
// A popup's default slot can hold 0, no item (After Effects' save of a project it opened).
|
||||
(None, _) => match p.pard_default() {
|
||||
Some(ParamValue::Index(0)) => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not stored, the first item used"));
|
||||
return;
|
||||
}
|
||||
Some(v) => v,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
match (convert(value, kind), value) {
|
||||
(Some(v), _) => prop.value = v,
|
||||
// An item of the file that is past the ones kept (reported with the cut): the first item.
|
||||
(None, ParamValue::Index(i)) if usize::try_from(i).is_ok_and(|i| i > MAX_POPUP_ITEMS && popup_len(p).is_some_and(|n| i <= n)) => {
|
||||
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item {i} is past the items kept, the first item used"));
|
||||
}
|
||||
(None, _) => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")),
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,8 @@ pub enum LossCategory {
|
||||
/// Layers that could not be imported for another reason (unknown layer type, missing or
|
||||
/// unsupported source, precomposition loop).
|
||||
UnsupportedLayers,
|
||||
/// Project items of a kind that is not imported.
|
||||
/// Project items of a kind that is not imported, and items made from a Photoshop layer
|
||||
/// without pixels (they show the merged image).
|
||||
UnsupportedItems,
|
||||
/// Data that could not be read (damaged headers, unreadable keyframes).
|
||||
DamagedData,
|
||||
@@ -160,6 +161,10 @@ pub struct Imported {
|
||||
/// in [`LossCategory::Effects`]).
|
||||
#[serde(default)]
|
||||
pub effects: usize,
|
||||
/// Effects with no counterpart, kept as placeholders that render nothing (their parameters,
|
||||
/// for expressions; each is also in [`LossCategory::Effects`]).
|
||||
#[serde(default)]
|
||||
pub placeholder_effects: usize,
|
||||
/// Layer styles (Drop Shadow, Stroke, ...), one per style on a layer.
|
||||
#[serde(default)]
|
||||
pub layer_styles: usize,
|
||||
@@ -277,6 +282,9 @@ pub(crate) struct Collector {
|
||||
/// many instances there were. They get a line each in [`Collector::finish`], so one that
|
||||
/// comes after the example lines are used up is still named (#3365).
|
||||
unmapped_effects: BTreeMap<String, (String, usize)>,
|
||||
/// The properties and popup items the placeholders of this import hold so far (at most
|
||||
/// `placeholder::MAX_COST`).
|
||||
pub placeholder_cost: usize,
|
||||
}
|
||||
|
||||
/// How many different unmapped effects get a line of their own (a file names at most this many).
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
|
||||
use crate::{AutoKern, Caps, FontBaseline, Justification, Layer as AepLayer, ParagraphRun, PropGroup, PropNode, StyleRun as AepRun, TextDocument};
|
||||
use effectcraft_keyframe::text_doc::{BaselineOption, CharStyle, Composer, Direction, Justify, Kerning, ParaStyle, StyleRun, TextDoc};
|
||||
use effectcraft_project::Property;
|
||||
|
||||
use crate::import::props::import_expression;
|
||||
use crate::import::report::{Collector, LossCategory};
|
||||
|
||||
/// How deep the walk over the text property groups goes.
|
||||
@@ -344,15 +346,27 @@ fn has_stored(g: &PropGroup<'_, '_>, depth: usize) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The Source Text expression into `target` (the layer's `text/sourceText`). The Source Text
|
||||
/// record keeps it like any other property: the text in its `Utf8`, the flags in its `tdb4`
|
||||
/// (`tests/fixtures/text-synthetic.aep`). An expression whose flags are unreadable, or a layer
|
||||
/// without a Source Text property, is reported.
|
||||
pub(crate) fn import_source_text_expression(layer: &AepLayer<'_, '_>, target: Option<&mut Property>, what: &str, col: &mut Collector) {
|
||||
let Some(st) = layer.source_text_property() else { return };
|
||||
if st.expression().is_none() {
|
||||
return;
|
||||
}
|
||||
match target {
|
||||
Some(p) if st.expression_enabled().is_some() => import_expression(&st, p, col),
|
||||
_ => col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a text layer besides its first text document that are not imported.
|
||||
pub(crate) fn report_text_extras(layer: &AepLayer<'_, '_>, what: &str, col: &mut Collector) {
|
||||
if let Some(st) = layer.source_text_property() {
|
||||
if st.is_animated() || layer.text_document_count() > 1 {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)"));
|
||||
}
|
||||
if st.expression().is_some() {
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: the Source Text expression is not imported"));
|
||||
}
|
||||
if let Some(st) = layer.source_text_property()
|
||||
&& (st.is_animated() || layer.text_document_count() > 1)
|
||||
{
|
||||
col.lose(LossCategory::TextLayers, format!("{what}: Source Text keyframes are not imported (the first text document is)"));
|
||||
}
|
||||
let Some(PropNode::Group(text)) = layer.properties().and_then(|p| p.get("ADBE Text Properties")) else { return };
|
||||
for e in text.entries() {
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
//!
|
||||
//! Not imported, and reported in [`LossCategory::TextLayers`]: wiggly and expression selectors,
|
||||
//! animator properties other than the ones mapped below (Character Value, Fill / Stroke
|
||||
//! Hue, Saturation, Brightness and Opacity, 3D rotations, variable font axes, ...), and a Tracking
|
||||
//! Type other than the default.
|
||||
//! Hue, Saturation and Brightness, Fill Opacity, 3D rotations, variable font axes, ...), and a
|
||||
//! Tracking Type other than the default.
|
||||
|
||||
use crate::{PropGroup as AepGroup, PropNode, Property as AepProp};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
@@ -37,6 +37,7 @@ const PROPS: &[(&str, &str, &str, Kind)] = &[
|
||||
("ADBE Text Opacity", "opacity", "opacity", Kind::Number),
|
||||
("ADBE Text Fill Color", "fillColor", "fillColor", Kind::EffectColor),
|
||||
("ADBE Text Stroke Color", "strokeColor", "strokeColor", Kind::EffectColor),
|
||||
("ADBE Text Stroke Opacity", "strokeOpacity", "strokeOpacity", Kind::Number),
|
||||
("ADBE Text Stroke Width", "strokeWidth", "strokeWidth", Kind::Number),
|
||||
("ADBE Text Tracking Amount", "tracking", "tracking", Kind::Number),
|
||||
("ADBE Text Line Spacing", "lineSpacing", "lineSpacing", Kind::Vec2),
|
||||
|
||||
@@ -21,8 +21,8 @@ pub use container::{
|
||||
GradientType, HueSaturationData, Interpolation, Item, ItemKind, Justification, KernRun, KeyEase, KeyLayout, KeyList, Keyframe, KeyframeKind, LIST, Layer,
|
||||
LayerHeader, LayerRef, LayerType, LevelsData, LightType, Limits, ListHeader, Marker, Mask, MaskAtom, MaskMode, MatteMode, MeshData, NESTED_IDS,
|
||||
Orientation, OrientationKey, ParagraphRun, ParamKind, ParamValue, PathVertex, PolystarType, Project, ProjectSettings, PropEntry, PropGroup, PropNode,
|
||||
Property, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, StyleRun,
|
||||
TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, WorkingSpace,
|
||||
curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, read_aepx_with_limits, style_map,
|
||||
write, write_to,
|
||||
Property, PsdLayer, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin,
|
||||
StyleRun, TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk,
|
||||
WorkingSpace, curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx,
|
||||
read_aepx_with_limits, style_map, write, write_to,
|
||||
};
|
||||
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
asset: text-synthetic.aep
|
||||
title: Small After Effects test project for the .aep importer's text animator and Source Text expression tests
|
||||
author: EffectCraft contributors
|
||||
source: original work (made in After Effects 2026 by script from own data: a composition with two text layers, a text animator Stroke Opacity, static and keyed, and Source Text expressions, enabled and disabled)
|
||||
license: MIT OR Apache-2.0
|
||||
added: 2026-11-08 by EffectCraft contributors
|
||||
notes: The working space was set to None, so the file embeds no ICC profile; nothing After Effects wrote was changed. See crates/aep/README.md (Clean room).
|
||||
@@ -18,10 +18,12 @@ mod effects_round2;
|
||||
mod effects_round3;
|
||||
mod effects_thirdparty;
|
||||
mod fx_inject;
|
||||
mod issue_3087;
|
||||
mod lumetri;
|
||||
mod markers;
|
||||
mod masks;
|
||||
mod mattes;
|
||||
mod placeholders;
|
||||
mod puppet;
|
||||
mod resaved_defaults;
|
||||
mod robustness;
|
||||
@@ -31,5 +33,6 @@ mod styles;
|
||||
mod synthetic;
|
||||
mod text;
|
||||
mod text_anim;
|
||||
mod text_synthetic;
|
||||
mod timing;
|
||||
mod versions;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
|
||||
use effectcraft_aep::{Body, Chunk, ParamKind, ParamValue, Project as AepProject, parse, write};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Project, PropGroup};
|
||||
use effectcraft_project::{GroupKind, Project, PropGroup};
|
||||
|
||||
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
|
||||
|
||||
@@ -274,10 +274,15 @@ pub fn import_bytes(bytes: &[u8], effect: &str) -> (Option<PropGroup>, ImportRes
|
||||
let mut project = Project::default();
|
||||
let none = |_: &str| false;
|
||||
let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
|
||||
let g = project
|
||||
.comps()
|
||||
.flat_map(|(_, c)| c.layers.iter())
|
||||
.find_map(|l| l.props.sub("effects").and_then(|fx| fx.children.iter().filter_map(|n| n.as_group()).find(|g| g.match_id == effect).cloned()));
|
||||
let g = project.comps().flat_map(|(_, c)| c.layers.iter()).find_map(|l| {
|
||||
l.props.sub("effects").and_then(|fx| {
|
||||
fx.children
|
||||
.iter()
|
||||
.filter_map(|n| n.as_group())
|
||||
.find(|g| g.match_id == effect || matches!(&g.kind, GroupKind::Effect { effect: e } if e == effect))
|
||||
.cloned()
|
||||
})
|
||||
});
|
||||
(g, r)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! #3087: an expression on Orientation, built into the committed `synthetic.aep` (no external
|
||||
//! files; the values are made up, the layouts are docs/aep-format.md's). The Photoshop layers and
|
||||
//! placeholders of the issue are tested in `synthetic.rs` and `placeholders.rs`.
|
||||
|
||||
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
|
||||
use effectcraft_aep::{Body, Chunk, parse, write};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::Project;
|
||||
|
||||
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
|
||||
|
||||
fn visit(chunks: &mut [Chunk<'_>], f: &mut dyn FnMut(&mut Chunk<'_>)) {
|
||||
for c in chunks {
|
||||
f(c);
|
||||
visit(c.children_mut(), f);
|
||||
}
|
||||
}
|
||||
|
||||
fn import_all(bytes: &[u8]) -> (Project, ImportResult) {
|
||||
let mut project = Project::default();
|
||||
let none = |_: &str| false;
|
||||
let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
|
||||
(project, r)
|
||||
}
|
||||
|
||||
/// `synthetic.aep` with every Orientation set to `[10, 20, 30]` and the expression `text`.
|
||||
fn with_orientation_expression(text: &str) -> Vec<u8> {
|
||||
let mut file = parse(SYNTHETIC).unwrap();
|
||||
let mut patched = 0;
|
||||
visit(&mut file.chunks, &mut |c| {
|
||||
if !c.is_list(b"otst") {
|
||||
return;
|
||||
}
|
||||
for k in c.children_mut() {
|
||||
if k.is_list(b"tdbs") {
|
||||
let kids = k.children_mut();
|
||||
for r in kids.iter_mut() {
|
||||
if let Body::Data(d) = &mut r.body {
|
||||
let d = d.to_mut();
|
||||
match &r.id {
|
||||
b"tdsb" => d.copy_from_slice(&1u32.to_be_bytes()),
|
||||
b"tdb4" => {
|
||||
d[119] = 0;
|
||||
d[120] = 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Body::List { children, .. } = &mut k.body else { continue };
|
||||
children.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
} else if k.is_list(b"otky") {
|
||||
let mut otda = Vec::new();
|
||||
for v in [10.0f64, 20.0, 30.0] {
|
||||
otda.extend(v.to_be_bytes());
|
||||
}
|
||||
*k = Chunk::list(*b"otky", vec![Chunk::data(*b"otda", otda)]);
|
||||
}
|
||||
}
|
||||
patched += 1;
|
||||
});
|
||||
assert!(patched > 0, "the synthetic project has an Orientation");
|
||||
write(&file).unwrap()
|
||||
}
|
||||
|
||||
/// An expression on Orientation arrives with the value (both were dropped and reported "not
|
||||
/// decoded").
|
||||
#[test]
|
||||
fn an_expression_on_orientation_is_imported() {
|
||||
let (p, r) = import_all(&with_orientation_expression("[1, 2, 3]"));
|
||||
let mut seen = 0;
|
||||
for (_, c) in p.comps() {
|
||||
for l in &c.layers {
|
||||
let Some(o) = l.props.prop("transform/orientation") else { continue };
|
||||
assert_eq!(o.value, Value::Vec3([10.0, 20.0, 30.0]), "{}", l.name);
|
||||
assert_eq!(o.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("[1, 2, 3]", true)), "{}", l.name);
|
||||
seen += 1;
|
||||
}
|
||||
}
|
||||
assert!(seen > 0);
|
||||
let orientation: Vec<String> = r
|
||||
.report
|
||||
.losses
|
||||
.iter()
|
||||
.filter(|l| l.category == LossCategory::TransformProperties)
|
||||
.flat_map(|l| l.details.clone())
|
||||
.filter(|d| d.contains("Orientation"))
|
||||
.collect();
|
||||
assert!(orientation.is_empty(), "{orientation:?}");
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! #3087: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect of
|
||||
//! expression controls) arrives as a placeholder holding its parameters, so expressions that read
|
||||
//! them keep working; it renders nothing and is still reported. Each effect is built into
|
||||
//! `synthetic.aep` (`fx_inject`) in place of its Glow, on the 8 x 8 sequence layer.
|
||||
|
||||
use crate::import::fx_inject::{Default, Fx, bytes_with, import_bytes, losses, other, popup, run, slider, v};
|
||||
use effectcraft_aep::import::LossCategory;
|
||||
use effectcraft_aep::{Body, Chunk, ParamKind as K, parse, write};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{GroupKind, ParamUi, PropGroup};
|
||||
|
||||
/// A third-party effect with one parameter of each kept kind, inside a twirl-down group.
|
||||
fn third_party(values: Vec<(usize, f64)>, keys: Vec<(usize, Vec<(i32, f64)>)>) -> Fx {
|
||||
Fx {
|
||||
match_name: "CC Cylinder",
|
||||
name: "CC Cylinder",
|
||||
defs: vec![
|
||||
other(K::GroupStart, "Light", Default::None),
|
||||
slider(K::FloatSlider, "Radius (%)", 30.0, (0.0, 30000.0)),
|
||||
other(K::GroupEnd, "", Default::None),
|
||||
other(K::Angle, "Rotation X", Default::Number(12.5)),
|
||||
other(K::Checkbox, "Wire", Default::Number(1.0)),
|
||||
other(K::Color, "Light Color", Default::Color([255, 51, 102, 204])),
|
||||
other(K::Point, "Position", Default::Point(0.25, 0.5)),
|
||||
popup("Render", 1, &["Full", "(-", "Outside", "Inside"]),
|
||||
slider(K::IntSlider, "Count", 3.0, (0.0, 50.0)),
|
||||
],
|
||||
values,
|
||||
data: vec![],
|
||||
keys,
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_of(fx: &Fx) -> (PropGroup, effectcraft_aep::import::ImportResult) {
|
||||
let (g, r) = run(fx, fx.match_name);
|
||||
(g.expect("the placeholder"), r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_without_a_counterpart_is_kept_with_its_values() {
|
||||
// Radius 37.5 and Render "Outside" (3: the separator counts) stored, the rest at defaults.
|
||||
let (g, r) = placeholder_of(&third_party(vec![(2, 37.5), (8, 3.0)], vec![]));
|
||||
assert_eq!(g.kind, GroupKind::Effect { effect: "CC Cylinder".into() });
|
||||
assert_eq!(g.name, "CC Cylinder");
|
||||
let names: Vec<(&str, &str)> = g.props().map(|p| (p.match_id.as_str(), p.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("CC Cylinder-0002", "Radius (%)"),
|
||||
("CC Cylinder-0004", "Rotation X"),
|
||||
("CC Cylinder-0005", "Wire"),
|
||||
("CC Cylinder-0006", "Light Color"),
|
||||
("CC Cylinder-0007", "Position"),
|
||||
("CC Cylinder-0008", "Render"),
|
||||
("CC Cylinder-0009", "Count"),
|
||||
],
|
||||
"flat, in order, without the group markers"
|
||||
);
|
||||
assert_eq!(v(&g, "CC Cylinder-0002"), Value::Scalar(37.5));
|
||||
assert_eq!(v(&g, "CC Cylinder-0004"), Value::Scalar(12.5));
|
||||
assert_eq!(v(&g, "CC Cylinder-0005"), Value::Bool(true));
|
||||
let Value::Color(c) = v(&g, "CC Cylinder-0006") else { panic!("a colour") };
|
||||
assert!(c.iter().zip([0.2, 0.4, 0.8, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{c:?}");
|
||||
assert_eq!(v(&g, "CC Cylinder-0007"), Value::Vec2([2.0, 4.0]), "layer pixels");
|
||||
assert_eq!(v(&g, "CC Cylinder-0008"), Value::Enum(2), "item 3 of 4, 0-based");
|
||||
assert_eq!(v(&g, "CC Cylinder-0009"), Value::Scalar(3.0));
|
||||
let render = g.prop("CC Cylinder-0008").unwrap();
|
||||
assert_eq!(render.ui, ParamUi::Popup { options: ["Full", "(-", "Outside", "Inside"].map(String::from).to_vec() });
|
||||
// Still reported, once, and counted apart from the imported effects.
|
||||
let found = losses(&r, LossCategory::Effects, "CC Cylinder");
|
||||
assert!(found.len() == 1 && found[0].ends_with("has the effect 'CC Cylinder' (CC Cylinder), kept without rendering"), "{found:?}");
|
||||
assert_eq!((r.report.imported.placeholder_effects, r.report.imported.effects), (1, 1), "the placeholder and the Levels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_and_expressions_of_a_placeholder_are_kept() {
|
||||
let fx = third_party(vec![(4, 12.5)], vec![(2, vec![(0, 10.0), (25, 20.0)])]);
|
||||
let bytes = with_expression(&bytes_with(&fx), "CC Cylinder-0004", "time * 90");
|
||||
let (g, _) = import_bytes(&bytes, "CC Cylinder");
|
||||
let g = g.unwrap();
|
||||
let radius = g.prop("CC Cylinder-0002").unwrap();
|
||||
assert_eq!(radius.keys.iter().map(|k| k.value.clone()).collect::<Vec<_>>(), [Value::Scalar(10.0), Value::Scalar(20.0)]);
|
||||
let angle = g.prop("CC Cylinder-0004").unwrap();
|
||||
assert_eq!(angle.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("time * 90", true)));
|
||||
}
|
||||
|
||||
/// A pseudo effect's parameter match names (`Pseudo/0.25-0001`) are no property path segment:
|
||||
/// its parameters are `param<index>`, found by their names.
|
||||
#[test]
|
||||
fn a_pseudo_effect_is_kept_with_its_parameter_names() {
|
||||
let fx = Fx {
|
||||
match_name: "Pseudo/0.25",
|
||||
name: "Settings",
|
||||
defs: vec![slider(K::FloatSlider, "Speed", 1.0, (0.0, 100.0)), popup("Mode", 2, &["A", "B"])],
|
||||
values: vec![(1, 4.0)],
|
||||
data: vec![],
|
||||
keys: vec![],
|
||||
};
|
||||
let (g, r) = placeholder_of(&fx);
|
||||
assert_eq!(g.prop("param1").map(|p| (p.name.as_str(), p.value.clone())), Some(("Speed", Value::Scalar(4.0))));
|
||||
assert_eq!(g.prop("param2").map(|p| (p.name.as_str(), p.value.clone())), Some(("Mode", Value::Enum(1))));
|
||||
assert_eq!(losses(&r, LossCategory::Effects, "Pseudo/0.25").len(), 1);
|
||||
// The effect id stays the match name (Find Missing Effects, expressions); the group's match id
|
||||
// is one path segment, so a match path (keyframe paste, pick whip) finds its parameters again.
|
||||
assert_eq!(g.kind, GroupKind::Effect { effect: "Pseudo/0.25".into() });
|
||||
let speed = g.prop("param1").map(|p| p.uid);
|
||||
let layer = PropGroup::new(0, "layer", "Layer").with(PropGroup::new(0, "effects", "Effects").with(g));
|
||||
let path = speed.and_then(|u| layer.match_path_of(u));
|
||||
assert_eq!(path.as_deref().and_then(|p| layer.prop(p)).map(|p| p.name.as_str()), Some("Speed"), "{path:?}");
|
||||
}
|
||||
|
||||
/// A float slider keeps its valid range and slider range, so Effect Controls drags and clamps it
|
||||
/// as After Effects does; a range that is not a range stays a plain number.
|
||||
#[test]
|
||||
fn a_float_slider_keeps_its_range() {
|
||||
let fx = Fx {
|
||||
match_name: "Pseudo/r",
|
||||
name: "Rig",
|
||||
defs: vec![slider(K::FloatSlider, "Speed", 1.0, (-10.0, 100.0)), slider(K::FloatSlider, "Odd", 1.0, (5.0, 1.0))],
|
||||
values: vec![],
|
||||
data: vec![],
|
||||
keys: vec![],
|
||||
};
|
||||
let (g, _) = placeholder_of(&fx);
|
||||
let ui = |id: &str| g.prop(id).map(|p| p.ui.clone());
|
||||
assert_eq!(ui("param1"), Some(ParamUi::Slider { min: -10.0, max: 100.0, slider_min: -10.0, slider_max: 100.0, decimals: 2 }));
|
||||
assert_eq!(ui("param2"), Some(ParamUi::Number));
|
||||
}
|
||||
|
||||
/// A popup whose definition is borrowed (the project copy) and has no value record: its default
|
||||
/// slot holds another copy's selection, so the first item is used and that is reported.
|
||||
#[test]
|
||||
fn a_borrowed_popup_without_a_record_takes_the_first_item_and_is_reported() {
|
||||
let bytes = without_instance_definitions(&bytes_with(&third_party(vec![], vec![])));
|
||||
let (g, r) = import_bytes(&bytes, "CC Cylinder");
|
||||
assert_eq!(v(&g.unwrap(), "CC Cylinder-0008"), Value::Enum(0));
|
||||
let found = losses(&r, LossCategory::Effects, "CC Cylinder");
|
||||
assert!(found.iter().any(|d| d.contains("Render") && d.contains("default item is not known")), "{found:?}");
|
||||
}
|
||||
|
||||
/// A popup default slot of 0 (no item; After Effects' save of a project it opened) takes the first
|
||||
/// item and is reported, not read as damaged data.
|
||||
#[test]
|
||||
fn a_popup_default_of_no_item_takes_the_first_item() {
|
||||
let fx = Fx { match_name: "Some Fx", name: "Some", defs: vec![popup("Mode", 0, &["A", "B"])], values: vec![], data: vec![], keys: vec![] };
|
||||
let (g, r) = placeholder_of(&fx);
|
||||
assert_eq!(v(&g, "Some Fx-0001"), Value::Enum(0));
|
||||
let found = losses(&r, LossCategory::Effects, "Some Fx");
|
||||
assert!(found.iter().any(|d| d.contains("default item is not stored")), "{found:?}");
|
||||
assert!(losses(&r, LossCategory::DamagedData, "Some Fx").is_empty());
|
||||
}
|
||||
|
||||
/// A popup past the 1024 items kept: the cut is reported, and a selection among the cut items
|
||||
/// takes the first item and is reported as such, not as damaged data.
|
||||
#[test]
|
||||
fn a_popup_past_the_items_kept_is_reported() {
|
||||
let items: &'static [&'static str] = Box::leak((0..1100).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
|
||||
let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("Pick", 1, items)], values: vec![(1, 1050.0)], data: vec![], keys: vec![] };
|
||||
let (g, r) = placeholder_of(&fx);
|
||||
let pick = g.prop("Long Fx-0001").unwrap();
|
||||
assert_eq!(pick.value, Value::Enum(0));
|
||||
assert!(matches!(&pick.ui, ParamUi::Popup { options } if options.len() == 1024));
|
||||
let found = losses(&r, LossCategory::Effects, "Long Fx");
|
||||
assert!(found.iter().any(|d| d.contains("past the first 1024")), "{found:?}");
|
||||
assert!(found.iter().any(|d| d.contains("item 1050 is past the items kept")), "{found:?}");
|
||||
assert!(losses(&r, LossCategory::DamagedData, "Long Fx").is_empty());
|
||||
}
|
||||
|
||||
/// Many large popups stay within the import's budget: what is beyond is reported, not kept.
|
||||
#[test]
|
||||
fn a_hostile_placeholder_stays_bounded() {
|
||||
let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
|
||||
let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] };
|
||||
let (g, r) = placeholder_of(&fx);
|
||||
let kept = g.props().count();
|
||||
assert!(kept > 0 && kept < 300, "{kept}");
|
||||
assert!(g.props().map(|p| if let ParamUi::Popup { options } = &p.ui { options.len() + 1 } else { 1 }).sum::<usize>() <= 200_000);
|
||||
assert!(losses(&r, LossCategory::Effects, "Big Fx").iter().any(|d| d.contains("placeholder parameters")));
|
||||
}
|
||||
|
||||
/// Two instances of an effect whose parameters fill the import's budget: the first keeps what fits
|
||||
/// and stops at the first parameter past it; the second is reported without a placeholder (its
|
||||
/// shared definitions are not read again).
|
||||
#[test]
|
||||
fn an_effect_past_the_spent_budget_gets_no_placeholder() {
|
||||
let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
|
||||
let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] };
|
||||
let bytes = twice(&bytes_with(&fx), "Big Fx");
|
||||
let mut project = effectcraft_project::Project::default();
|
||||
let none = |_: &str| false;
|
||||
let r = effectcraft_aep::import::import(
|
||||
&mut project,
|
||||
&bytes,
|
||||
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
|
||||
)
|
||||
.unwrap();
|
||||
let placeholders: Vec<usize> = project
|
||||
.comps()
|
||||
.flat_map(|(_, c)| c.layers.iter())
|
||||
.filter_map(|l| l.props.sub("effects"))
|
||||
.flat_map(|fx| fx.children.iter().filter_map(|n| n.as_group()).filter(|g| g.match_id == "Big Fx").map(|g| g.props().count()).collect::<Vec<_>>())
|
||||
.collect();
|
||||
// 199 popups of 1000 items (1001 each) fit in 200 000; the 200th stops the first instance.
|
||||
assert_eq!(placeholders, [199]);
|
||||
let found = losses(&r, LossCategory::Effects, "Big Fx");
|
||||
assert_eq!(found.iter().filter(|d| d.contains("and the ones after it not kept")).count(), 1, "{found:?}");
|
||||
assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}");
|
||||
assert!(found.iter().any(|d| d.contains("kept without rendering") && !d.contains("more like it")), "the kept instance alone: {found:?}");
|
||||
}
|
||||
|
||||
/// Parameters a placeholder does not keep (markers, arbitrary data) still spend the budget: a
|
||||
/// definition of very many of them, shared by many instances, is not walked again for each one.
|
||||
#[test]
|
||||
fn parameters_not_kept_still_spend_the_budget() {
|
||||
let defs = (0..200_000).map(|i| other(if i % 2 == 0 { K::NoData } else { K::ArbitraryData }, "X", Default::None)).collect();
|
||||
let fx = Fx { match_name: "Odd Fx", name: "Odd", defs, values: vec![], data: vec![], keys: vec![] };
|
||||
let (_, r) = import_bytes(&twice(&bytes_with(&fx), "Odd Fx"), "Odd Fx");
|
||||
let found = losses(&r, LossCategory::Effects, "Odd Fx");
|
||||
assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}");
|
||||
}
|
||||
|
||||
/// Long popup item names spend the budget by their length, so the names kept stay bounded.
|
||||
#[test]
|
||||
fn long_popup_item_names_spend_the_budget() {
|
||||
let long = "x".repeat(1600);
|
||||
let items: &'static [&'static str] =
|
||||
Box::leak((0..1024).map(|i| &*Box::leak(format!("{long}{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
|
||||
let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("A", 1, items), popup("B", 1, items)], values: vec![], data: vec![], keys: vec![] };
|
||||
let (g, r) = placeholder_of(&fx);
|
||||
assert_eq!(g.props().count(), 1);
|
||||
assert!(losses(&r, LossCategory::Effects, "Long Fx").iter().any(|d| d.contains("placeholder parameters")));
|
||||
}
|
||||
|
||||
/// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it.
|
||||
fn twice(bytes: &[u8], match_name: &str) -> Vec<u8> {
|
||||
let mut file = parse(bytes).unwrap();
|
||||
let mut done = 0;
|
||||
edit(&mut file.chunks, false, &mut |c, in_project_copy| {
|
||||
let Body::List { children, .. } = &mut c.body else { return };
|
||||
if in_project_copy {
|
||||
return;
|
||||
}
|
||||
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(match_name.as_bytes())))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let pair: Vec<Chunk<'_>> = children[at..at + 2].to_vec();
|
||||
children.splice(at + 2..at + 2, pair);
|
||||
done += 1;
|
||||
});
|
||||
assert_eq!(done, 1, "one instance");
|
||||
write(&file).unwrap()
|
||||
}
|
||||
|
||||
/// `bytes` with the expression `text` on the parameter record `param` (enabled: `tdb4` byte 120
|
||||
/// 1, docs/aep-format.md 3.6).
|
||||
fn with_expression(bytes: &[u8], param: &str, text: &str) -> Vec<u8> {
|
||||
let mut file = parse(bytes).unwrap();
|
||||
let mut done = 0;
|
||||
edit(&mut file.chunks, false, &mut |c, _| {
|
||||
let Body::List { children, .. } = &mut c.body else { return };
|
||||
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(param.as_bytes()))) else {
|
||||
return;
|
||||
};
|
||||
let Some(Body::List { children: record, .. }) = children.get_mut(at + 1).map(|k| &mut k.body) else { return };
|
||||
for k in record.iter_mut().filter(|k| k.is(b"tdb4")) {
|
||||
if let Body::Data(d) = &mut k.body
|
||||
&& let Some(b) = d.to_mut().get_mut(120)
|
||||
{
|
||||
*b = 1;
|
||||
}
|
||||
}
|
||||
record.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
|
||||
done += 1;
|
||||
});
|
||||
assert!(done >= 1);
|
||||
write(&file).unwrap()
|
||||
}
|
||||
|
||||
/// `bytes` with the layer's instance of `CC Cylinder` stripped of its own definitions (an empty
|
||||
/// `parT`): it borrows the project copy's (`EfdG`).
|
||||
fn without_instance_definitions(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut file = parse(bytes).unwrap();
|
||||
let mut done = 0;
|
||||
edit(&mut file.chunks, false, &mut |c, in_project_copy| {
|
||||
let Body::List { children, .. } = &mut c.body else { return };
|
||||
if in_project_copy {
|
||||
return;
|
||||
}
|
||||
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(&b"CC Cylinder"[..])))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(sspc) = children.get_mut(at + 1).filter(|k| k.is_list(b"sspc")) else { return };
|
||||
for k in sspc.children_mut() {
|
||||
if let Body::List { list_type, children } = &mut k.body
|
||||
&& list_type == b"parT"
|
||||
{
|
||||
children.clear();
|
||||
done += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(done, 1, "one instance");
|
||||
write(&file).unwrap()
|
||||
}
|
||||
|
||||
/// Calls `f` on every chunk with whether it is inside the project's effect definitions (`EfdG`).
|
||||
fn edit(chunks: &mut [Chunk<'_>], in_efdg: bool, f: &mut dyn FnMut(&mut Chunk<'_>, bool)) {
|
||||
for c in chunks {
|
||||
let inside = in_efdg || c.is_list(b"EfdG");
|
||||
f(c, inside);
|
||||
edit(c.children_mut(), inside, f);
|
||||
}
|
||||
}
|
||||
@@ -843,6 +843,92 @@ fn a_default_state_colour_record_holds_the_value() {
|
||||
assert_ne!(colour(&default_state), colour(&unchanged), "the recorded colour, not the default");
|
||||
}
|
||||
|
||||
/// The project with its png item made one layer of a Photoshop file `art.psd`: the `opti` of
|
||||
/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, a 1000 x 1000 document at 32 and 36,
|
||||
/// its bounds at 78-94, its name at 344) and the item `size` big.
|
||||
fn as_psd_layer(index: i32, bounds: [i32; 4], name: &str, size: (u32, u32)) -> Vec<u8> {
|
||||
let mut opti = vec![0u8; 602];
|
||||
opti[..4].copy_from_slice(b"8BPS");
|
||||
opti[14..18].copy_from_slice(&index.to_be_bytes());
|
||||
opti[32..36].copy_from_slice(&1000u32.to_le_bytes());
|
||||
opti[36..40].copy_from_slice(&1000u32.to_le_bytes());
|
||||
for (i, v) in bounds.iter().enumerate() {
|
||||
opti[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
opti[344..344 + name.len()].copy_from_slice(name.as_bytes());
|
||||
let alias = br#"{"fullpath":"C:\\x\\art.psd","platform":1,"target_is_folder":false}"#.to_vec();
|
||||
mutate(&mut |c| {
|
||||
if !c.is_list(b"Pin ") {
|
||||
return;
|
||||
}
|
||||
let Body::List { children, .. } = &mut c.body else { return };
|
||||
if !children.iter().any(|k| k.is(b"opti") && k.bytes().is_some_and(|d| d.get(..4) == Some(&b"png!"[..]))) {
|
||||
return;
|
||||
}
|
||||
// No sequence naming between the alias and the `opti`.
|
||||
children.retain(|k| k.is(b"sspc") || k.is(b"opti") || k.is_list(b"Als2"));
|
||||
for k in children.iter_mut() {
|
||||
if k.is(b"opti") {
|
||||
k.body = Body::Data(opti.clone().into());
|
||||
} else if k.is(b"sspc") {
|
||||
set_data(k, 30, &size.0.to_be_bytes());
|
||||
set_data(k, 34, &size.1.to_be_bytes());
|
||||
}
|
||||
}
|
||||
visit(children, &mut |k| {
|
||||
if k.is(b"alas") {
|
||||
k.body = Body::Data(alias.clone().into());
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/// #3087: an item made from one layer of a Photoshop file shows that layer, named
|
||||
/// `<layer>/<file>`; it showed the whole document, named after the file. Item as big as the layer:
|
||||
/// Retain Layer Sizes; as big as the document: the layer on the document.
|
||||
#[test]
|
||||
fn a_photoshop_layer_item_shows_its_layer() {
|
||||
for (size, layer_size) in [((48, 15), true), ((1000, 1000), false)] {
|
||||
let (p, r) = run(&as_psd_layer(7, [749, 800, 764, 848], "Tëst", size), true);
|
||||
r.unwrap();
|
||||
let (name, f) = p.items.values().find_map(|i| if let ItemKind::Footage(f) = &i.kind { Some((i.name.clone(), f.clone())) } else { None }).unwrap();
|
||||
assert_eq!(name, "Tëst/art.psd");
|
||||
let l = f.layer.expect("the layer");
|
||||
assert_eq!((l.index, l.name.as_str(), l.layer_size, (f.width, f.height)), (7, "Tëst", layer_size, size));
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer as big as the document but off its corner fits both framings: shown at its own bounds
|
||||
/// and reported. One at the corner, or bigger than the document, reads one way and is not. An item
|
||||
/// as big as neither is shown on the document and reported.
|
||||
#[test]
|
||||
fn a_photoshop_layer_as_big_as_the_document_off_its_corner_is_reported() {
|
||||
let framing = |bounds, size| {
|
||||
let (p, r) = run(&as_psd_layer(3, bounds, "Moved", size), true);
|
||||
let found = losses(&r.unwrap(), LossCategory::UnsupportedItems);
|
||||
let said = |what: &str| found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains(what));
|
||||
(the_footage(&p).layer.map(|l| l.layer_size), said("as big as the document"), said("neither the Photoshop layer's size"))
|
||||
};
|
||||
assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true, false));
|
||||
assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false, false));
|
||||
assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false, false));
|
||||
assert_eq!(framing([749, 800, 764, 848], (1000, 1000)), (Some(false), false, false));
|
||||
// An item as big as neither the layer nor the document: shown on the document, reported.
|
||||
assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false, true));
|
||||
}
|
||||
|
||||
/// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is
|
||||
/// reported; the merged image itself (index -1) is no layer.
|
||||
#[test]
|
||||
fn a_photoshop_layer_without_pixels_keeps_the_merged_image() {
|
||||
let (p, r) = run(&as_psd_layer(4, [0; 4], "Levels 1", (1000, 1000)), true);
|
||||
let found = losses(&r.unwrap(), LossCategory::UnsupportedItems);
|
||||
assert!(found.iter().any(|d| d.contains("'Levels 1/art.psd'") && d.contains("without pixels")), "{found:?}");
|
||||
assert_eq!(the_footage(&p).layer, None);
|
||||
let (p, _) = run(&as_psd_layer(-1, [0; 4], "", (1000, 1000)), true);
|
||||
assert_eq!(the_footage(&p).layer, None);
|
||||
}
|
||||
|
||||
/// #3087: an expression on Orientation arrives with the stored value, as on any property; it was
|
||||
/// dropped together with the value and reported as "not decoded".
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! A small committed text project (`tests/fixtures/text-synthetic.aep`), so the text animator
|
||||
//! Stroke Opacity and the Source Text expression are checked without the external corpus, on
|
||||
//! import and through an export and a second import (#3170).
|
||||
//!
|
||||
//! The project was made in After Effects 2026 with the working space set to None: one composition
|
||||
//! `C` (64x48, 25 fps, 2 s) with two text layers. `T` holds `Hi` (Arial, 20 px, a blue 2 px
|
||||
//! stroke), the Source Text expression `text.sourceText + "!"` (enabled), an animator `Stroke`
|
||||
//! with Stroke Opacity 40 % and an animator `Keyed` with Stroke Opacity keyed 0 % at 0 s and
|
||||
//! 100 % at 1 s. `Off` holds `Off` and the Source Text expression `"X"`, disabled. Nothing After
|
||||
//! Effects wrote was changed.
|
||||
|
||||
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
|
||||
use effectcraft_aep::{AepFile, Body, Chunk, parse, write};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Expression, Layer, Project, PropGroup};
|
||||
use effectcraft_time::{TICKS_PER_SECOND, Tick};
|
||||
|
||||
use crate::import::helpers::comp;
|
||||
|
||||
const TEXT_SYNTHETIC: &[u8] = include_bytes!("../../fixtures/text-synthetic.aep");
|
||||
|
||||
/// Imports `bytes` with losses allowed.
|
||||
fn run(bytes: &[u8]) -> (Project, ImportResult) {
|
||||
let mut project = Project::default();
|
||||
let none = |_: &str| false;
|
||||
let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).expect("the project imports");
|
||||
(project, r)
|
||||
}
|
||||
|
||||
/// The loss details of `category`.
|
||||
fn losses(r: &ImportResult, category: LossCategory) -> Vec<String> {
|
||||
r.report.losses.iter().filter(|l| l.category == category).flat_map(|l| l.details.clone()).collect()
|
||||
}
|
||||
|
||||
/// The layer `name` of composition `C`.
|
||||
fn layer<'p>(p: &'p Project, r: &ImportResult, name: &str) -> &'p Layer {
|
||||
let (_, c) = comp(p, r, "C");
|
||||
c.layers.iter().find(|l| l.name == name).unwrap_or_else(|| panic!("text layer {name}"))
|
||||
}
|
||||
|
||||
/// The text animator `name` of `l`.
|
||||
fn animator<'l>(l: &'l Layer, name: &str) -> &'l PropGroup {
|
||||
l.props.group("text/animators").expect("animators").groups().find(|a| a.name == name).unwrap_or_else(|| panic!("animator {name}"))
|
||||
}
|
||||
|
||||
/// The Source Text of `l`: its stored text and its expression.
|
||||
fn source_text(l: &Layer) -> (String, Option<Expression>) {
|
||||
let p = l.props.prop("text/sourceText").expect("Source Text");
|
||||
let Value::Text(doc) = &p.value else { panic!("{:?}", p.value) };
|
||||
(doc.text.clone(), p.expr.clone())
|
||||
}
|
||||
|
||||
/// Stroke Opacity 40 % and its keys 0 % / 100 % arrive in percent, without a loss.
|
||||
#[test]
|
||||
fn text_animator_stroke_opacity_is_imported_static_and_keyed() {
|
||||
let (p, r) = run(TEXT_SYNTHETIC);
|
||||
let text = losses(&r, LossCategory::TextLayers);
|
||||
assert!(!text.iter().any(|d| d.contains("Stroke Opacity")), "{text:?}");
|
||||
let t = layer(&p, &r, "T");
|
||||
// Stored as After Effects shows it: percent.
|
||||
let st = animator(t, "Stroke").prop("properties/strokeOpacity").expect("strokeOpacity");
|
||||
assert_eq!((st.value.clone(), st.keys.len()), (Value::Scalar(40.0), 0));
|
||||
let keyed = animator(t, "Keyed").prop("properties/strokeOpacity").expect("strokeOpacity");
|
||||
let keys: Vec<_> = keyed.keys.iter().map(|k| (k.time, k.value.clone())).collect();
|
||||
assert_eq!(keys, vec![(Tick::ZERO, Value::Scalar(0.0)), (Tick(TICKS_PER_SECOND), Value::Scalar(100.0))]);
|
||||
}
|
||||
|
||||
/// Both Source Text expressions arrive with their enable switch, next to the stored text.
|
||||
#[test]
|
||||
fn the_source_text_expression_is_imported_enabled_and_disabled() {
|
||||
let (p, r) = run(TEXT_SYNTHETIC);
|
||||
let text = losses(&r, LossCategory::TextLayers);
|
||||
assert!(!text.iter().any(|d| d.contains("Source Text expression")), "{text:?}");
|
||||
// The stored text stays the Source Text value; the expression comes next to it.
|
||||
assert_eq!(source_text(layer(&p, &r, "T")), ("Hi".to_string(), Some(Expression { text: "text.sourceText + \"!\"".into(), enabled: true })));
|
||||
assert_eq!(source_text(layer(&p, &r, "Off")), ("Off".to_string(), Some(Expression { text: "\"X\"".into(), enabled: false })));
|
||||
assert_eq!(r.report.imported.expressions, 2);
|
||||
}
|
||||
|
||||
/// Calls `f` on every chunk below `chunks`, depth-first.
|
||||
fn visit(chunks: &mut [Chunk<'_>], f: &mut dyn FnMut(&mut Chunk<'_>)) {
|
||||
for c in chunks {
|
||||
f(c);
|
||||
visit(c.children_mut(), f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Export and a second import keep the Source Text expressions and Stroke Opacity, unreported.
|
||||
#[test]
|
||||
fn stroke_opacity_and_source_text_expressions_survive_export() {
|
||||
let (p, r0) = run(TEXT_SYNTHETIC);
|
||||
let out = effectcraft_aep::export::export(&p, &effectcraft_aep::export::ExportOptions { allow_losses: true }).expect("export");
|
||||
let text: Vec<String> =
|
||||
out.report.losses.iter().filter(|l| l.category == effectcraft_aep::export::LossCategory::TextLayers).flat_map(|l| l.details.clone()).collect();
|
||||
assert!(!text.iter().any(|d| d.contains("Stroke Opacity") || d.contains("Source Text expression")), "{text:?}");
|
||||
assert_eq!(out.report.exported.expressions, 2);
|
||||
let (q, r) = run(&out.bytes);
|
||||
for name in ["T", "Off"] {
|
||||
assert_eq!(source_text(layer(&q, &r, name)), source_text(layer(&p, &r0, name)), "{name}");
|
||||
}
|
||||
let t = layer(&q, &r, "T");
|
||||
assert_eq!(animator(t, "Stroke").prop("properties/strokeOpacity").map(|p| p.value.clone()), Some(Value::Scalar(40.0)));
|
||||
let keys: Vec<_> = animator(t, "Keyed").prop("properties/strokeOpacity").expect("strokeOpacity").keys.iter().map(|k| (k.time, k.value.clone())).collect();
|
||||
assert_eq!(keys, vec![(Tick::ZERO, Value::Scalar(0.0)), (Tick(TICKS_PER_SECOND), Value::Scalar(100.0))]);
|
||||
}
|
||||
|
||||
/// Guard: an expression whose `tdb4` flags give no state stays reported instead of imported.
|
||||
#[test]
|
||||
fn a_source_text_expression_with_unreadable_flags_stays_reported() {
|
||||
// `tdb4` byte 120 is 1 on a property with an expression; with 0 the expression's state is
|
||||
// unknown, so it is reported instead of imported.
|
||||
let mut file: AepFile<'_> = parse(TEXT_SYNTHETIC).expect("parse");
|
||||
visit(&mut file.chunks, &mut |c| {
|
||||
if !c.is_list(b"btds") {
|
||||
return;
|
||||
}
|
||||
for tdbs in c.children_mut().iter_mut().filter(|c| c.is_list(b"tdbs")) {
|
||||
for tdb4 in tdbs.children_mut().iter_mut().filter(|c| c.is(b"tdb4")) {
|
||||
if let Body::Data(d) = &mut tdb4.body
|
||||
&& let Some(b) = d.to_mut().get_mut(120)
|
||||
{
|
||||
*b = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (p, r) = run(&write(&file).expect("write"));
|
||||
let text = losses(&r, LossCategory::TextLayers);
|
||||
assert_eq!(text.iter().filter(|d| d.contains("the Source Text expression is not imported")).count(), 2, "{text:?}");
|
||||
assert_eq!(source_text(layer(&p, &r, "T")), ("Hi".to_string(), None));
|
||||
}
|
||||
@@ -65,6 +65,8 @@ const REFUSED: &[&str] = &[
|
||||
"file.revealInFinder",
|
||||
"layer.openSource",
|
||||
"help.revealLogFile",
|
||||
// Hands the footage file to the platform's default application.
|
||||
"edit.editOriginal",
|
||||
"file.autoSave",
|
||||
// The Plug-in Library downloads code, installs it to load at start-up and reads `file://` catalogs.
|
||||
"library.refresh",
|
||||
@@ -73,6 +75,10 @@ const REFUSED: &[&str] = &[
|
||||
"library.uninstall",
|
||||
"library.loadInstalled",
|
||||
"library.preview",
|
||||
// Watch Folder renders the projects it finds to the outputs they name and writes status
|
||||
// files into the watched folder: neither is a path the agent gives, so neither is checked.
|
||||
"file.watchFolder",
|
||||
"file.watchFolder.poll",
|
||||
];
|
||||
|
||||
/// Most numbered folders `check_render_folder` inspects for one output; more are refused.
|
||||
@@ -91,7 +97,6 @@ const READS: &[(&str, &[&str])] = &[
|
||||
("file.replaceFootage", &["path"]),
|
||||
("file.relinkFootage", &["folder"]),
|
||||
("file.setProxy", &["path"]),
|
||||
("file.watchFolder", &["folder"]),
|
||||
("anim.applyPreset", &["path"]),
|
||||
("anim.applyRecentPreset", &["path"]),
|
||||
("keys.rpfCameraImport", &["path"]),
|
||||
@@ -105,7 +110,6 @@ const READS: &[(&str, &[&str])] = &[
|
||||
// unchecked.
|
||||
("essential.templateInfo", &["path"]),
|
||||
("file.importProject", &["path"]),
|
||||
("file.watchFolder.poll", &["folder"]),
|
||||
("footage.relink", &["path"]),
|
||||
("layer.newModel", &["path"]),
|
||||
("mediaBrowser.fileInfo", &["path"]),
|
||||
@@ -785,6 +789,16 @@ mod tests {
|
||||
assert!(read(&footage(&inside)).1.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watch_folder_and_edit_original_are_refused_while_confined() {
|
||||
let dir = std::env::temp_dir();
|
||||
let c = Confinement::new(std::slice::from_ref(&dir), std::slice::from_ref(&dir)).unwrap();
|
||||
for id in ["file.watchFolder", "file.watchFolder.poll", "edit.editOriginal"] {
|
||||
let e = c.check_command(id, &serde_json::json!({"folder": dir.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("not available while file access is confined"), "{id}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_and_outside_paths_of_newly_listed_commands_are_refused() {
|
||||
let base = std::env::temp_dir().join(format!("ec-confine-1243-{}", std::process::id()));
|
||||
|
||||
@@ -252,10 +252,18 @@ impl Lv {
|
||||
if clip_w {
|
||||
t = t.min(1.0);
|
||||
}
|
||||
self.ob + (self.ow - self.ob) * crate::color_fx::levels_gamma(t, self.g.max(0.01))
|
||||
let curve = crate::color_fx::levels_gamma(t, self.g.max(0.01)).clamp(-LEVELS_IC_CURVE_LIMIT, LEVELS_IC_CURVE_LIMIT);
|
||||
self.ob + (self.ow - self.ob) * curve
|
||||
}
|
||||
}
|
||||
|
||||
/// How far Levels (Individual Controls)' curve may reach: with gamma down to 0 (rendered as 0.01,
|
||||
/// an exponent of 100) an HDR value a few times Input White overflows `f32`, and an infinite curve
|
||||
/// times an empty output range is NaN. 1e30 times the widest output range (2e4) is still finite
|
||||
/// (`f32::MAX` is 3.4e38), and every curve that was finite before stays as it was below it. The
|
||||
/// GPU (`fxt_lv`) uses the same.
|
||||
const LEVELS_IC_CURVE_LIMIT: f32 = 1e30;
|
||||
|
||||
fn levels_ic(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let lv = LV_IDS.map(|ids| Lv {
|
||||
ib: ctx.params.f(ids[0]) as f32,
|
||||
@@ -978,11 +986,14 @@ fn cc_kernel(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let mut lv_params = Vec::new();
|
||||
for (ids, names) in LV_IDS.iter().zip(LV_NAMES.iter()) {
|
||||
lv_params.push(p(ids[0], names[0], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3)));
|
||||
lv_params.push(p(ids[1], names[1], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3)));
|
||||
lv_params.push(p(ids[2], names[2], num(1.0), slider(0.1, 10.0, 0.1, 3.0, 2)));
|
||||
lv_params.push(p(ids[3], names[3], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3)));
|
||||
lv_params.push(p(ids[4], names[4], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3)));
|
||||
// After Effects' valid ranges (#3487-#3491): levels -10000..10000 and gamma from 0 (the
|
||||
// renderer floors it at 0.01); gamma keeps its wider maximum. The sliders stay 0..1.
|
||||
let level = || slider(-10000.0, 10000.0, 0.0, 1.0, 3);
|
||||
lv_params.push(p(ids[0], names[0], num(0.0), level()));
|
||||
lv_params.push(p(ids[1], names[1], num(1.0), level()));
|
||||
lv_params.push(p(ids[2], names[2], num(1.0), slider(0.0, 10.0, 0.1, 3.0, 2)));
|
||||
lv_params.push(p(ids[3], names[3], num(0.0), level()));
|
||||
lv_params.push(p(ids[4], names[4], num(1.0), level()));
|
||||
}
|
||||
lv_params.push(p("clipToOutputBlack", "Clip To Output Black", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP)));
|
||||
lv_params.push(p("clipToOutputWhite", "Clip To Output White", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP)));
|
||||
|
||||
@@ -270,6 +270,39 @@ fn levels_ic_clip_popups() {
|
||||
assert!(run("ec.color.levelsic", &img, &off).data[0][0] > 1.5);
|
||||
}
|
||||
|
||||
/// #3487-#3491: over After Effects' valid ranges (levels ±10000, gamma from 0) the output stays
|
||||
/// finite: gamma 0 renders as 0.01, whose curve on an HDR value overflows `f32` unbounded.
|
||||
#[test]
|
||||
fn levels_ic_stays_finite_over_the_whole_range() {
|
||||
let img = Image::filled(2, 2, [3.0, 0.5, -2.0, 1.0]);
|
||||
for (ib, iw, ob, ow) in [
|
||||
(0.0, 1.0, 0.0, 1.0),
|
||||
(0.0, 1.0, 1.0, 1.0),
|
||||
(-10000.0, 10000.0, -10000.0, 10000.0),
|
||||
(10000.0, -10000.0, 10000.0, -10000.0),
|
||||
(0.0, 1e-3, -10000.0, 10000.0),
|
||||
] {
|
||||
let lv = [
|
||||
("rgb/rgbInBlack", num(ib)),
|
||||
("rgb/rgbInWhite", num(iw)),
|
||||
("rgb/rgbGamma", num(0.0)),
|
||||
("rgb/rgbOutBlack", num(ob)),
|
||||
("rgb/rgbOutWhite", num(ow)),
|
||||
("clipToOutputBlack", Value::Enum(0)),
|
||||
("clipToOutputWhite", Value::Enum(0)),
|
||||
];
|
||||
let out = run("ec.color.levelsic", &img, &lv);
|
||||
assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{ib} {iw} {ob} {ow}: {:?}", out.data[0]);
|
||||
}
|
||||
// The bound only stops the overflow: an HDR value that was finite before keeps its level
|
||||
// (gamma 0.1 at 4 x Input White: 4^10).
|
||||
let bright = run("ec.color.levelsic", &Image::filled(1, 1, [4.0, 4.0, 4.0, 1.0]), &[("rgb/rgbGamma", num(0.1)), ("clipToOutputWhite", Value::Enum(0))]);
|
||||
assert_eq!(bright.data[0][0], 4.0f32.powf(10.0));
|
||||
// Gamma 0 is the limit of a small gamma: below Input White the curve goes to 0.
|
||||
let dark = run("ec.color.levelsic", &Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]), &[("rgb/rgbGamma", num(0.0))]);
|
||||
assert!(dark.data[0][0] < 1e-6, "{:?}", dark.data[0]);
|
||||
}
|
||||
|
||||
/// A host whose other layers and other frames are a fixed image.
|
||||
struct ImgHost(Image);
|
||||
impl crate::EffectHost for ImgHost {
|
||||
|
||||
@@ -809,7 +809,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"Change Color",
|
||||
vec![
|
||||
p("view", "View", Value::Enum(0), popup(&["Corrected Layer", "Color Correction Mask"])),
|
||||
p("hueTransform", "Hue Transform", num(0.0), slider(-360.0, 360.0, -180.0, 180.0, 1)),
|
||||
p("hueTransform", "Hue Transform", num(0.0), slider(-1800.0, 1800.0, -180.0, 180.0, 1)),
|
||||
p("lightnessTransform", "Lightness Transform", num(0.0), bipolar()),
|
||||
p("saturationTransform", "Saturation Transform", num(0.0), bipolar()),
|
||||
p("colorToChange", "Color To Change", col(0.8, 0.2, 0.2), ParamUi::Color),
|
||||
|
||||
@@ -506,8 +506,8 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("anchor", "Anchor Point", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("position", "Position", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("uniform", "Uniform Scale", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("scaleHeight", "Scale Height", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)),
|
||||
p("scaleWidth", "Scale Width", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)),
|
||||
p("scaleHeight", "Scale Height", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)),
|
||||
p("scaleWidth", "Scale Width", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)),
|
||||
p("skew", "Skew", num(0.0), slider(-70.0, 70.0, -70.0, 70.0, 1)),
|
||||
p("skewAxis", "Skew Axis", num(0.0), ParamUi::Angle),
|
||||
p("rotation", "Rotation", num(0.0), ParamUi::Angle),
|
||||
|
||||
@@ -743,7 +743,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("evolution", "Evolution", num(0.0), ParamUi::Angle),
|
||||
p("evolutionOptions/cycleEvolution", "Cycle Evolution", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("evolutionOptions/cycle", "Cycle (in Revolutions)", num(1.0), slider(1.0, 1000.0, 1.0, 20.0, 0)),
|
||||
p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 10000.0, 0.0, 1000.0, 0)),
|
||||
p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 100000.0, 0.0, 1000.0, 0)),
|
||||
p("pinning", "Pinning", Value::Enum(1), popup(&TURBULENT_PINNING)),
|
||||
p("resizeLayer", "Resize Layer", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
//! Caches of what effects read from files named by a parameter (a LUT, an OCIO transform file, an
|
||||
//! OCIO config), keyed by the parameter text and checked against the files each result was read
|
||||
//! from (#3493, #3538).
|
||||
//!
|
||||
//! A cached result remembers every file its load read, with the file's size and modification time
|
||||
//! (its stamp) taken before reading, including the files a nested cached load read (a config's
|
||||
//! `FileTransform` LUTs) and files looked for but missing. Each lookup stamps those files again
|
||||
//! (one `metadata` call each) and loads again once one moved, so a file edited, created, deleted or
|
||||
//! repaired on disk is followed. Inline text reads no file and is its own content. An edit that keeps
|
||||
//! both the size and the modification time can't be told apart.
|
||||
//!
|
||||
//! Every file read is also followed by [`check_lut_files`], and [`lut_generation`] moves when one is
|
||||
//! found changed: the viewers and frame caches drop the frames made before.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// A file's size and modification time when it was read (`None`: missing, or a file that could
|
||||
/// not be described). A file whose stamp moved is read again.
|
||||
pub(crate) type FileStamp = Option<(u64, Option<SystemTime>)>;
|
||||
|
||||
/// The files a load read and their stamps.
|
||||
type Files = Vec<(String, FileStamp)>;
|
||||
|
||||
/// At most this many files are followed by [`check_lut_files`]; the least recently read go first.
|
||||
const MAX_FOLLOWED_FILES: usize = 1024;
|
||||
|
||||
/// One cached result and what it was read from.
|
||||
struct Entry<V> {
|
||||
files: Files,
|
||||
value: V,
|
||||
used: u64,
|
||||
/// The result's size estimate and the parameter text, counted against the cache's byte bound.
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
/// Results by parameter text, at most `max_entries` and `max_bytes` of them, the least recently
|
||||
/// used going first.
|
||||
pub(crate) struct SourceCache<V> {
|
||||
map: HashMap<String, Entry<V>>,
|
||||
clock: u64,
|
||||
bytes: usize,
|
||||
max_entries: usize,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl<V> SourceCache<V> {
|
||||
pub(crate) fn new(max_entries: usize, max_bytes: usize) -> Self {
|
||||
SourceCache { map: HashMap::new(), clock: 0, bytes: 0, max_entries, max_bytes }
|
||||
}
|
||||
|
||||
fn remove(&mut self, src: &str) {
|
||||
if let Some(e) = self.map.remove(src) {
|
||||
self.bytes = self.bytes.saturating_sub(e.bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the results read from `path`.
|
||||
fn forget_file(&mut self, path: &str) {
|
||||
let stale: Vec<String> = self.map.iter().filter(|(_, e)| e.files.iter().any(|(p, _)| p == path)).map(|(k, _)| k.clone()).collect();
|
||||
for src in stale {
|
||||
self.remove(&src);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep within the bounds, always the result for `keep`.
|
||||
fn evict(&mut self, keep: &str) {
|
||||
while self.map.len() > self.max_entries || (self.bytes > self.max_bytes && self.map.len() > 1) {
|
||||
let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break };
|
||||
self.remove(&oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the result cached for `src` was read from.
|
||||
pub(crate) fn files(&self, src: &str) -> Option<Vec<String>> {
|
||||
self.map.get(src).map(|e| e.files.iter().map(|(p, _)| p.clone()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn contains(&self, src: &str) -> bool {
|
||||
self.map.contains_key(src)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bytes(&self) -> (usize, usize, usize) {
|
||||
(self.bytes, self.map.values().map(|e| e.bytes).sum(), self.max_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock a cache; a panic elsewhere while it was held leaves a usable map.
|
||||
pub(crate) fn lock<V>(cache: &Mutex<SourceCache<V>>) -> MutexGuard<'_, SourceCache<V>> {
|
||||
cache.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A cache that registers with [`check_lut_files`] on first use.
|
||||
pub(crate) struct Registered<V: 'static> {
|
||||
cache: OnceLock<Mutex<SourceCache<V>>>,
|
||||
max_entries: usize,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl<V: Clone + Send + 'static> Registered<V> {
|
||||
pub(crate) const fn new(max_entries: usize, max_bytes: usize) -> Self {
|
||||
Registered { cache: OnceLock::new(), max_entries, max_bytes }
|
||||
}
|
||||
|
||||
pub(crate) fn get(&'static self) -> &'static Mutex<SourceCache<V>> {
|
||||
self.cache.get_or_init(|| {
|
||||
registry().push(self);
|
||||
Mutex::new(SourceCache::new(self.max_entries, self.max_bytes))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A cache [`check_lut_files`] tells to forget the results read from a changed file.
|
||||
trait ForgetFile: Sync {
|
||||
fn forget_file(&self, path: &str);
|
||||
/// Add the files the cached results were read from to `out`.
|
||||
fn held_files(&self, out: &mut HashSet<String>);
|
||||
}
|
||||
|
||||
impl<V: Send> ForgetFile for Registered<V> {
|
||||
fn forget_file(&self, path: &str) {
|
||||
if let Some(c) = self.cache.get() {
|
||||
lock(c).forget_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
fn held_files(&self, out: &mut HashSet<String>) {
|
||||
if let Some(c) = self.cache.get() {
|
||||
out.extend(lock(c).map.values().flat_map(|e| e.files.iter().map(|(p, _)| p.clone())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn registry() -> MutexGuard<'static, Vec<&'static dyn ForgetFile>> {
|
||||
static REGISTRY: OnceLock<Mutex<Vec<&'static dyn ForgetFile>>> = OnceLock::new();
|
||||
REGISTRY.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The loads running on this thread, innermost last: the files each read, and the bytes of
|
||||
/// the cached results it holds (a config holds the LUTs its `FileTransform`s loaded).
|
||||
static READING: RefCell<Vec<(Files, usize)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// Note that the running load read (or looked for) `path`, stamped `stamp`.
|
||||
pub(crate) fn note_file(path: &str, stamp: FileStamp) {
|
||||
READING.with(|r| {
|
||||
if let Ok(mut r) = r.try_borrow_mut()
|
||||
&& let Some((top, _)) = r.last_mut()
|
||||
&& !top.iter().any(|(p, _)| p == path)
|
||||
{
|
||||
top.push((path.to_string(), stamp));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Note that the running load holds a cached result of `bytes`.
|
||||
fn note_bytes(bytes: usize) {
|
||||
READING.with(|r| {
|
||||
if let Ok(mut r) = r.try_borrow_mut()
|
||||
&& let Some((_, held)) = r.last_mut()
|
||||
{
|
||||
*held = held.saturating_add(bytes);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Pops the files of a load when it ends, even by a panic.
|
||||
struct Reading {
|
||||
popped: bool,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
fn start() -> Reading {
|
||||
READING.with(|r| {
|
||||
if let Ok(mut r) = r.try_borrow_mut() {
|
||||
r.push((Vec::new(), 0));
|
||||
}
|
||||
});
|
||||
Reading { popped: false }
|
||||
}
|
||||
|
||||
fn pop() -> Option<(Files, usize)> {
|
||||
READING.with(|r| r.try_borrow_mut().ok().and_then(|mut r| r.pop()))
|
||||
}
|
||||
|
||||
/// The files the load read, and the bytes of the cached results it holds.
|
||||
fn finish(mut self) -> (Files, usize) {
|
||||
self.popped = true;
|
||||
Self::pop().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Reading {
|
||||
fn drop(&mut self) {
|
||||
if !self.popped {
|
||||
let _ = Self::pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stamp of the file at `path` now: one `metadata` call.
|
||||
pub(crate) fn file_stamp(path: &str) -> FileStamp {
|
||||
std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok()))
|
||||
}
|
||||
|
||||
/// Read the text file at `path` for the running load, stamped before reading (a file written
|
||||
/// after it was stamped has a newer stamp, and is read again next time).
|
||||
pub(crate) fn read(path: &str) -> std::io::Result<String> {
|
||||
note_file(path, file_stamp(path));
|
||||
std::fs::read_to_string(path)
|
||||
}
|
||||
|
||||
/// Note that the running load looked for `path` and did not find it: it loads again once the file
|
||||
/// appears.
|
||||
pub(crate) fn note_missing(path: &str) {
|
||||
note_file(path, None);
|
||||
}
|
||||
|
||||
/// The result cached for `src`, or `load`'s (and its size estimate in bytes), cached. `load` reads
|
||||
/// files with [`read`] (and notes the ones it looked for with [`note_missing`]); no lock is held
|
||||
/// while it runs or while the files are stamped.
|
||||
pub(crate) fn cached<V: Clone>(cache: &Mutex<SourceCache<V>>, src: &str, load: impl FnOnce() -> (V, usize)) -> V {
|
||||
let files = lock(cache).map.get(src).map(|e| e.files.clone());
|
||||
let stale = files.is_some();
|
||||
if let Some(files) = files
|
||||
&& files.iter().all(|(p, s)| file_stamp(p) == *s)
|
||||
{
|
||||
let mut c = lock(cache);
|
||||
c.clock += 1;
|
||||
let now = c.clock;
|
||||
if let Some(e) = c.map.get_mut(src)
|
||||
&& e.files == files
|
||||
{
|
||||
e.used = now;
|
||||
let (value, bytes) = (e.value.clone(), e.bytes);
|
||||
drop(c);
|
||||
// (an enclosing load depends on these files too, and holds this result)
|
||||
for (p, s) in &files {
|
||||
note_file(p, *s);
|
||||
}
|
||||
note_bytes(bytes);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
let reading = Reading::start();
|
||||
let (value, size) = load();
|
||||
let (files, held) = reading.finish();
|
||||
follow(&files, stale);
|
||||
for (p, s) in &files {
|
||||
note_file(p, *s);
|
||||
}
|
||||
// (what it holds counts against this cache's bound too: another cache letting go of it
|
||||
// frees nothing while this result keeps it)
|
||||
let bytes = size.saturating_add(held).saturating_add(src.len());
|
||||
note_bytes(bytes);
|
||||
let mut c = lock(cache);
|
||||
c.clock += 1;
|
||||
let used = c.clock;
|
||||
c.remove(src);
|
||||
c.map.insert(src.to_string(), Entry { files, value: value.clone(), used, bytes });
|
||||
c.bytes = c.bytes.saturating_add(bytes);
|
||||
c.evict(src);
|
||||
value
|
||||
}
|
||||
|
||||
/// How often a file a cached load read was found changed on disk ([`lut_generation`]).
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The files followed by [`check_lut_files`]: the stamp each was last read with, and when.
|
||||
#[derive(Default)]
|
||||
struct Followed {
|
||||
files: HashMap<String, (FileStamp, u64)>,
|
||||
clock: u64,
|
||||
}
|
||||
|
||||
fn followed() -> MutexGuard<'static, Followed> {
|
||||
static FOLLOWED: OnceLock<Mutex<Followed>> = OnceLock::new();
|
||||
FOLLOWED.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
impl Followed {
|
||||
/// Note that `files` were read with these stamps; true when one has a different stamp than
|
||||
/// its last read's: a file changed on disk.
|
||||
fn read(&mut self, files: &Files) -> bool {
|
||||
let mut moved = false;
|
||||
for (path, stamp) in files {
|
||||
self.clock += 1;
|
||||
let now = self.clock;
|
||||
if self.files.insert(path.clone(), (*stamp, now)).is_some_and(|(old, _)| old != *stamp) {
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// Keep at most [`MAX_FOLLOWED_FILES`], letting go of the least recently read first but never
|
||||
/// of a file in `held` (a cached result was read from it) or in `files` (just read).
|
||||
fn trim(&mut self, held: &HashSet<String>, files: &Files) {
|
||||
while self.files.len() > MAX_FOLLOWED_FILES {
|
||||
let Some(oldest) = self
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(p, _)| !held.contains(p.as_str()) && !files.iter().any(|(f, _)| f == *p))
|
||||
.min_by_key(|(_, (_, used))| *used)
|
||||
.map(|(p, _)| p.clone())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
self.files.remove(&oldest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the registered caches' results were read from.
|
||||
fn held_files() -> HashSet<String> {
|
||||
let caches: Vec<&'static dyn ForgetFile> = registry().clone();
|
||||
let mut out = HashSet::new();
|
||||
for c in caches {
|
||||
c.held_files(&mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Note that `files` were read with these stamps. A file read with a different stamp than last
|
||||
/// time, or a load replacing a result whose files moved (`stale`), means a file changed on disk,
|
||||
/// and frames made before may show the old contents.
|
||||
fn follow(files: &Files, stale: bool) {
|
||||
let (moved, over) = {
|
||||
let mut f = followed();
|
||||
(f.read(files), f.files.len() > MAX_FOLLOWED_FILES)
|
||||
};
|
||||
if over {
|
||||
// (gathered without the followed files' lock: no two of these locks are ever nested)
|
||||
let held = held_files();
|
||||
followed().trim(&held, files);
|
||||
}
|
||||
if moved || stale {
|
||||
GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes each time a file a cached load read is found changed on disk (by a load itself or
|
||||
/// [`check_lut_files`]): frames made before then may show the old contents.
|
||||
pub fn lut_generation() -> u64 {
|
||||
GENERATION.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Look at every file read (one `metadata` call each) and forget the results read from the ones
|
||||
/// that changed on disk since, so the next load reads them again. Returns [`lut_generation`].
|
||||
pub fn check_lut_files() -> u64 {
|
||||
let files: Vec<(String, FileStamp)> = followed().files.iter().map(|(p, (s, _))| (p.clone(), *s)).collect();
|
||||
// (stamped without the lock: a file on a slow share must not hold up renders)
|
||||
let changed: Vec<(String, FileStamp, FileStamp)> =
|
||||
files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect();
|
||||
let caches: Vec<&'static dyn ForgetFile> = registry().clone();
|
||||
for (path, old, now) in changed {
|
||||
{
|
||||
let mut f = followed();
|
||||
// (a render that read the file meanwhile has noted its new stamp already)
|
||||
match f.files.get_mut(&path) {
|
||||
Some((s, _)) if *s == old => *s = now,
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
for c in &caches {
|
||||
c.forget_file(&path);
|
||||
}
|
||||
GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
lut_generation()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn followed_stamp(path: &str) -> Option<FileStamp> {
|
||||
followed().files.get(path).map(|(s, _)| *s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a list of its own: the
|
||||
/// shared one's files belong to the other tests too).
|
||||
#[test]
|
||||
fn the_file_just_read_stays_followed_past_the_limit() {
|
||||
let mut f = Followed::default();
|
||||
let held: HashSet<String> = ["/followed/0.cube".to_string()].into();
|
||||
for i in 0..MAX_FOLLOWED_FILES + 8 {
|
||||
let files = vec![(format!("/followed/{i}.cube"), Some((1, None)))];
|
||||
assert!(!f.read(&files));
|
||||
f.trim(&held, &files);
|
||||
assert!(f.files.contains_key(&files[0].0), "{i}: the file just read");
|
||||
assert!(f.files.len() <= MAX_FOLLOWED_FILES);
|
||||
}
|
||||
assert!(f.files.contains_key("/followed/0.cube"), "a file a cached result was read from");
|
||||
assert!(!f.files.contains_key("/followed/1.cube"), "the least recently read other");
|
||||
assert!(f.read(&vec![("/followed/1030.cube".into(), Some((2, None)))]), "a moved stamp");
|
||||
}
|
||||
|
||||
/// A nested cached load's files count for the enclosing load.
|
||||
#[test]
|
||||
fn an_enclosing_load_depends_on_a_nested_loads_files() {
|
||||
static INNER: Registered<u32> = Registered::new(8, 1 << 20);
|
||||
static OUTER: Registered<u32> = Registered::new(8, 1 << 20);
|
||||
let v = cached(OUTER.get(), "outer", || {
|
||||
note_missing("/nested/outer-own.cube");
|
||||
let inner = cached(INNER.get(), "inner", || {
|
||||
note_missing("/nested/inner.cube");
|
||||
(7, 100)
|
||||
});
|
||||
(inner, 0)
|
||||
});
|
||||
assert_eq!(v, 7);
|
||||
let files = lock(OUTER.get()).files("outer").unwrap();
|
||||
let held = |src: &str| lock(OUTER.get()).map.get(src).map(|e| e.bytes);
|
||||
// ("inner" is 5 bytes, its result 100: "outer" holds it, on a load and on a hit alike)
|
||||
assert_eq!(held("outer"), Some(100 + 5 + "outer".len()), "the result an enclosing load holds counts");
|
||||
assert_eq!(files, vec!["/nested/outer-own.cube".to_string(), "/nested/inner.cube".to_string()]);
|
||||
// A hit on the inner result still reports its files to a new enclosing load.
|
||||
let w = cached(OUTER.get(), "outer 2", || (cached(INNER.get(), "inner", || (0, 0)), 0));
|
||||
assert_eq!(w, 7);
|
||||
assert_eq!(lock(OUTER.get()).files("outer 2").unwrap(), vec!["/nested/inner.cube".to_string()]);
|
||||
assert_eq!(held("outer 2"), Some(100 + 5 + "outer 2".len()));
|
||||
}
|
||||
}
|
||||
@@ -121,11 +121,17 @@ pub fn four_color_softening(blend: f64, scale: f64) -> f64 {
|
||||
(b * b).max(1e-6)
|
||||
}
|
||||
|
||||
/// 4-Color Gradient's Jitter (percent, up to After Effects' 500 %) as the dither's strength: 1 at
|
||||
/// 100 %, a few code values of noise per unit.
|
||||
pub fn four_color_jitter(jitter: f64) -> f32 {
|
||||
(jitter / 100.0).clamp(0.0, 5.0) as f32
|
||||
}
|
||||
|
||||
fn four_color(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pts: Vec<((f64, f64), [f32; 4])> =
|
||||
(1..=4).map(|i| (b.to_px(ctx.params.v2(&format!("positionsColors/point{i}"))), ctx.params.color(&format!("positionsColors/color{i}")))).collect();
|
||||
let k = four_color_softening(ctx.params.f("blend"), b.scale);
|
||||
let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let jitter = four_color_jitter(ctx.params.f("jitter"));
|
||||
let op = ctx.params.f("opacity") as f32 / 100.0;
|
||||
let mode = ctx.params.e("blendingMode");
|
||||
let seed = ctx.seed;
|
||||
@@ -349,8 +355,9 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("positionsColors/color3", "Color 3", col(1.0, 0.0, 1.0), ParamUi::Color),
|
||||
p("positionsColors/point4", "Point 4", pt(0.9, 0.9), ParamUi::Point),
|
||||
p("positionsColors/color4", "Color 4", col(0.0, 0.0, 1.0), ParamUi::Color),
|
||||
p("blend", "Blend", num(100.0), slider(1.0, 1000.0, 1.0, 1000.0, 1)),
|
||||
p("jitter", "Jitter", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
// After Effects' valid ranges (#3478, #3479); Blend keeps its lower minimum (1, not 5).
|
||||
p("blend", "Blend", num(100.0), slider(1.0, 10000.0, 1.0, 1000.0, 1)),
|
||||
p("jitter", "Jitter", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 1)),
|
||||
p("opacity", "Opacity", num(100.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
p("blendingMode", "Blending Mode", Value::Enum(0), popup(&GEN_BLEND_MODES[..18])),
|
||||
],
|
||||
@@ -384,7 +391,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("corner", "Corner", pt(0.1, 0.1), ParamUi::Point),
|
||||
p("width", "Width", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)),
|
||||
p("height", "Height", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)),
|
||||
p("border", "Border", num(2.0), slider(0.0, 400.0, 0.0, 40.0, 1)),
|
||||
p("border", "Border", num(2.0), slider(0.0, 2000.0, 0.0, 40.0, 1)),
|
||||
p("feather/featherWidth", "Width", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)),
|
||||
p("feather/featherHeight", "Height", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)),
|
||||
p("invertGrid", "Invert Grid", Value::Bool(false), ParamUi::Checkbox),
|
||||
@@ -465,6 +472,21 @@ mod generator_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3479: Jitter goes up to After Effects' 500 %, and more jitter dithers more (the dither
|
||||
/// stopped growing at 100 %).
|
||||
#[test]
|
||||
fn four_color_jitter_grows_up_to_five_hundred_percent() {
|
||||
let img = Image::filled(32, 32, [0.0, 0.0, 0.0, 1.0]);
|
||||
let spread = |jitter: f64| {
|
||||
let o = run_fx("ec.generate.fourcolor", &[("jitter", num(jitter))], img.clone(), 0.0, EffectEnv::default()).img;
|
||||
let flat = run_fx("ec.generate.fourcolor", &[], img.clone(), 0.0, EffectEnv::default()).img;
|
||||
o.data.iter().zip(&flat.data).map(|(a, b)| (a[0] - b[0]).abs()).fold(0.0f32, f32::max)
|
||||
};
|
||||
let (at100, at500) = (spread(100.0), spread(500.0));
|
||||
assert!(at100 > 0.0 && at500 > 4.0 * at100, "{at100} {at500}");
|
||||
assert!(at500 < 0.2, "a few code values: {at500}");
|
||||
}
|
||||
|
||||
/// After Effects 2026, 4-Color Gradient defaults (yellow, green, magenta, blue at 10 % / 90 %
|
||||
/// of a 1920 × 1080 layer) at Blend 100 and 300, here on a tenth-size layer with Blend 10
|
||||
/// and 30 (the weights scale with the layer): colours at AE pixels (10x + 5, 10y + 5).
|
||||
|
||||
@@ -1111,8 +1111,8 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("endPoint", "Ending Point", pt(0.75, 0.5), ParamUi::Point),
|
||||
p("length", "Length", num(25.0), pct()),
|
||||
p("time", "Time", num(0.0), pct()),
|
||||
p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)),
|
||||
p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)),
|
||||
p("softness", "Softness", num(20.0), pct()),
|
||||
p("insideColor", "Inside Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("outsideColor", "Outside Color", col(0.4, 0.4, 1.0), ParamUi::Color),
|
||||
|
||||
@@ -39,6 +39,7 @@ mod keying2;
|
||||
pub mod keylight;
|
||||
mod matte;
|
||||
|
||||
mod file_cache;
|
||||
pub mod migrate;
|
||||
mod misc;
|
||||
pub mod mocha_shape;
|
||||
@@ -99,7 +100,7 @@ pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state};
|
||||
pub use stylize2::strobe_on;
|
||||
// CPU helpers the GPU kernels share (effectcraft-gpu).
|
||||
pub use blur2::{CAMERA_LENS_MAX_RADIUS, camera_lens_plain, camera_lens_radius, camera_lens_spans, radial_fast_pad};
|
||||
pub use generate::{four_color_softening, gen_mode};
|
||||
pub use generate::{four_color_jitter, four_color_softening, gen_mode};
|
||||
pub use generate2::pattern_kind as cell_pattern_kind;
|
||||
pub use generate2::{BoltSeg, Contour, Ghost, RadioPlan, Wave, flare_ghosts, lightning_segments, radio_plan};
|
||||
pub use generate3::{
|
||||
@@ -123,13 +124,14 @@ pub use channel3d::{
|
||||
crypto_layer_name, crypto_layer_named, extractor_aux_channel, extractor_own_channel, id_color, is_extractor_copy, matte_only_px, reads_aux,
|
||||
selection_hashes,
|
||||
};
|
||||
pub use file_cache::{check_lut_files, lut_generation};
|
||||
pub use ocio::{ColorOp, Straight, Tf, color_program};
|
||||
pub use sim::{Acc, Blob, Bubble, Post, Shape, Sprite, SpritePlan, Tint, bubble_list, bubble_sample_bounds, drizzle_drops, mercury_blobs, sprite_plan};
|
||||
pub use sim2::{
|
||||
CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan,
|
||||
wave_world_plan,
|
||||
};
|
||||
pub use utility::{Lut, load_lut};
|
||||
pub use utility::{Lut, load_lut, lut_file, lut_files, lut_params};
|
||||
pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation};
|
||||
|
||||
/// Effect categories in Effects & Presets order.
|
||||
|
||||
@@ -919,7 +919,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("startAngle", "Start Angle", num(0.0), ParamUi::Angle),
|
||||
p("center", "Wipe Center", Value::Vec2([0.5, 0.5]), ParamUi::Point),
|
||||
p("wipe", "Wipe", Value::Enum(0), popup(&["Clockwise", "Counterclockwise", "Both"])),
|
||||
p("feather", "Feather", num(0.0), slider(0.0, 360.0, 0.0, 50.0, 1)),
|
||||
p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 50.0, 1)),
|
||||
],
|
||||
radial_wipe,
|
||||
),
|
||||
@@ -930,8 +930,8 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![
|
||||
p("completion", "Transition Completion", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
|
||||
p("direction", "Direction", num(90.0), ParamUi::Angle),
|
||||
p("width", "Width", num(30.0), slider(2.0, 1000.0, 2.0, 200.0, 0)),
|
||||
p("feather", "Feather", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
p("width", "Width", num(30.0), slider(1.0, 32000.0, 2.0, 200.0, 0)),
|
||||
p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 100.0, 1)),
|
||||
],
|
||||
venetian,
|
||||
),
|
||||
|
||||
@@ -766,10 +766,12 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
let hls_common = || {
|
||||
vec![
|
||||
p("noise", "Noise", Value::Enum(0), popup(&["Uniform", "Squared", "Grain"])),
|
||||
p("hue", "Hue", num(0.0), pct()),
|
||||
p("lightness", "Lightness", num(0.0), pct()),
|
||||
p("saturation", "Saturation", num(0.0), pct()),
|
||||
p("grainSize", "Grain Size", num(1.0), slider(0.1, 100.0, 0.5, 10.0, 2)),
|
||||
// After Effects' valid ranges (#3483, #3484): the amounts go to 1000 %, Grain Size
|
||||
// down to 0 (the renderer floors it at 0.1 px) and keeps its wider maximum.
|
||||
p("hue", "Hue", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("lightness", "Lightness", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("saturation", "Saturation", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("grainSize", "Grain Size", num(1.0), slider(0.0, 100.0, 0.5, 10.0, 2)),
|
||||
]
|
||||
};
|
||||
let mut hls = hls_common();
|
||||
@@ -967,6 +969,32 @@ mod tests {
|
||||
assert_eq!(still.img, img);
|
||||
}
|
||||
|
||||
/// #3483, #3484: amounts above 100 % keep adding noise, and Grain Size 0 renders (floored at
|
||||
/// 0.1 px) with finite output, for both effects.
|
||||
#[test]
|
||||
fn noise_hls_takes_after_effects_ranges() {
|
||||
let mut img = Image::new(16, 16);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
*p = premul([0.6, 0.3, (i % 7) as f32 / 7.0], 1.0);
|
||||
}
|
||||
for id in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] {
|
||||
for (param, lo, hi) in [("hue", 0.0, 1000.0), ("lightness", 0.0, 1000.0), ("saturation", 0.0, 1000.0), ("grainSize", 0.0, 100.0)] {
|
||||
let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == param).unwrap().ui;
|
||||
assert!(matches!(ui, ParamUi::Slider { min, max, .. } if *min == lo && *max == hi), "{id} {param}: {ui:?}");
|
||||
}
|
||||
let at = |amount: f64, grain: f64| {
|
||||
let vals =
|
||||
[("noise", Value::Enum(2)), ("hue", num(amount)), ("lightness", num(amount)), ("saturation", num(amount)), ("grainSize", num(grain))];
|
||||
run(id, &vals, img.clone(), 0.0).img
|
||||
};
|
||||
let (low, high) = (at(100.0, 1.0), at(1000.0, 1.0));
|
||||
assert_ne!(low, high, "{id}");
|
||||
for out in [high, at(1000.0, 0.0)] {
|
||||
assert!(out.data.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_grain_keeps_flat_mean() {
|
||||
let out = run("ec.noise.addgrain", &[("tweaking/intensity", num(2.0)), ("application/blendingMode", Value::Enum(2))], gray(64, 64, 0.5), 0.0);
|
||||
|
||||
@@ -24,8 +24,7 @@
|
||||
//! * Configuration ▸ Custom reads a `.ocio` file instead ([`crate::ocio_config`]); what it can't
|
||||
//! apply is reported by [`warning`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_color::ColorSpace;
|
||||
use effectcraft_color::space::{invert, mul, mul_vec, rgb_to_xyz};
|
||||
@@ -51,6 +50,7 @@ pub use effects::parse_looks;
|
||||
pub use effects::{color_stabilizer_maps, warning};
|
||||
#[cfg(test)]
|
||||
use effects::{tonemap, tonemap_inv};
|
||||
pub(crate) use lut::cached_files;
|
||||
pub use lut::{FileXform, load_file};
|
||||
#[cfg(test)]
|
||||
pub use lut::{parse_file, parse_spi1d, parse_spi3d, parse_spimtx};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::cdl::{Cdl, parse_cdl_xml};
|
||||
use super::{Arc, HashMap, Lut, Mutex, OnceLock, parse_cube};
|
||||
use super::{Arc, Lut, parse_cube};
|
||||
use crate::file_cache::{self, Registered};
|
||||
|
||||
// ---------------------------------------------------------------- LUT files
|
||||
|
||||
@@ -264,33 +265,38 @@ pub fn parse_file(text: &str, ext: &str) -> Option<FileXform> {
|
||||
parse_3dl(text).map(|lut| FileXform::Lut { lut, shaper: None })
|
||||
}
|
||||
|
||||
type FileCache = Mutex<HashMap<String, Option<Arc<FileXform>>>>;
|
||||
/// [`load_file`]'s cache, by parameter text (bounded like [`crate::load_lut`]'s).
|
||||
static FILES: Registered<Option<Arc<FileXform>>> = Registered::new(64, 512 << 20);
|
||||
|
||||
/// Load (and cache) a transform from a file path or inline content.
|
||||
/// The files the transform cached for `src` was read from.
|
||||
pub(crate) fn cached_files(src: &str) -> Option<Vec<String>> {
|
||||
file_cache::lock(FILES.get()).files(src)
|
||||
}
|
||||
|
||||
/// Load (and cache) a transform from a file path or inline content. A file is stamped (one
|
||||
/// `metadata` call) on every load and read again once its size or modification time moved (see
|
||||
/// [`crate::file_cache`]); inline content is its own content.
|
||||
pub fn load_file(src: &str) -> Option<Arc<FileXform>> {
|
||||
let src_t = src.trim();
|
||||
if src_t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
static CACHE: OnceLock<FileCache> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Ok(m) = cache.lock()
|
||||
&& let Some(v) = m.get(src)
|
||||
{
|
||||
return v.clone();
|
||||
}
|
||||
let inline = src.contains('\n');
|
||||
let parsed = if inline {
|
||||
parse_file(src, "")
|
||||
} else {
|
||||
let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("");
|
||||
std::fs::read_to_string(src_t).ok().and_then(|t| parse_file(&t, ext))
|
||||
}
|
||||
.map(Arc::new);
|
||||
if let Ok(mut m) = cache.lock() {
|
||||
m.insert(src.to_string(), parsed.clone());
|
||||
}
|
||||
parsed
|
||||
file_cache::cached(FILES.get(), src, || {
|
||||
let parsed = if src.contains('\n') {
|
||||
parse_file(src, "")
|
||||
} else {
|
||||
let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("");
|
||||
file_cache::read(src_t).ok().and_then(|t| parse_file(&t, ext))
|
||||
}
|
||||
.map(Arc::new);
|
||||
let bytes = match parsed.as_deref() {
|
||||
Some(FileXform::Lut { lut, shaper }) => crate::utility::lut_bytes(lut)
|
||||
.saturating_add(shaper.as_ref().map_or(0, |s| s.iter().map(Vec::len).sum::<usize>().saturating_mul(std::mem::size_of::<(f32, f32)>()))),
|
||||
Some(FileXform::Cdl(c)) => c.len().saturating_mul(std::mem::size_of::<(String, Cdl)>()),
|
||||
Some(FileXform::Matrix { .. }) | None => 0,
|
||||
};
|
||||
(parsed, bytes)
|
||||
})
|
||||
}
|
||||
|
||||
impl FileXform {
|
||||
|
||||
@@ -396,3 +396,43 @@ fn color_stabilizer_samples_the_reference_at_the_points_reference_positions() {
|
||||
assert!((o(x) - (a + b * v(x))).abs() < 1e-3, "x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `text` to `dir/name` with modification time `secs` (so an edit within the file system's
|
||||
/// time resolution still moves the stamp), returning the path.
|
||||
fn write_dated(dir: &std::path::Path, name: &str, text: &str, secs: u64) -> String {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let f = std::fs::File::options().write(true).open(&path).unwrap();
|
||||
f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// #3538: OCIO File Transform read a file once per process; an edited, created, repaired or
|
||||
/// deleted file was never followed.
|
||||
#[test]
|
||||
fn an_ocio_transform_file_is_read_again_once_it_changes() {
|
||||
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
|
||||
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3538-file-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |src: &str| load_file(src).map(|x| x.apply([0.5; 3], 1, false, ""));
|
||||
let edited = write_dated(dir.as_path(), "edited.cube", BLACK, 1_000);
|
||||
assert_eq!(at(&edited), Some([0.0; 3]));
|
||||
write_dated(dir.as_path(), "edited.cube", WHITE, 2_000);
|
||||
assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size");
|
||||
let created = dir.as_path().join("created.cube").to_string_lossy().into_owned();
|
||||
assert_eq!(at(&created), None);
|
||||
write_dated(dir.as_path(), "created.cube", WHITE, 1_000);
|
||||
assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load");
|
||||
let repaired = write_dated(dir.as_path(), "repaired.cube", "not a lut", 1_000);
|
||||
assert_eq!(at(&repaired), None);
|
||||
write_dated(dir.as_path(), "repaired.cube", WHITE, 2_000);
|
||||
assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file");
|
||||
std::fs::remove_file(&repaired).unwrap();
|
||||
assert_eq!(at(&repaired), None, "a deleted file");
|
||||
// Inline text is its own content: the same text is the same transform.
|
||||
let inline = load_file(BLACK).unwrap();
|
||||
assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap()));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -42,9 +42,10 @@
|
||||
//! resolving named transforms [`MAX_NAMED_DEPTH`] levels down or past [`MAX_OPS`] steps
|
||||
//! (a config that refers to itself in a loop), so a hostile config can't exhaust the stack.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::file_cache::{self, Registered};
|
||||
|
||||
use super::ocio::{ACES_CG, ACES2065_1, Cdl, D65, FileXform, P3, REC709, REC2020, Space, Tf, load_file, matrix, sp};
|
||||
|
||||
@@ -882,13 +883,21 @@ fn resolve(src: &str, dir: &Path, search: &[String]) -> Option<PathBuf> {
|
||||
if src.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// (a candidate not there is noted: the config is read again once it appears)
|
||||
let found = |c: PathBuf| {
|
||||
let there = c.exists();
|
||||
if !there {
|
||||
file_cache::note_missing(&c.to_string_lossy());
|
||||
}
|
||||
there.then_some(c)
|
||||
};
|
||||
let p = Path::new(src);
|
||||
if p.is_absolute() {
|
||||
return p.exists().then(|| p.to_path_buf());
|
||||
return found(p.to_path_buf());
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = search.iter().map(|s| dir.join(s)).collect();
|
||||
dirs.push(dir.to_path_buf());
|
||||
dirs.into_iter().map(|d| d.join(src)).find(|c| c.exists())
|
||||
dirs.into_iter().map(|d| d.join(src)).find_map(found)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the config
|
||||
@@ -1338,33 +1347,34 @@ impl<'c> Build<'c> {
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigCache = Mutex<HashMap<String, Result<Arc<Config>, String>>>;
|
||||
/// [`load_config`]'s cache, by parameter text.
|
||||
static CONFIGS: Registered<Result<Arc<Config>, String>> = Registered::new(16, 64 << 20);
|
||||
|
||||
/// The files the config cached for `src` was read from: the `.ocio` file, the files its
|
||||
/// `FileTransform`s read and the places it looked for missing ones.
|
||||
pub(crate) fn cached_files(src: &str) -> Option<Vec<String>> {
|
||||
file_cache::lock(CONFIGS.get()).files(src)
|
||||
}
|
||||
|
||||
/// Load (and cache) a config from a `.ocio` path or the config text itself; why not, when it
|
||||
/// can't be read.
|
||||
/// can't be read. The config file and the files its `FileTransform`s read are stamped (one
|
||||
/// `metadata` call each) on every load, and the config is read again once one of them moved or a
|
||||
/// missing one appeared (see [`crate::file_cache`]).
|
||||
pub fn load_config(src: &str) -> Result<Arc<Config>, String> {
|
||||
let t = src.trim();
|
||||
if t.is_empty() {
|
||||
return Err("no config file chosen".into());
|
||||
}
|
||||
static CACHE: OnceLock<ConfigCache> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Ok(m) = cache.lock()
|
||||
&& let Some(v) = m.get(src)
|
||||
{
|
||||
return v.clone();
|
||||
}
|
||||
let parsed = if src.contains('\n') {
|
||||
Config::parse(src, Path::new("."))
|
||||
} else {
|
||||
file_cache::cached(CONFIGS.get(), src, || {
|
||||
if src.contains('\n') {
|
||||
return (Config::parse(src, Path::new(".")).map(Arc::new), 0);
|
||||
}
|
||||
let p = Path::new(t);
|
||||
std::fs::read_to_string(p).map_err(|e| format!("{t}: {e}")).and_then(|text| Config::parse(&text, p.parent().unwrap_or(Path::new("."))))
|
||||
}
|
||||
.map(Arc::new);
|
||||
if let Ok(mut m) = cache.lock() {
|
||||
m.insert(src.to_string(), parsed.clone());
|
||||
}
|
||||
parsed
|
||||
match file_cache::read(t) {
|
||||
Ok(text) => (Config::parse(&text, p.parent().unwrap_or(Path::new("."))).map(Arc::new), text.len()),
|
||||
Err(e) => (Err(format!("{t}: {e}")), 0),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -410,3 +410,69 @@ fn builtin_styles() {
|
||||
fn rgb_white_xyz() -> [f64; 3] {
|
||||
[D65[0] / D65[1], 1.0, (1.0 - D65[0] - D65[1]) / D65[1]]
|
||||
}
|
||||
|
||||
/// #3538: a custom `.ocio` config, and the LUTs it reads, were read once per process.
|
||||
#[test]
|
||||
fn an_ocio_config_and_its_luts_are_read_again_once_they_change() {
|
||||
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
|
||||
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3538-config-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(dir.as_path().join("luts")).unwrap();
|
||||
let write = |name: &str, text: &str, secs: u64| {
|
||||
let path = dir.as_path().join(name);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let f = std::fs::File::options().write(true).open(&path).unwrap();
|
||||
f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
};
|
||||
let config = |space: &str| {
|
||||
format!(
|
||||
"ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !<ColorSpace>\n name: lin\n - !<ColorSpace>\n name: {space}\n to_reference: !<FileTransform> {{src: grade.cube, interpolation: linear}}\n - !<ColorSpace>\n name: later\n to_reference: !<FileTransform> {{src: later.cube, interpolation: linear}}\n"
|
||||
)
|
||||
};
|
||||
let src = dir.as_path().join("config.ocio").to_string_lossy().into_owned();
|
||||
assert!(load_config(&src).is_err(), "no config yet");
|
||||
write("config.ocio", &config("graded"), 1_000);
|
||||
write("luts/grade.cube", BLACK, 1_000);
|
||||
let to_lin = |space: &str| {
|
||||
let c = load_config(&src).unwrap();
|
||||
c.convert(c.space(space).unwrap(), c.space("lin").unwrap(), [0.5; 3])
|
||||
};
|
||||
assert_eq!(to_lin("graded"), [0.0; 3], "a config created after a failed load");
|
||||
write("luts/grade.cube", WHITE, 2_000);
|
||||
assert_eq!(to_lin("graded"), [1.0; 3], "a LUT the config reads, edited");
|
||||
assert_eq!(to_lin("later"), [0.5; 3], "a LUT not there yet passes through");
|
||||
write("luts/later.cube", BLACK, 1_000);
|
||||
assert_eq!(to_lin("later"), [0.0; 3], "a LUT the config reads, created");
|
||||
write("config.ocio", &config("regraded"), 2_000);
|
||||
assert!(load_config(&src).unwrap().space("regraded").is_some(), "an edited config");
|
||||
std::fs::remove_file(&src).unwrap();
|
||||
assert!(load_config(&src).is_err(), "a deleted config");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A LUT a cached config read that changes is noticed without a render loading the config (the
|
||||
/// interface's watcher), and the config's files name it (frame and layer cache keys hold them).
|
||||
#[test]
|
||||
fn check_lut_files_notices_a_configs_lut() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3538-check-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let lut = dir.join("watched.cube");
|
||||
std::fs::write(&lut, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
|
||||
let config = dir.join("config.ocio");
|
||||
std::fs::write(&config, "ocio_profile_version: 2\ncolorspaces:\n - !<ColorSpace>\n name: lin\n - !<ColorSpace>\n name: graded\n to_reference: !<FileTransform> {src: watched.cube}\n").unwrap();
|
||||
let src = config.to_string_lossy().into_owned();
|
||||
// A config not read yet is read: its files name its LUT from the first render on.
|
||||
let files = crate::lut_files(&src);
|
||||
assert!(files.contains(&lut.to_string_lossy().into_owned()), "{files:?}");
|
||||
assert!(load_config(&src).is_ok());
|
||||
let before = crate::check_lut_files();
|
||||
assert!(cached_files(&src).is_some(), "an unchanged config stays");
|
||||
std::fs::write(&lut, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap();
|
||||
assert!(crate::check_lut_files() > before);
|
||||
assert!(cached_files(&src).is_none(), "a config whose LUT changed is read again");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -612,7 +612,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"ec.stylize.scatter",
|
||||
"Scatter",
|
||||
vec![
|
||||
p("amount", "Scatter Amount", num(0.0), slider(0.0, 127.0, 0.0, 127.0, 1)),
|
||||
p("amount", "Scatter Amount", num(0.0), slider(0.0, 1000.0, 0.0, 127.0, 1)),
|
||||
p("grain", "Grain", Value::Enum(0), popup(&["Both", "Horizontal", "Vertical"])),
|
||||
p("randomizeEveryFrame", "Scatter Randomness", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
|
||||
+156
-19
@@ -1,9 +1,9 @@
|
||||
//! Utility effects: bounds growth, HDR inspection/compression, Cineon log conversion and colour
|
||||
//! lookup tables (.cube).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::file_cache::{self, Registered};
|
||||
use effectcraft_color::luminance;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
@@ -330,28 +330,71 @@ impl Lut {
|
||||
}
|
||||
}
|
||||
|
||||
type LutCache = Mutex<HashMap<String, Option<Arc<Lut>>>>;
|
||||
/// At most this many parsed LUTs (files and inline texts) are kept, and at most
|
||||
/// [`MAX_CACHED_BYTES`] of them; the least recently used go first.
|
||||
const MAX_CACHED_LUTS: usize = 64;
|
||||
const MAX_CACHED_BYTES: usize = 512 << 20;
|
||||
|
||||
/// Load (and cache) a LUT from inline `.cube` text or a file path.
|
||||
/// [`load_lut`]'s cache, by parameter text.
|
||||
static LUTS: Registered<Option<Arc<Lut>>> = Registered::new(MAX_CACHED_LUTS, MAX_CACHED_BYTES);
|
||||
|
||||
/// The parameters (paths in the effect's group) of `effect` that name a file an effect reads
|
||||
/// through a cache that follows it ([`load_lut`], the OCIO file transforms and configs).
|
||||
pub fn lut_params(effect: &str) -> &'static [&'static str] {
|
||||
match effect {
|
||||
"ec.utility.applylut" => &["lut"],
|
||||
"ec.color.lumetri" => &["basicCorrection/inputLutFile", "creative/lookFile"],
|
||||
"ec.color.ociofile" => &["file"],
|
||||
"ec.color.ociocolorspace" | "ec.color.ociodisplay" => &["configFile"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The file a LUT parameter names; `None` for inline `.cube` text or an empty parameter.
|
||||
pub fn lut_file(src: &str) -> Option<&str> {
|
||||
// `.cube` text always spans lines (a size header, then data rows); a path never does, even one
|
||||
// whose file name contains `LUT_` (#3454). Trimmed, so a trailing newline is still a path.
|
||||
let path = src.trim();
|
||||
(!path.is_empty() && !path.contains('\n')).then_some(path)
|
||||
}
|
||||
|
||||
/// The files a [`lut_params`] parameter set to `src` reads: the ones its cached result was read
|
||||
/// from (an OCIO config's also the LUTs it names, and the places it looked for missing ones; an
|
||||
/// `.ocio` config not read yet is read), else the file it names.
|
||||
pub fn lut_files(src: &str) -> Vec<String> {
|
||||
// A config not read yet is read now: the LUTs it names are its files from the first render.
|
||||
if crate::ocio_config::cached_files(src).is_none()
|
||||
&& lut_file(src).is_some_and(|p| std::path::Path::new(p).extension().is_some_and(|e| e.eq_ignore_ascii_case("ocio")))
|
||||
{
|
||||
let _ = crate::ocio_config::load_config(src);
|
||||
}
|
||||
crate::ocio_config::cached_files(src)
|
||||
.or_else(|| crate::ocio::cached_files(src))
|
||||
.or_else(|| file_cache::lock(LUTS.get()).files(src))
|
||||
.unwrap_or_else(|| lut_file(src).map(str::to_string).into_iter().collect())
|
||||
}
|
||||
|
||||
/// Load (and cache) a LUT from inline `.cube` text or a file path. A file is stamped (one
|
||||
/// `metadata` call) on every load and read again once its size or modification time moved (see
|
||||
/// [`crate::file_cache`]); inline text is its own content.
|
||||
pub fn load_lut(src: &str) -> Option<Arc<Lut>> {
|
||||
if src.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
static CACHE: OnceLock<LutCache> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Ok(m) = cache.lock()
|
||||
&& let Some(v) = m.get(src)
|
||||
{
|
||||
return v.clone();
|
||||
}
|
||||
// `.cube` text always spans lines (a size header, then data rows); a path never does, even one
|
||||
// whose file name contains `LUT_` (#3454). Trimmed, as the path is, so a trailing newline is a path.
|
||||
let inline = src.trim().contains('\n');
|
||||
let parsed = if inline { parse_cube(src) } else { std::fs::read_to_string(src.trim()).ok().and_then(|t| parse_cube(&t)) }.map(Arc::new);
|
||||
if let Ok(mut m) = cache.lock() {
|
||||
m.insert(src.to_string(), parsed.clone());
|
||||
}
|
||||
parsed
|
||||
file_cache::cached(LUTS.get(), src, || {
|
||||
let lut = match lut_file(src) {
|
||||
Some(path) => file_cache::read(path).ok().and_then(|t| parse_cube(&t)),
|
||||
None => parse_cube(src),
|
||||
}
|
||||
.map(Arc::new);
|
||||
let bytes = lut.as_ref().map_or(0, |l| lut_bytes(l));
|
||||
(lut, bytes)
|
||||
})
|
||||
}
|
||||
|
||||
/// The size of a LUT's tables.
|
||||
pub(crate) fn lut_bytes(l: &Lut) -> usize {
|
||||
l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>())
|
||||
}
|
||||
|
||||
fn apply_lut(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
@@ -500,6 +543,100 @@ mod tests {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// #3493: a LUT file was read once per process; an edited or newly created file never loaded.
|
||||
#[test]
|
||||
fn a_lut_file_is_read_again_once_it_changes() {
|
||||
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
|
||||
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3493-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let write = |name: &str, text: &str, secs: u64| {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let f = std::fs::File::options().write(true).open(&path).unwrap();
|
||||
f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
};
|
||||
let at = |src: &str| load_lut(src).map(|l| l.apply([0.5; 3]));
|
||||
let edited = write("edited.cube", BLACK, 1_000);
|
||||
assert_eq!(at(&edited), Some([0.0; 3]));
|
||||
write("edited.cube", WHITE, 2_000);
|
||||
assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size");
|
||||
let created = dir.join("created.cube").to_string_lossy().into_owned();
|
||||
assert_eq!(at(&created), None);
|
||||
write("created.cube", WHITE, 1_000);
|
||||
assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load");
|
||||
let repaired = write("repaired.cube", "not a lut", 1_000);
|
||||
assert_eq!(at(&repaired), None);
|
||||
write("repaired.cube", WHITE, 2_000);
|
||||
assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file");
|
||||
std::fs::remove_file(&repaired).unwrap();
|
||||
assert_eq!(at(&repaired), None, "a deleted file");
|
||||
// Inline text is its own content: the same text is the same LUT.
|
||||
let inline = load_lut(BLACK).unwrap();
|
||||
assert!(Arc::ptr_eq(&inline, &load_lut(BLACK).unwrap()));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A file that changed is noticed without a render loading it, and the generation that tells
|
||||
/// frames made before it apart moves.
|
||||
#[test]
|
||||
fn check_lut_files_forgets_a_changed_file() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3493-check-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("grade.cube");
|
||||
std::fs::write(&path, identity_cube(2)).unwrap();
|
||||
let src = path.to_string_lossy().into_owned();
|
||||
assert!(load_lut(&src).is_some());
|
||||
let before = crate::check_lut_files();
|
||||
assert!(file_cache::lock(LUTS.get()).contains(&src), "an unchanged file stays");
|
||||
std::fs::write(&path, identity_cube(3)).unwrap();
|
||||
assert!(crate::check_lut_files() > before);
|
||||
assert!(!file_cache::lock(LUTS.get()).contains(&src), "a changed file is read again");
|
||||
assert_eq!(load_lut(&src).map(|l| l.n3), Some(3));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// The cache keeps at most [`MAX_CACHED_LUTS`] LUTs, the least recently used going first.
|
||||
#[test]
|
||||
fn the_lut_cache_is_bounded() {
|
||||
// (text no other test loads: a load elsewhere would make it recently used)
|
||||
let oldest = format!("TITLE \"bounded first\"\n{}", identity_cube(2));
|
||||
let first = load_lut(&oldest).unwrap();
|
||||
for i in 0..MAX_CACHED_LUTS + 8 {
|
||||
let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2));
|
||||
assert!(load_lut(&text).is_some());
|
||||
assert!(file_cache::lock(LUTS.get()).len() <= MAX_CACHED_LUTS);
|
||||
}
|
||||
assert!(!Arc::ptr_eq(&first, &load_lut(&oldest).unwrap()), "the oldest was let go");
|
||||
let (bytes, sum, max) = file_cache::lock(LUTS.get()).bytes();
|
||||
assert_eq!(bytes, sum, "the bytes kept add up");
|
||||
assert!(bytes <= max);
|
||||
}
|
||||
|
||||
/// A LUT file whose LUT left the cache is still followed: its frames are dropped when it
|
||||
/// changes, though no render loads it again first.
|
||||
#[test]
|
||||
fn a_file_whose_lut_left_the_cache_is_still_followed() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-fx-3493-evicted-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("old.cube");
|
||||
std::fs::write(&path, identity_cube(2)).unwrap();
|
||||
let src = path.to_string_lossy().into_owned();
|
||||
assert!(load_lut(&src).is_some());
|
||||
for i in 0..MAX_CACHED_LUTS + 8 {
|
||||
assert!(load_lut(&format!("TITLE \"evict {i}\"\n{}", identity_cube(2))).is_some());
|
||||
}
|
||||
assert!(!file_cache::lock(LUTS.get()).contains(&src), "its LUT left the cache");
|
||||
std::fs::write(&path, identity_cube(3)).unwrap();
|
||||
crate::check_lut_files();
|
||||
assert_eq!(file_cache::followed_stamp(&src), Some(file_cache::file_stamp(&src)), "the change was noticed");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_d_lut_with_domain() {
|
||||
let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod camera_track;
|
||||
pub(crate) mod frames_key;
|
||||
pub mod mask_track;
|
||||
pub mod models;
|
||||
pub mod roto;
|
||||
|
||||
@@ -26,9 +26,10 @@ use effectcraft_track::camtrack::linalg::{self, Similarity, V3};
|
||||
use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::analysis::frames_key;
|
||||
use crate::offload::JobKind;
|
||||
use crate::tracking::lock;
|
||||
use crate::warp::{analysis_times, signature};
|
||||
use crate::warp::analysis_times;
|
||||
use crate::{Event, Session};
|
||||
|
||||
/// Live analysis progress (serde for agents / the control channel).
|
||||
@@ -81,7 +82,7 @@ pub struct CameraJob {
|
||||
pub comp: ItemId,
|
||||
pub layer: LayerId,
|
||||
pub effect: Uid,
|
||||
/// The layer signature the tracks are made from, and the solve settings key.
|
||||
/// What the tracks are made from (`tracks_key`), and the solve settings key.
|
||||
key: String,
|
||||
solve_key: String,
|
||||
}
|
||||
@@ -122,10 +123,21 @@ fn str_of(g: &PropGroup, m: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a tracker's tracks are made from: the layer's frames and Detailed Analysis.
|
||||
/// What a tracker's tracks are made from: its input (the layer's frames under its masks and the
|
||||
/// effects above it, `frames_key::analysis_key`) and Detailed Analysis.
|
||||
fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String {
|
||||
tracks_key_of(frames_key::analysis_key(project, cid, l, g.uid), g)
|
||||
}
|
||||
|
||||
fn tracks_key_of(input: String, g: &PropGroup) -> String {
|
||||
let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool);
|
||||
format!("{}{}", signature(project, cid, l), if detailed { "+detailed" } else { "" })
|
||||
format!("{input}{}", if detailed { "+detailed" } else { "" })
|
||||
}
|
||||
|
||||
/// Whether the tracker's saved tracks are made from its current input and settings, after an
|
||||
/// edit from `before` to `project` ([`frames_key::analysis_key_matches`]).
|
||||
fn tracks_match(before: &Project, project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool {
|
||||
frames_key::analysis_key_matches(before, project, cid, l, g.uid, &str_of(g, TRACKS_KEY), |k| tracks_key_of(k, g))
|
||||
}
|
||||
|
||||
/// Parameters of an instance from static values (the tracker's settings are not animated).
|
||||
@@ -165,7 +177,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId,
|
||||
let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id));
|
||||
for g in fx.groups().filter(|g| is_tracker(g)) {
|
||||
let tracked = !str_of(g, TRACKS).is_empty();
|
||||
if tracked && str_of(g, TRACKS_KEY) != tracks_key(after, *cid, l, g) {
|
||||
if tracked && !tracks_match(before, after, *cid, l, g) {
|
||||
clears.push((*cid, l.id, g.uid, true));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) {
|
||||
@@ -325,7 +337,7 @@ impl Session {
|
||||
let key = tracks_key(&self.project, comp, l, g);
|
||||
let settings = ct::settings(¶ms);
|
||||
let solve_key = ct::solve_key(&settings);
|
||||
let tracks = ct::tracks(¶ms).filter(|_| str_of(g, TRACKS_KEY) == key);
|
||||
let tracks = ct::tracks(¶ms).filter(|_| tracks_match(&self.project, &self.project, comp, l, g));
|
||||
let n = times.len();
|
||||
let work = CamWork {
|
||||
project: self.project.clone(),
|
||||
|
||||
@@ -0,0 +1,777 @@
|
||||
//! What an analysis of a layer is made from. One writer keys the Warp Stabilizer and the 3D
|
||||
//! Camera Tracker ([`analysis_key`]: frames, masks, effects above, a precomp's contents) and Roto
|
||||
//! Brush / Object Matte ([`input_key`]: frames, masks, effects above).
|
||||
//!
|
||||
//! The key hashes a text this module writes field by field. The source item (footage and its
|
||||
//! settings, solid), the Time Remap property, the masks and effect groups (their properties,
|
||||
//! keyframes and values) and a precomp's comp and layers are destructured or matched in full, and
|
||||
//! each variant is written as a fixed word (or, for an enum the project file names, its name
|
||||
//! there): a new field or variant doesn't compile until it is decided here, written if it changes
|
||||
//! the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant doesn't
|
||||
//! change keys. Of the analysed layer itself, only the fields named in `layer_frames` and
|
||||
//! [`analysis_key`] are read. The text leaves out observations (whether footage is available) and
|
||||
//! data that never changes pixels (colour labels, UI hints, markers but a comp's timing markers;
|
||||
//! only expressions read the others), so they never drop saved
|
||||
//! analyses (#3534, #3536).
|
||||
//!
|
||||
//! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises
|
||||
//! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and
|
||||
//! segmentations hash the saved key itself.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use effectcraft_color::ColorSpace;
|
||||
use effectcraft_keyframe::{Ease, FeatherPoint, Gradient, Interp, Keyframe, ShapePath, Value};
|
||||
use effectcraft_project::{
|
||||
AlphaMode, CineonSettings, CineonUnits, Comp, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer,
|
||||
LayerSource, LightKind, Marker, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Switches, TrackMatte, Uid,
|
||||
essential, styles::GlobalLight,
|
||||
};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
pub(crate) mod legacy;
|
||||
|
||||
/// The version of the text, its first word: a later change to what it writes bumps it.
|
||||
const VERSION: &str = "frames/1";
|
||||
|
||||
/// Property groups nest a few levels (effect ▸ group ▸ property); deeper trees are cut here.
|
||||
const MAX_DEPTH: usize = 32;
|
||||
|
||||
/// Precomps nest deeper than the renderer draws them (16) only in broken projects; deeper
|
||||
/// contents are cut here.
|
||||
const MAX_NESTING: usize = 32;
|
||||
|
||||
fn fnv(s: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in s.as_bytes() {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
fn hex(s: &str) -> String {
|
||||
format!("{:016x}", fnv(s))
|
||||
}
|
||||
|
||||
/// Which signature a key is made from: today's, or one an earlier release saved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Era {
|
||||
Current,
|
||||
Legacy,
|
||||
}
|
||||
|
||||
/// The signature of `layer`'s frames: its source (and the source item), In/Out, start time,
|
||||
/// stretch, Time Remap and the comp frame rate. Roto Brush Input Keys and [`analysis_key`] are
|
||||
/// made from it.
|
||||
pub(crate) fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String {
|
||||
hex(&signature_text(p, comp, layer))
|
||||
}
|
||||
|
||||
/// The text [`signature`] hashes.
|
||||
pub(crate) fn signature_text(p: &Project, comp: ItemId, layer: &Layer) -> String {
|
||||
let mut t = Text::new();
|
||||
t.word(VERSION);
|
||||
t.layer_frames(p, comp, layer);
|
||||
t.0
|
||||
}
|
||||
|
||||
/// A Roto Brush's (or Object Matte's) Input Key: the layer's frames, its masks and the effects
|
||||
/// above the instance `uid`.
|
||||
pub(crate) fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
input_key_of(signature(p, comp, layer), layer, uid)
|
||||
}
|
||||
|
||||
/// An Input Key from a [`signature`].
|
||||
pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String {
|
||||
let mut t = Text::new();
|
||||
t.word(VERSION);
|
||||
t.word(&signature);
|
||||
t.inputs_above(layer, uid, true);
|
||||
hex(&t.0)
|
||||
}
|
||||
|
||||
/// The first word of an [`analysis_key`]'s text: a later change to what it writes bumps it.
|
||||
const ANALYSIS_VERSION: &str = "analysis/1";
|
||||
|
||||
/// What a Warp Stabilizer or 3D Camera Tracker, the instance `uid` of `layer`, analyses: its
|
||||
/// input, the layer's frames ([`signature`]) under its masks and the effects above it, and a
|
||||
/// precomp's contents (#3535). The instance's own settings and the effects below it are not part
|
||||
/// of it.
|
||||
pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
let mut t = Text::new();
|
||||
t.word(ANALYSIS_VERSION);
|
||||
t.word(&signature(p, comp, layer));
|
||||
// The Effects switch turns the effects above on or off (it has none when it is the first).
|
||||
if layer.effects().and_then(|fx| fx.groups().next()).is_some_and(|g| g.uid != uid) {
|
||||
t.field("effectsSwitch", layer.switches.effects);
|
||||
}
|
||||
// While it is off the renderer skips the whole effect stack: the effects above draw nothing.
|
||||
t.inputs_above(layer, uid, layer.switches.effects);
|
||||
t.precomp(p, comp, layer);
|
||||
hex(&t.0)
|
||||
}
|
||||
|
||||
/// Whether `saved`, the key saved with the analysis of instance `uid` of `layer` in `after`, is
|
||||
/// for its current input ([`analysis_key`]). `key` makes the saved form from an input key or a
|
||||
/// frames signature (the tracker adds its Detailed Analysis).
|
||||
///
|
||||
/// Keys saved before #3535 hashed only the layer's frames ([`signature`], or a [`legacy`] one).
|
||||
/// Such a key is taken to be for the input the layer had when it was opened, and stays valid
|
||||
/// while each edit (from `before` to `after`) keeps the input: the first edit that changes it
|
||||
/// clears the analysis. A layer or instance new in `after` (pasted, opened) keeps such a key
|
||||
/// while its frames match.
|
||||
pub(crate) fn analysis_key_matches(
|
||||
before: &Project,
|
||||
after: &Project,
|
||||
comp: ItemId,
|
||||
layer: &Layer,
|
||||
uid: Uid,
|
||||
saved: &str,
|
||||
key: impl Fn(String) -> String,
|
||||
) -> bool {
|
||||
let now = analysis_key(after, comp, layer, uid);
|
||||
if key(now.clone()) == saved {
|
||||
return true;
|
||||
}
|
||||
let old = before.comp(comp).and_then(|c| c.layer(layer.id)).filter(|l| l.props.find_group(uid).is_some());
|
||||
match old {
|
||||
Some(old) => key_matches(before, comp, old, saved, |s, _| key(s)) && analysis_key(before, comp, old, uid) == now,
|
||||
None => key_matches(after, comp, layer, saved, |s, _| key(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `saved`, a key saved with an analysis of `layer`, is for the layer's current frames.
|
||||
/// `key` makes such a key from a signature of the given era. A key an earlier release saved for
|
||||
/// the same frames matches too: keep it rather than rewrite it (analysing writes today's).
|
||||
pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String, Era) -> String) -> bool {
|
||||
key(signature(p, comp, layer), Era::Current) == saved || legacy::signatures(p, comp, layer).into_iter().any(|s| key(s, Era::Legacy) == saved)
|
||||
}
|
||||
|
||||
/// The text a key is hashed from. Fields are `name=value;`; strings are quoted and escaped, so
|
||||
/// no value can end its field early.
|
||||
struct Text(String);
|
||||
|
||||
impl Text {
|
||||
fn new() -> Text {
|
||||
Text(String::new())
|
||||
}
|
||||
|
||||
fn word(&mut self, w: &str) {
|
||||
self.0.push_str(w);
|
||||
self.0.push(';');
|
||||
}
|
||||
|
||||
fn field(&mut self, name: &str, value: impl std::fmt::Display) {
|
||||
let _ = write!(self.0, "{name}={value};");
|
||||
}
|
||||
|
||||
fn str(&mut self, name: &str, s: &str) {
|
||||
let _ = write!(self.0, "{name}={s:?};");
|
||||
}
|
||||
|
||||
fn num(&mut self, name: &str, v: f64) {
|
||||
let _ = write!(self.0, "{name}={v:?};");
|
||||
}
|
||||
|
||||
fn nums(&mut self, name: &str, v: &[f64]) {
|
||||
let _ = write!(self.0, "{name}={v:?};");
|
||||
}
|
||||
|
||||
fn floats(&mut self, name: &str, v: &[f32]) {
|
||||
let _ = write!(self.0, "{name}={v:?};");
|
||||
}
|
||||
|
||||
fn opt<T>(&mut self, name: &str, v: Option<&T>, write: impl FnOnce(&mut Text, &T)) {
|
||||
match v {
|
||||
Some(v) => {
|
||||
let _ = write!(self.0, "{name}{{");
|
||||
write(self, v);
|
||||
self.0.push_str("};");
|
||||
}
|
||||
None => self.word(&format!("{name}=none")),
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self, name: &str, t: Tick) {
|
||||
self.field(name, t.0);
|
||||
}
|
||||
|
||||
fn rate(&mut self, name: &str, r: FrameRate) {
|
||||
let FrameRate { num, den } = r;
|
||||
let _ = write!(self.0, "{name}={num}/{den};");
|
||||
}
|
||||
|
||||
/// What a layer's frames are made of, before its masks and effects.
|
||||
fn layer_frames(&mut self, p: &Project, comp: ItemId, layer: &Layer) {
|
||||
self.layer_source(&layer.source);
|
||||
if let Some(item) = layer.source.item() {
|
||||
match p.item(item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => self.footage(f),
|
||||
Some(ItemKind::Solid(s)) => self.solid(s),
|
||||
// Its contents are in an [`analysis_key`], not here: Roto Brush keys are made from this.
|
||||
Some(ItemKind::Comp(c)) => {
|
||||
self.word("comp");
|
||||
self.field("w", c.width);
|
||||
self.field("h", c.height);
|
||||
self.rate("rate", c.frame_rate);
|
||||
self.tick("duration", c.duration);
|
||||
}
|
||||
Some(ItemKind::Folder) | None => self.word("item=none"),
|
||||
}
|
||||
}
|
||||
self.tick("in", layer.in_point);
|
||||
self.tick("out", layer.out_point);
|
||||
self.tick("start", layer.start_time);
|
||||
self.num("stretch", layer.stretch);
|
||||
self.opt("timeRemap", layer.props.get("timeRemap"), |t, pr| t.property(pr));
|
||||
self.opt("compRate", p.comp(comp).map(|c| &c.frame_rate), |t, r| t.rate("rate", *r));
|
||||
}
|
||||
|
||||
fn layer_source(&mut self, s: &LayerSource) {
|
||||
match s {
|
||||
LayerSource::Footage { item } => self.field("footage", item.0),
|
||||
LayerSource::Comp { item } => self.field("comp", item.0),
|
||||
LayerSource::Solid { item } => self.field("solid", item.0),
|
||||
LayerSource::Model { item } => self.field("model", item.0),
|
||||
LayerSource::Text => self.word("text"),
|
||||
LayerSource::Shape => self.word("shape"),
|
||||
LayerSource::Null => self.word("null"),
|
||||
LayerSource::Camera => self.word("camera"),
|
||||
LayerSource::Light { kind } => self.field(
|
||||
"light",
|
||||
match kind {
|
||||
LightKind::Parallel => "parallel",
|
||||
LightKind::Spot => "spot",
|
||||
LightKind::Point => "point",
|
||||
LightKind::Ambient => "ambient",
|
||||
LightKind::Environment => "environment",
|
||||
},
|
||||
),
|
||||
LayerSource::Primitive { kind } => self.field(
|
||||
"primitive",
|
||||
match kind {
|
||||
PrimitiveKind::Cube => "cube",
|
||||
PrimitiveKind::Sphere => "sphere",
|
||||
PrimitiveKind::Plane => "plane",
|
||||
PrimitiveKind::Torus => "torus",
|
||||
PrimitiveKind::Cone => "cone",
|
||||
PrimitiveKind::Cylinder => "cylinder",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn solid(&mut self, s: &Solid) {
|
||||
let Solid { color, width, height, pixel_aspect } = s;
|
||||
self.word("solid");
|
||||
self.floats("color", color);
|
||||
self.field("w", width);
|
||||
self.field("h", height);
|
||||
self.num("par", *pixel_aspect);
|
||||
}
|
||||
|
||||
fn footage(&mut self, f: &Footage) {
|
||||
let Footage {
|
||||
path,
|
||||
kind,
|
||||
width,
|
||||
height,
|
||||
pixel_aspect,
|
||||
frame_rate,
|
||||
native_rate,
|
||||
duration,
|
||||
has_video,
|
||||
has_audio,
|
||||
alpha,
|
||||
premul_color,
|
||||
loop_count,
|
||||
codec,
|
||||
// Whether the file is there is an observation (`footage.check`), not an edit: an
|
||||
// offline file is the same footage, and its analyses stay valid (#3534).
|
||||
missing: _,
|
||||
sequence,
|
||||
color_profile,
|
||||
layer,
|
||||
fields,
|
||||
invert_alpha,
|
||||
linear_light,
|
||||
preserve_rgb,
|
||||
cineon,
|
||||
data,
|
||||
page,
|
||||
alphabetical,
|
||||
start_timecode,
|
||||
file_timecode,
|
||||
// Markers annotate the footage; they never change its frames.
|
||||
markers: _,
|
||||
placed_page,
|
||||
} = f;
|
||||
self.word("footage");
|
||||
self.str("path", path);
|
||||
self.field(
|
||||
"kind",
|
||||
match kind {
|
||||
FootageKind::Video => "video",
|
||||
FootageKind::Still => "still",
|
||||
FootageKind::Sequence => "sequence",
|
||||
FootageKind::Audio => "audio",
|
||||
FootageKind::Model => "model",
|
||||
FootageKind::Data => "data",
|
||||
},
|
||||
);
|
||||
self.field("w", width);
|
||||
self.field("h", height);
|
||||
self.num("par", *pixel_aspect);
|
||||
self.rate("rate", *frame_rate);
|
||||
self.opt("nativeRate", native_rate.as_ref(), |t, r| t.rate("rate", *r));
|
||||
self.tick("duration", *duration);
|
||||
self.field("video", has_video);
|
||||
self.field("audio", has_audio);
|
||||
self.field(
|
||||
"alpha",
|
||||
match alpha {
|
||||
AlphaMode::Straight => "straight",
|
||||
AlphaMode::Premultiplied => "premultiplied",
|
||||
AlphaMode::Ignore => "ignore",
|
||||
},
|
||||
);
|
||||
self.floats("matte", premul_color);
|
||||
self.field("loop", loop_count);
|
||||
self.str("codec", codec);
|
||||
self.field("frames", sequence.len());
|
||||
for s in sequence {
|
||||
self.str("file", s);
|
||||
}
|
||||
self.opt("profile", color_profile.as_ref(), |t, c| t.word(color_space(*c)));
|
||||
self.opt("layer", layer.as_ref(), |t, l| t.source_layer(l));
|
||||
self.field(
|
||||
"fields",
|
||||
match fields {
|
||||
FieldOrder::Off => "off",
|
||||
FieldOrder::UpperFirst => "upper",
|
||||
FieldOrder::LowerFirst => "lower",
|
||||
},
|
||||
);
|
||||
self.field("invertAlpha", invert_alpha);
|
||||
self.field("linearLight", linear_light);
|
||||
self.field("preserveRgb", preserve_rgb);
|
||||
self.cineon(cineon);
|
||||
self.opt("data", data.as_ref(), |t, d| t.str("text", d));
|
||||
self.field("page", page);
|
||||
self.field("alphabetical", alphabetical);
|
||||
self.opt("startTimecode", start_timecode.as_ref(), |t, v| t.field("frame", v));
|
||||
self.opt("fileTimecode", file_timecode.as_ref(), |t, v| t.field("frame", v));
|
||||
self.field("placedPage", placed_page);
|
||||
}
|
||||
|
||||
fn source_layer(&mut self, l: &SourceLayer) {
|
||||
let SourceLayer { index, name, layer_size, embedded, placed } = l;
|
||||
self.field("index", index);
|
||||
// The layer is found by its index; the name only labels it.
|
||||
let _ = name;
|
||||
self.field("layerSize", layer_size);
|
||||
self.opt("embedded", embedded.as_ref(), |t, e| t.str("id", e));
|
||||
self.field("placed", placed);
|
||||
}
|
||||
|
||||
fn cineon(&mut self, c: &CineonSettings) {
|
||||
let CineonSettings { log_conversion, converted_black, converted_white, black, white, gamma, rolloff, units } = c;
|
||||
self.word("cineon");
|
||||
self.field("log", log_conversion);
|
||||
self.floats("points", &[*converted_black, *converted_white, *black, *white, *gamma, *rolloff]);
|
||||
self.field(
|
||||
"units",
|
||||
match units {
|
||||
CineonUnits::TenBit => "10bit",
|
||||
CineonUnits::EightBit => "8bit",
|
||||
CineonUnits::Float => "float",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The layer's masks and the effects above the instance `uid`: what the effect's input is
|
||||
/// made of besides the layer's frames.
|
||||
/// `effects`: whether to write the effects (a Roto Brush Input Key always does: frozen mattes
|
||||
/// hash the saved key, so it keeps its text).
|
||||
fn inputs_above(&mut self, layer: &Layer, uid: Uid, effects: bool) {
|
||||
if let Some(m) = layer.masks() {
|
||||
self.word("masks");
|
||||
self.group(m, 0);
|
||||
}
|
||||
if let Some(fx) = layer.effects() {
|
||||
self.word("effects");
|
||||
for g in fx.groups().take_while(|g| effects && g.uid != uid) {
|
||||
self.group(g, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A precomp layer's contents: its Essential Properties (they set values inside it) and what
|
||||
/// its comp draws, nested precomps included.
|
||||
fn precomp(&mut self, p: &Project, comp: ItemId, layer: &Layer) {
|
||||
let LayerSource::Comp { item } = layer.source else { return };
|
||||
if let Some(e) = layer.props.group(essential::GROUP) {
|
||||
self.word("essential");
|
||||
self.group(e, 0);
|
||||
}
|
||||
// A precomp never draws the comp it is in.
|
||||
let mut seen = HashSet::from([comp]);
|
||||
self.comp_contents(p, item, 0, &mut seen);
|
||||
}
|
||||
|
||||
/// What comp `id` draws. Each comp is written once per key, where it is first reached; a
|
||||
/// later reference (a comp used twice, or a cycle) writes only its id, so the work is bounded
|
||||
/// by the size of the project.
|
||||
fn comp_contents(&mut self, p: &Project, id: ItemId, depth: usize, seen: &mut HashSet<ItemId>) {
|
||||
self.field("contents", id.0);
|
||||
// Before `seen`: a comp first reached too deep is written in full where it is shallower.
|
||||
if depth >= MAX_NESTING {
|
||||
self.word("tooDeep");
|
||||
return;
|
||||
}
|
||||
if !seen.insert(id) {
|
||||
self.word("seen");
|
||||
return;
|
||||
}
|
||||
let Some(ItemKind::Comp(c)) = p.item(id).map(|i| &i.kind) else {
|
||||
self.word("none");
|
||||
return;
|
||||
};
|
||||
let Comp {
|
||||
width,
|
||||
height,
|
||||
pixel_aspect,
|
||||
frame_rate,
|
||||
duration,
|
||||
display_start,
|
||||
background,
|
||||
// The work area, Hide Shy, the viewer's Resolution and guides, and the poster frame
|
||||
// only show the comp or say what to preview; they never change its frames.
|
||||
work_area: _,
|
||||
layers,
|
||||
markers,
|
||||
shutter_angle,
|
||||
shutter_phase,
|
||||
motion_blur_samples,
|
||||
motion_blur_adaptive_limit,
|
||||
renderer,
|
||||
hide_shy: _,
|
||||
enable_motion_blur,
|
||||
enable_frame_blending,
|
||||
draft_3d,
|
||||
preserve_frame_rate,
|
||||
preserve_resolution,
|
||||
poster_time: _,
|
||||
global_light,
|
||||
guides: _,
|
||||
essential,
|
||||
resolution: _,
|
||||
} = &**c;
|
||||
self.field("w", width);
|
||||
self.field("h", height);
|
||||
self.num("par", *pixel_aspect);
|
||||
self.rate("rate", *frame_rate);
|
||||
self.tick("duration", *duration);
|
||||
self.tick("displayStart", *display_start);
|
||||
self.floats("background", background);
|
||||
self.timing_markers(markers);
|
||||
self.nums("shutter", &[*shutter_angle, *shutter_phase]);
|
||||
self.field("samples", format_args!("{motion_blur_samples}/{motion_blur_adaptive_limit}"));
|
||||
self.form("renderer", renderer);
|
||||
self.field("motionBlur", enable_motion_blur);
|
||||
self.field("frameBlending", enable_frame_blending);
|
||||
self.field("draft3d", draft_3d);
|
||||
self.field("preserveRate", preserve_frame_rate);
|
||||
self.field("preserveResolution", preserve_resolution);
|
||||
let GlobalLight { angle, altitude } = global_light;
|
||||
self.property(angle);
|
||||
self.property(altitude);
|
||||
self.opt("essentialGraphics", essential.as_ref(), |t, e| t.form("definition", e));
|
||||
for l in layers.iter() {
|
||||
self.nested_layer(p, l, depth, seen);
|
||||
}
|
||||
self.word("end");
|
||||
}
|
||||
|
||||
/// A layer of a precomp.
|
||||
fn nested_layer(&mut self, p: &Project, l: &Layer, depth: usize, seen: &mut HashSet<ItemId>) {
|
||||
let Layer {
|
||||
id,
|
||||
name,
|
||||
// Whether the name follows the Source Text changes nothing until the name changes.
|
||||
name_follows_text: _,
|
||||
source,
|
||||
// Labels and comments only show the layer.
|
||||
label: _,
|
||||
comment: _,
|
||||
start_time,
|
||||
in_point,
|
||||
out_point,
|
||||
stretch,
|
||||
switches,
|
||||
blend_mode,
|
||||
preserve_transparency,
|
||||
track_matte,
|
||||
parent,
|
||||
// Layer markers annotate it (only expressions read them, as for the analysed layer);
|
||||
// Lock Markers protects them.
|
||||
markers: _,
|
||||
markers_locked: _,
|
||||
auto_orient,
|
||||
environment,
|
||||
environment_background,
|
||||
props,
|
||||
} = l;
|
||||
self.field("layer", id.0);
|
||||
// Expressions find layers by name (`thisComp.layer("Clip")`), as they find effects.
|
||||
self.str("name", name);
|
||||
self.layer_source(source);
|
||||
if let Some(item) = source.item() {
|
||||
match p.item(item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => self.footage(f),
|
||||
Some(ItemKind::Solid(s)) => self.solid(s),
|
||||
Some(ItemKind::Comp(_)) => self.comp_contents(p, item, depth.saturating_add(1), seen),
|
||||
Some(ItemKind::Folder) | None => self.word("item=none"),
|
||||
}
|
||||
}
|
||||
self.tick("in", *in_point);
|
||||
self.tick("out", *out_point);
|
||||
self.tick("start", *start_time);
|
||||
self.num("stretch", *stretch);
|
||||
self.switches(switches);
|
||||
self.form("blend", blend_mode);
|
||||
self.field("preserveTransparency", preserve_transparency);
|
||||
self.opt("matte", track_matte.as_ref(), |t, m| {
|
||||
let TrackMatte { layer, kind } = m;
|
||||
t.field("layer", layer.0);
|
||||
t.form("kind", kind);
|
||||
});
|
||||
self.opt("parent", parent.as_ref(), |t, id| t.field("id", id.0));
|
||||
self.form("autoOrient", auto_orient);
|
||||
self.field("environment", format_args!("{environment}/{environment_background}"));
|
||||
self.group(props, 0);
|
||||
}
|
||||
|
||||
fn switches(&mut self, s: &Switches) {
|
||||
// Lock and Shy only protect and hide the layer in the Timeline. Audio is written (as are
|
||||
// the Audio group and audio effects, in the property tree): a waveform effect can draw it.
|
||||
let Switches { video, audio, solo, locked: _, shy: _, collapse, quality, sampling, effects, frame_blend, motion_blur, adjustment, three_d, guide } = s;
|
||||
self.field("switches", format_args!("{video}/{audio}/{solo}/{collapse}/{effects}/{motion_blur}/{adjustment}/{three_d}/{guide}"));
|
||||
self.form("quality", quality);
|
||||
self.form("sampling", sampling);
|
||||
self.form("frameBlend", frame_blend);
|
||||
}
|
||||
|
||||
/// A comp's protected markers with a duration: they set its timing (Responsive Design).
|
||||
/// Other markers annotate it; only expressions read them.
|
||||
fn timing_markers(&mut self, markers: &[Marker]) {
|
||||
for m in markers.iter().filter(|m| m.protected && m.duration > Tick::ZERO) {
|
||||
self.tick("timingMarker", m.time);
|
||||
self.tick("for", m.duration);
|
||||
}
|
||||
}
|
||||
|
||||
/// A value in its project-file form: enums the project file names, and the Essential Graphics
|
||||
/// definition.
|
||||
fn form<T: serde::Serialize>(&mut self, name: &str, v: &T) {
|
||||
self.str(name, &serde_json::to_string(v).unwrap_or_default());
|
||||
}
|
||||
|
||||
fn group(&mut self, g: &PropGroup, depth: usize) {
|
||||
// Expressions find effects and groups by name (`effect("Blur")`, `propertyGroup(1).name`).
|
||||
// The uid and colour label never change pixels.
|
||||
let PropGroup { uid: _, match_id, name, kind, enabled, label: _, children } = g;
|
||||
if depth >= MAX_DEPTH {
|
||||
self.word("tooDeep");
|
||||
return;
|
||||
}
|
||||
self.str("group", match_id);
|
||||
self.str("name", name);
|
||||
self.group_kind(kind);
|
||||
self.field("enabled", enabled);
|
||||
for c in children {
|
||||
match c {
|
||||
Node::Prop(p) => self.property(p),
|
||||
Node::Group(g) => self.group(g, depth + 1),
|
||||
}
|
||||
}
|
||||
self.word("end");
|
||||
}
|
||||
|
||||
fn group_kind(&mut self, k: &GroupKind) {
|
||||
match k {
|
||||
GroupKind::Plain => self.word("plain"),
|
||||
GroupKind::Indexed => self.word("indexed"),
|
||||
// A mask's colour and lock only show it in the UI.
|
||||
GroupKind::Mask { mode, inverted, color: _, locked: _, motion_blur, feather_falloff, roto_bezier } => {
|
||||
self.field(
|
||||
"mask",
|
||||
match mode {
|
||||
MaskMode::None => "none",
|
||||
MaskMode::Add => "add",
|
||||
MaskMode::Subtract => "subtract",
|
||||
MaskMode::Intersect => "intersect",
|
||||
MaskMode::Lighten => "lighten",
|
||||
MaskMode::Darken => "darken",
|
||||
MaskMode::Difference => "difference",
|
||||
},
|
||||
);
|
||||
self.field("inverted", inverted);
|
||||
self.field(
|
||||
"motionBlur",
|
||||
match motion_blur {
|
||||
MaskMotionBlur::SameAsLayer => "layer",
|
||||
MaskMotionBlur::On => "on",
|
||||
MaskMotionBlur::Off => "off",
|
||||
},
|
||||
);
|
||||
self.field(
|
||||
"falloff",
|
||||
match feather_falloff {
|
||||
FeatherFalloff::Smooth => "smooth",
|
||||
FeatherFalloff::Linear => "linear",
|
||||
},
|
||||
);
|
||||
self.field("rotoBezier", roto_bezier);
|
||||
}
|
||||
GroupKind::Effect { effect } => self.str("effect", effect),
|
||||
// A motion tracker's settings say how to track, not how to draw the layer.
|
||||
GroupKind::Tracker { settings: _ } => self.word("tracker"),
|
||||
GroupKind::Essential { overridden } => {
|
||||
self.word("essential");
|
||||
for u in overridden {
|
||||
self.field("overridden", u);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn property(&mut self, pr: &Property) {
|
||||
// Expressions read the name (`thisProperty.name`) and seed `random`/`wiggle` with the
|
||||
// uid: the uid is written for a property with an expression. UI hints and the 2D/3D-only
|
||||
// and hold-only flags say where and how it can be edited, not what it evaluates to.
|
||||
let Property { uid, match_id, name, value, keys, expr, ui: _, spatial, hold_only: _, three_d_only: _, two_d_only: _, shown_dims: _, static_only: _ } =
|
||||
pr;
|
||||
self.str("prop", match_id);
|
||||
self.str("name", name);
|
||||
if expr.is_some() {
|
||||
self.field("uid", uid);
|
||||
}
|
||||
self.value(value);
|
||||
self.field("spatial", spatial);
|
||||
for k in keys {
|
||||
self.keyframe(k);
|
||||
}
|
||||
self.opt("expr", expr.as_ref(), |t, e| {
|
||||
let Expression { text, enabled } = e;
|
||||
t.str("text", text);
|
||||
t.field("enabled", enabled);
|
||||
});
|
||||
}
|
||||
|
||||
fn keyframe(&mut self, k: &Keyframe) {
|
||||
// A key's colour label only shows it in the UI.
|
||||
let Keyframe {
|
||||
time,
|
||||
value,
|
||||
in_interp,
|
||||
out_interp,
|
||||
in_ease,
|
||||
out_ease,
|
||||
continuous,
|
||||
auto_bezier,
|
||||
spatial_in,
|
||||
spatial_out,
|
||||
spatial_auto,
|
||||
spatial_continuous,
|
||||
roving,
|
||||
label: _,
|
||||
muted,
|
||||
} = k;
|
||||
self.tick("key", *time);
|
||||
self.value(value);
|
||||
self.field("interp", format_args!("{}/{}", interp(*in_interp), interp(*out_interp)));
|
||||
for (side, eases) in [("inEase", in_ease), ("outEase", out_ease)] {
|
||||
for e in eases {
|
||||
let Ease { speed, influence } = e;
|
||||
self.nums(side, &[*speed, *influence]);
|
||||
}
|
||||
}
|
||||
self.field("continuous", continuous);
|
||||
self.field("autoBezier", auto_bezier);
|
||||
self.nums("spatialIn", spatial_in);
|
||||
self.nums("spatialOut", spatial_out);
|
||||
self.field("spatialAuto", spatial_auto);
|
||||
self.field("spatialContinuous", spatial_continuous);
|
||||
self.field("roving", roving);
|
||||
self.field("muted", muted);
|
||||
}
|
||||
|
||||
fn value(&mut self, v: &Value) {
|
||||
match v {
|
||||
Value::Scalar(x) => self.num("scalar", *x),
|
||||
Value::Vec2(x) => self.nums("vec2", x),
|
||||
Value::Vec3(x) => self.nums("vec3", x),
|
||||
Value::Color(x) => self.nums("color", x),
|
||||
Value::Bool(b) => self.field("bool", b),
|
||||
Value::Enum(i) => self.field("enum", i),
|
||||
Value::Path(p) => self.shape_path(p),
|
||||
// A text document has dozens of fields and no place in what a key covers today (a
|
||||
// text layer's Source Text is not under its masks or effects): its project-file form.
|
||||
Value::Text(d) => self.str("text", &serde_json::to_string(d).unwrap_or_default()),
|
||||
Value::Layer(l) => self.opt("layer", l.as_ref(), |t, id| t.field("id", id)),
|
||||
Value::Gradient(g) => {
|
||||
let Gradient { colors, opacities } = g;
|
||||
self.word("gradient");
|
||||
for (at, c) in colors {
|
||||
self.num("stop", *at);
|
||||
self.floats("rgba", c);
|
||||
}
|
||||
for (at, o) in opacities {
|
||||
self.num("stop", *at);
|
||||
self.floats("opacity", &[*o]);
|
||||
}
|
||||
}
|
||||
Value::Str(s) => self.str("str", s),
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_path(&mut self, p: &ShapePath) {
|
||||
let ShapePath { vertices, in_tangents, out_tangents, closed, feather } = p;
|
||||
self.word("path");
|
||||
for (name, points) in [("v", vertices), ("in", in_tangents), ("out", out_tangents)] {
|
||||
for pt in points {
|
||||
self.nums(name, pt);
|
||||
}
|
||||
}
|
||||
self.field("closed", closed);
|
||||
for f in feather {
|
||||
let FeatherPoint { segment, t, radius, tension } = f;
|
||||
self.field("featherSegment", segment);
|
||||
self.nums("feather", &[*t, *radius, *tension]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn interp(i: Interp) -> &'static str {
|
||||
match i {
|
||||
Interp::Linear => "linear",
|
||||
Interp::Bezier => "bezier",
|
||||
Interp::Hold => "hold",
|
||||
}
|
||||
}
|
||||
|
||||
fn color_space(c: ColorSpace) -> &'static str {
|
||||
match c {
|
||||
ColorSpace::Srgb => "srgb",
|
||||
ColorSpace::Rec709 => "rec709",
|
||||
ColorSpace::Rec2020 => "rec2020",
|
||||
ColorSpace::DisplayP3 => "p3",
|
||||
ColorSpace::AcesCg => "acescg",
|
||||
ColorSpace::Aces2065 => "aces2065",
|
||||
ColorSpace::Rec2100Pq => "rec2100pq",
|
||||
ColorSpace::Rec2100Hlg => "rec2100hlg",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Signatures as 0.22–0.24 wrote them, to recognise the keys those releases saved. Nothing new is
|
||||
//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys
|
||||
//! those releases saved: if a type change alters this text, write that part out here.
|
||||
|
||||
use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid};
|
||||
|
||||
use super::fnv;
|
||||
|
||||
/// The signatures a saved key of `layer` may have been made from. The footage's availability is
|
||||
/// tried both ways: those releases hashed it, though it isn't part of the footage (#3534). Before
|
||||
/// `Footage::placed_page` was added in 0.23, the footage text ended without that field.
|
||||
pub(crate) fn signatures(p: &Project, comp: ItemId, layer: &Layer) -> Vec<String> {
|
||||
let src = match &layer.source {
|
||||
LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => {
|
||||
let mut out = Vec::with_capacity(4);
|
||||
for missing in [false, true] {
|
||||
out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, true)));
|
||||
if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page {
|
||||
out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, false)));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Some(ItemKind::Solid(s)) => format!("{s:?}"),
|
||||
Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration),
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
};
|
||||
vec![signature_with_source(p, comp, layer, &src)]
|
||||
}
|
||||
|
||||
/// A Roto Brush Input Key as 0.22–0.24 made it from a [`signatures`] entry.
|
||||
pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String {
|
||||
if let Some(m) = layer.masks() {
|
||||
s.push_str(&format!("{m:?}"));
|
||||
}
|
||||
if let Some(fx) = layer.effects() {
|
||||
for g in fx.groups() {
|
||||
if g.uid == uid {
|
||||
break;
|
||||
}
|
||||
s.push_str(&format!("{g:?}"));
|
||||
}
|
||||
}
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
|
||||
/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23),
|
||||
/// with `missing` in place of the item's.
|
||||
pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String {
|
||||
format!("{:?}", FootageText { f, missing, placed_page })
|
||||
}
|
||||
|
||||
struct FootageText<'a> {
|
||||
f: &'a Footage,
|
||||
missing: bool,
|
||||
placed_page: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FootageText<'_> {
|
||||
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Every field is named so that a new one doesn't compile until it is decided here: a new
|
||||
// field was never in these keys, so it stays out.
|
||||
let Footage {
|
||||
path,
|
||||
kind,
|
||||
width,
|
||||
height,
|
||||
pixel_aspect,
|
||||
frame_rate,
|
||||
native_rate,
|
||||
duration,
|
||||
has_video,
|
||||
has_audio,
|
||||
alpha,
|
||||
premul_color,
|
||||
loop_count,
|
||||
codec,
|
||||
missing: _,
|
||||
sequence,
|
||||
color_profile,
|
||||
layer,
|
||||
fields,
|
||||
invert_alpha,
|
||||
linear_light,
|
||||
preserve_rgb,
|
||||
cineon,
|
||||
data,
|
||||
page,
|
||||
alphabetical,
|
||||
start_timecode,
|
||||
file_timecode,
|
||||
markers,
|
||||
placed_page,
|
||||
} = self.f;
|
||||
let mut d = out.debug_struct("Footage");
|
||||
d.field("path", path)
|
||||
.field("kind", kind)
|
||||
.field("width", width)
|
||||
.field("height", height)
|
||||
.field("pixel_aspect", pixel_aspect)
|
||||
.field("frame_rate", frame_rate)
|
||||
.field("native_rate", native_rate)
|
||||
.field("duration", duration)
|
||||
.field("has_video", has_video)
|
||||
.field("has_audio", has_audio)
|
||||
.field("alpha", alpha)
|
||||
.field("premul_color", premul_color)
|
||||
.field("loop_count", loop_count)
|
||||
.field("codec", codec)
|
||||
.field("missing", &self.missing)
|
||||
.field("sequence", sequence)
|
||||
.field("color_profile", color_profile)
|
||||
.field("layer", layer)
|
||||
.field("fields", fields)
|
||||
.field("invert_alpha", invert_alpha)
|
||||
.field("linear_light", linear_light)
|
||||
.field("preserve_rgb", preserve_rgb)
|
||||
.field("cineon", cineon)
|
||||
.field("data", data)
|
||||
.field("page", page)
|
||||
.field("alphabetical", alphabetical)
|
||||
.field("start_timecode", start_timecode)
|
||||
.field("file_timecode", file_timecode)
|
||||
.field("markers", markers);
|
||||
if self.placed_page {
|
||||
d.field("placed_page", placed_page);
|
||||
}
|
||||
d.finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String {
|
||||
let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default();
|
||||
let s = format!(
|
||||
"{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}",
|
||||
layer.source,
|
||||
layer.in_point,
|
||||
layer.out_point,
|
||||
layer.start_time,
|
||||
layer.stretch,
|
||||
layer.props.get("timeRemap")
|
||||
);
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
@@ -8,8 +8,8 @@
|
||||
//! (`Renderer::layer_input`, source → masks → the effects above it). `roto.freeze` runs the same
|
||||
//! pass and stores the final mattes in the effect (one undo step). `sync`, run after every
|
||||
//! 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.
|
||||
//! of (the layer's source and timing, its masks and the effects above it: `analysis::frames_key`),
|
||||
//! and drops frozen mattes made from other frames. Footage going offline keeps them.
|
||||
//!
|
||||
//! Object Matte instances run through the same jobs (`objectMatte.propagate` / `.freeze`): the
|
||||
//! frames are [`om::job_frames`] around the reference frame, each segmented through
|
||||
@@ -31,6 +31,7 @@ use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpt
|
||||
use effectcraft_time::Tick;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::analysis::frames_key::{self, Era};
|
||||
use crate::tracking::lock;
|
||||
use crate::{Event, Session};
|
||||
|
||||
@@ -207,40 +208,10 @@ fn set_str(g: &mut PropGroup, m: &str, v: String) {
|
||||
}
|
||||
}
|
||||
|
||||
fn fnv(s: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in s.as_bytes() {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// What the effect's input frames are made of: the layer's source and timing, its masks and the
|
||||
/// effects above the Roto Brush.
|
||||
pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
input_key_with_signature(crate::warp::signature(p, comp, layer), layer, uid)
|
||||
}
|
||||
|
||||
/// Recognize the input key serialized before 0.23 without re-keying its frozen matte.
|
||||
fn input_key_before_placed_page(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> Option<String> {
|
||||
let signature = crate::warp::signature_before_placed_page(p, comp, layer)?;
|
||||
Some(input_key_with_signature(signature, layer, uid))
|
||||
}
|
||||
|
||||
fn input_key_with_signature(mut s: String, layer: &Layer, uid: Uid) -> String {
|
||||
if let Some(m) = layer.masks() {
|
||||
s.push_str(&format!("{m:?}"));
|
||||
}
|
||||
if let Some(fx) = layer.effects() {
|
||||
for g in fx.groups() {
|
||||
if g.uid == uid {
|
||||
break;
|
||||
}
|
||||
s.push_str(&format!("{g:?}"));
|
||||
}
|
||||
}
|
||||
format!("{:016x}", fnv(&s))
|
||||
frames_key::input_key(p, comp, layer, uid)
|
||||
}
|
||||
|
||||
/// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from
|
||||
@@ -258,7 +229,11 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI
|
||||
let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid));
|
||||
let saved_key = str_of(g, INPUT_KEY);
|
||||
// Keep a matching old key: the frozen cache itself also hashes that key.
|
||||
if saved_key != key && input_key_before_placed_page(after, *cid, l, g.uid).as_deref() != Some(saved_key.as_str()) {
|
||||
let key_of = |s, era| match era {
|
||||
Era::Current => frames_key::input_key_of(s, l, g.uid),
|
||||
Era::Legacy => frames_key::legacy::input_key_of(s, l, g.uid),
|
||||
};
|
||||
if !frames_key::key_matches(after, *cid, l, &saved_key, key_of) {
|
||||
set.push((*cid, l.id, g.uid, key));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if old.is_none_or(|o| guard_of(o) != guard_of(g)) {
|
||||
|
||||
@@ -6,10 +6,11 @@
|
||||
//! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the
|
||||
//! stabilization plan once to validate and cache the result. When the job finishes, the analysis is
|
||||
//! written into the effect's hidden Analysis parameter as one undo step, together with a key of
|
||||
//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap). Edits that
|
||||
//! change those clear the analysis (`invalidate`, run after every edit) and queue the effect
|
||||
//! for re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses
|
||||
//! automatically too).
|
||||
//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap, its masks, the
|
||||
//! effects above the Warp Stabilizer and a precomp's contents: `analysis::frames_key::analysis_key`,
|
||||
//! shared with the 3D Camera Tracker). Edits that change those clear the analysis (`invalidate`, run after every edit) and queue the effect for
|
||||
//! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses
|
||||
//! automatically too). Footage going offline is not such a change.
|
||||
|
||||
use crate::offload::{JobKind, rate};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -17,13 +18,14 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid};
|
||||
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, WarpAnalysis};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::analysis::frames_key;
|
||||
use crate::tracking::lock;
|
||||
use crate::{Event, Session};
|
||||
|
||||
@@ -69,7 +71,7 @@ pub struct WarpJob {
|
||||
pub comp: ItemId,
|
||||
pub layer: LayerId,
|
||||
pub effect: Uid,
|
||||
/// The layer signature the analysis is made from.
|
||||
/// What the analysis is made from (`frames_key::analysis_key`).
|
||||
key: String,
|
||||
}
|
||||
|
||||
@@ -98,54 +100,6 @@ pub(crate) struct WarpWork {
|
||||
pub times: Vec<Tick>,
|
||||
}
|
||||
|
||||
fn fnv(s: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in s.as_bytes() {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// What an analysis of `layer` depends on (its frames): source (and the footage item's
|
||||
/// interpretation), In/Out, start time, stretch, Time Remap and the comp frame rate.
|
||||
pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String {
|
||||
let src = match &layer.source {
|
||||
LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => format!("{f:?}"),
|
||||
Some(ItemKind::Solid(s)) => format!("{s:?}"),
|
||||
Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration),
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
};
|
||||
signature_with_source(p, comp, layer, &src)
|
||||
}
|
||||
|
||||
/// Before `Footage::placed_page` was added in 0.23, the persisted signature hashed the
|
||||
/// same Debug representation without that last field. Only ordinary footage can match it.
|
||||
pub(crate) fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option<String> {
|
||||
let LayerSource::Footage { item } = &layer.source else { return None };
|
||||
let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None };
|
||||
let src = format!("{footage:?}");
|
||||
let old = src.strip_suffix(", placed_page: false }")?;
|
||||
Some(signature_with_source(p, comp, layer, &format!("{old} }}")))
|
||||
}
|
||||
|
||||
fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String {
|
||||
let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default();
|
||||
let s = format!(
|
||||
"{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}",
|
||||
layer.source,
|
||||
layer.in_point,
|
||||
layer.out_point,
|
||||
layer.start_time,
|
||||
layer.stretch,
|
||||
layer.props.get("timeRemap")
|
||||
);
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
|
||||
fn is_warp(g: &PropGroup) -> bool {
|
||||
matches!(&g.kind, GroupKind::Effect { effect } if effect == warp_stab::ID)
|
||||
}
|
||||
@@ -169,11 +123,10 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId,
|
||||
if !fx.groups().any(is_warp) {
|
||||
continue;
|
||||
}
|
||||
let sig = signature(after, *cid, l);
|
||||
let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id));
|
||||
for g in fx.groups().filter(|g| is_warp(g)) {
|
||||
let analysed = !str_of(g, ANALYSIS).is_empty();
|
||||
if analysed && str_of(g, ANALYSIS_KEY) != sig {
|
||||
if analysed && !frames_key::analysis_key_matches(before, after, *cid, l, g.uid, &str_of(g, ANALYSIS_KEY), |k| k) {
|
||||
clear.push((*cid, l.id, g.uid));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() {
|
||||
@@ -352,7 +305,7 @@ impl Session {
|
||||
detailed,
|
||||
times,
|
||||
};
|
||||
let key = signature(&self.project, comp, l);
|
||||
let key = frames_key::analysis_key(&self.project, comp, l, effect);
|
||||
if !wait && self.offloads() {
|
||||
drop(work);
|
||||
self.offload_analysis(crate::offload::WorkerJob::Warp { comp, layer, effect })?;
|
||||
|
||||
@@ -49,7 +49,7 @@ mod nav_more;
|
||||
pub mod paint;
|
||||
pub mod panels_cmds;
|
||||
pub(crate) mod path_nulls;
|
||||
mod paths;
|
||||
pub(crate) mod paths;
|
||||
mod project_items;
|
||||
pub(crate) mod prop;
|
||||
mod prop_groups;
|
||||
|
||||
@@ -319,15 +319,19 @@ impl Prober {
|
||||
return f.map(|footage| Probed { name, footage, ask_alpha: false, warning: None }).map_err(fail);
|
||||
}
|
||||
let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?;
|
||||
let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?;
|
||||
let mut warning = None;
|
||||
// What the file's own import left out (a model's textures over the limits) is a warning too.
|
||||
let (mut f, mut warning) = match src {
|
||||
Source::File(_) => importer.probe_noting(path).map_err(fail)?,
|
||||
_ => (crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?, None),
|
||||
};
|
||||
// Settings ▸ Import ▸ Report Missing Frames (numbered sequences).
|
||||
if f.kind == FootageKind::Sequence
|
||||
&& !f.alphabetical
|
||||
&& self.report_missing_frames
|
||||
&& let Some(gaps) = crate::sequence::missing_report(&f.sequence)
|
||||
{
|
||||
warning = Some(format!("{name}: {gaps} (the previous frame is held)"));
|
||||
let gaps = format!("{name}: {gaps} (the previous frame is held)");
|
||||
warning = Some(warning.map_or(gaps.clone(), |w| format!("{w}; {gaps}")));
|
||||
}
|
||||
// Settings ▸ Import ▸ Interpret Unlabeled Alpha As: images only (a 3D model renders its
|
||||
// own alpha, and audio and data have none).
|
||||
|
||||
@@ -762,7 +762,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("mask.new", "New Mask from Points", [], None, "{layer?, vertices: [[x,y]…], inTangents?, outTangents?, closed?, mode?}", has_layers, new_mask),
|
||||
cmd!("mask.addVertex", "Add Mask Vertex", [], None, "{layer?, mask, point: [x,y], in?, out?, index?}", has_layers, add_vertex),
|
||||
cmd!("mask.setVertex", "Set Mask Vertex", [], None, "{layer?, mask, index, point?, in?, out?, merge?}", has_layers, set_vertex),
|
||||
cmd!("mask.setClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{layer?, mask, closed?}", has_layers, set_closed),
|
||||
cmd!("mask.setClosed", "Closed", [], None, "{layer?, mask, closed?}", has_layers, set_closed),
|
||||
cmd!("mask.setRoundness", "Set Mask Roundness", [], None, "{layer?, mask, roundness (corner radius in px; 0 = square)}", has_layers, set_roundness),
|
||||
cmd!("mask.selectVertices", "Select Mask Vertices", [], None, "{vertices: [{layer, mask, index}], add?, toggle?}", has_comp, select_vertices),
|
||||
cmd!("mask.moveVertices", "Move Mask Vertices", [], None, "{vertices?: [{layer, mask, index}], delta: [dx,dy], merge?}", has_vertices, move_vertices),
|
||||
|
||||
@@ -12,6 +12,9 @@ use super::layer_menu::target_masks;
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_comp, has_layers, layer_mut, layer_p, merge_p, str_p};
|
||||
use crate::{EngineError, Result, Session, VertexRef, cmd};
|
||||
|
||||
mod closed;
|
||||
pub(crate) use closed::selected_paths_closed;
|
||||
|
||||
// ---------------------------------------------------------------- RotoBezier
|
||||
|
||||
/// Automatic (RotoBezier) tangents: each vertex's tangents follow the line through its
|
||||
@@ -547,6 +550,7 @@ fn ungroup_shapes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("path.toggleClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{}", closed::has_paths, closed::toggle_closed),
|
||||
cmd!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?, value?}", has_layers, roto_bezier),
|
||||
cmd!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?}", has_layers, convert_to_bezier),
|
||||
cmd!("path.groupShapes", "Group Shapes", ["Layer"], Some("Cmd+G"), "{layer?, items?: [uid]}", has_shape_items, group_shapes),
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! The selection-aware Closed menu action. Explicit edits retain `mask.setClosed`'s API.
|
||||
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::{GroupKind, Layer, LayerId, Node, PropGroup, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::{bad, layer_mut};
|
||||
use crate::{EngineError, Result, Session, VertexRef};
|
||||
|
||||
const MAX_DEPTH: usize = 128;
|
||||
|
||||
struct Target {
|
||||
layer: LayerId,
|
||||
route: Vec<usize>,
|
||||
closed: bool,
|
||||
editable: bool,
|
||||
}
|
||||
|
||||
struct Selection<'a> {
|
||||
vertices: &'a [VertexRef],
|
||||
props: &'a [(LayerId, Uid)],
|
||||
time: Tick,
|
||||
}
|
||||
|
||||
/// A route uses checked child access and never recurses through an input-controlled tree.
|
||||
fn group_at_mut<'a>(mut group: &'a mut PropGroup, route: &[usize]) -> Option<&'a mut PropGroup> {
|
||||
for &index in route {
|
||||
group = group.children.get_mut(index)?.as_group_mut()?;
|
||||
}
|
||||
Some(group)
|
||||
}
|
||||
|
||||
/// The selected paths on the selected layers, else every path of those layers (as the other
|
||||
/// Mask and Shape Path commands do). Locked layers and masks count as matches, so selecting one
|
||||
/// never falls back to its siblings, and are then left out.
|
||||
fn targets(s: &Session) -> Result<Vec<Target>> {
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let selection = Selection { vertices: &s.state.selected_vertices, props: &s.state.selected_props, time: s.time() };
|
||||
let mut targets = Vec::new();
|
||||
for whole_layers in [false, true] {
|
||||
// Only selected layers: navigation and insertion can retain point/property selections
|
||||
// on other layers, and every match below is per layer.
|
||||
for layer in comp.layers.iter().filter(|l| s.state.selected_layers.contains(&l.id)) {
|
||||
collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, layer.switches.locked, &mut targets)?;
|
||||
}
|
||||
if !targets.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
targets.retain(|target| target.editable);
|
||||
if targets.is_empty() {
|
||||
return Err(bad("path.toggleClosed", "select an unlocked mask or Bezier shape path"));
|
||||
}
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
fn collect(
|
||||
selection: &Selection,
|
||||
layer: &Layer,
|
||||
group: &PropGroup,
|
||||
route: &mut Vec<usize>,
|
||||
inherited: bool,
|
||||
locked: bool,
|
||||
targets: &mut Vec<Target>,
|
||||
) -> Result<()> {
|
||||
if route.len() > MAX_DEPTH {
|
||||
return Err(bad("path.toggleClosed", "path group nesting exceeds 128 levels"));
|
||||
}
|
||||
let locked = locked || matches!(group.kind, GroupKind::Mask { locked: true, .. });
|
||||
let selected = inherited || selection.props.contains(&(layer.id, group.uid));
|
||||
if super::super::mask::is_path_group(group)
|
||||
&& let Some(prop) = group.get("path")
|
||||
&& let KV::Path(path) = prop.value_at(layer.layer_time(selection.time))
|
||||
{
|
||||
// Selecting any of a path group's properties (Mask Path, Feather, Opacity…) or its points
|
||||
// selects the path.
|
||||
let selected = selected
|
||||
|| group.children.iter().any(|c| matches!(c, Node::Prop(p) if selection.props.contains(&(layer.id, p.uid))))
|
||||
|| selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len());
|
||||
if selected {
|
||||
targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed, editable: !locked });
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for (index, child) in group.children.iter().enumerate() {
|
||||
let Some(child) = child.as_group() else { continue };
|
||||
route.push(index);
|
||||
collect(selection, layer, child, route, selected, locked, targets)?;
|
||||
route.pop();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn selected_paths_closed(s: &Session) -> Option<bool> {
|
||||
targets(s).ok().map(|targets| targets.iter().all(|target| target.closed))
|
||||
}
|
||||
|
||||
pub(super) fn has_paths(s: &Session) -> std::result::Result<(), String> {
|
||||
targets(s).map(|_| ()).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn toggle_closed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let targets = targets(s)?;
|
||||
let closed = !targets.iter().all(|target| target.closed);
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let time = s.time();
|
||||
s.edit("Closed", None, |project, _| {
|
||||
for target in &targets {
|
||||
let layer = layer_mut(project, cid, target.layer)?;
|
||||
let time = layer.layer_time(time);
|
||||
let group = group_at_mut(&mut layer.props, &target.route).ok_or_else(|| bad("path.toggleClosed", "the selected path no longer exists"))?;
|
||||
let roto = super::is_roto(group);
|
||||
let prop = group.get_mut("path").ok_or_else(|| bad("path.toggleClosed", "the selected group has no path"))?;
|
||||
let KV::Path(mut path) = prop.value_at(time) else { return Err(bad("path.toggleClosed", "the selected value is not a path")) };
|
||||
if path.closed == closed {
|
||||
continue;
|
||||
}
|
||||
// As `mask.setClosed`: a path read from a file may have fewer tangents than vertices (#1250).
|
||||
path.fit_tangents();
|
||||
path.closed = closed;
|
||||
if roto {
|
||||
super::roto_smooth(&mut path);
|
||||
}
|
||||
prop.set_value_at(time, KV::Path(path));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"paths": targets.len(), "closed": closed}))
|
||||
}
|
||||
@@ -1370,6 +1370,13 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sel.is_empty() {
|
||||
return Err(bad(CMD, "no `path` given and no selected property has an expression"));
|
||||
}
|
||||
// Every layer is checked before the first is converted: a refusal leaves them all as they were.
|
||||
let step = comp.frame_duration().0;
|
||||
for (lid, _) in &sel {
|
||||
if let Some(l) = comp.layer(*lid) {
|
||||
check_convertible(step, l)?;
|
||||
}
|
||||
}
|
||||
let mut n = 0;
|
||||
for (lid, uid) in sel {
|
||||
n += convert_one_expr(s, cid, lid, uid)?.as_u64().unwrap_or(0);
|
||||
@@ -1380,14 +1387,36 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
convert_one_expr(s, cid, lid, uid)
|
||||
}
|
||||
|
||||
/// Most keyframes Convert Expression to Keyframes makes: 2^20, 4.8 hours at 60 fps (After Effects
|
||||
/// compositions run to 3 hours, 648,000 frames at 60 fps).
|
||||
const MAX_CONVERTED_KEYS: u64 = 1 << 20;
|
||||
const _: () = assert!(MAX_CONVERTED_KEYS >= 3 * 3600 * 60);
|
||||
|
||||
/// One evaluation and one key per frame of the layer: its In and Out points and the composition's
|
||||
/// frame duration are saved data, so the step must advance and the count (a partial last frame
|
||||
/// rounded up, as the loop steps, in 128 bits) is checked before any key is made.
|
||||
fn check_convertible(step: i64, layer: &Layer) -> Result<()> {
|
||||
const CMD: &str = "prop.convertExpressionToKeyframes";
|
||||
if step <= 0 {
|
||||
return Err(bad(CMD, "the composition's frame duration is not positive"));
|
||||
}
|
||||
let (step, span) = (i128::from(step), i128::from(layer.out_point.0) - i128::from(layer.in_point.0));
|
||||
let frames = if span > 0 { (span + step - 1) / step } else { 0 };
|
||||
if frames > i128::from(MAX_CONVERTED_KEYS) {
|
||||
return Err(bad(CMD, format!("the layer spans {frames} frames; at most {MAX_CONVERTED_KEYS} are converted")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces the expression on one property with keyframes sampled from its evaluated values.
|
||||
/// Returns the number of properties converted.
|
||||
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();
|
||||
let mut keys = vec![];
|
||||
let fd = comp.frame_duration();
|
||||
check_convertible(fd.0, &layer)?;
|
||||
let mut keys = vec![];
|
||||
let mut t = layer.in_point;
|
||||
while t < layer.out_point {
|
||||
let ctx = effectcraft_render::EvalCtx {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod doc_path;
|
||||
pub mod footage_check;
|
||||
pub mod footage_reload;
|
||||
pub mod lut_reload;
|
||||
pub mod media_browser;
|
||||
pub mod media_cache;
|
||||
pub mod sequence;
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! LUT files that change on disk (#3493).
|
||||
//!
|
||||
//! A render follows a LUT file by itself: [`effectcraft_effects::load_lut`] stamps the file and
|
||||
//! reads it again once it changed, and a layer's cache key holds the stamp. What the desktop app
|
||||
//! keeps of earlier renders, the frames of its viewer and RAM preview, is dropped when
|
||||
//! [`effectcraft_effects::lut_generation`] moves. The [`Watcher`] looks at the LUT files in use
|
||||
//! every two seconds, so an edit shows without anything rendering first, and wakes the interface
|
||||
//! only when one changed.
|
||||
|
||||
use std::sync::mpsc::{RecvTimeoutError, SyncSender};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Moves each time a LUT file in use was found changed on disk: frames rendered before may show
|
||||
/// the old LUT ([`effectcraft_effects::lut_generation`]).
|
||||
pub fn generation() -> u64 {
|
||||
effectcraft_effects::lut_generation()
|
||||
}
|
||||
|
||||
/// Stamp the LUT files in use now ([`effectcraft_effects::check_lut_files`]): the ones that
|
||||
/// changed are read again by the next render. Returns [`generation`].
|
||||
pub fn check() -> u64 {
|
||||
effectcraft_effects::check_lut_files()
|
||||
}
|
||||
|
||||
/// How often the LUT files in use are stamped.
|
||||
pub const INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// A worker thread that stamps the LUT files in use ([`effectcraft_effects::check_lut_files`])
|
||||
/// and runs `wake` when one changed. Dropping the watcher ends the thread.
|
||||
pub struct Watcher {
|
||||
_stop: SyncSender<()>,
|
||||
}
|
||||
|
||||
impl Watcher {
|
||||
/// Start the worker. `None` where there are no threads (the web app, whose LUTs don't come
|
||||
/// from files) or one couldn't be started.
|
||||
pub fn start(wake: impl Fn() + Send + 'static) -> Option<Watcher> {
|
||||
Self::start_with(wake, INTERVAL)
|
||||
}
|
||||
|
||||
/// [`Watcher::start`] stamping every `every` (tests).
|
||||
pub fn start_with(wake: impl Fn() + Send + 'static, every: Duration) -> Option<Watcher> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel::<()>(1);
|
||||
std::thread::Builder::new()
|
||||
.name("lut-watch".into())
|
||||
.spawn(move || {
|
||||
let mut seen = effectcraft_effects::lut_generation();
|
||||
// (ends once the watcher, the only sender, is dropped)
|
||||
while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(every) {
|
||||
let now = check();
|
||||
if now != seen {
|
||||
seen = now;
|
||||
wake();
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok()?;
|
||||
Some(Watcher { _stop: tx })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A LUT file edited on disk wakes the interface without a render loading it.
|
||||
#[test]
|
||||
fn an_edited_lut_file_wakes_the_interface() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("watched.cube");
|
||||
std::fs::write(&path, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
|
||||
let src = path.to_string_lossy().into_owned();
|
||||
assert!(effectcraft_effects::load_lut(&src).is_some());
|
||||
let before = effectcraft_effects::lut_generation();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let _watcher = Watcher::start_with(
|
||||
move || {
|
||||
let _ = tx.send(());
|
||||
},
|
||||
Duration::from_millis(10),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(&path, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap();
|
||||
rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
assert!(effectcraft_effects::lut_generation() > before);
|
||||
}
|
||||
}
|
||||
@@ -273,6 +273,7 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[
|
||||
("ec.distort.wavewarp", "width", "percent"),
|
||||
("ec.distort.wavewarp", "speed", "pixels"),
|
||||
("ec.generate.fourcolor", "blend", "percent"),
|
||||
("ec.generate.fourcolor", "jitter", "percent"),
|
||||
("ec.generate.advancedlightning", "coreSettings/coreRadius", ""),
|
||||
("ec.generate.advancedlightning", "glowSettings/glowRadius", "percent"),
|
||||
("ec.generate.advancedlightning", "alphaObstacle", "pixels"),
|
||||
@@ -317,6 +318,15 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[
|
||||
("ec.matte.rotobrush", "refineEdgeMatte/shiftEdge", "percent"),
|
||||
("ec.matte.rotobrush", "refineEdgeMatte/decontamination/increaseDecontaminationRadius", ""),
|
||||
("ec.matte.simplechoker", "chokeMatte", "pixels"),
|
||||
// Their ranges were 0..100 (#3483, #3484).
|
||||
("ec.noise.noisehls", "hue", "percent"),
|
||||
("ec.noise.noisehls", "lightness", "percent"),
|
||||
("ec.noise.noisehls", "saturation", "percent"),
|
||||
("ec.noise.noisehls", "grainSize", ""),
|
||||
("ec.noise.noisehlsauto", "hue", "percent"),
|
||||
("ec.noise.noisehlsauto", "lightness", "percent"),
|
||||
("ec.noise.noisehlsauto", "saturation", "percent"),
|
||||
("ec.noise.noisehlsauto", "grainSize", ""),
|
||||
("ec.noise.fractal", "transform/scale", "percent"),
|
||||
("ec.noise.fractal", "transform/scaleWidth", "percent"),
|
||||
("ec.noise.fractal", "transform/scaleHeight", "percent"),
|
||||
|
||||
@@ -8,6 +8,7 @@ use effectcraft_project::{Comp, ItemId, Layer, LayerSource, MaskMode, Project, P
|
||||
use effectcraft_svg::{Affine, Doc, Geom, GradientKind, Node, Paint};
|
||||
use kurbo::{BezPath, Point};
|
||||
|
||||
/// Convert a kurbo path into shape path property groups.
|
||||
fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec<PropGroup> {
|
||||
effectcraft_path::from_kurbo(path)
|
||||
.into_iter()
|
||||
@@ -20,6 +21,7 @@ fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec<PropGroup> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Uniform scale factor of a transform (square root of its determinant magnitude).
|
||||
fn det_scale(m: Affine) -> f64 {
|
||||
let c = m.as_coeffs();
|
||||
(c[0] * c[3] - c[1] * c[2]).abs().sqrt()
|
||||
@@ -31,6 +33,7 @@ fn axis_aligned(m: Affine) -> Option<(f64, f64, f64, f64)> {
|
||||
(c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && c[0] > 0.0 && c[3] > 0.0).then_some((c[0], c[3], c[4], c[5]))
|
||||
}
|
||||
|
||||
/// Convert an SVG gradient into the engine's gradient value.
|
||||
fn gradient_value(g: &effectcraft_svg::Gradient) -> Gradient {
|
||||
Gradient {
|
||||
colors: g.stops.iter().map(|(o, c)| (*o, [c[0] as f32, c[1] as f32, c[2] as f32, 1.0])).collect(),
|
||||
@@ -52,6 +55,7 @@ fn gradient_points(g: &effectcraft_svg::Gradient, m: Affine, bbox: kurbo::Rect)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert one SVG shape under transform `m` into shape-layer items.
|
||||
fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec<PropGroup> {
|
||||
use kurbo::Shape as _;
|
||||
let mut items = vec![];
|
||||
@@ -72,48 +76,60 @@ fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec<Prop
|
||||
let bbox = s.geom.to_path().bounding_box();
|
||||
if let Some(st) = &s.stroke {
|
||||
let width = st.width * det_scale(m);
|
||||
let mut g = match &st.paint {
|
||||
Paint::Color(c) => build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width),
|
||||
let paint = match &st.paint {
|
||||
Paint::Color(c) => Some(build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width)),
|
||||
Paint::Gradient(gr) => {
|
||||
let (radial, a, b) = gradient_points(gr, m, bbox);
|
||||
build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width)
|
||||
Some(build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width))
|
||||
}
|
||||
// Editable shape layers do not yet have a pattern paint operator. Keep the geometry
|
||||
// and any retained fallback as solid paint; SVG footage retains the rasterised pattern.
|
||||
Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_stroke(ids, [c[0], c[1], c[2], c[3]], width)),
|
||||
};
|
||||
set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0));
|
||||
set(&mut g, "cap", Value::Enum(st.cap as u32));
|
||||
set(&mut g, "join", Value::Enum(st.join as u32));
|
||||
set(&mut g, "miter", Value::Scalar(st.miter));
|
||||
if let Some((d, off)) = &st.dash
|
||||
&& let Some(dg) = g.sub_mut("dashes")
|
||||
{
|
||||
let k = det_scale(m);
|
||||
set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k));
|
||||
set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k));
|
||||
set(dg, "offset", Value::Scalar(off * k));
|
||||
if let Some(mut g) = paint {
|
||||
set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0));
|
||||
set(&mut g, "cap", Value::Enum(st.cap as u32));
|
||||
set(&mut g, "join", Value::Enum(st.join as u32));
|
||||
set(&mut g, "miter", Value::Scalar(st.miter));
|
||||
if let Some((d, off)) = &st.dash
|
||||
&& let Some(dg) = g.sub_mut("dashes")
|
||||
{
|
||||
let k = det_scale(m);
|
||||
set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k));
|
||||
set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k));
|
||||
set(dg, "offset", Value::Scalar(off * k));
|
||||
}
|
||||
items.push(g);
|
||||
}
|
||||
items.push(g);
|
||||
}
|
||||
if let Some(f) = &s.fill {
|
||||
let mut g = match f {
|
||||
Paint::Color(c) => build::shape_fill(ids, [c[0], c[1], c[2], 1.0]),
|
||||
let paint = match f {
|
||||
Paint::Color(c) => Some(build::shape_fill(ids, [c[0], c[1], c[2], 1.0])),
|
||||
Paint::Gradient(gr) => {
|
||||
let (radial, a, b) = gradient_points(gr, m, bbox);
|
||||
build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr))
|
||||
Some(build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr)))
|
||||
}
|
||||
// Pattern artwork is preserved in rasterised SVG footage; editable shapes keep only
|
||||
// any retained fallback as solid paint.
|
||||
Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_fill(ids, [c[0], c[1], c[2], c[3]])),
|
||||
};
|
||||
set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0));
|
||||
set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd)));
|
||||
items.push(g);
|
||||
if let Some(mut g) = paint {
|
||||
set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0));
|
||||
set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd)));
|
||||
items.push(g);
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// Set a child property's value if present.
|
||||
fn set(g: &mut PropGroup, k: &str, v: Value) {
|
||||
if let Some(p) = g.get_mut(k) {
|
||||
p.value = v;
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap items in a named shape group with the given opacity (0..1).
|
||||
fn group(ids: &mut Ids, name: &str, items: Vec<PropGroup>, opacity: f64) -> PropGroup {
|
||||
let mut g = build::shape_group(ids, name, items);
|
||||
if let Some(p) = g.prop_mut("transform/opacity") {
|
||||
@@ -165,6 +181,7 @@ fn clipped_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine, clips: &[
|
||||
/// [`shapes_from_vector`]). Images are skipped (Layer ▸ Create makes them footage layers, see
|
||||
/// [`split_at_images`]); soft masks are not converted.
|
||||
pub fn svg_contents(ids: &mut Ids, doc: &Doc) -> Vec<PropGroup> {
|
||||
/// Convert nodes to property groups, applying transform `m` and clip paths.
|
||||
fn walk(ids: &mut Ids, nodes: &[Node], m: Affine, clips: &[BezPath]) -> Vec<PropGroup> {
|
||||
let mut out = vec![];
|
||||
for n in nodes.iter().rev() {
|
||||
@@ -406,6 +423,7 @@ fn copy_transform(proj: &mut Project, src: &Layer, dst: &mut Layer) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy timing and parenting from `src` to `dst`.
|
||||
fn like_source(dst: &mut Layer, src: &Layer) {
|
||||
dst.start_time = src.start_time;
|
||||
dst.in_point = src.in_point;
|
||||
@@ -418,13 +436,17 @@ fn like_source(dst: &mut Layer, src: &Layer) {
|
||||
/// A raster image of a vector document (Create Shapes from Vector Layer makes it a footage
|
||||
/// layer: shape layers have no images).
|
||||
pub struct VectorImage {
|
||||
/// Image name.
|
||||
pub name: String,
|
||||
/// Pixel width.
|
||||
pub width: u32,
|
||||
/// Pixel height.
|
||||
pub height: u32,
|
||||
/// Straight RGBA8.
|
||||
pub rgba: std::sync::Arc<Vec<u8>>,
|
||||
/// Image pixels → document pixels.
|
||||
pub transform: Affine,
|
||||
/// Opacity, 0..1.
|
||||
pub opacity: f64,
|
||||
/// Inside a clipping group or under a soft mask (not carried over).
|
||||
pub clipped: bool,
|
||||
@@ -432,6 +454,7 @@ pub struct VectorImage {
|
||||
|
||||
/// The document's images, bottom first, and how many soft-masked groups it has.
|
||||
pub fn vector_images(doc: &Doc) -> (Vec<VectorImage>, usize) {
|
||||
/// Collect images from a group tree, counting soft-masked groups.
|
||||
fn walk(g: &effectcraft_svg::Group, m: Affine, opacity: f64, clipped: bool, out: &mut Vec<VectorImage>, masks: &mut usize) {
|
||||
let m = m * g.transform;
|
||||
let opacity = opacity * g.opacity;
|
||||
@@ -467,6 +490,7 @@ pub fn vector_images(doc: &Doc) -> (Vec<VectorImage>, usize) {
|
||||
/// layers and image footage layers can stack in the document's order. One more segment than
|
||||
/// images.
|
||||
pub fn split_at_images(doc: &Doc) -> Vec<Doc> {
|
||||
/// Count the images in a group tree.
|
||||
fn count(g: &effectcraft_svg::Group) -> usize {
|
||||
g.children
|
||||
.iter()
|
||||
|
||||
@@ -61,6 +61,7 @@ pub use effectcraft_track as track;
|
||||
pub use footage::doc_path;
|
||||
pub use footage::footage_check;
|
||||
pub use footage::footage_reload;
|
||||
pub use footage::lut_reload;
|
||||
pub use footage::media_browser;
|
||||
pub use footage::media_cache;
|
||||
pub use footage::sequence;
|
||||
|
||||
@@ -320,6 +320,7 @@ pub fn checked(s: &Session, command: &str, params: &Value) -> Option<bool> {
|
||||
let layer = s.state.selected_layers.first().and_then(|l| comp.layer(*l));
|
||||
let pstr = |k: &str| params.get(k).and_then(Value::as_str);
|
||||
match command {
|
||||
"path.toggleClosed" => crate::cmd::paths::selected_paths_closed(s),
|
||||
"layer.setBlendMode" => {
|
||||
let want = effectcraft_color::BlendMode::from_name(pstr("mode")?)?;
|
||||
Some(layer?.blend_mode == want)
|
||||
@@ -829,7 +830,7 @@ Layer
|
||||
Hide Locked Masks | layer.mask.hideLocked
|
||||
Mask and Shape Path
|
||||
RotoBezier | path.rotoBezier
|
||||
Closed | mask.setClosed
|
||||
Closed | path.toggleClosed
|
||||
Convert To Bezier Path | path.convertToBezier
|
||||
Set First Vertex | path.setFirstVertex
|
||||
Free Transform Points | path.freeTransform
|
||||
|
||||
@@ -159,6 +159,44 @@ fn checked_reflects_layer_state() {
|
||||
assert_eq!(checked(&s, "file.save", &serde_json::json!({})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_menu_opens_and_recloses_a_manual_shape() {
|
||||
use serde_json::json;
|
||||
let mut s = crate::Session::default();
|
||||
s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap();
|
||||
let r = s
|
||||
.execute(
|
||||
"shape.newPath",
|
||||
json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true,
|
||||
"inTangents": [[0, -12], [-8, 0], [0, -6]], "outTangents": [[12, 0], [0, 8], [-6, 0]]}),
|
||||
)
|
||||
.unwrap();
|
||||
let lid = effectcraft_project::LayerId(r["layer"].as_u64().unwrap());
|
||||
let uid = r["path"].as_u64().unwrap();
|
||||
let path =
|
||||
|s: &crate::Session| s.active_comp().unwrap().layer(lid).unwrap().props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone();
|
||||
let original = path(&s);
|
||||
for mac in [true, false] {
|
||||
let (_, entry) =
|
||||
platform_entries(mac).into_iter().find(|(p, e)| p.iter().map(String::as_str).eq(["Layer", "Mask and Shape Path"]) && e.label == "Closed").unwrap();
|
||||
assert!(s.is_enabled(&entry.command));
|
||||
assert_eq!(checked(&s, &entry.command, &entry.params), Some(true));
|
||||
s.execute(&entry.command, entry.params.clone()).unwrap();
|
||||
let mut opened = original.clone();
|
||||
opened.closed = false;
|
||||
assert_eq!(path(&s), opened);
|
||||
assert!(!effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath));
|
||||
assert_eq!(checked(&s, &entry.command, &entry.params), Some(false));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(path(&s), original);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(path(&s), opened);
|
||||
s.execute(&entry.command, entry.params).unwrap();
|
||||
assert_eq!(path(&s), original);
|
||||
assert!(effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath));
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test -p effectcraft-engine dump_specs -- --ignored --nocapture`: every command as TSV.
|
||||
#[test]
|
||||
#[ignore]
|
||||
|
||||
@@ -106,6 +106,11 @@ pub trait Importer: Send + Sync {
|
||||
/// Probe one file and return footage metadata. Image sequences are the engine's
|
||||
/// ([`sequence`]): it groups numbered stills and probes their first file here.
|
||||
fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String>;
|
||||
/// [`probe`](Self::probe), and what the import left out of the file (a 3D model's textures
|
||||
/// over the limits), which the import shows the user.
|
||||
fn probe_noting(&self, path: &str) -> std::result::Result<(effectcraft_project::Footage, Option<String>), String> {
|
||||
self.probe(path).map(|f| (f, None))
|
||||
}
|
||||
/// A footage file's bytes are now at `path` (extracted from a template): hosts whose media
|
||||
/// layer reads from memory (the browser) register them; file-based ones need nothing.
|
||||
fn register(&self, _path: &str, _data: &[u8]) {}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
mod add_item_options;
|
||||
mod aep_export;
|
||||
mod aep_import;
|
||||
mod analysis_inputs;
|
||||
mod analysis_signature;
|
||||
mod anim_presets;
|
||||
mod anim_tools;
|
||||
mod aux_footage;
|
||||
@@ -12,6 +14,7 @@ mod crypto_pick;
|
||||
mod delete_keys;
|
||||
mod disk_cache;
|
||||
mod display_pass;
|
||||
mod effect_ranges;
|
||||
mod effects;
|
||||
mod essential;
|
||||
mod essential_more;
|
||||
@@ -27,8 +30,10 @@ mod key_metadata_order;
|
||||
mod key_time;
|
||||
mod keyframe_text;
|
||||
mod keylight;
|
||||
mod legacy_analysis_keys;
|
||||
mod limits;
|
||||
mod lottie;
|
||||
mod lut_files;
|
||||
mod m137;
|
||||
mod m145;
|
||||
mod markers;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Warp Stabilizer and 3D Camera Tracker analyses follow their input: the layer's frames, its
|
||||
//! masks, the effects above them and a precomp's contents (#3535). Edits that leave the input
|
||||
//! as it was (effects below, names, labels) keep them.
|
||||
|
||||
use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
|
||||
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{ItemId, LayerId, Project};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const COMP: ItemId = ItemId(2);
|
||||
const CLIP: LayerId = LayerId(3);
|
||||
const WARP: u64 = 26;
|
||||
const TRACKER: u64 = 54;
|
||||
|
||||
/// `analysed-0.24.ecproj`: the clip of `tracked-0.22.ecproj` with a mask and, in order, a Warp Stabilizer, a 3D Camera
|
||||
/// Tracker, a Gaussian Blur and a Roto Brush.
|
||||
const ANALYSED: &str = include_str!("fixtures/analysed-0.24.ecproj");
|
||||
|
||||
fn open(json: &str) -> Session {
|
||||
let mut s = Session::default();
|
||||
s.replace_project(Project::from_json(json).unwrap(), None);
|
||||
s.open_comp(COMP);
|
||||
s
|
||||
}
|
||||
|
||||
/// Which keys an analysis saves.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Saved {
|
||||
/// Today's: the input to the instance.
|
||||
Input,
|
||||
/// Before #3535: the layer's frames only (still recognised).
|
||||
Frames,
|
||||
}
|
||||
|
||||
/// The key an analysis of instance `uid` (no Detailed Analysis) saves.
|
||||
fn key(p: &Project, uid: u64, saved: Saved) -> String {
|
||||
let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
match saved {
|
||||
Saved::Input => crate::analysis::frames_key::analysis_key(p, COMP, layer, uid),
|
||||
Saved::Frames => crate::analysis::frames_key::signature(p, COMP, layer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the Warp Stabilizer and the tracker an analysis of the clip as it is now, saved with
|
||||
/// `saved` keys, and reopen the project.
|
||||
fn analyse(s: &mut Session, saved: Saved) {
|
||||
let mut p = (*s.project).clone();
|
||||
let set = |p: &mut Project, uid: u64, data: &str, id: &str, key: &str| {
|
||||
let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(uid).unwrap();
|
||||
g.prop_mut(data).unwrap().value = Value::Str(format!("saved {data}"));
|
||||
g.prop_mut(id).unwrap().value = Value::Str(key.into());
|
||||
};
|
||||
// The Warp Stabilizer is above the tracker: its analysis is part of the tracker's input.
|
||||
let k = key(&p, WARP, saved);
|
||||
set(&mut p, WARP, ANALYSIS, ANALYSIS_KEY, &k);
|
||||
let k = key(&p, TRACKER, saved);
|
||||
set(&mut p, TRACKER, TRACKS, TRACKS_KEY, &k);
|
||||
*s = open(&p.to_json());
|
||||
run(s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"}));
|
||||
assert_eq!(analysed(s), [true, true], "{saved:?}");
|
||||
}
|
||||
|
||||
/// Whether the Warp Stabilizer and the tracker still have their analysis.
|
||||
fn analysed(s: &Session) -> [bool; 2] {
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let has = |uid: u64, id: &str| matches!(&layer.props.find_group(uid).unwrap().prop(id).unwrap().value, Value::Str(s) if !s.is_empty());
|
||||
[has(WARP, ANALYSIS), has(TRACKER, TRACKS)]
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, params: Json) -> Json {
|
||||
s.execute_checked(cmd, params).unwrap()
|
||||
}
|
||||
|
||||
fn undo(s: &mut Session) {
|
||||
run(s, "edit.undo", json!({}));
|
||||
}
|
||||
|
||||
/// An edit, its effect on the two analyses, and that undo brings them back.
|
||||
fn check(s: &mut Session, cmd: &str, params: Json, kept: [bool; 2]) {
|
||||
assert_eq!(analysed(s), [true, true], "before {cmd} {params}");
|
||||
run(s, cmd, params.clone());
|
||||
assert_eq!(analysed(s), kept, "{cmd} {params}");
|
||||
undo(s);
|
||||
assert_eq!(analysed(s), [true, true], "undo of {cmd} {params}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_and_effects_above_are_part_of_the_input() {
|
||||
for saved in [Saved::Input, Saved::Frames] {
|
||||
masks_and_effects_above(saved);
|
||||
}
|
||||
}
|
||||
|
||||
fn masks_and_effects_above(saved: Saved) {
|
||||
let mut s = open(ANALYSED);
|
||||
analyse(&mut s, saved);
|
||||
// The layer's mask is under every effect.
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]);
|
||||
// The Warp Stabilizer is above the tracker: its settings change the tracker's input only.
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, false]);
|
||||
// The Gaussian Blur and the Roto Brush are below both.
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4}), [true, true]);
|
||||
run(&mut s, "layer.rename", json!({"layer": CLIP.0, "name": "Renamed"}));
|
||||
assert_eq!(analysed(&s), [true, true]);
|
||||
// The Effects switch turns the Warp Stabilizer (above the tracker) off.
|
||||
check(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false}), [true, false]);
|
||||
// While it is off, the effects above draw nothing: editing them keeps the analyses.
|
||||
run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false}));
|
||||
analyse(&mut s, saved);
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, true]);
|
||||
run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": true}));
|
||||
assert_eq!(analysed(&s), [true, false]);
|
||||
analyse(&mut s, saved);
|
||||
|
||||
// An effect moved above the Warp Stabilizer is part of both inputs, and its settings too.
|
||||
s.edit("blur first", None, |p, _| {
|
||||
let fx = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.sub_mut("effects").unwrap();
|
||||
let blur = fx.children.remove(2);
|
||||
fx.children.insert(0, blur);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(analysed(&s), [false, false]);
|
||||
analyse(&mut s, saved);
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/blurriness", "value": 4}), [false, false]);
|
||||
|
||||
// Saved and reopened, they still match, and a mask edit still clears them.
|
||||
let mut s = open(&s.project.to_json());
|
||||
run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"}));
|
||||
assert_eq!(analysed(&s), [true, true]);
|
||||
check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]);
|
||||
}
|
||||
#[test]
|
||||
fn a_precomps_contents_are_part_of_the_input() {
|
||||
for saved in [Saved::Input, Saved::Frames] {
|
||||
precomp_contents(saved);
|
||||
}
|
||||
}
|
||||
|
||||
fn precomp_contents(saved: Saved) {
|
||||
let mut s = open(ANALYSED);
|
||||
// Pre-compose the clip, leaving its masks and effects on the precomp layer.
|
||||
let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"}));
|
||||
let inner = ItemId(r["comp"].as_u64().unwrap());
|
||||
let inner_layer = |s: &Session, comp: ItemId| s.project.comp(comp).unwrap().layers[0].id.0;
|
||||
let clip = inner_layer(&s, inner);
|
||||
analyse(&mut s, saved);
|
||||
// Edits inside the precomp change the frames.
|
||||
check(&mut s, "prop.set", json!({"comp": inner.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]);
|
||||
check(&mut s, "effect.apply", json!({"comp": inner.0, "layers": [clip], "effect": "ec.blur.gaussian"}), [false, false]);
|
||||
check(&mut s, "layer.timing", json!({"comp": inner.0, "layers": [clip], "out": 0.25}), [false, false]);
|
||||
// A label or comment inside it doesn't. A name does: expressions find layers by name.
|
||||
s.edit("label", None, |p, _| {
|
||||
let l = p.comp_mut(inner).unwrap().layer_mut(LayerId(clip)).unwrap();
|
||||
l.label = effectcraft_color::Label::Pink;
|
||||
l.comment = "a note".into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(analysed(&s), [true, true]);
|
||||
check(&mut s, "layer.rename", json!({"comp": inner.0, "layer": clip, "name": "Inner"}), [false, false]);
|
||||
|
||||
// A precomp inside the precomp: its contents too.
|
||||
let r = run(&mut s, "layer.precompose", json!({"comp": inner.0, "layers": [clip], "mode": "leave"}));
|
||||
let deeper = ItemId(r["comp"].as_u64().unwrap());
|
||||
assert_eq!(analysed(&s), [false, false], "pre-composing inside the precomp changes its contents");
|
||||
analyse(&mut s, saved);
|
||||
let clip = inner_layer(&s, deeper);
|
||||
check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]);
|
||||
|
||||
// Saved and reopened, they still match, and an edit inside still clears them.
|
||||
let mut s = open(&s.project.to_json());
|
||||
run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"}));
|
||||
assert_eq!(analysed(&s), [true, true]);
|
||||
check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]);
|
||||
}
|
||||
|
||||
/// Precomps used many times, nested deeply or (in a broken project) in a cycle are keyed in
|
||||
/// bounded time, and an edit deep inside still changes the key.
|
||||
#[test]
|
||||
fn shared_deep_and_cyclic_precomps_are_keyed_in_bounded_time() {
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_project::{ItemKind, LayerSource};
|
||||
let mut s = open(ANALYSED);
|
||||
let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"}));
|
||||
let inner = ItemId(r["comp"].as_u64().unwrap());
|
||||
let mut p = (*s.project).clone();
|
||||
let template = p.comp(inner).unwrap().clone();
|
||||
// 40 comps, each drawing the next one twice (2^40 paths if each were walked), the last
|
||||
// drawing the first.
|
||||
let ids: Vec<ItemId> = (0..40).map(|i| p.add_item(&format!("Nest {i}"), Label::default(), None, ItemKind::Comp(template.clone().into()))).collect();
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let next = ids[(i + 1) % ids.len()];
|
||||
let mut layer = template.layers[0].clone();
|
||||
layer.source = LayerSource::Comp { item: next };
|
||||
let c = p.comp_mut(*id).unwrap();
|
||||
c.layers.push(layer.clone());
|
||||
layer.id = LayerId(layer.id.0 + 1000);
|
||||
c.layers.push(layer);
|
||||
}
|
||||
p.comp_mut(inner).unwrap().layers[0].source = LayerSource::Comp { item: ids[0] };
|
||||
let key = |p: &Project| crate::analysis::frames_key::analysis_key(p, COMP, p.comp(COMP).unwrap().layer(CLIP).unwrap(), WARP);
|
||||
let start = std::time::Instant::now();
|
||||
let before = key(&p);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed());
|
||||
p.comp_mut(ids[10]).unwrap().background = [1.0, 0.0, 0.0];
|
||||
assert_ne!(key(&p), before);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Warp Stabilizer, 3D Camera Tracker and Roto Brush keys saved by 0.24 keep matching their
|
||||
//! layer's frames after edits that don't change them, and a real change still clears them.
|
||||
|
||||
use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
|
||||
use effectcraft_effects::roto::{FROZEN, INPUT_KEY};
|
||||
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{ItemId, LayerId, Project};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const COMP: ItemId = ItemId(2);
|
||||
const CLIP: LayerId = LayerId(3);
|
||||
const WARP: u64 = 26;
|
||||
const TRACKER: u64 = 54;
|
||||
const ROTO: u64 = 86;
|
||||
|
||||
/// Saved by 0.24.1 (before #3534/#3536): the clip of `tracked-0.22.ecproj` with Time Remap, a
|
||||
/// mask, a Gaussian Blur and a Roto Brush, its analyses replaced by short stand-ins. The keys
|
||||
/// are the ones that version computed for it.
|
||||
const ANALYSED_0_24: &str = include_str!("fixtures/analysed-0.24.ecproj");
|
||||
const SIGNATURE_0_24: &str = "03efb7c4b0f27b65";
|
||||
const ROTO_INPUT_0_24: &str = "7b319ce93027617c";
|
||||
|
||||
fn open(json: &str) -> Session {
|
||||
let mut s = Session::default();
|
||||
s.replace_project(Project::from_json(json).unwrap(), None);
|
||||
s.open_comp(COMP);
|
||||
s
|
||||
}
|
||||
|
||||
/// The (data, key) of the Warp Stabilizer, the 3D Camera Tracker and the Roto Brush.
|
||||
fn saved(s: &Session) -> [(String, String); 3] {
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let get = |uid: u64, data: &str, key: &str| {
|
||||
let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap());
|
||||
let text = |id: &str| match params.get(id) {
|
||||
Some(Value::Str(s)) => s.clone(),
|
||||
other => panic!("{id}: {other:?}"),
|
||||
};
|
||||
(text(data), text(key))
|
||||
};
|
||||
[get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY), get(ROTO, FROZEN, INPUT_KEY)]
|
||||
}
|
||||
|
||||
fn add_to_render_queue(s: &mut Session) {
|
||||
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() {
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
let before = saved(&s);
|
||||
assert_eq!(before[0], ("saved analysis".into(), SIGNATURE_0_24.into()));
|
||||
assert_eq!(before[1], ("saved tracks".into(), SIGNATURE_0_24.into()));
|
||||
assert_eq!(before[2], ("saved frozen".into(), ROTO_INPUT_0_24.into()));
|
||||
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Saved and reopened, the keys still match.
|
||||
let mut s = open(&s.project.to_json());
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Other frames: all three are cleared (the Roto Brush gets a new key), and undo brings them back.
|
||||
s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.25})).unwrap();
|
||||
let after = saved(&s);
|
||||
assert_eq!(after[0], (String::new(), String::new()));
|
||||
assert_eq!(after[1], (String::new(), String::new()));
|
||||
assert_eq!(after[2].0, "");
|
||||
assert_ne!(after[2].1, ROTO_INPUT_0_24);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Time Remap is part of the frames.
|
||||
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "timeRemap", "value": 0.3})).unwrap();
|
||||
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
|
||||
// The Roto Brush's input also has the layer's masks and the effects above it.
|
||||
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4})).unwrap();
|
||||
let after = saved(&s);
|
||||
assert_eq!(after[2].0, "");
|
||||
assert_ne!(after[2].1, ROTO_INPUT_0_24);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3})).unwrap();
|
||||
assert_eq!(saved(&s)[2].0, "");
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
}
|
||||
|
||||
/// The text keys are made from today, written field by field (#3536). It changes only when this
|
||||
/// test is changed with it: a new field of a type it writes doesn't compile until it is decided
|
||||
/// in `analysis::frames_key`, and renaming a field or variant doesn't change it.
|
||||
#[test]
|
||||
fn signature_text_is_pinned() {
|
||||
let s = open(ANALYSED_0_24);
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";name="Time Remap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#;
|
||||
assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key);
|
||||
}
|
||||
|
||||
/// Keys made today (after analysing again) match through edits, undo and save/reopen too, and
|
||||
/// renaming or relabelling never drops them.
|
||||
#[test]
|
||||
fn todays_keys_survive_edits_that_keep_their_frames() {
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
// Analysing again writes today's keys.
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let signature = crate::analysis::frames_key::signature(&s.project, COMP, layer);
|
||||
let input = crate::roto::input_key(&s.project, COMP, layer, ROTO);
|
||||
assert_ne!(signature, SIGNATURE_0_24);
|
||||
s.edit("analyse", None, |p, _| {
|
||||
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
|
||||
for (uid, id, key) in [(WARP, ANALYSIS_KEY, &signature), (TRACKER, TRACKS_KEY, &signature), (ROTO, INPUT_KEY, &input)] {
|
||||
l.props.find_group_mut(uid).unwrap().get_mut(id).unwrap().value = Value::Str(key.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// The Roto Brush's key covers the effects above it: the Warp Stabilizer's new key changed it.
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let input = crate::roto::input_key(&s.project, COMP, layer, ROTO);
|
||||
s.edit("roto key", None, |p, _| {
|
||||
let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(ROTO).unwrap();
|
||||
g.get_mut(INPUT_KEY).unwrap().value = Value::Str(input.clone());
|
||||
g.get_mut(FROZEN).unwrap().value = Value::Str("saved frozen".into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = saved(&s);
|
||||
assert_eq!(before[0].1, signature);
|
||||
assert_eq!(before[2], ("saved frozen".into(), input));
|
||||
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
let mut s = open(&s.project.to_json());
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
// Offline and back online (#3534).
|
||||
for missing in [true, false] {
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.missing = missing;
|
||||
}
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
}
|
||||
// Colour labels and footage markers only show things.
|
||||
s.edit("label", None, |p, _| {
|
||||
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
|
||||
l.props.find_group_mut(82).unwrap().label = Some(effectcraft_color::Label::Yellow);
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.markers.push(effectcraft_project::Marker::default());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
// Expressions find effects by name: renaming the effect above the Roto Brush is a change for it.
|
||||
s.edit("rename", None, |p, _| {
|
||||
p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(82).unwrap().name = "Soft".into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(saved(&s)[..2], before[..2]);
|
||||
assert_eq!(saved(&s)[2].0, "");
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// A real change still clears them.
|
||||
s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap();
|
||||
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
|
||||
}
|
||||
|
||||
/// Footage going offline (or coming back) is an observation, not an edit: the next edit keeps
|
||||
/// every analysis (#3534).
|
||||
#[test]
|
||||
fn offline_footage_keeps_analyses() {
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
let before = saved(&s);
|
||||
let missing = |s: &Session| matches!(&s.project.item(ItemId(1)).unwrap().kind, effectcraft_project::ItemKind::Footage(f) if f.missing);
|
||||
// The fixture's footage path doesn't exist here: the check marks it missing.
|
||||
let r = s.execute_checked("footage.check", json!({"wait": true})).unwrap();
|
||||
assert_eq!(r["missing"], 1, "{r}");
|
||||
assert!(missing(&s));
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Saved and reopened while offline, then back online.
|
||||
let mut s = open(&s.project.to_json());
|
||||
assert!(missing(&s));
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.missing = false;
|
||||
}
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// A real change while offline still clears them.
|
||||
s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap();
|
||||
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
|
||||
}
|
||||
|
||||
/// A key 0.24.1 saved while the footage was offline (it hashed the availability) matches too,
|
||||
/// online or offline. 0.24.1 gave the Roto Brush this Input Key when the fixture's footage went
|
||||
/// offline and an edit cleared the other two analyses.
|
||||
#[test]
|
||||
fn keys_saved_by_0_24_while_offline_still_match() {
|
||||
const ROTO_INPUT_0_24_OFFLINE: &str = "6183fdd46b514259";
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
s.edit("offline", None, |p, _| {
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.missing = true;
|
||||
}
|
||||
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
|
||||
// What 0.24.1's edit cleared then.
|
||||
use effectcraft_effects::camera_tracker::{AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY};
|
||||
for (uid, id) in
|
||||
[(WARP, ANALYSIS), (WARP, ANALYSIS_KEY), (TRACKER, SOLVE), (TRACKER, SOLVE_KEY), (TRACKER, METHOD_USED), (TRACKER, TRACKS), (TRACKER, TRACKS_KEY)]
|
||||
{
|
||||
l.props.find_group_mut(uid).unwrap().prop_mut(id).unwrap().value = Value::Str(String::new());
|
||||
}
|
||||
l.props.find_group_mut(TRACKER).unwrap().prop_mut(AVERAGE_ERROR).unwrap().value = Value::Scalar(0.0);
|
||||
let g = l.props.find_group_mut(ROTO).unwrap();
|
||||
g.get_mut(INPUT_KEY).unwrap().value = Value::Str(ROTO_INPUT_0_24_OFFLINE.into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let roto = |s: &Session| saved(s)[2].clone();
|
||||
assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into()));
|
||||
for missing in [true, false] {
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.missing = missing;
|
||||
}
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Expressions seed `random` and `wiggle` with the property's uid: a Time Remap with an expression
|
||||
/// keys its uid (a duplicated layer gets new uids), one without doesn't.
|
||||
#[test]
|
||||
fn an_expression_keys_its_property_uid() {
|
||||
let s = open(ANALYSED_0_24);
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().clone();
|
||||
let text = |l: &effectcraft_project::Layer| crate::analysis::frames_key::signature_text(&s.project, COMP, l);
|
||||
let renumbered = |l: &effectcraft_project::Layer| {
|
||||
let mut l = l.clone();
|
||||
l.props.get_mut("timeRemap").unwrap().uid += 1000;
|
||||
l
|
||||
};
|
||||
assert_eq!(text(&renumbered(&layer)), text(&layer));
|
||||
let mut with_expr = layer.clone();
|
||||
with_expr.props.get_mut("timeRemap").unwrap().expr =
|
||||
Some(effectcraft_project::Expression { text: "seedRandom(0, true); random(0, 1)".into(), enabled: true });
|
||||
assert_ne!(text(&renumbered(&with_expr)), text(&with_expr));
|
||||
}
|
||||
|
||||
/// Non-default values of the types the key writes are written as their fixed words (#3536).
|
||||
#[test]
|
||||
fn nested_values_are_written_as_fixed_words() {
|
||||
use effectcraft_project::{
|
||||
AlphaMode, CineonUnits, FieldOrder, FootageKind, GroupKind, ItemKind, LayerSource, MaskMode, MaskMotionBlur, Solid, SourceLayer,
|
||||
};
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
let p = std::sync::Arc::make_mut(&mut s.project);
|
||||
if let Some(ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
|
||||
f.kind = FootageKind::Sequence;
|
||||
f.sequence = vec!["a_0001.png".into(), "a_0002.png".into()];
|
||||
f.alpha = AlphaMode::Premultiplied;
|
||||
f.premul_color = [0.5, 0.25, 1.0];
|
||||
f.fields = FieldOrder::UpperFirst;
|
||||
f.cineon.units = CineonUnits::Float;
|
||||
f.cineon.log_conversion = true;
|
||||
f.color_profile = Some(effectcraft_color::ColorSpace::DisplayP3);
|
||||
f.layer = Some(SourceLayer { index: 3, name: "Sky".into(), layer_size: true, embedded: Some("id-7".into()), placed: true });
|
||||
f.native_rate = Some(effectcraft_time::FrameRate { num: 30000, den: 1001 });
|
||||
f.start_timecode = Some(42);
|
||||
f.data = Some("{\"k\":1}".into());
|
||||
}
|
||||
let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap().clone();
|
||||
let text = crate::analysis::frames_key::signature_text(p, COMP, &layer);
|
||||
let footage = text.split(";in=").next().unwrap();
|
||||
assert_eq!(
|
||||
footage,
|
||||
r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=sequence;w=160;h=120;par=1.0;rate=12/1;nativeRate{rate=30000/1001;};duration=254016000000;video=true;audio=false;alpha=premultiplied;matte=[0.5, 0.25, 1.0];loop=1;codec="H.264 (High)";frames=2;file="a_0001.png";file="a_0002.png";profile{p3;};layer{index=3;layerSize=true;embedded{id="id-7";};placed=true;};fields=upper;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=true;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=float;data{text="{\"k\":1}";};page=0;alphabetical=false;startTimecode{frame=42;};fileTimecode=none;placedPage=false"#
|
||||
);
|
||||
|
||||
let solid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.5, 0.0], width: 64, height: 48, pixel_aspect: 2.0 }));
|
||||
let mut on_solid = layer.clone();
|
||||
on_solid.source = LayerSource::Solid { item: solid };
|
||||
let text = crate::analysis::frames_key::signature_text(p, COMP, &on_solid);
|
||||
assert_eq!(text.split(";in=").next().unwrap(), format!("frames/1;solid={};solid;color=[1.0, 0.5, 0.0];w=64;h=48;par=2.0", solid.0));
|
||||
|
||||
// Every mask mode and motion blur setting gives its own Input Key.
|
||||
let mask = layer.masks().unwrap().groups().next().unwrap().uid;
|
||||
let mut keys = std::collections::BTreeSet::new();
|
||||
for mode in MaskMode::ALL {
|
||||
for blur in [MaskMotionBlur::SameAsLayer, MaskMotionBlur::On, MaskMotionBlur::Off] {
|
||||
let mut l = layer.clone();
|
||||
if let GroupKind::Mask { mode: m, motion_blur, .. } = &mut l.props.find_group_mut(mask).unwrap().kind {
|
||||
(*m, *motion_blur) = (mode, blur);
|
||||
}
|
||||
keys.insert(crate::analysis::frames_key::input_key(p, COMP, &l, ROTO));
|
||||
}
|
||||
}
|
||||
assert_eq!(keys.len(), MaskMode::ALL.len() * 3);
|
||||
}
|
||||
@@ -252,6 +252,15 @@ fn invalidation_resolve_cancel_and_undo() {
|
||||
assert_eq!(status(&mut s)["analyzed"], false);
|
||||
assert!(s.redo());
|
||||
assert_eq!(status(&mut s)["solved"], true);
|
||||
// A mask is part of the tracked input (#3535): drawing one clears the tracks, undo keeps them.
|
||||
s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap();
|
||||
assert_eq!(status(&mut s)["analyzed"], false);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(status(&mut s)["solved"], true);
|
||||
// An effect below the tracker isn't.
|
||||
s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap();
|
||||
assert_eq!(status(&mut s)["solved"], true);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
|
||||
// Changing the Solve Method keeps the tracks and only re-solves.
|
||||
s.execute_checked("prop.set", json!({"layer": clip.0, "path": "effects/#1/advanced/solveMethod", "value": 1})).unwrap();
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
//! Effect parameters take the whole valid range After Effects records for them (fx_defs in the
|
||||
//! aep crate), end to end: `prop.set` keeps both ends, undo and redo restore them, and a saved
|
||||
//! project reopens with them. The aep crate's
|
||||
//! `effect_hard_ranges_cover_recorded_after_effects_ranges` checks the ranges themselves
|
||||
//! against that table.
|
||||
|
||||
use effectcraft_project::{LayerId, Node, ParamUi, PropGroup};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// (issue, effect, parameter path, lowest, highest): the ends of the range the effect now accepts,
|
||||
/// in EffectCraft's units: After Effects' valid range, or wider where EffectCraft already was.
|
||||
/// At least one end of each is outside the range accepted before the issue.
|
||||
#[rustfmt::skip]
|
||||
const ROWS: &[(u32, &str, &str, f64, f64)] = &[
|
||||
(3487, "ec.color.levelsic", "rgb/rgbInBlack", -10000.0, 10000.0),
|
||||
(3488, "ec.color.levelsic", "rgb/rgbInWhite", -10000.0, 10000.0),
|
||||
(3489, "ec.color.levelsic", "rgb/rgbOutBlack", -10000.0, 10000.0),
|
||||
(3490, "ec.color.levelsic", "rgb/rgbOutWhite", -10000.0, 10000.0),
|
||||
(3491, "ec.color.levelsic", "rgb/rgbGamma", 0.0, 10.0),
|
||||
(3487, "ec.color.levelsic", "red/redInBlack", -10000.0, 10000.0),
|
||||
(3488, "ec.color.levelsic", "red/redInWhite", -10000.0, 10000.0),
|
||||
(3489, "ec.color.levelsic", "red/redOutBlack", -10000.0, 10000.0),
|
||||
(3490, "ec.color.levelsic", "red/redOutWhite", -10000.0, 10000.0),
|
||||
(3491, "ec.color.levelsic", "red/redGamma", 0.0, 10.0),
|
||||
(3487, "ec.color.levelsic", "green/greenInBlack", -10000.0, 10000.0),
|
||||
(3488, "ec.color.levelsic", "green/greenInWhite", -10000.0, 10000.0),
|
||||
(3489, "ec.color.levelsic", "green/greenOutBlack", -10000.0, 10000.0),
|
||||
(3490, "ec.color.levelsic", "green/greenOutWhite", -10000.0, 10000.0),
|
||||
(3491, "ec.color.levelsic", "green/greenGamma", 0.0, 10.0),
|
||||
(3487, "ec.color.levelsic", "blue/blueInBlack", -10000.0, 10000.0),
|
||||
(3488, "ec.color.levelsic", "blue/blueInWhite", -10000.0, 10000.0),
|
||||
(3489, "ec.color.levelsic", "blue/blueOutBlack", -10000.0, 10000.0),
|
||||
(3490, "ec.color.levelsic", "blue/blueOutWhite", -10000.0, 10000.0),
|
||||
(3491, "ec.color.levelsic", "blue/blueGamma", 0.0, 10.0),
|
||||
(3487, "ec.color.levelsic", "alpha/alphaInBlack", -10000.0, 10000.0),
|
||||
(3488, "ec.color.levelsic", "alpha/alphaInWhite", -10000.0, 10000.0),
|
||||
(3489, "ec.color.levelsic", "alpha/alphaOutBlack", -10000.0, 10000.0),
|
||||
(3490, "ec.color.levelsic", "alpha/alphaOutWhite", -10000.0, 10000.0),
|
||||
(3491, "ec.color.levelsic", "alpha/alphaGamma", 0.0, 10.0),
|
||||
(3478, "ec.generate.fourcolor", "blend", 1.0, 10000.0),
|
||||
(3479, "ec.generate.fourcolor", "jitter", 0.0, 500.0),
|
||||
(3483, "ec.noise.noisehls", "hue", 0.0, 1000.0),
|
||||
(3483, "ec.noise.noisehls", "lightness", 0.0, 1000.0),
|
||||
(3483, "ec.noise.noisehls", "saturation", 0.0, 1000.0),
|
||||
(3484, "ec.noise.noisehls", "grainSize", 0.0, 100.0),
|
||||
(3483, "ec.noise.noisehlsauto", "hue", 0.0, 1000.0),
|
||||
(3483, "ec.noise.noisehlsauto", "lightness", 0.0, 1000.0),
|
||||
(3483, "ec.noise.noisehlsauto", "saturation", 0.0, 1000.0),
|
||||
(3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0),
|
||||
(3480, "ec.color.changecolor", "hueTransform", -1800.0, 1800.0),
|
||||
(3476, "ec.generate.grid", "border", 0.0, 2000.0),
|
||||
(3472, "ec.transition.venetian", "width", 1.0, 32000.0),
|
||||
(3473, "ec.transition.venetian", "feather", 0.0, 32000.0),
|
||||
(3474, "ec.transition.radialwipe", "feather", 0.0, 32000.0),
|
||||
(3477, "ec.stylize.scatter", "amount", 0.0, 1000.0),
|
||||
(3475, "ec.generate.beam", "startThickness", 0.0, 4000.0),
|
||||
(3475, "ec.generate.beam", "endThickness", 0.0, 4000.0),
|
||||
(3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0),
|
||||
(3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0),
|
||||
(3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0),
|
||||
];
|
||||
|
||||
fn path(effect: &str, param: &str) -> String {
|
||||
format!("effects/{effect}/{param}")
|
||||
}
|
||||
|
||||
fn read(s: &mut Session, layer: u64, effect: &str, param: &str) -> f64 {
|
||||
let got = s.execute("prop.get", json!({"layer": layer, "path": path(effect, param)})).unwrap();
|
||||
got["value"].as_f64().unwrap_or_else(|| panic!("{effect} {param}: {got}"))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, layer: u64, effect: &str, param: &str, v: f64) -> Value {
|
||||
s.execute("prop.set", json!({"layer": layer, "path": path(effect, param), "value": v})).unwrap()
|
||||
}
|
||||
|
||||
/// A composition with two solids, each with one instance of every effect in [`ROWS`].
|
||||
fn session() -> (Session, u64, u64) {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let mut layers = [0; 2];
|
||||
for l in &mut layers {
|
||||
*l = s.execute("layer.newSolid", json!({"color": "#808080", "width": 64, "height": 36})).unwrap()["layer"].as_u64().unwrap();
|
||||
let mut effects: Vec<&str> = ROWS.iter().map(|r| r.1).collect();
|
||||
effects.dedup();
|
||||
for e in effects {
|
||||
s.execute("effect.apply", json!({"layers": [*l], "effect": e})).unwrap();
|
||||
}
|
||||
}
|
||||
(s, layers[0], layers[1])
|
||||
}
|
||||
|
||||
/// Both ends of every row survive `prop.set`, undo / redo, and a save and reopen.
|
||||
#[test]
|
||||
fn effect_parameters_keep_both_ends_of_the_after_effects_range() {
|
||||
let (mut s, low, high) = session();
|
||||
for &(issue, e, p, lo, hi) in ROWS {
|
||||
assert_eq!(set(&mut s, high, e, p, lo), json!(lo), "#{issue} {e} {p}: prop.set reply");
|
||||
assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}");
|
||||
set(&mut s, high, e, p, hi);
|
||||
assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}");
|
||||
assert!(s.undo());
|
||||
assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}: undo");
|
||||
assert!(s.redo());
|
||||
assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}: redo");
|
||||
set(&mut s, low, e, p, lo);
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("ec-effect-ranges-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("ranges.ecproj").to_string_lossy().to_string();
|
||||
s.execute("file.save", json!({"path": file})).unwrap();
|
||||
let mut s2 = Session::default();
|
||||
s2.execute("file.open", json!({"path": file})).unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
for &(issue, e, p, lo, hi) in ROWS {
|
||||
assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}: reopened");
|
||||
assert_eq!(read(&mut s2, high, e, p), hi, "#{issue} {e} {p}: reopened");
|
||||
}
|
||||
}
|
||||
|
||||
/// A project saved while these ranges were narrower stored that range with each instance
|
||||
/// (`ParamUi`) and values clamped to it: opening it takes the effect's current range and keeps
|
||||
/// the stored values, so the new ends can be set.
|
||||
#[test]
|
||||
fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() {
|
||||
let (mut s, low, _) = session();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let mut old = (*s.project).clone();
|
||||
let stored: Vec<f64> = ROWS.iter().map(|&(_, e, p, ..)| read(&mut s, low, e, p)).collect();
|
||||
{
|
||||
let effectcraft_project::ItemKind::Comp(comp) = &mut old.items.get_mut(&cid).unwrap().kind else { panic!("not a composition") };
|
||||
let l = std::sync::Arc::make_mut(comp).layers.find_mut(|l| l.id == LayerId(low)).unwrap();
|
||||
for (&(_, e, p, ..), v) in ROWS.iter().zip(&stored) {
|
||||
let g = l.props.sub_mut("effects").unwrap().children.iter_mut().find_map(|n| match n {
|
||||
Node::Group(g) if g.match_id == e => Some(g),
|
||||
_ => None,
|
||||
});
|
||||
let pr = prop_mut(g.unwrap(), p).unwrap_or_else(|| panic!("{e} {p}"));
|
||||
// The narrowest stored range that still holds the stored value.
|
||||
pr.ui = ParamUi::Slider { min: *v, max: *v, slider_min: *v, slider_max: *v, decimals: 1 };
|
||||
}
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("ec-effect-ranges-old-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("old.ecproj").to_string_lossy().to_string();
|
||||
std::fs::write(&file, old.to_json()).unwrap();
|
||||
let mut s2 = Session::default();
|
||||
s2.execute("file.open", json!({"path": file})).unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
for (&(issue, e, p, lo, hi), v) in ROWS.iter().zip(&stored) {
|
||||
assert_eq!(read(&mut s2, low, e, p), *v, "#{issue} {e} {p}: the stored value is kept");
|
||||
let spec = effectcraft_effects::find(e).unwrap().params.iter().find(|q| q.id == p).unwrap();
|
||||
let uid = s2.execute("prop.get", json!({"layer": low, "path": path(e, p)})).unwrap()["uid"].as_u64().unwrap();
|
||||
let layer = s2.project.comp(cid).unwrap().layer(LayerId(low)).unwrap();
|
||||
assert_eq!(layer.props.find(uid).unwrap().ui, spec.ui, "#{issue} {e} {p}: the range is refreshed");
|
||||
set(&mut s2, low, e, p, lo);
|
||||
assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}");
|
||||
set(&mut s2, low, e, p, hi);
|
||||
assert_eq!(read(&mut s2, low, e, p), hi, "#{issue} {e} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The property at `path` (`group/param`) in an effect instance.
|
||||
fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> {
|
||||
match path.split_once('/') {
|
||||
None => g.get_mut(path),
|
||||
Some((first, rest)) => prop_mut(g.sub_mut(first)?, rest),
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
asset: analysed-0.24.ecproj
|
||||
title: The tracked-0.22 clip with Time Remap, a mask, Gaussian Blur and Roto Brush, keyed by EffectCraft 0.24.1
|
||||
author: arnav-hiwarkar
|
||||
source: original work
|
||||
license: MIT OR Apache-2.0
|
||||
license-file: ../../../../../LICENSE-MIT
|
||||
added: 2026-11-12 by arnav-hiwarkar
|
||||
notes: Made from tracked-0.22.ecproj with 0.24.1 engine commands (enable Time Remap, a rectangle mask, Gaussian Blur and Roto Brush), its saved analyses replaced by short stand-in strings, and the Warp Stabilizer, 3D Camera Tracker and Roto Brush keys that 0.24.1 computed for it. Written as compact JSON. No media is needed: the tests only check that the keys are kept or cleared.
|
||||
+1593
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
asset: tracked-0.22.ecproj
|
||||
title: One clip with an analysed Warp Stabilizer and 3D Camera Tracker from EffectCraft 0.22.0
|
||||
author: arnav-hiwarkar
|
||||
source: original work
|
||||
license: MIT OR Apache-2.0
|
||||
license-file: ../../../../../LICENSE-MIT
|
||||
added: 2026-11-12 by arnav-hiwarkar
|
||||
notes: Saved by the released 0.22.0 CLI after importing a generated 160x120, 12-frame shaking crop of an ffmpeg testsrc2 pattern, applying both effects and analysing them. The source path is a generic test path; the video is not needed by the tests, which only check that the saved analyses are kept or cleared.
|
||||
@@ -480,3 +480,29 @@ fn camera_light_and_material_options_are_written_as_after_effects_does() {
|
||||
assert!(text.contains(block), "{block}in\n{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit column of `name`'s block in copied keyframe text.
|
||||
fn unit_of<'a>(text: &'a str, name: &str) -> &'a str {
|
||||
let mut lines = text.lines().skip_while(|l| !l.contains(&format!("\t{name} #")));
|
||||
lines.next().unwrap_or_else(|| panic!("no {name} in\n{text}"));
|
||||
lines.next().and_then(|l| l.strip_prefix("\tFrame\t")).and_then(|l| l.strip_suffix('\t')).unwrap_or_else(|| panic!("{name} in\n{text}"))
|
||||
}
|
||||
|
||||
/// Widening a 0..100 slider to After Effects' range (#3479, #3483, #3484) keeps the unit the
|
||||
/// keyframe text writes for it.
|
||||
#[test]
|
||||
fn widened_effect_ranges_keep_their_keyframe_text_units() {
|
||||
let (mut s, l) = session();
|
||||
s.execute("effect.apply", json!({"layer": l.0, "effect": "ec.generate.fourcolor"})).unwrap();
|
||||
let text = copy_props(&mut s, l, &["effects/#1/blend", "effects/#1/jitter"]);
|
||||
assert_eq!(unit_of(&text, "Blend"), "percent");
|
||||
assert_eq!(unit_of(&text, "Jitter"), "percent");
|
||||
for fx in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] {
|
||||
let (mut s, l) = session();
|
||||
s.execute("effect.apply", json!({"layer": l.0, "effect": fx})).unwrap();
|
||||
let text = copy_props(&mut s, l, &["effects/#1/hue", "effects/#1/lightness", "effects/#1/saturation", "effects/#1/grainSize"]);
|
||||
for (name, unit) in [("Hue", "percent"), ("Lightness", "percent"), ("Saturation", "percent"), ("Grain Size", "")] {
|
||||
assert_eq!(unit_of(&text, name), unit, "{fx} {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching
|
||||
//! their footage after an edit that doesn't change it (#3456), and a real change still clears them.
|
||||
|
||||
use effectcraft_effects::camera_tracker::{SOLVE, TRACKS, TRACKS_KEY};
|
||||
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{ItemId, LayerId, Project};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const FOOTAGE: ItemId = ItemId(1);
|
||||
const COMP: ItemId = ItemId(2);
|
||||
const CLIP: LayerId = LayerId(3);
|
||||
const WARP: u64 = 26;
|
||||
const TRACKER: u64 = 54;
|
||||
|
||||
/// The analysis (as its length and a hash: it's long) and key of the Warp Stabilizer and the
|
||||
/// 3D Camera Tracker.
|
||||
fn saved(s: &Session) -> [(usize, u64, String); 2] {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let get = |uid: u64, data: &str, key: &str| {
|
||||
let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap());
|
||||
let text = |id: &str| match params.get(id) {
|
||||
Some(Value::Str(s)) => s.clone(),
|
||||
other => panic!("{id}: {other:?}"),
|
||||
};
|
||||
let analysis = text(data);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
analysis.hash(&mut h);
|
||||
(analysis.len(), h.finish(), text(key))
|
||||
};
|
||||
[get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY)]
|
||||
}
|
||||
|
||||
fn open(json: &str) -> Session {
|
||||
let mut s = Session::default();
|
||||
s.replace_project(Project::from_json(json).unwrap(), None);
|
||||
s.open_comp(COMP);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() {
|
||||
// Saved by the released 0.22.0 CLI after analysing both effects; its footage is offline here.
|
||||
let mut s = open(include_str!("fixtures/tracked-0.22.ecproj"));
|
||||
let before = saved(&s);
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
for (len, _, key) in &before {
|
||||
assert!(*len > 0);
|
||||
// The key predates Footage::placed_page, so it isn't today's signature.
|
||||
assert_ne!(key, &crate::analysis::frames_key::signature(&s.project, COMP, layer));
|
||||
}
|
||||
|
||||
// Adding to the render queue edits the project, as `effectcraft-cli render` does.
|
||||
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Saved and reopened (by this version), the old keys are kept and still match.
|
||||
let mut s = open(&s.project.to_json());
|
||||
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
|
||||
// Other frames, from other timing or a reinterpreted footage item: both analyses are
|
||||
// cleared, and undo brings them back.
|
||||
let cleared = |s: &Session| saved(s).iter().all(|(len, _, key)| *len == 0 && key.is_empty());
|
||||
s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.5})).unwrap();
|
||||
assert!(cleared(&s));
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
s.execute_checked("file.interpretFootage", json!({"items": [FOOTAGE.0], "invertAlpha": true})).unwrap();
|
||||
assert!(cleared(&s));
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
// Footage framed as a placed page has other frames too, though 0.22 had no such field.
|
||||
s.edit("place page", None, |p, _| {
|
||||
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(FOOTAGE).map(|i| &mut i.kind) {
|
||||
f.placed_page = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(cleared(&s));
|
||||
}
|
||||
|
||||
/// Solving again reuses the 0.22 tracks rather than tracking the (here offline) footage again.
|
||||
#[test]
|
||||
fn camera_tracker_solves_again_from_tracks_saved_by_0_22() {
|
||||
let mut s = open(include_str!("fixtures/tracked-0.22.ecproj"));
|
||||
let tracks = saved(&s)[1].clone();
|
||||
let solve = |s: &Session| {
|
||||
let g = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().props.find_group(TRACKER).unwrap();
|
||||
crate::camera_track::static_params(g).get(SOLVE).cloned().unwrap()
|
||||
};
|
||||
// Another solve method, and back, clears the solve and keeps the tracks.
|
||||
for method in [1, 0] {
|
||||
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#2/advanced/solveMethod", "value": method})).unwrap();
|
||||
}
|
||||
assert_eq!(solve(&s), Value::Str(String::new()));
|
||||
assert_eq!(saved(&s)[1], tracks);
|
||||
s.execute_checked("camera.analyze", json!({"layer": CLIP.0, "effect": TRACKER, "wait": true})).unwrap();
|
||||
assert!(matches!(solve(&s), Value::Str(v) if !v.is_empty()));
|
||||
assert_eq!(saved(&s)[1], tracks);
|
||||
}
|
||||
|
||||
/// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must
|
||||
/// not change it (or every saved analysis is dropped again).
|
||||
#[test]
|
||||
fn footage_signature_text_is_pinned() {
|
||||
use effectcraft_project::{Footage, FootageKind};
|
||||
let f = Footage {
|
||||
path: "clip.mp4".into(),
|
||||
kind: FootageKind::Video,
|
||||
width: 160,
|
||||
height: 120,
|
||||
invert_alpha: true,
|
||||
page: 2,
|
||||
placed_page: true,
|
||||
..Footage::default()
|
||||
};
|
||||
let fields = r#"path: "clip.mp4", kind: Video, width: 160, height: 120, pixel_aspect: 1.0, frame_rate: FrameRate { num: 30, den: 1 }, native_rate: None, duration: Tick(0), has_video: false, has_audio: false, alpha: Straight, premul_color: [0.0, 0.0, 0.0], loop_count: 1, codec: "", missing: false, sequence: [], color_profile: None, layer: None, fields: Off, invert_alpha: true, linear_light: false, preserve_rgb: false, cineon: CineonSettings { log_conversion: false, converted_black: 0.0, converted_white: 1023.0, black: 95.0, white: 685.0, gamma: 1.7, rolloff: 20.0, units: TenBit }, data: None, page: 2, alphabetical: false, start_timecode: None, file_timecode: None, markers: []"#;
|
||||
assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, true), format!("Footage {{ {fields}, placed_page: true }}"));
|
||||
assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, false), format!("Footage {{ {fields} }}"));
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! A LUT file that changes on disk renders again (#3493): Apply Color LUT and Lumetri's Input
|
||||
//! LUT name a `.cube` file; an edit to it, or a file created, deleted or repaired, shows on the
|
||||
//! next render of the same frame, from warm layer caches in memory and on disk, through a precomp
|
||||
//! and a layer reading that precomp, and a frame kept on disk made with the old file is refused.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::render::RenderOpts;
|
||||
use effectcraft_project::ItemId;
|
||||
use effectcraft_render::disk_cache::{DiskCache, comp_content_key, frame_key};
|
||||
use effectcraft_render::reads::ReadLog;
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
/// Every input to black, or to white (1D, two entries: the same size, so only the modification
|
||||
/// time tells the two apart).
|
||||
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
|
||||
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
|
||||
const GREY: f32 = 128.0 / 255.0;
|
||||
|
||||
/// Write `text` to `path` with its modification time `secs` after the epoch.
|
||||
fn write(path: &Path, text: &str, secs: u64) {
|
||||
std::fs::write(path, text).unwrap();
|
||||
let f = std::fs::File::options().write(true).open(path).unwrap();
|
||||
f.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap();
|
||||
}
|
||||
|
||||
/// A session, its layer buffers written to a disk cache in `disk` when given.
|
||||
fn session(disk: Option<&Path>) -> Session {
|
||||
let mut s = Session::default();
|
||||
if let Some(dir) = disk {
|
||||
s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap();
|
||||
s.disk_cache.as_ref().unwrap().set_min_layer_ms(0);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Comp "Grade": a grey solid graded by `effect` (`params` set on it). Comp "Shot" shows it as a
|
||||
/// precomp layer, under a solid that copies the precomp's channels (Set Channels): that layer is
|
||||
/// cached with what the precomp shows. Returns (Grade, Shot).
|
||||
fn shot(s: &mut Session, effect: &str, params: &[(&str, Value)]) -> (ItemId, ItemId) {
|
||||
s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
|
||||
let shot = s.active_comp_id().unwrap();
|
||||
let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone();
|
||||
s.execute_checked("effect.apply", json!({"layer": plate, "effect": effect})).unwrap();
|
||||
for (path, value) in params {
|
||||
s.execute_checked("prop.set", json!({"layer": plate, "path": format!("effects/#1/{path}"), "value": value})).unwrap();
|
||||
}
|
||||
let pre = s.execute_checked("layer.precompose", json!({"layers": [plate], "name": "Grade"})).unwrap();
|
||||
let grade = ItemId(pre["comp"].as_u64().unwrap());
|
||||
let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone();
|
||||
s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap();
|
||||
for i in 1..=3 {
|
||||
s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": pre["layer"]})).unwrap();
|
||||
}
|
||||
(grade, shot)
|
||||
}
|
||||
|
||||
/// The red and green of the centre of both comps' first frame.
|
||||
fn colours(s: &Session, (grade, shot): (ItemId, ItemId)) -> [f32; 4] {
|
||||
let at = |comp| {
|
||||
let img = s.render(comp, Tick::ZERO, RenderOpts::default());
|
||||
img.get(i64::from(img.width / 2), i64::from(img.height / 2))
|
||||
};
|
||||
let (g, c) = (at(grade), at(shot));
|
||||
[g[0], g[1], c[0], c[1]]
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_all(got: [f32; 4], want: f32) {
|
||||
assert!(got.iter().all(|v| (v - want).abs() < 0.01), "{got:?}, want {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edited_lut_file_renders_again_from_warm_caches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lut = dir.path().join("grade.cube");
|
||||
write(&lut, BLACK, 1_000);
|
||||
let mut s = session(None);
|
||||
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
|
||||
assert_all(colours(&s, comps), 0.0);
|
||||
let misses = s.layer_cache.stats().misses;
|
||||
assert_all(colours(&s, comps), 0.0);
|
||||
assert_eq!(s.layer_cache.stats().misses, misses, "an unchanged file keeps the cached layers");
|
||||
// A frame on disk made with the file names it.
|
||||
let frames = DiskCache::open(dir.path().join("frames"), 1 << 30).unwrap();
|
||||
let key = frame_key(comp_content_key(&s.project, comps.1), 0, 1000, 0);
|
||||
let log = ReadLog::new();
|
||||
let mut r = s.renderer(RenderOpts::default());
|
||||
r.reads = Some(&log);
|
||||
let _ = r.comp_frame(comps.1, Tick::ZERO);
|
||||
let files = log.into_files();
|
||||
assert!(files.get(&lut.to_string_lossy()).is_some(), "the render notes the LUT file: {files:?}");
|
||||
frames.put_frame_now(key, 1, 1, &[0; 4], &files);
|
||||
assert!(frames.get_frame(key, None).is_some());
|
||||
let generation = effectcraft_effects::lut_generation();
|
||||
write(&lut, WHITE, 2_000);
|
||||
assert_all(colours(&s, comps), 1.0);
|
||||
assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped");
|
||||
assert!(frames.get_frame(key, None).is_none(), "the frame on disk made with the old file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edited_lut_file_is_not_served_from_the_disk_cache() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (lut, disk) = (dir.path().join("grade.cube"), dir.path().join("cache"));
|
||||
write(&lut, BLACK, 1_000);
|
||||
let mut s = session(Some(&disk));
|
||||
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
|
||||
assert_all(colours(&s, comps), 0.0);
|
||||
let dc = s.disk_cache.clone().unwrap();
|
||||
dc.flush();
|
||||
assert!(dc.stats().entries > 0, "layer buffers written");
|
||||
let project = s.project.clone();
|
||||
drop((s, dc));
|
||||
// A restart on the same cache, after the file changed.
|
||||
write(&lut, WHITE, 2_000);
|
||||
let mut s = session(Some(&disk));
|
||||
s.project = project;
|
||||
s.bump();
|
||||
assert_all(colours(&s, comps), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lut_file_created_deleted_or_repaired_renders_again() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lut = dir.path().join("later.cube");
|
||||
let mut s = session(None);
|
||||
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
|
||||
assert_all(colours(&s, comps), GREY);
|
||||
write(&lut, WHITE, 1_000);
|
||||
assert_all(colours(&s, comps), 1.0);
|
||||
std::fs::remove_file(&lut).unwrap();
|
||||
assert_all(colours(&s, comps), GREY);
|
||||
write(&lut, "not a LUT", 2_000);
|
||||
assert_all(colours(&s, comps), GREY);
|
||||
write(&lut, BLACK, 3_000);
|
||||
assert_all(colours(&s, comps), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lumetri_follows_its_input_lut_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lut = dir.path().join("input.cube");
|
||||
write(&lut, BLACK, 1_000);
|
||||
let mut s = session(None);
|
||||
let comps = shot(&mut s, "Lumetri Color", &[("basicCorrection/inputLut", json!(1)), ("basicCorrection/inputLutFile", json!(lut.to_string_lossy()))]);
|
||||
assert_all(colours(&s, comps), 0.0);
|
||||
write(&lut, WHITE, 2_000);
|
||||
assert_all(colours(&s, comps), 1.0);
|
||||
}
|
||||
|
||||
/// A precomp instance whose Essential Property names another LUT file follows that file, also
|
||||
/// for a layer that reads the instance through a layer parameter.
|
||||
#[test]
|
||||
fn an_overridden_lut_file_renders_again() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (base, overridden) = (dir.path().join("base.cube"), dir.path().join("override.cube"));
|
||||
write(&base, WHITE, 1_000);
|
||||
write(&overridden, BLACK, 1_000);
|
||||
let mut s = session(None);
|
||||
s.execute_checked("comp.new", json!({"name": "Grade", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
|
||||
let grade = s.active_comp_id().unwrap();
|
||||
let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone();
|
||||
s.execute_checked("effect.apply", json!({"layer": plate, "effect": "Apply Color LUT"})).unwrap();
|
||||
s.execute_checked("prop.set", json!({"layer": plate, "path": "effects/#1/lut", "value": base.to_string_lossy()})).unwrap();
|
||||
let control = s.execute_checked("essential.addProperty", json!({"layer": plate, "path": "effects/#1/lut", "name": "LUT"})).unwrap()["controls"][0].clone();
|
||||
s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
|
||||
let shot = s.active_comp_id().unwrap();
|
||||
let instance = s.execute_checked("layer.addItem", json!({"item": grade.0})).unwrap()["layer"].clone();
|
||||
s.execute_checked("essential.set", json!({"layer": instance, "control": control, "value": overridden.to_string_lossy()})).unwrap();
|
||||
let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone();
|
||||
s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap();
|
||||
for i in 1..=3 {
|
||||
s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": instance})).unwrap();
|
||||
}
|
||||
let centre = |s: &Session| {
|
||||
let img = s.render(shot, Tick::ZERO, RenderOpts::default());
|
||||
let p = img.get(i64::from(img.width / 2), i64::from(img.height / 2));
|
||||
[p[0], p[1], p[0], p[1]]
|
||||
};
|
||||
assert_all(centre(&s), 0.0);
|
||||
write(&overridden, WHITE, 2_000);
|
||||
assert_all(centre(&s), 1.0);
|
||||
}
|
||||
|
||||
/// #3538: OCIO File Transform and a custom OCIO config (and the LUT it names) follow their files
|
||||
/// through warm layer caches, and a render notes the config's LUT for the disk cache.
|
||||
#[test]
|
||||
fn ocio_files_render_again_from_warm_caches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube"));
|
||||
std::fs::create_dir_all(dir.path().join("luts")).unwrap();
|
||||
write(&lut, BLACK, 1_000);
|
||||
write(&grade, BLACK, 1_000);
|
||||
let text = "ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !<ColorSpace>\n name: lin\n - !<ColorSpace>\n name: graded\n to_reference: !<FileTransform> {src: grade.cube, interpolation: linear}\n";
|
||||
write(&config, text, 1_000);
|
||||
let mut s = session(None);
|
||||
let file = shot(&mut s, "OCIO File Transform", &[("file", json!(lut.to_string_lossy()))]);
|
||||
let custom = shot(
|
||||
&mut s,
|
||||
"OCIO Color Space Transform",
|
||||
&[("config", json!(1)), ("configFile", json!(config.to_string_lossy())), ("sourceName", json!("graded")), ("destinationName", json!("lin"))],
|
||||
);
|
||||
// A render notes the LUT the config names (a frame on disk is made of it too).
|
||||
let log = ReadLog::new();
|
||||
let mut r = s.renderer(RenderOpts::default());
|
||||
r.reads = Some(&log);
|
||||
let _ = r.comp_frame(custom.1, Tick::ZERO);
|
||||
let files = log.into_files();
|
||||
assert!(files.get(&grade.to_string_lossy()).is_some(), "the render notes the config's LUT: {files:?}");
|
||||
assert_all(colours(&s, file), 0.0);
|
||||
assert_all(colours(&s, custom), 0.0);
|
||||
let misses = s.layer_cache.stats().misses;
|
||||
assert_all(colours(&s, file), 0.0);
|
||||
assert_all(colours(&s, custom), 0.0);
|
||||
assert_eq!(s.layer_cache.stats().misses, misses, "unchanged files keep the cached layers");
|
||||
let generation = effectcraft_effects::lut_generation();
|
||||
write(&lut, WHITE, 2_000);
|
||||
assert_all(colours(&s, file), 1.0);
|
||||
write(&grade, WHITE, 2_000);
|
||||
assert_all(colours(&s, custom), 1.0);
|
||||
assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped");
|
||||
}
|
||||
@@ -391,6 +391,15 @@ fn warp_analysis_invalidates_and_cancels() {
|
||||
let fx = r["effect"].as_u64().unwrap();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true);
|
||||
// A mask is part of the analysed input (#3535): drawing one clears the analysis, undo keeps it.
|
||||
s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap();
|
||||
assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], false);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true);
|
||||
// An effect below it isn't.
|
||||
s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap();
|
||||
assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true);
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
// Trimming the layer clears the analysis and queues it again.
|
||||
s.execute("layer.timing", json!({"layers": [clip.0], "out": 0.8})).unwrap();
|
||||
let st = s.execute("warp.status", json!({})).unwrap();
|
||||
|
||||
@@ -96,6 +96,25 @@ fn imported_files_go_into_the_comp_where_they_were_dropped() {
|
||||
assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y");
|
||||
}
|
||||
|
||||
/// What an import left out of a file (a 3D model's textures over the limits) comes back in the
|
||||
/// import's `warnings`.
|
||||
#[test]
|
||||
fn what_an_import_left_out_is_a_warning() {
|
||||
use effectcraft_project::{Footage, FootageKind};
|
||||
struct Probe;
|
||||
impl crate::Importer for Probe {
|
||||
fn probe(&self, path: &str) -> Result<Footage, String> {
|
||||
Ok(Footage { path: path.into(), kind: FootageKind::Model, ..Default::default() })
|
||||
}
|
||||
fn probe_noting(&self, path: &str) -> Result<(Footage, Option<String>), String> {
|
||||
Ok((self.probe(path)?, Some(format!("{path}: texture `a.png` left out"))))
|
||||
}
|
||||
}
|
||||
let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() };
|
||||
let r = s.execute("file.import", json!({"paths": ["/m/scene.obj"]})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(["/m/scene.obj: texture `a.png` left out"]));
|
||||
}
|
||||
|
||||
/// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in
|
||||
/// a background job that says which file it is reading and how many are left; then they arrive
|
||||
/// in one undo step, all selected, with a count. The same file imported again arrives again.
|
||||
|
||||
@@ -1581,3 +1581,28 @@ fn a_typed_component_moves_its_follow_components_by_each_layers_own_change() {
|
||||
let keys: Vec<Vec<f64>> = prop(&s, b, "audio/levels").keys.iter().map(|k| k.value.components()).collect();
|
||||
assert_eq!(keys, vec![vec![-20.0, -30.0], vec![-4.0, -34.0]], "B's 1 s key rises 6 dB on both channels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_expression_to_keyframes_refuses_a_layer_of_millions_of_frames() {
|
||||
let (mut s, l) = setup();
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap();
|
||||
// A saved Out point a million seconds after the In point.
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().out_point =
|
||||
effectcraft_time::Tick::from_seconds_f64(1e6);
|
||||
let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string();
|
||||
assert!(e.contains("at most"), "{e}");
|
||||
assert!(prop(&s, l, "transform/rotation").keys.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_expression_to_keyframes_refuses_a_zero_frame_duration() {
|
||||
let (mut s, l) = setup();
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap();
|
||||
// A saved frame rate of 0/1 s has a frame duration of 0: the sampling loop never advanced.
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().frame_rate.den = 0;
|
||||
let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string();
|
||||
assert!(e.contains("frame duration"), "{e}");
|
||||
assert!(prop(&s, l, "transform/rotation").keys.is_empty());
|
||||
}
|
||||
|
||||
@@ -320,6 +320,41 @@ fn paste_svg_markup_as_a_shape_layer() {
|
||||
assert_eq!(s.active_comp().unwrap().layers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_svg_pattern_keeps_geometry_and_editable_fallback_paint() {
|
||||
let (mut s, _) = text_session();
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
|
||||
<defs><pattern id="p" patternUnits="userSpaceOnUse" width="4" height="4">
|
||||
<circle cx="2" cy="2" r="1" fill="red"/>
|
||||
</pattern></defs>
|
||||
<rect id="patterned" width="16" height="6" fill="url(#p) rgba(255, 0, 0, 0.5)"/>
|
||||
<path id="patterned-stroke" d="M0 8 H16" fill="none" stroke="url(#p) rgba(0, 0, 255, 0.25)" stroke-width="2"/>
|
||||
<rect id="patterned-no-fallback" y="10" width="16" height="6" fill="url(#p)"/>
|
||||
<path id="patterned-stroke-no-fallback" d="M0 15 H16" fill="none" stroke="url(#p)" stroke-width="2"/>
|
||||
</svg>"##;
|
||||
let result = s.execute_checked("edit.pasteSvg", json!({"svg": svg})).unwrap();
|
||||
let layer_id = effectcraft_project::LayerId(result["layer"].as_u64().unwrap());
|
||||
let layer = s.active_comp().unwrap().layer(layer_id).unwrap();
|
||||
let shape = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned").unwrap();
|
||||
let items: Vec<_> = shape.sub("contents").unwrap().groups().collect();
|
||||
assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains");
|
||||
let fill = items.iter().find(|item| item.match_id == "fill").expect("fallback fill remains editable");
|
||||
assert_eq!(fill.get("color").unwrap().value, KV::Color([1.0, 0.0, 0.0, 0.5]));
|
||||
let stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke").unwrap();
|
||||
let items: Vec<_> = stroke.sub("contents").unwrap().groups().collect();
|
||||
assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke path remains");
|
||||
let stroke = items.iter().find(|item| item.match_id == "stroke").expect("fallback stroke remains editable");
|
||||
assert_eq!(stroke.get("color").unwrap().value, KV::Color([0.0, 0.0, 1.0, 0.25]));
|
||||
let no_fallback = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-no-fallback").unwrap();
|
||||
let items: Vec<_> = no_fallback.sub("contents").unwrap().groups().collect();
|
||||
assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains without a fallback");
|
||||
assert!(!items.iter().any(|item| item.match_id == "fill"), "pattern paint without a fallback is omitted");
|
||||
let no_fallback_stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke-no-fallback").unwrap();
|
||||
let items: Vec<_> = no_fallback_stroke.sub("contents").unwrap().groups().collect();
|
||||
assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke geometry remains without a fallback");
|
||||
assert!(!items.iter().any(|item| item.match_id == "stroke"), "pattern stroke without a fallback is omitted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_svg_rejects_text_that_is_not_usable_svg() {
|
||||
let (mut s, _) = text_session();
|
||||
|
||||
@@ -346,6 +346,263 @@ fn shape_path(s: &Session, lid: u64, uid: u64) -> effectcraft_keyframe::ShapePat
|
||||
l.props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_respects_path_and_vertex_selection() {
|
||||
let mut s = comp();
|
||||
let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let lid = a["layer"].as_u64().unwrap();
|
||||
let a = a["path"].as_u64().unwrap();
|
||||
let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["path"].as_u64().unwrap();
|
||||
let leaf = layer(&s, lid).props.find_group(a).unwrap().get("path").unwrap().uid;
|
||||
s.state.selected_vertices.clear();
|
||||
s.state.selected_props = vec![(LayerId(lid), leaf)];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, lid, a).closed);
|
||||
assert!(shape_path(&s, lid, b).closed, "an unselected sibling stays closed");
|
||||
s.state.selected_props = vec![(LayerId(lid), b)];
|
||||
s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: a, index: 1 }];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(shape_path(&s, lid, a).closed, "selected points and properties both describe target paths");
|
||||
assert!(shape_path(&s, lid, b).closed);
|
||||
s.state.selected_vertices.clear();
|
||||
s.state.selected_props = vec![(LayerId(lid), a), (LayerId(lid), leaf), (LayerId(lid), b)];
|
||||
let r = s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert_eq!(r["paths"], json!(2));
|
||||
assert!(!shape_path(&s, lid, a).closed);
|
||||
assert!(!shape_path(&s, lid, b).closed);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(shape_path(&s, lid, a).closed);
|
||||
assert!(shape_path(&s, lid, b).closed, "all paths undo in one step");
|
||||
s.execute("mask.setClosed", json!({"layer": lid, "mask": a, "closed": false})).unwrap();
|
||||
assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false), "a mixed selection is unchecked");
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(shape_path(&s, lid, a).closed);
|
||||
assert!(shape_path(&s, lid, b).closed, "a mixed selection closes all paths");
|
||||
s.state.selected_props.clear();
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, lid, a).closed);
|
||||
assert!(!shape_path(&s, lid, b).closed, "layer selection addresses all editable paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_combines_property_and_shape_group_selections() {
|
||||
let mut s = comp();
|
||||
let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let (lid, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap());
|
||||
let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap();
|
||||
let (b_path, b_group) = (b["path"].as_u64().unwrap(), b["group"].as_u64().unwrap());
|
||||
let c_path =
|
||||
s.execute("shape.newPath", json!({"layer": lid, "vertices": [[20, 20], [80, 20], [80, 80]], "closed": true})).unwrap()["path"].as_u64().unwrap();
|
||||
s.execute("prop.select", json!({"layer": lid, "prop": a_path})).unwrap();
|
||||
s.execute("prop.select", json!({"layer": lid, "prop": b_group, "add": true})).unwrap();
|
||||
assert!(s.state.selected_vertices.iter().all(|v| v.mask == a_path), "only the selected path group implies selected vertices");
|
||||
assert!(!s.state.selected_vertices.is_empty());
|
||||
assert!(s.state.selected_props.contains(&(LayerId(lid), b_group)));
|
||||
let result = s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert_eq!(result["paths"], json!(2));
|
||||
assert!(!shape_path(&s, lid, a_path).closed);
|
||||
assert!(!shape_path(&s, lid, b_path).closed, "the added shape group is included alongside implied vertices");
|
||||
assert!(shape_path(&s, lid, c_path).closed, "unselected sibling stays unchanged");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(shape_path(&s, lid, a_path).closed);
|
||||
assert!(shape_path(&s, lid, b_path).closed, "both selected paths undo together");
|
||||
assert!(shape_path(&s, lid, c_path).closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_ignores_selections_retained_on_other_layers() {
|
||||
let mut s = comp();
|
||||
let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let (a_layer, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap());
|
||||
let b_layer = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap();
|
||||
assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(a_layer)), "insertion retains old vertices");
|
||||
assert!(!s.is_enabled("path.toggleClosed"));
|
||||
assert!(s.execute("path.toggleClosed", json!({})).is_err());
|
||||
assert!(shape_path(&s, a_layer, a_path).closed);
|
||||
|
||||
let b_path =
|
||||
s.execute("shape.newPath", json!({"layer": b_layer, "vertices": [[0, 0], [50, 0], [50, 50]], "closed": true})).unwrap()["path"].as_u64().unwrap();
|
||||
s.execute("prop.select", json!({"layer": b_layer, "prop": b_path})).unwrap();
|
||||
s.execute("layer.selectNext", json!({})).unwrap();
|
||||
assert_eq!(s.state.selected_layers, vec![LayerId(a_layer)]);
|
||||
assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(b_layer)), "navigation retains old vertices");
|
||||
assert!(s.state.selected_props.contains(&(LayerId(b_layer), b_path)));
|
||||
assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true));
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, a_layer, a_path).closed);
|
||||
assert!(shape_path(&s, b_layer, b_path).closed, "the deselected layer stays unchanged");
|
||||
s.execute("layer.selectPrevious", json!({})).unwrap();
|
||||
assert_eq!(s.state.selected_layers, vec![LayerId(b_layer)]);
|
||||
s.execute("prop.select", json!({"layer": b_layer, "path": "transform/position"})).unwrap();
|
||||
assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true), "a non-path property falls back to the layer's paths");
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, b_layer, b_path).closed);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("layer.selectNext", json!({})).unwrap();
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(shape_path(&s, a_layer, a_path).closed, "a property retained on another layer cannot block this layer");
|
||||
assert!(shape_path(&s, b_layer, b_path).closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_falls_back_from_stale_selection_and_rejects_locked_or_pathless_layers() {
|
||||
let mut s = comp();
|
||||
let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap());
|
||||
let before = s.project.clone();
|
||||
s.state.selected_vertices.clear();
|
||||
s.state.selected_props = vec![(LayerId(lid), u64::MAX)];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, lid, uid).closed, "a stale property selection falls back to the layer's paths");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.project.same_content(&before));
|
||||
s.state.selected_props.clear();
|
||||
s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: uid, index: usize::MAX }];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!shape_path(&s, lid, uid).closed, "a stale vertex selection falls back to the layer's paths");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.state.selected_vertices.clear();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().switches.locked = true;
|
||||
assert!(!s.is_enabled("path.toggleClosed"));
|
||||
assert!(s.execute("path.toggleClosed", json!({})).is_err());
|
||||
assert!(shape_path(&s, lid, uid).closed);
|
||||
s.execute("layer.newShape", json!({"kind": "rect"})).unwrap();
|
||||
s.state.selected_props.clear();
|
||||
assert!(!s.is_enabled("path.toggleClosed"));
|
||||
assert!(s.execute("path.toggleClosed", json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() {
|
||||
let mut s = comp();
|
||||
let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap();
|
||||
let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone();
|
||||
let original = path(&s);
|
||||
let other = s.execute("mask.new", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["mask"].as_u64().unwrap();
|
||||
let other_closed = |s: &Session| layer(s, lid).props.find_group(other).unwrap().get("path").unwrap().value.as_path().unwrap().closed;
|
||||
let feather = layer(&s, lid).props.find_group(uid).unwrap().get("feather").unwrap().uid;
|
||||
s.state.selected_vertices.clear();
|
||||
s.state.selected_props = vec![(LayerId(lid), feather)];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert!(!path(&s).closed, "selecting Mask Feather selects its mask");
|
||||
assert!(other_closed(&s), "an unselected mask stays closed");
|
||||
assert!(layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().keys.is_empty(), "a static path gains no keyframe");
|
||||
s.state.selected_props = vec![(LayerId(lid), uid)];
|
||||
s.execute("mask.setClosed", json!({"layer": lid, "mask": uid})).unwrap();
|
||||
assert_eq!(path(&s), original, "explicit API still defaults to closed");
|
||||
s.execute("mask.setClosed", json!({"layer": lid, "mask": uid, "closed": false})).unwrap();
|
||||
assert!(!path(&s).closed);
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert_eq!(path(&s), original);
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let g = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().props.find_group_mut(uid).unwrap();
|
||||
if let effectcraft_project::GroupKind::Mask { locked, .. } = &mut g.kind {
|
||||
*locked = true;
|
||||
}
|
||||
assert!(!s.is_enabled("path.toggleClosed"));
|
||||
assert!(s.execute("path.toggleClosed", json!({})).is_err());
|
||||
assert_eq!(path(&s), original);
|
||||
assert!(other_closed(&s), "a selected locked mask does not fall back to its unlocked siblings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_recomputes_roto_bezier_tangents() {
|
||||
let mut s = comp();
|
||||
let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let uid =
|
||||
s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap();
|
||||
s.execute("path.rotoBezier", json!({"layer": lid, "value": true})).unwrap();
|
||||
let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone();
|
||||
let closed = path(&s);
|
||||
assert_ne!(closed.out_tangents[0], [0.0; 2], "a closed RotoBezier path has tangents at every vertex");
|
||||
s.state.selected_props = vec![(LayerId(lid), uid)];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
let open = path(&s);
|
||||
assert!(!open.closed);
|
||||
assert_eq!((open.in_tangents[0], open.out_tangents[3]), ([0.0; 2], [0.0; 2]), "open ends lose their automatic tangents");
|
||||
assert_ne!(open.out_tangents[1], [0.0; 2]);
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
assert_eq!(path(&s), closed, "reclosing restores the closed RotoBezier tangents");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_fits_short_tangent_lists() {
|
||||
let mut s = comp();
|
||||
let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let layer_mut = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap();
|
||||
let prop = layer_mut.props.find_group_mut(uid).unwrap().get_mut("path").unwrap();
|
||||
let KV::Path(path) = &mut prop.value else { panic!("not a path") };
|
||||
// A file can store fewer tangents than vertices (#1250).
|
||||
path.in_tangents.clear();
|
||||
path.out_tangents.truncate(1);
|
||||
s.state.selected_props = vec![(LayerId(lid), uid)];
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
let path = layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone();
|
||||
assert!(!path.closed);
|
||||
assert_eq!((path.in_tangents.len(), path.out_tangents.len()), (3, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_edits_layer_time_and_roundtrips() {
|
||||
use effectcraft_keyframe::Keyframe;
|
||||
let mut s = comp();
|
||||
let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap());
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let original = shape_path(&s, lid, uid);
|
||||
let second = Tick::from_seconds_f64(1.0);
|
||||
let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap();
|
||||
layer.start_time = second;
|
||||
layer.stretch = 200.0;
|
||||
let prop = layer.props.find_group_mut(uid).unwrap().get_mut("path").unwrap();
|
||||
prop.keys = vec![Keyframe::new(Tick::ZERO, KV::Path(original.clone())), Keyframe::new(second, KV::Path(original.clone()))];
|
||||
let keys = prop.keys.clone();
|
||||
s.execute("time.set", json!({"time": 3.0})).unwrap();
|
||||
s.execute("path.toggleClosed", json!({})).unwrap();
|
||||
let prop = s.project.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap();
|
||||
assert_eq!(prop.keys.len(), 2);
|
||||
assert_eq!(prop.keys[0], keys[0], "the other keyframe is untouched");
|
||||
let mut opened = original;
|
||||
opened.closed = false;
|
||||
assert_eq!(prop.value_at(second), KV::Path(opened.clone()));
|
||||
assert!(prop.value_at(Tick::from_seconds_f64(0.5)).as_path().unwrap().closed, "the earlier segment keeps its closedness");
|
||||
let bytes = serde_json::to_vec(&*s.project).unwrap();
|
||||
let restored: effectcraft_project::Project = serde_json::from_slice(&bytes).unwrap();
|
||||
let prop = restored.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap();
|
||||
assert_eq!(prop.value_at(second), KV::Path(opened));
|
||||
s.execute("time.set", json!({"time": 2.0})).unwrap();
|
||||
assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true));
|
||||
s.execute("time.set", json!({"time": 3.0})).unwrap();
|
||||
assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_closed_rejects_excessive_group_nesting_without_an_edit() {
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
let mut s = comp();
|
||||
let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap();
|
||||
let lid = LayerId(r["layer"].as_u64().unwrap());
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let project = std::sync::Arc::make_mut(&mut s.project);
|
||||
let mut next = project.next_id;
|
||||
let contents = project.comp_mut(cid).unwrap().layer_mut(lid).unwrap().props.sub_mut("contents").unwrap();
|
||||
let node = contents.children.first_mut().unwrap();
|
||||
let mut nested = node.as_group().unwrap().clone();
|
||||
for _ in 0..130 {
|
||||
nested = build::shape_group(&mut Ids(&mut next), "Nested", vec![nested]);
|
||||
}
|
||||
*node = effectcraft_project::Node::Group(nested);
|
||||
project.next_id = next;
|
||||
let before = s.project.clone();
|
||||
assert!(!s.is_enabled("path.toggleClosed"));
|
||||
assert!(s.execute("path.toggleClosed", json!({})).is_err());
|
||||
assert!(s.project.same_content(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_pen_builds_shape_group_and_renders() {
|
||||
let mut s = comp();
|
||||
|
||||
@@ -321,7 +321,7 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>)
|
||||
let mut i = 0;
|
||||
while i < st.total {
|
||||
let end = (i + batch).min(st.total);
|
||||
let ks: Vec<u64> = (i..end).filter(|k| !(cx.settings.skip_existing && out::exists(cx.sink, &sequence_path(cx.path, f0 + *k as i64)))).collect();
|
||||
let ks: Vec<u64> = (i..end).filter(|k| !(cx.settings.skip_existing && cx.frame_exists(&sequence_path(cx.path, f0 + *k as i64)))).collect();
|
||||
let written: Vec<Result<u64>> = cx
|
||||
.frames(comp, ks, |k, img| {
|
||||
let path = sequence_path(cx.path, f0 + k as i64);
|
||||
|
||||
@@ -894,6 +894,20 @@ impl<'a> Cx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Skip Existing finds `path` already written: at its own place or, with Use Storage
|
||||
/// Overflow, in any overflow folder (checked before a frame is placed, so a skipped frame
|
||||
/// reserves no quota).
|
||||
pub fn frame_exists(&self, path: &str) -> bool {
|
||||
if out::exists(self.sink, path) {
|
||||
return true;
|
||||
}
|
||||
if !self.job.settings.storage_overflow {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = std::path::Path::new(path).file_name() else { return false };
|
||||
self.job.options.overflow.iter().any(|dir| out::exists(self.sink, &std::path::Path::new(dir).join(name).to_string_lossy()))
|
||||
}
|
||||
|
||||
/// Where a file goes: `path`, or (Use Storage Overflow) the first overflow folder with room
|
||||
/// for `bytes` when the quota hook says the output volume is full.
|
||||
pub fn place(&self, path: &str, bytes: u64) -> String {
|
||||
|
||||
@@ -444,6 +444,54 @@ fn cancelled_export_removes_only_files_it_opened() {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Skip Existing keeps a frame that is already in the overflow folder the frame is placed in
|
||||
/// (it checked only the primary destination, then truncated the overflow file).
|
||||
#[test]
|
||||
fn skip_existing_keeps_a_frame_in_the_overflow_folder() {
|
||||
use std::path::PathBuf;
|
||||
// Room only in the second overflow folder; the frame already sits in the first (which is full).
|
||||
struct Overflow(PathBuf);
|
||||
impl StorageQuota for Overflow {
|
||||
fn has_room(&self, path: &str, _: u64) -> bool {
|
||||
std::path::Path::new(path).starts_with(&self.0)
|
||||
}
|
||||
}
|
||||
let guard = tempfile::tempdir().unwrap();
|
||||
let (dir, full, over) = (guard.path().to_path_buf(), guard.path().join("full"), guard.path().join("over"));
|
||||
std::fs::create_dir_all(&full).unwrap();
|
||||
std::fs::create_dir_all(&over).unwrap();
|
||||
std::fs::write(full.join("clip_00000.png"), b"keep").unwrap();
|
||||
let quota = Overflow(over.clone());
|
||||
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
|
||||
let settings = RenderSettings { skip_existing: true, storage_overflow: true, ..Default::default() };
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let path = dir.join("clip_[#####].png");
|
||||
let result = export(
|
||||
&Job {
|
||||
project: &p,
|
||||
footage: &NoFootage,
|
||||
expr: None,
|
||||
accel: None,
|
||||
comp: cid,
|
||||
settings: &settings,
|
||||
output: &om,
|
||||
path: path.to_str().unwrap(),
|
||||
sink: None,
|
||||
nested_switches: true,
|
||||
options: JobOptions {
|
||||
storage: Some("a),
|
||||
overflow: vec![full.to_string_lossy().into_owned(), over.to_string_lossy().into_owned()],
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
&mut |_| true,
|
||||
);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(std::fs::read(full.join("clip_00000.png")).unwrap(), b"keep");
|
||||
assert!(!over.join("clip_00000.png").exists(), "no duplicate in another overflow folder");
|
||||
assert!(over.join("clip_00001.png").exists(), "the other frames are still written");
|
||||
}
|
||||
|
||||
/// A GPU compositor stand-in that renders every frame solid green (the CPU draws the bar and the
|
||||
/// block on black) and keeps Auto's timing history.
|
||||
#[derive(Default)]
|
||||
|
||||
+53
-11
@@ -9,7 +9,8 @@
|
||||
|
||||
use effectcraft_geom::{Mat3, Mat4};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property};
|
||||
use effectcraft_project::ae_order::{self, AeChild};
|
||||
use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property};
|
||||
use effectcraft_render::EvalCtx;
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
@@ -272,6 +273,19 @@ fn node_resp(path: String, n: &Node, index: usize) -> Resp {
|
||||
])
|
||||
}
|
||||
|
||||
/// A top-level slot the layer has no node for, as group data: `@marker` (the markers, built by the
|
||||
/// prelude) or `@absent` (an empty group, as After Effects shows an unused slot).
|
||||
fn slot_resp(path: &str, s: &ae_order::AeSlot, index: usize) -> Resp {
|
||||
Resp::List(vec![
|
||||
Resp::Str(path.into()),
|
||||
Resp::Bool(true),
|
||||
Resp::Str(s.name.into()),
|
||||
Resp::Str(s.match_name.into()),
|
||||
Resp::Num(0.0),
|
||||
Resp::Num(index as f64),
|
||||
])
|
||||
}
|
||||
|
||||
fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
|
||||
match key {
|
||||
Key::Index(i) => usize::try_from(*i).ok().filter(|i| *i >= 1).and_then(|i| g.children.get(i - 1)),
|
||||
@@ -283,6 +297,9 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
|
||||
.find(|n| n.match_id() == m)
|
||||
.or_else(|| g.children.iter().find(|n| n.name().eq_ignore_ascii_case(name)))
|
||||
.or_else(|| g.children.iter().find(|n| compact(n.name()) == c || compact(n.match_id()) == c))
|
||||
// An effect by its After Effects match name, an imported placeholder's effect id
|
||||
// (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`).
|
||||
.or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -348,7 +365,36 @@ impl<'a> Resolver<'a> {
|
||||
let uid = segs.get(keep - 1)?.strip_prefix('@')?.parse::<u64>().ok()?;
|
||||
let index = parent.children.iter().position(|c| c.uid() == uid)?;
|
||||
let n = parent.children.get(index)?;
|
||||
Some(node_resp(group_path, n, index + 1))
|
||||
// A top-level group's number is After Effects' (see `ae_order`).
|
||||
let number = if keep == 1 { ae_order::ae_index(l, n.match_id()) } else { None }.unwrap_or(index + 1);
|
||||
Some(node_resp(group_path, n, number))
|
||||
}
|
||||
|
||||
/// A child of a layer (`group` empty) or of one of its groups, by name or 1-based number.
|
||||
fn child(&self, comp: u64, layer: u64, group: &str, key: &Key) -> Option<Resp> {
|
||||
let l = self.layer(comp, layer)?;
|
||||
// A layer's numbers are After Effects' (Marker is 1, unused groups keep their slot), and so
|
||||
// are its match names (`thisLayer("ADBE Effect Parade")`, as scripts such as Karton write).
|
||||
let slot = match key {
|
||||
Key::Index(i) => usize::try_from(*i).ok(),
|
||||
Key::Name(name) => ae_order::ae_index_of_match_name(l, name),
|
||||
};
|
||||
if group.is_empty()
|
||||
&& ae_order::ae_slots(&l.source).is_some()
|
||||
&& let Some(i) = slot
|
||||
{
|
||||
return Some(match ae_order::ae_child(l, i)? {
|
||||
AeChild::Node(n) => node_resp(format!("@{}", n.uid()), n, i),
|
||||
AeChild::Marker => slot_resp("@marker", &ae_order::MARKER, 1),
|
||||
AeChild::Absent(s) => slot_resp("@absent", s, i),
|
||||
});
|
||||
}
|
||||
let g = if group.is_empty() { &l.props } else { l.props.group(group)? };
|
||||
let n = find_child(g, key)?;
|
||||
let index = if group.is_empty() { ae_order::ae_index(l, n.match_id()) } else { None }
|
||||
.unwrap_or_else(|| g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1);
|
||||
let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) };
|
||||
Some(node_resp(path, n, index))
|
||||
}
|
||||
|
||||
fn try_resolve(&self, req: &Req) -> Option<Resp> {
|
||||
@@ -403,14 +449,7 @@ impl<'a> Resolver<'a> {
|
||||
Resp::Bool(l.switches.video),
|
||||
])
|
||||
}
|
||||
Req::Child { comp, layer, group, key } => {
|
||||
let l = self.layer(*comp, *layer)?;
|
||||
let g = if group.is_empty() { &l.props } else { l.props.group(group)? };
|
||||
let n = find_child(g, key)?;
|
||||
let index = g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1;
|
||||
let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) };
|
||||
node_resp(path, n, index)
|
||||
}
|
||||
Req::Child { comp, layer, group, key } => return self.child(*comp, *layer, group, key),
|
||||
Req::Ancestor { comp, layer, path, up } => return self.ancestor(*comp, *layer, path, *up),
|
||||
Req::PropInfo { comp, layer, path } => {
|
||||
let (l, p) = self.prop(*comp, *layer, path)?;
|
||||
@@ -423,7 +462,10 @@ impl<'a> Resolver<'a> {
|
||||
Some(g) => l.props.group(g)?,
|
||||
None => &l.props,
|
||||
};
|
||||
g.children.iter().position(|n| format!("@{}", n.uid()) == last).map(|i| i + 1)
|
||||
let i = g.children.iter().position(|n| format!("@{}", n.uid()) == last)?;
|
||||
// A top-level property (an enabled Time Remap) has After Effects' number.
|
||||
let top = if parent.is_none() { g.children.get(i).and_then(|n| ae_order::ae_index(l, n.match_id())) } else { None };
|
||||
Some(top.unwrap_or(i + 1))
|
||||
});
|
||||
Resp::List(vec![
|
||||
Resp::Str(p.name.clone()),
|
||||
|
||||
@@ -495,6 +495,8 @@ function __mod(a, d) { return ((a % d) + d) % d; }
|
||||
function __child(c, l, group, key) {
|
||||
var info = __h(__CHILD, c, l, group, key);
|
||||
if (info === null) return undefined;
|
||||
// `thisLayer(1)` is the layer's markers, as in After Effects (see `ae_order`).
|
||||
if (group === '' && info[0] === '@marker') return new Markers(c, l);
|
||||
return info[1] ? __mkGroup(c, l, info) : __mkProp(c, l, info[0]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1376,6 +1376,28 @@ fn checkbox_and_dropdown_results() {
|
||||
assert_close!(f.ev(f.b, ROT, "effect('Dropdown Menu Control')('Menu') * 10", 0.0).unwrap().as_f64(), 10.0);
|
||||
}
|
||||
|
||||
/// An effect EffectCraft does not have (an imported After Effects placeholder, #3087) is read by
|
||||
/// name like any other: its parameters by their names, a popup 1-based. It is also found by its
|
||||
/// After Effects match name, its effect id (the group's match id is one path segment).
|
||||
#[test]
|
||||
fn an_unknown_effects_parameters_are_read_by_name() {
|
||||
let mut f = fx();
|
||||
let g = group_push(&mut f.p, |ids| {
|
||||
let mut g = ids.group("Pseudo_0_25", "Settings");
|
||||
g.kind = effectcraft_project::GroupKind::Effect { effect: "Pseudo/0.25".into() };
|
||||
g.children.push(ids.prop("param1", "Speed", Value::Scalar(3.0)).into());
|
||||
g.children.push(ids.prop("param2", "Mode", Value::Enum(1)).into());
|
||||
g
|
||||
});
|
||||
f.layer_mut(f.b).props.sub_mut("effects").unwrap().children.push(g.into());
|
||||
assert_close!(f.ev(f.b, ROT, "effect('Settings')('Speed') * 2", 0.0).unwrap().as_f64(), 6.0);
|
||||
assert_close!(f.ev(f.b, ROT, "effect('Settings')('Mode') * 10", 0.0).unwrap().as_f64(), 20.0);
|
||||
assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0);
|
||||
assert_close!(f.ev(f.b, ROT, "effect('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
|
||||
assert_close!(f.ev(f.b, ROT, "thisLayer('Effects')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
|
||||
assert_close!(f.ev(f.b, ROT, "thisLayer('ADBE Effect Parade')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_error_reports_line() {
|
||||
let f = fx();
|
||||
@@ -2025,6 +2047,7 @@ fn an_expression_cant_change_the_prelude_for_the_next() {
|
||||
}
|
||||
}
|
||||
|
||||
mod ae_layer_order;
|
||||
mod property_group;
|
||||
|
||||
/// Timing harness for the prelude's cost on the evaluation path. Ignored: it is a measurement, not
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! A layer's top-level numbers are After Effects' (`project::ae_order`): Marker is 1, and slots the
|
||||
//! layer does not use (Time Remap, Motion Trackers, Layer Styles…) keep their place. Rigs that read
|
||||
//! a palette by number, such as `comp("Palette").layer(1)(4)(n)(1)` on a shape layer, failed
|
||||
//! silently before: `(4)` reached Transform, the expression's `try` fell back to the stored value and
|
||||
//! every linked colour rendered near-black.
|
||||
|
||||
use super::*;
|
||||
use effectcraft_project::Property;
|
||||
|
||||
/// The fixture with a Slider Control (value 7) on layer "Shape".
|
||||
fn with_shape_slider() -> Fx {
|
||||
let mut f = fx();
|
||||
let spec = effectcraft_effects::find("ec.control.slider").unwrap();
|
||||
let mut slider = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Swatch 1", [20.0, 20.0]));
|
||||
slider.prop_mut("slider").unwrap().value = Value::Scalar(7.0);
|
||||
f.layer_mut(f.shape).props.sub_mut("effects").unwrap().children.push(slider.into());
|
||||
f
|
||||
}
|
||||
|
||||
fn yes(f: &Fx, cond: &str) -> f64 {
|
||||
f.num(&format!("({cond}) ? 1 : 0"), 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_by_number_on_a_shape_layer_is_four() {
|
||||
let f = with_shape_slider();
|
||||
// The Ray Dynamic Color lookup: layer(1)(4)(swatch)(1).
|
||||
assert_close!(f.num("thisComp.layer('Shape')(4)(1)(1)", 0.0), 7.0);
|
||||
assert_close!(f.num("try { thisComp.layer('Shape')(4)(1)(1) } catch (e) { -1 }", 0.0), 7.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_by_number_on_a_solid_is_five() {
|
||||
let f = fx();
|
||||
assert_close!(f.num("thisComp.layer('A')(5)(1)(1)", 0.0), 42.0);
|
||||
assert_close!(f.num("thisComp.layer('A')(5)('Slider Control')('Slider')", 0.0), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_level_names_follow_after_effects() {
|
||||
let f = fx();
|
||||
assert_close!(yes(&f, "thisComp.layer('A')(4).name == 'Masks'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('A')(5).name == 'Effects'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('A')(6).name == 'Transform'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('Shape')(2).name == 'Contents'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('Shape')(5).name == 'Transform'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('Title')(2).name == 'Text'"), 1.0);
|
||||
assert_close!(yes(&f, "thisComp.layer('Title')(4).name == 'Effects'"), 1.0);
|
||||
assert_close!(f.num("thisComp.layer('A')(6)('Position')[0]", 0.0), 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_is_the_markers() {
|
||||
let f = fx();
|
||||
assert_close!(f.num("thisComp.layer('A')(1).numKeys", 0.0), 2.0);
|
||||
assert_close!(f.num("thisComp.layer('A')(1).key(2).time", 0.0), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unused_slot_is_an_empty_group() {
|
||||
let f = fx();
|
||||
// Layer Styles (7) and Data (12) exist in After Effects before they are used.
|
||||
assert_close!(yes(&f, "thisComp.layer('A')(7).name == 'Layer Styles'"), 1.0);
|
||||
assert_close!(f.num("thisComp.layer('A')(12).numProperties", 0.0), 0.0);
|
||||
assert_close!(f.num("try { thisComp.layer('A')(12)(1); 1 } catch (e) { -1 }", 0.0), -1.0);
|
||||
// Past the last slot there is nothing.
|
||||
assert_close!(f.num("try { thisComp.layer('A')(16); 1 } catch (e) { -1 }", 0.0), -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_index_of_a_top_level_group_is_after_effects() {
|
||||
let f = fx();
|
||||
assert_close!(f.num("thisComp.layer('A').effect('Slider Control').propertyGroup(1).propertyIndex", 0.0), 5.0);
|
||||
assert_close!(f.num("thisComp.layer('A')('Transform').propertyIndex", 0.0), 6.0);
|
||||
assert_close!(f.num("thisComp.layer('Shape')('Contents').propertyIndex", 0.0), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_level_groups_by_after_effects_match_name() {
|
||||
// Karton's expressions: thisLayer("ADBE Effect Parade")("…").
|
||||
let f = with_shape_slider();
|
||||
assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade')('Slider Control')('Slider')", 0.0), 42.0);
|
||||
assert_close!(f.num("thisComp.layer('Shape')('ADBE Effect Parade')(1)(1)", 0.0), 7.0);
|
||||
assert_close!(f.num("thisComp.layer('A')('ADBE Transform Group')('Position')[0]", 0.0), 50.0);
|
||||
assert_close!(f.num("thisComp.layer('A')('ADBE Marker').numKeys", 0.0), 2.0);
|
||||
assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade').propertyIndex", 0.0), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_enabled_time_remap_is_number_two() {
|
||||
// Enabled Time Remap is a property at the top of the tree; After Effects numbers it 2.
|
||||
let mut f = fx();
|
||||
let uid = f.p.next_id;
|
||||
f.p.next_id += 1;
|
||||
f.layer_mut(f.a).props.children.insert(0, Property::new(uid, "timeRemap", "Time Remap", Value::Scalar(0.0)).into());
|
||||
assert_close!(f.num("thisComp.layer('A')('Time Remap').propertyIndex", 0.0), 2.0);
|
||||
assert_close!(f.num("thisComp.layer('A')(2).propertyIndex", 0.0), 2.0);
|
||||
}
|
||||
@@ -385,7 +385,7 @@ fn four_color(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
|
||||
p.f[4 + i] = ctx.params.color(&format!("positionsColors/color{}", i + 1));
|
||||
}
|
||||
let k = effectcraft_effects::four_color_softening(ctx.params.f("blend"), b.scale);
|
||||
let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let jitter = effectcraft_effects::four_color_jitter(ctx.params.f("jitter"));
|
||||
p.u[0] = [gen_mode(ctx.params.e("blendingMode")), ctx.seed, 0, 0];
|
||||
p.f[8] = [k as f32, jitter, ctx.params.f("opacity") as f32 / 100.0, 0.0];
|
||||
run(e, "gen_fourcolor", &p, b, None, None)
|
||||
|
||||
@@ -40,7 +40,16 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 {
|
||||
if (clip_w) {
|
||||
t = min(t, 1.0);
|
||||
}
|
||||
return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * fxt_gamma(t, max(data[o + 2u], 0.01));
|
||||
// color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. WGSL leaves an overflowing pow
|
||||
// indeterminate, so a curve past the bound saturates before pow: |t|^(1/g) > 1e30 once
|
||||
// log2|t| / g > 99.66; between 1e30 and 2^99.7 the clamp gives the same 1e30.
|
||||
// A branch, not select: select evaluates both sides, so pow would still run.
|
||||
let g = max(data[o + 2u], 0.01);
|
||||
var curve = sign(t) * 1e30;
|
||||
if (!(abs(t) > 1.0 && log2(abs(t)) / g > 99.7)) {
|
||||
curve = clamp(fxt_gamma(t, g), -1e30, 1e30);
|
||||
}
|
||||
return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve;
|
||||
}
|
||||
|
||||
// color_fx::level (data offset o: ib, iw, g, ob, ow, clip black, clip white).
|
||||
|
||||
@@ -38,6 +38,8 @@ fn twirl_bulge_ripple_wave_warp() {
|
||||
#[test]
|
||||
fn turbulent_displace_and_cc_lens() {
|
||||
effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0))]);
|
||||
// #3470: After Effects' maximum Random Seed.
|
||||
effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0)), ("evolutionOptions/randomSeed", n(100000.0))]);
|
||||
effect_case(
|
||||
"ec.distort.turbulentdisplace",
|
||||
&[("displacement", e(1)), ("complexity", n(3.5)), ("evolution", n(90.0)), ("size", n(25.0)), ("pinning", e(2)), ("resizeLayer", on())],
|
||||
|
||||
@@ -40,6 +40,8 @@ fn closed_form() {
|
||||
env_case("ec.generate.beam", &[]);
|
||||
env_case("ec.generate.beam", &[("length", n(70.0)), ("time", n(40.0)), ("softness", n(0.0)), ("perspective3d", off()), ("compositeOnOriginal", off())]);
|
||||
env_case("ec.generate.beam", &[("startThickness", n(3.0)), ("endThickness", n(20.0)), ("insideColor", c(0.3, 0.9, 1.0))]);
|
||||
// #3475: After Effects' maximum thickness.
|
||||
env_case("ec.generate.beam", &[("startThickness", n(0.0)), ("endThickness", n(4000.0))]);
|
||||
env_case("ec.generate.lensflare", &[]);
|
||||
env_case("ec.generate.lensflare", &[("lensType", e(1)), ("flareCenter", pt(50.0, 30.0)), ("blendWithOriginal", n(30.0))]);
|
||||
env_case("ec.generate.lensflare", &[("lensType", e(2)), ("flareBrightness", n(160.0))]);
|
||||
|
||||
@@ -83,6 +83,11 @@ fn wipes() {
|
||||
effect_case("ec.transition.radialwipe", &[("completion", n(45.0)), ("wipe", e(1)), ("center", pt(30.2, 19.6))]);
|
||||
effect_case("ec.transition.radialwipe", &[("completion", n(60.0)), ("wipe", e(2)), ("startAngle", n(-40.0)), ("feather", n(3.0))]);
|
||||
effect_case("ec.transition.radialwipe", &[("completion", n(0.0)), ("feather", n(20.0))]);
|
||||
// #3472-#3474: the ends of After Effects' ranges (a Feather wider than 8 blinds is the CPU's
|
||||
// even veil).
|
||||
effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(1.0)), ("feather", n(6.0))]);
|
||||
effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(32000.0)), ("feather", n(32000.0))]);
|
||||
effect_case("ec.transition.radialwipe", &[("completion", n(40.0)), ("feather", n(32000.0))]);
|
||||
effect_case("ec.transition.gradientwipe", &[("completion", n(40.0))]);
|
||||
effect_case("ec.transition.gradientwipe", &[("completion", n(55.0)), ("softness", n(30.0)), ("invert", b(true))]);
|
||||
effect_case("ec.transition.gradientwipe", &[("completion", n(100.0))]);
|
||||
@@ -147,6 +152,8 @@ fn generators() {
|
||||
);
|
||||
effect_case("ec.generate.checkerboard", &[("sizeFrom", e(0)), ("corner", pt(16.0, 11.0)), ("color", c(0.9, 0.3, 0.1)), ("blendingMode", e(1))]);
|
||||
effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(3.0))]);
|
||||
// #3476: a border wider than the cells (After Effects' maximum).
|
||||
effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(2000.0))]);
|
||||
effect_case(
|
||||
"ec.generate.grid",
|
||||
&[
|
||||
@@ -167,6 +174,8 @@ fn generators() {
|
||||
effect_case("ec.generate.fourcolor", &[]);
|
||||
effect_case("ec.generate.fourcolor", &[("blend", n(40.0)), ("jitter", n(50.0)), ("opacity", n(80.0)), ("blendingMode", e(3))]);
|
||||
effect_case("ec.generate.fourcolor", &[("blend", n(600.0)), ("blendingMode", e(16)), ("positionsColors/point2", pt(30.0, 20.0))]);
|
||||
// #3478, #3479: the top of After Effects' ranges.
|
||||
effect_case("ec.generate.fourcolor", &[("blend", n(10000.0)), ("jitter", n(500.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -164,6 +164,8 @@ fn noise_alpha_and_hls() {
|
||||
effect_case("ec.noise.noisehls", &[("hue", n(30.0)), ("lightness", n(20.0)), ("saturation", n(40.0))]);
|
||||
effect_case("ec.noise.noisehls", &[("noise", e(1)), ("lightness", n(50.0)), ("noisePhase", n(200.0))]);
|
||||
effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(60.0)), ("saturation", n(25.0)), ("grainSize", n(3.0))]);
|
||||
// #3483, #3484: the ends of After Effects' ranges.
|
||||
effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(1000.0)), ("lightness", n(1000.0)), ("saturation", n(1000.0)), ("grainSize", n(0.0))]);
|
||||
effect_case("ec.noise.noisehlsauto", &[("noise", e(0)), ("hue", n(20.0)), ("lightness", n(30.0)), ("noiseAnimationSpeed", n(7.0))]);
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,8 @@ fn arbitrary_map_signed_fractional_and_near_zero_wraps() {
|
||||
#[test]
|
||||
fn scatter_brush_strokes() {
|
||||
effect_case("ec.stylize.scatter", &[("amount", n(5.0))]);
|
||||
// #3477: After Effects' maximum, far beyond the layer.
|
||||
effect_case("ec.stylize.scatter", &[("amount", n(1000.0))]);
|
||||
effect_case("ec.stylize.scatter", &[("amount", n(3.0)), ("grain", e(1))]);
|
||||
effect_case("ec.stylize.scatter", &[("amount", n(7.0)), ("grain", e(2)), ("randomizeEveryFrame", on())]);
|
||||
effect_case("ec.stylize.brushstrokes", &[]);
|
||||
|
||||
@@ -29,6 +29,17 @@ fn levels_and_gamma() {
|
||||
);
|
||||
effect_case("ec.color.levelsic", &[("green/greenInBlack", n(0.2)), ("green/greenInWhite", n(0.6)), ("clipToOutputWhite", e(0))]);
|
||||
effect_case("ec.color.levelsic", &[("alpha/alphaOutBlack", n(0.3))]);
|
||||
// #3487-#3491: the ends of the valid ranges, the curve bounded where gamma 0 would overflow.
|
||||
effect_case(
|
||||
"ec.color.levelsic",
|
||||
&[
|
||||
("rgb/rgbInWhite", n(0.2)),
|
||||
("rgb/rgbGamma", n(0.0)),
|
||||
("red/redOutBlack", n(-10000.0)),
|
||||
("blue/blueOutWhite", n(10000.0)),
|
||||
("clipToOutputWhite", e(0)),
|
||||
],
|
||||
);
|
||||
effect_case("ec.color.levels", &[("redInBlack", n(0.1)), ("greenGamma", n(1.5)), ("blueOutWhite", n(0.7)), ("inWhite", n(0.9))]);
|
||||
effect_case("ec.color.levels", &[("alphaInWhite", n(0.6)), ("redInWhite", n(0.5)), ("redClipToOutputWhite", e(0))]);
|
||||
effect_case("ec.color.gammapedestalgain", &[("redGamma", n(1.4)), ("greenPedestal", n(0.1)), ("blueGain", n(0.8))]);
|
||||
@@ -70,6 +81,8 @@ fn colour_replacement() {
|
||||
&[("amount", n(100.0)), ("color", c(0.8, 0.4, 0.3)), ("matchColors", e(1)), ("tolerance", n(5.0)), ("edgeSoftness", n(30.0))],
|
||||
);
|
||||
effect_case("ec.color.changecolor", &[("hueTransform", n(90.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]);
|
||||
// #3480: near the top of After Effects' range (four and three quarter turns).
|
||||
effect_case("ec.color.changecolor", &[("hueTransform", n(1710.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]);
|
||||
effect_case(
|
||||
"ec.color.changecolor",
|
||||
&[
|
||||
@@ -188,3 +201,33 @@ fn color_stabilizer() {
|
||||
fn gradient_ramp_matches_the_cpu() {
|
||||
effect_case("ec.generate.gradientramp", &[]);
|
||||
}
|
||||
|
||||
/// #3487-#3491: at the ends of the valid ranges the GPU's Levels (Individual Controls) output is
|
||||
/// finite (the CPU / GPU comparison counts infinity on both sides as equal).
|
||||
#[test]
|
||||
fn levels_ic_is_finite_at_the_ends_of_its_ranges() {
|
||||
let Some(g) = crate::tests::gpu() else { return };
|
||||
let spec = effectcraft_effects::find("ec.color.levelsic").unwrap();
|
||||
let size = [16.0, 8.0];
|
||||
let mut params =
|
||||
effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() };
|
||||
for (k, v) in [
|
||||
("rgb/rgbInWhite", n(0.2)),
|
||||
("rgb/rgbGamma", n(0.0)),
|
||||
("red/redOutBlack", n(-10000.0)),
|
||||
("blue/blueOutWhite", n(10000.0)),
|
||||
("green/greenOutWhite", n(0.0)),
|
||||
("clipToOutputWhite", e(0)),
|
||||
] {
|
||||
params.values.insert(k.to_string(), v);
|
||||
}
|
||||
let mut img = crate::tests::pattern(7, 16, 8);
|
||||
for p in &mut img.data {
|
||||
*p = p.map(|v| v * 3.0);
|
||||
}
|
||||
let buf = effectcraft_effects::Buf { img, offset: [0.0, 0.0], scale: 1.0 };
|
||||
let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: size, seed: 1, adjustment: false, env: Default::default() };
|
||||
let out = effectcraft_render::Accelerator::effects(g, &[effectcraft_render::FxStep { spec, ctx }], &buf, None)
|
||||
.expect("the GPU runs Levels (Individual Controls)");
|
||||
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "{:?}", out.img.data.iter().find(|p| p.iter().any(|v| !v.is_finite())));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user