Merge main while isolating shared GIF writer revision

This commit is contained in:
Dylan M. Taylor committed 2026-11-15 14:13:01 -05:00
commit e1fc3ba0dc
141 files changed
+9291 -1198

No files matched your search

Generated
+68 -61
View File
@@ -1092,26 +1092,40 @@ dependencies = [
[[package]]
name = "craft-aep"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-doc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-ecproj-format",
"craft-pcraft-format",
"craft-vectorcraft-format",
"flate2",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
[[package]]
name = "craft-dpx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"thiserror 2.0.21",
]
@@ -1119,7 +1133,7 @@ dependencies = [
[[package]]
name = "craft-ecproj-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"serde",
"serde_json",
@@ -1129,12 +1143,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
[[package]]
name = "craft-exr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"serde_json",
]
@@ -1142,7 +1156,7 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
[[package]]
name = "craft-gif"
@@ -1155,7 +1169,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1178,9 +1192,8 @@ dependencies = [
[[package]]
name = "craft-lottie"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-zip",
"serde_json",
"thiserror 2.0.21",
]
@@ -1188,7 +1201,7 @@ dependencies = [
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"thiserror 2.0.21",
]
@@ -1204,16 +1217,26 @@ dependencies = [
[[package]]
name = "craft-mesh"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"miniz_oxide 0.9.1",
"serde_json",
]
[[package]]
name = "craft-pcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"hayro-syntax",
"thiserror 2.0.21",
@@ -1222,7 +1245,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"encoding_rs",
"flate2",
@@ -1233,7 +1256,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"dispatch2",
"egui",
@@ -1244,21 +1267,19 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-xml",
"flate2",
"kurbo",
"roxmltree",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-pathops",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1279,7 +1300,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"chrono",
"dunce",
@@ -1303,12 +1324,23 @@ dependencies = [
"zip 9.1.3",
]
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"flate2",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"rayon",
"thiserror 2.0.21",
]
@@ -1316,7 +1348,7 @@ dependencies = [
[[package]]
name = "craft-webp"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"thiserror 2.0.21",
]
@@ -1324,22 +1356,12 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.3",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -1700,7 +1722,7 @@ version = "0.24.1"
dependencies = [
"craft-audio",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-video",
"effectcraft-color",
"effectcraft-effects",
@@ -1787,6 +1809,7 @@ dependencies = [
name = "effectcraft-host"
version = "0.24.1"
dependencies = [
"craft-vectorcraft-format",
"effectcraft-engine",
"effectcraft-export",
"effectcraft-expr",
@@ -1869,7 +1892,7 @@ dependencies = [
"craft-dpx",
"craft-exr",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)",
"craft-webp",
"effectcraft-color",
"effectcraft-effects",
@@ -1932,14 +1955,18 @@ dependencies = [
name = "effectcraft-pdf"
version = "0.24.1"
dependencies = [
"craft-doc",
"craft-eps",
"craft-pdf",
"craft-vectorcraft-format",
"effectcraft-raster",
"effectcraft-svg",
"effectcraft-text",
"flate2",
"image",
"kurbo",
"miniz_oxide 0.9.1",
"serde_json",
"skrifa",
"wasm-bindgen-test",
"zune-jpeg",
@@ -2123,6 +2150,7 @@ dependencies = [
"effectcraft-segment",
"effectcraft-text",
"effectcraft-time",
"effectcraft-ui-egui",
"eframe",
"egui",
"egui_extras",
@@ -3439,7 +3467,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"hayro-ccitt",
]
@@ -3453,7 +3481,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=948b5c23c12dc8c87c8b1828892b1462113dd5a7#948b5c23c12dc8c87c8b1828892b1462113dd5a7"
source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
@@ -6700,27 +6728,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"linesweeper",
"thiserror 2.0.21",
"vectorcraft-geom",
]
[[package]]
name = "vello_common"
version = "0.2.0"
+22 -20
View File
@@ -11,22 +11,24 @@ rust-version = "1.95"
repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-vectorcraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
# 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 = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["egui"] }
# internal
effectcraft-time = { path = "crates/time" }
effectcraft-geom = { path = "crates/geom" }
@@ -90,9 +92,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 = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", 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 +124,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 = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", features = ["serde"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", 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 +233,8 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7", version = "=0.3.0" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", 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" }
+375
View File
@@ -0,0 +1,375 @@
//! Every native dialog the desktop app opens (rfd), through one path: [`guarded`].
//!
//! [`guarded`] opens a dialog only on the main thread and catches a panic while it is made, so a
//! dialog that can't open becomes an error in the status line instead of taking the app, and
//! the open project, down with it. On macOS rfd makes the panel with `+[NSOpenPanel openPanel]`,
//! and objc2's binding panics when AppKit returns nil there (#3084). That panic used to unwind
//! out of the frame into winit's AppKit callback, which stops the app and re-raises it: the app
//! quit. The engine's last-resort guard (`effectcraft_engine::guard`) didn't catch it because it
//! wraps the commands only; a command that needs a path returns at once and its dialog opens
//! later, at the end of the frame ([`show_asked`]), outside any command.
//!
//! The commands' dialogs don't block the frame (macOS and Linux, `Hooks::file_dialog_async`).
//! A blocking `rfd::FileDialog` runs a nested modal event loop inside eframe's frame, that is
//! inside winit's event handler. On macOS a file dragged over the window while that loop ran
//! re-entered winit's handler, which panics across the Objective-C boundary and aborts the app
//! (#511). On Linux the blocking dialog is worse than slow: rfd uses the XDG desktop portal, so
//! the main thread sits waiting on the portal's answer and never pumps winit's events — the
//! window stops answering the compositor and the desktop offers to force-quit the app while the
//! Open dialog is up (#1275). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window
//! (macOS) or through the portal from a worker thread (Linux) and returns at once; the answer
//! arrives when the dialog closes, outside the frame, and the app runs the command then.
//!
//! The panels' own pickers (Settings paths, Effect Controls, the shortcut editor) still use the
//! blocking hooks [`install_pickers`] sets; they go through [`guarded`] as well.
use effectcraft_ui_egui::{DialogDone, EffectcraftApp, FileDialog};
use rfd::{AsyncFileDialog, FileHandle};
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex, PoisonError};
type Answer = Pin<Box<dyn Future<Output = Vec<String>> + Send>>;
/// A command's dialog waiting for [`show_asked`].
pub type Asked = (FileDialog, DialogDone);
/// Open dialog `what` (its title, for the error) with `open`: on the main thread only, and a
/// panic while it opens is an error instead of a crash (#3084).
pub fn guarded<T>(what: &str, open: impl FnOnce() -> T) -> Result<T, String> {
guarded_on(on_main_thread(), what, open)
}
/// Whether this is the thread AppKit's panels belong to. AppKit makes panels on the main thread
/// only, and rfd would block this thread on the main one to get there; the hooks aren't `Send`,
/// so the app only ever asks from the main thread. Other platforms' dialogs open on any thread.
fn on_main_thread() -> bool {
#[cfg(target_os = "macos")]
{
objc2::MainThreadMarker::new().is_some()
}
#[cfg(not(target_os = "macos"))]
{
true
}
}
fn guarded_on<T>(main_thread: bool, what: &str, open: impl FnOnce() -> T) -> Result<T, String> {
if !main_thread {
log::error!("{what} dialog: asked for off the main thread");
return Err(couldnt_open(what, "it was asked for off the main thread"));
}
std::panic::catch_unwind(AssertUnwindSafe(open)).map_err(|payload| {
// The panic hook has logged the panic and where it happened.
let why = panic_message(payload.as_ref());
log::error!("{what} dialog: {why}");
couldnt_open(what, &why)
})
}
fn couldnt_open(what: &str, why: &str) -> String {
format!("The system's {what} dialog couldn't be created ({why}). Your project is still open.")
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
payload.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_else(|| "internal error".into())
}
/// Where a blocking picker's error goes: the status line, through `Desktop`, which `ctx`
/// wakes so it shows without waiting for input.
#[derive(Clone)]
struct Errors {
tx: Sender<String>,
ctx: egui::Context,
}
/// Run blocking dialog `what`; one that can't open sends why to `errors` and counts as
/// cancelled (the blocking hooks can't return an error).
fn blocking<T>(errors: &Errors, what: &str, open: impl FnOnce() -> Option<T>) -> Option<T> {
blocking_on(errors, what, on_main_thread(), open)
}
fn blocking_on<T>(errors: &Errors, what: &str, main_thread: bool, open: impl FnOnce() -> Option<T>) -> Option<T> {
guarded_on(main_thread, what, open).unwrap_or_else(|e| {
let _ = errors.tx.send(e);
errors.ctx.request_repaint();
None
})
}
fn path_string(p: std::path::PathBuf) -> String {
p.to_string_lossy().to_string()
}
/// Install the blocking pickers (`Hooks::pick_files` and friends), each through [`guarded`].
/// Returns where the errors of those that couldn't open arrive, for the status line; `ctx` is
/// woken when one does.
pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receiver<String> {
let (tx, rx) = std::sync::mpsc::channel::<String>();
let tx = Errors { tx, ctx: ctx.clone() };
let errors = tx.clone();
app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("Media", exts).pick_files()).unwrap_or_default().into_iter().map(path_string).collect()
}));
let errors = tx.clone();
app.hooks.pick_save = Some(Box::new(move |name: &str| {
blocking(&errors, "Save", || rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).set_file_name(name).save_file()).map(path_string)
}));
let errors = tx.clone();
app.hooks.pick_open_project = Some(Box::new(move || {
blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file()).map(path_string)
}));
let errors = tx.clone();
app.hooks.pick_folder = Some(Box::new(move || blocking(&errors, "Choose Folder", || rfd::FileDialog::new().pick_folder()).map(path_string)));
let errors = tx;
app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| {
blocking(&errors, "Save", || {
// A default with a folder that exists opens the dialog there.
let path = std::path::Path::new(name);
// (No filter for a name without an extension, such as a folder to create.)
let mut d = if ext.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter(ext, &[ext]) };
if let Some(dir) = path.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
let file = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
d.set_file_name(file).save_file()
})
.map(path_string)
}));
rx
}
/// An error message box, through [`guarded`] (one that can't open is logged).
pub fn message(title: &str, description: String) {
let shown = guarded("message", || rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title(title).set_description(description).show());
if let Err(e) = shown {
// The diagnostic helper runs before logging is installed.
if log::log_enabled!(log::Level::Error) {
log::error!("{e}");
} else {
eprintln!("effectcraft: {e}");
}
}
}
/// Show the dialogs the commands asked for in this frame (on the main thread: a sheet opens
/// here) and hand each one's paths to its `done` once it closes, then wake the UI.
///
/// On macOS the sheet goes on the main window (`frame`'s). Without a parent rfd puts it on
/// AppKit's main window, which is a floating panel's OS window after a click in one; that
/// window hides while the app has no focused window, and a sheet whose window goes away ends
/// without answering, with later sheets queued behind it on the same window.
pub fn show_asked(asked: &Receiver<Asked>, frame: &eframe::Frame, ctx: &egui::Context) {
while let Ok((dialog, done)) = asked.try_recv() {
show(dialog, done, ctx.clone(), |dialog| open(dialog, frame));
}
}
/// The dialog's title, for errors.
fn title(dialog: &FileDialog) -> &'static str {
match dialog {
FileDialog::Open { .. } | FileDialog::OpenProject => "Open",
FileDialog::Folder => "Choose Folder",
FileDialog::Save { .. } => "Save",
}
}
/// Open `dialog` with `open` through [`guarded`] and wait for its answer on a worker thread.
/// `done` always gets an answer: the paths, or why the dialog couldn't open or answer.
fn show(dialog: FileDialog, done: DialogDone, ctx: egui::Context, open: impl FnOnce(FileDialog) -> Answer) {
show_on(dialog, done, ctx, on_main_thread(), open);
}
fn show_on(dialog: FileDialog, done: DialogDone, ctx: egui::Context, main_thread: bool, open: impl FnOnce(FileDialog) -> Answer) {
let what = title(&dialog);
let answer = match guarded_on(main_thread, what, || open(dialog)) {
Ok(answer) => answer,
Err(e) => {
done(Err(e));
ctx.request_repaint();
return;
}
};
// Kept here too, so a worker that can't start still answers.
let done = Arc::new(Mutex::new(Some(done)));
let take = |done: &Mutex<Option<DialogDone>>| done.lock().unwrap_or_else(PoisonError::into_inner).take();
let (worker_done, worker_ctx) = (done.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("ec-file-dialog".into()).spawn(move || {
let paths = std::panic::catch_unwind(AssertUnwindSafe(|| pollster::block_on(answer))).map_err(|payload| {
let why = panic_message(payload.as_ref());
log::error!("{what} dialog: {why}");
format!("The system's {what} dialog stopped without an answer ({why}). Your project is still open.")
});
if let Some(done) = take(&worker_done) {
done(paths);
}
worker_ctx.request_repaint();
});
if let Err(e) = spawned {
log::error!("file dialog: {e}");
if let Some(done) = take(&done) {
done(Err(couldnt_open(what, &e.to_string())));
}
ctx.request_repaint();
}
}
/// A dialog on the main window. Linux keeps the portal's dialog unparented: rfd exports the
/// window for the portal from the dialog's worker thread there.
fn parented(frame: &eframe::Frame) -> AsyncFileDialog {
let d = AsyncFileDialog::new();
if cfg!(target_os = "macos") { d.set_parent(frame) } else { d }
}
fn paths(files: Option<Vec<FileHandle>>) -> Vec<String> {
files.unwrap_or_default().into_iter().map(|f| f.path().to_string_lossy().to_string()).collect()
}
fn path(file: Option<FileHandle>) -> Vec<String> {
paths(file.map(|f| vec![f]))
}
/// The dialog, as the blocking hooks show it. On macOS rfd makes the panel here, before the
/// future is returned, so a panel AppKit can't make panics here, inside [`guarded`].
///
/// No blocking fallback when that fails: rfd's app-modal dialog makes its panel with the same
/// `+[NSOpenPanel openPanel]`, so it would fail the same way, and it would bring back the
/// nested modal loop of #511. What [`guarded`] can't reach: rfd's own panics inside AppKit's
/// completion handler (its `URL().unwrap()`, or a poisoned lock of its future's state) run
/// under an Objective-C callback and still abort; only rfd can fix those.
fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
match dialog {
FileDialog::Open { exts, many } => {
let d = parented(frame).add_filter("Media", &exts);
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
} else {
let f = d.pick_file();
Box::pin(async move { path(f.await) })
}
}
FileDialog::OpenProject => {
let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file();
Box::pin(async move { path(f.await) })
}
FileDialog::Folder => {
let f = parented(frame).pick_folder();
Box::pin(async move { path(f.await) })
}
FileDialog::Save { default, ext, project } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = if project {
parented(frame).add_filter("EffectCraft Project", &["ecproj"])
} else if ext.is_empty() {
parented(frame)
} else {
parented(frame).add_filter(&ext, &[ext.as_str()])
};
// A default with a folder that exists opens the dialog there.
if let Some(dir) = at.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
let f = d.set_file_name(name).save_file();
Box::pin(async move { path(f.await) })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::channel;
use std::time::Duration;
/// The panic objc2 raises when AppKit returns nil for the panel (#3084).
const NIL_PANEL: &str = "unexpected NULL returned from +[NSOpenPanel openPanel]";
fn answered(dialog: FileDialog, open: impl FnOnce(FileDialog) -> Answer) -> Result<Vec<String>, String> {
let (tx, rx) = channel();
show_on(dialog, Box::new(move |r| tx.send(r).unwrap()), egui::Context::default(), true, open);
rx.recv_timeout(Duration::from_secs(10)).expect("the dialog answers")
}
/// #3084: a panel AppKit can't make panics inside rfd; the command's dialog answers with
/// the error instead, and the panic doesn't leave the frame.
#[test]
fn a_panel_that_cannot_be_made_answers_with_an_error() {
let r = answered(FileDialog::Open { exts: vec!["aep".into(), "aepx".into()], many: false }, |_| panic!("{NIL_PANEL}"));
let e = r.unwrap_err();
assert!(e.starts_with("The system's Open dialog couldn't be created") && e.contains(NIL_PANEL) && e.contains("still open"), "{e}");
let e = answered(FileDialog::Folder, |_| std::panic::panic_any(7_u8)).unwrap_err();
assert!(e.contains("Choose Folder") && e.contains("internal error"), "{e}");
}
/// A dialog that opens answers with its paths from the worker thread; one whose answer
/// panics answers with an error rather than never.
#[test]
fn a_dialog_that_opens_answers_with_its_paths() {
let r = answered(FileDialog::OpenProject, |_| Box::pin(async { vec!["/a/b.ecproj".to_string()] }));
assert_eq!(r, Ok(vec!["/a/b.ecproj".to_string()]));
assert_eq!(answered(FileDialog::save("Frame.png"), |_| Box::pin(async { Vec::new() })), Ok(Vec::new()), "cancelled");
fn lost() -> Vec<String> {
panic!("lost the sheet")
}
let e = answered(FileDialog::OpenProject, |_| Box::pin(async { lost() })).unwrap_err();
assert!(e.contains("stopped without an answer") && e.contains("lost the sheet"), "{e}");
}
/// Off the main thread a dialog isn't opened at all (AppKit makes panels on the main thread
/// only); a panic while one opens is an error; an answer passes through.
#[test]
fn guarded_opens_on_the_main_thread_and_catches_panics() {
let mut opened = false;
let e = guarded_on(false, "Open", || opened = true).unwrap_err();
assert!(!opened && e.contains("off the main thread"), "{e}");
assert_eq!(guarded_on(true, "Open", || 5), Ok(5));
let e = guarded_on(true, "Save", || -> u8 { panic!("{NIL_PANEL}") }).unwrap_err();
assert!(e.contains("Save") && e.contains(NIL_PANEL), "{e}");
}
/// A blocking picker that can't open counts as cancelled and reports why.
#[test]
fn a_blocking_picker_that_cannot_open_reports_why() {
let (tx, rx) = channel();
let tx = Errors { tx, ctx: egui::Context::default() };
assert_eq!(blocking_on(&tx, "Open", true, || -> Option<u8> { panic!("{NIL_PANEL}") }), None);
assert!(rx.try_recv().is_ok_and(|e| e.contains(NIL_PANEL)));
assert_eq!(blocking_on(&tx, "Open", true, || Some(3)), Some(3));
assert!(rx.try_recv().is_err(), "nothing to report");
assert_eq!(blocking_on(&tx, "Open", false, || Some(5)), None);
assert!(rx.try_recv().is_ok_and(|e| e.contains("off the main thread")));
}
/// #3084: every rfd dialog in the desktop app goes through this module (and so through
/// [`guarded`]); no other source file opens one directly.
#[test]
fn every_dialog_opens_through_this_module() {
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = vec![];
let mut dirs = vec![src];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
dirs.push(path);
} else if path.extension().is_some_and(|e| e == "rs") {
files.push(path);
}
}
}
assert!(files.len() > 3, "{files:?}");
let exempt = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join("file_dialogs.rs");
assert!(files.contains(&exempt));
// `rfd` as a word: a path, a `use`, an alias or `extern crate`.
let word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
for file in files.iter().filter(|f| **f != exempt) {
let text = std::fs::read_to_string(file).unwrap();
let named = text.match_indices("rfd").any(|(i, _)| !word(text[..i].chars().next_back()) && !word(text[i + 3..].chars().next()));
assert!(!named, "{}: open dialogs through `file_dialogs` (#3084)", file.display());
}
}
}
+24 -41
View File
@@ -27,9 +27,10 @@ mod diagnostic_state;
mod launch_guard;
#[cfg(target_os = "macos")]
mod native_menu;
// Built everywhere so it stays checked; the macOS and Linux apps use it.
// Every native dialog. Built everywhere; only the macOS and Linux apps show the commands'
// dialogs without blocking the frame.
#[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))]
mod sheet_dialogs;
mod file_dialogs;
mod window;
use effectcraft_ui_egui::EffectcraftApp;
@@ -150,12 +151,12 @@ fn control_port(name: &str, value: Option<&str>) -> Result<u16, String> {
/// answer without pumping events, so the window stops answering the compositor and the desktop
/// offers to force-quit it while the Open dialog is up (#1275). Windows' blocking dialog pumps
/// its own messages, so it keeps [`effectcraft_ui_egui::Hooks::pick_files`] and friends.
/// The dialogs asked for in a frame show at its end ([`sheet_dialogs::show_asked`]), where the
/// The dialogs asked for in a frame show at its end ([`file_dialogs::show_asked`]), where the
/// main window's handle is at hand.
fn install_file_dialogs(app: &mut EffectcraftApp) -> Option<std::sync::mpsc::Receiver<sheet_dialogs::Asked>> {
fn install_file_dialogs(app: &mut EffectcraftApp) -> Option<std::sync::mpsc::Receiver<file_dialogs::Asked>> {
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
let (tx, rx) = std::sync::mpsc::channel::<sheet_dialogs::Asked>();
let (tx, rx) = std::sync::mpsc::channel::<file_dialogs::Asked>();
app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| {
if tx.send((dialog, done)).is_err() {
log::error!("file dialog: the window is gone");
@@ -195,7 +196,7 @@ fn start_helpers_if_opted_in(session: &mut effectcraft_engine::Session) {
fn main() -> eframe::Result {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if crash_report::maybe_run(&args, |description| {
rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title("EffectCraft diagnostic report").set_description(description).show();
file_dialogs::message("EffectCraft diagnostic report", description.to_owned());
}) {
return Ok(());
}
@@ -401,12 +402,9 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
{
app.ui.status = note.into();
}
app.hooks.pick_files = Some(Box::new(|exts: &[&str]| {
rfd::FileDialog::new().add_filter("Media", exts).pick_files().unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect()
}));
app.hooks.pick_save = Some(Box::new(|name: &str| {
rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string())
}));
// Every dialog opens through `file_dialogs::guarded`: one that can't open is an error
// in the status line, not a crash (#3084).
let dialog_errors = file_dialogs::install_pickers(&mut app, &cc.egui_ctx);
// The window closes after a lost graphics device (#591); say why, unless an agent drives
// the app through the control channel.
if control_port.is_none() {
@@ -416,31 +414,15 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
Some(Err(e)) => format!("\n\nYour unsaved changes could not be saved ({e})."),
None => String::new(),
};
rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title("EffectCraft: graphics device lost")
.set_description(format!("The graphics driver stopped responding, so EffectCraft has to close.{saved}"))
.show();
file_dialogs::message(
"EffectCraft: graphics device lost",
format!("The graphics driver stopped responding, so EffectCraft has to close.{saved}"),
);
}));
}
app.hooks.pick_open_project = Some(Box::new(|| {
rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file().map(|p| p.to_string_lossy().to_string())
}));
app.hooks.system_theme = appearance::service();
app.hooks.audio_device = Some(Box::new(audio_out::open));
app.hooks.audio_devices = Some(Box::new(audio_out::devices));
app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));
app.hooks.pick_save_file = Some(Box::new(|name: &str, ext: &str| {
// A default with a folder that exists opens the dialog there.
let path = std::path::Path::new(name);
// (No filter for a name without an extension, such as a folder to create.)
let mut d = if ext.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter(ext, &[ext]) };
if let Some(dir) = path.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
let file = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
d.set_file_name(file).save_file().map(|p| p.to_string_lossy().to_string())
}));
// The commands' file dialogs don't block the frame where the platform's backend
// would (#511, #1275); see [`install_file_dialogs`].
let file_dialogs = install_file_dialogs(&mut app);
@@ -462,6 +444,7 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
apple_events: apple_events.connect(&cc.egui_ctx),
app,
file_dialogs,
dialog_errors,
window: window::Tracker::new(opened, saved_window, control_port.is_none()),
launch,
drawn: false,
@@ -536,19 +519,16 @@ fn startup_failed(e: &eframe::Error, gl_next: bool) {
} else {
eprintln!("effectcraft: {message}");
}
let _ = rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title("EffectCraft")
.set_description(message)
.set_buttons(rfd::MessageButtons::Ok)
.show();
file_dialogs::message("EffectCraft", message);
}
/// The desktop app: the egui app plus, on macOS, the system menu bar.
struct Desktop {
app: EffectcraftApp,
/// The commands' file dialogs, shown at the end of the frame that asked for them.
file_dialogs: Option<std::sync::mpsc::Receiver<sheet_dialogs::Asked>>,
file_dialogs: Option<std::sync::mpsc::Receiver<file_dialogs::Asked>>,
/// Why a blocking picker couldn't open (#3084), for the status line.
dialog_errors: std::sync::mpsc::Receiver<String>,
#[cfg(target_os = "macos")]
menu: native_menu::NativeBar,
/// Documents opened from Finder, the Dock or `open` (macOS).
@@ -570,8 +550,11 @@ impl eframe::App for Desktop {
self.menu.update(&mut self.app, ctx);
self.app.tick(ctx, frame);
self.app.finish_ime_logic(ctx);
while let Ok(e) = self.dialog_errors.try_recv() {
self.app.ui.status = e;
}
if let Some(asked) = &self.file_dialogs {
sheet_dialogs::show_asked(asked, frame, ctx);
file_dialogs::show_asked(asked, frame, ctx);
}
effectcraft_ui_egui::panels::unsaved::quit_on_close(ctx);
}
@@ -579,7 +562,7 @@ impl eframe::App for Desktop {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.app.ui(ui, frame);
if let Some(asked) = &self.file_dialogs {
sheet_dialogs::show_asked(asked, frame, ui.ctx());
file_dialogs::show_asked(asked, frame, ui.ctx());
}
self.window.frame(ui.ctx(), self.app.session.config.as_deref());
if !self.drawn {
-101
View File
@@ -1,101 +0,0 @@
//! File dialogs that don't block the frame (macOS and Linux), for `Hooks::file_dialog_async`.
//!
//! A blocking `rfd::FileDialog` runs a nested modal event loop inside eframe's frame, that is
//! inside winit's event handler. On macOS a file dragged over the window while that loop ran
//! re-entered winit's handler, which panics across the Objective-C boundary and aborts the app
//! (#511). On Linux the blocking dialog is worse than slow: rfd uses the XDG desktop portal, so
//! the main thread sits waiting on the portal's answer and never pumps winit's events — the
//! window stops answering the compositor and the desktop offers to force-quit the app while the
//! Open dialog is up (#1275). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window
//! (macOS) or through the portal from a worker thread (Linux) and returns at once; the answer
//! arrives when the dialog closes, outside the frame, and the app runs the command then.
use effectcraft_ui_egui::{DialogDone, FileDialog};
use rfd::{AsyncFileDialog, FileHandle};
use std::future::Future;
use std::pin::Pin;
type Answer = Pin<Box<dyn Future<Output = Vec<String>> + Send>>;
/// A command's dialog waiting for [`show_asked`].
pub type Asked = (FileDialog, DialogDone);
/// Show the dialogs the commands asked for in this frame (on the main thread: a sheet opens
/// here) and hand each one's paths to its `done` once it closes, then wake the UI.
///
/// On macOS the sheet goes on the main window (`frame`'s). Without a parent rfd puts it on
/// AppKit's main window, which is a floating panel's OS window after a click in one; that
/// window hides while the app has no focused window, and a sheet whose window goes away ends
/// without answering, with later sheets queued behind it on the same window.
pub fn show_asked(asked: &std::sync::mpsc::Receiver<Asked>, frame: &eframe::Frame, ctx: &egui::Context) {
while let Ok((dialog, done)) = asked.try_recv() {
show(dialog, done, frame, ctx.clone());
}
}
fn show(dialog: FileDialog, done: DialogDone, frame: &eframe::Frame, ctx: egui::Context) {
let answer = open(dialog, frame);
let spawned = std::thread::Builder::new().name("ec-file-dialog".into()).spawn(move || {
done(pollster::block_on(answer));
ctx.request_repaint();
});
if let Err(e) = spawned {
log::error!("file dialog: {e}");
}
}
/// A dialog on the main window. Linux keeps the portal's dialog unparented: rfd exports the
/// window for the portal from the dialog's worker thread there.
fn parented(frame: &eframe::Frame) -> AsyncFileDialog {
let d = AsyncFileDialog::new();
if cfg!(target_os = "macos") { d.set_parent(frame) } else { d }
}
fn paths(files: Option<Vec<FileHandle>>) -> Vec<String> {
files.unwrap_or_default().into_iter().map(|f| f.path().to_string_lossy().to_string()).collect()
}
fn path(file: Option<FileHandle>) -> Vec<String> {
paths(file.map(|f| vec![f]))
}
/// The dialog, as the blocking hooks in `main.rs` show it.
fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
match dialog {
FileDialog::Open { exts, many } => {
let d = parented(frame).add_filter("Media", &exts);
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
} else {
let f = d.pick_file();
Box::pin(async move { path(f.await) })
}
}
FileDialog::OpenProject => {
let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file();
Box::pin(async move { path(f.await) })
}
FileDialog::Folder => {
let f = parented(frame).pick_folder();
Box::pin(async move { path(f.await) })
}
FileDialog::Save { default, ext, project } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = if project {
parented(frame).add_filter("EffectCraft Project", &["ecproj"])
} else if ext.is_empty() {
parented(frame)
} else {
parented(frame).add_filter(&ext, &[ext.as_str()])
};
// A default with a folder that exists opens the dialog there.
if let Some(dir) = at.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
let f = d.set_file_name(name).save_file();
Box::pin(async move { path(f.await) })
}
}
}
+77 -4
View File
@@ -1160,8 +1160,29 @@ pub const GLOW_MIDPOINT_MAX: f64 = 0.990_005_493_164_062_5;
/// language, so an item can start with a capital outside ASCII (French "Écran"), and its key must
/// be the same as for the same word in lower case.
pub fn popup_key(item: &str) -> String {
let s = item.trim().to_lowercase();
s.strip_suffix(" channel").map(str::to_string).unwrap_or(s)
// The whole string is lowered at once: Unicode's lower case depends on the context (a Greek
// capital sigma ends a word as final sigma), which a per-character mapping loses.
popup_stem(item).to_lowercase()
}
/// [`popup_key`] before the lower-casing, borrowed: `item` trimmed, without a final ` channel`
/// in any case (the suffix is ASCII, so the cut is on a character boundary).
pub(crate) fn popup_stem(item: &str) -> &str {
let t = item.trim();
let cut = t.len().saturating_sub(SUFFIX.len());
match (t.as_bytes().get(cut..), t.get(..cut)) {
(Some(end), Some(stem)) if t.len() >= SUFFIX.len() && end.eq_ignore_ascii_case(SUFFIX) => stem,
_ => t,
}
}
const SUFFIX: &[u8] = b" channel";
/// Whether two popup items have the same [`popup_key`], without building either key.
pub(crate) fn popup_keys_match(a: &str, b: &str) -> bool {
let (a, b) = (popup_stem(a), popup_stem(b));
// ASCII lowers per byte without a key; anything else lowers as a whole string (see `popup_key`).
if a.is_ascii() && b.is_ascii() { a.eq_ignore_ascii_case(b) } else { a.to_lowercase() == b.to_lowercase() }
}
/// The English [`popup_key`] a non-English After Effects popup item name stands for, when this
@@ -1208,12 +1229,64 @@ pub const LEVELS_RGB: [&str; 5] = ["inBlack", "inWhite", "gamma", "outBlack", "o
mod tests {
use super::*;
/// The key as it was built before the borrowed form (the reference for the differential test).
fn old_key(item: &str) -> String {
let s = item.trim().to_lowercase();
s.strip_suffix(" channel").map(str::to_string).unwrap_or(s)
}
#[test]
fn the_borrowed_popup_key_matches_the_owned_one() {
let items = [
"",
" ",
"(-",
"Red",
"red channel",
"Red Channel",
" Alpha CHANNEL ",
"channel",
" channel",
"x channel",
"Xchannel",
"\u{c4} channel",
"Gr\u{fc}n Channel",
"\u{e9}",
"\u{dc}nit channel",
"a channel channel",
"Luminance",
"\u{c9}CRAN",
"\u{e9}cran",
// Greek: a capital sigma at the end of a word lowers to the final form.
"\u{39f}\u{3a3}",
"\u{3bf}\u{3c2}",
"\u{3bf}\u{3c3}",
"\u{39f}\u{3a3} Channel",
"\u{3a3}\u{39f}\u{3a3}",
];
for a in items {
assert_eq!(popup_key(a), old_key(a), "{a:?}");
for b in items {
assert_eq!(popup_keys_match(a, b), old_key(a) == old_key(b), "{a:?} {b:?}");
}
}
}
/// A capital outside ASCII has the same key as its lower case; ASCII keys are unchanged.
#[test]
fn popup_key_lowers_non_ascii_capitals() {
assert_eq!(popup_key("ÉCRAN"), popup_key("écran"));
assert_eq!(popup_key(" Désactivé "), "désactivé");
assert_eq!(popup_key("\u{c9}CRAN"), popup_key("\u{e9}cran"));
assert_eq!(popup_key(" D\u{e9}sactiv\u{e9} "), "d\u{e9}sactiv\u{e9}");
assert_eq!(popup_key("Off for 32 bpc Color"), "off for 32 bpc color");
assert_eq!(popup_key("Red Channel"), "red");
}
/// Lower case is context sensitive: a capital sigma at the end of a word is a final sigma.
#[test]
fn popup_key_keeps_the_final_sigma() {
assert_eq!(popup_key("\u{39f}\u{3a3}"), "\u{3bf}\u{3c2}");
assert!(popup_keys_match("\u{39f}\u{3a3}", "\u{3bf}\u{3c2}"));
assert!(!popup_keys_match("\u{39f}\u{3a3}", "\u{3bf}\u{3c3}"));
assert_eq!(popup_key("\u{3a3}\u{39f}\u{3a3} Channel"), "\u{3c3}\u{3bf}\u{3c2}");
}
}
+326 -230
View File
@@ -29,14 +29,17 @@
use std::collections::HashMap;
use std::sync::OnceLock;
use crate::effect_map::{Conv, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, by_effect, by_match_name, popup_key};
use crate::{AepFile, Body, CURVE_IDENTITY, Chunk, CurvesData, MeshData, ParamKind};
use effectcraft_keyframe::{Interp, Keyframe, Value};
use crate::effect_map::{Conv, EffectMap, Extra, HUE_SATURATION_MASTER, LEVELS_RGB, by_effect, by_match_name, popup_keys_match};
use crate::{AepFile, CURVE_IDENTITY, Chunk, CurvesData, MeshData, ParamKind};
use effectcraft_keyframe::{Interp, Value};
use effectcraft_project::{GroupKind, Layer, LayerId, Node, ParamUi, PropGroup, Property};
use crate::export::fx_defs::{FX_DEFS, FxDef, PDef};
use crate::export::keys::{fill_key_list, replace_cdat, spatial_record, timed_keys};
use crate::export::plan::{CompPlan, EaseSlot, KeyPlan, LIMIT};
use crate::export::report::{Collector, LossCategory};
use crate::export::tree::{R, child_data, child_mut, data_mut, kids_mut, list_mut, put, put_f64, put_u8, put_u16, put_u32, tpl};
use crate::export::synth::{NO_NAME, is_tdmn, tdmn, tdmn_name, tdsn, utf8_in};
use crate::export::tree::{R, child_data, child_mut, data_mut, kids_mut, list_mut, put, put_f64, put_u8, put_u32, tpl};
/// How a parameter is stored in its value record.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -154,10 +157,6 @@ pub(crate) struct ParDef {
pub record: String,
/// `pard@12`.
pub code: u32,
/// `pard@16`, or a checkbox's `pdnm` label.
pub name: String,
/// The popup items (`pdnm`, separated by `|`).
pub items: Vec<String>,
/// The default in stored units (`pard@56`).
pub default: Vec<f64>,
/// The slider range a value record repeats as `tdum` / `tduM`.
@@ -168,114 +167,77 @@ pub(crate) struct ParDef {
pub data: Option<Vec<u8>>,
}
fn be_i32(d: &[u8], at: usize) -> Option<i32> {
Some(i32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?))
}
fn be_u32(d: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?))
}
fn be_f32(d: &[u8], at: usize) -> Option<f64> {
Some(f64::from(f32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?)))
}
fn be_f64(d: &[u8], at: usize) -> Option<f64> {
Some(f64::from_be_bytes(d.get(at..at.checked_add(8)?)?.try_into().ok()?))
}
fn cname(d: &[u8]) -> String {
d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect()
/// A fixed slider's or angle's value as its 16.16 `pard` copy holds it (`fxsynth::pard`).
fn fixed(v: f64) -> f64 {
f64::from(crate::export::fxsynth::fixed_i32(v)) / 65536.0
}
impl ParDef {
fn from_pard(pard: &[u8], pdnm: Option<&str>, data: Option<&[u8]>) -> ParDef {
let code = be_u32(pard, 12).unwrap_or(u32::MAX);
let fx = |at: usize| be_i32(pard, at).map(|v| f64::from(v) / 65536.0);
let default: Vec<f64> = match code {
10 => be_f64(pard, 56).into_iter().collect(),
2 | 3 => fx(56).into_iter().collect(),
1 => be_i32(pard, 56).map(f64::from).into_iter().collect(),
4 | 7 => be_u32(pard, 56).map(f64::from).into_iter().collect(),
/// The definition of parameter `p` of the table row `fx`, in the stored units the
/// prototype's `pard` holds (`fxsynth::default_sspc` writes it from the same row): fixed
/// sliders, angles and points at 16.16, integers, checkboxes and popups rounded, colours as
/// bytes, float slider ranges as `f32`. Read straight from the table; the round trip through
/// the encoded `pard` that this replaces is the reference in the tests.
fn from_table(fx: &FxDef, p: &PDef) -> ParDef {
let d = |i: usize| p.default.get(i).copied().unwrap_or(0.0);
let int = |v: f64| f64::from(crate::export::fxsynth::int_i32(v));
let f32_of = |v: f64| f64::from(v as f32);
let default: Vec<f64> = match p.code {
10 => vec![d(0)],
2 | 3 => vec![fixed(d(0))],
1 => vec![int(d(0))],
// On when the stored word is not 0 (as the importer reads it).
4 => vec![if d(0).round().max(0.0) as u32 != 0 { 1.0 } else { 0.0 }],
7 => vec![f64::from(d(0).round().clamp(0.0, f64::from(u16::MAX)) as u32)],
// Fractions of the layer, or percent after an After Effects re-save (see the reader).
6 => {
let p: Vec<f64> = [fx(56), fx(60)].into_iter().flatten().collect();
if p.iter().any(|c| c.abs() > 1.0 + 1e-9) { p.iter().map(|c| c / 100.0).collect() } else { p }
let pt = [fixed(d(0)), fixed(d(1))];
if pt.iter().any(|c| c.abs() > 1.0 + 1e-9) { pt.iter().map(|c| c / 100.0).collect() } else { pt.to_vec() }
}
5 => pard.get(56..60).map(|c| c.iter().map(|b| f64::from(*b)).collect()).unwrap_or_default(),
5 => (0..4).map(|i| f64::from(d(i).round().clamp(0.0, 255.0) as u8)).collect(),
_ => Vec::new(),
};
let range = match code {
10 => be_f32(pard, 112).zip(be_f32(pard, 116)),
2 => fx(132).zip(fx(136)),
1 => be_i32(pard, 132).map(f64::from).zip(be_i32(pard, 136).map(f64::from)),
_ => None,
// A slider without a range or valid maximum in the table stores zeros there.
let (lo, hi) = p.range.unwrap_or((0.0, 0.0));
let max = p.valid_max.unwrap_or(0.0);
let (range, valid_max) = match p.code {
10 => (Some((f32_of(lo), f32_of(hi))), Some(f32_of(max))),
2 => (Some((fixed(lo), fixed(hi))), Some(fixed(max))),
1 => (Some((int(lo), int(hi))), Some(int(max))),
_ => (None, None),
};
let valid_max = match code {
10 => be_f32(pard, 108),
2 => fx(128),
1 => be_i32(pard, 128).map(f64::from),
_ => None,
};
let pname = pard.get(16..48).map(cname).unwrap_or_default();
let (name, items) = match (code, pdnm) {
(7, Some(p)) if !p.is_empty() => (pname, p.split('|').map(str::to_string).collect()),
(4, Some(p)) if pname.trim().is_empty() => (p.to_string(), Vec::new()),
_ => (pname, Vec::new()),
};
ParDef { record: String::new(), code, name, items, default, range, valid_max, data: data.map(<[u8]>::to_vec) }
// The record is the text of its `tdmn` as the exporter reads it back (`synth::tdmn_name`),
// so the instance finds its records by it.
let record = tdmn_name(&tdmn(&fx.record(p))).unwrap_or_default();
// The prototype's `pard` holds no name and its `pdnm` is empty: no name, no popup items.
let data = if p.code == 11 { crate::export::fxsynth::default_data(fx.match_name) } else { None };
ParDef { record, code: u32::from(p.code), default, range, valid_max, data }
}
/// The definitions of the table row `fx`, by position (the table's index).
fn of_effect(fx: &FxDef) -> HashMap<u16, ParDef> {
let mut out = HashMap::with_capacity(fx.params.len());
let mut position = 0u16;
for p in fx.params {
out.insert(position, ParDef::from_table(fx, p));
position = position.saturating_add(1);
}
out
}
}
/// The parameter definitions of an instance's `parT`, by position (the table's index).
fn par_defs(sspc: &Chunk<'_>) -> HashMap<u16, ParDef> {
let mut out = HashMap::new();
let Some(part) = sspc.child_list(b"parT") else { return out };
let k = part.children();
let mut i = 0usize;
let mut position = 0u16;
while i < k.len() {
let (Some(m), Some(p)) = (k.get(i), k.get(i + 1)) else { break };
if !(m.is(b"tdmn") && p.is(b"pard")) {
i += 1;
continue;
}
let name = tdmn_name(m).unwrap_or_default();
let mut j = i + 2;
let mut pdnm = None;
let mut data = None;
while let Some(c) = k.get(j) {
if c.is(b"tdmn") {
break;
}
if c.is(b"pdnm") {
pdnm = c.children().iter().find(|u| u.is(b"Utf8")).and_then(|u| u.bytes()).map(|b| String::from_utf8_lossy(b).to_string());
}
if c.is(b"aRbp") {
data = c.bytes();
}
j += 1;
}
if let Some(bytes) = p.bytes() {
out.insert(position, ParDef { record: name, ..ParDef::from_pard(bytes, pdnm.as_deref(), data) });
}
position = position.saturating_add(1);
i = j;
}
out
}
/// The parameter definitions of every effect type, by match name (read from the default
/// instances built from the effect table).
/// The parameter definitions of every effect type, by match name (from the effect table the
/// default instances are built from).
fn defs() -> &'static HashMap<String, HashMap<u16, ParDef>> {
static DEFS: OnceLock<HashMap<String, HashMap<u16, ParDef>>> = OnceLock::new();
DEFS.get_or_init(|| {
crate::export::fx_defs::FX_DEFS.iter().map(|fx| (fx.match_name.to_string(), par_defs(&crate::export::fxsynth::default_sspc(fx)))).collect()
})
DEFS.get_or_init(|| FX_DEFS.iter().map(|fx| (fx.match_name.to_string(), ParDef::of_effect(fx))).collect())
}
// ---------------------------------------------------------------------------------------------
// Planning.
/// The stored components of an EffectCraft value, `None` when it does not fit.
fn stored(conv: Conv, kind: PKind, v: &Value, size: (f64, f64), ui: &ParamUi, def: &ParDef) -> Option<Vec<f64>> {
fn stored(conv: Conv, kind: PKind, v: &Value, size: (f64, f64), ui: &ParamUi) -> Option<Vec<f64>> {
let c = v.components();
let g = |i: usize| c.get(i).copied().and_then(sane);
let one = |x: f64| -> Vec<f64> {
@@ -306,8 +268,8 @@ fn stored(conv: Conv, kind: PKind, v: &Value, size: (f64, f64), ui: &ParamUi, de
};
let ParamUi::Popup { options } = ui else { return None };
let name = options.get(i)?;
let file: Vec<&str> = if def.items.is_empty() { items.to_vec() } else { def.items.iter().map(String::as_str).collect() };
let at = file.iter().position(|f| f.trim() != "(-" && popup_key(f) == popup_key(name))?;
// The prototype's `pdnm` names no items: the table's are After Effects'.
let at = items.iter().position(|f| f.trim() != "(-" && popup_keys_match(f, name))?;
vec![f64::from(u32::try_from(at).ok()?.checked_add(1)?)]
}
// Not a value record (layer parameters, histograms).
@@ -317,16 +279,15 @@ fn stored(conv: Conv, kind: PKind, v: &Value, size: (f64, f64), ui: &ParamUi, de
/// Whether a popup's items are After Effects' items in the same order (separators included, as
/// After Effects counts them), so an expression's 1-based result picks the same item in both.
fn same_popup_order(items: &[&str], ui: &ParamUi, def: &ParDef) -> bool {
fn same_popup_order(items: &[&str], ui: &ParamUi) -> bool {
let ParamUi::Popup { options } = ui else { return false };
let file: Vec<&str> = if def.items.is_empty() { items.to_vec() } else { def.items.iter().map(String::as_str).collect() };
file.len() == options.len() && file.iter().zip(options).all(|(f, o)| f.trim() != "(-" && popup_key(f) == popup_key(o))
items.len() == options.len() && items.iter().zip(options).all(|(f, o)| f.trim() != "(-" && popup_keys_match(f, o))
}
/// [`stored`], reporting what it changes in a value it can store: a colour channel outside 0 to 1
/// (written as the nearest limit) and a fraction on an integer parameter (rounded).
fn stored_reported(conv: Conv, kind: PKind, v: &Value, (size, ui, def): ((f64, f64), &ParamUi, &ParDef), what: &str, col: &mut Collector) -> Option<Vec<f64>> {
let s = stored(conv, kind, v, size, ui, def)?;
fn stored_reported(conv: Conv, kind: PKind, v: &Value, (size, ui): ((f64, f64), &ParamUi), what: &str, col: &mut Collector) -> Option<Vec<f64>> {
let s = stored(conv, kind, v, size, ui)?;
if matches!(conv, Conv::Color) {
let c = v.components();
if c.iter().take(3).any(|x| !(0.0..=1.0).contains(x)) {
@@ -339,7 +300,7 @@ fn stored_reported(conv: Conv, kind: PKind, v: &Value, (size, ui, def): ((f64, f
}
}
if kind == PKind::Int
&& let Some(raw) = stored(conv, PKind::Fixed, v, size, ui, def)
&& let Some(raw) = stored(conv, PKind::Fixed, v, size, ui)
&& raw.iter().zip(&s).any(|(a, b)| a.to_bits() != b.to_bits())
{
col.lose(LossCategory::Effects, format!("{what}: {raw:?} is written as the whole number {s:?}"));
@@ -501,16 +462,26 @@ fn plan_extra(spec: &EffectMap, g: &PropGroup, pdefs: &HashMap<u16, ParDef>, her
(data != before).then_some((index, data))
}
/// `x,y` pairs (EffectCraft's curve points and mesh offsets; whitespace or `;` between pairs).
fn pairs_of(s: &str) -> Vec<(f64, f64)> {
s.split(|c: char| c.is_whitespace() || c == ';')
/// `x,y` pairs (EffectCraft's curve points; whitespace or `;` between pairs), and how many
/// entries are not a pair of finite numbers (left out).
fn pairs_of(s: &str) -> (Vec<(f64, f64)>, usize) {
let mut unreadable = 0usize;
let pairs = s
.split(|c: char| c.is_whitespace() || c == ';')
.filter(|t| !t.is_empty())
.filter_map(|t| {
let (x, y) = t.split_once(',')?;
let (x, y) = (x.trim().parse::<f64>().ok()?, y.trim().split(',').next()?.trim().parse::<f64>().ok()?);
(x.is_finite() && y.is_finite()).then_some((x, y))
let pair = (|| {
let (x, y) = t.split_once(',')?;
let (x, y) = (x.trim().parse::<f64>().ok()?, y.trim().split(',').next()?.trim().parse::<f64>().ok()?);
(x.is_finite() && y.is_finite()).then_some((x, y))
})();
if pair.is_none() {
unreadable = unreadable.saturating_add(1);
}
pair
})
.collect()
.collect();
(pairs, unreadable)
}
/// The arbitrary-data parameter's index and default data.
@@ -537,7 +508,10 @@ fn static_str<'p>(g: &'p PropGroup, id: &str, here: &str, col: &mut Collector) -
fn plan_curves(g: &PropGroup, pdefs: &HashMap<u16, ParDef>, here: &str, col: &mut Collector) -> Option<(u16, Vec<u8>)> {
let mut curves: [Vec<(u8, u8)>; 5] = Default::default();
for (slot, id) in curves.iter_mut().zip(["rgb", "red", "green", "blue", "alpha"]) {
let pts = static_str(g, id, here, col).map(pairs_of).unwrap_or_default();
let (pts, unreadable) = static_str(g, id, here, col).map(pairs_of).unwrap_or_default();
if unreadable > 0 {
col.lose(LossCategory::InvalidValues, format!("{here}: curve '{id}': {unreadable} entries are not an x,y pair of numbers and are not written"));
}
let mut ints: Vec<(u8, u8)> = Vec::with_capacity(pts.len());
let (mut rounded, mut clipped) = (false, false);
for (x, y) in pts {
@@ -584,17 +558,25 @@ fn plan_mesh(g: &PropGroup, pdefs: &HashMap<u16, ParDef>, size: (f64, f64), here
let (rows, columns) = (int("rows"), int("columns"));
// Per vertex `dx,dy` (pixels), optionally followed by the eight pixel moves of its handles
// (top, right, bottom, left) that the importer keeps.
let mut unreadable = 0usize;
let offs: Vec<Vec<f64>> = static_str(g, "mesh", here, col)
.map(|s| {
s.split(|c: char| c.is_whitespace() || c == ';')
.filter(|t| !t.is_empty())
.filter_map(|t| {
let v: Vec<f64> = t.split(',').map(|x| x.trim().parse::<f64>().ok().filter(|x| x.is_finite())).collect::<Option<_>>()?;
(v.len() >= 2).then_some(v)
let v: Option<Vec<f64>> = t.split(',').map(|x| x.trim().parse::<f64>().ok().filter(|x| x.is_finite())).collect();
let v = v.filter(|v| v.len() >= 2);
if v.is_none() {
unreadable = unreadable.saturating_add(1);
}
v
})
.collect()
})
.unwrap_or_default();
if unreadable > 0 {
col.lose(LossCategory::InvalidValues, format!("{here}: the Distortion Mesh has {unreadable} entries that are not numbers, left out"));
}
let count = usize::try_from((rows + 1) * (columns + 1)).ok()?;
let moved = offs.iter().any(|v| v.iter().any(|x| *x != 0.0));
if !moved && rows == 7 && columns == 7 {
@@ -714,7 +696,7 @@ fn plan_param(pin: ParamIn<'_>, index: u16, cp: &CompPlan, here: &str, col: &mut
// factor parameter has other units) or a popup's items are in another order, its result
// means something else in After Effects. Popups count from 1 in both programs' expressions.
let other_units = match conv {
Conv::Popup { items, .. } => !same_popup_order(items, &prop.ui, def),
Conv::Popup { items, .. } => !same_popup_order(items, &prop.ui),
Conv::Percent { valid_max } => (valid_max - 100.0).abs() > 1e-9,
Conv::Factor { factor, .. } => (factor - 1.0).abs() > 1e-9,
_ => false,
@@ -724,7 +706,7 @@ fn plan_param(pin: ParamIn<'_>, index: u16, cp: &CompPlan, here: &str, col: &mut
}
}
if prop.keys.is_empty() {
let Some(s) = stored_reported(conv, kind, &prop.value, (size, &prop.ui, def), &what, col) else {
let Some(s) = stored_reported(conv, kind, &prop.value, (size, &prop.ui), &what, col) else {
if matches!(conv, Conv::Popup { .. }) {
col.lose(LossCategory::Effects, format!("{what}: the popup item has no After Effects counterpart, the default was written"));
} else {
@@ -744,7 +726,7 @@ fn plan_param(pin: ParamIn<'_>, index: u16, cp: &CompPlan, here: &str, col: &mut
format!("{what}: keys on a popup, checkbox, angle or integer slider are not written (not sampled), the first key's value was written"),
);
let first = prop.keys.first().map(|k| &k.value).unwrap_or(&prop.value);
let s = stored_reported(conv, kind, first, (size, &prop.ui, def), &what, col)?;
let s = stored_reported(conv, kind, first, (size, &prop.ui), &what, col)?;
return (!is_default(kind, &s, def) || expr.is_some()).then_some(ParamPlan { index, kind, value: ParamValue::Static(s), expr });
}
let keys = plan_keys(pin, cp, &what, col);
@@ -756,22 +738,8 @@ fn plan_param(pin: ParamIn<'_>, index: u16, cp: &CompPlan, here: &str, col: &mut
}
fn plan_keys(pin: ParamIn<'_>, cp: &CompPlan, what: &str, col: &mut Collector) -> Vec<KeyPlan> {
let ParamIn { conv, kind, def, prop, size } = pin;
let keys: &[Keyframe] = &prop.keys;
let mut timed: Vec<(i64, &Keyframe)> = Vec::with_capacity(keys.len());
for k in keys {
let (u, inexact) = cp.tb.units(k.time);
if inexact {
col.lose(LossCategory::RoundedTimes, format!("{what}: key at {:.4} s moved to the time base", k.time.seconds()));
}
timed.push((u, k));
}
timed.sort_by_key(|(u, _)| *u);
let before = timed.len();
timed.dedup_by_key(|(u, _)| *u);
if timed.len() != before {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: keys at the same time were merged"));
}
let ParamIn { conv, kind, prop, size, .. } = pin;
let timed = timed_keys(&prop.keys, &cp.tb, what, "key", col);
// The ease of colour keys is sampled only as speed 0 / influence 0, which After Effects
// interpolates linearly (598): a colour key is written linear.
let ease_ok = matches!(kind, PKind::Fixed | PKind::Float | PKind::Point);
@@ -790,7 +758,7 @@ fn plan_keys(pin: ParamIn<'_>, cp: &CompPlan, what: &str, col: &mut Collector) -
col.lose(LossCategory::InvalidValues, format!("{what}: key time out of range, key dropped"));
continue;
};
let Some(value) = stored_reported(conv, kind, &k.value, (size, &prop.ui, def), what, col) else {
let Some(value) = stored_reported(conv, kind, &k.value, (size, &prop.ui), what, col) else {
col.lose(LossCategory::InvalidValues, format!("{what}: a key value that cannot be stored, key dropped"));
continue;
};
@@ -884,11 +852,6 @@ fn keyed_kind(k: PKind) -> Option<KeyedKind> {
}
}
pub(crate) fn tdmn_name(c: &Chunk<'_>) -> Option<String> {
let d = c.bytes()?;
Some(d.iter().take_while(|b| **b != 0).map(|b| char::from(*b)).collect())
}
impl FxProtos {
/// The prototypes built in code from the effect table (`fx_defs`, `fxsynth`).
pub(crate) fn build() -> FxProtos {
@@ -919,27 +882,10 @@ pub(crate) struct FxUse {
pub types: Vec<&'static str>,
}
/// A `tdsn` chunk holding `text`.
fn tdsn(text: &str) -> Chunk<'static> {
nested(*b"tdsn", text)
}
/// A chunk that holds one `Utf8` chunk (`tdsn`, `fnam`).
fn nested(id: [u8; 4], text: &str) -> Chunk<'static> {
Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", text.as_bytes().to_vec())]), pad: None }
}
/// The value record of `p`, built from the record of its parameter type.
pub(crate) fn value_record(protos: &FxProtos, p: &ParamPlan, def: &ParDef, source_size: (u32, u32)) -> R<(Chunk<'static>, Chunk<'static>)> {
let mut rec = protos.kinds.get(&p.kind.code()).cloned().ok_or_else(|| tpl("effect value prototype missing"))?;
{
let kids = kids_mut(&mut rec)?;
if let Some(slot) = kids.iter_mut().find(|c| c.is(b"tdsn"))
&& !def.name.is_empty()
{
*slot = tdsn(&def.name);
}
}
// The record keeps the prototype's `tdsn`: the prototypes name no parameter.
if p.kind == PKind::Point {
// The layer's aspect, as on the Anchor Point (369: 16 / 9, 383: 1 on 100 x 100).
put_f64(child_data(&mut rec, b"tdb4")?, 24, f64::from(source_size.0) / f64::from(source_size.1.max(1)))?;
@@ -970,35 +916,22 @@ pub(crate) fn value_record(protos: &FxProtos, p: &ParamPlan, def: &ParDef, sourc
put_u8(tdb4, at, *ktdb4.get(at).ok_or_else(|| tpl("short tdb4"))?)?;
}
}
let n = u32::try_from(keys.len()).map_err(|_| tpl("too many keys"))?;
let dims = p.kind.dims();
let size = match kk {
KeyedKind::Fixed | KeyedKind::Float => 8 + 40 * dims,
KeyedKind::Color | KeyedKind::Point => 56 + 24 * dims,
};
{
let lhd3 = child_data(&mut list, b"lhd3")?;
crate::export::synth::put_key_counts(lhd3, n, u32::try_from(size).map_err(|_| tpl("record size"))?)?;
}
let mut ldat = Vec::with_capacity(size * keys.len());
let mut ldat = Vec::with_capacity(size.saturating_mul(keys.len()));
for k in keys {
ldat.extend(match kk {
KeyedKind::Fixed | KeyedKind::Float => crate::export::emit::plain_record(1, k, size)?,
KeyedKind::Color | KeyedKind::Point => spatial_record(kk, k, dims, size)?,
// A colour (flags `0x0001`, 210, 364) or a point (flags `0x0007`, the
// temporal ease in layer heights per second, 382, 598).
KeyedKind::Color | KeyedKind::Point => spatial_record(k, dims, kk == KeyedKind::Point, size)?,
});
}
{
let lk = kids_mut(&mut list)?;
match lk.iter_mut().find(|c| c.is(b"ldat")) {
Some(c) => *c = Chunk::data(*b"ldat", ldat),
None => lk.push(Chunk::data(*b"ldat", ldat)),
}
}
let kids = kids_mut(&mut rec)?;
let at = kids.iter().position(|c| c.is(b"cdat")).ok_or_else(|| tpl("value record without cdat"))?;
if let Some(slot) = kids.get_mut(at) {
*slot = list;
}
fill_key_list(&mut list, ldat, keys.len(), size)?;
replace_cdat(&mut rec, list)?;
}
}
if let Some((text, enabled)) = &p.expr {
@@ -1013,46 +946,7 @@ pub(crate) fn value_record(protos: &FxProtos, p: &ParamPlan, def: &ParDef, sourc
let at = kids.iter().position(|c| c.is(b"tdum")).unwrap_or(kids.len());
kids.insert(at, Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
}
Ok((Chunk::data(*b"tdmn", tdmn_bytes(&def.record)), rec))
}
/// A key of a colour (flags `0x0001`, 210, 364) or point (flags `0x0007`, `u32@8` the automatic
/// tangent switch, 382) parameter: the spatial layout with the value at 56.
fn spatial_record(kk: KeyedKind, k: &KeyPlan, n: usize, size: usize) -> R<Vec<u8>> {
let mut r = vec![0u8; size];
put(&mut r, 0, &k.time.to_be_bytes())?;
put_u8(&mut r, 4, k.in_interp)?;
put_u8(&mut r, 5, k.out_interp)?;
let base: u16 = if kk == KeyedKind::Point { 0x0007 } else { 0x0001 };
put_u16(&mut r, 6, base | (u16::from(k.label) << 6))?;
if kk == KeyedKind::Point {
put_u32(&mut r, 8, u32::from(k.spatial_auto))?;
// The temporal ease (598): speed in layer heights per second, influence a fraction.
let (i, o) = (k.in_ease.first().copied().unwrap_or_default(), k.out_ease.first().copied().unwrap_or_default());
put_f64(&mut r, 24, i.speed)?;
put_f64(&mut r, 32, i.influence)?;
put_f64(&mut r, 40, o.speed)?;
put_f64(&mut r, 48, o.influence)?;
}
for j in 0..n {
put_f64(&mut r, 56 + 8 * j, k.value.get(j).copied().unwrap_or(0.0))?;
if kk == KeyedKind::Point {
put_f64(&mut r, 56 + 8 * n + 8 * j, k.spatial_in.get(j).copied().unwrap_or(0.0))?;
put_f64(&mut r, 56 + 16 * n + 8 * j, k.spatial_out.get(j).copied().unwrap_or(0.0))?;
}
}
Ok(r)
}
/// A match name padded to the 40 bytes of `tdmn`.
fn tdmn_bytes(name: &str) -> Vec<u8> {
let mut v = vec![0u8; 40];
for (i, b) in name.bytes().take(39).enumerate() {
if let Some(slot) = v.get_mut(i) {
*slot = b;
}
}
v
Ok((tdmn(&def.record), rec))
}
/// The `tdmn` + `sspc` of one instance on the layer with id `layer_id`.
@@ -1066,14 +960,15 @@ fn instance(
) -> R<Vec<Chunk<'static>>> {
let (tdmn, sspc, _) = protos.defaults.get(fx.match_name).ok_or_else(|| tpl("effect prototype missing"))?;
let mut sspc = sspc.clone();
let pdefs = par_defs(&sspc);
// The prototype's definitions are the table's (the prototype is built from it).
let pdefs = defs().get(fx.match_name).ok_or_else(|| tpl("effect definitions missing"))?;
// `fnam` keeps the effect's own name; a name of the user's goes into the value group's
// `tdsn`, which holds the placeholder `-_0_/-` otherwise (610 against 609).
let own = child_mut(&mut sspc, b"fnam")?.children().iter().find(|c| c.is(b"Utf8")).and_then(|c| c.bytes()).map(|b| String::from_utf8_lossy(b).to_string());
if own.as_deref() != Some(fx.name.as_str()) && !fx.name.is_empty() {
let values = list_mut(&mut sspc, b"tdgp")?;
let slot = child_mut(values, b"tdsn")?;
*slot = nested(*b"tdsn", &fx.name);
*slot = utf8_in(*b"tdsn", &fx.name);
}
// The fx switch: the value group's `tdsb` (`fx-switch` cases).
put_u32(child_data(list_mut(&mut sspc, b"tdgp")?, b"tdsb")?, 0, u32::from(fx.enabled))?;
@@ -1086,9 +981,7 @@ fn instance(
let values = list_mut(&mut sspc, b"tdgp")?;
let kids = kids_mut(values)?;
// The input layer (`-0000`) names the layer that owns the effect (320).
let tdpi_of = |kids: &mut Vec<Chunk<'static>>, record: &str| -> Option<usize> {
kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(record)).map(|i| i + 1)
};
let tdpi_of = |kids: &mut Vec<Chunk<'static>>, record: &str| -> Option<usize> { kids.iter().position(|c| is_tdmn(c, record)).map(|i| i + 1) };
let input = pdefs.get(&0).map(|d| d.record.clone()).unwrap_or_default();
// The prototype's own layer id (its input layer), to tell "the owning layer" from None.
let mut proto_owner = None;
@@ -1108,7 +1001,7 @@ fn instance(
let mapped: Vec<u16> = by_match_name(fx.match_name)
.map(|s| s.params.iter().filter(|p| matches!(p.conv, Conv::LayerRef { .. })).filter_map(|p| u16::try_from(p.index).ok()).collect())
.unwrap_or_default();
for (index, def) in &pdefs {
for (index, def) in pdefs {
if *index == 0 || def.code != 0 {
continue;
}
@@ -1130,10 +1023,7 @@ fn instance(
// Arbitrary data: the `aRbp` of the `LIST aRbs` after the parameter's record.
if let Some((index, data)) = &fx.data {
let want = pdefs.get(index).map(|d| d.record.clone()).unwrap_or_default();
let i = kids
.iter()
.position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(want.as_str()))
.ok_or_else(|| tpl("arbitrary data record missing"))?;
let i = kids.iter().position(|c| is_tdmn(c, &want)).ok_or_else(|| tpl("arbitrary data record missing"))?;
let list = kids.iter_mut().skip(i + 1).take(3).find(|c| c.is_list(b"aRbs")).ok_or_else(|| tpl("arbitrary data missing"))?;
let arbp = child_mut(list, b"aRbp")?;
*data_mut(arbp)? = data.clone();
@@ -1161,7 +1051,7 @@ fn instance(
let Some(sel) = v.first().map(|x| x.round()).filter(|x| *x >= 1.0 && *x <= 1000.0) else { continue };
let want = pdefs.get(&p.index).map(|d| d.record.clone()).unwrap_or_default();
let kids = kids_mut(part)?;
if let Some(i) = kids.iter().position(|c| c.is(b"tdmn") && tdmn_name(c).as_deref() == Some(want.as_str()))
if let Some(i) = kids.iter().position(|c| is_tdmn(c, &want))
&& let Some(pard) = kids.get_mut(i + 1)
{
put_u32(data_mut(pard)?, 56, sel as u32)?;
@@ -1187,12 +1077,12 @@ pub(crate) fn build_parade(
source_size: (u32, u32),
uses: &mut FxUse,
) -> R<Vec<Chunk<'static>>> {
let mut kids = vec![Chunk::data(*b"tdsb", vec![0, 0, 0, 1]), tdsn("-_0_/-")];
let mut kids = vec![Chunk::data(*b"tdsb", vec![0, 0, 0, 1]), tdsn(NO_NAME)];
for fx in fxs {
kids.extend(instance(protos, fx, layer_id, layer_ids, source_size, uses)?);
}
kids.push(Chunk::data(*b"tdmn", tdmn_bytes("ADBE Group End")));
Ok(vec![Chunk::data(*b"tdmn", tdmn_bytes("ADBE Effect Parade")), Chunk::list(*b"tdgp", kids)])
kids.push(tdmn(crate::export::synth::GROUP_END));
Ok(vec![tdmn("ADBE Effect Parade"), Chunk::list(*b"tdgp", kids)])
}
/// Writes the project-level effect lists: `Pefl` (one `pjef` per type, sorted by match name, 365)
@@ -1219,3 +1109,209 @@ pub(crate) fn put_project_lists(protos: &FxProtos, file: &mut AepFile<'static>,
file.chunks.insert(at + 1, Chunk::list(*b"EfdG", efdg));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// The definitions as the importer's decoder reads them back from the prototype's `parT`
/// encoded from the table (the reference for [`ParDef::from_table`]; one `pard` decoder).
mod reference {
use super::super::*;
/// A definition as the decoder read it, with the name and popup items it also read.
pub(super) struct Old {
pub def: ParDef,
pub name: String,
pub items: Vec<String>,
}
/// An encoded `pard` as the importer's decoder (`container::Pard`) reads it, in the
/// export's stored units: what `ParDef::from_table` must agree with.
pub(super) fn from_pard(pard: &[u8], pdnm: Option<&str>, data: Option<&[u8]>) -> Old {
use crate::ParamValue as Pv;
let d = crate::container::Pard(pard);
let kind = d.kind();
let default: Vec<f64> = match d.default(kind) {
Some(Pv::Number(x)) => vec![x],
Some(Pv::Bool(on)) => vec![if on { 1.0 } else { 0.0 }],
Some(Pv::Index(i)) => vec![f64::from(i)],
Some(Pv::Point(pt)) => pt.to_vec(),
// Bytes 0..255, read as fractions.
Some(Pv::Argb(c)) => c.iter().map(|x| (x * 255.0).round()).collect(),
Some(Pv::Layer(_)) | None => Vec::new(),
};
let items = match pdnm {
Some(text) if kind == crate::ParamKind::Popup && !text.is_empty() => text.split('|').map(str::to_string).collect(),
_ => Vec::new(),
};
let name = match (kind, pdnm) {
(crate::ParamKind::Checkbox, Some(text)) if d.name().unwrap_or_default().trim().is_empty() => text.to_string(),
_ => d.name().unwrap_or_default(),
};
let def = ParDef {
record: String::new(),
code: d.code().unwrap_or(u32::MAX),
default,
range: d.slider_range(kind),
valid_max: d.valid_max(kind),
data: data.map(<[u8]>::to_vec),
};
Old { def, name, items }
}
/// The parameter definitions of an instance's `parT`, by position (the table's index).
pub(super) fn par_defs(sspc: &Chunk<'_>) -> HashMap<u16, Old> {
let mut out = HashMap::new();
let Some(part) = sspc.child_list(b"parT") else { return out };
let k = part.children();
let mut i = 0usize;
let mut position = 0u16;
while i < k.len() {
let (Some(m), Some(p)) = (k.get(i), k.get(i + 1)) else { break };
if !(m.is(b"tdmn") && p.is(b"pard")) {
i += 1;
continue;
}
let name = tdmn_name(m).unwrap_or_default();
let mut j = i + 2;
let mut pdnm = None;
let mut data = None;
while let Some(c) = k.get(j) {
if c.is(b"tdmn") {
break;
}
if c.is(b"pdnm") {
pdnm = c.children().iter().find(|u| u.is(b"Utf8")).and_then(|u| u.bytes()).map(|b| String::from_utf8_lossy(b).to_string());
}
if c.is(b"aRbp") {
data = c.bytes();
}
j += 1;
}
if let Some(bytes) = p.bytes() {
let mut old = from_pard(bytes, pdnm.as_deref(), data);
old.def.record = name;
out.insert(position, old);
}
position = position.saturating_add(1);
i = j;
}
out
}
}
fn bits(v: &[f64]) -> Vec<u64> {
v.iter().map(|x| x.to_bits()).collect()
}
/// Every field equal, numbers bit for bit.
fn assert_same(a: &HashMap<u16, reference::Old>, b: &HashMap<u16, ParDef>, what: &str) {
let mut keys: Vec<&u16> = a.keys().collect();
keys.sort_unstable();
assert_eq!(keys.len(), b.len(), "{what}");
for k in keys {
let (old, y) = (&a[k], b.get(k).unwrap_or_else(|| panic!("{what}: {k}")));
// The prototypes name no parameter and no popup item.
assert!(old.name.is_empty() && old.items.is_empty(), "{what}: parameter {k}");
let x = &old.def;
let range = |r: Option<(f64, f64)>| r.map(|(lo, hi)| (lo.to_bits(), hi.to_bits()));
assert_eq!(
(&x.record, x.code, bits(&x.default), range(x.range), x.valid_max.map(f64::to_bits), &x.data),
(&y.record, y.code, bits(&y.default), range(y.range), y.valid_max.map(f64::to_bits), &y.data),
"{what}: parameter {k}"
);
}
}
#[test]
fn the_table_definitions_equal_the_encoded_and_parsed_ones() {
for fx in FX_DEFS {
let sspc = crate::export::fxsynth::default_sspc(fx);
// The decoder only tells a checkbox on from off: the table's words are 0 or 1.
let part = sspc.child_list(b"parT").map(|p| p.children()).unwrap_or_default();
for pard in part.iter().filter(|c| c.is(b"pard")).filter_map(|c| c.bytes()) {
if crate::container::Pard(pard).kind() == crate::ParamKind::Checkbox {
let word = pard.get(56..60).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
assert!(matches!(word, Some(0 | 1)), "{}: checkbox word {word:?}", fx.match_name);
}
}
let parsed = reference::par_defs(&sspc);
assert_same(&parsed, &ParDef::of_effect(fx), fx.match_name);
}
}
#[test]
fn a_record_name_that_is_not_ascii_is_found_in_its_prototype() {
static PARAMS: [PDef; 1] = [PDef { id: 1, code: 2, default: &[0.0], range: None, valid_max: None, valid_min: None, display: 0 }];
let fx = FxDef { match_name: "Effekt Größe", name: "x", params: &PARAMS };
let record = ParDef::of_effect(&fx).get(&0).map(|d| d.record.clone()).expect("the parameter");
assert_eq!(record, "Effekt Größe-0001");
let sspc = crate::export::fxsynth::default_sspc(&fx);
let part = sspc.child_list(b"parT").expect("parT");
assert!(part.children().iter().any(|c| is_tdmn(c, &record)));
}
#[test]
fn generated_definitions_equal_the_encoded_and_parsed_ones() {
// Every parameter type with defaults, ranges and maxima that are fractional, negative,
// huge, beyond the 16.16 and f32 ranges, and not numbers.
let values = [0.0, -0.0, 1.0, -1.0, 0.5, 1.0 / 3.0, 1.01, 100.0, 255.4, 255.6, 256.0, -3.7, 65535.6, 70000.0, 1e9, -1e9, 1e40, f64::NAN, f64::INFINITY];
let mut state = 7u64;
let mut pick = move |n: usize| {
state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
usize::try_from(state >> 33).unwrap_or(0) % n
};
for round in 0..400 {
let params: Vec<PDef> = (0..16u16)
.map(|id| {
let code = [0u8, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15][pick(15)];
let default: &'static [f64] = Box::leak((0..pick(5)).map(|_| values[pick(values.len())]).collect::<Vec<_>>().into_boxed_slice());
let opt = |pick: &mut dyn FnMut(usize) -> usize| (pick(3) > 0).then(|| values[pick(values.len())]);
let range = opt(&mut pick).map(|lo| (lo, values[pick(values.len())]));
PDef { id, code, default, range, valid_max: opt(&mut pick), valid_min: opt(&mut pick), display: u32::try_from(pick(40)).unwrap_or(0) }
})
.collect();
let fx =
FxDef { match_name: Box::leak(format!("Generated {round}").into_boxed_str()), name: "Generated", params: Box::leak(params.into_boxed_slice()) };
let parsed = reference::par_defs(&crate::export::fxsynth::default_sspc(&fx));
assert_same(&parsed, &ParDef::of_effect(&fx), fx.match_name);
}
}
fn group(effect: &str, text: (&str, &str)) -> PropGroup {
let spec = effectcraft_effects::find(effect).expect("the effect");
let mut next = 1;
let mut g = effectcraft_effects::instantiate(spec, &mut effectcraft_project::build::Ids(&mut next), "fx", [100.0, 100.0]);
g.prop_mut(text.0).expect("the text parameter").value = Value::Str(text.1.to_string());
g
}
fn invalid(col: Collector) -> Vec<String> {
col.finish().losses.into_iter().filter(|l| l.category == LossCategory::InvalidValues).flat_map(|l| l.details).collect()
}
#[test]
fn unreadable_curve_points_are_reported() {
let pdefs = defs().get("ADBE CurvesCustom").expect("the Curves prototype");
let mut col = Collector::default();
plan_curves(&group("ec.color.curves", ("rgb", "0,0 junk 0.5,0.7 nan,1 1,1")), pdefs, "fx", &mut col);
let found = invalid(col);
assert!(found.iter().any(|d| d.contains("curve 'rgb': 2 entries")), "{found:?}");
let mut col = Collector::default();
plan_curves(&group("ec.color.curves", ("rgb", "0,0 0.5,0.7 1,1")), pdefs, "fx", &mut col);
assert_eq!(invalid(col), Vec::<String>::new());
}
#[test]
fn unreadable_mesh_entries_are_reported() {
let pdefs = defs().get("ADBE MESH WARP").expect("the Mesh Warp prototype");
let mut col = Collector::default();
plan_mesh(&group("ec.distort.meshwarp", ("mesh", "0,0 x,1 2")), pdefs, (100.0, 100.0), "fx", &mut col);
let found = invalid(col);
assert!(found.iter().any(|d| d.contains("2 entries that are not numbers")), "{found:?}");
let mut col = Collector::default();
plan_mesh(&group("ec.distort.meshwarp", ("mesh", "0,0 1,1")), pdefs, (100.0, 100.0), "fx", &mut col);
assert_eq!(invalid(col), Vec::<String>::new());
}
}
+13 -3
View File
@@ -39,7 +39,17 @@ pub(crate) fn value_spec(code: u8, range: Option<(f64, f64)>) -> Option<RecSpec>
}
fn fixed(v: f64) -> [u8; 4] {
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
fixed_i32(v).to_be_bytes()
}
/// A number as the 16.16 `i32` a `pard` stores it in (rounded, within the `i32` range).
pub(crate) fn fixed_i32(v: f64) -> i32 {
(v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32
}
/// A number as the `i32` of an integer slider's `pard` (rounded).
pub(crate) fn int_i32(v: f64) -> i32 {
v.round() as i32
}
/// The 148-byte `pard` of a parameter: the type at 12, the default at 56 and the copies After
@@ -71,7 +81,7 @@ fn pard_layout(p: &PDef, popup_items: Option<u16>) -> Fixed {
b.put(56, &fixed(d(0)));
b.put(60, &fixed(d(0)));
}
1 => b.put(56, &(d(0).round() as i32).to_be_bytes()),
1 => b.put(56, &int_i32(d(0)).to_be_bytes()),
// A checkbox: the default again as a byte at 60.
4 => {
b.put(56, &(d(0).round().max(0.0) as u32).to_be_bytes());
@@ -116,7 +126,7 @@ fn pard_layout(p: &PDef, popup_items: Option<u16>) -> Fixed {
}
}
1 | 2 => {
let enc = |v: f64| if p.code == 2 { fixed(v) } else { (v.round() as i32).to_be_bytes() };
let enc = |v: f64| if p.code == 2 { fixed(v) } else { int_i32(v).to_be_bytes() };
if let Some(m) = p.valid_min {
b.put(124, &enc(m));
}
+359 -51
View File
@@ -2,7 +2,7 @@
//! file's units, with everything that cannot be written already reported. Pure data; the chunks
//! are built from it in `emit`.
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use effectcraft_color::{BlendMode, Label};
use effectcraft_keyframe::{Ease, Interp, Keyframe};
@@ -11,6 +11,7 @@ use effectcraft_time::{FrameRate, Tick};
use crate::export::report::{Collector, LossCategory};
use crate::export::timebase::{TimeBase, time_base};
use crate::import::build::{closes_loop, components};
/// No sensible coordinate, angle or percentage comes near this; larger numbers (and NaN
/// or infinity) are written as the default.
@@ -352,24 +353,40 @@ pub(crate) fn natural_key(name: &str) -> Vec<(bool, String, u128)> {
out
}
fn sort_entries(v: &mut [Entry]) {
v.sort_by(|a, b| {
let ka = natural_key(&a.name);
let kb = natural_key(&b.name);
let cmp = |x: &(bool, String, u128), y: &(bool, String, u128)| match (x.0, y.0) {
(true, true) => x.2.cmp(&y.2).then_with(|| x.1.cmp(&y.1)),
(false, false) => x.1.cmp(&y.1),
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
};
for (x, y) in ka.iter().zip(kb.iter()) {
let c = cmp(x, y);
/// A [`natural_key`] ordered segment by segment: a number before text, numbers by value and then
/// by their digits, text by its lowercase string, and a key that is a prefix of the other first.
/// (The derived order of the tuples is not this one: it puts text first and compares the digits
/// before the value.)
#[derive(PartialEq, Eq)]
struct Natural(Vec<(bool, String, u128)>);
impl Ord for Natural {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
for (x, y) in self.0.iter().zip(other.0.iter()) {
let c = match (x.0, y.0) {
(true, true) => x.2.cmp(&y.2).then_with(|| x.1.cmp(&y.1)),
(false, false) => x.1.cmp(&y.1),
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
};
if c != std::cmp::Ordering::Equal {
return c;
}
}
ka.len().cmp(&kb.len()).then_with(|| a.ec.0.cmp(&b.ec.0))
});
self.0.len().cmp(&other.0.len())
}
}
impl PartialOrd for Natural {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Sorts by name in natural order, then by project id. Each name's key is built once, not on
/// every comparison (the sort is stable, as `sort_by` is).
fn sort_entries(v: &mut [Entry]) {
v.sort_by_cached_key(|e| (Natural(natural_key(&e.name)), e.ec.0));
}
/// Plans the whole project.
@@ -408,7 +425,8 @@ pub(crate) fn plan(project: &Project, col: &mut Collector) -> ProjectPlan {
by_parent.entry(item.parent.filter(|p| project.items.contains_key(p))).or_default().push(*id);
}
}
let cx = PlanCx { project, by_parent: &by_parent, ok: &ok };
let component = components(&precomp_links(project));
let cx = PlanCx { project, by_parent: &by_parent, ok: &ok, component: &component };
let root = plan_children(&cx, None, col);
// The base writes an empty render queue.
for job in &project.render_queue {
@@ -422,6 +440,8 @@ struct PlanCx<'a> {
project: &'a Project,
by_parent: &'a BTreeMap<Option<ItemId>, Vec<ItemId>>,
ok: &'a HashSet<ItemId>,
/// The component of each composition in the precomposition links ([`precomp_loop`]).
component: &'a HashMap<ItemId, usize>,
}
fn plan_children(cx: &PlanCx<'_>, parent: Option<ItemId>, col: &mut Collector) -> Vec<Entry> {
@@ -627,16 +647,17 @@ fn plan_comp(cx: &PlanCx<'_>, comp_id: ItemId, name: &str, comp: &Comp, col: &mu
cp.layers.push(lp);
}
}
resolve_parents(&mut cp, name, col);
resolve_mattes(&mut cp, name, col);
resolve_effect_layers(&mut cp, name, col);
// The layers that are written; none of the three steps below adds or removes one.
let exported: HashSet<LayerId> = cp.layers.iter().map(|l| l.ec_id).collect();
resolve_parents(&mut cp, &exported, name, col);
resolve_mattes(&mut cp, &exported, name, col);
resolve_effect_layers(&mut cp, &exported, name, col);
cp
}
/// An effect's layer parameter that names a layer that is not exported falls back to the owning
/// layer (After Effects' default) and is reported.
fn resolve_effect_layers(cp: &mut CompPlan, comp_name: &str, col: &mut Collector) {
let exported: HashSet<LayerId> = cp.layers.iter().map(|l| l.ec_id).collect();
fn resolve_effect_layers(cp: &mut CompPlan, exported: &HashSet<LayerId>, comp_name: &str, col: &mut Collector) {
for l in &mut cp.layers {
for fx in &mut l.fx {
let before = fx.layers.len();
@@ -655,8 +676,7 @@ fn resolve_effect_layers(cp: &mut CompPlan, comp_name: &str, col: &mut Collector
}
/// A track matte whose layer is not exported, or is the layer itself, is dropped and reported.
fn resolve_mattes(cp: &mut CompPlan, comp_name: &str, col: &mut Collector) {
let exported: HashSet<LayerId> = cp.layers.iter().map(|l| l.ec_id).collect();
fn resolve_mattes(cp: &mut CompPlan, exported: &HashSet<LayerId>, comp_name: &str, col: &mut Collector) {
for l in &mut cp.layers {
if let Some((m, _)) = l.matte
&& (m == l.ec_id || !exported.contains(&m))
@@ -668,17 +688,95 @@ fn resolve_mattes(cp: &mut CompPlan, comp_name: &str, col: &mut Collector) {
}
/// Parent links to a layer that was not exported, and links that lead into a loop, are cut.
fn resolve_parents(cp: &mut CompPlan, comp_name: &str, col: &mut Collector) {
let exported: HashSet<LayerId> = cp.layers.iter().map(|l| l.ec_id).collect();
let mut links: std::collections::HashMap<LayerId, LayerId> = cp.layers.iter().filter_map(|l| l.parent.map(|p| (l.ec_id, p))).collect();
for l in &mut cp.layers {
let Some(p) = l.parent else { continue };
fn resolve_parents(cp: &mut CompPlan, exported: &HashSet<LayerId>, comp_name: &str, col: &mut Collector) {
let links: Vec<(LayerId, Option<LayerId>)> = cp.layers.iter().map(|l| (l.ec_id, l.parent)).collect();
let cut = parents_to_cut(&links, exported);
for (l, cut) in cp.layers.iter_mut().zip(cut) {
if cut {
col.lose(LossCategory::ParentLinks, format!("{comp_name}: '{}' has a parent that was not exported or forms a loop", l.name));
l.parent = None;
}
}
}
/// Which parent links (`(layer, parent)` in stack order) are cut: one to a layer that is not
/// exported, and, of each loop, the link of its first layer in stack order (cutting it opens
/// the loop, so the others stay).
///
/// Each parent chain used to be walked from every layer (a chain of N layers took N² steps).
/// With unique layer ids each layer has one link, the links form chains and disjoint loops, and
/// the layers on a loop are found once ([`loop_of`]). Repeated ids (not made by EffectCraft)
/// keep the walk ([`parents_to_cut_by_walk`]).
fn parents_to_cut(links: &[(LayerId, Option<LayerId>)], exported: &HashSet<LayerId>) -> Vec<bool> {
if exported.len() != links.len() {
return parents_to_cut_by_walk(links, exported);
}
let on_loop = loop_of(&links.iter().filter_map(|(l, p)| p.map(|p| (*l, p))).collect());
let mut opened: HashSet<usize> = HashSet::new();
links
.iter()
.map(|(l, p)| match p {
None => false,
Some(p) if !exported.contains(p) => true,
Some(_) => on_loop.get(l).is_some_and(|lp| opened.insert(*lp)),
})
.collect()
}
/// The loop each layer is on (a number per loop), for the links `layer -> parent`. Each layer is
/// visited once.
fn loop_of(links: &HashMap<LayerId, LayerId>) -> HashMap<LayerId, usize> {
// Absent: not seen; `false`: on the chain being walked; `true`: finished.
let mut done: HashMap<LayerId, bool> = HashMap::with_capacity(links.len());
let mut on_loop: HashMap<LayerId, usize> = HashMap::new();
let mut loops = 0usize;
for &start in links.keys() {
let mut chain = Vec::new();
let mut at = start;
loop {
match done.get(&at) {
Some(false) => {
// Back on the chain: the part from `at` on is a loop.
if let Some(i) = chain.iter().position(|l| *l == at) {
for l in chain.get(i..).unwrap_or_default() {
on_loop.insert(*l, loops);
}
loops = loops.saturating_add(1);
}
break;
}
Some(true) => break,
None => {}
}
done.insert(at, false);
chain.push(at);
match links.get(&at) {
Some(next) => at = *next,
None => break,
}
}
for l in chain {
done.insert(l, true);
}
}
on_loop
}
/// [`parents_to_cut`] by following each chain from its layer (for repeated layer ids): a chain
/// longer than the number of links is a loop.
fn parents_to_cut_by_walk(layers: &[(LayerId, Option<LayerId>)], exported: &HashSet<LayerId>) -> Vec<bool> {
let mut links: HashMap<LayerId, LayerId> = layers.iter().filter_map(|(l, p)| p.map(|p| (*l, p))).collect();
let mut out = Vec::with_capacity(layers.len());
for (l, p) in layers {
let Some(p) = *p else {
out.push(false);
continue;
};
let mut cut = !exported.contains(&p);
if !cut {
// Follow the chain; a chain longer than the number of links is a loop.
let mut at = p;
for _ in 0..=links.len() {
if at == l.ec_id {
if at == *l {
cut = true;
break;
}
@@ -687,16 +785,16 @@ fn resolve_parents(cp: &mut CompPlan, comp_name: &str, col: &mut Collector) {
None => break,
}
}
if !cut && at == l.ec_id {
if !cut && at == *l {
cut = true;
}
}
if cut {
col.lose(LossCategory::ParentLinks, format!("{comp_name}: '{}' has a parent that was not exported or forms a loop", l.name));
links.remove(&l.ec_id);
l.parent = None;
links.remove(l);
}
out.push(cut);
}
out
}
/// The source of a layer and its size; `None` (with a loss) for a layer that is not written.
@@ -761,7 +859,7 @@ fn plan_source(
}
},
LayerSource::Comp { item } => match cx.project.item(*item).filter(|_| cx.ok.contains(item)).map(|i| &i.kind) {
Some(ItemKind::Comp(c)) if !precomp_loop(cx.project, comp_id, *item) => {
Some(ItemKind::Comp(c)) if !precomp_loop(cx.component, comp_id, *item) => {
(LayerSrc::Comp(*item), (c.width.clamp(1, MAX_SIDE), c.height.clamp(1, MAX_SIDE)))
}
Some(ItemKind::Comp(_)) => {
@@ -1115,27 +1213,28 @@ fn has_bezier_keys(g: &effectcraft_project::PropGroup, depth: usize) -> bool {
})
}
/// Whether showing the composition `to` inside `from` closes a loop (`to` is `from`, or uses it
/// through its own precomposition layers). The walk is iterative and visits each item once.
fn precomp_loop(project: &Project, from: ItemId, to: ItemId) -> bool {
let mut seen: HashSet<ItemId> = HashSet::new();
let mut stack = vec![to];
while let Some(at) = stack.pop() {
if at == from {
return true;
}
if !seen.insert(at) {
continue;
}
if let Some(ItemKind::Comp(c)) = project.item(at).map(|i| &i.kind) {
for l in &c.layers {
/// Every precomposition link of the project once: composition -> the items its layers show.
fn precomp_links(project: &Project) -> HashMap<ItemId, HashSet<ItemId>> {
let mut links: HashMap<ItemId, HashSet<ItemId>> = HashMap::new();
for (id, item) in &project.items {
if let ItemKind::Comp(c) = &item.kind {
for l in c.layers.iter() {
if let LayerSource::Comp { item } = &l.source {
stack.push(*item);
links.entry(*id).or_default().insert(*item);
}
}
}
}
false
links
}
/// Whether showing the composition `to` in `from` closes a loop: `to` is `from` or uses it
/// through its own precomposition layers. The layer itself links `from` to `to`, so `to` uses
/// `from` exactly when both are in one component of the project's precomposition links
/// (`component`, found once per export). Before, every precomposition layer walked the layers of
/// every composition below its source (N layers of a precomposition with N layers took N² steps).
fn precomp_loop(component: &HashMap<ItemId, usize>, from: ItemId, to: ItemId) -> bool {
closes_loop(from, to, |to| matches!((component.get(&from), component.get(&to)), (Some(a), Some(b)) if a == b))
}
/// The names of a layer's Material Options that differ from a new layer's (value, keys or an
@@ -1346,3 +1445,212 @@ fn plan_remap(p: &Property, comp: &Comp, cp: &CompPlan, layer: &str, comp_name:
}
plan
}
#[cfg(test)]
mod tests {
use super::*;
/// The comparator as it was written before the keys were cached (the reference).
fn old_cmp(a: &str, b: &str) -> std::cmp::Ordering {
let (ka, kb) = (natural_key(a), natural_key(b));
let cmp = |x: &(bool, String, u128), y: &(bool, String, u128)| match (x.0, y.0) {
(true, true) => x.2.cmp(&y.2).then_with(|| x.1.cmp(&y.1)),
(false, false) => x.1.cmp(&y.1),
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
};
for (x, y) in ka.iter().zip(kb.iter()) {
let c = cmp(x, y);
if c != std::cmp::Ordering::Equal {
return c;
}
}
ka.len().cmp(&kb.len())
}
/// A pseudo-random generator for the differential tests.
fn lcg(seed: u64) -> impl FnMut(u64) -> u64 {
let mut state = seed;
move |n| {
state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
(state >> 33) % n.max(1)
}
}
#[test]
fn parent_links_are_cut_as_the_walk_cut_them() {
for seed in 0..500 {
let mut next = lcg(seed);
let n = 1 + next(12);
// Unique ids, or (one seed in five) some repeated; parents among the layers, missing
// ones (not exported) and none.
let ids: Vec<LayerId> = (0..n).map(|i| LayerId(if seed % 5 == 0 { next(n) } else { i })).collect();
let links: Vec<(LayerId, Option<LayerId>)> = ids
.iter()
.map(|l| {
let p = match next(4) {
0 => None,
1 => Some(LayerId(100 + next(3))),
_ => Some(LayerId(next(n))),
};
(*l, p)
})
.collect();
let exported: HashSet<LayerId> = ids.iter().copied().collect();
assert_eq!(parents_to_cut(&links, &exported), parents_to_cut_by_walk(&links, &exported), "{links:?}");
}
}
#[test]
fn a_long_parent_chain_is_resolved_in_linear_time() {
// 200 000 layers each parented to the next and the last to the first: one link is cut.
// Walking the chain from every layer (as before) is 4e10 steps.
let n = 200_000u64;
let links: Vec<(LayerId, Option<LayerId>)> = (0..n).map(|i| (LayerId(i), Some(LayerId((i + 1) % n)))).collect();
let exported: HashSet<LayerId> = (0..n).map(LayerId).collect();
let cut = parents_to_cut(&links, &exported);
assert_eq!(cut.iter().filter(|c| **c).count(), 1);
assert!(cut[0]);
}
/// The loop check as it was (the reference): a walk from `to` over the layers of every
/// composition below it.
fn old_precomp_loop(project: &Project, from: ItemId, to: ItemId) -> bool {
let mut seen: HashSet<ItemId> = HashSet::new();
let mut stack = vec![to];
while let Some(at) = stack.pop() {
if at == from {
return true;
}
if !seen.insert(at) {
continue;
}
if let Some(ItemKind::Comp(c)) = project.item(at).map(|i| &i.kind) {
for l in c.layers.iter() {
if let LayerSource::Comp { item } = &l.source {
stack.push(*item);
}
}
}
}
false
}
/// A project with `comps` compositions; composition `i` shows the items `shows(i)` (repeats
/// and non-compositions allowed), as layers.
fn project_of(comps: usize, shows: &mut dyn FnMut(usize) -> Vec<usize>) -> (Project, Vec<ItemId>) {
use effectcraft_project::build;
let mut p = Project::default();
let solid = p.add_item(
"S",
effectcraft_color::Label::None,
None,
ItemKind::Solid(effectcraft_project::Solid { color: [0.0; 3], width: 4, height: 4, pixel_aspect: 1.0 }),
);
let ids: Vec<ItemId> = (0..comps)
.map(|i| {
let c = Comp::new(4, 4, effectcraft_time::FrameRate::new(25, 1), Tick(effectcraft_time::TICKS_PER_SECOND));
p.add_item(&format!("C{i}"), effectcraft_color::Label::None, None, ItemKind::Comp(std::sync::Arc::new(c)))
})
.collect();
for (i, id) in ids.iter().enumerate() {
let Some(mut c) = p.comp(*id).cloned() else { continue };
for s in shows(i) {
let source = match ids.get(s) {
Some(item) => LayerSource::Comp { item: *item },
None => LayerSource::Solid { item: solid },
};
let l = build::layer(&mut p, &c, "L", source, (4, 4), None);
c.layers.push(l);
}
if let Some(item) = p.item_mut(*id) {
item.kind = ItemKind::Comp(std::sync::Arc::new(c));
}
}
(p, ids)
}
#[test]
fn precomp_loops_are_found_as_the_walk_found_them() {
for seed in 0..300 {
let mut next = lcg(seed);
let comps = 1 + usize::try_from(next(10)).unwrap_or(0);
let (p, ids) = project_of(comps, &mut |_| (0..next(6)).map(|_| usize::try_from(next(comps as u64 + 2)).unwrap_or(0)).collect());
let component = components(&precomp_links(&p));
for from in &ids {
let Some(c) = p.comp(*from) else { continue };
for l in c.layers.iter() {
if let LayerSource::Comp { item } = &l.source {
assert_eq!(precomp_loop(&component, *from, *item), old_precomp_loop(&p, *from, *item), "{from:?} -> {item:?}");
}
}
}
}
}
#[test]
fn layered_precomps_are_checked_in_linear_time() {
// K top compositions each show K middle ones, each of which shows K leaves: the old walk
// from every layer took K^3 steps; the components are found once.
let k = 60;
let (p, ids) = project_of(3 * k, &mut |i| if i < 2 * k { (0..k).map(|j| if i < k { k + j } else { 2 * k + j }).collect() } else { Vec::new() });
let component = components(&precomp_links(&p));
let mut checked = 0;
for from in &ids {
let Some(c) = p.comp(*from) else { continue };
for l in c.layers.iter() {
if let LayerSource::Comp { item } = &l.source {
assert!(!precomp_loop(&component, *from, *item));
checked += 1;
}
}
}
assert_eq!(checked, 2 * k * k);
// One more layer, a leaf showing a top composition, closes a loop through all three.
let (p, ids) = project_of(3 * k, &mut |i| match i {
_ if i < k => (k..2 * k).collect(),
_ if i < 2 * k => (2 * k..3 * k).collect(),
_ if i == 2 * k => vec![0],
_ => Vec::new(),
});
let component = components(&precomp_links(&p));
assert!(precomp_loop(&component, ids[2 * k], ids[0]));
assert!(precomp_loop(&component, ids[0], ids[k]));
assert!(!precomp_loop(&component, ids[k], ids[2 * k + 1]));
}
#[test]
fn the_cached_natural_key_orders_as_the_comparator_did() {
let names = [
"",
"a",
"A",
"a1",
"a01",
"a001",
"a2",
"a10",
"1",
"01",
"001",
"10",
"1a",
"a b",
"a-b",
"Comp 2",
"comp 10",
"Comp 1 copy",
"ß",
"Ä 3",
"x99999999999999999999999999999999999999999999",
"x100000000000000000000000000000000000000000000",
"Solids",
"solids 0",
];
for a in names {
for b in names {
assert_eq!(Natural(natural_key(a)).cmp(&Natural(natural_key(b))), old_cmp(a, b), "{a:?} {b:?}");
}
}
}
}
+5 -4
View File
@@ -250,11 +250,11 @@ impl Collector {
}
pub fn finish(self) -> ExportReport {
ExportReport {
exported: self.exported,
losses: self.losses.into_values().collect(),
limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect(),
let mut losses: Vec<_> = self.losses.into_values().collect();
for loss in &mut losses {
loss.unlisted = loss.count.saturating_sub(loss.details.len());
}
ExportReport { exported: self.exported, losses, limitations: LIMITATIONS.iter().map(|s| (*s).to_string()).collect() }
}
}
@@ -308,5 +308,6 @@ mod tests {
let report = col.finish();
assert_eq!(report.count(LossCategory::Masks), MAX_DETAILS + 5);
assert_eq!(report.losses[0].details.len(), MAX_DETAILS);
assert_eq!(report.losses[0].unlisted, 5);
}
}
+1 -1
View File
@@ -25,7 +25,7 @@
//! for wasm32; it reads no files itself: the caller passes the bytes, a way to ask whether a
//! footage path exists and one to ask whether a font is installed.
mod build;
pub(crate) mod build;
mod camera;
mod effects;
mod lumetri;
+506 -56
View File
@@ -57,7 +57,7 @@ struct PendingComp<'f, 'a> {
struct Ctx<'o> {
sources: HashMap<u32, Source>,
/// Which comps use which comps as precomps (to refuse loops).
uses: HashMap<ItemId, Vec<ItemId>>,
precomps: Precomps,
created: Vec<ItemId>,
col: Collector,
options: &'o ImportOptions<'o>,
@@ -70,7 +70,7 @@ struct Ctx<'o> {
pub(crate) fn run(project: &mut Project, view: &AepProject<'_, '_>, options: &ImportOptions<'_>) -> (ItemId, Vec<ItemId>, Vec<ItemId>, ImportReport) {
let mut cx = Ctx {
sources: HashMap::new(),
uses: HashMap::new(),
precomps: Precomps::default(),
created: Vec::new(),
col: Collector::default(),
options,
@@ -102,9 +102,9 @@ pub(crate) fn run(project: &mut Project, view: &AepProject<'_, '_>, options: &Im
// After Effects writes an `Sfdr` even for an empty folder (and other chunks next to the
// items in it); without one the contents are lost.
if !item.has_folder_contents() {
cx.col.lose(LossCategory::DamagedData, format!("folder '{name}': its contents list is missing, imported empty"));
cx.col.lose_with(LossCategory::DamagedData, || format!("folder '{name}': its contents list is missing, imported empty"));
} else if item.folder_contents_unreadable() {
cx.col.lose(LossCategory::DamagedData, format!("folder '{name}': its contents list is damaged, imported empty"));
cx.col.lose_with(LossCategory::DamagedData, || format!("folder '{name}': its contents list is damaged, imported empty"));
}
let mut kids: Vec<_> = item.children().map(|k| (k, id)).collect();
kids.reverse();
@@ -113,16 +113,16 @@ pub(crate) fn run(project: &mut Project, view: &AepProject<'_, '_>, options: &Im
Some(AepKind::Composition) => {
let name = if name.is_empty() { "Composition".to_string() } else { name };
let Some(comp_view) = item.comp() else {
cx.col.lose(LossCategory::DamagedData, format!("composition '{name}': composition data missing, not imported"));
cx.col.lose_with(LossCategory::DamagedData, || format!("composition '{name}': composition data missing, not imported"));
continue;
};
let Some(header) = comp_view.header() else {
cx.col.lose(LossCategory::DamagedData, format!("composition '{name}': header unreadable, not imported"));
cx.col.lose_with(LossCategory::DamagedData, || format!("composition '{name}': header unreadable, not imported"));
continue;
};
let tb = header.time_base;
let Some(rate) = frame_rate(tb.timescale, tb.frame_duration) else {
cx.col.lose(LossCategory::DamagedData, format!("composition '{name}': time base unreadable, not imported"));
cx.col.lose_with(LossCategory::DamagedData, || format!("composition '{name}': time base unreadable, not imported"));
continue;
};
let map = TimeMap { timescale: tb.timescale, frame_duration: tb.frame_duration, rate };
@@ -138,12 +138,13 @@ pub(crate) fn run(project: &mut Project, view: &AepProject<'_, '_>, options: &Im
pending.push(PendingComp { id, item, map });
}
Some(AepKind::Footage) => import_footage(project, &mut cx, &item, name, label, parent, &null_only),
Some(AepKind::Other(code)) => cx.col.lose(LossCategory::UnsupportedItems, format!("'{name}': item type {code}")),
Some(AepKind::Other(code)) => cx.col.lose_with(LossCategory::UnsupportedItems, || format!("'{name}': item type {code}")),
None => cx.col.lose(LossCategory::DamagedData, "a project item without a readable type".to_string()),
}
}
// Pass 2: the layers. The effect definitions are indexed once for every layer of every comp.
cx.precomps = Precomps::new(&precomp_candidates(&cx.sources, &pending));
let defs = view.effect_definition_index();
for p in &pending {
build_layers(project, &mut cx, &defs, p);
@@ -186,12 +187,12 @@ fn new_comp(h: &CompHeader, renderer: Option<AepRenderer>, map: &TimeMap, name:
comp.work_area = if start >= Tick::ZERO && end > start {
(start, end)
} else {
col.lose(LossCategory::DamagedData, format!("composition '{name}': the work area is empty or negative, the whole composition is used"));
col.lose_with(LossCategory::DamagedData, || format!("composition '{name}': the work area is empty or negative, the whole composition is used"));
(Tick::ZERO, duration)
};
comp.background = h.background.map(|c| f32::from(c) / 255.0);
comp.pixel_aspect = h.pixel_aspect.to_f64().filter(|v| v.is_finite() && *v > 0.0).unwrap_or_else(|| {
col.lose(LossCategory::DamagedData, format!("composition '{name}': the pixel aspect ratio is not valid, 1 is used"));
col.lose_with(LossCategory::DamagedData, || format!("composition '{name}': the pixel aspect ratio is not valid, 1 is used"));
1.0
});
comp.shutter_angle = f64::from(h.shutter_angle);
@@ -211,7 +212,7 @@ fn new_comp(h: &CompHeader, renderer: Option<AepRenderer>, map: &TimeMap, name:
/// Unreadable footage is recorded as a loss, solids and null placeholders are handled separately, and file and sequence footage is linked to its files.
fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_>, name: String, label: Label, parent: ItemId, null_only: &HashSet<u32>) {
let Some(f) = item.footage() else {
cx.col.lose(LossCategory::DamagedData, format!("footage '{name}': data unreadable, not imported"));
cx.col.lose_with(LossCategory::DamagedData, || format!("footage '{name}': data unreadable, not imported"));
return;
};
let aep_id = item.id();
@@ -240,7 +241,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
let mut rgb = f.solid_rgb().unwrap_or([0.0; 3]);
if rgb.iter().any(|c| !c.is_finite()) {
rgb = rgb.map(|c| if c.is_finite() { c } else { 0.0 });
cx.col.lose(LossCategory::DamagedData, format!("solid '{name}': a color channel is not a number, replaced by 0"));
cx.col.lose_with(LossCategory::DamagedData, || format!("solid '{name}': a color channel is not a number, replaced by 0"));
}
let solid = Solid { color: rgb, width: f.width, height: f.height, pixel_aspect: 1.0 };
let id = project.add_item(&name, label, Some(parent), ItemKind::Solid(solid));
@@ -273,10 +274,9 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
let bytes = len(folder.len().saturating_add(1)).saturating_mul(u64::from(frames)).saturating_add(file_bytes);
if frames > MAX_SEQUENCE_FRAMES || frames > cx.sequence_budget || bytes > cx.sequence_bytes {
// Not expanded: the item keeps its first file (a still standing for the sequence).
cx.col.lose(
LossCategory::DamagedData,
format!("footage '{name}': a sequence of {frames} frames is longer than the import expands; only its first file is linked"),
);
cx.col.lose_with(LossCategory::DamagedData, || {
format!("footage '{name}': a sequence of {frames} frames is longer than the import expands; only its first file is linked")
});
path = format!("{folder}{sep}{}", seq.nth_file_name(0).unwrap_or_default());
} else {
cx.sequence_budget -= frames;
@@ -288,7 +288,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
}
} else if f.is_sequence && !path.is_empty() {
// The alias is a folder, but the file names could not be read: the item links the folder.
cx.col.lose(LossCategory::DamagedData, format!("footage '{name}': image sequence naming not read, linked to its folder"));
cx.col.lose_with(LossCategory::DamagedData, || format!("footage '{name}': image sequence naming not read, linked to its folder"));
}
let present = !path.is_empty() && (cx.options.exists)(&path);
if !present {
@@ -531,10 +531,13 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
let mut layer_refs: Vec<PendingLayerRef> = Vec::new();
// The id of the layer above in the file (the matte of the older "layer above" form).
let mut above: Option<u32> = None;
// The comps that use this one, directly or through others: a precomp layer of one of them
// would close a loop. Found once, at the first precomp layer (see `Precomps`).
let mut users = Users::NotSearched;
for layer in comp_view.layers() {
let Some(h) = layer.header() else {
cx.col.lose(LossCategory::DamagedData, format!("{comp_name}: a layer header is unreadable, layer not imported"));
cx.col.lose_with(LossCategory::DamagedData, || format!("{comp_name}: a layer header is unreadable, layer not imported"));
above = None;
continue;
};
@@ -598,11 +601,17 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
SourceKind::Solid => (LayerSource::Solid { item: s.item }, (s.width.max(1), s.height.max(1))),
SourceKind::Footage => (LayerSource::Footage { item: s.item }, (s.width.max(1), s.height.max(1))),
SourceKind::Comp => {
if would_loop(&cx.uses, p.id, s.item) {
skip(cx, &mut skipped, LossCategory::UnsupportedLayers, "precomposition loop, layer");
continue;
match cx.precomps.accept(p.id, s.item, &mut users) {
Link::Accepted => {}
Link::Loop => {
skip(cx, &mut skipped, LossCategory::UnsupportedLayers, "precomposition loop, layer");
continue;
}
Link::Unchecked => {
skip(cx, &mut skipped, LossCategory::UnsupportedLayers, "precomposition in a loop of compositions too large to check, layer");
continue;
}
}
cx.uses.entry(p.id).or_default().push(s.item);
(LayerSource::Comp { item: s.item }, (s.width.max(1), s.height.max(1)))
}
},
@@ -624,7 +633,7 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
Some(b) => l.blend_mode = b,
// Cameras and lights have no blend mode (their byte is 0, 251).
None if is_camera || light.is_some() => {}
None => cx.col.lose(LossCategory::BlendModes, format!("{comp_name}: '{name}' uses blend mode code {}", h.blend_mode.code())),
None => cx.col.lose_with(LossCategory::BlendModes, || format!("{comp_name}: '{name}' uses blend mode code {}", h.blend_mode.code())),
}
let what = format!("{comp_name}: '{name}'");
l.markers = import_markers(layer.markers(), layer.chunk(), &what, &tm, &mut cx.col);
@@ -693,9 +702,13 @@ fn build_layers(project: &mut Project, cx: &mut Ctx<'_>, defs: &EffectDefinition
comp.layers.push(l);
}
resolve_parents(&mut comp, &parents, &ids, &skipped, &comp_name, &mut cx.col);
resolve_mattes(&mut comp, &mattes, &ids, &skipped, &comp_name, &mut cx.col);
resolve_layer_refs(&mut comp, &layer_refs, &ids, &mut cx.col);
// Project layer id -> position in `comp.layers` (the first, as `Comp::layer_mut` finds it):
// one lookup per link instead of a scan of the layers, which made a composition of many
// parented, matted or referenced layers quadratic.
let at = layer_positions(&comp);
resolve_parents(&mut comp, &at, &parents, &ids, &skipped, &comp_name, &mut cx.col);
resolve_mattes(&mut comp, &at, &mattes, &ids, &skipped, &comp_name, &mut cx.col);
resolve_layer_refs(&mut comp, &at, &layer_refs, &ids, &mut cx.col);
// Global Light is one setting per composition here: the layers' stored values are adopted.
effectcraft_project::styles::sync_comp(&mut comp);
@@ -715,10 +728,10 @@ fn import_source_text(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, cx: &
let value = text_doc(&doc, what, cx.options.has_font, &mut cx.col);
match l.props.prop_mut("text/sourceText") {
Some(p) => p.value = Value::Text(Box::new(value)),
None => cx.col.lose(LossCategory::DamagedData, format!("{what}: the text layer has no Source Text property, the text is not imported")),
None => cx.col.lose_with(LossCategory::DamagedData, || format!("{what}: the text layer has no Source Text property, the text is not imported")),
}
}
None => cx.col.lose(LossCategory::DamagedData, format!("{what}: the text document is unreadable, the layer is imported with empty text")),
None => cx.col.lose_with(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);
@@ -733,33 +746,250 @@ fn import_text_animators(l: &mut Layer, layer: &AepLayer<'_, '_>, what: &str, tm
}
match l.props.group_mut("text/animators") {
Some(target) => import_animators(&animators, what, tm, ids, target, col),
None => col.lose(LossCategory::TextLayers, format!("{what}: the text layer has no animator group, its text animators are not imported")),
None => col.lose_with(LossCategory::TextLayers, || format!("{what}: the text layer has no animator group, its text animators are not imported")),
}
}
/// Whether adding `to` as a precomp of `from` would close a loop.
fn would_loop(uses: &HashMap<ItemId, Vec<ItemId>>, from: ItemId, to: ItemId) -> bool {
if from == to {
return true;
/// Whether a precomp layer of `to` in `from` closes a loop: `to` is `from`, or `to` already uses
/// `from` (`uses_from`, directly or through others). Shared by the import and the export.
pub(crate) fn closes_loop(from: ItemId, to: ItemId, uses_from: impl FnOnce(ItemId) -> bool) -> bool {
to == from || uses_from(to)
}
/// The walk's own stack in [`components`]: a node, the nodes it links to and how many are done.
type Walk = Vec<(ItemId, Vec<ItemId>, usize)>;
/// The strongly connected components of the graph `edges` (node -> the nodes it links to): each
/// node's component number (every node of a loop has the same one). Iterative (Tarjan), linear in
/// nodes and links.
pub(crate) fn components(edges: &HashMap<ItemId, HashSet<ItemId>>) -> HashMap<ItemId, usize> {
struct Tarjan<'e> {
edges: &'e HashMap<ItemId, HashSet<ItemId>>,
index: HashMap<ItemId, usize>,
low: HashMap<ItemId, usize>,
on_stack: HashSet<ItemId>,
stack: Vec<ItemId>,
counter: usize,
}
let mut seen = HashSet::new();
let mut stack = vec![to];
while let Some(c) = stack.pop() {
if c == from {
return true;
}
if seen.insert(c) {
stack.extend(uses.get(&c).into_iter().flatten().copied());
impl Tarjan<'_> {
fn enter(&mut self, n: ItemId, walk: &mut Walk) {
self.index.insert(n, self.counter);
self.low.insert(n, self.counter);
self.counter = self.counter.saturating_add(1);
self.stack.push(n);
self.on_stack.insert(n);
walk.push((n, self.edges.get(&n).map(|s| s.iter().copied().collect()).unwrap_or_default(), 0));
}
}
false
let mut t = Tarjan { edges, index: HashMap::new(), low: HashMap::new(), on_stack: HashSet::new(), stack: Vec::new(), counter: 0 };
let mut component: HashMap<ItemId, usize> = HashMap::new();
let mut found = 0usize;
for &root in edges.keys() {
if t.index.contains_key(&root) {
continue;
}
let mut walk: Walk = Vec::new();
t.enter(root, &mut walk);
while let Some((v, next, done)) = walk.last_mut() {
let v = *v;
if let Some(w) = next.get(*done).copied() {
*done += 1;
if !t.index.contains_key(&w) {
t.enter(w, &mut walk);
} else if t.on_stack.contains(&w) {
let iw = t.index.get(&w).copied().unwrap_or(usize::MAX);
if let Some(lv) = t.low.get_mut(&v) {
*lv = (*lv).min(iw);
}
}
continue;
}
walk.pop();
let lv = t.low.get(&v).copied().unwrap_or(usize::MAX);
if let Some((u, _, _)) = walk.last()
&& let Some(lu) = t.low.get_mut(u)
{
*lu = (*lu).min(lv);
}
if Some(lv) == t.index.get(&v).copied() {
while let Some(x) = t.stack.pop() {
t.on_stack.remove(&x);
component.insert(x, found);
if x == v {
break;
}
}
found = found.saturating_add(1);
}
}
}
component
}
/// The precomp links of the import: the links every precomp layer of the file could make (the
/// candidates, known before any layer is built), and the ones accepted so far, stored as precomp
/// -> the comps that use it.
///
/// A precomp layer of `to` in `from` closes a loop when `to` already uses `from` over accepted
/// links ([`closes_loop`]). That path and the layer's own link form a loop of candidate links, so
/// `to` and `from` share a component of the candidate graph: between components the answer is no
/// without a search (a file without a precomp loop never searches). Within a component, the comps
/// that use `from` are found once per composition, among that component's comps only: while
/// `from`'s layers are built the only links added start at `from`, and a path that reaches `from`
/// never needs one of them. (Before, every precomp layer walked the whole graph, which held one
/// link per layer.)
///
/// Which links of a loop are refused depends on the order they come in (the first link that
/// closes it), so inside a component the answer cannot be computed once for all compositions:
/// each composition's search covers the links accepted so far, and a component of K compositions
/// and L links costs up to K x L steps. Those searches share one budget
/// ([`MAX_LOOP_SEARCH_STEPS`] links visited per import); once it is spent, a precomp layer inside a
/// loop's component whose search would have to visit a link is refused unchecked (reported),
/// which never closes a loop; a search that needs no step still decides exactly. Every file of
/// the corpus has no precomp loop and never searches.
struct Precomps {
used_by: HashMap<ItemId, HashSet<ItemId>>,
component: HashMap<ItemId, usize>,
/// Links the searches may still visit.
steps_left: usize,
}
impl Default for Precomps {
fn default() -> Self {
Precomps { used_by: HashMap::new(), component: HashMap::new(), steps_left: MAX_LOOP_SEARCH_STEPS }
}
}
/// The most links the precomp loop searches of one import visit together (see [`Precomps`]).
const MAX_LOOP_SEARCH_STEPS: usize = 4_000_000;
/// The comps that use the composition being built, as far as they were needed.
enum Users {
/// Not looked for yet (no layer needed them).
NotSearched,
Found(HashSet<ItemId>),
/// The search budget ran out.
OutOfBudget,
}
/// What becomes of a precomp layer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Link {
Accepted,
/// It would close a loop.
Loop,
/// Inside a loop's component after the search budget is spent: refused without a check.
Unchecked,
}
impl Precomps {
/// `candidates`: comp -> the comps its layers could show.
fn new(candidates: &HashMap<ItemId, HashSet<ItemId>>) -> Self {
Precomps { component: components(candidates), ..Precomps::default() }
}
/// Decides a precomp layer of `to` in `from`, recording it when it is accepted. `users` holds
/// the comps that use `from` once they are needed (one search per composition).
fn accept(&mut self, from: ItemId, to: ItemId, users: &mut Users) -> Link {
let inside = to != from && self.same_component(from, to);
if inside && matches!(users, Users::NotSearched) {
*users = self.users_of(from).map_or(Users::OutOfBudget, Users::Found);
}
let found = match users {
Users::Found(u) => Some(&*u),
Users::NotSearched | Users::OutOfBudget => None,
};
if inside && found.is_none() {
return Link::Unchecked;
}
if closes_loop(from, to, |to| inside && found.is_some_and(|u| u.contains(&to))) {
return Link::Loop;
}
// Only a link inside a component can lie on a path the loop search follows (it never
// leaves the component of the layer's comp), so only those are kept: the searches never
// visit, or pay budget for, a link between components.
if self.same_component(from, to) {
self.used_by.entry(to).or_default().insert(from);
}
Link::Accepted
}
/// Whether `a` and `b` are in one component of the candidate graph.
fn same_component(&self, a: ItemId, b: ItemId) -> bool {
matches!((self.component.get(&a), self.component.get(&b)), (Some(x), Some(y)) if x == y)
}
/// The comps of `comp`'s component that use it over accepted links, directly or through
/// others (each visited once); `None` when the search budget runs out.
fn users_of(&mut self, comp: ItemId) -> Option<HashSet<ItemId>> {
let mut found = HashSet::new();
let mut stack = vec![comp];
while let Some(c) = stack.pop() {
for u in self.used_by.get(&c).into_iter().flatten() {
if !self.same_component(*u, comp) {
continue;
}
self.steps_left = self.steps_left.checked_sub(1)?;
if found.insert(*u) {
stack.push(*u);
}
}
}
Some(found)
}
}
/// The source id of a layer that `build_layers` decides by [`Precomps::accept`] when the source is
/// a composition: a camera, light, text, shape or null layer never becomes a precomp layer, whatever
/// source it stores, so it is no candidate link.
fn precomp_layer_source(h: &LayerHeader) -> Option<u32> {
if h.layer_type != LayerType::Av || h.is_null_object() { None } else { h.source_id }
}
/// Every link a precomp layer of the file could make: comp -> the comps its layers name as their
/// source (resolved as `build_layers` resolves them).
fn precomp_candidates(sources: &HashMap<u32, Source>, pending: &[PendingComp<'_, '_>]) -> HashMap<ItemId, HashSet<ItemId>> {
candidate_links(
sources,
pending.iter().filter_map(|p| {
let comp = p.item.comp()?;
Some((p.id, comp.layers().filter_map(|l| l.header().and_then(|h| precomp_layer_source(&h))).collect::<Vec<_>>()))
}),
)
}
/// [`precomp_candidates`] from each comp's precomp-eligible layer source ids.
fn candidate_links(sources: &HashMap<u32, Source>, comps: impl IntoIterator<Item = (ItemId, Vec<u32>)>) -> HashMap<ItemId, HashSet<ItemId>> {
let mut links: HashMap<ItemId, HashSet<ItemId>> = HashMap::new();
for (from, ids) in comps {
for s in ids.iter().filter_map(|id| sources.get(id)) {
if s.kind == SourceKind::Comp {
links.entry(from).or_default().insert(s.item);
}
}
}
links
}
/// Each layer's position in `comp.layers`, the first one for an id that repeats.
fn layer_positions(comp: &Comp) -> HashMap<LayerId, usize> {
let mut at = HashMap::with_capacity(comp.layers.len());
for (i, l) in comp.layers.iter().enumerate() {
at.entry(l.id).or_insert(i);
}
at
}
/// The layer with project id `id`, through [`layer_positions`].
pub(crate) fn layer_at<'c>(comp: &'c mut Comp, at: &HashMap<LayerId, usize>, id: LayerId) -> Option<&'c mut Layer> {
comp.layers.get_mut(*at.get(&id)?)
}
fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &mut Collector) {
// The exact ratio `stretch / stretch_den` (50 % is 1/2, -100 % is -1/1); a zero or unreadable
// one is 100 %.
let stretch = h.stretch_ratio().filter(|r| r.num != 0).unwrap_or_else(|| {
col.lose(LossCategory::DamagedData, format!("layer '{name}': the time stretch is zero or unreadable, 100 % is used"));
col.lose_with(LossCategory::DamagedData, || format!("layer '{name}': the time stretch is zero or unreadable, 100 % is used"));
Rational { num: 1, den: 1 }
});
let stored = stretch.to_f64().map_or(100.0, |r| r * 100.0);
@@ -768,7 +998,9 @@ fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &
// out points keep the comp times the file stores.
l.stretch = effectcraft_project::limits::stretch(stored);
if l.stretch.to_bits() != stored.to_bits() {
col.lose(LossCategory::DamagedData, format!("layer '{name}': the time stretch of {stored:e} % is outside ±1 % to ±9900 %, {} % is used", l.stretch));
col.lose_with(LossCategory::DamagedData, || {
format!("layer '{name}': the time stretch of {stored:e} % is outside ±1 % to ±9900 %, {} % is used", l.stretch)
});
}
// A stored time with a zero denominator (or a sum that overflows) has no value; it is read as 0
// and reported, so the layer's timing never changes silently.
@@ -780,9 +1012,11 @@ fn apply_timing(l: &mut Layer, h: &LayerHeader, tm: &TimeMap, name: &str, col: &
l.start_time = tm.ticks(h.start.num, h.start.den);
let points = [(h.in_relative, h.in_point()), (h.out_relative, h.out_point())].map(|(offset, reduced)| absolute(h.start, offset, stretch, reduced));
if !unreadable.is_empty() {
col.lose(LossCategory::DamagedData, format!("layer '{name}': the stored {} time is unreadable (zero denominator), 0 is used", unreadable.join(", ")));
col.lose_with(LossCategory::DamagedData, || {
format!("layer '{name}': the stored {} time is unreadable (zero denominator), 0 is used", unreadable.join(", "))
});
} else if points.iter().any(Option::is_none) {
col.lose(LossCategory::DamagedData, format!("layer '{name}': the in or out point is out of range, 0 is used"));
col.lose_with(LossCategory::DamagedData, || format!("layer '{name}': the in or out point is out of range, 0 is used"));
}
let [a, b] = points.map(|p| p.map_or(Tick::ZERO, |(n, d)| tm.ticks(n, d)));
// A negative stretch reverses the layer (981-983): the stored in point is then the later
@@ -853,7 +1087,15 @@ struct PendingMatte {
/// above: that layer is used. The matte layer's video switch is imported as stored (After Effects
/// switches it off when the matte is set, 403; EffectCraft, like After Effects, still uses a
/// hidden layer as a matte).
fn resolve_mattes(comp: &mut Comp, mattes: &[PendingMatte], ids: &HashMap<u32, LayerId>, skipped: &HashMap<u32, String>, comp_name: &str, col: &mut Collector) {
fn resolve_mattes(
comp: &mut Comp,
at: &HashMap<LayerId, usize>,
mattes: &[PendingMatte],
ids: &HashMap<u32, LayerId>,
skipped: &HashMap<u32, String>,
comp_name: &str,
col: &mut Collector,
) {
for m in mattes {
let kind = match m.matte.mode {
MatteMode::Alpha => MatteKind::Alpha,
@@ -861,24 +1103,24 @@ fn resolve_mattes(comp: &mut Comp, mattes: &[PendingMatte], ids: &HashMap<u32, L
MatteMode::Luma => MatteKind::Luma,
MatteMode::LumaInverted => MatteKind::LumaInverted,
MatteMode::Other(code) => {
col.lose(LossCategory::TrackMattes, format!("{comp_name}: '{}' has a track matte of unknown mode {code}", m.name));
col.lose_with(LossCategory::TrackMattes, || format!("{comp_name}: '{}' has a track matte of unknown mode {code}", m.name));
continue;
}
};
let Some(source) = m.matte.layer.or(m.above) else {
col.lose(LossCategory::TrackMattes, format!("{comp_name}: '{}' has a track matte but no layer above it", m.name));
col.lose_with(LossCategory::TrackMattes, || format!("{comp_name}: '{}' has a track matte but no layer above it", m.name));
continue;
};
let Some(target) = ids.get(&source).copied() else {
let why = skipped.get(&source).map_or("a layer that does not exist", |s| s.as_str());
col.lose(LossCategory::TrackMattes, format!("{comp_name}: '{}' has {why} as its track matte", m.name));
col.lose_with(LossCategory::TrackMattes, || format!("{comp_name}: '{}' has {why} as its track matte", m.name));
continue;
};
if target == m.layer {
col.lose(LossCategory::TrackMattes, format!("{comp_name}: '{}' is its own track matte", m.name));
col.lose_with(LossCategory::TrackMattes, || format!("{comp_name}: '{}' is its own track matte", m.name));
continue;
}
if let Some(l) = comp.layer_mut(m.layer) {
if let Some(l) = layer_at(comp, at, m.layer) {
l.track_matte = Some(TrackMatte { layer: target, kind });
col.imported.track_mattes += 1;
}
@@ -923,6 +1165,7 @@ fn parent_cycles(links: &HashMap<LayerId, LayerId>) -> HashSet<LayerId> {
/// Sets the parent links that point at an imported layer, without loops.
fn resolve_parents(
comp: &mut Comp,
at: &HashMap<LayerId, usize>,
parents: &[(u32, LayerId, String, u32)],
ids: &HashMap<u32, LayerId>,
skipped: &HashMap<u32, String>,
@@ -937,7 +1180,7 @@ fn resolve_parents(
}
None => {
let why = skipped.get(parent).map_or("a layer that does not exist", |s| s.as_str());
col.lose(LossCategory::ParentLinks, format!("{comp_name}: '{name}' has {why} as its parent"));
col.lose_with(LossCategory::ParentLinks, || format!("{comp_name}: '{name}' has {why} as its parent"));
}
}
}
@@ -946,11 +1189,11 @@ fn resolve_parents(
let looped: Vec<LayerId> = links.keys().copied().filter(|l| on_loop.contains(l)).collect();
for l in &looped {
links.remove(l);
let name = comp.layer(*l).map(|x| x.name.clone()).unwrap_or_default();
col.lose(LossCategory::ParentLinks, format!("{comp_name}: '{name}' has a parent loop"));
let name = at.get(l).and_then(|i| comp.layers.get(*i)).map(|x| x.name.clone()).unwrap_or_default();
col.lose_with(LossCategory::ParentLinks, || format!("{comp_name}: '{name}' has a parent loop"));
}
for (layer, parent) in links {
if let Some(l) = comp.layer_mut(layer) {
if let Some(l) = layer_at(comp, at, layer) {
l.parent = Some(parent);
}
}
@@ -994,6 +1237,213 @@ mod tests {
assert_eq!(found, [1, 2, 3, 5]);
}
/// The loop check as it was (a walk over every link per precomp layer), the reference.
fn old_would_loop(uses: &HashMap<ItemId, Vec<ItemId>>, from: ItemId, to: ItemId) -> bool {
if from == to {
return true;
}
let mut seen = HashSet::new();
let mut stack = vec![to];
while let Some(c) = stack.pop() {
if c == from {
return true;
}
if seen.insert(c) {
stack.extend(uses.get(&c).into_iter().flatten().copied());
}
}
false
}
/// Builds the compositions `0..comps` in order, each with `layers` precomp layers of
/// pseudo-random compositions, deciding every layer with the old and the new check.
fn decide_both(comps: u64, layers: u64, seed: u64) -> usize {
let mut state = seed;
let mut next = || {
state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
state >> 33
};
let plan: Vec<(ItemId, Vec<ItemId>)> = (0..comps).map(|c| (ItemId(c), (0..layers).map(|_| ItemId(next() % comps)).collect())).collect();
let mut candidates: HashMap<ItemId, HashSet<ItemId>> = HashMap::new();
for (from, tos) in &plan {
candidates.entry(*from).or_default().extend(tos.iter().copied());
}
let (mut uses, mut new) = (HashMap::<ItemId, Vec<ItemId>>::new(), Precomps::new(&candidates));
let mut refused = 0;
for (from, tos) in &plan {
let mut users = Users::NotSearched;
for to in tos {
let link = new.accept(*from, *to, &mut users);
assert_ne!(link, Link::Unchecked, "the budget is not reached here");
assert_eq!(link == Link::Loop, old_would_loop(&uses, *from, *to), "{from:?} -> {to:?}");
if link == Link::Accepted {
uses.entry(*from).or_default().push(*to);
} else {
refused += 1;
}
}
}
refused
}
#[test]
fn outside_users_do_not_spend_the_loop_search_budget() {
// A is in a loop with B (A <-> B). 100 comps outside the loop show A; the budget is nearly
// spent. Building A: its layer of B needs A's users, which are only B's side of the loop:
// the outside comps cannot close a loop and must cost nothing, so A's layer is decided.
let (a, b) = (ItemId(1), ItemId(2));
let ext = |i: u64| ItemId(10 + i);
let mut candidates: HashMap<ItemId, HashSet<ItemId>> = HashMap::from([(a, HashSet::from([b])), (b, HashSet::from([a]))]);
for i in 0..100 {
candidates.insert(ext(i), HashSet::from([a]));
}
let mut p = Precomps::new(&candidates);
for i in 0..100 {
assert_eq!(p.accept(ext(i), a, &mut Users::NotSearched), Link::Accepted);
}
p.steps_left = 5;
// B shows A first (inside the loop, one user of A is B itself once accepted), then A shows B.
assert_eq!(p.accept(b, a, &mut Users::NotSearched), Link::Accepted);
assert_eq!(p.accept(a, b, &mut Users::NotSearched), Link::Loop);
}
#[test]
fn ineligible_layers_are_no_candidate_links() {
let source = |item: u64, kind| Source { item: ItemId(item), name: String::new(), kind, width: 1, height: 1 };
let sources = HashMap::from([(1, source(1, SourceKind::Comp)), (2, source(2, SourceKind::Comp)), (3, source(3, SourceKind::Solid))]);
// Comp 1 shows 2 (eligible); comp 2 has no eligible layer of comp 1 (a null or text layer
// with that source is filtered by `precomp_layer_source` before): no loop component.
let links = candidate_links(&sources, [(ItemId(1), vec![2, 3]), (ItemId(2), vec![])]);
let p = Precomps::new(&links);
assert!(!p.same_component(ItemId(1), ItemId(2)));
// With the back-edge as a candidate they share one, which is what ineligible layers used to do.
let looped = candidate_links(&sources, [(ItemId(1), vec![2]), (ItemId(2), vec![1])]);
assert!(Precomps::new(&looped).same_component(ItemId(1), ItemId(2)));
}
#[test]
fn the_precomp_loop_check_decides_as_the_full_walk_did() {
let mut refused = 0;
for seed in 0..200 {
refused += decide_both(1 + seed % 12, 1 + seed % 5, seed);
}
// Both kinds of answer occur.
assert!(refused > 0);
}
#[test]
fn many_layers_of_one_precomp_are_checked_in_linear_time() {
// C holds 200 000 layers of B, B 200 000 of A, built B first: before, every layer of C
// walked B's 200 000 links (4e10 steps); now no layer searches (no loop in the file).
let (a, b, c) = (ItemId(1), ItemId(2), ItemId(3));
let candidates = HashMap::from([(b, HashSet::from([a])), (c, HashSet::from([b]))]);
let mut p = Precomps::new(&candidates);
for (from, to) in [(b, a), (c, b)] {
let mut users = Users::NotSearched;
for _ in 0..200_000 {
assert_eq!(p.accept(from, to, &mut users), Link::Accepted);
}
assert!(matches!(users, Users::NotSearched), "no search");
}
}
#[test]
fn layered_precomps_are_checked_without_a_search() {
// K top comps each show K middle comps, each of which shows K leaf comps, built leaves
// last (the order that made each leaf's users the whole graph): K^3 steps before the
// components, now none. K = 300: 180 000 links.
let k = 300u64;
let (top, mid, leaf) = (|i: u64| ItemId(i), |i: u64| ItemId(1000 + i), |i: u64| ItemId(2000 + i));
let mut candidates: HashMap<ItemId, HashSet<ItemId>> = HashMap::new();
for i in 0..k {
candidates.insert(top(i), (0..k).map(mid).collect());
candidates.insert(mid(i), (0..k).map(leaf).collect());
}
let mut p = Precomps::new(&candidates);
for from in (0..k).map(top).chain((0..k).map(mid)) {
let mut users = Users::NotSearched;
for to in candidates.get(&from).into_iter().flatten() {
assert_eq!(p.accept(from, *to, &mut users), Link::Accepted);
}
assert!(matches!(users, Users::NotSearched), "no search");
}
}
#[test]
fn a_large_loop_of_compositions_is_checked_within_the_budget() {
// 100 000 compositions in one loop (each shows the next, the last the first), built in
// order: the users of each one are all the ones before it, so checking every layer
// exactly is 5e9 steps. The searches stop at the budget; past it the layers inside the
// loop that need a search are refused unchecked (one whose composition has no accepted
// user needs none and is still decided exactly). The loop never closes.
let n = 100_000u64;
let c = |i: u64| ItemId(i);
let candidates: HashMap<ItemId, HashSet<ItemId>> = (0..n).map(|i| (c(i), HashSet::from([c((i + 1) % n)]))).collect();
let mut p = Precomps::new(&candidates);
let mut seen = HashMap::new();
for i in 0..n {
let link = p.accept(c(i), c((i + 1) % n), &mut Users::NotSearched);
*seen.entry(link).or_insert(0usize) += 1;
}
// Before the budget runs out every link is accepted (none closes the loop yet); after
// it, the ones that need a search are refused unchecked; the closing one never gets in.
let accepted = seen.get(&Link::Accepted).copied().unwrap_or(0);
assert!(accepted > 1000 && accepted < n as usize, "{seen:?}");
assert!(seen.get(&Link::Unchecked).copied().unwrap_or(0) > 0, "{seen:?}");
assert!(!seen.contains_key(&Link::Loop), "{seen:?}");
assert_eq!(accepted + seen.get(&Link::Unchecked).copied().unwrap_or(0), n as usize, "{seen:?}");
// The accepted links hold no loop: every component of them is a single composition.
let mut forward: HashMap<ItemId, HashSet<ItemId>> = HashMap::new();
for (to, froms) in &p.used_by {
for from in froms {
forward.entry(*from).or_default().insert(*to);
}
}
let parts = components(&forward);
assert_eq!(parts.values().collect::<HashSet<_>>().len(), parts.len());
// Below the budget the same loop is decided exactly: the closing link is refused.
let small: HashMap<ItemId, HashSet<ItemId>> = (0..100).map(|i| (c(i), HashSet::from([c((i + 1) % 100)]))).collect();
let mut p = Precomps::new(&small);
let links: Vec<Link> = (0..100).map(|i| p.accept(c(i), c((i + 1) % 100), &mut Users::NotSearched)).collect();
assert!(links[..99].iter().all(|l| *l == Link::Accepted));
assert_eq!(links[99], Link::Loop);
}
#[test]
fn components_are_the_loops() {
let n = |i: u64| ItemId(i);
// 1 -> 2 -> 3 -> 1 is a loop, 4 leads into it, 5 -> 5 links to itself, 6 -> 7 ends.
let edges: HashMap<ItemId, HashSet<ItemId>> = [(1, 2), (2, 3), (3, 1), (4, 1), (5, 5), (6, 7)].into_iter().fold(HashMap::new(), |mut m, (a, b)| {
m.entry(n(a)).or_default().insert(n(b));
m
});
let c = components(&edges);
assert!(c[&n(1)] == c[&n(2)] && c[&n(2)] == c[&n(3)]);
let others = [4, 5, 6, 7].map(|i| c[&n(i)]);
assert!(others.iter().all(|x| *x != c[&n(1)]));
assert_eq!(others.iter().collect::<HashSet<_>>().len(), 4);
// A chain of 200 000 links closed into one loop, walked without recursion.
let big: HashMap<ItemId, HashSet<ItemId>> = (0..200_000u64).map(|i| (n(i), HashSet::from([n((i + 1) % 200_000)]))).collect();
let c = components(&big);
assert_eq!(c.values().collect::<HashSet<_>>().len(), 1);
}
#[test]
fn layer_positions_find_the_first_layer_of_an_id() {
let mut project = Project::default();
let mut comp = Comp::new(10, 10, effectcraft_time::FrameRate::new(25, 1), Tick::ZERO);
for (id, name) in [(5, "a"), (6, "b"), (5, "c")] {
let mut l = build::layer(&mut project, &comp, name, LayerSource::Null, (10, 10), None);
l.id = LayerId(id);
l.name = name.into();
comp.layers.push(l);
}
let at = layer_positions(&comp);
assert_eq!(layer_at(&mut comp, &at, LayerId(5)).map(|l| l.name.clone()).as_deref(), Some("a"));
assert_eq!(layer_at(&mut comp, &at, LayerId(6)).map(|l| l.name.clone()).as_deref(), Some("b"));
assert!(layer_at(&mut comp, &at, LayerId(7)).is_none());
}
#[test]
fn a_long_parent_chain_is_checked_in_linear_time() {
// 200 000 layers each parented to the next, the last to the first: walking the chain from
+114 -76
View File
@@ -84,10 +84,10 @@ pub(crate) fn import_effects<'f, 'a>(
}
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
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());
let lost = || format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
if defs.source(&fx) == DefinitionSource::Missing {
match found {
Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")),
Some(_) => col.lose_with(LossCategory::Effects, || format!("{} without readable parameter definitions, not imported", lost())),
None => col.lose_unmapped_effect(fx.match_name(), lost),
}
continue;
@@ -97,7 +97,7 @@ pub(crate) fn import_effects<'f, 'a>(
// 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)"));
col.lose_unmapped_effect(&key, || format!("{}, not kept (past the import's placeholder parameters)", lost()));
continue;
}
let params = defs.params(&fx);
@@ -106,7 +106,7 @@ pub(crate) fn import_effects<'f, 'a>(
// No counterpart: kept as a placeholder that renders nothing, for expressions (#3087).
let mut group = crate::import::placeholder::placeholder(&fx, &params, 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.lose_unmapped_effect(fx.match_name(), || format!("{}, kept without rendering", lost()));
col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1);
target.children.push(Node::Group(group));
continue;
@@ -132,7 +132,9 @@ pub(crate) fn import_effects<'f, 'a>(
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)),
None => {
col.lose_with(LossCategory::DamagedData, || format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer))
}
}
}
@@ -144,10 +146,9 @@ fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectPar
}
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()),
);
col.lose_with(LossCategory::Effects, || {
format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name())
});
}
}
@@ -199,7 +200,7 @@ fn import_param(fx: &AepEffect<'_, '_>, map: &EffectMap, p: &EffectParam<'_, '_>
// Not in the table: lost only when the file stores something for it. A layer parameter
// set to no layer (its record always exists, Timewarp's Matte Layer 529) holds nothing.
if p.stored().is_some() && !matches!(p.stored_value(), Some(ParamValue::Layer(0))) {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} not imported"));
}
return;
};
@@ -212,7 +213,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
let (here, label) = names;
let ParamOut { group, refs, col } = out;
if p.kind != m.kind {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has type {:?}, expected {:?}; not imported", p.kind, m.kind));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} has type {:?}, expected {:?}; not imported", p.kind, m.kind));
return;
}
match m.conv {
@@ -232,7 +233,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
// After Effects 2026 writes 0.990005 (the 16.16 rounding differs); the scale is the same.
let ok = found.is_some_and(|v| (v - valid_max).abs() <= valid_max.abs() * 1e-4);
if !ok {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has the valid maximum {found:?}, expected {valid_max}; not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} has the valid maximum {found:?}, expected {valid_max}; not imported"));
}
ok
};
@@ -241,10 +242,9 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
(Conv::Popup { .. }, Some(items)) => items.clone(),
(Conv::Popup { items, .. }, None) => {
if p.popup_item_count().map(usize::from) != Some(items.len()) {
col.lose(
LossCategory::Effects,
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported", p.popup_item_count()),
);
col.lose_with(LossCategory::Effects, || {
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported", p.popup_item_count())
});
return;
}
items.iter().map(|s| s.to_string()).collect()
@@ -269,7 +269,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
};
// Grouped parameters are addressed by path (`master/exposure`).
let Some(prop) = group.prop_mut(m.target) else {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has no counterpart '{}'", m.target));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} has no counterpart '{}'", m.target));
return;
};
// For a popup: file item (0-based over all items) -> EffectCraft item, by name.
@@ -277,7 +277,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
Conv::Popup { .. } => match popup_mapping(&items, &prop.ui) {
Some(map) => Some(map),
None => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the popup items do not match EffectCraft's, not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label}: the popup items do not match EffectCraft's, not imported"));
return;
}
},
@@ -294,7 +294,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
_ => false,
};
if converted && stored.expression().is_some() {
col.lose(LossCategory::Effects, format!("{here}: the expression on parameter {label} is not imported (the value is converted here)"));
col.lose_with(LossCategory::Effects, || format!("{here}: the expression on parameter {label} is not imported (the value is converted here)"));
} else {
import_expression(&stored, prop, col);
}
@@ -302,14 +302,14 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
if p.is_animated() {
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 imported (not decoded), default used"));
col.lose_with(LossCategory::Effects, || format!("{here}: the keyframes of parameter {label} are not imported (not decoded), default used"));
return;
}
if let Some(stored) = p.stored() {
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, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{here}: parameter {label} has no readable keyframe, default used"));
}
if let Some(map) = &popup_map {
remap_popup_keys(prop, map, here, label, col);
@@ -323,7 +323,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
let value = match (p.stored(), p.recorded_value()) {
(Some(_), Some(v)) => Some(v),
(Some(_), None) => {
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{here}: parameter {label} holds an unreadable value, default used"));
return;
}
// Absent = default. A borrowed popup's default slot is not reliable (a selection writes
@@ -341,7 +341,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
Some(Some(ec)) => Some(Value::Enum(ec)),
Some(None) => {
let item = usize::try_from(i).ok().and_then(|i| i.checked_sub(1)).and_then(|i| items.get(i)).cloned().unwrap_or_default();
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item '{item}' has no counterpart, default used"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label}: item '{item}' has no counterpart, default used"));
return;
}
None => None,
@@ -353,7 +353,7 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx
report_beyond_limit(m.limit, std::iter::once(&v), here, label, col);
prop.value = v;
}
None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?}), default used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: parameter {label} holds a value that is not valid ({value:?}), default used")),
}
}
@@ -363,7 +363,9 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator<Item
let Some((lo, hi)) = limit else { return };
let beyond: Vec<f64> = values.filter_map(|v| if let Value::Scalar(x) = v { Some(*x) } else { None }).filter(|x| *x < lo || *x > hi).collect();
if let Some(x) = beyond.first() {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} is {x}, EffectCraft's effect uses {lo} to {hi} (rendered as the nearest of them)"));
col.lose_with(LossCategory::Effects, || {
format!("{here}: parameter {label} is {x}, EffectCraft's effect uses {lo} to {hi} (rendered as the nearest of them)")
});
}
}
@@ -381,11 +383,11 @@ pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool,
src.value = Value::Enum(0);
}
let Some(prop) = group.prop_mut(target) else {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} has no counterpart '{target}'"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} has no counterpart '{target}'"));
return;
};
if p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some()) {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on the layer parameter {label} are not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: keyframes or an expression on the layer parameter {label} are not imported"));
}
// No record: the default, the owning layer (320).
match p.layer_ref(cx.aep_id).unwrap_or(LayerRef::This) {
@@ -401,19 +403,21 @@ pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool,
}
/// Sets the layer parameters that name another layer of the composition (`ids`: file id ->
/// project layer); one whose layer was not imported stays unset and is reported.
/// project layer; `at`: project layer -> position in the composition); one whose layer was not
/// imported stays unset and is reported.
pub(crate) fn resolve_layer_refs(
comp: &mut effectcraft_project::Comp,
at: &std::collections::HashMap<effectcraft_project::LayerId, usize>,
refs: &[PendingLayerRef],
ids: &std::collections::HashMap<u32, effectcraft_project::LayerId>,
col: &mut Collector,
) {
for r in refs {
let Some(target) = ids.get(&r.target) else {
col.lose(LossCategory::Effects, format!("{} names a layer that is not imported (id {}), left unset", r.what, r.target));
col.lose_with(LossCategory::Effects, || format!("{} names a layer that is not imported (id {}), left unset", r.what, r.target));
continue;
};
if let Some(prop) = comp.layers.iter_mut().find(|l| l.id == r.layer).and_then(|l| l.props.find_mut(r.prop)) {
if let Some(prop) = crate::import::build::layer_at(comp, at, r.layer).and_then(|l| l.props.find_mut(r.prop)) {
prop.value = Value::Layer(Some(target.0));
}
}
@@ -423,7 +427,9 @@ pub(crate) fn resolve_layer_refs(
/// non-English name for it, [`popup_alias`]); `None` when the parameter here is not a popup.
fn popup_mapping(file_items: &[String], ui: &ParamUi) -> Option<Vec<Option<u32>>> {
let ParamUi::Popup { options } = ui else { return None };
let norm = popup_key;
// The file's item count is not bounded (its `pdnm`), EffectCraft's options are: the options'
// keys are built once, and each file item's once, so the cost is linear in the file's items.
let options: Vec<String> = options.iter().map(|o| popup_key(o)).collect();
Some(
file_items
.iter()
@@ -431,11 +437,11 @@ fn popup_mapping(file_items: &[String], ui: &ParamUi) -> Option<Vec<Option<u32>>
if item.trim() == "(-" {
return None;
}
let key = norm(item);
let key = popup_key(item);
options
.iter()
.position(|o| norm(o) == key)
.or_else(|| popup_alias(&key).and_then(|a| options.iter().position(|o| norm(o) == a)))
.position(|o| *o == key)
.or_else(|| popup_alias(&key).and_then(|a| options.iter().position(|o| o == a)))
.and_then(|i| u32::try_from(i).ok())
})
.collect(),
@@ -456,7 +462,7 @@ fn remap_popup_keys(prop: &mut effectcraft_project::Property, map: &[Option<u32>
_ => true,
});
if prop.keys.len() != before {
col.lose(LossCategory::Effects, format!("{here}: a keyframe of parameter {label} has an item without a counterpart, dropped"));
col.lose_with(LossCategory::Effects, || format!("{here}: a keyframe of parameter {label} has an item without a counterpart, dropped"));
}
if let Some(first) = prop.keys.first() {
prop.value = first.value.clone();
@@ -466,17 +472,16 @@ fn remap_popup_keys(prop: &mut effectcraft_project::Property, map: &[Option<u32>
/// Hue/Saturation's master values, Levels' RGB values: from the arbitrary data of `p`.
fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, here: &str, size: (u32, u32), group: &mut PropGroup, col: &mut Collector) {
if p.is_animated() || p.stored().is_some_and(|s| s.expression().is_some()) {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {} are not imported", p.name));
col.lose_with(LossCategory::Effects, || format!("{here}: keyframes or an expression on {} are not imported", p.name));
}
let Some(data) = fx.arbitrary_data(&p.match_name) else {
// No record: every value is at its default. A Channel Info value record without its
// aRbs/aRbp payload (every sampled record has it) is damaged: the payload may have chosen
// other channels (`Z`), so the defaults are not what After Effects renders.
if p.stored().is_some() && matches!(extra, Extra::Extractor | Extra::Identifier) {
col.lose(
LossCategory::DamagedData,
format!("{here}: the Channel Info data is missing (a value record without its data), the default channels used"),
);
col.lose_with(LossCategory::DamagedData, || {
format!("{here}: the Channel Info data is missing (a value record without its data), the default channels used")
});
}
return;
};
@@ -494,10 +499,10 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
set(id, f64::from(v));
}
if !d.ranges_are_default() {
col.lose(LossCategory::Effects, format!("{here}: the colour ranges (Reds ... Magentas) are not imported (not sampled)"));
col.lose_with(LossCategory::Effects, || format!("{here}: the colour ranges (Reds ... Magentas) are not imported (not sampled)"));
}
}
None => col.lose(LossCategory::DamagedData, format!("{here}: the Hue/Saturation data is unreadable, defaults used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: the Hue/Saturation data is unreadable, defaults used")),
},
Extra::Levels => match LevelsData::parse(data) {
Some(d) => {
@@ -505,10 +510,10 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
set(id, f64::from(v));
}
if d.channels[1..].iter().any(|c| *c != LevelsData::DEFAULT_CHANNEL) {
col.lose(LossCategory::Effects, format!("{here}: the per-channel values (Red, Green, Blue, Alpha) are not imported (not sampled)"));
col.lose_with(LossCategory::Effects, || format!("{here}: the per-channel values (Red, Green, Blue, Alpha) are not imported (not sampled)"));
}
}
None => col.lose(LossCategory::DamagedData, format!("{here}: the Levels data is unreadable, defaults used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: the Levels data is unreadable, defaults used")),
},
Extra::Curves => match CurvesData::parse(data) {
Some(d) => {
@@ -522,11 +527,11 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
}
}
}
None => col.lose(LossCategory::DamagedData, format!("{here}: the Curves data is unreadable, defaults used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: the Curves data is unreadable, defaults used")),
},
Extra::MeshWarp => match MeshData::parse(data) {
Some(m) => import_mesh(&m, here, size, group, col),
None => col.lose(LossCategory::DamagedData, format!("{here}: the Distortion Mesh is unreadable, defaults used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: the Distortion Mesh is unreadable, defaults used")),
},
Extra::Extractor => match ExtractorChannels::parse(data).map(|c| (c.sources(effectcraft_effects::EXTRACTOR_COPY), c)) {
// Each output channel reads the footage's channel of the stored name, which
@@ -542,16 +547,16 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
}
Some((Err(k), c)) => {
let names: Vec<&str> = c.channels.iter().map(|(_, n)| n.as_str()).collect();
col.lose(
col.lose_with(
LossCategory::Effects,
format!(
|| format!(
"{here}: the channels {} are not imported (record {} is of an unknown kind or names no channel), R, G, B, A used",
names.join(", "),
k.saturating_add(1)
),
);
}
None => col.lose(LossCategory::Effects, format!("{here}: the Channel Info data is not in the sampled layout, R, G, B, A used")),
None => col.lose_with(LossCategory::Effects, || format!("{here}: the Channel Info data is not in the sampled layout, R, G, B, A used")),
},
Extra::Identifier => match crate::identifier_channel_type(data) {
// No channel chosen (the type's label): After Effects lists only the footage's integer
@@ -561,9 +566,9 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
if let Some(prop) = group.prop_mut("channelType") {
prop.value = Value::Enum(0);
}
col.lose(
col.lose_with(
LossCategory::Effects,
format!("{here}: no ID channel is chosen (Channel Info), so After Effects leaves the layer unchanged; EffectCraft draws the footage's object ID channel"),
|| format!("{here}: no ID channel is chosen (Channel Info), so After Effects leaves the layer unchanged; EffectCraft draws the footage's object ID channel"),
);
}
// A chosen channel, by name. EffectCraft's IDentifier has no channel of its own: it
@@ -575,12 +580,12 @@ fn import_extra(fx: &AepEffect<'_, '_>, extra: Extra, p: &EffectParam<'_, '_>, h
prop.value = Value::Enum(u32::try_from(kind).unwrap_or(0));
}
}
None => col.lose(
None => col.lose_with(
LossCategory::Effects,
format!("{here}: the ID channel '{name}' (Channel Info) is not imported; EffectCraft reads the footage's object ID channel (ObjectID, object_id, objectId, id)"),
|| format!("{here}: the ID channel '{name}' (Channel Info) is not imported; EffectCraft reads the footage's object ID channel (ObjectID, object_id, objectId, id)"),
),
},
None => col.lose(LossCategory::Effects, format!("{here}: the Channel Info data is not in the sampled layout, the object ID channel used")),
None => col.lose_with(LossCategory::Effects, || format!("{here}: the Channel Info data is not in the sampled layout, the object ID channel used")),
},
Extra::None | Extra::Lumetri | Extra::Cryptomatte => {}
}
@@ -610,13 +615,13 @@ fn import_cryptomatte(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx
match (p.index, p.kind) {
(1, ParamKind::ArbitraryData) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: keyframes or an expression on {label} are not imported"));
}
// No record: the definition's default, no layer and no selection. A record
// without its data (every sampled record has it) is damaged.
let Some(data) = fx.arbitrary_data(&p.match_name) else {
if p.stored().is_some() {
col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) have no data, none used"));
col.lose_with(LossCategory::DamagedData, || format!("{here}: the Cryptomatte settings (layer, selection) have no data, none used"));
}
continue;
};
@@ -625,12 +630,14 @@ fn import_cryptomatte(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx
set(group, "layerName", Value::Str(d.layer));
set(group, "selection", Value::Str(d.selection));
}
None => col.lose(LossCategory::DamagedData, format!("{here}: the Cryptomatte settings (layer, selection) are unreadable, none used")),
None => {
col.lose_with(LossCategory::DamagedData, || format!("{here}: the Cryptomatte settings (layer, selection) are unreadable, none used"))
}
}
}
(2, ParamKind::Popup) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported, Colors used"));
col.lose_with(LossCategory::Effects, || format!("{here}: keyframes or an expression on {label} are not imported, Colors used"));
continue;
}
let (display, matte_only) = crypto_output(p, &here, &label, col);
@@ -639,19 +646,19 @@ fn import_cryptomatte(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx
}
(3, ParamKind::Checkbox) => {
if moving {
col.lose(LossCategory::Effects, format!("{here}: keyframes or an expression on {label} are not imported"));
col.lose_with(LossCategory::Effects, || format!("{here}: keyframes or an expression on {label} are not imported"));
} else {
match selection_mode_on(p) {
// A picking switch of the plug-in; EffectCraft picks with its own tool.
Some(true) => col.lose(LossCategory::Effects, format!("{here}: parameter {label} is on and has no counterpart")),
Some(true) => col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} is on and has no counterpart")),
Some(false) => {}
None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, off used")),
None => col.lose_with(LossCategory::DamagedData, || format!("{here}: parameter {label} holds an unreadable value, off used")),
}
}
}
_ => {
if p.stored().is_some() && !matches!(p.stored_value(), Some(ParamValue::Layer(0))) {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} ({:?}) not imported", p.kind));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label} ({:?}) not imported", p.kind));
}
}
}
@@ -682,17 +689,16 @@ fn crypto_output(p: &EffectParam<'_, '_>, here: &str, label: &str, col: &mut Col
Some(items) => items.clone(),
None if p.popup_item_count().map(usize::from) == Some(CRYPTOMATTE_OUTPUT.len()) => CRYPTOMATTE_OUTPUT.iter().map(|s| s.to_string()).collect(),
None => {
col.lose(
LossCategory::Effects,
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported, Colors used", p.popup_item_count()),
);
col.lose_with(LossCategory::Effects, || {
format!("{here}: parameter {label}: the file names no popup items and has {:?} of them, not imported, Colors used", p.popup_item_count())
});
return CRYPTO_COLORS;
}
};
let index = match (p.stored(), p.stored_value()) {
(Some(_), Some(ParamValue::Index(i))) => i,
(Some(_), _) => {
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value, Colors used"));
col.lose_with(LossCategory::DamagedData, || format!("{here}: parameter {label} holds an unreadable value, Colors used"));
return CRYPTO_COLORS;
}
// No record: the default. The plug-in's is Colors (1): the `pard` default of the
@@ -710,14 +716,14 @@ fn crypto_output(p: &EffectParam<'_, '_>, here: &str, label: &str, col: &mut Col
"matted rgba" => (1, false),
"matte only" => (1, true),
"matted colors" => {
col.lose(
col.lose_with(
LossCategory::Effects,
format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, imported as Matte (the layer's colours keyed by the selection, not the ID colours)"),
|| format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, imported as Matte (the layer's colours keyed by the selection, not the ID colours)"),
);
(1, false)
}
_ => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, Colors used"));
col.lose_with(LossCategory::Effects, || format!("{here}: parameter {label}: item '{item}' ({index}) has no counterpart, Colors used"));
CRYPTO_COLORS
}
}
@@ -745,7 +751,9 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
let rows_stored = group.prop("rows").map(|p| p.value.as_f64().round());
let cols_stored = group.prop("columns").map(|p| p.value.as_f64().round());
if rows_stored != Some(f64::from(m.rows)) || cols_stored != Some(f64::from(m.columns)) {
col.lose(LossCategory::Effects, format!("{here}: the Distortion Mesh is {} x {} cells, Rows / Columns say otherwise; not imported", m.columns, m.rows));
col.lose_with(LossCategory::Effects, || {
format!("{here}: the Distortion Mesh is {} x {} cells, Rows / Columns say otherwise; not imported", m.columns, m.rows)
});
return;
}
let mut offs = Vec::with_capacity(m.vertices.len());
@@ -771,7 +779,7 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
}
}
if !(dx.is_finite() && dy.is_finite() && own.iter().all(|x| x.is_finite())) {
col.lose(LossCategory::DamagedData, format!("{here}: the Distortion Mesh holds a number that is not valid, not imported"));
col.lose_with(LossCategory::DamagedData, || format!("{here}: the Distortion Mesh holds a number that is not valid, not imported"));
return;
}
// EffectCraft's mesh reads the first two numbers of a vertex; moved handles follow as
@@ -786,10 +794,9 @@ fn import_mesh(m: &MeshData, here: &str, size: (u32, u32), group: &mut PropGroup
offs.push(token);
}
if handles_moved {
col.lose(
LossCategory::Effects,
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept for the export)"),
);
col.lose_with(LossCategory::Effects, || {
format!("{here}: Distortion Mesh Bezier handles moved on their own are not drawn (EffectCraft's mesh is bilinear; they are kept for the export)")
});
}
if let Some(p) = group.prop_mut("rows") {
p.value = Value::Scalar(f64::from(m.rows));
@@ -822,3 +829,34 @@ pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
};
kind.value(&raw)
}
#[cfg(test)]
mod tests {
use super::*;
fn ui(options: &[&str]) -> ParamUi {
ParamUi::Popup { options: options.iter().map(|s| s.to_string()).collect() }
}
#[test]
fn popup_items_map_by_name_ignoring_case_separators_and_channel() {
let file: Vec<String> = ["Red Channel", "(-", " GREEN ", "Alpha channel", "Other", "red"].iter().map(|s| s.to_string()).collect();
let map = popup_mapping(&file, &ui(&["Red", "Green", "Blue", "Alpha", "red"])).expect("a popup");
// The first option of a name wins, as `position` finds it.
assert_eq!(map, [Some(0), None, Some(1), Some(3), None, Some(0)]);
assert_eq!(popup_mapping(&file, &ParamUi::Checkbox), None);
}
#[test]
fn a_popup_with_a_huge_item_list_maps_in_linear_time() {
// A `pdnm` of 200 000 items (a hostile file: the count is not bounded there) against an
// effect's options. Each comparison used to build two keys (two allocations), 4e7 of
// them here at 100 options; now each key is borrowed once and compared in place.
let options: Vec<String> = (0..100).map(|i| format!("Option {i}")).collect();
let file: Vec<String> = (0..200_000).map(|i| format!("Item {}", i % 1000)).collect();
let ui = ParamUi::Popup { options };
let map = popup_mapping(&file, &ui).expect("a popup");
assert_eq!(map.len(), file.len());
assert!(map.iter().all(Option::is_none));
}
}
+47 -24
View File
@@ -11,11 +11,11 @@
//! progress per second and reported.
use crate::{Layer as AepLayer, MaskAtom, MaskMode as AepMode, PropNode, ShapePath as AepPath, ValueSource};
use effectcraft_keyframe::{Ease, Interp, Keyframe, ShapePath, Value};
use effectcraft_keyframe::{Interp, Keyframe, ShapePath, Value};
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{GroupKind, MaskMode, Node, PropGroup as EcGroup};
use crate::import::props::{Kind, LIMIT, import_expression, import_keys, interp};
use crate::import::props::{Kind, LIMIT, ease, import_expression, import_keys, interp, sort_unique};
use crate::import::report::{Collector, LossCategory};
use crate::import::time::TimeMap;
@@ -132,7 +132,7 @@ fn import_mask(atom: &MaskAtom<'_, '_>, index: usize, name: &str, what: &str, ml
let first = match first {
Ok(p) => p,
Err(why) => {
col.lose(LossCategory::Masks, format!("{what}: not imported, {why}"));
col.lose_with(LossCategory::Masks, || format!("{what}: not imported, {why}"));
return None;
}
};
@@ -142,11 +142,11 @@ fn import_mask(atom: &MaskAtom<'_, '_>, index: usize, name: &str, what: &str, ml
AepMode::Other(c) => c,
_ => 0,
};
col.lose(LossCategory::Masks, format!("{what}: mode code {shown} is not known, imported as Add"));
col.lose_with(LossCategory::Masks, || format!("{what}: mode code {shown} is not known, imported as Add"));
MaskMode::Add
}),
None => {
col.lose(LossCategory::DamagedData, format!("{what}: mode and invert switch unreadable, Add used"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: mode and invert switch unreadable, Add used"));
MaskMode::Add
}
};
@@ -188,14 +188,14 @@ fn import_mask(atom: &MaskAtom<'_, '_>, index: usize, name: &str, what: &str, ml
fn set_static(g: &mut EcGroup, id: &str, value: Value, source: ValueSource, valid: impl Fn(&Value) -> bool, what: &str, col: &mut Collector) {
match source {
ValueSource::Default | ValueSource::Keyframed => {}
ValueSource::Unreadable => col.lose(LossCategory::DamagedData, format!("{what}: {id} unreadable, default used")),
ValueSource::Unreadable => col.lose_with(LossCategory::DamagedData, || format!("{what}: {id} unreadable, default used")),
ValueSource::Stored => {
if crate::import::props::sane(&value) && valid(&value) {
if let Some(p) = g.get_mut(id) {
p.value = value;
}
} else {
col.lose(LossCategory::DamagedData, format!("{what}: {id} holds a number that is not valid, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: {id} holds a number that is not valid, default used"));
}
}
}
@@ -213,25 +213,25 @@ pub(crate) fn import_path_keys(
col: &mut Collector,
) {
let Some(list) = path.keys() else {
col.lose(LossCategory::DamagedData, format!("{what}: path keyframes unreadable, the first shape is static"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: path keyframes unreadable, the first shape is static"));
return;
};
let records: Vec<_> = list.keyframes().collect();
if records.len() != shapes.len() {
col.lose(LossCategory::DamagedData, format!("{what}: {} path keyframes but {} shapes, the first shape is static", records.len(), shapes.len()));
col.lose_with(LossCategory::DamagedData, || format!("{what}: {} path keyframes but {} shapes, the first shape is static", records.len(), shapes.len()));
return;
}
let scale = path.time_scale().filter(|s| *s != 0).unwrap_or(tm.timescale);
let mut keys: Vec<Keyframe> = Vec::new();
for (rec, shape) in records.iter().zip(shapes) {
let Some(units) = rec.time_units() else {
col.lose(LossCategory::DamagedData, format!("{what}: unreadable path keyframe"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: unreadable path keyframe"));
continue;
};
let path = match shape.as_ref().ok_or("its shape is unreadable").and_then(|s| to_path(s, size)) {
Ok(p) => p,
Err(why) => {
col.lose(LossCategory::DamagedData, format!("{what}: a path keyframe was dropped, {why}"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: a path keyframe was dropped, {why}"));
continue;
}
};
@@ -241,20 +241,25 @@ pub(crate) fn import_path_keys(
if key.in_interp == Interp::Bezier || key.out_interp == Interp::Bezier {
// The ease at byte 24 (599, 700): influences as fractions; a speed of 0 is exact, the
// unit of another speed is not verified (taken as progress per second).
match rec.ease().filter(|e| [e.in_speed, e.in_influence, e.out_speed, e.out_influence].iter().all(|v| v.is_finite())) {
Some(e) => {
// The same rule as every other key's ease (`props::ease`): a speed beyond its limit is
// unreadable, not imported as it is.
match rec.ease().and_then(path_eases) {
Some((in_e, out_e)) => {
let unverified = (key.in_interp == Interp::Bezier && in_e.speed != 0.0) || (key.out_interp == Interp::Bezier && out_e.speed != 0.0);
if key.in_interp == Interp::Bezier {
key.in_ease = vec![Ease { speed: e.in_speed, influence: e.in_influence.clamp(0.001, 1.0) }];
key.in_ease = vec![in_e];
}
if key.out_interp == Interp::Bezier {
key.out_ease = vec![Ease { speed: e.out_speed, influence: e.out_influence.clamp(0.001, 1.0) }];
key.out_ease = vec![out_e];
}
if (key.in_interp == Interp::Bezier && e.in_speed != 0.0) || (key.out_interp == Interp::Bezier && e.out_speed != 0.0) {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: path key ease speed imported unverified (only speed 0 is sampled)"));
if unverified {
col.lose_with(LossCategory::ApproximatedKeyframes, || {
format!("{what}: path key ease speed imported unverified (only speed 0 is sampled)")
});
}
}
None => {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: bezier path key read as linear (its ease is unreadable)"));
col.lose_with(LossCategory::ApproximatedKeyframes, || format!("{what}: bezier path key read as linear (its ease is unreadable)"));
key.in_interp = if key.in_interp == Interp::Bezier { Interp::Linear } else { key.in_interp };
key.out_interp = if key.out_interp == Interp::Bezier { Interp::Linear } else { key.out_interp };
}
@@ -267,12 +272,7 @@ pub(crate) fn import_path_keys(
if keys.is_empty() {
return;
}
keys.sort_by_key(|k| k.time);
let before = keys.len();
keys.dedup_by_key(|k| k.time);
if keys.len() != before {
col.lose(LossCategory::DamagedData, format!("{what}: path keyframes at the same time"));
}
sort_unique(&mut keys, what, "path keyframes", col);
// The first key's incoming and the last key's outgoing ease mean nothing.
if let Some(first) = keys.first_mut() {
first.in_ease.clear();
@@ -286,3 +286,26 @@ pub(crate) fn import_path_keys(
}
prop.keys = keys;
}
/// The in and out ease of a mask path key, under the rule of every other key's ease
/// (`props::ease`); `None` when either side cannot be used.
fn path_eases(e: crate::KeyEase) -> Option<(effectcraft_keyframe::Ease, effectcraft_keyframe::Ease)> {
Some((ease(e.in_speed, e.in_influence, 1.0)?, ease(e.out_speed, e.out_influence, 1.0)?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_ease_speed_beyond_the_property_limit_is_unreadable() {
let e = |speed: f64| crate::KeyEase { in_speed: speed, in_influence: 0.5, out_speed: 0.0, out_influence: 2.0 };
let (i, o) = path_eases(e(3.0)).expect("usable");
assert_eq!((i.speed, i.influence, o.speed, o.influence), (3.0, 0.5, 0.0, 1.0));
// Finite but far beyond what a property key accepts (before, only finiteness was checked).
assert!(path_eases(e(1e12)).is_none());
assert!(path_eases(e(-1e12)).is_none());
assert!(path_eases(e(f64::NAN)).is_none());
assert!(path_eases(crate::KeyEase { out_speed: 1e12, ..e(0.0) }).is_none());
}
}
+52 -23
View File
@@ -200,12 +200,12 @@ pub(crate) fn import_transform(
}
if source_of == ValueSource::Unreadable {
// Present in the file but not decodable: the reader gave the default in its place.
col.lose(LossCategory::DamagedData, format!("{layer_name}: {match_name} unreadable, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{layer_name}: {match_name} unreadable, default used"));
}
if sane(&base) {
prop.value = base;
} else {
col.lose(LossCategory::DamagedData, format!("{layer_name}: {match_name} holds a number that is not valid, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{layer_name}: {match_name} holds a number that is not valid, default used"));
}
let Some(PropNode::Property(node)) = group.get(match_name) else { continue };
if source_of == ValueSource::Keyframed {
@@ -216,7 +216,7 @@ pub(crate) fn import_transform(
for (match_name, id) in ROTATIONS {
let Some(PropNode::Property(node)) = group.get(match_name) else { continue };
let Some(prop) = target.get_mut(id) else {
col.lose(LossCategory::TransformProperties, format!("{layer_name}: {match_name}"));
col.lose_with(LossCategory::TransformProperties, || format!("{layer_name}: {match_name}"));
continue;
};
if node.is_animated() {
@@ -226,7 +226,7 @@ pub(crate) fn import_transform(
if sane(&value) {
prop.value = value;
} else {
col.lose(LossCategory::DamagedData, format!("{layer_name}: {match_name} holds a number that is not valid, default used"));
col.lose_with(LossCategory::DamagedData, || format!("{layer_name}: {match_name} holds a number that is not valid, default used"));
}
}
import_expression(&node, prop, col);
@@ -246,7 +246,7 @@ pub(crate) fn import_transform(
}
// A layer without an orientation (an ambient light) loses nothing with the default.
(Some(o), None) if !o.animated && !o.has_expression && o.degrees == [0.0; 3] => {}
_ => col.lose(LossCategory::TransformProperties, format!("{layer_name}: ADBE Orientation")),
_ => col.lose_with(LossCategory::TransformProperties, || format!("{layer_name}: ADBE Orientation")),
}
}
report_other_properties(&group, layer_name, col);
@@ -259,7 +259,7 @@ fn import_orientation_keys(layer: &AepLayer<'_, '_>, layer_name: &str, tm: &Time
let what = format!("{layer_name}: ADBE Orientation");
let stored = layer.orientation_keys();
if stored.is_empty() {
col.lose(LossCategory::TransformProperties, format!("{what} keys unreadable, the static value is used"));
col.lose_with(LossCategory::TransformProperties, || format!("{what} keys unreadable, the static value is used"));
return;
}
// Key times count in the property's time scale (a stretched layer's is scaled), as in
@@ -270,7 +270,7 @@ fn import_orientation_keys(layer: &AepLayer<'_, '_>, layer_name: &str, tm: &Time
for k in &stored {
let value = Value::Vec3(k.degrees);
if !sane(&value) {
col.lose(LossCategory::DamagedData, format!("{what}: keyframe value is not a number"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: keyframe value is not a number"));
continue;
}
let mut key = Keyframe::new(tm.units(i64::from(k.time_units), scale), value);
@@ -286,10 +286,10 @@ fn import_orientation_keys(layer: &AepLayer<'_, '_>, layer_name: &str, tm: &Time
keys.push(key);
}
if approximated {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: bezier key read as linear (the Orientation ease is not sampled)"));
col.lose_with(LossCategory::ApproximatedKeyframes, || format!("{what}: bezier key read as linear (the Orientation ease is not sampled)"));
}
keys.sort_by_key(|k| k.time);
keys.dedup_by_key(|k| k.time);
// Reported as on every other property (`import_keys`, mask paths).
sort_unique(&mut keys, &what, "keyframes", col);
col.imported.keyframes = col.imported.keyframes.saturating_add(keys.len());
if let Some(first) = keys.first() {
prop.value = first.value.clone();
@@ -308,7 +308,7 @@ fn report_other_properties(group: &PropGroup<'_, '_>, layer_name: &str, col: &mu
// A property in its default state (`tdsb` 3) holds nothing to lose.
let stored = p.is_animated() || p.flags() == Some(1) || p.expression().is_some();
if stored && !(IGNORED.contains(&name) && p.flags() != Some(1) && !p.is_animated()) {
col.lose(LossCategory::TransformProperties, format!("{layer_name}: {name}"));
col.lose_with(LossCategory::TransformProperties, || format!("{layer_name}: {name}"));
}
}
}
@@ -327,14 +327,26 @@ pub(crate) fn interp(i: Option<Interpolation>, col: &mut Collector, what: &str)
Some(Interpolation::Bezier) => Interp::Bezier,
Some(Interpolation::Hold) => Interp::Hold,
Some(Interpolation::Other(code)) => {
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: unknown interpolation {code} read as linear"));
col.lose_with(LossCategory::ApproximatedKeyframes, || format!("{what}: unknown interpolation {code} read as linear"));
Interp::Linear
}
}
}
/// An ease that can be evaluated: finite speed, influence within 0.1 % and 100 %.
fn ease(speed: f64, influence: f64, factor: f64) -> Option<Ease> {
/// Puts `keys` in time order and keeps the first of keys at the same time, reporting that some
/// were dropped (`noun` names them: "keyframes", "path keyframes").
pub(crate) fn sort_unique(keys: &mut Vec<Keyframe>, what: &str, noun: &str, col: &mut Collector) {
keys.sort_by_key(|k| k.time);
let before = keys.len();
keys.dedup_by_key(|k| k.time);
if keys.len() != before {
col.lose_with(LossCategory::DamagedData, || format!("{what}: {noun} at the same time"));
}
}
/// An ease that can be evaluated: finite speed within `LIMIT * 100`, influence within 0.1 % and
/// 100 % (also the rule for mask path keys, `import/masks.rs`).
pub(crate) fn ease(speed: f64, influence: f64, factor: f64) -> Option<Ease> {
let speed = speed * factor;
(speed.is_finite() && speed.abs() <= LIMIT * 100.0 && influence.is_finite()).then(|| Ease { speed, influence: influence.clamp(0.001, 1.0) })
}
@@ -376,11 +388,11 @@ pub(crate) fn import_keys(node: &AepProp<'_, '_>, kind: Kind, layer_name: &str,
let mut keys: Vec<Keyframe> = Vec::new();
for rec in list.keyframes() {
let (Some(units), Some(raw)) = (rec.time_units(), rec.value()) else {
col.lose(LossCategory::DamagedData, format!("{what}: unreadable keyframe"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: unreadable keyframe"));
continue;
};
let Some(value) = kind.value(&raw) else {
col.lose(LossCategory::DamagedData, format!("{what}: keyframe value is missing or not a number"));
col.lose_with(LossCategory::DamagedData, || format!("{what}: keyframe value is missing or not a number"));
continue;
};
let mut key = Keyframe::new(tm.units(i64::from(units), scale), value);
@@ -422,7 +434,7 @@ pub(crate) fn import_keys(node: &AepProp<'_, '_>, kind: Kind, layer_name: &str,
None => {
// The ease cannot be used, so the bezier sides become linear.
let why = if undecoded { "the ease of this effect parameter is not decoded" } else { "ease data not decodable" };
col.lose(LossCategory::ApproximatedKeyframes, format!("{what}: bezier key read as linear ({why})"));
col.lose_with(LossCategory::ApproximatedKeyframes, || format!("{what}: bezier key read as linear ({why})"));
if key.in_interp == Interp::Bezier {
key.in_interp = Interp::Linear;
}
@@ -437,12 +449,7 @@ pub(crate) fn import_keys(node: &AepProp<'_, '_>, kind: Kind, layer_name: &str,
if keys.is_empty() {
return;
}
keys.sort_by_key(|k| k.time);
let before = keys.len();
keys.dedup_by_key(|k| k.time);
if keys.len() != before {
col.lose(LossCategory::DamagedData, format!("{what}: keyframes at the same time"));
}
sort_unique(&mut keys, &what, "keyframes", col);
// The first key's incoming and the last key's outgoing ease mean nothing.
if let Some(first) = keys.first_mut() {
first.in_ease.clear();
@@ -456,3 +463,25 @@ pub(crate) fn import_keys(node: &AepProp<'_, '_>, kind: Kind, layer_name: &str,
}
prop.keys = keys;
}
#[cfg(test)]
mod tests {
use super::*;
use effectcraft_time::Tick;
#[test]
fn keys_at_the_same_time_are_merged_and_reported() {
let key = |t: i64, v: f64| Keyframe::new(Tick(t), Value::Scalar(v));
let mut keys = vec![key(5, 1.0), key(0, 2.0), key(5, 3.0)];
let mut col = Collector::default();
sort_unique(&mut keys, "L: ADBE Orientation", "keyframes", &mut col);
assert_eq!(keys.iter().map(|k| (k.time.0, k.value.clone())).collect::<Vec<_>>(), [(0, Value::Scalar(2.0)), (5, Value::Scalar(1.0))]);
let report = col.finish();
assert_eq!(report.count(LossCategory::DamagedData), 1);
assert_eq!(report.losses[0].details, ["L: ADBE Orientation: keyframes at the same time"]);
// Distinct times: nothing reported.
let mut col = Collector::default();
sort_unique(&mut vec![key(1, 0.0), key(0, 0.0)], "L", "keyframes", &mut col);
assert!(col.finish().losses.is_empty());
}
}
+6 -5
View File
@@ -340,14 +340,15 @@ impl Collector {
/// Records one instance of an effect with no counterpart. The loss is counted now; its line is
/// made in [`Collector::finish`], one per effect with the number of instances, so that many
/// other losses cannot hide which effects were dropped.
pub fn lose_unmapped_effect(&mut self, match_name: &str, detail: String) {
/// `detail` is only called for an effect not seen before.
pub fn lose_unmapped_effect(&mut self, match_name: &str, detail: impl FnOnce() -> String) {
let loss =
self.losses.entry(LossCategory::Effects).or_insert_with(|| Loss { category: LossCategory::Effects, count: 0, details: Vec::new(), unlisted: 0 });
loss.count = loss.count.saturating_add(1);
if let Some(seen) = self.unmapped_effects.get_mut(match_name) {
seen.1 = seen.1.saturating_add(1);
} else if self.unmapped_effects.len() < MAX_UNMAPPED_EFFECTS {
self.unmapped_effects.insert(match_name.to_string(), (detail, 1));
self.unmapped_effects.insert(match_name.to_string(), (detail(), 1));
}
// (Past the limit an effect is only counted: its name is not worth a line of its own.)
}
@@ -457,9 +458,9 @@ mod tests {
col.lose(LossCategory::Effects, format!("C: 'L{i}': parameter P not imported"));
}
for i in 0..25 {
col.lose_unmapped_effect("CC Cylinder", format!("C: 'Cyl{i}' has the effect 'CC Cylinder' (CC Cylinder)"));
col.lose_unmapped_effect("CC Cylinder", || format!("C: 'Cyl{i}' has the effect 'CC Cylinder' (CC Cylinder)"));
}
col.lose_unmapped_effect("Pseudo/", "C: 'D' has the effect 'Dropdown' (Pseudo/)".to_string());
col.lose_unmapped_effect("Pseudo/", || "C: 'D' has the effect 'Dropdown' (Pseudo/)".to_string());
let report = col.finish();
let effects = report.losses.iter().find(|l| l.category == LossCategory::Effects).unwrap();
assert_eq!(effects.count, 56, "30 parameters, 25 cylinders and 1 dropdown");
@@ -496,7 +497,7 @@ mod tests {
fn at_most_the_limit_of_unmapped_effects_are_named() {
let mut col = Collector::default();
for i in 0..=MAX_UNMAPPED_EFFECTS {
col.lose_unmapped_effect(&format!("Effect {i}"), format!("C: 'L' has the effect 'Effect {i}' (Effect {i})"));
col.lose_unmapped_effect(&format!("Effect {i}"), || format!("C: 'L' has the effect 'Effect {i}' (Effect {i})"));
}
let report = col.finish();
let effects = report.losses.iter().find(|l| l.category == LossCategory::Effects).unwrap();
+53 -23
View File
@@ -54,7 +54,7 @@ fn key_kind(conv: StyleConv) -> Option<Kind> {
fn import_param(spec: &StyleParam, full: &str, node: Option<PropNode<'_, '_>>, prop: &mut EcProp, tm: &TimeMap, what: &str, col: &mut Collector) {
if spec.conv == StyleConv::Gradient {
if node.is_some() {
col.lose(LossCategory::LayerStyles, format!("{what}: {full} (gradient colours are not decoded, EffectCraft's default gradient kept)"));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: {full} (gradient colours are not decoded, EffectCraft's default gradient kept)"));
}
return;
}
@@ -63,7 +63,7 @@ fn import_param(spec: &StyleParam, full: &str, node: Option<PropNode<'_, '_>>, p
}
let Some(node) = node else { return };
let PropNode::Property(p) = node else {
col.lose(LossCategory::LayerStyles, format!("{what}: {full} is not a property, default used"));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: {full} is not a property, default used"));
return;
};
import_record(spec.conv, &p, full, prop, tm, what, col);
@@ -73,12 +73,12 @@ fn import_record(conv: StyleConv, p: &AepProp<'_, '_>, full: &str, prop: &mut Ec
if p.is_animated() {
match key_kind(conv) {
Some(kind) => import_keys(p, kind, what, full, tm, prop, col),
None => col.lose(LossCategory::LayerStyles, format!("{what}: keys on {full} are not imported (not sampled), default used")),
None => col.lose_with(LossCategory::LayerStyles, || format!("{what}: keys on {full} are not imported (not sampled), default used")),
}
} else if let Some(stored) = p.static_value() {
match value(conv, &stored) {
Some(v) => prop.value = v,
None => col.lose(LossCategory::LayerStyles, format!("{what}: {full} holds a value that is not valid ({stored:?}), default used")),
None => col.lose_with(LossCategory::LayerStyles, || format!("{what}: {full} holds a value that is not valid ({stored:?}), default used")),
}
}
import_expression(p, prop, col);
@@ -102,33 +102,37 @@ pub(crate) fn import_layer_styles(layer: &AepLayer<'_, '_>, l: &mut Layer, gl: &
Some(sm::FLAGS_ON) => true,
Some(sm::FLAGS_OFF) => false,
other => {
col.lose(LossCategory::LayerStyles, format!("{what}: style {prefix} in state {} (not sampled), not imported", other.unwrap_or(0)));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: style {prefix} in state {} (not sampled), not imported", other.unwrap_or(0)));
continue;
}
};
match sm::by_ae(prefix) {
Some(spec) => applied.push((spec, g, on)),
None if prefix == sm::PATTERN_OVERLAY => col.lose(LossCategory::LayerStyles, format!("{what}: Pattern Overlay (no counterpart)")),
None => col.lose(LossCategory::LayerStyles, format!("{what}: unknown layer style {prefix}")),
None if prefix == sm::PATTERN_OVERLAY => col.lose_with(LossCategory::LayerStyles, || format!("{what}: Pattern Overlay (no counterpart)")),
None => col.lose_with(LossCategory::LayerStyles, || format!("{what}: unknown layer style {prefix}")),
}
}
if applied.is_empty() {
// Without a style the Blending Options group holds only an empty Advanced Blending group
// (every case); stored values there have nowhere to go.
if let Some(PropNode::Group(bo)) = ls.get(sm::BLEND_OPTIONS)
&& holds_values(&bo, 0)
{
col.lose(LossCategory::LayerStyles, format!("{what}: Blending Options set without a layer style, not imported"));
if let Some(PropNode::Group(bo)) = ls.get(sm::BLEND_OPTIONS) {
match holds_values(&bo, 0) {
Held::Values => col.lose_with(LossCategory::LayerStyles, || format!("{what}: Blending Options set without a layer style, not imported")),
Held::TooDeep => col.lose_with(LossCategory::LayerStyles, || {
format!("{what}: Blending Options nest groups deeper than {MAX_HELD_DEPTH} levels, not read (they may hold values)")
}),
Held::Nothing => {}
}
}
return;
}
if !l.can_have_styles() {
col.lose(LossCategory::LayerStyles, format!("{what}: this kind of layer takes no layer styles here ({} not imported)", applied.len()));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: this kind of layer takes no layer styles here ({} not imported)", applied.len()));
return;
}
for (spec, g, on) in &applied {
let Some(uid) = st::add_style(l, ids, spec.ec, gl, *on) else {
col.lose(LossCategory::LayerStyles, format!("{what}: style {} could not be added", spec.ae));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: style {} could not be added", spec.ae));
continue;
};
let Some(group) = l.props.find_group_mut(uid) else { continue };
@@ -138,12 +142,12 @@ pub(crate) fn import_layer_styles(layer: &AepLayer<'_, '_>, l: &mut Layer, gl: &
let node = records.iter().find(|r| r.match_name == full).map(|r| r.node);
match group.get_mut(prm.ec) {
Some(prop) => import_param(prm, &full, node, prop, tm, what, col),
None => col.lose(LossCategory::LayerStyles, format!("{what}: {full} has no counterpart '{}'", prm.ec)),
None => col.lose_with(LossCategory::LayerStyles, || format!("{what}: {full} has no counterpart '{}'", prm.ec)),
}
}
for r in &records {
if r.match_name != "ADBE Group End" && !spec.params.iter().any(|prm| spec.param_name(prm) == r.match_name) {
col.lose(LossCategory::LayerStyles, format!("{what}: {} is not imported (unknown parameter)", r.match_name));
col.lose_with(LossCategory::LayerStyles, || format!("{what}: {} is not imported (unknown parameter)", r.match_name));
}
}
col.imported.layer_styles += 1;
@@ -151,14 +155,40 @@ pub(crate) fn import_layer_styles(layer: &AepLayer<'_, '_>, l: &mut Layer, gl: &
import_blending(&ls, l, tm, what, col);
}
/// True when `g` or a group below it (to a bounded depth) stores a property.
fn holds_values(g: &AepGroup<'_, '_>, depth: usize) -> bool {
depth < 8
&& g.entries().iter().any(|e| match e.node {
PropNode::Property(_) => true,
PropNode::Group(sub) => holds_values(&sub, depth.saturating_add(1)),
PropNode::Other(_) => false,
})
/// The deepest group below Blending Options that is looked into for stored values.
const MAX_HELD_DEPTH: usize = 8;
/// What a group stores, looked at to [`MAX_HELD_DEPTH`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Held {
Nothing,
/// A property, in the group or a group below it.
Values,
/// No property within the depth, but a group at the depth limit that is not empty (it may
/// hold values; deeper is not read).
TooDeep,
}
/// Whether `g` or a group below it (to a bounded depth) stores a property. A non-empty group at
/// the depth limit is not looked into: it counts as [`Held::TooDeep`] (reported), not as empty;
/// After Effects nests Blending Options two levels deep.
fn holds_values(g: &AepGroup<'_, '_>, depth: usize) -> Held {
if depth >= MAX_HELD_DEPTH {
return if g.entries().is_empty() { Held::Nothing } else { Held::TooDeep };
}
let mut held = Held::Nothing;
for e in g.entries() {
match e.node {
PropNode::Property(_) => return Held::Values,
PropNode::Group(sub) => match holds_values(&sub, depth.saturating_add(1)) {
Held::Values => return Held::Values,
Held::TooDeep => held = Held::TooDeep,
Held::Nothing => {}
},
PropNode::Other(_) => {}
}
}
held
}
/// Blending Options: Global Light (adopted by the composition later) and Advanced Blending.
+1
View File
@@ -3,6 +3,7 @@
#[macro_use]
mod helpers;
mod bounds;
mod built;
mod ease;
mod effects;
+72
View File
@@ -0,0 +1,72 @@
//! Projects that used to cost quadratic time to export (#3299): many layers of one
//! precomposition in a composition that is itself shown many times, and a long parent chain. The
//! sizes are moderate, so the tests check what is written; the bounds are pinned by the unit tests
//! in `export::plan`.
use std::sync::Arc;
use crate::export::helpers::*;
use effectcraft_aep::export::LossCategory;
use effectcraft_project::{ItemId, ItemKind, LayerSource, Project, build};
use effectcraft_time::FrameRate;
/// Puts `n` layers of `source` into `comp` at once; `edit` changes layer `i`.
fn fill(p: &mut Project, comp: ItemId, n: usize, source: LayerSource, edit: &dyn Fn(usize, &mut effectcraft_project::Layer)) {
let mut c = p.comp(comp).cloned().expect("comp");
for i in 0..n {
let mut l = build::layer(p, &c, &format!("L{i}"), source.clone(), (100, 100), None);
l.name = format!("L{i}");
edit(i, &mut l);
c.layers.push(l);
}
if let Some(item) = p.item_mut(comp) {
item.kind = ItemKind::Comp(Arc::new(c));
}
}
#[test]
fn many_layers_of_one_precomp_in_a_shown_composition_are_written() {
let n = 1500;
let mut p = Project::default();
let a = add_comp(&mut p, "A", 100, 100, FrameRate::new(25, 1), 1.0, None);
let s = add_solid(&mut p, "S", 100, 100, [1.0, 0.0, 0.0], None);
add_layer(&mut p, a, "S", LayerSource::Solid { item: s }, (100, 100));
let b = add_comp(&mut p, "B", 100, 100, FrameRate::new(25, 1), 1.0, None);
fill(&mut p, b, n, LayerSource::Comp { item: a }, &|_, _| {});
let c = add_comp(&mut p, "C", 100, 100, FrameRate::new(25, 1), 1.0, None);
fill(&mut p, c, n, LayerSource::Comp { item: b }, &|_, _| {});
let r = export_all(&p);
assert_eq!(r.report.exported.precomp_layers, 2 * n);
assert_eq!(r.report.count(LossCategory::UnsupportedLayers), 0, "{:?}", r.report.losses);
}
#[test]
fn a_long_parent_chain_is_written_and_its_loop_cut_once() {
let n = 1500;
let mut p = Project::default();
let s = add_solid(&mut p, "S", 100, 100, [1.0, 0.0, 0.0], None);
let c = add_comp(&mut p, "C", 100, 100, FrameRate::new(25, 1), 1.0, None);
fill(&mut p, c, n, LayerSource::Solid { item: s }, &|_, _| {});
// Each layer parented to the next; with `closed`, the last to the first (a loop).
for closed in [false, true] {
let mut q = p.clone();
with_comp(&mut q, c, |cc| {
let ids: Vec<_> = cc.layers.iter().map(|l| l.id).collect();
for i in 0..n {
let next = if i + 1 < n {
Some(ids[i + 1])
} else if closed {
Some(ids[0])
} else {
None
};
if let Some(l) = cc.layers.get_mut(i) {
l.parent = next;
}
}
});
let r = export_all(&q);
assert_eq!(r.report.exported.layers, n);
assert_eq!(r.report.count(LossCategory::ParentLinks), usize::from(closed), "{:?}", r.report.losses);
}
}
+1
View File
@@ -6,6 +6,7 @@ mod helpers;
mod aepx;
mod ai_mask;
mod blend_modes;
mod bounds;
mod cameras;
mod cases;
mod combined;
+341
View File
@@ -0,0 +1,341 @@
//! Hostile inputs that used to cost quadratic time, and losses that used to be silent (#3299).
//!
//! The quadratic cases are built from the committed `tests/fixtures/synthetic.aep` (composition
//! `C`, id 2, with a sequence layer, id 17, and a solid layer, id 16): its composition item and
//! its solid layer are copied with new ids. The sizes here are moderate, so the tests check what
//! arrives; the bounds themselves are pinned by the unit tests next to the code
//! (`import::build`, `import::effects`).
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
use effectcraft_aep::{AepFile, Body, Chunk, parse, write};
use effectcraft_project::{ItemKind, LayerId, LayerSource, Project};
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
/// The item id of composition `C` and the layer id of its solid layer.
const COMP_C: u32 = 2;
const SOLID_LAYER: u32 = 16;
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("imports");
(project, r)
}
fn losses(r: &ImportResult, category: LossCategory) -> Vec<String> {
r.report.losses.iter().filter(|l| l.category == category).flat_map(|l| l.details.clone()).collect()
}
fn set_be_u32(c: &mut Chunk<'_>, at: usize, v: u32) {
if let Body::Data(d) = &mut c.body {
d.to_mut()[at..at + 4].copy_from_slice(&v.to_be_bytes());
}
}
fn be_u32(c: &Chunk<'_>, at: usize) -> u32 {
u32::from_be_bytes(c.bytes().expect("data")[at..at + 4].try_into().unwrap())
}
fn children<'c, 'a>(c: &'c mut Chunk<'a>) -> &'c mut Vec<Chunk<'a>> {
match &mut c.body {
Body::List { children, .. } | Body::Chunks(children) => children,
_ => panic!("not a list"),
}
}
/// The project's folder list (`LIST Fold`, top level).
fn fold<'f, 'a>(file: &'f mut AepFile<'a>) -> &'f mut Vec<Chunk<'a>> {
children(file.chunks.iter_mut().find(|c| c.is_list(b"Fold")).expect("Fold"))
}
/// The `Item` list of composition `C`.
fn comp_c<'a>(file: &AepFile<'a>) -> Chunk<'a> {
let fold = file.list(b"Fold").expect("Fold");
fold.children().iter().find(|c| c.is_list(b"Item") && c.child(b"idta").is_some_and(|i| be_u32(i, 16) == COMP_C)).expect("composition C").clone()
}
/// The solid layer of `C` (`LIST Layr` with id 16).
fn solid_layer<'a>(comp: &Chunk<'a>) -> Chunk<'a> {
comp.children().iter().find(|c| c.is_list(b"Layr") && c.child(b"ldta").is_some_and(|l| be_u32(l, 0) == SOLID_LAYER)).expect("the solid layer").clone()
}
/// A copy of `layer` with layer id `id`; `edit` changes its `ldta`.
fn layer_copy<'a>(layer: &Chunk<'a>, id: u32, edit: &dyn Fn(&mut Chunk<'a>)) -> Chunk<'a> {
let mut l = layer.clone();
let ldta = children(&mut l).iter_mut().find(|c| c.is(b"ldta")).expect("ldta");
set_be_u32(ldta, 0, id);
edit(ldta);
l
}
/// A composition like `C` with item id `id`, name `name` and only the layers `layers`.
fn comp_with<'a>(c: &Chunk<'a>, id: u32, name: &str, layers: Vec<Chunk<'a>>) -> Chunk<'a> {
let mut item = c.clone();
let kids = children(&mut item);
kids.retain(|k| !k.is_list(b"Layr"));
for k in kids.iter_mut() {
if k.is(b"idta") {
set_be_u32(k, 16, id);
}
if k.is(b"Utf8") {
*k = Chunk::data(*b"Utf8", name.as_bytes().to_vec());
}
}
let at = kids.iter().position(|k| k.is_list(b"Ewst")).unwrap_or(kids.len());
kids.splice(at..at, layers);
item
}
/// Composition `B` (id 900) with `n` layers of `C`, and `D` (id 901) with `n` layers of `B`,
/// after `C` in the file. With `c_uses_d`, `C` also gets a layer of `D`, which closes a loop.
fn precomp_chain(n: u32, c_uses_d: bool) -> Vec<u8> {
precomp_chain_with(n, c_uses_d, false)
}
/// [`precomp_chain`]; with `null_back_edge` the layer of `D` in `C` is a null object (which shows
/// nothing, so no loop).
fn precomp_chain_with(n: u32, c_uses_d: bool, null_back_edge: bool) -> Vec<u8> {
let mut file = parse(SYNTHETIC).unwrap();
let c = comp_c(&file);
let solid = solid_layer(&c);
let layers = |first: u32, source: u32| -> Vec<Chunk<'_>> { (0..n).map(|i| layer_copy(&solid, first + i, &|l| set_be_u32(l, 40, source))).collect() };
let b = comp_with(&c, 900, "B", layers(100_000, COMP_C));
let d = comp_with(&c, 901, "D", layers(200_000, 900));
let fold = fold(&mut file);
let at = fold.iter().position(|k| k.is_list(b"Item") && k.child(b"idta").is_some_and(|i| be_u32(i, 16) == COMP_C)).expect("C") + 1;
fold.splice(at..at, [b, d]);
if c_uses_d {
let c = fold.iter_mut().find(|k| k.is_list(b"Item") && k.child(b"idta").is_some_and(|i| be_u32(i, 16) == COMP_C)).expect("C");
let kids = children(c);
let at = kids.iter().position(|k| k.is_list(b"Layr")).expect("a layer");
kids.insert(
at,
layer_copy(&solid, 300_000, &|l| {
set_be_u32(l, 40, 901);
if null_back_edge && let Body::Data(d) = &mut l.body {
d.to_mut()[38] |= 0x80;
}
}),
);
}
write(&file).unwrap()
}
fn comp_named<'p>(p: &'p Project, name: &str) -> &'p effectcraft_project::Comp {
p.items.values().find_map(|i| if let ItemKind::Comp(c) = &i.kind { (i.name == name).then_some(&**c) } else { None }).unwrap_or_else(|| panic!("no {name}"))
}
#[test]
fn many_layers_of_one_precomp_in_a_used_composition_import() {
let n = 1500;
let (p, r) = run(&precomp_chain(n, false));
let (b, d) = (comp_named(&p, "B"), comp_named(&p, "D"));
let item = |name: &str| p.items.values().find(|i| i.name == name).map(|i| i.id).expect("item");
assert_eq!(b.layers.len(), n as usize);
assert!(b.layers.iter().all(|l| l.source == LayerSource::Comp { item: item("C") }));
assert!(d.layers.iter().all(|l| l.source == LayerSource::Comp { item: item("B") }));
assert_eq!(d.layers.len(), n as usize);
assert_eq!(r.report.imported.precomp_layers, 2 * n as usize);
let found = losses(&r, LossCategory::UnsupportedLayers);
assert!(!found.iter().any(|d| d.contains("loop")), "{found:?}");
}
#[test]
fn every_precomp_layer_that_closes_a_loop_is_refused() {
// C (built first) uses D; B uses C; so D's layers of B would close C -> D -> B -> C.
let n = 300;
let (_, base) = run(SYNTHETIC);
let (p, r) = run(&precomp_chain(n, true));
assert_eq!(comp_named(&p, "B").layers.len(), n as usize);
assert!(comp_named(&p, "D").layers.is_empty());
let refused = r.report.count(LossCategory::UnsupportedLayers) - base.report.count(LossCategory::UnsupportedLayers);
assert_eq!(refused, n as usize, "{:?}", r.report.losses);
assert!(losses(&r, LossCategory::UnsupportedLayers).iter().any(|d| d.contains("precomposition loop")));
}
#[test]
fn a_null_layer_naming_a_composition_closes_no_loop() {
// The same files as above, but C's layer of D is a null object: it shows nothing, so D's
// layers of B are no loop and all of them are imported.
let n = 300;
let (p, r) = run(&precomp_chain_with(n, true, true));
assert_eq!(comp_named(&p, "D").layers.len(), n as usize);
assert!(comp_named(&p, "C").layers.iter().any(|l| l.source == LayerSource::Null));
assert!(!losses(&r, LossCategory::UnsupportedLayers).iter().any(|d| d.contains("loop")), "{:?}", r.report.losses);
}
#[test]
fn many_parented_and_matted_layers_resolve() {
// `n` copies of the solid layer in C, each parented to it and using it as an alpha matte.
let n = 1500;
let mut file = parse(SYNTHETIC).unwrap();
let c = comp_c(&file);
let solid = solid_layer(&c);
let fold = fold(&mut file);
let item = fold.iter_mut().find(|k| k.is_list(b"Item") && k.child(b"idta").is_some_and(|i| be_u32(i, 16) == COMP_C)).expect("C");
let kids = children(item);
let at = kids.iter().position(|k| k.is_list(b"Layr")).expect("a layer");
let copies: Vec<Chunk<'_>> = (0..n)
.map(|i| {
layer_copy(&solid, 100_000 + i, &|l| {
set_be_u32(l, 132, SOLID_LAYER);
if let Body::Data(d) = &mut l.body {
d.to_mut()[107] = 1;
}
set_be_u32(l, 160, SOLID_LAYER);
})
})
.collect();
kids.splice(at..at, copies);
let (p, r) = run(&write(&file).unwrap());
let c = comp_named(&p, "C");
// The original solid layer: the last layer whose source is the solid and that has no parent.
let target: LayerId = c.layers.iter().rev().find(|l| l.parent.is_none() && matches!(l.source, LayerSource::Solid { .. })).map(|l| l.id).expect("the solid");
let linked: Vec<_> = c.layers.iter().filter(|l| l.parent.is_some()).collect();
assert_eq!(linked.len(), n as usize);
assert!(linked.iter().all(|l| l.parent == Some(target) && l.track_matte.map(|m| m.layer) == Some(target)));
assert_eq!(r.report.imported.track_mattes, n as usize);
assert_eq!(r.report.count(LossCategory::ParentLinks), 0, "{:?}", r.report.losses);
}
/// `count` nested groups (`tdmn` + `LIST tdgp`), the innermost empty.
fn nested(count: usize) -> Vec<Chunk<'static>> {
let end = || {
let mut name = b"ADBE Group End".to_vec();
name.resize(40, 0);
Chunk::data(*b"tdmn", name)
};
let mut inner = vec![end()];
for _ in 0..count {
let mut name = b"ADBE Deep Group".to_vec();
name.resize(40, 0);
inner = vec![Chunk::data(*b"tdmn", name), Chunk::list(*b"tdgp", inner), end()];
}
inner
}
#[test]
fn blending_options_nested_past_the_read_depth_are_reported() {
let mut file = parse(SYNTHETIC).unwrap();
let mut patched = 0;
// Every layer's Advanced Blending group gets groups nested twelve deep (no property in them).
fn visit(chunks: &mut [Chunk<'_>], patched: &mut usize) {
let mut next_is_adv = false;
for c in chunks.iter_mut() {
if next_is_adv && c.is_list(b"tdgp") {
*children(c) = nested(12);
*patched += 1;
}
next_is_adv = c.is(b"tdmn") && c.bytes().is_some_and(|b| b.starts_with(b"ADBE Adv Blend Group\0"));
visit(c.children_mut(), patched);
}
}
visit(&mut file.chunks, &mut patched);
assert!(patched >= 2, "{patched}");
let (_, r) = run(&write(&file).unwrap());
let found = losses(&r, LossCategory::LayerStyles);
assert!(found.iter().any(|d| d.contains("deeper than 8 levels")), "{found:?}");
// Nested within the depth, an empty group still holds nothing.
let mut file = parse(SYNTHETIC).unwrap();
fn shallow(chunks: &mut [Chunk<'_>]) {
let mut next_is_adv = false;
for c in chunks.iter_mut() {
if next_is_adv && c.is_list(b"tdgp") {
*children(c) = nested(3);
}
next_is_adv = c.is(b"tdmn") && c.bytes().is_some_and(|b| b.starts_with(b"ADBE Adv Blend Group\0"));
shallow(c.children_mut());
}
}
shallow(&mut file.chunks);
let (_, r) = run(&write(&file).unwrap());
assert_eq!(losses(&r, LossCategory::LayerStyles), Vec::<String>::new());
}
/// Every key record of the property `match_name` (the `LIST list` of its `LIST tdbs`; a mask
/// shape's vertex lists are not touched) gets `patch`.
fn patch_keys(file: &mut AepFile<'_>, match_name: &[u8], patch: &dyn Fn(usize, &mut [u8])) -> usize {
fn lists(c: &mut Chunk<'_>, patch: &dyn Fn(usize, &mut [u8]), n: &mut usize) {
if c.is_list(b"tdbs") {
for k in c.children_mut() {
keys(k, patch, n);
}
return;
}
for k in c.children_mut() {
lists(k, patch, n);
}
}
fn keys(c: &mut Chunk<'_>, patch: &dyn Fn(usize, &mut [u8]), n: &mut usize) {
if c.is_list(b"list") {
let size = c.child(b"lhd3").and_then(|h| h.bytes()).map(|h| u32::from_be_bytes(h[16..20].try_into().unwrap()) as usize).unwrap_or(0);
if let Some(Body::Data(d)) = children(c).iter_mut().find(|k| k.is(b"ldat")).map(|k| &mut k.body)
&& size > 0
{
for (i, rec) in d.to_mut().chunks_exact_mut(size).enumerate() {
patch(i, rec);
*n += 1;
}
}
}
}
fn visit(chunks: &mut [Chunk<'_>], name: &[u8], patch: &dyn Fn(usize, &mut [u8]), n: &mut usize) {
let mut next = false;
for c in chunks.iter_mut() {
if next {
lists(c, patch, n);
}
next = c.is(b"tdmn") && c.bytes().is_some_and(|b| b.strip_prefix(name).is_some_and(|r| r.first() == Some(&0)));
visit(c.children_mut(), name, patch, n);
}
}
let mut n = 0;
visit(&mut file.chunks, match_name, patch, &mut n);
n
}
#[test]
fn orientation_keys_at_the_same_time_are_reported() {
let Some(bytes) = crate::common::try_fixture("703-key-orientation-0-to-10-20-30-linear.aep") else { return };
let mut file = parse(&bytes).unwrap();
// The second key at the first key's time (the record starts with its time).
let first = std::cell::Cell::new([0u8; 4]);
let n = patch_keys(&mut file, b"ADBE Orientation", &|i, rec| {
if i == 0 {
first.set(rec[0..4].try_into().unwrap());
} else {
rec[0..4].copy_from_slice(&first.get());
}
});
assert!(n >= 2, "{n}");
let (p, r) = run(&write(&file).unwrap());
let found = losses(&r, LossCategory::DamagedData);
assert!(found.iter().any(|d| d.contains("ADBE Orientation: keyframes at the same time")), "{found:?}");
let l = comp_named(&p, "C").layers.iter().find(|l| l.name == "L").expect("L");
assert_eq!(l.props.prop("transform/orientation").expect("orientation").keys.len(), 1);
}
#[test]
fn a_mask_path_ease_speed_beyond_the_limit_is_not_imported() {
let Some(bytes) = crate::common::try_fixture("700-key-mask-path-ease-out20-in50.aep") else { return };
let mut file = parse(&bytes).unwrap();
// Both speeds (bytes 24 and 40 of a mask path record) far past what a property key accepts.
let n = patch_keys(&mut file, b"ADBE Mask Shape", &|_, rec| {
rec[24..32].copy_from_slice(&1e12f64.to_be_bytes());
rec[40..48].copy_from_slice(&1e12f64.to_be_bytes());
});
assert!(n >= 2, "{n}");
let (p, r) = run(&write(&file).unwrap());
let found = losses(&r, LossCategory::ApproximatedKeyframes);
assert!(found.iter().any(|d| d.contains("its ease is unreadable")), "{found:?}");
let speeds: Vec<f64> = p
.items
.values()
.filter_map(|i| if let ItemKind::Comp(c) = &i.kind { Some(c.layers.iter().cloned().collect::<Vec<_>>()) } else { None })
.flatten()
.flat_map(|l| l.props.sub("masks").map(|m| m.groups().filter_map(|g| g.prop("path").cloned()).collect::<Vec<_>>()).unwrap_or_default())
.flat_map(|p| p.keys)
.flat_map(|k| k.in_ease.into_iter().chain(k.out_ease).map(|e| e.speed))
.collect();
assert!(speeds.iter().all(|s| s.abs() <= 1e11), "{speeds:?}");
}
+2 -1
View File
@@ -244,7 +244,8 @@ pub fn preroll(id: &str, params: &Params) -> f64 {
}
/// Run audio effect `id` over interleaved stereo `buf` (L R L R …) at `rate` Hz, from a cleared
/// state. `start` is the layer time (seconds) of the first sample (oscillator phase).
/// state. `start` is the time (seconds) of the first sample since the layer's start, counted at
/// comp speed whatever the layer's time stretch (oscillator phase).
pub fn process(id: &str, params: &Params, buf: &mut [f32], rate: u32, start: f64) {
if rate == 0 || buf.len() < 2 {
return;
+64 -7
View File
@@ -53,7 +53,8 @@ fn gradient_ramp(ctx: &EffectCtx, mut b: Buf) -> Buf {
}
/// Blending Mode options of the shape generators (Checkerboard, Grid, Circle): "None" shows the
/// generated pattern only; the others composite it onto the layer like layer blending modes.
/// generated pattern only, inside the layer's alpha (see [`gen_alpha`]); the others composite it
/// onto the layer like layer blending modes.
pub(crate) const GEN_BLEND_MODES: [&str; 20] = [
"None",
"Normal",
@@ -103,7 +104,8 @@ pub fn gen_mode(i: u32) -> Option<BlendMode> {
}
/// Composite a generated premultiplied pixel `g` onto the original `o` with blending mode
/// index `mode` (into [`GEN_BLEND_MODES`]).
/// index `mode` (into [`GEN_BLEND_MODES`]). None returns `g` as is: the caller keeps the layer's
/// alpha in `g` with [`gen_alpha`].
#[inline]
pub(crate) fn gen_blend(o: Px, g: Px, mode: u32) -> Px {
match gen_mode(mode) {
@@ -112,6 +114,16 @@ pub(crate) fn gen_blend(o: Px, g: Px, mode: u32) -> Px {
}
}
/// The generated alpha `a` with Blending Mode None (`keep_alpha`, `gen_mode(mode).is_none()`):
/// scaled by the layer's alpha `layer_a`, so the pattern stays inside the layer's shape and its
/// masks, which are applied before effects (#1381, #3121). The other modes composite onto the
/// layer as After Effects' blending modes do and keep `a`; their alpha outside the layer is not
/// verified against After Effects. Mirrored by `gen_alpha` in `fx_generate.wgsl`.
#[inline]
pub(crate) fn gen_alpha(a: f32, layer_a: f32, keep_alpha: bool) -> f32 {
if keep_alpha { a * layer_a } else { a }
}
/// 4-Color Gradient's weights are inverse squared distances softened by Blend²: each point
/// weighs 1 / (d² + Blend²) (pixels). Fitted to After Effects 2026 renders at Blend 10, 50, 100
/// and 300 (power 2.00 at every Blend, softening 0 / 2367 / 9817 / 90127 ≈ Blend²; mean error
@@ -134,6 +146,7 @@ fn four_color(ctx: &EffectCtx, mut b: Buf) -> Buf {
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 keep_alpha = gen_mode(mode).is_none();
let seed = ctx.seed;
b.img.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
@@ -155,7 +168,7 @@ fn four_color(ctx: &EffectCtx, mut b: Buf) -> Buf {
}
// None keeps the layer's alpha (#1381), as the Gradient Ramp does: the gradient fills
// a shape or text, not its bounding box.
let a = if gen_mode(mode).is_none() { op * px[3] } else { op };
let a = gen_alpha(op, px[3], keep_alpha);
*px = gen_blend(*px, [c[0] * a, c[1] * a, c[2] * a, a], mode);
}
});
@@ -185,6 +198,7 @@ fn checkerboard(ctx: &EffectCtx, mut b: Buf) -> Buf {
let c = ctx.params.color("color");
let op = ctx.params.f("opacity") as f32 / 100.0;
let mode = ctx.params.e("blendingMode");
let keep_alpha = gen_mode(mode).is_none();
// Signed distance (in feather units) to the nearest cell edge, positive in even cells.
let axis = |p: f64, size: f64, f: f64| -> f64 {
let u = p / size;
@@ -197,8 +211,8 @@ fn checkerboard(ctx: &EffectCtx, mut b: Buf) -> Buf {
for (x, px) in row.iter_mut().enumerate() {
let sx = axis(x as f64 + 0.5 - anchor.0, w, fw);
let sy = axis(y as f64 + 0.5 - anchor.1, h, fh);
let cov = ((0.5 + 0.5 * sx * sy) as f32).clamp(0.0, 1.0) * op;
*px = gen_blend(*px, [c[0] * cov, c[1] * cov, c[2] * cov, cov], mode);
let a = gen_alpha(((0.5 + 0.5 * sx * sy) as f32).clamp(0.0, 1.0) * op, px[3], keep_alpha);
*px = gen_blend(*px, [c[0] * a, c[1] * a, c[2] * a, a], mode);
}
});
b
@@ -214,6 +228,7 @@ fn grid(ctx: &EffectCtx, mut b: Buf) -> Buf {
let c = ctx.params.color("color");
let op = ctx.params.f("opacity") as f32 / 100.0;
let mode = ctx.params.e("blendingMode");
let keep_alpha = gen_mode(mode).is_none();
b.img.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let gx = (x as f64 + 0.5 - anchor.0).rem_euclid(w);
@@ -225,7 +240,7 @@ fn grid(ctx: &EffectCtx, mut b: Buf) -> Buf {
if invert {
cov = 1.0 - cov;
}
let a = cov * op;
let a = gen_alpha(cov * op, px[3], keep_alpha);
*px = gen_blend(*px, [c[0] * a, c[1] * a, c[2] * a, a], mode);
}
});
@@ -262,6 +277,7 @@ fn circle(ctx: &EffectCtx, mut b: Buf) -> Buf {
let op = ctx.params.f("opacity") as f32 / 100.0;
let invert = ctx.params.b("invert");
let mode = ctx.params.e("blendingMode");
let keep_alpha = gen_mode(mode).is_none();
b.img.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let d = ((x as f64 + 0.5 - c.0).powi(2) + (y as f64 + 0.5 - c.1).powi(2)).sqrt();
@@ -272,7 +288,7 @@ fn circle(ctx: &EffectCtx, mut b: Buf) -> Buf {
if invert {
cov = 1.0 - cov;
}
let a = cov * op;
let a = gen_alpha(cov * op, px[3], keep_alpha);
*px = gen_blend(*px, [color[0] * a, color[1] * a, color[2] * a, a], mode);
}
});
@@ -594,6 +610,47 @@ mod generator_tests {
assert!(o.img.get(0, 5)[0] > 0.9 && o.img.get(5, 5)[3] < 0.01);
}
/// With Blending Mode None, a shape generator's pattern shows only where the layer has alpha
/// (#1381, #3121: masks come before effects). `set` makes the pattern cover (5, 5) and (35, 5).
fn assert_none_stays_inside_the_layer_alpha(id: &str, set: &[(&'static str, Value)]) {
// Three bands: transparent, half and fully opaque, premultiplied.
let mut img = Image::filled(40, 24, [1.0, 0.0, 0.0, 1.0]);
for (i, p) in img.data.iter_mut().enumerate() {
let a = [0.0, 0.5, 1.0][i % 40 / 14];
*p = p.map(|c| c * a);
}
for op in [100.0, 50.0] {
let mut set = set.to_vec();
set.push(("opacity", num(op)));
let o = run_fx(id, &set, img.clone(), 0.0, EffectEnv::default());
let k = op as f32 / 100.0;
for (src, out) in img.data.iter().zip(&o.img.data) {
assert!(out[3] <= src[3] * k + 1e-6, "{id} opacity {op}: alpha {} became {}", src[3], out[3]);
assert!(out[..3].iter().all(|&c| c <= out[3] + 1e-6), "{id} opacity {op}: premultiplied colour above alpha");
}
assert!(o.img.get(5, 5)[3] < 1e-6, "{id} opacity {op}: the pattern shows where the layer is transparent");
assert!(o.img.get(35, 5)[3] > 0.9 * k, "{id} opacity {op}: the pattern shows on the opaque layer: {:?}", o.img.get(35, 5));
}
}
#[test]
fn grid_none_stays_inside_the_layer_alpha() {
// Inverted, the grid covers nearly every pixel, wherever the lines fall.
assert_none_stays_inside_the_layer_alpha("ec.generate.grid", &[("width", num(10.0)), ("border", num(2.0)), ("invertGrid", Value::Bool(true))]);
}
#[test]
fn checkerboard_none_stays_inside_the_layer_alpha() {
// 8-pixel squares from the anchor at 0: (5, 5) and (35, 5) lie in on squares.
assert_none_stays_inside_the_layer_alpha("ec.generate.checkerboard", &[("width", num(8.0))]);
}
#[test]
fn circle_none_stays_inside_the_layer_alpha() {
// A disk larger than the image covers every pixel.
assert_none_stays_inside_the_layer_alpha("ec.generate.circle", &[("center", Value::Vec2([20.0, 12.0])), ("radius", num(100.0))]);
}
#[test]
fn circle_edge_makes_a_ring() {
let c = ("center", Value::Vec2([16.0, 16.0]));
+1 -1
View File
@@ -131,7 +131,7 @@ 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, lut_file, lut_files, lut_params};
pub use utility::{Lut, cineon_gamma, cineon_gamma_scale, 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.
+29
View File
@@ -165,6 +165,9 @@ pub fn legacy_default(effect: &str, param: &str) -> Option<Value> {
("ec.transition.linearwipe", "legacyFeather") => Value::Bool(true),
// 3D Channel: Cryptomatte's Matte Only put the matte in alpha too (#3127).
("ec.3d.cryptomatte", crate::channel3d::MATTE_ONLY_IN_ALPHA) => Value::Bool(true),
// Utility: Cineon Converter version 1, where Gamma 1.7 gave linear output
// (`crate::utility::cineon_gamma`).
("ec.utility.cineon", "version") => Value::Scalar(1.0),
_ => return None,
})
}
@@ -819,4 +822,30 @@ not a stroke",
to_effect_space(spec, &mut twirl, SIZE, [0.0; 2], &|_| [0.0; 2]);
assert_eq!(twirl, before);
}
#[test]
fn cineon_converter_saved_before_its_version_upgrades_to_version_1() {
let spec = find("ec.utility.cineon").unwrap();
let mut next = 1;
let fresh = instantiate(spec, &mut Ids(&mut next), "Cineon Converter", [100.0, 50.0]);
assert_eq!(fresh.get("version").unwrap().value, Value::Scalar(2.0));
assert_eq!(fresh.get("gamma").unwrap().value, Value::Scalar(1.7));
// Gamma, its keyframes and its expression are kept as saved.
let mut g = fresh.clone();
take_prop(&mut g, "version");
let gamma = g.get_mut("gamma").unwrap();
gamma.value = Value::Scalar(2.2);
gamma.keys = vec![effectcraft_keyframe::Keyframe::new(Default::default(), Value::Scalar(3.4))];
gamma.expr = Some(effectcraft_project::Expression { text: "value * 2".into(), enabled: true });
let saved = gamma.clone();
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), [100.0, 50.0]));
assert_eq!(g.get("version").unwrap().value, Value::Scalar(1.0));
assert_eq!(g.get("gamma"), Some(&saved));
// Saved without Gamma too: it takes version 1's default, which gave linear output.
let mut g = fresh.clone();
take_prop(&mut g, "version");
take_prop(&mut g, "gamma");
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), [100.0, 50.0]));
assert_eq!(g.get("gamma").unwrap().value, Value::Scalar(1.7));
}
}
+21 -8
View File
@@ -360,18 +360,30 @@ pub(super) fn profile_converter(ctx: &EffectCtx, mut b: Buf) -> Buf {
// ---- Color Stabilizer
/// Mean straight colour of a square (half-size `r` layer pixels) around layer point `pt`.
fn sample_mean(b: &Buf, pt: [f64; 2], r: f64) -> [f64; 3] {
let (cx, cy) = b.to_px(pt);
let rr = (r * b.scale).max(0.5);
let (x0, x1) = ((cx - rr).floor().max(0.0) as i64, ((cx + rr).ceil() as i64).min(b.img.width as i64));
let (y0, y1) = ((cy - rr).floor().max(0.0) as i64, ((cy + rr).ceil() as i64).min(b.img.height as i64));
/// Mean straight colour of Color Stabilizer's sampled area for layer point `pt`, as After Effects
/// 2026 samples it (#3125): a square `size` layer pixels wide (Sample Size is the full width)
/// centred on the middle of the pixel the point names, i.e. half a pixel right of and below the
/// layer point (After Effects' point (x, y) is the centre of pixel (x, y)). Each pixel counts
/// with the share of it the square covers, so the mean changes smoothly with a sub-pixel point
/// or a fractional size. At least one buffer pixel wide.
fn sample_mean(b: &Buf, pt: [f64; 2], size: f64) -> [f64; 3] {
let (cx, cy) = b.to_px([pt[0] + 0.5, pt[1] + 0.5]);
let h = (size * 0.5 * b.scale).max(0.5);
// The share of pixel `i` (covering [i, i + 1]) inside [c − h, c + h].
let cover = |i: i64, c: f64| ((i as f64 + 1.0).min(c + h) - (i as f64).max(c - h)).max(0.0);
let (x0, x1) = ((cx - h).floor().max(0.0) as i64, ((cx + h).ceil() as i64).min(b.img.width as i64));
let (y0, y1) = ((cy - h).floor().max(0.0) as i64, ((cy + h).ceil() as i64).min(b.img.height as i64));
let mut acc = [0.0f64; 4];
for y in y0..y1 {
let wy = cover(y, cy);
for x in x0..x1 {
let w = wy * cover(x, cx);
if w <= 0.0 {
continue;
}
let p = b.img.get(x, y);
for k in 0..4 {
acc[k] += p[k] as f64;
acc[k] += w * p[k] as f64;
}
}
}
@@ -410,7 +422,8 @@ fn stabilizer_samples(ctx: &EffectCtx, b: &Buf) -> Option<([[f64; 3]; 3], [[f64;
let host = ctx.env.host?;
let t_ref = ctx.params.f("referenceFrame");
let reference = host.self_at(t_ref, ctx.env.effect_index)?;
let r = ctx.params.f("sampleSize").max(0.5);
// Sample Size is the full width of the sampled square in layer pixels (#3125).
let r = ctx.params.f("sampleSize").max(1.0);
let pts = STABILIZER_POINTS.map(|id| ctx.params.v2(id));
let ref_params = host.params_at(t_ref);
let ref_pts = match &ref_params {
+97
View File
@@ -397,6 +397,103 @@ fn color_stabilizer_samples_the_reference_at_the_points_reference_positions() {
}
}
/// After Effects 2026's Sample Size samples (#3125): a horizontal ramp, Stabilize Levels, and a
/// 6 px white square centred at `square` that appears after the reference frame (the card at
/// `square: None` is the reference).
fn sample_size_card(w: u32, h: u32, square: Option<[f64; 2]>) -> Image {
let mut img = Image::new(w, h);
for y in 0..h {
for x in 0..w {
let (cx, cy) = (x as f64 + 0.5, y as f64 + 0.5);
let mut v = (cx / w as f64) as f32;
if square.is_some_and(|s| (cx - s[0]).abs() < 3.0 && (cy - s[1]).abs() < 3.0) {
v = 1.0;
}
img.set(x, y, [v, v, v, 1.0]);
}
}
img
}
/// Whether Color Stabilizer (Levels, Black Point at `bp`, Sample Size `size`) changes the
/// `w` × `h` card when the square at `square` appears: the change is read on the right half of
/// the layer, far from the square.
fn stabilizer_reacts(w: u32, h: u32, square: [f64; 2], bp: [f64; 2], size: f64) -> bool {
let host = RefHost(sample_size_card(w, h, None));
let env = EffectEnv { host: Some(&host), ..Default::default() };
let vals = [
("stabilize", Value::Enum(1)),
("blackPoint", Value::Vec2(bp)),
("whitePoint", Value::Vec2([w as f64 * 0.85, h as f64 * 0.5])),
("sampleSize", num(size)),
];
let input = sample_size_card(w, h, Some(square));
let out = run_fx("ec.color.colorstabilizer", &vals, input.clone(), 0.0, env);
let (x, y) = (w as i64 * 7 / 8, h as i64 / 4);
(out.img.get(x, y)[0] - input.get(x, y)[0]).abs() > 1e-5
}
/// #3125: Sample Size is the full width of the sampled square in layer pixels, at any layer
/// size. After Effects 2026 (320 × 180 and 640 × 360, Black Point at 25 % width, mid-height)
/// reacts to a square whose near edge is 7 px to the right of the point from Sample Size 13.5
/// (not at 13), to one 17 px away by 35, and never to one 37 px away up to 50. EffectCraft used
/// Sample Size as the half-width and reacted at 12 and 30.
#[test]
fn color_stabilizer_sample_size_is_the_full_width_in_pixels() {
for (w, h) in [(320u32, 180u32), (640, 360)] {
let (bx, by) = (w as f64 * 0.25, h as f64 * 0.5);
let r = |dx: f64, size: f64| stabilizer_reacts(w, h, [bx + dx, by], [bx, by], size);
assert!(r(10.0, 13.5), "{w}x{h}: d 10 at 13.5");
assert!(!r(10.0, 13.0), "{w}x{h}: d 10 at 13");
assert!(!r(10.0, 12.0), "{w}x{h}: d 10 at 12");
assert!(r(20.0, 35.0), "{w}x{h}: d 20 at 35");
assert!(!r(20.0, 33.0), "{w}x{h}: d 20 at 33");
assert!(!r(20.0, 30.0), "{w}x{h}: d 20 at 30");
for size in [1.0, 5.0, 12.0, 25.0, 40.0, 50.0] {
assert!(!r(40.0, size), "{w}x{h}: d 40 at {size}");
}
}
}
/// #3125: the sampled area is a square centred on the middle of the pixel the point names, half a
/// pixel right of and below EffectCraft's layer point. After Effects 2026 with the Black Point at
/// (80, 90) on a 320 × 180 card: a square 7 px to the right or below reacts from 13.5 (not at
/// 13), one 7 px to the left or above only from 15.5 (not at 15). Diagonally, with the square's
/// near corner 7, 10 and 14 px away on both axes, it reacts at 16, 26 and 38 and not at 13, 19
/// and 27: a square area (a circle of that width would first react at 18.4, 26.9 and 38.2).
#[test]
fn color_stabilizer_samples_a_square_centred_on_the_pixel() {
let r = |square: [f64; 2], size: f64| stabilizer_reacts(320, 180, square, [80.0, 90.0], size);
for (square, no, yes) in [
([90.0, 90.0], 13.0, 13.5),
([80.0, 100.0], 13.0, 13.5),
([70.0, 90.0], 15.0, 15.5),
([80.0, 80.0], 15.0, 15.5),
([90.0, 100.0], 13.0, 16.0),
([93.0, 103.0], 19.0, 26.0),
([97.0, 107.0], 27.0, 38.0),
] {
assert!(!r(square, no), "{square:?} at {no}");
assert!(r(square, yes), "{square:?} at {yes}");
}
}
/// #3125: sub-pixel Black Points. After Effects 2026, square near edge at x 87 (or y 97): with
/// the point at x (or y) + 0.25 it reacts from 13 (not 12.5), + 0.5 from 12.5 (not 12), + 0.75
/// already at 12; each pixel counts with the share of it the area covers.
#[test]
fn color_stabilizer_sub_pixel_points_cover_partial_pixels() {
for (f, no, yes) in [(0.25, Some(12.5), 13.0), (0.5, Some(12.0), 12.5), (0.75, None, 12.0)] {
for (square, bp) in [([90.0, 90.0], [80.0 + f, 90.0]), ([80.0, 100.0], [80.0, 90.0 + f])] {
let r = |size: f64| stabilizer_reacts(320, 180, square, bp, size);
if let Some(no) = no {
assert!(!r(no), "{bp:?} at {no}");
}
assert!(r(yes), "{bp:?} at {yes}");
}
}
}
/// 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 {
+208 -49
View File
@@ -10,7 +10,7 @@ use effectcraft_project::ParamUi;
use rayon::prelude::*;
use crate::util::{premul, unpremul};
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
use crate::{Buf, EffectCtx, EffectSpec, Params, col, num, p, popup, slider};
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
EffectSpec { id, name, category: "Utility", params, render, gpu: false, float: true }
@@ -102,8 +102,10 @@ pub(crate) struct Cineon {
pub white: f32,
pub ib: f32,
pub iw: f32,
/// Version 2: [`cineon_gamma`]. Version 1: the saved Gamma, where 1.7 gives linear output.
pub gamma: f32,
pub rolloff: f32,
pub version_2: bool,
}
impl Cineon {
@@ -113,14 +115,25 @@ impl Cineon {
fn knee(&self) -> f32 {
1.0 - (self.rolloff / 100.0).clamp(0.0, 0.99)
}
/// Normalized code value (code / 1023) → linear, raised to `1.7 / gamma`
/// ([`effectcraft_project::cineon_log_to_lin`], which Interpret Footage ▸ Cineon Settings
/// also uses with `1 / gamma`).
/// Normalized code value (code / 1023) to linear output.
pub fn log_to_lin(&self, v: f32) -> f32 {
let lin = effectcraft_project::cineon_log_to_lin(v, self.black, self.white, 1.7, self.gamma, self.rolloff);
let lin = if self.version_2 {
let offset = self.offset().powf(1.0 / self.gamma.max(0.001));
let exposure = 10f32.powf((v * 1023.0 - self.white) * 0.002 / 0.6).powf(1.0 / self.gamma.max(0.001));
let mut lin = ((exposure - offset) / (1.0 - offset).max(1e-6)).max(0.0);
let k = self.knee();
if k < 1.0 && lin > k {
let w = 1.0 - k;
lin = k + w * (1.0 - (-(lin - k) / w).exp());
}
lin
} else {
// Version 1 keeps its earlier arithmetic, so saved instances render the same bits.
effectcraft_project::cineon_log_to_lin(v, self.black, self.white, 1.7, self.gamma, self.rolloff)
};
self.ib + (self.iw - self.ib) * lin
}
/// Linear → normalised code value.
/// Linear to normalized code value.
pub fn lin_to_log(&self, v: f32) -> f32 {
let off = self.offset();
let d = self.iw - self.ib;
@@ -130,27 +143,61 @@ impl Cineon {
let w = 1.0 - k;
lin = k - w * (1.0 - (lin - k) / w).max(1e-6).ln();
}
lin = lin.max(0.0).powf(self.gamma.max(0.01) / 1.7);
let code = self.white + (lin * (1.0 - off) + off).max(1e-9).log10() * 0.6 / 0.002;
let exposure = if self.version_2 {
let root_offset = off.powf(1.0 / self.gamma.max(0.001));
(lin.max(0.0) * (1.0 - root_offset) + root_offset).max(0.0).powf(self.gamma.max(0.001))
} else {
lin.max(0.0).powf(self.gamma.max(0.01) / 1.7) * (1.0 - off) + off
};
let code = self.white + exposure.max(1e-9).log10() * 0.6 / 0.002;
code / 1023.0
}
}
/// The Gamma that gives linear output in Cineon Converter version 1.
pub const CINEON_V1_LINEAR_GAMMA: f64 = 1.7;
/// The Gamma scale used by Cineon Converter version `version`: `1 / 1.7` for version 1, 1 for
/// version 2. Preset conversion aligns the linear points but not other Gamma values. Version 1
/// instances (saved before the hidden Version parameter existed; see
/// [`crate::migrate::legacy_default`]) raised the linear value to `1.7 / gamma`.
pub fn cineon_gamma_scale(version: f64) -> f64 {
if version < 2.0 { 1.0 / CINEON_V1_LINEAR_GAMMA } else { 1.0 }
}
/// Cineon Converter's Gamma on the version 2 scale ([`cineon_gamma_scale`]), limited to `0.01 /
/// 1.7` or more: version 1 limited its saved Gamma to 0.01.
pub fn cineon_gamma(params: &Params) -> f64 {
(params.f("gamma") * cineon_gamma_scale(params.f("version"))).max(0.01 * cineon_gamma_scale(1.0))
}
fn cineon(ctx: &EffectCtx, mut b: Buf) -> Buf {
let version_2 = ctx.params.f("version") >= 2.0;
let c = Cineon {
black: ctx.params.f("tenBitBlackPoint") as f32,
white: ctx.params.f("tenBitWhitePoint") as f32,
ib: ctx.params.f("internalBlackPoint") as f32,
iw: ctx.params.f("internalWhitePoint") as f32,
gamma: ctx.params.f("gamma") as f32,
gamma: if version_2 { cineon_gamma(ctx.params) } else { ctx.params.f("gamma") } as f32,
rolloff: ctx.params.f("highlightRolloff") as f32,
version_2,
};
let std = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma: 1.7, rolloff: c.rolloff };
let std = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma: 1.7, rolloff: c.rolloff, version_2: false };
let kind = ctx.params.e("conversionType");
b.img.map_straight(|v| {
v.map(|x| match kind {
0 => c.lin_to_log(x),
1 => c.log_to_lin(x),
_ if c.version_2 => {
// Custom points use the Gamma 1 code conversion before the code-value power.
let code = if (c.black, c.white, c.ib, c.iw) == (95.0, 685.0, 0.0, 1.0) {
x
} else {
let unit = Cineon { gamma: 1.0, ..c };
std.lin_to_log(unit.log_to_lin(x))
};
code.max(0.0).powf(1.0 / c.gamma.max(0.001))
}
_ => std.lin_to_log(c.log_to_lin(x)),
})
});
@@ -432,8 +479,10 @@ pub fn specs() -> Vec<EffectSpec> {
p("internalBlackPoint", "Internal Black Point", num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3)),
p("tenBitWhitePoint", "10 Bit White Point", num(685.0), slider(0.0, 1023.0, 0.0, 1023.0, 0)),
p("internalWhitePoint", "Internal White Point", num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3)),
p("gamma", "Gamma", num(1.7), slider(0.1, 5.0, 0.1, 5.0, 2)),
p("gamma", "Gamma", num(1.7), slider(0.05, 5.0, 0.1, 5.0, 2)),
p("highlightRolloff", "Highlight Rolloff", num(20.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
// 2: Gamma 1 gives linear output (`cineon_gamma`).
p("version", "Version", num(2.0), ParamUi::Hidden),
],
cineon,
),
@@ -646,29 +695,133 @@ mod tests {
#[test]
fn cineon_round_trip() {
let c = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma: 1.7, rolloff: 20.0 };
for code in [100.0f32, 200.0, 350.0, 500.0, 600.0] {
let v = code / 1023.0;
let back = c.lin_to_log(c.log_to_lin(v));
assert!((back - v).abs() < 1e-3, "{code}: {back}");
for gamma in [1.0, 1.7, 0.6] {
let c = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma, rolloff: 20.0, version_2: true };
for code in [100.0f32, 200.0, 350.0, 500.0, 600.0] {
let v = code / 1023.0;
let back = c.lin_to_log(c.log_to_lin(v));
assert!((back - v).abs() < 1e-3, "gamma {gamma}, {code}: {back}");
}
assert!(c.log_to_lin(95.0 / 1023.0).abs() < 1e-4);
}
let custom = Cineon { black: 120.0, white: 700.0, ib: 0.1, iw: 0.9, gamma: 2.2, rolloff: 35.0, version_2: true };
for code in [120.0f32, 250.0, 400.0, 560.0, 700.0] {
let value = code / 1023.0;
let back = custom.lin_to_log(custom.log_to_lin(value));
assert!((back - value).abs() < 1e-5, "code {code}: {back}");
}
assert!(c.log_to_lin(95.0 / 1023.0).abs() < 1e-4);
}
/// Interpret Footage ▸ Cineon Settings and the Cineon Converter's Log to Linear give the same
/// values for the same points and Highlight Rolloff when the converter's Gamma is 1.7 times
/// Cineon Settings' Gamma: the converter's default 1.7 and Cineon Settings' Gamma 1 both give
/// linear light (code 400 is 0.10251).
/// Gamma 1 gives linear light: Kodak's printing-density curve with nothing
/// raised, so code 400 is (10^(-0.95) - 10^(-1.9667)) / (1 - 10^(-1.9667)) = 0.10251. A larger
/// Gamma lightens the midtones, and Linear to Log undoes it.
#[test]
fn cineon_gamma_1_is_linear_and_larger_lightens() {
let c = |gamma| Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma, rolloff: 0.0, version_2: true };
let lin = c(1.0).log_to_lin(400.0 / 1023.0);
assert!((lin - 0.10251).abs() < 1e-4, "{lin}");
let lighter = c(2.0).log_to_lin(400.0 / 1023.0);
let offset = c(2.0).offset().sqrt();
let exposure = 10f32.powf((400.0 - 685.0) * 0.002 / 0.6).sqrt();
assert!((lighter - (exposure - offset) / (1.0 - offset)).abs() < 1e-4, "{lighter}");
assert!((c(2.0).lin_to_log(lighter) - 400.0 / 1023.0).abs() < 1e-4);
let out = run("ec.utility.cineon", &[("gamma", num(1.0))], {
let mut img = Image::new(1, 1);
img.set(0, 0, [400.0 / 1023.0, 400.0 / 1023.0, 400.0 / 1023.0, 1.0]);
img
});
assert!((out.img.data[0][0] - 0.10251).abs() < 1e-4, "Gamma 1 is linear: {:?}", out.img.data[0]);
}
#[test]
fn cineon_log_to_log_gamma_1_keeps_code_values() {
let codes = [95.0f32, 250.0, 400.0, 560.0, 685.0, 800.0];
let mut img = Image::new(codes.len() as u32, 1);
for (x, code) in codes.iter().enumerate() {
let value = code / 1023.0;
img.set(x as u32, 0, [value, value, value, 1.0]);
}
for rolloff in [0.0, 20.0] {
let out = run("ec.utility.cineon", &[("conversionType", Value::Enum(2)), ("gamma", num(1.0)), ("highlightRolloff", num(rolloff))], img.clone());
for (x, code) in codes.iter().enumerate() {
assert!((out.img.data[x][0] - code / 1023.0).abs() < 1e-6, "code {code}: {}", out.img.data[x][0]);
}
}
}
#[test]
fn cineon_version_2_log_to_linear_matches_observed_codes() {
for (gamma, codes, expected) in [
(1.7, &[95.0, 180.0, 250.0, 320.0, 400.0, 480.0, 560.0, 620.0, 685.0][..], &[0, 9, 19, 34, 57, 89, 136, 185, 255][..]),
(2.2, &[180.0, 250.0, 320.0, 400.0, 480.0, 560.0, 620.0][..], &[13, 27, 44, 71, 106, 152, 196][..]),
] {
let c = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma, rolloff: 0.0, version_2: true };
for (&code, &want) in codes.iter().zip(expected) {
let got = (c.log_to_lin(code / 1023.0).clamp(0.0, 1.0) * 255.0).round() as i32;
assert!((got - want).abs() <= 1, "Gamma {gamma}, code {code}: {got} vs {want}");
}
}
}
#[test]
fn cineon_version_2_log_to_log_matches_observed_codes() {
let codes = [95.0f32, 180.0, 250.0, 320.0, 400.0, 480.0, 560.0, 620.0, 685.0, 800.0];
let expected = [63, 92, 111, 129, 146, 164, 179, 190, 202, 221];
let mut img = Image::new(codes.len() as u32, 1);
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
img.set(x as u32, 0, [v, v, v, 1.0]);
}
let out = run("ec.utility.cineon", &[("conversionType", Value::Enum(2)), ("gamma", num(1.7))], img);
for (x, (&code, &want)) in codes.iter().zip(&expected).enumerate() {
let got = (out.img.data[x][0].clamp(0.0, 1.0) * 255.0).round() as i32;
assert!((got - want).abs() <= 2, "code {code}: {got} vs {want}");
}
}
/// A version 1 instance renders as version 1 did: Gamma 1.7 gives linear light, and a
/// version 1 Gamma of 3.4 has the old post-normalization power.
#[test]
fn cineon_version_1_gamma_17_is_linear() {
let px = |vals: &[(&str, Value)]| {
let mut img = Image::new(1, 1);
img.set(0, 0, [400.0 / 1023.0, 400.0 / 1023.0, 400.0 / 1023.0, 1.0]);
run("ec.utility.cineon", vals, img).img.data[0][0]
};
let v1 = |gamma: f64| px(&[("version", num(1.0)), ("gamma", num(gamma)), ("highlightRolloff", num(0.0))]);
assert!((v1(1.7) - 0.10251).abs() < 1e-4, "{}", v1(1.7));
let v2 = px(&[("gamma", num(2.0)), ("highlightRolloff", num(0.0))]);
assert!((v1(3.4) - v2).abs() > 1e-3, "{} vs {v2}", v1(3.4));
// Version 1 limited the saved Gamma to 0.01: Gamma 0 raised the linear value to 170.
let code = 684.0 / 1023.0;
let base = Cineon { black: 95.0, white: 685.0, ib: 0.0, iw: 1.0, gamma: 1.7, rolloff: 0.0, version_2: false }.log_to_lin(code);
let mut img = Image::new(1, 1);
img.set(0, 0, [code, code, code, 1.0]);
let zero = run("ec.utility.cineon", &[("version", num(1.0)), ("gamma", num(0.0)), ("highlightRolloff", num(0.0))], img).img.data[0][0];
assert!((zero - base.powf(170.0)).abs() < 1e-4, "{zero} != {}", base.powf(170.0));
// The version 2 formula differs even when Gamma uses the version 1 scale.
let mut img = Image::new(1, 1);
img.set(0, 0, [code, code, code, 1.0]);
let v2_floor = run("ec.utility.cineon", &[("gamma", num(0.01 / 1.7)), ("highlightRolloff", num(0.0))], img).img.data[0][0];
assert!((v2_floor - zero).abs() > 1e-4, "{v2_floor} vs {zero}");
// An instance without the parameter reads as version 1.
let s = crate::find("ec.utility.cineon").unwrap();
let mut params = Params { values: s.params.iter().filter(|p| p.id != "version").map(|p| (p.id.to_string(), p.default.clone())).collect() };
params.values.insert("gamma".into(), num(1.7));
assert!((cineon_gamma(&params) - 1.0).abs() < 1e-12);
}
/// Interpret Footage and version 2 Converter agree at Gamma 1.
#[test]
fn cineon_converter_matches_interpret_footage() {
let codes = [0.0f32, 95.0, 250.0, 400.0, 560.0, 685.0, 800.0, 1023.0];
for (gamma, rolloff) in [(1.0, 20.0), (1.0, 0.0), (1.7, 50.0), (2.4, 50.0)] {
for (gamma, rolloff) in [(1.0, 20.0), (1.0, 0.0)] {
let mut img = Image::new(codes.len() as u32, 1);
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
img.set(x as u32, 0, [v, v, v, 1.0]);
}
let vals = [("conversionType", Value::Enum(1)), ("gamma", num(gamma * 1.7)), ("highlightRolloff", num(rolloff))];
let vals = [("conversionType", Value::Enum(1)), ("gamma", num(gamma)), ("highlightRolloff", num(rolloff))];
let out = run("ec.utility.cineon", &vals, img);
let settings = effectcraft_project::CineonSettings { log_conversion: true, gamma: gamma as f32, rolloff: rolloff as f32, ..Default::default() };
for (x, code) in codes.iter().enumerate() {
@@ -681,9 +834,9 @@ mod tests {
assert!((linear.convert(400.0 / 1023.0) - 0.10251).abs() < 1e-4);
}
/// The Cineon Converter gives the same values as before Cineon Settings shared its
/// log-to-linear function, at the default Gamma (1.7) and at Gamma 2.4, for all three
/// conversion types.
/// Saved version 1 Cineon Converter effects give the same bits as the converter before the
/// Version parameter (`log_to_lin` and `lin_to_log` below), at the default and custom black
/// and white points, for several Gammas and all three conversion types.
#[test]
fn cineon_converter_output_is_unchanged() {
fn log_to_lin(v: f32, gamma: f32, rolloff: f32, black: f32, white: f32) -> f32 {
@@ -708,29 +861,35 @@ mod tests {
lin = lin.max(0.0).powf(gamma.max(0.01) / 1.7);
(white + (lin * (1.0 - off) + off).max(1e-9).log10() * 0.6 / 0.002) / 1023.0
}
let codes = [0.0f32, 95.0, 250.0, 400.0, 560.0, 685.0, 800.0, 1023.0];
for gamma in [None, Some(2.4)] {
for kind in 0..3 {
let mut img = Image::new(codes.len() as u32, 1);
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
img.set(x as u32, 0, [v, v, v, 1.0]);
}
let mut vals = vec![("conversionType", Value::Enum(kind))];
if let Some(g) = gamma {
vals.push(("gamma", num(g)));
}
let out = run("ec.utility.cineon", &vals, img);
let g = gamma.unwrap_or(1.7) as f32;
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
let want = match kind {
0 => lin_to_log(v, g, 20.0, 95.0, 685.0),
1 => log_to_lin(v, g, 20.0, 95.0, 685.0),
_ => lin_to_log(log_to_lin(v, g, 20.0, 95.0, 685.0), 1.7, 20.0, 95.0, 685.0),
};
let got = out.img.data[x][0];
assert!((want - got).abs() < 1e-6, "gamma {g}, type {kind}, code {code}: {want} vs {got}");
let codes = [0.0f32, 95.0, 120.0, 250.0, 400.0, 560.0, 685.0, 700.0, 800.0, 1023.0];
for (black, white) in [(95.0f32, 685.0f32), (120.0, 700.0)] {
for g in [1.7, 1.0, 2.4, 0.6, 3.4, 0.0] {
for kind in 0..3 {
let mut img = Image::new(codes.len() as u32, 1);
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
img.set(x as u32, 0, [v, v, v, 1.0]);
}
let vals = [
("version", num(1.0)),
("conversionType", Value::Enum(kind)),
("gamma", num(g)),
("tenBitBlackPoint", num(f64::from(black))),
("tenBitWhitePoint", num(f64::from(white))),
];
let out = run("ec.utility.cineon", &vals, img);
let g = g as f32;
for (x, code) in codes.iter().enumerate() {
let v = code / 1023.0;
let want = match kind {
0 => lin_to_log(v, g, 20.0, black, white),
1 => log_to_lin(v, g, 20.0, black, white),
_ => lin_to_log(log_to_lin(v, g, 20.0, black, white), 1.7, 20.0, 95.0, 685.0),
};
let got = out.img.data[x][0];
// Bit for bit: a saved version 1 instance renders exactly as before.
assert_eq!(want.to_bits(), got.to_bits(), "points {black}-{white}, gamma {g}, type {kind}, code {code}: {want} vs {got}");
}
}
}
}
+2 -1
View File
@@ -187,7 +187,8 @@ impl Session {
"cancelled" => format!("{} cancelled", t.label),
_ => format!("{} failed: {message}", t.label),
};
self.events.push(crate::Event::Toast { message: toast, error: status == "failed" });
let has_errors = rec.result["errors"].as_array().is_some_and(|errors| !errors.is_empty());
self.events.push(crate::Event::Toast { message: toast, error: status == "failed" || has_errors });
self.job_log.push(rec.clone());
if self.job_log.len() > 50 {
self.job_log.remove(0);
+174 -13
View File
@@ -17,10 +17,15 @@ use crate::{EngineError, KeyRef, Result, Session, cmd};
/// Preset file format version tag (`*.ecpreset`, JSON).
pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
/// The preset format version that `anim.savePreset` writes.
pub const PRESET_VERSION: u64 = 3;
/// The first preset version that stores effect keys relative to the earliest key (#1971).
const RELATIVE_EFFECT_KEYS: u64 = 2;
/// The first preset version that stores text animators and selectors under `textAnimators`.
const TEXT_ANIMATORS: u64 = 3;
/// The preset format version written under [`PRESET_TAG`]. 4: a property that is a Cineon
/// Converter's Gamma, directly or through Essential Properties, records that Cineon Converter's
/// version in `cineonVersion`; the Gamma properties of version 1 to 3 presets are version 1 Gammas.
pub const PRESET_VERSION: u64 = 4;
fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
has_comp(s)?;
@@ -105,7 +110,8 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let (Some(pr), Some(mp)) = (l.props.find(uid), match_path_of(&l.props, uid)) else { continue };
props.push((l.layer_time(t), mp, pr.clone()));
let version = cineon_gamma_version(&s.project, l, uid, Some(t), NESTING);
props.push((l.layer_time(t), mp, pr.clone(), version));
}
if props.is_empty() && effects.is_empty() && animators.is_empty() {
return Err(bad("anim.savePreset", "select properties or effects to save"));
@@ -113,7 +119,7 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
// Key times are stored relative to the earliest key so the preset applies at the CTI.
let first = props
.iter()
.flat_map(|(_, _, pr)| pr.keys.iter().map(|k| k.time))
.flat_map(|(_, _, pr, _)| pr.keys.iter().map(|k| k.time))
.chain(earliest_key(effects.iter().map(|(_, g)| g).chain(&animators)))
.min()
.unwrap_or(Tick::ZERO);
@@ -122,12 +128,16 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
let props_json: Vec<Value> = props
.iter()
.map(|(_, mp, pr)| {
.map(|(_, mp, pr, version)| {
let mut pr = pr.clone();
for k in &mut pr.keys {
k.time -= first;
}
json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr})
let mut v = json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr});
if let Some((version, _)) = version {
v["cineonVersion"] = json!(version);
}
v
})
.collect();
let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
@@ -198,7 +208,19 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
retime_effect(g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_sub(first.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?;
}
}
let props: Vec<(String, Property)> = doc["properties"]
// A Cineon Converter saved before version 2 gets its Version (1), as when a project opens.
if let Some(spec) = effectcraft_effects::find("ec.utility.cineon") {
for g in &mut effects {
if matches!(&g.kind, GroupKind::Effect { effect } if effect == spec.id) {
// The uids are reassigned when the group is applied.
let mut next = 0;
effectcraft_effects::migrate::upgrade_instance(spec, g, &mut Ids(&mut next), [0.0; 2]);
}
}
}
// The Cineon Converter version of each saved Gamma; a format 1 to 3 preset holds version 1 Gammas.
let legacy = doc[PRESET_TAG].as_u64().unwrap_or(1) < PRESET_VERSION;
let props: Vec<(String, Property, Option<f64>)> = doc["properties"]
.as_array()
.map(|a| {
a.iter()
@@ -210,12 +232,29 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
let mut pr = Property::new(0, "", "", value);
pr.keys = keys;
pr.expr = expr;
Some((path, pr))
let version = v["cineonVersion"].as_f64().or(legacy.then_some(1.0));
Some((path, pr, version))
})
.collect()
})
.unwrap_or_default();
let saved_3d = props.iter().any(|(path, src)| path == "text/perChar3d" && src.value.as_bool());
// Per layer and property: the version of the Cineon Converter Gammas the property drives
// through Essential Properties.
let exposed: Vec<Vec<Option<f64>>> = ids
.iter()
.map(|lid| {
let l = s.project.comp(cid).and_then(|c| c.layer(*lid));
props
.iter()
.map(|(path, _, _)| {
let l = l?;
let pr = l.props.prop(&resolve_effect_path(l, path))?;
cineon_gamma_version(&s.project, l, pr.uid, Some(s.time()), NESTING).and_then(|(v, direct)| (!direct).then_some(v))
})
.collect()
})
.collect();
let saved_3d = props.iter().any(|(path, src, _)| path == "text/perChar3d" && src.value.as_bool());
let t = s.time();
// Effect bounds per layer size the point defaults of parameters added since the preset was saved.
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
@@ -225,7 +264,7 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
let mut skipped = vec![];
s.edit("Apply Animation Preset", None, |proj, _| {
let mut next = proj.next_id;
for lid in &ids {
for (li, lid) in ids.iter().enumerate() {
let size = sizes.get(lid).copied().unwrap_or([100.0, 100.0]);
let l = layer_mut(proj, cid, *lid)?;
let lt = l.layer_time(t);
@@ -248,7 +287,41 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
applied += 1;
}
}
for (path, src) in &props {
for (pi, (path, src, version)) in props.iter().enumerate() {
// A Gamma of a Cineon Converter whose Version is keyframed is converted to that
// Version, and skipped when the keys hold more than one version or an expression
// sets the Version. A preset that holds the Version too sets it.
let version_path = cineon_version_path(path).filter(|vp| !props.iter().any(|(p, v, _)| p == vp && matches!(v.value, KV::Scalar(_))));
let keyed = match (version, &version_path) {
(Some(_), Some(vp)) => {
l.props.prop(&resolve_effect_path(l, vp)).filter(|pr| pr.has_expression() || pr.keys.iter().any(|k| !k.muted)).map(constant_version)
}
_ => None,
};
let target = match keyed {
Some(None) => {
skipped.push(path.clone());
continue;
}
Some(to) => to,
None => exposed[li][pi],
};
// An exposed Gamma is converted to the scale of the Cineon Converters it drives.
// One with an enabled expression is skipped: expressions are applied as saved.
let rescaled;
let src = match (version, target) {
(Some(from), Some(to)) if *from != to && src.has_expression() => {
skipped.push(path.clone());
continue;
}
(Some(from), Some(to)) if *from != to => {
let mut c = src.clone();
rescale_gamma(&mut c, effectcraft_effects::cineon_gamma_scale(*from) / effectcraft_effects::cineon_gamma_scale(to));
rescaled = c;
&rescaled
}
_ => src,
};
let resolved = resolve_effect_path(l, path);
match l.props.prop_mut(&resolved) {
Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
@@ -267,7 +340,18 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
applied += 1;
}
_ => skipped.push(path.clone()),
_ => {
skipped.push(path.clone());
continue;
}
}
// A Cineon Converter's Gamma sets the instance's Version to the one it was saved
// with, unless that Version is keyframed or the preset holds it.
if keyed.is_none()
&& let (Some(v), Some(vp)) = (version, &version_path)
&& let Some(pr) = l.props.prop_mut(&resolve_effect_path(l, vp))
{
pr.value = KV::Scalar(*v);
}
}
// After the properties, so a saved Per-character 3D setting counts: it needs a 3D layer
@@ -299,7 +383,7 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
// Without this, a preset that fits no layer does nothing and says nothing.
if applied == 0 && !skipped.is_empty() {
let legacy_text = doc[PRESET_TAG].as_u64().unwrap_or(1) < PRESET_VERSION && props.iter().any(|(path, _)| path.starts_with("text/animators/"));
let legacy_text = doc[PRESET_TAG].as_u64().unwrap_or(1) < TEXT_ANIMATORS && props.iter().any(|(path, _, _)| path.starts_with("text/animators/"));
let message = if legacy_text {
"nothing in this preset fits the layer. A text animation preset saved by an earlier version only updates animators a layer already has: save it again"
} else {
@@ -319,6 +403,83 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"applied": applied, "skipped": skipped}))
}
/// The preset path of the Version of the Cineon Converter whose Gamma is at preset path `path`
/// (`effects/<match name>[#n]/gamma`, as [`match_path_of`] writes it).
fn cineon_version_path(path: &str) -> Option<String> {
let (seg, tail) = path.strip_prefix("effects/")?.split_once('/')?;
(seg.rsplit_once('#').map_or(seg, |(m, _)| m) == "ec.utility.cineon" && tail == "gamma").then(|| format!("effects/{seg}/version"))
}
/// How many nested comps [`cineon_gamma_version`] follows Essential Properties through.
const NESTING: u32 = 16;
/// The version of the Cineon Converter whose Gamma property `uid` of `l` is, and whether that
/// Cineon Converter is on `l`. With `t`, a keyframed Version is read at comp time `t`; without
/// it, a Version whose keyframes hold more than one value has no version. A Version that an
/// expression sets has none either. An Essential
/// Properties value of a precomp layer counts when its control drives only Cineon Converter
/// Gammas of one version, in the nested comp or, through further Essential Properties, in comps
/// up to `depth` levels deeper.
fn cineon_gamma_version(p: &Project, l: &Layer, uid: Uid, t: Option<Tick>, depth: u32) -> Option<(f64, bool)> {
let direct = l.effects().and_then(|fx| {
fx.groups().find(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.utility.cineon") && g.get("gamma").is_some_and(|pr| pr.uid == uid))
});
if let Some(g) = direct {
let Some(pr) = g.get("version") else { return Some((1.0, true)) };
if pr.has_expression() {
return None;
}
let version = match t {
Some(t) => pr.value_at(l.layer_time(t)).as_f64(),
None => constant_version(pr)?,
};
return Some((version, true));
}
let LayerSource::Comp { item } = l.source else { return None };
let depth = depth.checked_sub(1)?;
let ctl = effectcraft_project::essential::group(l)?.find(uid).and_then(|pr| effectcraft_project::essential::control_of(&pr.match_id))?;
let c = p.comp(item)?;
let mut version = None;
for (lid, target) in c.essential.as_ref()?.resolve(ctl)?.kind.targets() {
let (v, _) = cineon_gamma_version(p, c.layer(lid)?, target, None, depth)?;
if version.is_some_and(|x| x != v) {
return None;
}
version = Some(v);
}
version.map(|v| (v, false))
}
/// The value a Cineon Converter's Version holds at every time: its value without keyframes
/// that play, and none when the keyframes that play hold more than one value or ease with a
/// speed that moves the value between them, or when an expression sets it.
fn constant_version(pr: &Property) -> Option<f64> {
if pr.has_expression() {
return None;
}
let keys: Vec<&Keyframe> = pr.keys.iter().filter(|k| !k.muted).collect();
let first = keys.first().map_or_else(|| pr.value.as_f64(), |k| k.value.as_f64());
let still = |interp: Interp, eases: &[effectcraft_keyframe::Ease]| interp != Interp::Bezier || eases.iter().all(|e| e.speed == 0.0);
let eases_between =
keys.windows(2).any(|w| w[0].out_interp != Interp::Hold && (!still(w[0].out_interp, &w[0].out_ease) || !still(w[1].in_interp, &w[1].in_ease)));
(keys.iter().all(|k| k.value.as_f64() == first) && !eases_between).then_some(first)
}
/// Multiplies a Gamma value, its keyframes and their speeds by `f`.
fn rescale_gamma(pr: &mut Property, f: f64) {
if let KV::Scalar(x) = &mut pr.value {
*x *= f;
}
for k in &mut pr.keys {
if let KV::Scalar(x) = &mut k.value {
*x *= f;
}
for e in k.in_ease.iter_mut().chain(k.out_ease.iter_mut()) {
e.speed *= f;
}
}
}
// ---------------------------------------------------------------- keyframes
fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
+5
View File
@@ -1173,9 +1173,14 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
}
.ok_or_else(|| bad("effect.reset", "unknown effect"))?;
let name = g.name.clone();
// Reset keeps a Cineon Converter's Version.
let cineon_version = if spec.id == "ec.utility.cineon" { g.get("version").map(|v| v.value.as_f64()) } else { None };
s.edit(&format!("Reset {name}"), None, |proj, _| {
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad("effect.reset", "gone"))?;
for ps in &spec.params {
if ps.id == "version" && cineon_version.is_some() {
continue;
}
// (`group/param` ids live in twirl-down groups.)
if let Some(pr) = g.prop_mut(ps.id) {
pr.set_value_at(lt, effectcraft_effects::default_value(ps, size));
+26 -12
View File
@@ -2,7 +2,7 @@
//! Language menu (the ⓕ button next to an expression), written from the public Expression
//! Language Reference.
use effectcraft_project::{Expression, ItemId, Layer, Property};
use effectcraft_project::{Comp, Expression, ItemId, Layer, Property};
use effectcraft_render::EvalCtx;
use effectcraft_time::Tick;
use serde::Serialize;
@@ -42,8 +42,16 @@ impl ExprError {
/// expressions and the syntax errors that disabled others.
pub fn errors(s: &Session, cid: ItemId, t: Tick) -> Vec<ExprError> {
let Some(comp) = s.project.comp(cid) else { return vec![] };
let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, t) };
errors_in(&ctx, s.expr_check, || true).unwrap_or_default()
errors_in(&eval_ctx(s, cid, comp, t), s.expr_check, || true).unwrap_or_default()
}
/// The context to evaluate expressions of comp `cid` at comp time `t` as the render does for the
/// comp at top level: with the session's expression host and its footage source, so
/// `sampleImage()` reads footage pixels instead of failing or sampling transparent (#1000,
/// #3231). `expr.errors`, `prop.get`, [`Session::expression_errors`] and the script value query
/// all evaluate through this one context.
pub fn eval_ctx<'a>(s: &'a Session, cid: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {
EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, t) }
}
/// Evaluate diagnostics against an immutable snapshot. Background callers can cancel between
@@ -65,15 +73,7 @@ pub fn errors_in(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<()
if !keep_going() {
return None;
}
let msg = if e.enabled {
match &ctx.expr {
Some(h) => h.eval(ctx, l, p, &p.value_at(l.layer_time(ctx.time))).err(),
None => None,
}
} else {
check.and_then(|check| check(&e.text).err())
};
if let Some(message) = msg {
if let Some(message) = property_error(ctx, check, l, p) {
out.push(error_of(ctx.comp_id, i, l, p, message, !e.enabled));
}
}
@@ -81,6 +81,20 @@ pub fn errors_in(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<()
keep_going().then_some(out)
}
/// Why property `p` of layer `l` fails at `ctx.time` (comp time), as `expr.errors` reports it and
/// scripts read it as `Property.expressionError`: the evaluation error (an exception or a
/// non-finite result) of an enabled expression, or the syntax error that disabled one. `None`
/// without an expression or when it evaluates. Evaluates this one expression; renders nothing.
/// Without an evaluator an enabled expression gets the syntax check, so a broken one (from a
/// project file) still reports why.
pub fn property_error(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<(), String>>, l: &Layer, p: &Property) -> Option<String> {
let e = p.expr.as_ref().filter(|e| !e.text.trim().is_empty())?;
match ctx.expr {
Some(h) if e.enabled => h.eval(ctx, l, p, &p.value_at(l.layer_time(ctx.time))).err(),
_ => check.and_then(|check| check(&e.text).err()),
}
}
fn error_of(cid: ItemId, i: usize, l: &Layer, p: &Property, message: String, disabled: bool) -> ExprError {
ExprError {
comp: cid.0,
+15 -6
View File
@@ -143,7 +143,8 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
_ => format!("Importing {total} files"),
};
let p = p.clone();
return s.spawn_task("import", label, false, move |ctl| {
let immediate_errors = pending.errors.clone();
let mut result = s.spawn_task("import", label, false, move |ctl| {
let mut probed = Vec::with_capacity(total);
for (k, src) in sources.iter().enumerate() {
ctl.message(format!("{} ({} of {total})", src.name(), k + 1));
@@ -162,13 +163,19 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
match errors.as_slice() {
[] => {}
[one] => toast = format!("{toast}. {one}"),
[first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)", rest.len()),
[first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)\n{}", rest.len(), errors.join("\n")),
}
r["toast"] = json!(toast);
Ok(r)
});
Ok(apply)
});
})?;
// Preparation can reject layered files before the remaining footage needs probing.
// Report those failures now as well as in the eventual job result.
if result["started"] == true {
result["errors"] = json!(immediate_errors);
}
return Ok(result);
}
let probed = pending.sources.iter().map(|src| pending.prober.probe(src)).collect();
let mut r = add_footage(s, pending, probed)?;
@@ -346,8 +353,9 @@ impl Prober {
None => ask_alpha = true,
}
}
// Page: another page of a PDF / Illustrator file.
if self.page > 0 && matches!(f.codec.as_str(), "PDF" | "AI") {
// Page: another page of a PDF / Illustrator file, or another artboard of a VectorCraft
// document's PDF.
if self.page > 0 && matches!(f.codec.as_str(), "PDF" | "AI" | "VectorCraft") {
let doc = self
.services
.read_file(path)
@@ -563,7 +571,8 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result:
/// definition, OpenEXR premultiplied); TGA, TIFF and movies with alpha don't.
fn alpha_is_labeled(path: &str, codec: &str) -> bool {
let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") || codec.eq_ignore_ascii_case("PSD")
matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps" | "vectorcraft")
|| codec.eq_ignore_ascii_case("PSD")
}
/// A Photoshop layer by index or name (pixel layers only).
+34 -2
View File
@@ -56,15 +56,39 @@ fn items_p(s: &Session, p: &Value) -> Vec<ItemId> {
}
}
/// `project.newFolder {name?, parent?, items?}`. With `items` (ids or names), they move into the
/// new folder in the same undo step: Project items dropped on the panel's New Folder button, as
/// in After Effects (#3196). A folder can't end up inside itself.
fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
let c = "project.newFolder";
let name = str_p(p, "name").unwrap_or("Untitled Folder").to_string();
let parent = p.get("parent").and_then(Value::as_u64).map(ItemId).filter(|i| s.project.item(*i).is_some_and(|x| x.is_folder()));
let mut items: Vec<ItemId> = vec![];
if let Some(v) = p.get("items") {
let Value::Array(a) = v else { return Err(bad(c, "`items` must be an array of item ids or names")) };
for v in a {
let id = super::project_items::item_ref(s, v, c)?;
if !items.contains(&id) {
items.push(id);
}
}
if let Some(f) = parent
&& let Some(inside) = items.iter().find(|i| super::project_items::is_within(&s.project, f, **i))
{
return Err(bad(c, format!("can't move folder {} into a folder inside itself", inside.0)));
}
}
let id = s.edit("New Folder", None, |proj, st| {
let id = proj.add_item(&name, Label::Yellow, parent, ItemKind::Folder);
for i in &items {
if let Some(it) = proj.item_mut(*i) {
it.parent = Some(id);
}
}
st.project_selection = vec![id];
Ok(id)
})?;
Ok(json!({"item": id.0}))
if p.get("items").is_some() { Ok(json!({"item": id.0, "moved": items.len()})) } else { Ok(json!({"item": id.0})) }
}
fn close(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1211,7 +1235,15 @@ fn reveal_in_finder(s: &mut Session, p: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("project.newFolder", "New Folder", ["File", "New"], Some("Cmd+Alt+Shift+N"), "{name?, parent?}", always, new_folder),
cmd!(
"project.newFolder",
"New Folder",
["File", "New"],
Some("Cmd+Alt+Shift+N"),
"{name?, parent?, items?: [id|name] (moved into it)}",
always,
new_folder
),
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{comp?}", has_comp, close),
cmd!("file.closeProject", "Close Project", ["File"], None, "{}", always, close_project),
cmd!("file.saveCopy", "Save a Copy...", ["File", "Save As"], None, "{path}", always, save_copy),
+2 -2
View File
@@ -867,8 +867,8 @@ impl Session {
});
for pr in has {
let text = pr.expr.as_ref().map(|e| e.text.clone()).unwrap_or_default();
let mut ctx = effectcraft_render::EvalCtx::new(&self.project, cid, comp, t);
ctx.expr = Some(host.as_ref());
// With the footage source, so `sampleImage()` doesn't fail here only (#3231).
let ctx = super::expr_tools::eval_ctx(self, cid, comp, t);
if let Err(e) = host.eval(&ctx, l, pr, &pr.value_at(l.layer_time(t))) {
errors.push(json!({"layer": l.id.0, "prop": pr.uid, "name": pr.name, "expression": text, "error": e}));
}
+1 -1
View File
@@ -8,7 +8,7 @@ use super::{CommandSpec, always, b_p, bad, str_p};
use crate::{EngineError, Result, Session, cmd, query};
/// `item` (id or name) → id.
fn item_ref(s: &Session, v: &Value, cmd: &str) -> Result<ItemId> {
pub(super) fn item_ref(s: &Session, v: &Value, cmd: &str) -> Result<ItemId> {
match v {
Value::Number(n) => n.as_u64().map(ItemId).filter(|i| s.project.item(*i).is_some()),
Value::String(name) => s.project.find_by_name(name).map(|i| i.id),
+54 -8
View File
@@ -371,20 +371,41 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
};
let follow: Vec<usize> =
p.get("follow").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).filter_map(|d| usize::try_from(d).ok()).collect();
// A typed `*2`, `/2` (`factor`) or `+10` (`addend`) (#3195): each layer's own value times it
// or plus it, not the edited layer's result (which its range may have clamped).
let factor = p.get("factor").and_then(Value::as_f64).filter(|k| k.is_finite() && delta.is_none());
let addend = p.get("addend").and_then(Value::as_f64).filter(|n| n.is_finite() && delta.is_none());
let own_step = |v: f64| -> Option<f64> {
let r = match (factor, addend) {
(Some(k), _) => v * k,
(None, Some(n)) => v + n,
(None, None) => return None,
};
r.is_finite().then_some(r)
};
// Each layer's own value where `set` writes it (a `time` other than the CTI keys there).
let typed = |s: &Session, q: &mut Value, olid: LayerId, ouid: Uid| {
let at = snapped_key_time(s, cid, olid, q, "prop.set").ok().flatten();
if scalar && let Some(v) = components_at(s, cid, olid, ouid, at).and_then(|c| c.first().copied()).and_then(own_step) {
q["value"] = json!(v);
}
if let (Some(dims), Some(n)) = (&dims, &new)
&& let Some(mut c) = components_at(s, cid, olid, ouid, snapped_key_time(s, cid, olid, q, "prop.set").ok().flatten())
&& let Some(mut c) = components_at(s, cid, olid, ouid, at)
{
let change = dims.first().and_then(|&d| Some(n.get(d)? - c.get(d)?)).unwrap_or(0.0);
// The typed components' new values on this layer.
let typed_value = |c: &[f64], d: usize| {
if factor.is_some() || addend.is_some() { c.get(d).copied().and_then(own_step) } else { n.get(d).copied() }
};
let change = dims.first().and_then(|&d| Some(typed_value(&c, d)? - c.get(d)?)).unwrap_or(0.0);
let values: Vec<Option<f64>> = dims.iter().map(|&d| typed_value(&c, d)).collect();
for &d in &follow {
if let Some(slot) = c.get_mut(d) {
*slot += change;
}
}
for &d in dims {
if let (Some(slot), Some(v)) = (c.get_mut(d), n.get(d)) {
*slot = *v;
for (&d, v) in dims.iter().zip(values) {
if let (Some(slot), Some(v)) = (c.get_mut(d), v) {
*slot = v;
}
}
q["value"] = json!(c);
@@ -421,6 +442,9 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
let mut q = twin_params(p, olid, ouid);
shifted(s, &mut q, olid, ouid, k);
typed(s, &mut q, olid, ouid);
if is_mask_feather(s, cid, olid, ouid) {
non_negative(&mut q["value"]);
}
// (a layer that can't take it, e.g. a clamped or static property, keeps its value)
let _ = set(s, &q);
}
@@ -429,6 +453,26 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
if merge_p(p).is_some() { run(s) } else { super::app_more::grouped(s, "Change Property", run) }
}
/// Whether property `uid` of `lid` is a mask's Mask Feather, which is never negative (After
/// Effects; the panels clamp a typed or scrubbed value at 0).
fn is_mask_feather(s: &Session, cid: ItemId, lid: LayerId, uid: Uid) -> bool {
let Some(l) = s.project.comp(cid).and_then(|c| c.layer(lid)) else { return false };
l.props.find(uid).is_some_and(|q| q.match_id == "feather") && l.props.parent_of(uid).is_some_and(|g| matches!(g.kind, GroupKind::Mask { .. }))
}
/// A JSON number, or each number of an array, raised to at least 0.
fn non_negative(v: &mut Value) {
match v {
Value::Number(n) => {
if let Some(x) = n.as_f64().filter(|x| *x < 0.0) {
*v = json!(x.max(0.0));
}
}
Value::Array(a) => a.iter_mut().for_each(non_negative),
_ => {}
}
}
/// `prop.toggleAnimation`; with `selected`, the other selected layers' same property follows.
fn toggle_anim_selected(s: &mut Session, p: &Value) -> Result<Value> {
let twins = selected_twins(s, p, "prop.toggleAnimation")?;
@@ -558,8 +602,9 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
} else if pr.has_expression()
&& let (Some(h), Some(comp)) = (s.expr.as_deref(), s.project.comp(cid))
{
let mut ctx = crate::render::EvalCtx::new(&s.project, cid, comp, t);
ctx.expr = Some(h);
// The render's context, footage source included, so `sampleImage()` evaluates here as it
// renders and as `expr.errors` reports it (#3231).
let ctx = super::expr_tools::eval_ctx(s, cid, comp, t);
match h.eval(&ctx, l, pr, &raw) {
Ok(v) => out["evaluated"] = v.to_json(),
Err(e) => {
@@ -1445,6 +1490,7 @@ fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Res
})
}
/// Returns the command specs for the property commands (get, set, keyframes, expressions and the rest).
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("prop.get", "Get Property", "{layer?, path|prop, time? (comp s)}", get),
@@ -1453,7 +1499,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Property Value",
[],
None,
"{layer?, path|prop, value, time? (layer s by default), timeBase?: layer|comp, merge?, selected? (also the other selected layers), offset? (them by the same change), proportional? (with offset: Proportional Scrubbing, each layer by its share in selection order, the first none, the last all), dims? (with selected, a typed value: the components edited, e.g. [2] for Z; the other layers keep the rest of their own value), follow? (with dims: components that move on each other layer by the change its first typed component takes)}",
"{layer?, path|prop, value, time? (layer s by default), timeBase?: layer|comp, merge?, selected? (also the other selected layers), offset? (them by the same change), proportional? (with offset: Proportional Scrubbing, each layer by its share in selection order, the first none, the last all), dims? (with selected, a typed value: the components edited, e.g. [2] for Z; the other layers keep the rest of their own value), follow? (with dims: components that move on each other layer by the change its first typed component takes), factor? (with selected, a typed `*` or `/`: the other layers take their own value times it, in the dims components of a vector), addend? (the same for a typed `+`: their own value plus it)}",
has_layers,
set_selected
),
+1 -1
View File
@@ -197,7 +197,7 @@ fn sort_entries(entries: &mut [Entry]) {
entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase()));
}
const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "svg", "tga", "dpx", "cin", "hdr"];
const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "svg", "tga", "dpx", "cin", "hdr", "vectorcraft"];
const AUDIO: &[&str] = &["wav", "aif", "aiff", "mp3", "m4a", "aac", "flac", "ogg", "opus"];
const DATA: &[&str] = &["json", "csv", "tsv", "mgjson"];
const MODEL: &[&str] = &["gltf", "glb", "obj", "stl", "fbx"];
+12 -1
View File
@@ -99,7 +99,7 @@ fn extension(path: &str) -> String {
/// Stills that can form a sequence (not layered or vector documents, which import as comps).
fn sequenceable(path: &str) -> bool {
crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb")
crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb" | "vectorcraft")
}
/// The run a still belongs to: (folder, name prefix, extension); alphabetical runs ignore the
@@ -343,6 +343,17 @@ mod tests {
assert_eq!(sequences(&t, &strs(&["/s/a_0001.png", "/s/c.png"]), false).len(), 1);
}
/// VectorCraft documents list as media in the Media Browser and import from a folder, each on
/// its own, as SVG files do: numbered ones don't form a sequence.
#[test]
fn vectorcraft_documents_are_media_but_not_sequences() {
assert_eq!(crate::media_browser::kind_of("/art/Poster.VECTORCRAFT"), Some("image"));
let t = Table(vec!["/art/frame_0001.vectorcraft", "/art/frame_0002.vectorcraft"]);
let on = SequenceOptions::default();
assert_eq!(group(&t, &strs(&["/art/frame_0001.vectorcraft"]), on), [Source::File("/art/frame_0001.vectorcraft".into())]);
assert_eq!(group(&t, &strs(&["/art"]), on), [Source::File("/art/frame_0001.vectorcraft".into()), Source::File("/art/frame_0002.vectorcraft".into())]);
}
/// Thousands of files picked one by one from one folder: the folder is listed once, not
/// once per file, and each finds its run by key.
#[test]
+529
View File
@@ -681,6 +681,535 @@ fn opening_a_schema_1_project_moves_shape_layer_effect_points_into_effect_space(
check(&s3);
}
/// Writes `s`'s project as a build before Cineon Converter version 2 saved it: schema 2, and no
/// hidden Version parameter on Cineon Converter instances. Returns the folder and the file.
fn save_before_cineon_version_2(s: &Session, name: &str) -> (std::path::PathBuf, String) {
fn drop_version(v: &mut serde_json::Value) {
match v {
serde_json::Value::Object(o) => {
if o.get("match") == Some(&json!("ec.utility.cineon"))
&& let Some(serde_json::Value::Array(children)) = o.get_mut("children")
{
children.retain(|c| c["match"] != json!("version"));
}
o.values_mut().for_each(drop_version);
}
serde_json::Value::Array(a) => a.iter_mut().for_each(drop_version),
_ => {}
}
}
let mut old: serde_json::Value = serde_json::from_str(&s.project.to_file_json().unwrap()).unwrap();
old["schema"] = json!(2);
drop_version(&mut old);
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("old.ecproj").to_string_lossy().to_string();
std::fs::write(&path, old.to_string()).unwrap();
(dir, path)
}
/// Opening a project with a Cineon Converter saved before version 2 leaves the text of every
/// expression as it was saved: one on an unrelated property (a wiggle) and one on Gamma.
#[test]
fn opening_an_old_cineon_converter_project_keeps_expression_text() {
let (mut s, a, b) = comp_with_two_solids();
let fx = apply(&mut s, a, "Cineon Converter");
let wiggle = "wiggle(2, 10)";
let on_gamma = "value + time / 10";
s.execute("prop.setExpression", json!({"layer": b, "path": "transform/position", "expression": wiggle})).unwrap();
let gamma = effect_group(&s, a, fx).prop("gamma").unwrap().uid;
s.execute("prop.setExpression", json!({"layer": a, "prop": gamma, "expression": on_gamma})).unwrap();
let (dir, path) = save_before_cineon_version_2(&s, "ec-cineon-expressions");
let mut s2 = Session::default();
s2.execute("file.open", json!({"path": path})).unwrap();
let _ = std::fs::remove_dir_all(dir);
let position = layer(&s2, b).props.prop("transform/position").and_then(|p| p.expr.clone()).map(|e| e.text);
assert_eq!(position.as_deref(), Some(wiggle));
let gamma = effect_group(&s2, a, fx).prop("gamma").and_then(|p| p.expr.clone()).map(|e| e.text);
assert_eq!(gamma.as_deref(), Some(on_gamma));
}
/// Cineon Converter version 1's Log to Linear: the linear value raised to `1.7 / gamma` (no
/// Highlight Rolloff).
fn cineon_version_1(v: f32, gamma: f32) -> f32 {
let off = 10f32.powf((95.0 - 685.0) * 0.002 / 0.6);
((10f32.powf((v * 1023.0 - 685.0) * 0.002 / 0.6) - off) / (1.0 - off)).max(0.0).powf(1.7 / gamma)
}
fn cineon_version_2(v: f32, gamma: f32) -> f32 {
let offset = 10f32.powf((95.0 - 685.0) * 0.002 / 0.6).powf(1.0 / gamma);
let exposure = 10f32.powf((v * 1023.0 - 685.0) * 0.002 / 0.6).powf(1.0 / gamma);
((exposure - offset) / (1.0 - offset)).max(0.0)
}
/// A project saved before Cineon Converter version 2 opens with each instance at version 1,
/// where Gamma 1.7 gives linear output: Gamma and its keyframes keep their saved values, and the
/// frames render as they did. Saving and opening again changes nothing. A Cineon Converter
/// applied after that is version 2, where Gamma 1 gives linear output.
#[test]
fn opening_an_old_cineon_converter_project_keeps_what_it_renders() {
let mut s = Session::default();
// 32 bpc, so frames are not rounded to 8-bit steps.
s.execute("file.projectSettings", json!({"bitDepth": 32})).unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let animated = s.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let cid = s.active_comp_id().unwrap();
let input = s.render(cid, Tick::ZERO, Default::default()).get(4, 4);
let fx = apply(&mut s, animated, "Cineon Converter");
s.execute("prop.set", json!({"layer": animated, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
animate_effect(&mut s, animated, fx, "gamma", &[(0.0, 2.2), (1.0, 3.4)]);
let still = s.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let still_fx = apply(&mut s, still, "Cineon Converter");
s.execute("prop.set", json!({"layer": still, "path": "effects/#1/gamma", "value": 2.2})).unwrap();
s.execute("layer.setSwitch", json!({"layers": [still], "switch": "video", "value": false})).unwrap();
let (dir, path) = save_before_cineon_version_2(&s, "ec-cineon-render");
let mut s2 = Session::default();
s2.execute("file.open", json!({"path": path})).unwrap();
let check = |s2: &Session| {
let prop = |lid: u64, uid: u64, id: &str| effect_group(s2, lid, uid).prop(id).unwrap().clone();
assert_eq!(prop(animated, fx, "version").value, KV::Scalar(1.0));
assert_eq!(prop(still, still_fx, "version").value, KV::Scalar(1.0));
let keys: Vec<f64> = prop(animated, fx, "gamma").keys.iter().map(|k| k.value.as_f64()).collect();
assert_eq!(keys, [2.2, 3.4]);
assert_eq!(prop(still, still_fx, "gamma").value, KV::Scalar(2.2));
for (t, gamma) in [(0.0, 2.2), (0.5, 2.8), (1.0, 3.4)] {
let got = s2.render(cid, Tick::from_seconds_f64(t), Default::default()).get(4, 4);
for c in 0..3 {
let want = cineon_version_1(input[c], gamma);
assert!((got[c] - want).abs() < 1e-4, "{t} s, channel {c}: {} rendered, {want} before", got[c]);
}
}
};
check(&s2);
s2.execute("file.save", json!({"path": path})).unwrap();
let mut s3 = Session::default();
s3.execute("file.open", json!({"path": path})).unwrap();
let _ = std::fs::remove_dir_all(dir);
check(&s3);
// A new instance on top is version 2 with Gamma 1.7.
let top = s3.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let top_fx = apply(&mut s3, top, "Cineon Converter");
s3.execute("prop.set", json!({"layer": top, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
assert_eq!(effect_group(&s3, top, top_fx).prop("version").unwrap().value, KV::Scalar(2.0));
assert_eq!(effect_group(&s3, top, top_fx).prop("gamma").unwrap().value, KV::Scalar(1.7));
let got = s3.render(cid, Tick::ZERO, Default::default()).get(4, 4);
for c in 0..3 {
let want = cineon_version_2(input[c], 1.7);
assert!((got[c] - want).abs() < 1e-4, "channel {c}: {} rendered, {want}", got[c]);
}
}
/// A precomp layer that overrides an exposed Gamma of an old Cineon Converter keeps its saved
/// value, and the nested version 1 instance renders it as before.
#[test]
fn opening_an_old_project_keeps_an_overridden_cineon_gamma() {
let mut s = Session::default();
s.execute("file.projectSettings", json!({"bitDepth": 32})).unwrap();
s.execute("comp.new", json!({"name": "Inner", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let inner = s.active_comp_id().unwrap();
let solid = s.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let input = s.render(inner, Tick::ZERO, Default::default()).get(4, 4);
apply(&mut s, solid, "Cineon Converter");
s.execute("prop.set", json!({"layer": solid, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
s.execute("prop.set", json!({"layer": solid, "path": "effects/#1/gamma", "value": 1.7})).unwrap();
let control = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/gamma"})).unwrap()["controls"][0].as_u64().unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let main = s.active_comp_id().unwrap();
let inst = s.execute("layer.addItem", json!({"item": inner.0})).unwrap()["layer"].as_u64().unwrap();
s.execute("essential.set", json!({"layer": inst, "control": control, "value": 2.2})).unwrap();
let (dir, path) = save_before_cineon_version_2(&s, "ec-cineon-essential");
let mut s2 = Session::default();
s2.execute("file.open", json!({"path": path})).unwrap();
let _ = std::fs::remove_dir_all(dir);
let c = s2.execute("essential.instance", json!({"comp": main.0, "layer": inst})).unwrap()["controls"][0].clone();
assert_eq!(c["overridden"], json!(true), "{c}");
assert_eq!(c["value"].as_f64(), Some(2.2), "{c}");
let got = s2.render(main, Tick::ZERO, Default::default()).get(4, 4);
for ch in 0..3 {
let want = cineon_version_1(input[ch], 2.2);
assert!((got[ch] - want).abs() < 1e-4, "channel {ch}: {} rendered, {want} before", got[ch]);
}
}
/// A project saved by this build opens in a build from before Cineon Converter version 2 as
/// `docs/architecture.md` describes. The file is still schema 2. That build's registry has no
/// Version parameter: opening keeps the saved one, and Gamma is read on version 1's scale. A
/// version 1 instance holds its Gamma as saved before, so it renders there as it did; a version 2
/// instance's Gamma 1.7 renders there as a version 1 Gamma of 1.7.
#[test]
fn a_project_saved_now_opens_in_an_older_build_as_documented() {
let mut s = Session::default();
s.execute("file.projectSettings", json!({"bitDepth": 32})).unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let cid = s.active_comp_id().unwrap();
let old = s.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let input = s.render(cid, Tick::ZERO, Default::default()).get(4, 4);
let old_fx = apply(&mut s, old, "Cineon Converter");
s.execute("prop.set", json!({"layer": old, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
s.execute("prop.set", json!({"layer": old, "path": "effects/#1/gamma", "value": 2.2})).unwrap();
let (dir, path) = save_before_cineon_version_2(&s, "ec-cineon-older-build");
let mut s2 = Session::default();
s2.execute("file.open", json!({"path": path})).unwrap();
let new = s2.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let new_fx = apply(&mut s2, new, "Cineon Converter");
s2.execute("prop.set", json!({"layer": new, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
s2.execute("file.save", json!({"path": path})).unwrap();
let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let _ = std::fs::remove_dir_all(dir);
assert_eq!(saved["schema"], json!(2));
// The saved Cineon Converter groups, read with the older registry's Cineon Converter.
fn groups(v: &serde_json::Value, out: &mut Vec<PropGroup>) {
match v {
serde_json::Value::Object(o) => {
if o.get("match") == Some(&json!("ec.utility.cineon")) {
out.push(serde_json::from_value(v.clone()).unwrap());
}
o.values().for_each(|c| groups(c, out));
}
serde_json::Value::Array(a) => a.iter().for_each(|c| groups(c, out)),
_ => {}
}
}
let mut saved_groups = vec![];
groups(&saved, &mut saved_groups);
let spec = effectcraft_effects::find("ec.utility.cineon").unwrap();
let older = effectcraft_effects::EffectSpec {
params: spec
.params
.iter()
.filter(|p| p.id != "version")
.map(|p| effectcraft_effects::ParamSpec { id: p.id, name: p.name, default: p.default.clone(), ui: p.ui.clone() })
.collect(),
..*spec
};
let opened_in_older = |uid: u64| {
let mut g = saved_groups.iter().find(|g| g.uid == uid).unwrap().clone();
let mut next = 1_000_000;
effectcraft_effects::migrate::upgrade_instance(&older, &mut g, &mut effectcraft_project::build::Ids(&mut next), [8.0, 8.0]);
(g.get("version").map(|p| p.value.clone()), g.get("gamma").unwrap().value.clone())
};
assert_eq!(opened_in_older(old_fx), (Some(KV::Scalar(1.0)), KV::Scalar(2.2)));
assert_eq!(opened_in_older(new_fx), (Some(KV::Scalar(2.0)), KV::Scalar(1.7)));
// This build renders the version 1 instance as the older build does: Gamma 2.2 read as a
// version 1 Gamma. The older build reads the new instance's Gamma 1.7 on the version 1 scale.
let got_new = s2.render(cid, Tick::ZERO, Default::default()).get(4, 4);
s2.execute("layer.setSwitch", json!({"layers": [new], "switch": "video", "value": false})).unwrap();
let got_old = s2.render(cid, Tick::ZERO, Default::default()).get(4, 4);
for c in 0..3 {
let want = cineon_version_1(input[c], 2.2);
assert!((got_old[c] - want).abs() < 1e-4, "channel {c}: {} rendered, {want} in the older build", got_old[c]);
let want_new = cineon_version_2(input[c], 1.7);
assert!((got_new[c] - want_new).abs() < 1e-4, "channel {c}: {} rendered, {want_new}", got_new[c]);
assert!((cineon_version_1(input[c], 1.7) - want_new).abs() > 1e-3, "channel {c}: the older build renders Gamma 1.7 differently");
}
}
/// Reset on a version 1 Cineon Converter keeps its Version, so its other Gamma keyframes render
/// as before, and keys Gamma to version 1's linear Gamma (1.7) at the current time.
#[test]
fn resetting_an_old_cineon_converter_keeps_its_version() {
let mut s = Session::default();
s.execute("file.projectSettings", json!({"bitDepth": 32})).unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let cid = s.active_comp_id().unwrap();
let l = s.execute("layer.newSolid", json!({"color": [0.4, 0.5, 0.6], "width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
let input = s.render(cid, Tick::ZERO, Default::default()).get(4, 4);
let fx = apply(&mut s, l, "Cineon Converter");
s.execute("prop.set", json!({"layer": l, "path": "effects/#1/highlightRolloff", "value": 0.0})).unwrap();
animate_effect(&mut s, l, fx, "gamma", &[(0.0, 2.2), (1.0, 3.4)]);
let (dir, path) = save_before_cineon_version_2(&s, "ec-cineon-reset");
let mut s2 = Session::default();
s2.execute("file.open", json!({"path": path})).unwrap();
let _ = std::fs::remove_dir_all(dir);
s2.execute("time.set", json!({"time": 1.5})).unwrap();
s2.execute("effect.reset", json!({"layer": l, "effect": fx})).unwrap();
let g = effect_group(&s2, l, fx);
assert_eq!(g.prop("version").unwrap().value, KV::Scalar(1.0));
let keys: Vec<f64> = g.prop("gamma").unwrap().keys.iter().map(|k| k.value.as_f64()).collect();
assert_eq!(keys, [2.2, 3.4, 1.7]);
let got = s2.render(cid, Tick::ZERO, Default::default()).get(4, 4);
for c in 0..3 {
let want = cineon_version_1(input[c], 2.2);
assert!((got[c] - want).abs() < 1e-4, "channel {c}: {} rendered, {want} before", got[c]);
}
}
/// Removes what a build before Cineon Converter version 2 did not write into an animation
/// preset: format 1, and no `cineonVersion` on its properties.
fn preset_before_cineon_version_2(preset: &serde_json::Value) -> serde_json::Value {
let mut old = preset.clone();
old["effectcraftAnimationPreset"] = json!(1);
for p in old["properties"].as_array_mut().unwrap() {
p.as_object_mut().unwrap().remove("cineonVersion");
}
old
}
/// A Cineon Converter's Gamma saved alone in an animation preset records its instance's
/// version, and applying it sets the Version of the instance it lands on. A preset saved before
/// format 4 records none, and its Gamma lands on the instance as a version 1 value.
#[test]
fn cineon_gamma_presets_carry_the_version() {
let (mut s, a, _) = comp_with_two_solids();
let fx = apply(&mut s, a, "Cineon Converter");
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/gamma", "value": 1.3})).unwrap();
s.execute("prop.select", json!({"layer": a, "path": "effects/#1/gamma"})).unwrap();
let file = std::env::temp_dir().join(format!("ec-cineon-gamma-preset-{}.ecpreset", std::process::id()));
let saved = s.execute("anim.savePreset", json!({"path": file})).unwrap();
assert_eq!(saved["properties"], json!(1));
let preset: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
assert_eq!(preset["effectcraftAnimationPreset"], json!(4));
assert_eq!(preset["properties"][0]["path"], json!("effects/ec.utility.cineon/gamma"));
assert_eq!(preset["properties"][0]["cineonVersion"], json!(2.0));
let get = |s: &Session, id: &str| layer(s, a).effects().unwrap().groups().next().unwrap().get(id).unwrap().value.clone();
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/version", "value": 1.0})).unwrap();
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/gamma", "value": 4.0})).unwrap();
let r = s.execute("anim.applyPreset", json!({"preset": preset.clone(), "layers": [a]})).unwrap();
assert_eq!((&r["applied"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
assert_eq!((get(&s, "gamma"), get(&s, "version")), (KV::Scalar(1.3), KV::Scalar(2.0)));
s.execute("anim.applyPreset", json!({"preset": preset_before_cineon_version_2(&preset), "layers": [a]})).unwrap();
assert_eq!((get(&s, "gamma"), get(&s, "version")), (KV::Scalar(1.3), KV::Scalar(1.0)));
// Format 2 already had relative effect keys and format 3 whole text animators, but their
// Gammas had no version tag.
for format in [2, 3] {
s.execute("anim.applyPreset", json!({"preset": preset.clone(), "layers": [a]})).unwrap();
assert_eq!(get(&s, "version"), KV::Scalar(2.0), "format {format}");
let mut untagged = preset.clone();
untagged["effectcraftAnimationPreset"] = json!(format);
untagged["properties"][0].as_object_mut().unwrap().remove("cineonVersion");
s.execute("anim.applyPreset", json!({"preset": untagged, "layers": [a]})).unwrap();
assert_eq!((get(&s, "gamma"), get(&s, "version")), (KV::Scalar(1.3), KV::Scalar(1.0)), "format {format}");
}
// A whole Cineon Converter from a preset saved before version 2 is applied as version 1,
// and a Gamma preset applied to it later sets its Version.
select_effect(&mut s, a, fx);
let file = std::env::temp_dir().join(format!("ec-cineon-effect-preset-{}.ecpreset", std::process::id()));
s.execute("anim.savePreset", json!({"path": file})).unwrap();
let mut effect: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
effect["effects"][0]["children"].as_array_mut().unwrap().retain(|c| c["match"] != json!("version"));
s.execute("anim.applyPreset", json!({"preset": effect, "layers": [a]})).unwrap();
let second = |s: &Session, id: &str| layer(s, a).effects().unwrap().groups().nth(1).unwrap().get(id).map(|p| p.value.clone());
assert_eq!(second(&s, "version"), Some(KV::Scalar(1.0)));
let mut onto_second = preset;
for p in onto_second["properties"].as_array_mut().unwrap() {
p["path"] = json!(p["path"].as_str().unwrap().replace("ec.utility.cineon", "ec.utility.cineon#2"));
}
s.execute("anim.applyPreset", json!({"preset": onto_second, "layers": [a]})).unwrap();
assert_eq!((second(&s, "gamma"), second(&s, "version")), (Some(KV::Scalar(1.3)), Some(KV::Scalar(2.0))));
}
/// A Gamma preset records the Version its Cineon Converter has at the time it is saved. Applied
/// to a Cineon Converter whose Version is keyframed, it keeps the keys and is converted to the
/// one version they hold, or skipped when they hold several. A nested Cineon Converter's
/// keyframed Version counts only when its keys that play hold one value.
#[test]
fn cineon_gamma_presets_follow_a_keyframed_version() {
let (mut s, a, _) = comp_with_two_solids();
apply(&mut s, a, "Cineon Converter");
for (time, value) in [(0.0, 2.0), (1.0, 1.0)] {
s.execute("prop.addKey", json!({"layer": a, "path": "effects/#1/version", "time": time, "value": value})).unwrap();
}
s.execute("time.set", json!({"time": 2.0})).unwrap();
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/gamma", "value": 1.3})).unwrap();
s.execute("prop.select", json!({"layer": a, "path": "effects/#1/gamma"})).unwrap();
let file = std::env::temp_dir().join(format!("ec-cineon-keyed-version-{}.ecpreset", std::process::id()));
s.execute("anim.savePreset", json!({"path": file})).unwrap();
let preset: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
assert_eq!(preset["properties"][0]["cineonVersion"], json!(1.0));
// Applied to a Cineon Converter whose Version keys hold more than one version, the Gamma is
// skipped and the keys stay.
let get = |s: &Session, id: &str| layer(s, a).effects().unwrap().groups().next().unwrap().get(id).unwrap().clone();
let keys = get(&s, "version").keys;
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/gamma", "value": 4.0})).unwrap();
let err = s.execute("anim.applyPreset", json!({"preset": preset.clone(), "layers": [a]})).unwrap_err();
assert!(err.to_string().contains("nothing in this preset fits"), "{err}");
assert_eq!((get(&s, "gamma").value, get(&s, "version").keys), (KV::Scalar(4.0), keys));
// When the keys hold one version, the Gamma is converted to it and the keys stay.
s.execute("prop.addKey", json!({"layer": a, "path": "effects/#1/version", "time": 0.0, "value": 1.0})).unwrap();
let keys = get(&s, "version").keys;
let mut version_2 = preset;
version_2["properties"][0]["cineonVersion"] = json!(2.0);
let r = s.execute("anim.applyPreset", json!({"preset": version_2.clone(), "layers": [a]})).unwrap();
assert_eq!((&r["applied"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
let gamma = get(&s, "gamma").value.as_f64();
assert!((gamma - 1.3 * 1.7).abs() < 1e-9, "{gamma}");
assert_eq!(get(&s, "version").keys, keys);
// Keys of one value that ease with a speed move the Version between them, so the Gamma is
// skipped. A muted key of another value does not count, and neither does the ease of a key
// with no other key that plays.
let cid = s.active_comp_id().unwrap();
let fx = layer(&s, a).effects().unwrap().groups().next().unwrap().uid;
let edit_keys = |s: &mut Session, f: &dyn Fn(&mut [effectcraft_keyframe::Keyframe])| {
s.edit("keys", None, |project, _| {
let pr = project.comp_mut(cid).unwrap().layer_mut(LayerId(a)).unwrap().props.find_group_mut(fx).unwrap().get_mut("version").unwrap();
f(&mut pr.keys);
Ok(())
})
.unwrap();
};
edit_keys(&mut s, &|keys| {
keys[0].out_interp = Interp::Bezier;
keys[0].out_ease = vec![Ease { speed: 3.0, influence: 50.0 }];
});
let mut with_gamma = version_2.clone();
with_gamma["properties"].as_array_mut().unwrap().push(json!({"path": "transform/opacity", "value": KV::Scalar(80.0), "keys": []}));
let r = s.execute("anim.applyPreset", json!({"preset": with_gamma, "layers": [a]})).unwrap();
assert_eq!(r["skipped"], json!(["effects/ec.utility.cineon/gamma"]), "{r}");
edit_keys(&mut s, &|keys| {
keys[1].value = KV::Scalar(2.0);
keys[1].muted = true;
});
s.execute("prop.set", json!({"layer": a, "path": "effects/#1/gamma", "value": 4.0})).unwrap();
s.execute("anim.applyPreset", json!({"preset": version_2.clone(), "layers": [a]})).unwrap();
let gamma = get(&s, "gamma").value.as_f64();
assert!((gamma - 1.3 * 1.7).abs() < 1e-9, "{gamma}");
// A preset that holds the Version after the Gamma sets the Version, and the Gamma lands as
// saved.
edit_keys(&mut s, &|keys| keys[1].muted = false);
let mut both = version_2;
both["properties"].as_array_mut().unwrap().push(json!({"path": "effects/ec.utility.cineon/version", "value": KV::Scalar(2.0), "keys": []}));
let r = s.execute("anim.applyPreset", json!({"preset": both.clone(), "layers": [a]})).unwrap();
assert_eq!((&r["applied"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
let version = get(&s, "version");
assert_eq!((get(&s, "gamma").value, version.value, version.keys.len()), (KV::Scalar(1.3), KV::Scalar(2.0), 0));
// Listed before the Gamma, the preset's Version stays as the preset has it.
let mut first = both.clone();
let props = first["properties"].as_array_mut().unwrap();
let saved_version = props.pop().unwrap();
props.insert(0, saved_version);
props[0]["value"] = json!(KV::Scalar(1.0));
s.execute("anim.applyPreset", json!({"preset": first.clone(), "layers": [a]})).unwrap();
assert_eq!((get(&s, "gamma").value, get(&s, "version").value), (KV::Scalar(1.3), KV::Scalar(1.0)));
// A Version of another type is skipped, and the Gamma sets the Version it was saved with.
first["properties"][0]["value"] = json!(KV::Bool(true));
s.execute("anim.applyPreset", json!({"preset": first, "layers": [a]})).unwrap();
assert_eq!(get(&s, "version").value, KV::Scalar(2.0));
// A Version that an expression sets has no version to record or convert to.
s.execute("prop.setExpression", json!({"layer": a, "path": "effects/#1/version", "expression": "1"})).unwrap();
s.execute("prop.select", json!({"layer": a, "path": "effects/#1/gamma"})).unwrap();
let file = std::env::temp_dir().join(format!("ec-cineon-version-expression-{}.ecpreset", std::process::id()));
s.execute("anim.savePreset", json!({"path": file})).unwrap();
let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
assert_eq!(saved["properties"][0]["cineonVersion"], json!(null));
let mut tagged = saved;
tagged["properties"][0]["cineonVersion"] = json!(2.0);
tagged["properties"].as_array_mut().unwrap().push(json!({"path": "transform/opacity", "value": KV::Scalar(80.0), "keys": []}));
let r = s.execute("anim.applyPreset", json!({"preset": tagged, "layers": [a]})).unwrap();
assert_eq!(r["skipped"], json!(["effects/ec.utility.cineon/gamma"]), "{r}");
// A Gamma exposed from a nested comp records a keyframed Version only when its keys all
// hold one value.
for (second, recorded) in [(1.0, json!(null)), (2.0, json!(2.0))] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Inner", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let inner = s.active_comp_id().unwrap();
let solid = s.execute("layer.newSolid", json!({"width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
apply(&mut s, solid, "Cineon Converter");
for (time, value) in [(0.0, 2.0), (1.0, second)] {
s.execute("prop.addKey", json!({"layer": solid, "path": "effects/#1/version", "time": time, "value": value})).unwrap();
}
let control = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/gamma"})).unwrap()["controls"][0].as_u64().unwrap();
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let instance = s.execute("layer.addItem", json!({"item": inner.0})).unwrap()["layer"].as_u64().unwrap();
let path = format!("essential/{}", effectcraft_project::essential::match_id(control));
s.execute("prop.select", json!({"layer": instance, "path": path})).unwrap();
let file = std::env::temp_dir().join(format!("ec-cineon-keyed-nested-{}-{second}.ecpreset", std::process::id()));
s.execute("anim.savePreset", json!({"path": file})).unwrap();
let preset: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
assert_eq!(preset["properties"][0]["cineonVersion"], recorded, "second key {second}");
}
}
/// A Gamma exposed through Essential Properties (directly, or again from a middle comp) is
/// converted to the version of the Cineon Converter it drives when the preset was saved with
/// another version, or before version 2. A control that also drives another property keeps the
/// saved value.
#[test]
fn presets_convert_exposed_cineon_gamma_to_the_driven_version() {
for nested in [false, true] {
for mixed in [false, true] {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Inner", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let mut source = s.active_comp_id().unwrap();
let solid = s.execute("layer.newSolid", json!({"width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
apply(&mut s, solid, "Cineon Converter");
let mut control = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/gamma"})).unwrap()["controls"][0].as_u64().unwrap();
if mixed {
s.execute("essential.linkProperty", json!({"control": control, "layer": solid, "path": "transform/opacity"})).unwrap();
}
if nested {
s.execute("comp.new", json!({"name": "Middle", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let middle = s.active_comp_id().unwrap();
let instance = s.execute("layer.addItem", json!({"item": source.0})).unwrap()["layer"].as_u64().unwrap();
let path = format!("essential/{}", effectcraft_project::essential::match_id(control));
control = s.execute("essential.addProperty", json!({"layer": instance, "path": path})).unwrap()["controls"][0].as_u64().unwrap();
source = middle;
}
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap();
let instance = s.execute("layer.addItem", json!({"item": source.0})).unwrap()["layer"].as_u64().unwrap();
let path = format!("essential/{}", effectcraft_project::essential::match_id(control));
s.execute("essential.set", json!({"layer": instance, "control": control, "value": 2.2})).unwrap();
s.execute("prop.select", json!({"layer": instance, "path": path})).unwrap();
let file = std::env::temp_dir().join(format!("ec-cineon-exposed-preset-{}-{nested}-{mixed}.ecpreset", std::process::id()));
s.execute("anim.savePreset", json!({"path": file})).unwrap();
let preset: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
std::fs::remove_file(file).unwrap();
assert_eq!(preset["properties"][0]["path"], json!(path));
let recorded = if mixed { json!(null) } else { json!(2.0) };
assert_eq!(preset["properties"][0]["cineonVersion"], recorded, "nested={nested}, mixed={mixed}");
let mut as_version_1 = preset.clone();
as_version_1["properties"][0]["cineonVersion"] = json!(1.0);
let cases = [(preset.clone(), 2.2), (preset_before_cineon_version_2(&preset), 2.2 / 1.7), (as_version_1, 2.2 / 1.7)];
for (i, (preset, converted)) in cases.into_iter().enumerate() {
s.execute("essential.set", json!({"layer": instance, "control": control, "value": 0.5})).unwrap();
let result = s.execute("anim.applyPreset", json!({"preset": preset, "layers": [instance]})).unwrap();
assert_eq!(result["skipped"], json!([]));
let value = s.execute("prop.get", json!({"layer": instance, "path": path})).unwrap()["value"].as_f64().unwrap();
let expected = if mixed { 2.2 } else { converted };
assert!((value - expected).abs() < 1e-9, "nested={nested}, mixed={mixed}, case {i}: {value} != {expected}");
}
// With an expression, a Gamma saved on another version is skipped. It is the only
// property in the preset, so nothing is applied and the command reports that.
let mut with_expression = preset_before_cineon_version_2(&preset);
with_expression["properties"][0]["expression"] = json!({"text": "1.7", "enabled": true});
s.execute("essential.set", json!({"layer": instance, "control": control, "value": 0.5})).unwrap();
let steps = s.history.undo.len();
let result = s.execute("anim.applyPreset", json!({"preset": with_expression.clone(), "layers": [instance]}));
if mixed {
assert_eq!(result.unwrap()["skipped"], json!([]), "nested={nested}");
} else {
assert!(result.unwrap_err().to_string().contains("nothing in this preset fits"), "nested={nested}");
assert_eq!(s.history.undo.len(), steps, "nested={nested}");
// Beside a property that fits, the Gamma is listed as skipped.
let mut with_opacity = with_expression;
with_opacity["properties"].as_array_mut().unwrap().push(json!({"path": "transform/opacity", "value": KV::Scalar(80.0), "keys": []}));
let result = s.execute("anim.applyPreset", json!({"preset": with_opacity, "layers": [instance]})).unwrap();
assert_eq!((&result["applied"], &result["skipped"]), (&json!(1), &json!([path])), "nested={nested}");
}
let value = s.execute("prop.get", json!({"layer": instance, "path": path})).unwrap()["value"].as_f64().unwrap();
assert!((value - if mixed { 2.2 } else { 0.5 }).abs() < 1e-9, "nested={nested}, mixed={mixed}: {value}");
}
}
}
/// #410: `effect.warning` reports what an OCIO effect can't render as asked (Effect Controls
/// shows it under the effect's name): a transform of its custom config that passes colours
/// through, a colour space the config lacks or a config it can't read; nothing for the
+46
View File
@@ -40,6 +40,52 @@ fn move_into_folder_rename_label_comment_with_undo() {
assert_eq!(s.project.item(comp).unwrap().comment, "");
}
/// #3196: `project.newFolder` with `items` (items dropped on the Project panel's New Folder
/// button) makes the folder and moves them into it, out of the folder they were in, in one undo
/// step. A folder can't go into a new folder made inside itself.
#[test]
fn new_folder_with_items_moves_them_into_it_in_one_undo_step() {
let mut s = Session::default();
let a = ItemId(s.execute("comp.new", json!({"name": "A", "width": 64, "height": 64, "duration": 1})).unwrap()["comp"].as_u64().unwrap());
let b = ItemId(s.execute("comp.new", json!({"name": "B", "width": 64, "height": 64, "duration": 1})).unwrap()["comp"].as_u64().unwrap());
let bin = ItemId(s.execute("project.newFolder", json!({"name": "Bin"})).unwrap()["item"].as_u64().unwrap());
s.execute("project.move", json!({"items": [b.0], "folder": bin.0})).unwrap();
let before = s.project.clone();
let undo = s.history.undo.len();
let r = s.execute("project.newFolder", json!({"items": [a.0, "B", a.0]})).unwrap();
let f = ItemId(r["item"].as_u64().unwrap());
assert_eq!(r["moved"], 2, "duplicates count once");
let folder = s.project.item(f).unwrap();
assert!(folder.is_folder());
assert_eq!((folder.name.as_str(), folder.parent), ("Untitled Folder", None), "the New Folder button's name and place");
assert_eq!(s.project.item(a).unwrap().parent, Some(f));
assert_eq!(s.project.item(b).unwrap().parent, Some(f), "out of the folder it was in");
assert_eq!(s.state.project_selection, [f], "the new folder is selected");
assert_eq!(s.history.undo.len(), undo + 1, "one undo step");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project, before, "one undo takes back the folder and the move");
// A folder dropped on New Folder goes into the new folder; a new folder made inside the
// folder that is moving into it is refused, and nothing changes.
let r = s.execute("project.newFolder", json!({"items": [bin.0]})).unwrap();
let f = ItemId(r["item"].as_u64().unwrap());
assert_eq!(s.project.item(bin).unwrap().parent, Some(f));
s.execute("edit.undo", json!({})).unwrap();
// Inside another folder (`parent`), and an empty list moves nothing.
let r = s.execute("project.newFolder", json!({"parent": bin.0, "items": [a.0]})).unwrap();
let f = ItemId(r["item"].as_u64().unwrap());
assert_eq!((s.project.item(f).unwrap().parent, s.project.item(a).unwrap().parent), (Some(bin), Some(f)));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("project.newFolder", json!({"items": []})).unwrap()["moved"], 0);
s.execute("edit.undo", json!({})).unwrap();
let before = s.project.clone();
assert!(s.execute("project.newFolder", json!({"parent": bin.0, "items": [bin.0]})).is_err());
assert!(s.execute("project.newFolder", json!({"items": [999_999]})).is_err(), "an unknown item");
assert!(s.execute("project.newFolder", json!({"items": a.0})).is_err(), "not an array");
assert_eq!(s.project, before);
}
#[test]
fn delete_and_duplicate_items() {
let mut s = Session::default();
+1
View File
@@ -173,6 +173,7 @@ fn background_imports_report_progress_and_select_what_arrived() {
s.execute("jobs.wait", json!({})).unwrap();
assert_eq!(s.active_comp().unwrap().layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["c.png"]);
assert_eq!(s.job_log.last().unwrap().message, "Imported 1 item. /drop/d.xyz: unsupported file");
assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::Toast { message, error: true } if message.contains("/drop/d.xyz"))));
// Agents and scripts import at once by default.
let r = s.execute("file.import", json!({"paths": ["/drop/e.png"]})).unwrap();
assert_eq!(r["items"].as_array().map(Vec::len), Some(1));
+44 -1
View File
@@ -139,7 +139,7 @@ fn one_selected_property_saves_its_whole_animator() {
let end = saved[0].prop("selectors/rangeSelector/end").unwrap().uid;
let path = save(&mut s, "one-property", source, &[end]);
let file: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(file["effectcraftAnimationPreset"], 3);
assert_eq!(file["effectcraftAnimationPreset"], 4);
assert_eq!(file["properties"], json!([]));
assert_eq!(file["textAnimators"].as_array().unwrap().len(), 1);
let target = new_text(&mut s, "Target");
@@ -338,6 +338,49 @@ fn an_older_preset_updates_animators_and_asks_to_be_saved_again_without_them() {
assert_eq!(s.history.undo.len(), steps);
}
/// A format 3 preset holds whole animators, and its Cineon Converter Gamma has no
/// `cineonVersion`. Its animators are made on the layer and its Gamma lands as a version 1
/// value. The same preset in format 4 keeps the Gamma's version 2. A loose animator path in a
/// format 3 preset is not reported as saved by an earlier version.
#[test]
fn a_format_3_preset_applies_its_animators_and_a_version_1_cineon_gamma() {
let mut s = session();
let source = new_text(&mut s, "Source");
let animator = fade_on(&mut s, source, "Fade In");
let cineon = |s: &Session, layer: u64, id: &str| {
let l = s.active_comp().unwrap().layer(LayerId(layer)).unwrap();
l.effects().unwrap().groups().next().unwrap().prop(id).unwrap().clone()
};
s.execute("effect.apply", json!({"layers": [source], "effect": "Cineon Converter"})).unwrap();
s.execute("prop.set", json!({"layer": source, "path": "effects/#1/gamma", "value": 1.3})).unwrap();
let gamma = cineon(&s, source, "gamma").uid;
let path = save(&mut s, "format-3", source, &[animator, gamma]);
let format_4: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
let _ = std::fs::remove_file(&path);
assert_eq!(format_4["effectcraftAnimationPreset"], 4);
assert_eq!(format_4["textAnimators"].as_array().unwrap().len(), 1);
assert_eq!(format_4["properties"][0]["cineonVersion"], json!(2.0));
let mut format_3 = format_4.clone();
format_3["effectcraftAnimationPreset"] = json!(3);
format_3["properties"][0].as_object_mut().unwrap().remove("cineonVersion");
for (preset, version) in [(format_3, 1.0), (format_4, 2.0)] {
let target = new_text(&mut s, "Target");
s.execute("effect.apply", json!({"layers": [target], "effect": "Cineon Converter"})).unwrap();
assert_eq!(cineon(&s, target, "version").value, KV::Scalar(2.0));
let r = s.execute("anim.applyPreset", json!({"preset": preset, "layers": [target]})).unwrap();
assert_eq!((r["applied"].as_u64(), r["skipped"].clone()), (Some(2), json!([])), "version {version}");
assert_eq!(names(&s, target), ["Fade In"], "version {version}");
assert_eq!((cineon(&s, target, "gamma").value, cineon(&s, target, "version").value), (KV::Scalar(1.3), KV::Scalar(version)));
}
let loose = json!({"effectcraftAnimationPreset": 3, "properties": [{"path": "text/animators/animator/properties/opacity", "value": KV::Scalar(40.0), "keys": []}], "effects": []});
let fresh = new_text(&mut s, "Fresh");
let message = s.execute("anim.applyPreset", json!({"preset": loose, "layers": [fresh]})).unwrap_err().to_string();
assert!(message.contains("nothing in this preset fits the selected layer(s)"), "{message}");
assert!(!message.contains("save it again"), "{message}");
}
/// A malformed file, or a key that can't move to a later layer's playhead, is an error that
/// changes nothing, on the layers before it too.
#[test]
+58
View File
@@ -1556,6 +1556,64 @@ fn a_typed_component_applies_only_that_component_to_the_selected_layers() {
assert_eq!(pos(&s, c), vec![1.0, 2.0, 3.0]);
}
/// #3195: a typed `*2` or `/2` with several layers selected scales each layer's own value (in
/// the typed components of a vector), not the edited layer's result.
#[test]
fn a_typed_factor_scales_each_selected_layers_own_value() {
let (mut s, a) = setup();
let b = s.execute("layer.newSolid", json!({"color": "#ff0000", "width": 50, "height": 50})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": a, "path": "transform/opacity", "value": 40.0})).unwrap();
s.execute("prop.set", json!({"layer": b, "path": "transform/opacity", "value": 30.0})).unwrap();
s.execute("prop.set", json!({"layer": a, "path": "transform/position", "value": [10.0, 20.0]})).unwrap();
s.execute("prop.set", json!({"layer": b, "path": "transform/position", "value": [100.0, 50.0]})).unwrap();
s.execute("layer.select", json!({"layers": [a, b]})).unwrap();
let opacity = prop(&s, a, "transform/opacity").uid;
let undo = s.history.undo.len();
s.execute_checked("prop.set", json!({"layer": a, "prop": opacity, "value": 80.0, "selected": true, "factor": 2.0})).unwrap();
assert_eq!(prop(&s, a, "transform/opacity").value.as_f64(), 80.0);
assert_eq!(prop(&s, b, "transform/opacity").value.as_f64(), 60.0, "B doubles its own 30");
assert_eq!(s.history.undo.len(), undo + 1, "one undo step");
let position = prop(&s, a, "transform/position").uid;
s.execute_checked("prop.set", json!({"layer": a, "prop": position, "value": [5.0, 20.0], "selected": true, "dims": [0], "factor": 0.5})).unwrap();
assert_eq!(prop(&s, a, "transform/position").value.components()[..2], [5.0, 20.0]);
assert_eq!(prop(&s, b, "transform/position").value.components()[..2], [50.0, 50.0], "B halves its own X, keeps its Y");
// A typed `+10` (`addend`): each layer's own value plus 10, within its own range, even where
// the edited layer's range cut its change short (95 + 10 stops at 100).
s.execute("prop.set", json!({"layer": a, "path": "transform/opacity", "value": 95.0})).unwrap();
s.execute("prop.set", json!({"layer": b, "path": "transform/opacity", "value": 30.0})).unwrap();
s.execute_checked("prop.set", json!({"layer": a, "prop": opacity, "value": 100.0, "selected": true, "addend": 10.0})).unwrap();
assert_eq!(prop(&s, b, "transform/opacity").value.as_f64(), 40.0, "B adds 10, not the 5 A moved");
s.execute("prop.set", json!({"layer": b, "path": "transform/opacity", "value": 95.0})).unwrap();
s.execute_checked("prop.set", json!({"layer": a, "prop": opacity, "value": 100.0, "selected": true, "addend": 10.0})).unwrap();
assert_eq!(prop(&s, b, "transform/opacity").value.as_f64(), 100.0, "B's own range still applies");
s.execute_checked("prop.set", json!({"layer": a, "prop": position, "value": [15.0, 20.0], "selected": true, "dims": [0], "addend": 10.0})).unwrap();
assert_eq!(prop(&s, b, "transform/position").value.components()[..2], [60.0, 50.0], "B adds 10 to its own X");
}
/// #3195: Mask Feather is never negative on the other selected layers either, when a typed `*-1`
/// (the edited layer clamped at 0 by the panel) or a change by the same amount takes theirs
/// below 0.
#[test]
fn a_selected_mask_feather_stays_non_negative() {
let (mut s, a) = setup();
let b = s.execute("layer.newSolid", json!({"color": "#ff0000", "width": 50, "height": 50})).unwrap()["layer"].as_u64().unwrap();
for (l, feather) in [(a, [10.0, 20.0]), (b, [4.0, 30.0])] {
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [20, 0], [20, 20]]})).unwrap();
s.execute("prop.set", json!({"layer": l, "path": "masks/#1/feather", "value": feather})).unwrap();
}
s.execute("layer.select", json!({"layers": [a, b]})).unwrap();
let feather = |s: &Session, l: u64| prop(s, l, "masks/#1/feather").value.components();
let uid = prop(&s, a, "masks/#1/feather").uid;
// `*-1` into the linked pair: the panel clamps the edited layer at [0, 0].
s.execute_checked("prop.set", json!({"layer": a, "prop": uid, "value": [0.0, 0.0], "selected": true, "dims": [0, 1], "factor": -1.0})).unwrap();
assert_eq!(feather(&s, a), [0.0, 0.0]);
assert_eq!(feather(&s, b), [0.0, 0.0], "B is clamped at 0, not [-4, -30]");
// A change by the same amount (a scrub, or a typed `+`): A by [-10, -15] from [10, 20].
s.execute("edit.undo", json!({})).unwrap();
s.execute_checked("prop.set", json!({"layer": a, "prop": uid, "value": [0.0, 5.0], "selected": true, "offset": true})).unwrap();
assert_eq!(feather(&s, b), [0.0, 15.0], "B's X is clamped at 0, its Y moves by -15");
}
/// #2485: linked Audio Levels typed with several layers selected: each takes the typed Left, and
/// its Right moves by its own change, so every layer keeps its own stereo balance.
#[test]
+55
View File
@@ -433,3 +433,58 @@ fn analyze_1080p_single_point_speed() {
assert!(dist(fc.value_at(frame_time(30)).as_vec2(), [990.0, 555.0]) < 0.25);
assert!(fps > 30.0, "{fps} frames/s");
}
/// A stand-in for `sampleImage()` on a footage layer (the engine has no expression language): the
/// pixel at (0, 0) of the layer's footage, read through the context's footage source. The real
/// one samples transparent without the source; this one fails, so either symptom shows.
struct SampleFootage;
impl crate::render::ExprHost for SampleFootage {
/// Reads the red channel of the layer's footage pixel at (0, 0) through the context's footage source, scaled to 0-100.
fn eval(
&self,
ctx: &EvalCtx,
layer: &effectcraft_project::Layer,
_: &effectcraft_project::Property,
_: &effectcraft_keyframe::Value,
) -> Result<effectcraft_keyframe::Value, String> {
let item = layer.source.item().ok_or("not a footage layer")?;
let Some(ItemKind::Footage(footage)) = ctx.project.item(item).map(|i| &i.kind) else { return Err("not a footage layer".into()) };
let src = ctx.footage.ok_or("sampleImage: no footage source")?;
let img = src.frame(item, footage, ctx.time).ok_or("no frame")?;
Ok(effectcraft_keyframe::Value::Scalar(f64::from(img.get(0, 0)[0]) * 100.0))
}
}
/// The clip of [`setup`] (uniform 25 % grey footage) with an opacity expression that samples its
/// footage: 25 with the footage source. Here for `setup`'s footage layer (#3231).
fn sampling_clip() -> (Session, ItemId, LayerId) {
let (mut s, clip, _) = setup(|_| Image::filled(W, H, [0.25, 0.25, 0.25, 1.0]));
let cid = s.active_comp_id().unwrap();
s.expr = Some(Arc::new(SampleFootage));
s.execute("prop.setExpression", json!({"layer": clip.0, "path": "transform/opacity", "expression": "sampleImage([0, 0])[0] * 100"})).unwrap();
(s, cid, clip)
}
/// #3231: `prop.get` evaluates an expression that samples footage pixels with the footage source,
/// as the render and `expr.errors` do: the same value and no spurious `expressionError`.
#[test]
fn prop_get_evaluates_footage_sampling_expressions_with_the_footage_source() {
let (mut s, cid, clip) = sampling_clip();
let got = s.execute("prop.get", json!({"layer": clip.0, "path": "transform/opacity", "time": 0.0})).unwrap();
assert!(got.get("expressionError").is_none(), "no spurious error: {got}");
assert_eq!(got["evaluated"].as_f64(), Some(25.0), "the footage pixel, not the keyframed 100: {got}");
// The render applies the same opacity: the clip alone (outside the solid) covers 25 %.
let img = s.render(cid, Tick::ZERO, crate::render::RenderOpts::default());
let a = img.get(5, 5)[3];
assert!((a - 0.25).abs() < 0.01, "rendered opacity {a}");
assert!(crate::cmd::expr_tools::errors(&s, cid, Tick::ZERO).is_empty());
}
/// #3231: Reveal Expression Errors and the viewer's error banner evaluate with the footage source,
/// so an expression that samples footage pixels isn't reported as failing.
#[test]
fn expression_errors_evaluate_footage_sampling_expressions_with_the_footage_source() {
let (s, cid, _) = sampling_clip();
assert_eq!(s.expression_errors(cid), Vec::<serde_json::Value>::new());
}
+175 -1
View File
@@ -8,7 +8,9 @@ use effectcraft_time::Tick;
use serde_json::json;
use crate::Session;
use crate::viewer::{Channel, DisplayPass, FrameEncoding, PRI_GRID, PRI_GUIDE, PRI_LAYER, PRI_VERTEX, PassCurve, SnapKind, SnapSource, SnapTarget, snap};
use crate::viewer::{
Channel, DisplayPass, FrameEncoding, PRI_COMP, PRI_GRID, PRI_GUIDE, PRI_LAYER, PRI_VERTEX, PassCurve, SnapKind, SnapSource, SnapTarget, snap,
};
fn comp() -> Session {
let mut s = Session::default();
@@ -84,6 +86,46 @@ fn snap_point_beats_one_line_and_loses_only_to_two_nearer_lines() {
assert_eq!(s.hits, [v, h]);
}
/// #2681: a pair of lines, one of them through the point (the layer's own edge line), beats the
/// point only when it is clearly nearer (by `POINT_BIAS` of the tolerance, 2 of 8 here); a pair
/// only a little nearer leaves the feature on the point.
#[test]
fn a_line_pair_through_a_point_beats_it_only_by_a_clear_margin() {
use crate::viewer::POINT_BIAS;
assert_eq!(8.0 * POINT_BIAS, 2.0);
let src = SnapSource::Layer(LayerId(1));
let edge = SnapTarget::vline(100.0, PRI_LAYER, src);
let row = SnapTarget::hline(51.5, PRI_COMP, SnapSource::Comp);
// The point is 5 away; the pair (3 and ½) about 3.04, under 2 nearer: the point.
let pt = SnapTarget::point([100.0, 47.0], PRI_LAYER, src);
let s = snap(&[[103.0, 51.0]], &[edge, row, pt], 8.0).unwrap();
assert_eq!(s.hits, [pt]);
assert_eq!(s.at, [100.0, 47.0]);
// The point about 6.7 away, the same pair more than 2 nearer: the pair.
let far = SnapTarget::point([100.0, 45.0], PRI_LAYER, src);
let s = snap(&[[103.0, 51.0]], &[edge, row, far], 8.0).unwrap();
assert_eq!(s.hits, [edge, row]);
assert_eq!(s.at, [100.0, 51.5]);
}
/// #2681: two guides crossing 1 px beside a layer's point are reachable right next to it: a pair
/// of lines that both miss the point gets no margin, only the nearer one wins.
#[test]
fn a_guide_intersection_beside_a_point_stays_reachable() {
let src = SnapSource::Layer(LayerId(1));
let pt = SnapTarget::point([100.0, 50.0], PRI_LAYER, src);
let own = [SnapTarget::vline(100.0, PRI_LAYER, src), SnapTarget::hline(50.0, PRI_LAYER, src)];
let guides = [SnapTarget::vline(101.0, PRI_GUIDE, SnapSource::Guide), SnapTarget::hline(51.0, PRI_GUIDE, SnapSource::Guide)];
let t = [own[0], own[1], guides[0], guides[1], pt];
// Nearer the intersection (about 0.71) than the point (about 2.12): the intersection.
let s = snap(&[[101.5, 51.5]], &t, 8.0).unwrap();
assert_eq!(s.at, [101.0, 51.0]);
assert_eq!(s.hits, guides);
// Nearer the point: the point.
let s = snap(&[[100.3, 50.3]], &t, 8.0).unwrap();
assert_eq!(s.hits, [pt]);
}
/// #2855: an unrotated layer's centre lines follow its edges' span rule, reach the outer comp
/// through a collapsed precomp layer, and a rotated layer keeps its points only.
#[test]
@@ -116,6 +158,105 @@ fn layer_centre_lines_follow_the_edges() {
assert_eq!(lines(&at(&s, off), pre), (None, None));
}
/// #2681: two Ellipse-tool circles, one moved so its left point meets the other's right point.
/// The point must land exactly on the other circle's point at 100 % as at 200 % and 400 %, on
/// HiDPI displays too. The tolerance is the viewer's (8 screen points over the zoom in points per
/// comp pixel), so at 100 % it reaches the comp's centre row 6 px below the circles and a guide
/// 3 px below them. Neither may pull the circle off the point: the other circle's own edge line
/// and row pass through its point, so a pair of lines made with that row or guide is only a
/// little nearer than the point (the row or guide a few pixels nearer on y), and a point wins
/// unless a pair is clearly nearer (`POINT_BIAS`). Before #2855 one nearer line was enough, and
/// even after it any pair nearer by a hair; zoomed in the row and guide were out of reach, so
/// the snap looked right there and not at 100 %.
#[test]
fn circles_snap_point_to_point_at_every_zoom() {
circles_snap_point_to_point(false);
}
/// #2681 with the circles converted to Bezier paths (Convert To Bezier Path): the dragged path
/// point lands on the other circle's path point (a vertex target) the same way.
#[test]
fn bezier_circles_snap_path_point_to_path_point_at_every_zoom() {
circles_snap_point_to_point(true);
}
/// The #2681 drops: parametric circles (their edge midpoints snap) or, with `bezier`, the same
/// circles as Bezier paths (their path points snap).
fn circles_snap_point_to_point(bezier: bool) {
use crate::viewer::{SnapOptions, layer_features, layer_vertices, targets};
let mut s = comp();
// Circle A: 100 px, centred at (200, 174), its right point at (250, 174); the comp's centre
// row is y = 180, a horizontal guide at y = 177.
s.execute("view.addGuide", json!({"orientation": "horizontal", "position": 177})).unwrap();
let a = s.execute("shape.newShape", json!({"kind": "ellipse", "size": [100, 100], "position": [200, 174]})).unwrap()["layer"].as_u64().unwrap();
s.execute("edit.deselectAll", json!({})).unwrap();
let b = s.execute("shape.newShape", json!({"kind": "ellipse", "size": [100, 100], "position": [400, 300]})).unwrap()["layer"].as_u64().unwrap();
assert_ne!(a, b, "two shape layers");
if bezier {
for l in [a, b] {
/// Returns the uid of the first ellipse group in the tree, searching depth first.
fn ellipse(g: &effectcraft_project::PropGroup) -> Option<u64> {
if g.match_id == "ellipse" {
return Some(g.uid);
}
g.groups().find_map(ellipse)
}
let uid = ellipse(layer(&s, l).props.sub("contents").unwrap()).unwrap();
s.state.selected_props = vec![(LayerId(l), uid)];
s.execute("path.convertToBezier", json!({})).unwrap();
}
}
let cid = s.active_comp_id().unwrap();
// The circle's right (`right`) or left point: an edge midpoint of its box (features:
// corners, edge midpoints top, right, bottom, left, centre, anchor point), or a path point.
let point = |s: &Session, id: u64, right: bool| {
let comp = s.project.comp(cid).unwrap().clone();
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, &comp, Tick::ZERO);
let l = comp.layer(LayerId(id)).unwrap();
if !bezier {
return layer_features(&ctx, l)[if right { 5 } else { 7 }];
}
let v = layer_vertices(&ctx, l);
assert!(v.len() >= 4, "a Bezier circle: {v:?}");
let x = |p: &&[f64; 2]| p[0];
*(if right { v.iter().max_by(|p, q| x(p).total_cmp(&x(q))) } else { v.iter().min_by(|p, q| x(p).total_cmp(&x(q))) }).unwrap()
};
let near = |p: [f64; 2], q: [f64; 2], e: f64| (p[0] - q[0]).abs() < e && (p[1] - q[1]).abs() < e;
let right_of_a = point(&s, a, true);
assert!(near(right_of_a, [250.0, 174.0], 1e-6), "{right_of_a:?}");
let left_of_b = point(&s, b, false);
assert!(near(left_of_b, [350.0, 300.0], 1e-6), "{left_of_b:?}");
let to_left = [left_of_b[0] - 400.0, left_of_b[1] - 300.0];
let source = if bezier { SnapSource::Vertex(LayerId(a)) } else { SnapSource::Layer(LayerId(a)) };
// B's left point dropped right of and below A's right point (screen points): just off it,
// and nearer the comp's centre row (at 100 %) than A's own row. With and without snapping to
// the guide.
for (dx, dy) in [(3.0, 1.0), (3.0, 3.5)] {
for guides in [false, true] {
for ppp in [1.0, 1.25, 1.5] {
for magnification in [1.0, 2.0, 4.0] {
let case = format!("bezier {bezier}, drop ({dx}, {dy}) pt, guides {guides}, {magnification}x, ppp {ppp}");
// The viewer's zoom (points per comp pixel) and snap tolerance (`SNAP_PX / zoom`).
let zoom: f64 = magnification / ppp;
let tol = 8.0 / zoom;
let want = [right_of_a[0] + dx / zoom, right_of_a[1] + dy / zoom];
s.execute("prop.set", json!({"layer": b, "path": "transform/position", "value": [want[0] - to_left[0], want[1] - to_left[1], 0]})).unwrap();
let src = point(&s, b, false);
assert!(near(src, want, 1e-9), "{case}: {src:?} {want:?}");
let comp = s.project.comp(cid).unwrap().clone();
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, &comp, Tick::ZERO);
let t = targets(&ctx, &[LayerId(b)], SnapOptions { layers: true, guides, ..Default::default() });
let hit = snap(&[src], &t, tol).unwrap_or_else(|| panic!("{case}: nothing snapped"));
assert!(near(hit.at, right_of_a, 1e-9), "{case}: B's left point lands at {:?}, not on A's right point {right_of_a:?}", hit.at);
assert_eq!(hit.hits.len(), 1, "{case}: one point, not two lines: {:?}", hit.hits);
assert_eq!(hit.hits[0].kind, SnapKind::Point, "{case}");
assert_eq!(hit.hits[0].source, source, "{case}");
}
}
}
}
}
#[test]
fn snap_targets_cover_layers_comp_guides_and_grid() {
let mut s = comp();
@@ -1177,3 +1318,36 @@ fn polystar_undo_sanitizes_live_and_parked_property_selections_before_uid_reuse(
assert_eq!(layer(&s, lid).props.prop("transform/positionZ").unwrap(), &position_z, "the reused UID must not become an implicit expression target");
}
}
/// #3229: a drag Shift keeps to one axis snaps only that axis. A point a few pixels off the axis
/// lines the feature up with it (along x: its x) without taking it off the axis, as a line
/// through the point would; lines along the drag are left out, and the point reaches only `tol`
/// off the axis. Unconstrained (`snap`) the same point takes both coordinates, the feature leaving
/// the axis.
#[test]
fn a_shift_drag_snaps_only_along_its_axis() {
use crate::viewer::snap_along;
let src = SnapSource::Layer(LayerId(1));
let corner = SnapTarget::point([450.0, 150.0], PRI_LAYER, src);
let row = SnapTarget::hline(151.0, PRI_GUIDE, SnapSource::Guide);
let column = SnapTarget::vline(449.0, PRI_GUIDE, SnapSource::Guide);
let feature = [[448.0, 153.0]];
assert_eq!(snap(&feature, &[corner, row], 8.0).unwrap().at, [450.0, 150.0]);
// Along x: x onto the corner's, y kept (the nearer row does not pull it either).
let s = snap_along(&feature, &[corner, row], 8.0, true).unwrap();
assert_eq!(s.delta, [2.0, 0.0]);
assert_eq!(s.at, [450.0, 153.0]);
// The point, and the line from it to the feature (the feedback).
assert_eq!(s.hits, [corner, SnapTarget::vline(450.0, PRI_LAYER, src).within(Some([150.0, 153.0]))]);
// Along y: y onto the corner's, x kept (the column is left out).
let s = snap_along(&feature, &[corner, column], 8.0, false).unwrap();
assert_eq!(s.delta, [0.0, -3.0]);
assert_eq!(s.at, [448.0, 150.0]);
assert_eq!(s.hits, [corner, SnapTarget::hline(150.0, PRI_LAYER, src).within(Some([450.0, 448.0]))]);
// A line across the drag still snaps; a nearer one wins over the point.
let s = snap_along(&feature, &[corner, column], 8.0, true).unwrap();
assert_eq!(s.at, [449.0, 153.0]);
assert_eq!(s.hits, [column]);
// The point reaches only the tolerance off the axis.
assert_eq!(snap_along(&[[448.0, 170.0]], &[corner], 8.0, true), None);
}
+67 -4
View File
@@ -128,11 +128,23 @@ fn better(a: (f64, u8), b: (f64, u8)) -> bool {
if (a.0 - b.0).abs() < 1e-6 { a.1 < b.1 } else { a.0 < b.0 }
}
/// How much nearer (as a share of the tolerance: 2 of the viewer's 8 screen points, whatever the
/// zoom) a vertical and a horizontal line together must be than a point target to win over it
/// when one of the two lines runs through the point. A layer's point lies on that layer's own
/// edge and centre lines, so such a pair is only as near as the point itself plus whatever a
/// foreign line (the comp's centre row, a guide) gains on the other axis; without the margin that
/// pair took the foreign axis and left the feature just off the point, more often the wider the
/// tolerance is in comp pixels, i.e. at 100 % rather than zoomed in (#2681). A pair of lines that
/// both miss the point (a guide crossing beside a layer's point) gets no margin, so such an
/// intersection stays reachable right next to the point.
pub const POINT_BIAS: f64 = 0.25;
/// Snap feature points `sources` (comp pixels) to the nearest target within `tol` comp pixels.
/// A point target snaps both axes and wins unless a vertical and a horizontal line both resolve
/// and together lie nearer than it (one line alone leaves the other axis free, so it never beats
/// a point: a layer's edge midpoint lies on its edge line); otherwise the nearest vertical and
/// horizontal lines snap x and y independently. Ties go to the lower priority value.
/// and together lie nearer than it, by more than [`POINT_BIAS`] of `tol` when one of them runs
/// through the point (one line alone leaves the other axis free, so it never beats a point: a
/// layer's edge midpoint lies on its edge line); otherwise the nearest vertical and horizontal
/// lines snap x and y independently. Ties go to the lower priority value.
pub fn snap(sources: &[[f64; 2]], targets: &[SnapTarget], tol: f64) -> Option<Snap> {
let mut best_pt: Option<((f64, u8), [f64; 2], SnapTarget)> = None;
let mut best_x: Option<((f64, u8), [f64; 2], SnapTarget)> = None;
@@ -155,8 +167,15 @@ pub fn snap(sources: &[[f64; 2]], targets: &[SnapTarget], tol: f64) -> Option<Sn
}
}
let both_lines = best_x.zip(best_y).map_or(f64::INFINITY, |(x, y)| x.0.0.hypot(y.0.0));
// A line of the pair through the point: the point's own edge / centre line (`at`: the
// line's axis, 0 for x).
let through = |line: Option<((f64, u8), [f64; 2], SnapTarget)>, at: usize| {
best_pt.zip(line).is_some_and(|((_, _, p), (_, _, l))| (l.pos[at] - p.pos[at]).abs() < 1e-6)
};
// (At least a hair, so an exact tie goes to the point.)
let bias = if through(best_x, 0) || through(best_y, 1) { (tol * POINT_BIAS).max(1e-9) } else { 1e-9 };
if let Some((k, s, t)) = best_pt
&& k.0 <= both_lines + 1e-9
&& k.0 <= both_lines + bias
{
return Some(Snap { delta: [t.pos[0] - s[0], t.pos[1] - s[1]], hits: vec![t], at: t.pos });
}
@@ -189,6 +208,50 @@ pub fn layer_features(ctx: &EvalCtx, layer: &Layer) -> Vec<[f64; 2]> {
out
}
/// [`snap`] for a drag Shift keeps to one axis (`along_x`: it moves along x and y stays put, else
/// the other way round): only the free coordinate snaps, so the feature never leaves the axis
/// (#3229). A point target acts as a line through it across the drag (a vertical line at its x
/// for a drag along x) that reaches it only within `tol` on each axis (a square around the point),
/// so the feature lines up with a point near the axis, not with every point in the comp; lines
/// along the drag (horizontal ones for a drag along x) would only move the locked coordinate and
/// are left out. The nearest target wins, ties to the lower priority value. A hit on a point
/// reports the point (the feedback box) and the line from it to where the feature landed.
pub fn snap_along(sources: &[[f64; 2]], targets: &[SnapTarget], tol: f64, along_x: bool) -> Option<Snap> {
// (Key, source, target, and the free coordinate it snaps to.)
let mut best: Option<((f64, u8), [f64; 2], SnapTarget, f64)> = None;
for s in sources {
let (free, along) = if along_x { (s[0], s[1]) } else { (s[1], s[0]) };
for t in targets {
// The line the target snaps as: its coordinate and extent along it.
let (line, span) = match (t.kind, along_x) {
(SnapKind::Point, true) => (t.pos[0], Some([t.pos[1] - tol, t.pos[1] + tol])),
(SnapKind::Point, false) => (t.pos[1], Some([t.pos[0] - tol, t.pos[0] + tol])),
(SnapKind::VLine, true) => (t.pos[0], t.span),
(SnapKind::HLine, false) => (t.pos[1], t.span),
(SnapKind::VLine, false) | (SnapKind::HLine, true) => continue,
};
let d = (line - free).abs();
if d > tol || span.is_some_and(|[a, b]| along < a || along > b) {
continue;
}
let key = (d, t.priority);
if best.as_ref().is_none_or(|(k, _, _, _)| better(key, *k)) {
best = Some((key, *s, *t, line));
}
}
}
let (_, s, t, line) = best?;
let (delta, at) = if along_x { ([line - s[0], 0.0], [line, s[1]]) } else { ([0.0, line - s[1]], [s[0], line]) };
let mut hits = vec![t];
if t.kind == SnapKind::Point {
// The alignment, drawn from the point to the feature.
let (from, to) = if along_x { (t.pos[1], at[1]) } else { (t.pos[0], at[0]) };
let l = if along_x { SnapTarget::vline(line, t.priority, t.source) } else { SnapTarget::hline(line, t.priority, t.source) };
hits.push(l.within(Some([from, to])));
}
Some(Snap { delta, hits, at })
}
/// A layer's content box in comp space: corners (top left, top right, bottom right, bottom
/// left), edge midpoints (top, right, bottom, left) and centre.
struct BoxPoints {
+90 -25
View File
@@ -334,7 +334,7 @@ fn raw(item: &Item) -> Piece {
Item::Tok(t) => Piece { ws: t.ws.clone(), body: t.text.clone() },
Item::Group { open, inner, close } => {
let mut body = open.text.clone();
body.push_str(&rewrite_seq(inner));
body.push_str(&rewrite_seq(inner, open.text == "{"));
if let Some(c) = close {
body.push_str(&c.ws);
body.push_str(&c.text);
@@ -378,25 +378,7 @@ fn operand(items: &[Item], i: usize) -> Option<(Piece, usize)> {
};
return Some((Piece { ws: t.ws.clone(), body }, j));
}
let mut p = raw(first);
let mut j = i + 1;
// `function name(args) { body }` is one atom.
if first.tok().is_some_and(|t| t.is_kw(&["function"])) {
if items.get(j).is_some_and(|x| x.is("*")) {
push(&mut p, &items[j]);
j += 1;
}
if items.get(j).and_then(Item::tok).is_some_and(|t| t.kind == Kind::Ident) {
push(&mut p, &items[j]);
j += 1;
}
for g in ["(", "{"] {
if items.get(j).and_then(Item::group) == Some(g) {
push(&mut p, &items[j]);
j += 1;
}
}
}
let (mut p, mut j) = if is_function(first) { function_atom(items, i) } else { (raw(first), i + 1) };
// Postfix: member access, calls, indexing, tagged templates, `x++`.
while let Some(it) = items.get(j) {
let member = it.is(".") || it.is("?.");
@@ -428,6 +410,59 @@ fn operand(items: &[Item], i: usize) -> Option<(Piece, usize)> {
Some((p, j))
}
fn is_function(item: &Item) -> bool {
item.tok().is_some_and(|t| t.is_kw(&["function"]))
}
/// `function [*] [name] (args) { body }` from the `function` keyword at `i`, as one atom.
fn function_atom(items: &[Item], i: usize) -> (Piece, usize) {
let Some(first) = items.get(i) else {
// Unreachable for callers (they pass a `function` item); still advance so no loop stalls.
return (Piece { ws: String::new(), body: String::new() }, i.saturating_add(1));
};
let mut p = raw(first);
let mut j = i + 1;
if items.get(j).is_some_and(|x| x.is("*")) {
push(&mut p, &items[j]);
j += 1;
}
if items.get(j).and_then(Item::tok).is_some_and(|t| t.kind == Kind::Ident) {
push(&mut p, &items[j]);
j += 1;
}
for g in ["(", "{"] {
if items.get(j).and_then(Item::group) == Some(g) {
push(&mut p, &items[j]);
j += 1;
}
}
(p, j)
}
/// Is the `function` keyword at `i` at the start of a statement, so a function declaration
/// (ECMAScript: an expression statement cannot start with `function`)? A declaration ends at its
/// `}`: whatever follows is a new statement, never an operand of it. `stmts` says whether
/// `items` is a statement list (the whole expression or a `{ … }` block) rather than the inside
/// of `( … )` or `[ … ]`.
fn at_statement_start(items: &[Item], i: usize, stmts: bool) -> bool {
// `async function`: the statement starts at `async` (no line break may come between them).
let is_async = |k: usize| items.get(k).and_then(Item::tok).is_some_and(|a| a.is_kw(&["async"]));
let at = match i.checked_sub(1) {
Some(k) if is_async(k) && !items.get(i).is_some_and(Item::nl) => k,
_ => i,
};
let Some(prev) = at.checked_sub(1).and_then(|k| items.get(k)) else {
return stmts;
};
match prev {
// A block, an `if (…)`/`while (…)` header or a value the line break ends.
Item::Group { .. } => true,
// Known limit: after a label, `case …:` or `default:` a declaration is still read as an
// expression (that `:` cannot be told from an object literal's or a conditional's here).
Item::Tok(t) => t.is(";") || t.is_kw(&["else", "do"]) || ends_value(t),
}
}
fn push(p: &mut Piece, item: &Item) {
let r = raw(item);
p.body.push_str(&r.ws);
@@ -510,7 +545,9 @@ fn assignment_end(items: &[Item], i: usize) -> usize {
j
}
fn rewrite_seq(items: &[Item]) -> String {
/// Rewrite a sequence of items. `stmts`: the sequence is a statement list (the whole expression
/// or the inside of `{ … }`), not the inside of `( … )` or `[ … ]`.
fn rewrite_seq(items: &[Item], stmts: bool) -> String {
let mut out = String::new();
let mut i = 0;
while i < items.len() {
@@ -521,12 +558,20 @@ fn rewrite_seq(items: &[Item]) -> String {
i += 2;
continue;
}
// A function declaration ends at its `}` (#3212): `function f() {}\n-1` is two statements,
// so the next line must not become an operand (`__sub(function f() {}, 1)` is NaN).
if is_function(it) && at_statement_start(items, i, stmts) {
let (p, j) = function_atom(items, i);
push_piece(&mut out, p);
i = j;
continue;
}
if let Some((p, j)) = chain(items, i) {
// Compound assignment: `x += v` → `x = __add(x, (v))` (the target is evaluated twice,
// which only matters for targets with side effects).
if let Some(op) = items.get(j).and_then(Item::tok).filter(|t| t.kind == Kind::Punct && matches!(t.text.as_str(), "+=" | "-=" | "*=" | "/=")) {
let end = assignment_end(items, j + 1);
let rhs = rewrite_seq(&items[j + 1..end]);
let rhs = rewrite_seq(&items[j + 1..end], false);
let h = helper(&op.text[..1]).unwrap_or("__add");
let target = compound_assignment_target(items, i, j);
out.push_str(&p.ws);
@@ -555,7 +600,7 @@ fn raw_ref(item: &Item) -> String {
out.push_str(&raw_ref(item));
}
} else {
out.push_str(&rewrite_seq(inner));
out.push_str(&rewrite_seq(inner, open.text == "{"));
}
if let Some(close) = close {
out.push_str(&close.text);
@@ -794,7 +839,7 @@ pub fn check_nesting(src: &str) -> Result<(), String> {
if too_nested(&toks) {
return Err(too_deep());
}
let mut out = rewrite_seq(&build(toks));
let mut out = rewrite_seq(&build(toks), true);
out.push_str(&tail);
if over_rewrite_limit(&out) {
return Err(too_large());
@@ -825,7 +870,7 @@ pub fn rewrite(src: &str) -> String {
if too_nested(&toks) {
return throw_too_deep();
}
let mut out = rewrite_seq(&build(toks));
let mut out = rewrite_seq(&build(toks), true);
out.push_str(&tail);
if over_rewrite_limit(&out) {
return throw_too_large();
@@ -897,6 +942,26 @@ mod tests {
assert_eq!(n(&rewrite("2 ** 3 * 2")), n("__mul(2 ** 3, 2)"));
}
#[test]
fn a_function_declaration_is_not_an_operand_of_the_next_statement() {
// #3212: a declaration ends at its `}` (an expression statement cannot start with
// `function`), so a following `-`, `+` or `[` starts a new statement.
assert_eq!(n(&rewrite("function f(x){ return x; }\n-50 + 100")), n("function f(x){ return x; }\n__add(-50, 100)"));
assert_eq!(n(&rewrite("function f(){}\n+a - b")), n("function f(){}\n__sub(+a, b)"));
assert_eq!(n(&rewrite("function f(){}\n[1, 2] - [1, 1]")), n("function f(){}\n__sub([1, 2], [1, 1])"));
assert_eq!(n(&rewrite("function f(){}\n(a) - b")), n("function f(){}\n__sub((a), b)"));
assert_eq!(n(&rewrite("function* g(){} -x")), n("function* g(){} __neg(x)"));
assert_eq!(n(&rewrite("async function f(){}\n-x")), n("async function f(){}\n__neg(x)"));
assert_eq!(n(&rewrite("var a = 1;function f(){}\n-x")), n("var a = 1;function f(){}\n__neg(x)"));
assert_eq!(n(&rewrite("if (a) { function f(){}\n-b }")), n("if (a) { function f(){}\n__neg(b) }"));
// Function expressions stay operands, whatever follows on the next line.
assert_eq!(n(&rewrite("x = function(a){ return a } - 1")), n("x = __sub(function(a){ return a }, 1)"));
assert_eq!(n(&rewrite("var g = function(){}\n- 1")), n("var g = __sub(function(){},\n 1)"));
assert_eq!(n(&rewrite("(function f(){} - 1)")), n("(__sub(function f(){}, 1))"));
assert_eq!(n(&rewrite("[function(){} - 1]")), n("[__sub(function(){}, 1)]"));
assert_eq!(n(&rewrite("o = {k: function(){} - 1}")), n("o = {k: __sub(function(){}, 1)}"));
}
#[test]
fn source_expansion_is_bounded_before_rewriting() {
let src = "x += 1;".repeat(super::MAX_REWRITTEN_BYTES / 6 + 1);
+16
View File
@@ -193,6 +193,22 @@ fn functions_and_let_are_reusable_across_evaluations() {
assert_close!(f.num(e, 2.0), 9.0);
}
#[test]
fn a_function_declaration_ends_at_its_brace_so_a_leading_minus_starts_a_new_statement() {
// #3212: the array-math rewrite took `function … {…}\n-50 + 100` for one expression,
// `(function … {…}) - 50 + 100`, which is NaN (and left the function undeclared).
let f = fx();
assert_close!(f.num("function same3212(x){ return x; }\n-50 + 100", 0.0), 50.0);
// The declaration really declared the function (globals do not outlive one evaluation).
assert_close!(f.num("function same3212(x){ return x; }\n-50 + 100;\nsame3212(7)", 0.0), 7.0);
assert_close!(f.num("function twice3212(x){ return x * 2; }\n-twice3212(10) + 100", 0.0), 80.0);
assert_close!(f.num("function seven3212(){ return 7; }\n+seven3212()", 0.0), 7.0);
assert_close!(f.num("function one3212(){ return 1; } -one3212() * 3", 0.0), -3.0);
assert_close!(f.num("if (time >= 0) { function neg3212(x){ return -x; }\n-neg3212(4) }", 0.0), 4.0);
// A function expression stays an operand: `function - 1` is NaN in JavaScript too.
assert_close!(f.num("var g3212 = function(){ return 1; }\n- 1;\ntypeof g3212 == 'number' ? 5 : 6", 0.0), 5.0);
}
#[test]
fn an_expression_cannot_rebind_a_prelude_name_for_the_next_one() {
let f = fx();
+5 -2
View File
@@ -229,8 +229,11 @@ fn point(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
let rolloff = pr.f("highlightRolloff") as f32;
let offset = |black: f32, white: f32| 10f32.powf((black - white) * 0.002 / 0.6);
let knee = 1.0 - (rolloff / 100.0).clamp(0.0, 0.99);
p.u[0] = [0, pr.e("conversionType"), 0, 0];
p.f[0] = [offset(black, white), knee, white, pr.f("gamma") as f32];
let version_2 = pr.f("version") >= 2.0;
// Version 1 keeps the saved Gamma, where 1.7 gives linear output.
let gamma = if version_2 { effectcraft_effects::cineon_gamma(pr) } else { pr.f("gamma") };
p.u[0] = [0, pr.e("conversionType"), version_2 as u32, 0];
p.f[0] = [offset(black, white), knee, white, gamma as f32];
p.f[1] = [pr.f("internalBlackPoint") as f32, pr.f("internalWhitePoint") as f32, 0.0, 0.0];
p.f[2] = [offset(95.0, 685.0), knee, 685.0, 1.7];
}
+3 -2
View File
@@ -29,8 +29,9 @@ fn fxe_circle(@builtin(global_invocation_id) gid: vec3<u32>) {
if (P.u[0].z != 0u) {
cov = 1.0 - cov;
}
let a = cov * P.f[1].z;
textureStore(out, p, gen_blend(textureLoad(src, p, 0), vec4<f32>(P.f[2].xyz * a, a), P.u[0].x));
let o = textureLoad(src, p, 0);
let a = gen_alpha(cov * P.f[1].z, o.w, P.u[0].x);
textureStore(out, p, gen_blend(o, vec4<f32>(P.f[2].xyz * a, a), P.u[0].x));
}
// ---------------------------------------------------------------- Ellipse (generate2::ellipse)
+13 -5
View File
@@ -32,6 +32,12 @@ fn gen_blend(o: vec4<f32>, g: vec4<f32>, mode: u32) -> vec4<f32> {
return blend_pixel(mode, o, g, 0.5);
}
// generate::gen_alpha: with None (mode 255) the generated alpha `a` is scaled by the layer's
// alpha, so the pattern stays inside the layer and its masks; other modes keep `a`.
fn gen_alpha(a: f32, layer_a: f32, mode: u32) -> f32 {
return select(a, a * layer_a, mode == 255u);
}
// A (hi, lo) pair from `data`.
fn gen_hl(i: u32) -> vec2<f32> {
return vec2<f32>(data[i], data[i + 1u]);
@@ -466,9 +472,10 @@ fn gen_checker(@builtin(global_invocation_id) gid: vec3<u32>) {
}
let sx = gen_axis(f32(p.x) + P.f[0].x, P.f[0].z, P.f[1].x);
let sy = gen_axis(f32(p.y) + P.f[0].y, P.f[0].w, P.f[1].y);
let cov = clamp(0.5 + 0.5 * sx * sy, 0.0, 1.0) * P.f[1].z;
let o = textureLoad(src, p, 0);
let a = gen_alpha(clamp(0.5 + 0.5 * sx * sy, 0.0, 1.0) * P.f[1].z, o.w, P.u[0].x);
let c = P.f[2].xyz;
textureStore(out, p, gen_blend(textureLoad(src, p, 0), vec4<f32>(c * cov, cov), P.u[0].x));
textureStore(out, p, gen_blend(o, vec4<f32>(c * a, a), P.u[0].x));
}
// f32::rem_euclid.
@@ -502,8 +509,9 @@ fn gen_grid(@builtin(global_invocation_id) gid: vec3<u32>) {
if (P.u[0].y != 0u) {
cov = 1.0 - cov;
}
let a = cov * P.f[1].z;
textureStore(out, p, gen_blend(textureLoad(src, p, 0), vec4<f32>(P.f[2].xyz * a, a), P.u[0].x));
let o = textureLoad(src, p, 0);
let a = gen_alpha(cov * P.f[1].z, o.w, P.u[0].x);
textureStore(out, p, gen_blend(o, vec4<f32>(P.f[2].xyz * a, a), P.u[0].x));
}
// u[0] = (mode, seed); f[0..4] = points (x, y); f[4..8] = colours;
@@ -535,7 +543,7 @@ fn gen_fourcolor(@builtin(global_invocation_id) gid: vec3<u32>) {
}
let o = textureLoad(src, p, 0);
// None keeps the layer's alpha, as the CPU path does (#1381).
let op = select(P.f[8].z, P.f[8].z * o.w, P.u[0].x == 255u);
let op = gen_alpha(P.f[8].z, o.w, P.u[0].x);
textureStore(out, p, gen_blend(o, vec4<f32>(c * op, op), P.u[0].x));
}
+33 -10
View File
@@ -258,10 +258,17 @@ fn fp2_vector(@builtin(global_invocation_id) gid: vec3<u32>) {
// 3 CC Overbrights, 4 Color Link (alpha), 5 Color Link (blend), 6 CC Composite.
// utility::Cineon::log_to_lin; c = (offset, knee, white, gamma), r = (internal black, white).
fn fp2_log_to_lin(v: f32, c: vec4<f32>, r: vec2<f32>) -> f32 {
// Version 1 takes the saved Gamma, where 1.7 gives linear output.
fn fp2_log_to_lin(v: f32, c: vec4<f32>, r: vec2<f32>, version_2: bool) -> f32 {
let code = v * 1023.0;
var lin = (pow(10.0, (code - c.z) * 0.002 / 0.6) - c.x) / max(1.0 - c.x, 1e-6);
lin = powz(max(lin, 0.0), 1.7 / max(c.w, 0.01));
let exposure = pow(10.0, (code - c.z) * 0.002 / 0.6);
var lin: f32;
if (version_2) {
let root_offset = pow(c.x, 1.0 / max(c.w, 0.001));
lin = max((pow(exposure, 1.0 / max(c.w, 0.001)) - root_offset) / max(1.0 - root_offset, 1e-6), 0.0);
} else {
lin = powz(max((exposure - c.x) / max(1.0 - c.x, 1e-6), 0.0), 1.7 / max(c.w, 0.01));
}
let k = c.y;
if (k < 1.0 && lin > k) {
let w = 1.0 - k;
@@ -271,7 +278,7 @@ fn fp2_log_to_lin(v: f32, c: vec4<f32>, r: vec2<f32>) -> f32 {
}
// utility::Cineon::lin_to_log.
fn fp2_lin_to_log(v: f32, c: vec4<f32>, r: vec2<f32>) -> f32 {
fn fp2_lin_to_log(v: f32, c: vec4<f32>, r: vec2<f32>, version_2: bool) -> f32 {
let d = r.y - r.x;
var lin = (v - r.x) / select(d, 1e-6, abs(d) < 1e-6);
let k = c.y;
@@ -279,8 +286,14 @@ fn fp2_lin_to_log(v: f32, c: vec4<f32>, r: vec2<f32>) -> f32 {
let w = 1.0 - k;
lin = k - w * log(max(1.0 - (lin - k) / w, 1e-6));
}
lin = powz(max(lin, 0.0), max(c.w, 0.01) / 1.7);
let code = c.z + log(max(lin * (1.0 - c.x) + c.x, 1e-9)) * 0.4342944819032518 * 0.6 / 0.002;
var exposure: f32;
if (version_2) {
let root_offset = pow(c.x, 1.0 / max(c.w, 0.001));
exposure = powz(max(lin, 0.0) * (1.0 - root_offset) + root_offset, max(c.w, 0.001));
} else {
exposure = powz(max(lin, 0.0), max(c.w, 0.01) / 1.7) * (1.0 - c.x) + c.x;
}
let code = c.z + log(max(exposure, 1e-9)) * 0.4342944819032518 * 0.6 / 0.002;
return code / 1023.0;
}
@@ -292,15 +305,25 @@ fn fp2_spow(v: f32, e: f32) -> f32 {
fn fp2_cineon(v: f32) -> f32 {
let c = P.f[0];
let r = P.f[1].xy;
let version_2 = P.u[0].z != 0u;
switch P.u[0].y {
case 0u: {
return fp2_lin_to_log(v, c, r);
return fp2_lin_to_log(v, c, r, version_2);
}
case 1u: {
return fp2_log_to_lin(v, c, r);
return fp2_log_to_lin(v, c, r, version_2);
}
default: {
return fp2_lin_to_log(fp2_log_to_lin(v, c, r), P.f[2], vec2<f32>(0.0, 1.0));
if (version_2) {
// Default points keep the input code; custom points pass through Gamma 1 first.
var code = v;
if (c.x != P.f[2].x || c.z != 685.0 || r.x != 0.0 || r.y != 1.0) {
let unit = vec4<f32>(c.xyz, 1.0);
code = fp2_lin_to_log(fp2_log_to_lin(v, unit, r, true), P.f[2], vec2<f32>(0.0, 1.0), false);
}
return powz(max(code, 0.0), 1.0 / max(c.w, 0.001));
}
return fp2_lin_to_log(fp2_log_to_lin(v, c, r, false), P.f[2], vec2<f32>(0.0, 1.0), false);
}
}
}
@@ -314,7 +337,7 @@ fn fp2_point(@builtin(global_invocation_id) gid: vec3<u32>) {
let px = textureLoad(src, p, 0);
var o = px;
switch P.u[0].x {
// f[0], f[1], f[2]: see fp2_cineon; u[0].y = conversion type.
// f[0], f[1], f[2]: see fp2_cineon; u[0].y = conversion type, z = version 2.
case 0u: {
if (px.w > 0.0) {
let c = px.xyz / px.w;
+32
View File
@@ -179,7 +179,14 @@ fn composites_and_colour() {
env_case("ec.color.colorlink", &[("sourceLayer", Value::Layer(Some(9))), ("sampleSource", e(4)), ("clip", n(5.0))]);
effect_case("ec.utility.cineon", &[]);
effect_case("ec.utility.cineon", &[("conversionType", e(0)), ("gamma", n(2.2))]);
effect_case("ec.utility.cineon", &[("version", n(1.0)), ("gamma", n(2.2))]);
effect_case("ec.utility.cineon", &[("version", n(1.0)), ("gamma", n(0.0)), ("conversionType", e(0))]);
effect_case("ec.utility.cineon", &[("conversionType", e(2)), ("highlightRolloff", n(60.0)), ("tenBitWhitePoint", n(800.0))]);
effect_case("ec.utility.cineon", &[("conversionType", e(1)), ("gamma", n(1.7)), ("highlightRolloff", n(0.0))]);
effect_case("ec.utility.cineon", &[("conversionType", e(1)), ("gamma", n(2.2)), ("highlightRolloff", n(0.0))]);
effect_case("ec.utility.cineon", &[("conversionType", e(2)), ("gamma", n(1.0)), ("highlightRolloff", n(0.0))]);
effect_case("ec.utility.cineon", &[("conversionType", e(2)), ("gamma", n(1.7))]);
env_case_allow("ec.utility.cineon", &[("version", n(1.0)), ("conversionType", e(2)), ("gamma", n(2.2))], 0.005);
effect_case("ec.utility.hdrcompander", &[("gain", n(4.0)), ("gamma", n(2.0))]);
effect_case("ec.utility.hdrcompander", &[("mode", e(1)), ("gain", n(3.0)), ("gamma", n(1.5))]);
effect_case("ec.utility.hdrcompression", &[]);
@@ -210,6 +217,31 @@ fn hdr_compression_over_range() {
}
}
#[test]
fn cineon_version_2_paths_match_cpu() {
for vals in [
&[("conversionType", e(2)), ("gamma", n(1.0)), ("highlightRolloff", n(0.0))][..],
&[("conversionType", e(2)), ("gamma", n(1.0)), ("highlightRolloff", n(20.0))][..],
&[("conversionType", e(2)), ("gamma", n(1.7)), ("highlightRolloff", n(20.0))][..],
&[("conversionType", e(1)), ("gamma", n(2.2)), ("highlightRolloff", n(0.0))][..],
] {
env_case_allow("ec.utility.cineon", vals, 0.005);
}
let Some(g) = gpu() else { return };
let spec = effectcraft_effects::find("ec.utility.cineon").unwrap();
let mut params =
effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, [1.0, 1.0]))).collect() };
params.values.insert("gamma".into(), n(1.7));
params.values.insert("highlightRolloff".into(), n(0.0));
let mut img = effectcraft_raster::Image::new(1, 1);
img.set(0, 0, [400.0 / 1023.0, 400.0 / 1023.0, 400.0 / 1023.0, 1.0]);
let buf = Buf { img, offset: [0.0; 2], scale: 1.0 };
let ctx = effectcraft_effects::EffectCtx { params: &params, time: 0.0, layer_size: [1.0, 1.0], seed: 0, adjustment: false, env: EffectEnv::default() };
let out = effectcraft_render::Accelerator::effects(g, &[effectcraft_render::FxStep { spec, ctx }], &buf, None).expect("the GPU runs the effect");
let got = (out.img.get(0, 0)[0].clamp(0.0, 1.0) * 255.0).round() as i32;
assert!((got - 57).abs() <= 1, "code 400: {got} vs 57");
}
#[test]
fn stylize() {
let _flips = allow_llvmpipe_boundary_flips();
+1
View File
@@ -32,6 +32,7 @@ tempfile = { workspace = true }
effectcraft-psd = { workspace = true }
effectcraft-svg = { workspace = true }
effectcraft-pdf = { workspace = true }
craft-vectorcraft-format = { workspace = true }
effectcraft-raster = { workspace = true }
effectcraft-time = { workspace = true }
effectcraft-interchange = { workspace = true }
+6 -2
View File
@@ -34,10 +34,14 @@ fn flat(rgba: [f32; 4], extra: bool) -> Vec<u8> {
write(&d)
}
/// Write `bytes` to `path` so its modification time moves even on coarse file systems.
/// Write `bytes` to `path` so its modification time moves even on coarse file systems. The file
/// is replaced in one step, as an application's save does: written in place, a watcher looking
/// every 20 ms can see it empty or half written and report the one save twice.
fn save(path: &str, bytes: &[u8]) {
std::thread::sleep(std::time::Duration::from_millis(30));
std::fs::write(path, bytes).unwrap();
let part = format!("{path}.part");
std::fs::write(&part, bytes).unwrap();
std::fs::rename(&part, path).unwrap();
}
fn footage(s: &Session, id: ItemId) -> Footage {
+147
View File
@@ -950,3 +950,150 @@ fn ai_composition_retains_layer_sizes_and_positions() {
assert!(frame.get(39, 10)[0] > 0.99, "reload invalidates cached pixels");
}
}
/// A `.vectorcraft` file (written with craft-vectorcraft-format's envelope) holding an empty
/// document and `pdf` as the PDF it carries (Create PDF-Compatible File).
fn vectorcraft_file(pdf: Option<&[u8]>) -> Vec<u8> {
let mut file = craft_vectorcraft_format::File::new(json!({"artboards": [], "layers": []}));
let mut tail = file.tail();
file.pdf = pdf.map(|b| tail.image("application/pdf", b, false));
let mut out = serde_json::to_vec(&file).unwrap();
tail.write_to(&mut out).unwrap();
out
}
/// An A4 page (595.28 × 841.89 pt) whose artwork sits inside a page clip and ten nested
/// clipping groups, as PDFs exported from layout and office applications nest them: a black bar
/// whose left edge is at x = 30 pt, from 41.89 to 191.89 pt down the page.
fn a4_clipped_pdf() -> Vec<u8> {
let mut content = String::from(
"q 0 0 595.28 841.89 re W n
",
);
for i in 0..10 {
content.push_str(&format!(
"q {} {} {} {} re W n
",
20 + i,
600 + i,
300 - 2 * i,
230 - 2 * i
));
}
content.push_str(
"0 0 0 rg 30 650 40 150 re f
",
);
content.push_str(
&"Q
"
.repeat(11),
);
effectcraft_pdf::write::pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".into(), None),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), None),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595.28 841.89] /Resources << >> /Contents 4 0 R >>".into(), None),
(4, "<< >>".into(), Some(content.into_bytes())),
],
1,
)
}
/// #2895: an A4 PDF imports at its size in points, rounded up (596 × 842 px; After Effects
/// also takes a point as a pixel), and scaled 200 % with Continuously Rasterize on it is drawn
/// at that scale: the bar's left edge stays one pixel wide. It used to come out empty: at
/// 200 % (a 32 MB page) each nested clipping group copied the whole page and drew on a second
/// page-size surface, so the eighth level of clips ran past the rasteriser's 512 MB surface
/// budget. With the switch off the layer is the page's pixels enlarged, soft as before.
#[test]
fn a4_pdf_scaled_200_percent_continuously_rasterizes_sharp() {
let path = tmp("a4-clipped.pdf");
std::fs::write(&path, a4_clipped_pdf()).unwrap();
let mut s = effectcraft_host::session();
let r = s.execute_checked("file.import", json!({"paths": [path]})).unwrap();
assert_eq!(r["errors"], json!([]), "{r}");
let item = r["items"][0].as_u64().unwrap();
let effectcraft_project::ItemKind::Footage(f) = &s.project.item(ItemId(item)).unwrap().kind else { panic!("footage") };
assert_eq!((f.codec.as_str(), f.width, f.height), ("PDF", 596, 842), "A4 in points");
s.execute("comp.new", json!({"name": "A4", "width": 400, "height": 400, "frameRate": 30, "duration": 1})).unwrap();
let lid = s.execute_checked("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap();
for (k, v) in [("transform/anchor", json!([0, 0])), ("transform/position", json!([0, 0])), ("transform/scale", json!([200, 200]))] {
s.execute("prop.set", json!({"layer": lid, "path": k, "value": v})).unwrap();
}
let cid = s.active_comp_id().unwrap();
let t = effectcraft_time::Tick::ZERO;
// Row 240 (120 pt down the page) crosses the bar's left edge at x = 60 (30 pt × 2).
let soft_pixels = |img: &Image| (50..70).filter(|&x| (0.05..0.95).contains(&img.get(x, 240)[3])).count();
let off = s.render(cid, t, RenderOpts::default());
assert!(off.get(100, 240)[3] > 0.99, "the bar shows with the switch off");
assert!(soft_pixels(&off) >= 2, "off: the page's pixels enlarged, a soft edge ({} partial pixels)", soft_pixels(&off));
s.execute("layer.setSwitch", json!({"layers": [lid], "switch": "collapse", "value": true})).unwrap();
let on = s.render(cid, t, RenderOpts::default());
assert!(on.get(100, 240)[3] > 0.99, "the clipped bar is drawn at 200 %: {:?}", on.get(100, 240));
assert!(on.get(61, 240)[3] > 0.99 && on.get(58, 240)[3] < 0.01, "a hard edge at x = 60: {:?} {:?}", on.get(58, 240), on.get(61, 240));
assert!(soft_pixels(&on) <= 1, "on: the edge is at most one pixel wide ({} partial pixels)", soft_pixels(&on));
// Outside the clips (x = 10 pt) nothing is drawn.
assert!(on.get(20, 240)[3] < 0.01);
}
#[test]
fn vectorcraft_documents_import_through_the_pdf_they_carry() {
let bytes = layered_pdf();
let doc = effectcraft_pdf::parse(&bytes).unwrap();
let direct = effectcraft_svg::rasterize(&doc, 120, 80, 1.0);
let path = tmp("art.vectorcraft");
std::fs::write(&path, vectorcraft_file(Some(&bytes))).unwrap();
// As footage: drawn as the PDF, and continuously rasterized.
let mut s = effectcraft_host::session();
let r = s.execute_checked("file.import", json!({"paths": [path]})).unwrap();
assert_eq!(r["errors"], json!([]), "{r}");
let item = r["items"][0].as_u64().unwrap();
let effectcraft_project::ItemKind::Footage(f) = &s.project.item(ItemId(item)).unwrap().kind else { panic!("footage") };
assert_eq!((f.codec.as_str(), f.width, f.height), ("VectorCraft", 120, 80));
s.execute("comp.new", json!({"name": "V", "width": 120, "height": 80, "frameRate": 30, "duration": 1})).unwrap();
let lid = s.execute_checked("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap();
let cid = s.active_comp_id().unwrap();
let t = effectcraft_time::Tick::ZERO;
assert!(mean_diff(&s.render(cid, t, RenderOpts::default()), &direct) < 1.0 / 255.0, "footage = the carried PDF");
for (k, v) in [("transform/anchor", json!([0, 0])), ("transform/position", json!([0, 0])), ("transform/scale", json!([300, 300]))] {
s.execute("prop.set", json!({"layer": lid, "path": k, "value": v})).unwrap();
}
let want = effectcraft_svg::rasterize(&doc, 120, 80, 3.0);
s.execute("layer.setSwitch", json!({"layers": [lid], "switch": "collapse", "value": true})).unwrap();
let sharp = mean_diff(&s.render(cid, t, RenderOpts::default()), &want);
assert!(sharp < 0.004, "continuously rasterized {sharp}");
// As a composition: one layer per PDF layer, top first.
for import_as in ["composition", "compositionLayerSizes"] {
let mut s = effectcraft_host::session();
let r = s.execute_checked("file.import", json!({"paths": [path], "importAs": import_as})).unwrap();
assert_eq!(r["errors"], json!([]), "{r}");
let cid = ItemId(r["comps"][0].as_u64().unwrap());
let comp = s.project.comp(cid).unwrap();
assert_eq!(comp.layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), vec!["Art", "Sky"]);
assert_eq!((comp.width, comp.height), (120, 80));
let d = mean_diff(&s.render(cid, t, RenderOpts::default()), &direct);
assert!(d < 1.0 / 255.0, "{import_as}: comp vs page {d}");
}
// Another artboard: the carried PDF's page 2.
let pages = tmp("pages.vectorcraft");
std::fs::write(&pages, vectorcraft_file(Some(&two_page_pdf()))).unwrap();
let mut s = effectcraft_host::session();
let r = s.execute_checked("file.import", json!({"paths": [pages], "page": 2})).unwrap();
assert_eq!(r["errors"], json!([]), "{r}");
let effectcraft_project::ItemKind::Footage(f) = &s.project.item(ItemId(r["items"][0].as_u64().unwrap())).unwrap().kind else { panic!("footage") };
assert_eq!((f.width, f.height, f.page), (100, 60, 1));
}
#[test]
fn a_vectorcraft_document_without_a_pdf_reports_the_option_to_turn_on() {
let path = tmp("no-pdf.vectorcraft");
std::fs::write(&path, vectorcraft_file(None)).unwrap();
for import_as in ["footage", "composition"] {
let mut s = effectcraft_host::session();
let r = s.execute_checked("file.import", json!({"paths": [path], "importAs": import_as})).unwrap();
let e = r["errors"][0].as_str().unwrap_or_default();
assert!(e.contains("no-pdf.vectorcraft") && e.contains("Create PDF-Compatible File"), "{import_as}: {r}");
assert_eq!(r["items"], json!([]), "{import_as}: {r}");
}
}
+23 -1
View File
@@ -539,8 +539,15 @@ struct Entry {
impl Entry {
/// Dropping it would free nothing or lose a decode in progress: an effect (or a picture
/// waiting for its effects) still holds its planes, or it is decoding.
/// waiting for its effects) still holds its planes, someone is using the slot, or it is decoding.
fn in_use(&self) -> bool {
// `get_or_init` hands an active caller a borrow of the OnceLock value before that caller
// can clone the decoded Arc. Keep the entry while any caller still holds this slot, or a
// concurrent account/eviction can remove it in that gap and make the next request decode
// the same file again.
if Arc::strong_count(&self.slot) > 1 {
return true;
}
match self.slot.get() {
None => true,
Some((None, _)) => false,
@@ -967,6 +974,21 @@ mod tests {
assert_eq!(reads.load(Ordering::Relaxed), frames as u64);
}
#[test]
fn cache_does_not_evict_a_slot_while_a_caller_is_using_it() {
let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into();
let one = 4 * 32 * 32 * 4 + 4;
let cache = ChannelCache::new(one);
drop(cache.get("/active.exr", Use::Channels, || Some(bytes.clone())));
let active_slot = cache.lock().entries.iter().find(|entry| entry.path == "/active.exr").unwrap().slot.clone();
drop(cache.get("/next.exr", Use::Channels, || Some(bytes.clone())));
assert!(cache.cached().contains(&"/active.exr".to_string()), "an active caller pins the slot");
drop(active_slot);
drop(cache.get("/newest.exr", Use::Channels, || Some(bytes.clone())));
assert!(!cache.cached().contains(&"/active.exr".to_string()), "an idle slot is eligible for eviction");
}
/// #474: a decode that panics doesn't leave its file "decoding" in the cache (never dropped,
/// its planes counted): the entry goes, and the next request decodes the file.
#[test]
+2 -2
View File
@@ -1,7 +1,7 @@
//! Layered and vector stills: Photoshop documents (`effectcraft-psd`: the merged image, or one
//! layer for footage imported as a composition) and vector files rasterised at any scale: SVG
//! (`effectcraft-svg`), PDF / Illustrator / EPS (`effectcraft-pdf`; one layer of the file for
//! footage imported as a composition).
//! (`effectcraft-svg`), PDF / Illustrator / EPS and the PDF a VectorCraft document carries
//! (`effectcraft-pdf`; one layer of the file for footage imported as a composition).
use effectcraft_project::{AlphaMode, Footage};
use effectcraft_raster::Image;
+1 -1
View File
@@ -65,7 +65,7 @@ impl From<filmcraft_media::MediaError> for MediaError {
/// File extensions recognised as stills.
pub const STILL_EXTENSIONS: &[&str] =
&["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps"];
&["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"];
/// File extensions recognised as audio-only files.
pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS;
pub use effectcraft_project::VIDEO_EXTENSIONS;
+7 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "effectcraft-pdf"
description = "Vector footage import: PDF and PDF-compatible Illustrator (.ai) pages and EPS (a PostScript subset) parsed into the SVG render tree (paths, fills, strokes, shadings, tiling patterns, clipping, text with embedded fonts, images, blend modes, soft masks, optional-content layers)"
description = "Vector footage import: PDF and PDF-compatible Illustrator (.ai) pages, EPS (a PostScript subset) and the PDF a VectorCraft (.vectorcraft) document carries, parsed into the SVG render tree (paths, fills, strokes, shadings, tiling patterns, clipping, text with embedded fonts, images, blend modes, soft masks, optional-content layers)"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -12,6 +12,8 @@ workspace = true
[dependencies]
craft-eps = { workspace = true }
craft-pdf.workspace = true
# The PDF a VectorCraft document carries (Create PDF-Compatible File).
craft-doc = { workspace = true }
effectcraft-svg = { workspace = true }
kurbo = { workspace = true }
effectcraft-text = { workspace = true }
@@ -25,6 +27,10 @@ zune-jpeg = "0.5"
# Encodes JPEG fixtures for the DCT image test.
image = { workspace = true }
effectcraft-raster = { workspace = true }
# Writes the VectorCraft documents the tests read.
craft-vectorcraft-format = { workspace = true }
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
+4
View File
@@ -114,6 +114,10 @@ ffmpeg elsewhere) to check the code tables against an independent implementation
stitching and PostScript calculator (type 4) functions.
- **Pages:** any page ([`parse_page`], [`page_count`]); File ▸ Import takes `page` (from 1) and
the Import dialog asks for it; footage remembers its page (`Footage::page`).
- **VectorCraft documents** (`.vectorcraft`, plain or compressed): the PDF the document carries
when VectorCraft saved it with Create PDF-Compatible File, one page per artboard, read through
`craft-doc` from craft-libs. The footage codec is `VectorCraft`. A document saved without that
option has no PDF, and importing it reports an error that names the option.
## Limitations
+45 -4
View File
@@ -34,6 +34,8 @@ pub enum Error {
NoPages,
PageOutOfRange(usize),
NoBoundingBox,
/// A VectorCraft document saved without Create PDF-Compatible File.
NoCarriedPdf,
Read(String),
}
@@ -45,6 +47,9 @@ impl std::fmt::Display for Error {
Error::NoPages => write!(f, "the PDF has no pages"),
Error::PageOutOfRange(n) => write!(f, "the PDF has no page {}", n.saturating_add(1)),
Error::NoBoundingBox => write!(f, "the EPS file has no %%BoundingBox"),
Error::NoCarriedPdf => {
write!(f, "the VectorCraft document holds no PDF; save it in VectorCraft with Create PDF-Compatible File turned on")
}
Error::Read(message) => f.write_str(message),
}
}
@@ -53,17 +58,24 @@ impl std::fmt::Display for Error {
impl std::error::Error for Error {}
/// File extensions read as vector footage by this crate.
pub const EXTENSIONS: &[&str] = &["pdf", "ai", "eps", "epsf", "epsi"];
pub const EXTENSIONS: &[&str] = &["pdf", "ai", "eps", "epsf", "epsi", "vectorcraft"];
/// The format of a file, by its first bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Pdf,
Eps,
/// A VectorCraft document (`.vectorcraft`), read through the PDF it carries when it was
/// saved with Create PDF-Compatible File: one page per artboard.
VectorCraft,
}
/// Sniff a PDF (`%PDF-` near the start, as PDF-compatible `.ai` files are) or an EPS file.
/// Sniff a VectorCraft document, a PDF (`%PDF-` near the start, as PDF-compatible `.ai` files
/// are) or an EPS file. The first 64 KiB suffice.
pub fn sniff(bytes: &[u8]) -> Option<Format> {
if craft_doc::sniff(bytes) == Some(craft_doc::Kind::VectorCraft) {
return Some(Format::VectorCraft);
}
let head = &bytes[..bytes.len().min(1024)];
if head.windows(5).any(|w| w == b"%PDF-") {
return Some(Format::Pdf);
@@ -74,11 +86,12 @@ pub fn sniff(bytes: &[u8]) -> Option<Format> {
None
}
/// A footage codec name for a sniffed file ("PDF", "AI", "EPS").
/// A footage codec name for a sniffed file ("PDF", "AI", "EPS", "VectorCraft").
pub fn codec(path: &str, bytes: &[u8]) -> Option<&'static str> {
let f = sniff(bytes)?;
let ai = path.to_ascii_lowercase().ends_with(".ai");
Some(match (f, ai) {
(Format::VectorCraft, _) => "VectorCraft",
(_, true) => "AI",
(Format::Pdf, false) => "PDF",
(Format::Eps, false) => "EPS",
@@ -112,19 +125,47 @@ pub fn parse_page_framed(bytes: &[u8], index: usize, framing: Framing) -> Result
match sniff(bytes) {
Some(Format::Pdf) => parse_pdf(bytes, index, framing),
Some(Format::Eps) => parse_eps(bytes),
Some(Format::VectorCraft) => parse_pdf(&carried_pdf(bytes)?, index, framing),
None => Err(Error::NotVector),
}
}
/// Number of pages (1 for EPS).
pub fn page_count(bytes: &[u8]) -> usize {
let pdf_pages = |bytes: &[u8]| object::File::parse(bytes).map(|file| page::pages(&file).len()).unwrap_or(0);
match sniff(bytes) {
Some(Format::Pdf) => object::File::parse(bytes).map(|file| page::pages(&file).len()).unwrap_or(0),
Some(Format::Pdf) => pdf_pages(bytes),
Some(Format::Eps) => 1,
Some(Format::VectorCraft) => carried_pdf(bytes).map(|pdf| pdf_pages(&pdf)).unwrap_or(0),
None => 0,
}
}
/// The PDF a VectorCraft document carries: [`Error::NoCarriedPdf`] when it was saved without
/// Create PDF-Compatible File. The preview is not read, so a damaged preview does not stop the
/// import.
fn carried_pdf(bytes: &[u8]) -> Result<Vec<u8>, Error> {
let pdf = craft_doc::rendition(bytes, craft_doc::RenditionKind::Pdf, &carried_limits())
.map_err(|e| Error::Read(format!("VectorCraft document: {e}")))?
.ok_or(Error::NoCarriedPdf)?;
if sniff(&pdf.bytes) != Some(Format::Pdf) {
return Err(Error::Read("VectorCraft document: its PDF member is not a PDF".into()));
}
Ok(pdf.bytes)
}
/// craft-doc's limits for [`carried_pdf`]: a PDF after the JSON (version 4) may be as large as a
/// PDF file this crate opens (`craft_pdf::MAX_INPUT_BYTES`); one inline in the JSON as base64
/// (version 3) stays within `max_json`, about 192 MiB of PDF. `max_total` allows `max_json` (craft-doc's default) for a
/// compressed document's JSON, and twice `max_entry` for its data up to the PDF's end and the PDF
/// copied out, which caps what a hostile file can make the import allocate.
fn carried_limits() -> craft_doc::Limits {
let mut limits = craft_doc::Limits::default();
limits.max_entry = u64::try_from(craft_pdf::MAX_INPUT_BYTES).unwrap_or(u64::MAX);
limits.max_total = limits.max_json.saturating_add(limits.max_entry.saturating_mul(2));
limits
}
/// Build the document: `root` children become layer groups (see the crate docs).
fn finish(nodes: Vec<Node>, flags: Vec<bool>, skipped: Vec<String>, width: f64, height: f64, to_doc: Affine) -> Doc {
let mut layers: Vec<Node> = vec![];
+30
View File
@@ -8,6 +8,7 @@ mod groups;
mod import;
mod reader;
mod shading;
mod vectorcraft;
const CONTENT: &str = "/OC /MC0 BDC\n0 1 0 rg 0 0 200 100 re f\nEMC\n\
/OC /MC1 BDC\nq 10 10 80 80 re W n\n1 0 0 rg 0 0 50 100 re f\nQ\n\
@@ -1305,3 +1306,32 @@ fn cmap_entries_at_the_top_of_the_code_range_do_not_overflow() {
// Code 0 is CID u32::MAX; code 2 would be past it, so it falls back to CID 0 like an unmapped code.
assert_eq!((f.width(0), f.width(2)), (0.5, 0.7));
}
/// Never crash: a crafted page nests `q … W n` twenty thousand deep. The document is a tree
/// that is drawn, measured and dropped recursively, so groups past the nesting limit are left
/// out (said in the skip notes) and the page parses, draws and drops on a thread with a small
/// stack; the artwork inside them still draws, clipped by the groups that were kept.
#[test]
fn clip_groups_nested_without_end_are_capped() {
let run = std::thread::Builder::new().stack_size(2 << 20).spawn(|| {
let n = 20_000;
let mut content = "q 0 0 50 50 re W n\n".repeat(n);
content.push_str("0 0 1 rg 0 0 50 50 re f\n");
content.push_str(&"Q\n".repeat(n));
let bytes = pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), None),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_string(), None),
(4, "<< >>".to_string(), Some(content.into_bytes())),
],
1,
);
let doc = parse(&bytes).unwrap();
(doc.skipped.clone(), px(&doc, 25, 75), px(&doc, 75, 25))
});
let (skipped, inside, outside) = run.unwrap().join().unwrap();
assert!(skipped.iter().any(|s| s.contains("nesting limit")), "{skipped:?}");
assert!(inside[2] > 0.99 && inside[3] > 0.99, "the artwork draws inside the clips: {inside:?}");
assert!(outside[3] < 0.01, "and is clipped: {outside:?}");
}
+140
View File
@@ -0,0 +1,140 @@
//! VectorCraft documents read through the PDF they carry (Create PDF-Compatible File), written
//! with craft-vectorcraft-format's envelope types: plain and compressed, the PDF inline as base64
//! (version 3) and after the JSON (version 4).
use std::io::Write;
use craft_vectorcraft_format::{BLOB_MAGIC, File, INLINE_MAX, Image};
use crate::write::pdf;
use crate::*;
/// Two artboards: a 200×100 page with the layers "Background" (green) and "Art" (a red left
/// half), and a 100×50 blue page. `pad` adds an unused object so the PDF is long enough to go
/// after the JSON.
fn artboards_pdf(pad: bool) -> Vec<u8> {
let first = "/OC /L0 BDC\n0 1 0 rg 0 0 200 100 re f\nEMC\n/OC /L1 BDC\n1 0 0 rg 0 0 100 100 re f\nEMC\n";
let mut objs = vec![
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None),
(2, "<< /Type /Pages /Kids [3 0 R 8 0 R] /Count 2 >>".to_string(), None),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << /Properties << /L0 5 0 R /L1 6 0 R >> >> /Contents 4 0 R >>".to_string(), None),
(4, "<< >>".to_string(), Some(first.as_bytes().to_vec())),
(5, "<< /Type /OCG /Name (Background) >>".to_string(), None),
(6, "<< /Type /OCG /Name (Art) >>".to_string(), None),
(7, "<< >>".to_string(), Some(b"0 0 1 rg 0 0 100 50 re f\n".to_vec())),
(8, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 50] /Contents 7 0 R >>".to_string(), None),
];
if pad {
// Written as given (the writer compresses streams without a `/Filter`); never read.
objs.push((9, "<< /Filter /ASCIIHexDecode >>".to_string(), Some(vec![b'0'; INLINE_MAX + 1024])));
}
pdf(&objs, 1)
}
/// A `.vectorcraft` file of `version` holding an empty document and `carried` as its `pdf`
/// member, gzip-compressed when `gzip` is set (Use Compression).
fn vectorcraft(carried: Option<&[u8]>, version: u32, gzip: bool) -> Vec<u8> {
vectorcraft_with_preview(carried, None, version, gzip)
}
/// [`vectorcraft`] with `preview` as the file's `preview` member.
fn vectorcraft_with_preview(carried: Option<&[u8]>, preview: Option<Image>, version: u32, gzip: bool) -> Vec<u8> {
let mut file = File::new(serde_json::json!({"artboards": [], "layers": []}));
file.version = version;
file.generator = Some("VectorCraft 0.1.0".into());
file.preview = preview;
let mut tail = file.tail();
file.pdf = carried.map(|b| tail.image("application/pdf", b, false));
let mut out = serde_json::to_vec(&file).unwrap();
tail.write_to(&mut out).unwrap();
if !gzip {
return out;
}
let mut gz = flate2::write::GzEncoder::new(vec![], flate2::Compression::default());
gz.write_all(&out).unwrap();
gz.finish().unwrap()
}
fn pixels(doc: &Doc) -> Vec<[f32; 4]> {
let (w, h) = doc.pixel_size();
effectcraft_svg::rasterize(doc, w, h, 1.0).data
}
#[test]
fn a_vectorcraft_document_reads_as_the_pdf_it_carries() {
for (version, gzip, pad) in [(3, false, false), (3, true, false), (4, false, true), (4, true, true)] {
let carried = artboards_pdf(pad);
let file = vectorcraft(Some(&carried), version, gzip);
let case = format!("version {version}, gzip {gzip}");
if !gzip {
let after_json = file.windows(BLOB_MAGIC.len()).any(|w| w == BLOB_MAGIC);
assert_eq!(after_json, version == 4, "{case}: the PDF goes after the JSON in version 4");
}
assert_eq!(sniff(&file), Some(Format::VectorCraft), "{case}");
assert_eq!(codec("art.vectorcraft", &file), Some("VectorCraft"), "{case}");
assert_eq!(page_count(&file), 2, "{case}");
let doc = parse(&file).unwrap();
assert_eq!((doc.width, doc.height), (200.0, 100.0), "{case}");
assert_eq!(layer_names(&doc), vec!["Background", "Art"], "{case}");
assert_eq!(pixels(&doc), pixels(&parse(&carried).unwrap()), "{case}: drawn as the PDF itself");
let second = parse_page(&file, 1).unwrap();
assert_eq!((second.width, second.height), (100.0, 50.0), "{case}");
assert_eq!(parse_page(&file, 2).err(), Some(Error::PageOutOfRange(2)), "{case}");
}
}
#[test]
fn a_vectorcraft_document_without_a_pdf_names_create_pdf_compatible_file() {
for gzip in [false, true] {
let file = vectorcraft(None, 4, gzip);
assert_eq!(sniff(&file), Some(Format::VectorCraft));
assert_eq!(page_count(&file), 0);
let e = parse(&file).err();
assert_eq!(e, Some(Error::NoCarriedPdf));
assert!(e.map(|e| e.to_string()).unwrap_or_default().contains("Create PDF-Compatible File"));
}
}
#[test]
fn a_damaged_preview_does_not_stop_the_carried_pdf_from_reading() {
let mut not_base64 = Image::default();
not_base64.mime = "image/png".into();
not_base64.data = "not base64!".into();
let mut past_the_end = Image::default();
past_the_end.mime = "image/png".into();
past_the_end.blob = Some([u64::MAX / 2, 16]);
for (preview, what) in [(not_base64, "not base64"), (past_the_end, "past the end")] {
for (version, gzip, pad) in [(3, false, false), (4, false, true), (4, true, true)] {
let carried = artboards_pdf(pad);
let file = vectorcraft_with_preview(Some(&carried), Some(preview.clone()), version, gzip);
let case = format!("{what}, version {version}, gzip {gzip}");
assert_eq!(page_count(&file), 2, "{case}");
let doc = parse(&file).unwrap_or_else(|e| panic!("{case}: {e}"));
assert_eq!(layer_names(&doc), vec!["Background", "Art"], "{case}");
}
}
}
#[test]
fn a_carried_pdf_may_be_as_large_as_a_pdf_file() {
let limits = carried_limits();
assert_eq!(limits.max_entry, craft_pdf::MAX_INPUT_BYTES as u64);
assert_eq!(limits.max_json, craft_doc::Limits::default().max_json);
assert_eq!(limits.max_total, limits.max_json + 2 * limits.max_entry);
}
#[test]
fn a_vectorcraft_document_read_wrongly_is_an_error() {
// A newer format version.
let newer = vectorcraft(Some(&artboards_pdf(false)), craft_vectorcraft_format::VERSION + 1, false);
let e = parse(&newer).err().map(|e| e.to_string()).unwrap_or_default();
assert!(e.contains("newer"), "{e}");
// A `pdf` member that holds something else.
let not_pdf = vectorcraft(Some(b"not a PDF"), 4, false);
assert!(matches!(parse(&not_pdf), Err(Error::Read(_))));
// A cut-off file.
let file = vectorcraft(Some(&artboards_pdf(true)), 4, true);
assert!(parse(&file[..file.len() / 2]).is_err());
// Other JSON is not a VectorCraft document.
assert_eq!(sniff(br#"{"format":"other","version":1}"#), None);
}
+3 -3
View File
@@ -172,12 +172,12 @@ impl CineonSettings {
}
}
/// Cineon log to linear, shared by Interpret Footage ▸ Cineon Settings and the Cineon Converter
/// effect. `v` is a code value as 0–1 of the 10-bit range; `black` and `white` are the 10 Bit
/// Cineon log to linear for Interpret Footage ▸ Cineon Settings and version 1 Cineon Converter
/// effects. `v` is a code value as 0–1 of the 10-bit range; `black` and `white` are the 10 Bit
/// Black and White Points. The result is 0 at the black point and 1 at the white point, raised to
/// `scale / gamma`, with values above `1 - rolloff / 100` ramped off toward 1 (Highlight Rolloff
/// 0–100; 0 keeps over-range values). A Gamma below 0.01 is raised to 0.01. Cineon Settings passes
/// a `scale` of 1 (Gamma 1 gives linear light) and the Cineon Converter passes 1.7 (its default
/// a `scale` of 1 (Gamma 1 gives linear light) and a version 1 Cineon Converter passes 1.7 (its
/// Gamma 1.7 gives linear light).
pub fn cineon_log_to_lin(v: f32, black: f32, white: f32, scale: f32, gamma: f32, rolloff: f32) -> f32 {
// Kodak printing density: 0.002 density per code value, negative gamma 0.6.
+111 -25
View File
@@ -12,8 +12,11 @@
//! pre-roll of earlier audio and only the block's tail is kept — so preview playback and export
//! produce identical samples.
//!
//! Time-stretched layers are resampled nearest-sample; reversed (negative stretch) layers are
//! silent for now.
//! Time-stretched layers are resampled linearly, so pitch follows the speed. A reversed layer
//! (negative stretch, Layer > Time > Time-Reverse Layer) plays its audio backwards at the same
//! speed: comp sample `k` plays the source just before layer time `layer_time(k)`, so at -100 %
//! with the start at the out point (After Effects' layout) it is the exact mirror of the
//! layer's span. Backwards on a reversed layer plays it forwards again.
use effectcraft_effects::Params;
use effectcraft_effects::audio_fx;
@@ -24,9 +27,18 @@ use crate::{EvalCtx, ExprHost, FootageSource};
const MAX_DEPTH: usize = 16;
/// The fastest a layer's audio plays (a Stretch of 1%).
/// Fastest a layer's audio plays (source samples per comp sample): 1 % stretch, the smallest
/// Time Stretch accepts. The mix plays the clamped stretch (`Layer::effective_stretch`, #3247),
/// so a layer is never faster; a faster speed would be silent instead of reading unbounded
/// source: a last-resort guard.
const MAX_SPEED: f64 = 100.0;
/// Most source sample frames one read asks a footage item or precomp for; a longer read is made
/// in pieces, so memory stays bounded however fast a layer plays and however deep stretched
/// precomps nest. The work is not bounded: each 1 % precomp level still reads 100 times its
/// span.
pub(crate) const MAX_READ: usize = 1 << 18;
/// The most effect preroll (history before a block) mixed, in seconds, across a layer's effects.
const MAX_PREROLL_SECONDS: f64 = 30.0;
@@ -118,6 +130,13 @@ fn animated(g: &effectcraft_project::PropGroup) -> bool {
})
}
/// The clock (seconds) a layer's audio effects run on at comp time `t` (oscillator phase): comp
/// time since the layer's start. It advances one sample per sample at any stretch, forwards or
/// reversed, so blocks join up; at 100 % it is the layer time.
fn fx_clock(l: &Layer, t: Tick) -> f64 {
Tick(t.0.saturating_sub(l.start_time.0)).seconds()
}
fn sample_tick(i: i64, rate: u32) -> Tick {
// Keep the requested sample when the rate does not divide the tick clock.
let t = Tick::from_units(i, i64::from(rate));
@@ -143,7 +162,7 @@ impl MixEnv<'_> {
/// The layer's own (pre-effect) audio for comp sample indices `i0 .. i0 + n`, silent
/// outside its [in, out) span. Comp sample index `k` maps to `in + out − 1 − k` when
/// `reversed`.
/// `reversed` (the Backwards effect).
fn layer_raw(&self, l: &Layer, i0: i64, n: usize, reversed: bool) -> Vec<f32> {
let rate = self.rate;
let mut out = vec![0.0f32; n * 2];
@@ -170,42 +189,86 @@ impl MixEnv<'_> {
if a >= b {
return out;
}
let m = b - a;
// Within ±1 % to ±9900 % (#3247): a stretch of 1e-300 % set in memory read about
// usize::MAX source samples for one block.
let speed = (100.0 / l.effective_stretch()).min(MAX_SPEED);
let src_n = ((m as f64 * speed).ceil() as usize).max(1);
let lt = l.layer_time(sample_tick(i0 + a as i64, rate));
// usize::MAX source samples for one block. A negative stretch plays backwards (#3239).
let speed = 100.0 / l.effective_stretch();
let aspeed = speed.abs();
// The clamped stretch keeps the speed within MAX_SPEED; NaN is checked anyway. The
// tolerance keeps exactly 1 % audible whatever the float noise in the stretch.
if aspeed.is_nan() || aspeed > MAX_SPEED * (1.0 + 1e-9) {
return out;
}
let backwards = speed < 0.0;
// Comp samples per piece, so that one piece reads at most MAX_READ source frames (its
// span, the fraction it starts past a source sample, and the sample after its end).
let piece = (((MAX_READ - 4) as f64 / aspeed) as usize).clamp(1, b - a);
let mut p0 = a;
while p0 < b {
let p1 = p0.saturating_add(piece).min(b);
// Forwards a piece reads the source from the layer time of its first sample. Backwards
// it reads from the layer time of its end and plays what it read last to first, so
// comp sample `k` plays the source just before `layer_time(k)` — at -100 % the exact
// mirror Backwards gives a forward layer.
let origin = sample_tick(i0.saturating_add((if backwards { p1 } else { p0 }) as i64), rate);
let Some(run) = self.source_run(l, l.layer_time(origin), p1 - p0, aspeed) else { return out };
for (i, f) in run.as_chunks::<2>().0.iter().take(p1 - p0).enumerate() {
let k = if backwards { (p1 - 1).saturating_sub(i) } else { p0 + i };
if let Some(o) = out.get_mut(k * 2..k * 2 + 2) {
o.copy_from_slice(f);
}
}
p0 = p1;
}
out
}
/// `m` sample frames of the layer's source audio from layer time `lt` on, played at `speed`
/// (≥ 0) source samples per comp sample: blended linearly between source samples, or copied
/// as they are at speed 1. `None` when the layer has no source audio.
///
/// Sources deliver samples on their sample grid (from the sample at or before the time asked
/// for), so a resampled run reads from that grid sample and starts `x` at `lt`'s exact
/// position past it: a run then continues where the previous block or piece left off.
fn source_run(&self, l: &Layer, lt: Tick, m: usize, speed: f64) -> Option<Vec<f32>> {
let rate = self.rate;
let same = (speed - 1.0).abs() < 1e-9;
let s0 = lt.to_units_floor(i64::from(rate));
let from = sample_tick(s0, rate);
// `lt`'s position past sample s0, in samples (0 ≤ frac < 1); copies ignore it.
let tps = TICKS_PER_SECOND as i128;
let frac = if same { 0.0 } else { (i128::from(lt.0) * i128::from(rate)).rem_euclid(tps) as f64 / tps as f64 };
// Resampled, one more source sample than the run covers: the last sample blends with it.
let src_n = ((frac + m as f64 * speed).ceil() as usize).saturating_add(usize::from(!same)).max(1);
let buf = match &l.source {
LayerSource::Footage { item } => match self.project.item(*item).map(|i| &i.kind) {
Some(ItemKind::Footage(f)) if f.has_audio => self.footage.audio(*item, f, lt, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]),
_ => return out,
Some(ItemKind::Footage(f)) if f.has_audio => self.footage.audio(*item, f, from, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]),
_ => return None,
},
LayerSource::Comp { item } => {
if self.project.comp_contains(*item, self.comp_id) {
return out;
return None;
}
let mut sub = vec![0.0f32; src_n * 2];
mix_into(&AudioSources { project: self.project, footage: self.footage, expr: self.expr, rate }, *item, lt, &mut sub, self.depth + 1);
mix_into(&AudioSources { project: self.project, footage: self.footage, expr: self.expr, rate }, *item, from, &mut sub, self.depth + 1);
sub
}
_ => return out,
_ => return None,
};
let same = (speed - 1.0).abs() < 1e-9;
let mut out = vec![0.0f32; m * 2];
for i in 0..m {
// The source sample at fractional index `x`, blended linearly with the next one unless the
// layer plays at its own speed (then the samples are copied as they are).
let x = i as f64 * speed;
let x = frac + i as f64 * speed;
let j = if same { i } else { (x as usize).min(src_n - 1) };
if j * 2 + 1 >= buf.len() {
break;
}
let k = if same || (j + 1) * 2 + 1 >= buf.len() { j } else { j + 1 };
let f = if same { 0.0 } else { ((x - j as f64) as f32).clamp(0.0, 1.0) };
out[(a + i) * 2] = buf[j * 2] + (buf[k * 2] - buf[j * 2]) * f;
out[(a + i) * 2 + 1] = buf[j * 2 + 1] + (buf[k * 2 + 1] - buf[j * 2 + 1]) * f;
out[i * 2] = buf[j * 2] + (buf[k * 2] - buf[j * 2]) * f;
out[i * 2 + 1] = buf[j * 2 + 1] + (buf[k * 2 + 1] - buf[j * 2 + 1]) * f;
}
out
Some(out)
}
/// Effect parameters at comp time `t`.
@@ -233,7 +296,7 @@ impl MixEnv<'_> {
let pre = (pre_s * self.rate as f64).ceil() as usize;
let b0 = i0 - pre as i64;
let mut buf = self.layer_raw(l, b0, n + pre, reversed);
let start = l.layer_time(sample_tick(b0, self.rate)).seconds();
let start = fx_clock(l, sample_tick(b0, self.rate));
for (id, g, p) in &fx {
if audio_fx::per_sample(id) && animated(g) {
self.process_stepped(l, id, g, &mut buf, b0);
@@ -257,7 +320,7 @@ impl MixEnv<'_> {
let end = usize::try_from(next.saturating_sub(b0)).unwrap_or(frames).clamp(k + 1, frames);
let t = sample_tick(i, self.rate);
if let Some(piece) = buf.get_mut(k * 2..end * 2) {
audio_fx::process(id, &self.params(l, g, t), piece, self.rate, l.layer_time(t).seconds());
audio_fx::process(id, &self.params(l, g, t), piece, self.rate, fx_clock(l, t));
}
k = end;
}
@@ -309,8 +372,9 @@ fn mix_into(sources: &AudioSources<'_>, comp_id: ItemId, start: Tick, out: &mut
let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l));
let s0 = start.to_units_floor(rate as i64);
for l in &comp.layers {
// The stretch the layer's time uses (#3247): 0 and NaN play at 100 %, as `layer_time`.
if !audible(project, l) || (any_solo && !l.switches.solo) || l.effective_stretch() <= 0.0 {
// The stretch the layer's time uses (#3247): 0 and NaN play at 100 %, as `layer_time`;
// a negative one plays backwards (#3239).
if !audible(project, l) || (any_solo && !l.switches.solo) {
continue;
}
// Sample range of the block that falls inside the layer's [in, out).
@@ -552,6 +616,11 @@ mod tests {
let base = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0));
let mut tone = build::layer(&mut p, &base, "tone", LayerSource::Footage { item: fid }, (0, 0), None);
tone.stretch = stretch;
// A reversed layer as After Effects lays it out: over [0, 2) s, starting at its out point.
let end = if stretch < 0.0 { 2.0 } else { 0.0 };
if stretch < 0.0 {
(tone.in_point, tone.out_point, tone.start_time) = (Tick::ZERO, Tick::from_seconds_f64(2.0), Tick::from_seconds_f64(2.0));
}
let mut comp = base.clone();
comp.layers = vec![tone].into();
let cid = p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.into()));
@@ -561,8 +630,11 @@ mod tests {
let speed = 100.0 / stretch;
let (mut worst, mut sq) = (0.0f64, 0.0f64);
for i in 0..n {
// The source plays `speed` times as fast as the comp: source time = speed * comp time.
let ideal = (std::f64::consts::TAU * 440.0 * speed * (t.seconds() + i as f64 / rate as f64)).sin() * 0.5;
// The source plays `speed` times as fast as the comp: source time = speed * (comp time −
// start). Reversed, a comp sample plays the source sample just before that time.
let back = if stretch < 0.0 { speed / rate as f64 } else { 0.0 };
let src = speed * (t.seconds() + i as f64 / rate as f64 - end) + back;
let ideal = (std::f64::consts::TAU * 440.0 * src).sin() * 0.5;
let e = (m[i * 2] as f64 - ideal).abs();
worst = worst.max(e);
sq += e * e;
@@ -581,4 +653,18 @@ mod tests {
assert!(worst < 1e-2, "stretch {stretch}%: error {worst} at 8 kHz");
}
}
/// A reversed layer plays its tone backwards with the same resampling quality as forwards
/// (it was silent, #3239); at -100 % the samples are copied exactly.
#[test]
fn reversed_layers_resample_a_tone_with_small_error() {
for stretch in [-70.0, -33.0] {
let (worst, _) = stretch_error(stretch, 48_000);
assert!(worst < 1e-3, "stretch {stretch}%: error {worst} at 48 kHz");
let (worst, _) = stretch_error(stretch, 8_000);
assert!(worst < 1e-2, "stretch {stretch}%: error {worst} at 8 kHz");
}
let (worst, _) = stretch_error(-100.0, 48_000);
assert!(worst < 1e-5, "stretch -100%: error {worst}");
}
}
+10
View File
@@ -630,6 +630,15 @@ fn group_has(g: &PropGroup, match_id: &str) -> bool {
})
}
/// A frame-blended layer's pixels also depend on how far its source runs during the comp frame:
/// a fast-conformed clip mixes every source frame the comp frame spans (#3180), so a time
/// stretch or remap change can alter the pixels at an unchanged source time.
fn hash_blend_spans(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) {
if crate::frames::frame_blend_mode(ctx, layer) != effectcraft_project::FrameBlend::Off {
crate::frames::blend_spans(ctx, layer).hash(h);
}
}
/// Feed every property of `g` that can change over time (keyframes or expression) as its value
/// at the context time. The static structure is hashed separately.
/// Mix the collapsed-instance overrides that target `id` into a cache key. They replace values
@@ -801,6 +810,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo
}
// Frame blending mixes neighbouring source frames.
ctx.comp.enable_frame_blending.hash(&mut h);
hash_blend_spans(&mut h, ctx, layer);
}
_ => return None,
}
+6 -1
View File
@@ -124,6 +124,8 @@ impl Dependencies<'_> {
Some(())
}
/// Folds what the layer contributes at this time into the dependency cache key, including its source, effects and frame blend state.
/// Returns `None` when the layer cannot be keyed: past the depth limit, in a reference cycle, or with expressions that read other times.
fn layer(&mut self, ctx: &EvalCtx, layer: &Layer) -> Option<()> {
let id = (ctx.comp_id, layer.id);
if self.path.len() > crate::MAX_FX_DEPTH || self.path.contains(&id) {
@@ -167,7 +169,10 @@ impl Dependencies<'_> {
hash_debug(self.h, &source);
if let Some(source) = source {
match &source.kind {
ItemKind::Footage(_) => ctx.source_time(layer).0.hash(self.h),
ItemKind::Footage(_) => {
ctx.source_time(layer).0.hash(self.h);
super::hash_blend_spans(self.h, ctx, layer);
}
ItemKind::Comp(comp) => {
let time = ctx.source_time(layer);
time.0.hash(self.h);
+1 -1
View File
@@ -231,7 +231,7 @@ impl FootageSource for CancellableFootage<'_> {
/// Footage that can be rasterised at any scale: SVG, PDF, Illustrator and EPS files, and a
/// placed page of an After Effects project (its codec is not stored there).
pub fn is_vector_footage(f: &Footage) -> bool {
matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS") || f.placed_page
matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS" | "VectorCraft") || f.placed_page
}
/// How vector footage `f` is drawn at `scale` × its size: the image size, and the x and y scale
+78
View File
@@ -89,6 +89,84 @@ pub fn frame_position(t: Tick, rate: FrameRate) -> (i64, f64) {
(num.div_euclid(den) as i64, num.rem_euclid(den) as f64 / den as f64)
}
/// The fewest source frames one comp frame must run through before frame blending averages all
/// of them ([`mix_window`]); below this the two neighbouring frames blend as they always have.
/// Conservative on purpose: common footage (60p in a 30, 25 or 24 fps comp, 50p in 25) keeps
/// its familiar look, while fast-conformed footage (600 fps in a 25 fps comp, #3180) gets the
/// mix. Pending a comparison with After Effects, whose exact threshold is not documented.
pub const MIN_MIX_FRAMES: f64 = 4.0;
/// The most source frames one comp frame mixes; a wider span is sampled at this many evenly
/// spaced frames (After Effects is reported to blend about a dozen; this also bounds the
/// decoding per comp frame). Pending a comparison with After Effects.
pub const MAX_MIX_FRAMES: usize = 16;
/// A span of more source frames than this in one comp frame is a jump (a time remap cut), not
/// motion to blur.
pub const MAX_MIX_SPAN: f64 = 1000.0;
/// How finely [`blend_spans`] probes the source's speed: at 1/16 of a comp frame.
const SPEED_PROBE: i64 = 16;
/// How far a frame-blended layer's source runs during one comp frame from the context time
/// (Interpret Footage's conformed rate, time stretch and time remap all show up in it), as
/// `(local, whole)`: the local speed just after the comp frame's time scaled to a whole frame,
/// and the actual difference to the next comp frame. They disagree across a time remap jump
/// (a hold keyframe followed by a cut, a `loopOut` wrapping back), which then does not mix.
/// Measured on the shown source time ([`EvalCtx::nested_time`]: a precomp proxy that preserves
/// its frame rate is floored to its frames).
pub(crate) fn blend_spans(ctx: &EvalCtx, layer: &Layer) -> (Tick, Tick) {
let frame = ctx.comp.frame_duration();
let t0 = ctx.nested_time(layer);
let probe = Tick(frame.0 / SPEED_PROBE);
let local = ctx.at(ctx.time + probe).nested_time(layer) - t0;
let whole = ctx.at(ctx.time + frame).nested_time(layer) - t0;
(Tick(local.0.saturating_mul(SPEED_PROBE)), whole)
}
/// The source frames a frame-blended comp frame averages when the layer runs through many
/// source frames per comp frame (footage interpreted at a much higher frame rate than the comp,
/// a sped-up time stretch or time remap), so a comp frame skips whole source frames: the frames
/// at `rate` that one comp frame's worth of source from `t` overlaps, each weighted by the share
/// of a frame it covers. `spans` is [`blend_spans`]' `(local, whole)`; playing forwards the span
/// is `[t, t + span)`, backwards it ends with the frame at `t` (the unblended frame). `None` —
/// the two neighbouring frames then blend ([`frame_position`], [`blend_frames`]) — when the span
/// is shorter than [`MIN_MIX_FRAMES`], longer than [`MAX_MIX_SPAN`], or the local speed and the
/// whole frame's difference disagree by more than a source frame (a time remap jump).
pub fn mix_window(t: Tick, spans: (Tick, Tick), rate: FrameRate) -> Option<Vec<(i64, f64)>> {
if rate.num <= 0 || rate.den <= 0 {
return None;
}
let frames_of = |s: Tick| s.0 as f64 * rate.num as f64 / (TICKS_PER_SECOND as f64 * rate.den as f64);
let width = frames_of(spans.0);
let whole = frames_of(spans.1);
if !width.is_finite() || !whole.is_finite() || (width - whole).abs() > 1.0 + 1e-9 {
return None;
}
if width.abs() < MIN_MIX_FRAMES - 1e-9 || width.abs() > MAX_MIX_SPAN {
return None;
}
let (i, w) = frame_position(t, rate);
let p = i as f64 + w;
let lo = if width < 0.0 { p + 1.0 + width } else { p };
let width = width.abs();
let hi = lo + width;
let first = lo.floor();
let n = hi.ceil() - first;
if n <= MAX_MIX_FRAMES as f64 {
let frames = (0..n as usize)
.filter_map(|k| {
let j = first + k as f64;
let cover = (j + 1.0).min(hi) - j.max(lo);
(cover > 1e-9).then_some((j as i64, cover))
})
.collect();
return Some(frames);
}
let m = MAX_MIX_FRAMES as f64;
Some((0..MAX_MIX_FRAMES).map(|k| ((lo + width * (k as f64 + 0.5) / m).floor() as i64, 1.0)).collect())
}
/// Blend two neighbouring frames `w` of the way from `a` to `b`: a cross-fade (Frame Mix) or a
/// motion-compensated interpolation (Pixel Motion).
pub fn blend_frames(mode: FrameBlend, a: &Image, b: &Image, w: f32) -> Image {
+1 -1
View File
@@ -50,7 +50,7 @@ pub use accel::{Accelerator, Backend, FrameMemory, FxStep, FxTarget};
pub use footage::{CancellableFootage, FloatCurve, FootageSource, NoFootage, is_vector_footage, missing_item_problem, vector_fit};
pub use frames::{
adaptive_samples, blend_frames, cineon_frame, content_bounds, extended_region, field_frame, frame_position, frame_size, interpret_pixels, kurbo_path,
render_frame, roi_inside,
mix_window, render_frame, roi_inside,
};
#[cfg(test)]
use fx_host::FxHost;
+79 -17
View File
@@ -93,6 +93,26 @@ pub struct Collapsed {
pub(crate) media_overrides: Vec<MediaOverride>,
}
/// Cache key of a frame-blended footage frame: `seed` (which frames, how they mix, the footage
/// file) and the Interpret Footage settings that change the decoded pixels.
fn blended_frame_key(f: &Footage, seed: impl std::hash::Hash) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
// Every file of a sequence: the key must tell two projects apart whose items share an id
// and a first frame (on disk, no project-wide salt does, #3184).
f.sequence.hash(&mut h);
(f.alpha as u8).hash(&mut h);
if f.alpha == effectcraft_project::AlphaMode::Premultiplied {
f.premul_color.map(f32::to_bits).hash(&mut h);
}
if f.cineon_applies() {
let c = &f.cineon;
[c.converted_black, c.converted_white, c.black, c.white, c.gamma, c.rolloff].map(f32::to_bits).hash(&mut h);
}
h.finish()
}
/// The property and media overrides of a collapsed precomp layer. `None` when its Essential
/// Properties group or the source comp's definitions are missing (the flattened path then
/// preserves the old behaviour).
@@ -1223,26 +1243,16 @@ impl<'a> Renderer<'a> {
let mode = frame_blend_mode(ctx, layer);
let float = self.pipe.float_curve(f);
if mode != FrameBlend::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) {
// Many source frames per comp frame (footage interpreted much faster than the comp,
// #3180): the frames the comp frame spans are averaged.
if let Some(img) = self.mixed_span_frame(ctx, layer, item, f, t, size) {
return Some(img);
}
let (i, w) = frame_position(t, f.frame_rate);
if w > 1e-6 {
// Blended frames are cached (Pixel Motion is expensive).
let key = self.cache.map(|_| {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
(0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h);
// Every file of a sequence: the key must tell two projects apart whose items
// share an id and a first frame (on disk, no project-wide salt does, #3184).
f.sequence.hash(&mut h);
(f.alpha as u8).hash(&mut h);
if f.alpha == effectcraft_project::AlphaMode::Premultiplied {
f.premul_color.map(f32::to_bits).hash(&mut h);
}
if f.cineon_applies() {
let c = &f.cineon;
[c.converted_black, c.converted_white, c.black, c.white, c.gamma, c.rolloff].map(f32::to_bits).hash(&mut h);
}
h.finish()
});
let seed = (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float);
let key = self.cache.map(|_| blended_frame_key(f, seed));
if let Some((b, _)) = self.cached(key) {
return Some(Arc::new(b.img.clone()));
}
@@ -1261,6 +1271,58 @@ impl<'a> Renderer<'a> {
self.read(|| self.footage.frame_with(item, f, t, size, float)).map(|img| cineon_frame(img, f))
}
/// A frame-blended footage frame at source time `t` when one comp frame runs through many
/// source frames: the average of the source frames the comp frame spans, each weighted by
/// the share of it the span covers ([`super::frames::mix_window`]). Both Frame Mix and
/// Pixel Motion average real frames here (there is no in-between frame to synthesise).
/// `size`: the frames may come resampled to it ([`FootageSource::frame_at_size`]). `None`
/// when the span is too short (or a jump) to mix, or no frame decodes.
fn mixed_span_frame(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option<Arc<Image>> {
use rayon::prelude::*;
let float = self.pipe.float_curve(f);
let spans = super::frames::blend_spans(ctx, layer);
let frames = super::frames::mix_window(t, spans, f.frame_rate)?;
let seed = (0x00f8_a3e6_u64, item, t.0, spans, size, f.frame_rate.num, f.frame_rate.den, &f.path, float);
let key = self.cache.map(|_| blended_frame_key(f, seed));
if let Some((b, _)) = self.cached(key) {
return Some(Arc::new(b.img.clone()));
}
// A weighted sum in one buffer, divided by the total weight at the end. A frame that does
// not decode, or has another size than the first (a sequence of mixed sizes), is left
// out and the mix renormalises over the rest. Log scans are converted before they mix.
let ((acc, total), files) = self.recorded(key, |r| {
let mut acc: Option<Image> = None;
let mut total = 0.0;
for (j, w) in frames {
let Some(img) = r.read(|| r.footage.frame_with(item, f, f.frame_rate.tick_of(j), size, float)).map(|a| cineon_frame(a, f)) else { continue };
let sum = acc.get_or_insert_with(|| Image::new(img.width, img.height));
if (sum.width, sum.height) != (img.width, img.height) {
continue;
}
let wf = w as f32;
sum.data.par_iter_mut().zip(img.data.par_iter()).for_each(|(s, p)| {
for (a, b) in s.iter_mut().zip(p) {
*a += b * wf;
}
});
total += w;
}
(acc, total)
});
let mut img = acc?;
if total <= 1e-9 {
return None;
}
let norm = (1.0 / total) as f32;
img.data.par_iter_mut().for_each(|s| {
for c in s.iter_mut() {
*c *= norm;
}
});
let _kept = self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files);
Some(Arc::new(img))
}
/// Source → masks, clamped/quantised to the project depth.
fn masked_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
let (mut buf, quantized) = match self.content_times(ctx, layer) {
+24
View File
@@ -927,6 +927,30 @@ fn effects_see_layer_masks() {
assert!(img.get(150, 50)[3] > 0.99, "mode None mask does not cut the layer");
}
/// Masks come before effects: Grid (Blending Mode None) draws only inside a masked solid (#3121).
#[test]
fn grid_stays_inside_the_layer_mask() {
let (mut p, cid, comp) = setup();
let mut l = solid(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100);
let mut next = p.next_id;
let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]);
p.next_id = next;
l.props.sub_mut("masks").unwrap().children.push(m.into());
// Inverted, the grid covers nearly every pixel, so the check does not depend on where the
// lines fall.
let set = [("width", Value::Scalar(10.0)), ("border", Value::Scalar(2.0)), ("invertGrid", Value::Bool(true))];
add_effect(&mut p, &mut l, "ec.generate.grid", [200.0, 100.0], &set);
p.comp_mut(cid).unwrap().layers.push(l);
let img = render_frame(&p, cid, Tick::ZERO, 1.0);
for y in 0..100 {
for x in 100..200 {
assert!(img.get(x, y)[3] < 0.01, "grid outside the mask at ({x}, {y}): {:?}", img.get(x, y));
}
}
assert!(img.get(15, 15)[3] < 0.01, "grid left of and above the mask: {:?}", img.get(15, 15));
assert!(img.get(55, 55)[3] > 0.5, "grid inside the mask: {:?}", img.get(55, 55));
}
/// An open mask (the Pen still drawing it) leaves the layer whole; closed, it masks (#290).
#[test]
fn open_masks_make_no_transparency() {
+217 -1
View File
@@ -1,13 +1,14 @@
//! Audio effects through the mixdown (the path preview playback and export share).
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use effectcraft_keyframe::{Keyframe, Value};
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, Solid};
use effectcraft_time::{FrameRate, Tick};
use crate::audio::{comp_has_audio, footage_peaks, mix_comp, peak_summary};
use crate::audio::{MAX_READ, comp_has_audio, footage_peaks, mix_comp, peak_summary};
use crate::{FootageSource, Image};
const SR: u32 = 8000;
@@ -109,6 +110,221 @@ fn backwards_reverses_the_layer_span() {
assert!((m[4000 * 2] - 0.5).abs() < 1e-3);
}
/// `comp_with`, its layer reversed at `stretch` (< 0) the way After Effects lays it out: in 0,
/// out `out` s, starting at the out point.
fn reversed(id: Option<&str>, vals: &[(&str, Value)], solid: bool, stretch: f64, out: f64) -> (Project, ItemId) {
let (mut p, cid) = comp_with(id, vals, solid);
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.stretch = stretch;
(l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(out), Tick::from_seconds_f64(out));
(p, cid)
}
/// A time-reversed layer plays its audio backwards instead of being silent (#3239): at -100 %
/// sample for sample what Backwards plays on the forward layer, in any block size.
#[test]
fn a_reversed_layer_plays_its_audio_backwards() {
let n = SR as usize;
let (p, cid) = reversed(None, &[], false, -100.0, 1.0);
let m = mix(&p, &Signal(ramp), cid, 0.0, n);
// Comp sample k plays source sample n − 1 − k.
for k in [0usize, 1, 2000, 4000, 7000] {
let want = (n - 1 - k) as f32 / SR as f32;
assert!((m[k * 2] - want).abs() < 1e-6 && (m[k * 2 + 1] + want).abs() < 1e-6, "k={k}: {} {}, want {want}", m[k * 2], m[k * 2 + 1]);
}
let (bp, bcid) = comp_with(Some("ec.audio.backwards"), &[], false);
assert_eq!(m, mix(&bp, &Signal(ramp), bcid, 0.0, n), "not the mirror Backwards plays");
let mut blocks = vec![];
for k in 0..n / 320 {
blocks.extend(mix(&p, &Signal(ramp), cid, (k * 320) as f64 / SR as f64, 320));
}
let worst = m.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(worst < 1e-6, "block size changes the result by {worst}");
}
/// The speed of a reversed layer follows its stretch as a forward one's does: -50 % plays the
/// source twice as fast, -200 % at half speed, both backwards.
#[test]
fn a_reversed_layer_plays_at_its_stretch() {
// -50 % over 0.5 s: comp sample k plays source sample 2 (n − 1 − k), n = 4000.
let (p, cid) = reversed(None, &[], false, -50.0, 0.5);
let m = mix(&p, &Signal(ramp), cid, 0.0, 4000);
for k in [0usize, 1000, 3000] {
let want = 2.0 * (3999 - k) as f32 / SR as f32;
assert!((m[k * 2] - want).abs() < 1e-6, "-50 %, k={k}: {}, want {want}", m[k * 2]);
}
// -200 % over 2 s: comp sample k plays source sample (n − 1 − k) / 2, n = 16000, blended.
let (p, cid) = reversed(None, &[], false, -200.0, 2.0);
let m = mix(&p, &Signal(ramp), cid, 0.0, 16_000);
for k in [0usize, 1, 5001, 12_000] {
let want = (15_999 - k) as f32 / 2.0 / SR as f32;
assert!((m[k * 2] - want).abs() < 1e-5, "-200 %, k={k}: {}, want {want}", m[k * 2]);
}
}
/// Backwards on a reversed layer plays it forwards: the two reversals cancel.
#[test]
fn backwards_on_a_reversed_layer_plays_forwards() {
let (p, cid) = reversed(Some("ec.audio.backwards"), &[], false, -100.0, 1.0);
let (fp, fcid) = comp_with(None, &[], false);
for (from, frames) in [(0.0, SR as usize), (0.25, 2000)] {
let m = mix(&p, &Signal(ramp), cid, from, frames);
assert!(m.iter().any(|v| v.abs() > 0.1), "silent from {from} s");
assert_eq!(m, mix(&fp, &Signal(ramp), fcid, from, frames), "from {from} s");
}
}
/// Effects on a reversed layer run on a clock that moves forwards with the samples at comp speed,
/// so a Tone joins up across blocks (preview's frame blocks and export's one-second blocks
/// agree), at -50 % too. On the layer-time clock, block k at -100 % would start 0.08 k s off:
/// 35.2 k cycles at 440 Hz, a phase jump.
#[test]
fn tone_on_a_reversed_layer_joins_up_across_blocks() {
let mut vals: Vec<(&str, Value)> = vec![("frequency1", Value::Scalar(440.0))];
for k in ["frequency2", "frequency3", "frequency4", "frequency5"] {
vals.push((k, Value::Scalar(0.0)));
}
for stretch in [-100.0, -50.0] {
let (p, cid) = reversed(Some("ec.audio.tone"), &vals, true, stretch, 1.0);
let long = mix(&p, &Signal(ramp), cid, 0.2, 1600);
assert!(rms(&long) > 0.05, "{stretch} %: silent: {}", rms(&long));
let mut blocks = vec![];
for k in 0..5 {
blocks.extend(mix(&p, &Signal(ramp), cid, 0.2 + k as f64 * 0.04, 320));
}
let worst = long.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(worst < 1e-3, "{stretch} %: block size changes the tone by {worst}");
}
}
/// Footage audio on its sample grid, as the media pool decodes it: a read from any time starts
/// at the sample at or before it. Sample n is `f(n / rate)` over [0, 2) s.
struct Grid(fn(f64) -> (f32, f32));
impl FootageSource for Grid {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
None
}
fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {
let s0 = start.to_units_floor(i64::from(rate));
Some(
(0..frames as i64)
.flat_map(|i| {
let t = (s0 + i) as f64 / rate as f64;
let (l, r) = if (0.0..2.0).contains(&t) { (self.0)(t) } else { (0.0, 0.0) };
[l, r]
})
.collect(),
)
}
}
/// A stretched layer, forwards or reversed, gives the same samples mixed in one block as in
/// blocks of any size (preview's video-frame blocks, export's seconds): each block resamples
/// from the exact source position, not from the source sample a block happens to start on.
#[test]
fn stretched_layers_join_up_across_blocks() {
// (stretch, out point, start): the reversed layers start at their out point, the -50 % one
// off the sample grid (a third of a sample late), so its source positions are fractional.
let third = Tick(Tick::from_seconds_f64(1.0 / SR as f64).0 / 3);
for (stretch, out, start) in [
(200.0, 2.0, Tick::ZERO),
(-70.0, 0.7, Tick::from_seconds_f64(0.7)),
(-50.0, 0.5, Tick(Tick::from_seconds_f64(0.5).0 + third.0)),
(-200.0, 2.0, Tick::from_seconds_f64(2.0)),
] {
let (mut p, cid) = comp_with(None, &[], false);
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.stretch = stretch;
(l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(out), start);
let n = 3210;
let long = mix(&p, &Grid(ramp), cid, 0.1, n);
assert!(long.iter().any(|v| v.abs() > 0.05), "{stretch} %: silent");
for block in [321, 107] {
let mut blocks = vec![];
for k in 0..n / block {
blocks.extend(mix(&p, &Grid(ramp), cid, 0.1 + (k * block) as f64 / SR as f64, block));
}
let worst = long.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(worst < 1e-6, "{stretch} %, blocks of {block}: off by {worst}");
}
}
}
/// At 200 % the last sample of a block blends with the source sample after it, as inside the
/// block, instead of holding the one before.
#[test]
fn a_stretched_block_ends_on_a_blended_sample() {
let (mut p, cid) = comp_with(None, &[], false);
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.stretch = 200.0;
(l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(2.0), Tick::ZERO);
let m = mix(&p, &Grid(ramp), cid, 0.0, 320);
// Comp sample 319 plays source position 159.5.
let want = 159.5 / SR as f32;
assert!((m[319 * 2] - want).abs() < 1e-6, "{}, want {want}", m[319 * 2]);
}
/// Records the longest audio read and answers with a short run, so an unbounded request fails
/// the assert below instead of allocating.
struct Longest(AtomicUsize);
impl FootageSource for Longest {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
None
}
fn audio(&self, _: ItemId, _: &Footage, _: Tick, frames: usize, _: u32) -> Option<Vec<f32>> {
self.0.fetch_max(frames, Ordering::Relaxed);
Some(vec![0.25; frames.min(4096) * 2])
}
}
/// Tiny, huge, zero and non-finite stretches, and fast precomps nested in fast precomps, read
/// at most MAX_READ source frames at a time and mix to finite samples (a tiny positive stretch
/// asked for 10⁸ times the block, and its precomp buffer could abort the process).
#[test]
fn extreme_stretches_read_bounded_source() {
let stretches = [1e-6, -1e-6, 0.5, -0.5, 1.0, -1.0, 1e12, -1e12, f64::MIN_POSITIVE, 0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY];
for stretch in stretches {
let (mut p, cid) = comp_with(None, &[], false);
p.comp_mut(cid).unwrap().layers[0].stretch = stretch;
let src = Longest(AtomicUsize::new(0));
let m = mix(&p, &src, cid, 0.0, 800);
let longest = src.0.load(Ordering::Relaxed);
assert!(longest <= MAX_READ, "stretch {stretch}: read {longest} frames at once");
assert!(m.iter().all(|v| v.is_finite()), "stretch {stretch}");
}
// Exactly 1 %, give or take float noise, stays audible.
let (mut p, cid) = comp_with(None, &[], false);
p.comp_mut(cid).unwrap().layers[0].stretch = 1.0 - 1e-12;
let m = mix(&p, &Longest(AtomicUsize::new(0)), cid, 0.0, 800);
assert!(m.iter().any(|v| *v != 0.0), "1 % is silent");
// A 1 % footage layer in a 1 % precomp: 10⁴ source samples per comp sample. The precomp layer
// lasts 0.02 s, which plays the inner layer's 2 s once (backwards from its out point at -1 %).
for sign in [1.0, -1.0] {
let mut p = Project::default();
let base = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0));
let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(audio_footage()));
let mut inner_l = build::layer(&mut p, &base, "a", LayerSource::Footage { item: fid }, (64, 64), None);
inner_l.stretch = sign;
(inner_l.in_point, inner_l.out_point, inner_l.start_time) =
(Tick::ZERO, Tick::from_seconds_f64(2.0), if sign < 0.0 { Tick::from_seconds_f64(2.0) } else { Tick::ZERO });
let mut inner = base.clone();
inner.layers = vec![inner_l].into();
let inner_id = p.add_item("Inner", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(inner.into()));
let mut pre = build::layer(&mut p, &base, "pre", LayerSource::Comp { item: inner_id }, (64, 64), None);
pre.stretch = sign;
let pre_out = Tick::from_seconds_f64(0.02);
(pre.in_point, pre.out_point, pre.start_time) = (Tick::ZERO, pre_out, if sign < 0.0 { pre_out } else { Tick::ZERO });
let mut outer = base.clone();
outer.layers = vec![pre].into();
let outer_id = p.add_item("Outer", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(outer.into()));
let src = Longest(AtomicUsize::new(0));
let m = mix(&p, &src, outer_id, 0.0, 800);
let longest = src.0.load(Ordering::Relaxed);
assert!(longest > 0 && longest <= MAX_READ, "nested {sign}%: read {longest} frames at once");
assert!(m.iter().all(|v| v.is_finite()));
}
}
#[test]
fn high_low_pass_attenuates() {
fn hi(t: f64) -> (f32, f32) {
+177 -4
View File
@@ -5,12 +5,13 @@ use std::sync::Arc;
use rayon::prelude::*;
use effectcraft_color::Label;
use effectcraft_keyframe::{Keyframe, Value};
use effectcraft_keyframe::{Interp, Keyframe, Value};
use effectcraft_project::build;
use effectcraft_project::{AlphaMode, BitDepth, Comp, Footage, FootageKind, FrameBlend, ItemId, ItemKind, LayerSource, Project, Solid};
use effectcraft_time::{FrameRate, Tick};
use crate::{FootageSource, Image, RenderOpts, Renderer, frame_position};
use crate::frames::MAX_MIX_FRAMES;
use crate::{FootageSource, Image, RenderOpts, Renderer, frame_position, mix_window};
#[test]
fn frame_mix_weights_for_24_to_30_conform() {
@@ -57,7 +58,13 @@ impl FootageSource for Frames {
}
}
/// [`setup_rated`] with 24 fps footage and no recorded native rate.
fn setup(mode: FrameBlend, size: (u32, u32)) -> (Project, ItemId) {
setup_rated(mode, size, FrameRate::FPS_24, None)
}
/// [`setup`] with footage at `rate` (its Interpret Footage frame rate) recorded at `native`.
fn setup_rated(mode: FrameBlend, size: (u32, u32), rate: FrameRate, native: Option<FrameRate>) -> (Project, ItemId) {
let mut p = Project::default();
p.settings.bit_depth = BitDepth::Bpc32;
let comp = Comp::new(size.0, size.1, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
@@ -68,8 +75,8 @@ fn setup(mode: FrameBlend, size: (u32, u32)) -> (Project, ItemId) {
width: size.0,
height: size.1,
pixel_aspect: 1.0,
frame_rate: FrameRate::FPS_24,
native_rate: None,
frame_rate: rate,
native_rate: native,
duration: Tick::from_seconds_f64(2.0),
has_video: true,
has_audio: false,
@@ -168,6 +175,172 @@ fn time_stretched_precomp_frame_mixes() {
assert!(img.get(12, 10)[3] < 1e-3 && (img.get(17, 10)[3] - 1.0).abs() < 1e-3 && (img.get(22, 10)[3] - 1.0).abs() < 1e-3 && img.get(27, 10)[3] < 1e-3);
}
/// Fast-conformed footage (30 fps interpreted as 300 fps) averages every source frame a comp frame spans, for Frame Mix and Pixel Motion.
#[test]
fn frame_mix_averages_every_frame_of_fast_conformed_footage() {
// #3180: 30 fps footage interpreted as 300 fps in a 30 fps comp. Every comp frame lands
// exactly on a source frame, but it spans ten of them: frame blending averages all ten
// (greys 0.0 … 0.9 → 0.45), not just the frame it starts on (0.0).
let fast = FrameRate::new(300, 1);
let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
let v = frame(&p, cid, 0, false).get(4, 4)[0];
assert!((v - 0.45).abs() < 1e-5, "{v}");
// Pixel Motion has no in-between frame to make either: it averages the same frames.
let (p, cid) = setup_rated(FrameBlend::PixelMotion, (16, 8), fast, Some(FrameRate::FPS_30));
let v = frame(&p, cid, 0, false).get(4, 4)[0];
assert!((v - 0.45).abs() < 1e-5, "{v}");
// Off (layer switch or comp switch): the one frame at the comp frame's time.
let (p, cid) = setup_rated(FrameBlend::Off, (16, 8), fast, Some(FrameRate::FPS_30));
assert!(frame(&p, cid, 0, false).get(4, 4)[0].abs() < 1e-6);
let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
p.comp_mut(cid).unwrap().enable_frame_blending = false;
assert!(frame(&p, cid, 0, false).get(4, 4)[0].abs() < 1e-6);
}
/// Footage at the comp's rate, or only mildly faster, renders as before.
#[test]
fn frame_mix_of_common_footage_is_unchanged() {
// Footage at the comp's rate: each comp frame is exactly one source frame, blended or not.
let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), FrameRate::FPS_30, None);
for k in 0..4 {
let v = frame(&p, cid, k, false).get(4, 4)[0];
assert!((v - k as f32 / 10.0).abs() < 1e-6, "comp frame {k}: {v}");
}
// A mild speed-up (36 fps footage in a 30 fps comp) keeps the two-frame cross-fade: comp
// frame 1 → source frame 1.2, 0.8·frame 1 + 0.2·frame 2 = 0.12.
let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), FrameRate::new(36, 1), None);
let v = frame(&p, cid, 1, false).get(4, 4)[0];
assert!((v - 0.12).abs() < 1e-6, "{v}");
// 60 and 90 fps in a 30 fps comp (two and three source frames per comp frame) stay crisp:
// comp frame 1 is source frame 2 or 3, as before.
for (rate, want) in [(FrameRate::FPS_60, 0.2), (FrameRate::new(90, 1), 0.3)] {
let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), rate, None);
let v = frame(&p, cid, 1, false).get(4, 4)[0];
assert!((v - want).abs() < 1e-6, "{rate:?}: {v}");
}
}
/// Adds Time Remap with `keys` (layer time → source seconds) to the comp's footage layer.
fn remap(p: &mut Project, cid: ItemId, keys: Vec<Keyframe>) {
let mut next = p.next_id;
let mut tr = build::Ids(&mut next).prop("timeRemap", "Time Remap", Value::Scalar(0.0));
p.next_id = next;
tr.keys = keys;
p.comp_mut(cid).unwrap().layers[0].props.children.push(effectcraft_project::Node::Prop(tr));
}
/// Time remap holds and cuts do not smear: a still frame stays a single source frame.
#[test]
fn time_remap_jumps_stay_crisp() {
let fast = FrameRate::new(300, 1);
let s = |frames: f64| Value::Scalar(frames / 300.0);
let at = |k: i64| FrameRate::FPS_30.tick_of(k);
// Hold on source frame 0, then cut to source frame 10 at comp frame 1: comp frame 0 is a
// still frame, not a smear of the ten frames the cut skips.
let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
remap(&mut p, cid, vec![Keyframe::new(at(0), s(0.0)).hold(), Keyframe::new(at(1), s(10.0)).hold()]);
let v = frame(&p, cid, 0, false).get(4, 4)[0];
assert!(v.abs() < 1e-6, "hold then cut: {v}");
// A loop wrapping back (like `loopOut("cycle")`): from source frame 10 at normal speed,
// back to frame 0 by the next comp frame. Comp frame 0 shows frame 10 (grey 1.0), not
// frames 1 … 10 run backwards.
let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
let mut top = Keyframe::new(FrameRate::FPS_60.tick_of(1), s(15.0));
top.out_interp = Interp::Hold;
remap(&mut p, cid, vec![Keyframe::new(at(0), s(10.0)), top, Keyframe::new(at(1), s(0.0))]);
let v = frame(&p, cid, 0, false).get(4, 4)[0];
assert!((v - 1.0).abs() < 1e-6, "loop wrap: {v}");
// A remap running at normal speed through fast-conformed footage still mixes its frames.
let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
remap(&mut p, cid, vec![Keyframe::new(at(0), s(0.0)), Keyframe::new(at(30), s(300.0))]);
let v = frame(&p, cid, 0, false).get(4, 4)[0];
assert!((v - 0.45).abs() < 1e-5, "steady remap: {v}");
}
/// A frame-blended dependency changes its owner's cache key when its source goes from holding to running at speed.
#[test]
fn a_frame_blended_dependency_keys_how_far_its_source_runs() {
// A footage layer selected by another layer's effect: at comp frames 0 and 1 its source time
// is the same (0), but at frame 0 it holds and at frame 1 it runs at speed, which mixes ten
// source frames. The owner's cache key must tell the two apart.
let fast = FrameRate::new(300, 1);
let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30));
let at = |k: i64| FrameRate::FPS_30.tick_of(k);
let keys = vec![Keyframe::new(at(0), Value::Scalar(0.0)).hold(), Keyframe::new(at(1), Value::Scalar(0.0)), Keyframe::new(at(31), Value::Scalar(1.0))];
remap(&mut p, cid, keys);
let comp = p.comp(cid).unwrap().clone();
let footage = comp.layers[0].id;
let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [1.0; 3], width: 16, height: 8, pixel_aspect: 1.0 }));
let mut owner = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (16, 8), None);
super::add_effect(&mut p, &mut owner, "ec.channel.setmatte", [16.0, 8.0], &[("takeMatteFromLayer", Value::Layer(Some(footage.0)))]);
p.comp_mut(cid).unwrap().layers.push(owner);
let key = |k: i64| {
let c = p.comp(cid).unwrap();
crate::cache::layer_key(&crate::EvalCtx::new(&p, cid, c, at(k)), &c.layers[1], 1.0, false, false).unwrap()
};
assert_ne!(key(0), key(1));
}
/// The mix window is the source span of one comp frame, and falls back to the two-frame blend below four source frames per comp frame.
#[test]
fn mix_window_covers_the_source_span_of_one_comp_frame() {
let comp_frame = |r: FrameRate| r.frame_duration();
let steady = |r: FrameRate| (comp_frame(r), comp_frame(r));
// Fewer than four source frames per comp frame (slow-down, same rate, 60p in 30, 24 or 25,
// 50p in 25, 90 in 30): the two-frame blend applies, as before.
for (comp, footage) in [
(FrameRate::FPS_30, FrameRate::FPS_30),
(FrameRate::FPS_30, FrameRate::FPS_24),
(FrameRate::FPS_30, FrameRate::new(36, 1)),
(FrameRate::FPS_25, FrameRate::FPS_30),
(FrameRate::FPS_30, FrameRate::FPS_60),
(FrameRate::FPS_24, FrameRate::FPS_60),
(FrameRate::FPS_25, FrameRate::FPS_60),
(FrameRate::FPS_25, FrameRate::FPS_50),
(FrameRate::FPS_29_97, FrameRate::FPS_59_94),
(FrameRate::FPS_30, FrameRate::new(90, 1)),
] {
assert_eq!(mix_window(Tick::ZERO, steady(comp), footage), None, "{footage:?} in {comp:?}");
}
// Four source frames per comp frame: 120 fps in a 30 fps comp mixes all four.
assert_eq!(mix_window(Tick::ZERO, steady(FrameRate::FPS_30), FrameRate::FPS_120), Some(vec![(0, 1.0), (1, 1.0), (2, 1.0), (3, 1.0)]));
// The report's case: 600 fps in a 25 fps comp, 24 source frames per comp frame, sampled at
// 16 evenly spread frames.
let w = mix_window(FrameRate::FPS_25.tick_of(3), steady(FrameRate::FPS_25), FrameRate::new(600, 1)).unwrap();
assert_eq!(w.len(), MAX_MIX_FRAMES);
assert!(w.iter().all(|x| (72..96).contains(&x.0) && x.1 == 1.0), "{w:?}");
assert!(w.windows(2).all(|p| p[0].0 < p[1].0), "{w:?}");
// 150 fps in a 30 fps comp: comp frame 1 spans source frames 5 … 10.
let w = mix_window(FrameRate::FPS_30.tick_of(1), steady(FrameRate::FPS_30), FrameRate::new(150, 1));
assert_eq!(w, Some((5..10).map(|j| (j, 1.0)).collect()));
// 135 fps in a 30 fps comp: comp frame 1 spans source frames 4.5 … 9.0.
let w = mix_window(FrameRate::FPS_30.tick_of(1), steady(FrameRate::FPS_30), FrameRate::new(135, 1)).unwrap();
assert_eq!(w.iter().map(|x| x.0).collect::<Vec<_>>(), vec![4, 5, 6, 7, 8]);
for (got, want) in w.iter().map(|x| x.1).zip([0.5, 1.0, 1.0, 1.0, 1.0]) {
assert!((got - want).abs() < 1e-9, "{w:?}");
}
// Playing backwards: the span ends with the comp frame's own source frame.
let back = -comp_frame(FrameRate::FPS_30);
let w = mix_window(FrameRate::FPS_30.tick_of(1), (back, back), FrameRate::new(300, 1)).unwrap();
assert_eq!(w.iter().map(|x| x.0).collect::<Vec<_>>(), (1..=10).collect::<Vec<_>>());
// A hold (no local speed) or a jump (local speed and the whole frame disagree) does not mix.
let f = comp_frame(FrameRate::FPS_30);
assert_eq!(mix_window(Tick::ZERO, (Tick::ZERO, f), FrameRate::new(300, 1)), None);
assert_eq!(mix_window(Tick::ZERO, (f, -f), FrameRate::new(300, 1)), None);
// A long span is sampled at a bounded number of frames; a span beyond any footage's speed is
// a jump.
let ten = Tick::from_seconds_f64(10.0);
let w = mix_window(Tick::ZERO, (ten, ten), FrameRate::FPS_60).unwrap();
assert_eq!(w.len(), MAX_MIX_FRAMES);
assert!(w.iter().all(|x| (0..600).contains(&x.0)));
let far = Tick::from_seconds_f64(100.0);
assert_eq!(mix_window(Tick::ZERO, (far, far), FrameRate::FPS_60), None);
// Degenerate rates and huge spans don't panic.
assert_eq!(mix_window(Tick::ZERO, (Tick::MAX, Tick::MAX), FrameRate { num: 0, den: 1 }), None);
assert_eq!(mix_window(Tick::MIN, (Tick::MAX, Tick::MAX), FrameRate::FPS_60), None);
assert_eq!(mix_window(Tick::MAX, (Tick::MIN, Tick::MAX), FrameRate::FPS_60), None);
}
#[test]
fn frame_position_survives_degenerate_rates() {
for rate in [FrameRate { num: 24, den: 0 }, FrameRate { num: 0, den: 1 }, FrameRate { num: -24, den: 1 }] {
+19 -11
View File
@@ -33,6 +33,7 @@ fn layer_of<'a>(s: &'a Session, a: &J) -> Result<(ItemId, &'a Comp, &'a Layer),
Ok((cid, c, l))
}
/// Answers a script model query of the given `kind` against the session, dispatching to the matching reader, and errors on an unknown kind.
pub fn query(s: &mut Session, kind: &str, a: &J) -> R {
match kind {
"project" => Ok(project(s)),
@@ -52,13 +53,7 @@ pub fn query(s: &mut Session, kind: &str, a: &J) -> R {
let i = u(a, "index").unwrap_or(0) as usize;
Ok(effectcraft_engine::command_specs().get(i.wrapping_sub(1)).map(|c| json!(c.id)).unwrap_or(J::Null))
}
"exprError" => {
let code = a.get("code").and_then(J::as_str).unwrap_or("");
Ok(match s.expr_check {
Some(check) => json!(check(code).err().unwrap_or_default()),
None => json!(""),
})
}
"exprError" => expr_error(s, a),
"labels" => Ok(json!(Label::ALL.iter().map(|l| l.name()).collect::<Vec<_>>())),
"effects" => Ok(json!(
effectcraft_engine::effects::all()
@@ -532,6 +527,7 @@ fn text_json(d: &TextDoc) -> J {
doc
}
/// Returns the property's value at the requested time, evaluating its expression unless `pre` is set.
fn value(s: &Session, a: &J) -> R {
let (cid, c, l) = layer_of(s, a)?;
let uid = u(a, "uid").ok_or("missing uid")?;
@@ -541,16 +537,28 @@ fn value(s: &Session, a: &J) -> R {
let v = if pre || !p.has_expression() {
p.value_at(l.layer_time(t))
} else {
let mut ctx = EvalCtx::new(&s.project, cid, c, t);
ctx.expr = s.expr.as_deref();
// Sample expressions (`sampleImage`) read footage through the session's source; without
// it footage layers sample as transparent (#1000).
ctx.footage = Some(s.footage.as_ref());
ctx.value(l, p)
effectcraft_engine::commands::expr_tools::eval_ctx(s, cid, c, t).value(l, p)
};
Ok(js_value(c, &v))
}
/// `Property.expressionError`: why the property's expression fails at the comp's current time
/// (where After Effects evaluates it; the prelude sends no `time`, a direct query may give one
/// in comp seconds). The message is the one `expr.errors` gives: an evaluation error (an
/// exception or a non-finite result) or the syntax error that disabled it; `""` when it
/// evaluates (#3219).
fn expr_error(s: &Session, a: &J) -> R {
let (cid, c, l) = layer_of(s, a)?;
let uid = u(a, "uid").ok_or("missing uid")?;
let p = l.props.find(uid).ok_or("the property no longer exists (it was deleted)")?;
let t = f(a, "time").map(Tick::from_seconds_f64).unwrap_or_else(|| s.time_of(cid));
// With the footage source, like `value`: `sampleImage` must not fail for want of it (#1000).
let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, c, t) };
Ok(json!(effectcraft_engine::commands::expr_tools::property_error(&ctx, s.expr_check, l, p).unwrap_or_default()))
}
fn interp(i: Interp) -> &'static str {
match i {
Interp::Linear => "LINEAR",
+2 -2
View File
@@ -868,8 +868,8 @@ Property.prototype.property = function () { return null; };
__call("prop.setExpression", this.__ref({ enabled: !!v }));
});
def("expressionError", function () {
var e = this.expression;
return e ? __get("exprError", { code: e }) : "";
// Evaluated at the comp's current time, so a runtime error or a non-finite result shows too.
return this.expression ? __get("exprError", { comp: this.__layer.__comp, layer: this.__layer.__id, uid: this.__uid }) : "";
});
def("canSetExpression", function () { return !!this.__info().canSetExpression; });
def("canVaryOverTime", function () { return !!this.__info().canVaryOverTime; });
+35
View File
@@ -1306,6 +1306,41 @@ fn sample_image_reads_footage_pixels_in_scripts() {
assert_eq!(out.result, json!([0, 1, 0, 1, ""]), "green footage sampled, not transparent black");
}
/// `expressionError` reports what evaluating the expression at the comp's current time does, as
/// After Effects: a non-finite result and an exception, not only a syntax error (#3219).
#[test]
fn expression_error_reports_evaluation_errors() {
let mut s = session();
let out = ok(
&mut s,
r#"
var c = app.project.items.addComp("E", 320, 240, 1, 5, 30);
var p = c.layers.addSolid([1, 1, 1], "S", 320, 240, 1).transform.opacity;
p.expression = "Math.sqrt(-1)";
var nan = p.expressionError;
p.expression = 'throw new Error("boom")';
var thrown = p.expressionError;
p.expression = "value";
var fine = p.expressionError;
p.expression = "thisLayer.nope(";
var syntax = p.expressionError;
p.expression = "time > 1 ? Math.sqrt(-1) : value";
c.time = 0;
var early = p.expressionError;
c.time = 2;
var late = p.expressionError;
[nan, thrown, fine, syntax.length > 0, early, late];
"#,
);
let v = out.result;
assert!(v[0].as_str().is_some_and(|e| e.contains("not a finite number")), "{v}");
assert!(v[1].as_str().is_some_and(|e| e.contains("boom")), "{v}");
assert_eq!(v[2], json!(""), "{v}");
assert_eq!(v[3], json!(true), "a syntax error is still reported: {v}");
assert_eq!(v[4], json!(""), "evaluated at the current time (0), where it is fine: {v}");
assert!(v[5].as_str().is_some_and(|e| e.contains("not a finite number")), "evaluated at the current time (2): {v}");
}
#[test]
fn binary_file_io_preserves_all_byte_values() {
let dir = std::env::temp_dir().join(format!("ec-script-binary-{}", std::process::id()));
+191
View File
@@ -69,15 +69,34 @@ pub fn try_rasterize_with(doc: &Doc, w: u32, h: u32, m: Affine) -> Result<Image,
/// Render `doc`, returning the image drawn so far and the first budget refusal, if any.
fn render(doc: &Doc, w: u32, h: u32, m: Affine) -> (Image, Option<RasterError>) {
render_with_limit(doc, w, h, m, MAX_LIVE_SURFACE_BYTES)
}
/// [`rasterize_with`] with at most `limit_bytes` of image surfaces (the destination included)
/// live at once.
#[cfg(test)]
pub(crate) fn rasterize_with_budget(doc: &Doc, w: u32, h: u32, m: Affine, limit_bytes: usize) -> Image {
render_with_limit(doc, w, h, m, limit_bytes).0
}
/// [`render`] with the live surface limit set to `limit_bytes`.
fn render_with_limit(doc: &Doc, w: u32, h: u32, m: Affine, limit_bytes: usize) -> (Image, Option<RasterError>) {
// Nested knockout and non-isolated groups draw their children more than once; the number of
// node draws is bounded by a multiple of the tree's size, past which drawing stops.
let mut budget = SurfaceBudget::new();
budget.limit_bytes = limit_bytes;
budget.draws_left = node_count(&doc.root).saturating_mul(MAX_DRAWS_PER_NODE).max(MIN_DRAWS);
let Some(mut img) = budget.image(w, h, None) else { return (Image::default(), budget.refusal) };
draw_group(&doc.root, m, 1.0, &mut img, &mut budget);
(img, budget.refusal)
}
/// The deepest group nesting drawn: drawing recurses, and a crafted document can nest groups
/// without end, so groups deeper than this are not drawn. Above the 256 levels the SVG parser
/// and the PDF builder let a document nest, so everything they keep is drawn (the root group
/// and wrappers come on top).
const MAX_GROUP_DEPTH: usize = 288;
/// Bound the simultaneously live offscreen image surfaces created by nested groups.
const MAX_LIVE_SURFACE_BYTES: usize = 512 * 1024 * 1024;
/// Bound tile allocation and rasterisation work across one SVG render, even though each tile is
@@ -248,6 +267,11 @@ struct SurfaceBudget {
refusal: Option<RasterError>,
/// Node draws left (see [`MAX_DRAWS_PER_NODE`]).
draws_left: usize,
/// Groups entered on the way to the one being drawn.
depth: usize,
/// Every group being drawn below the current one composites Normal, without knockout
/// (known once for a whole subtree, so it isn't walked again at every level).
plain: bool,
}
impl SurfaceBudget {
@@ -268,6 +292,8 @@ impl SurfaceBudget {
limit_bytes: MAX_LIVE_SURFACE_BYTES,
refusal: None,
draws_left: usize::MAX,
depth: 0,
plain: false,
}
}
@@ -420,6 +446,15 @@ impl SurfaceBudget {
}
fn draw_group(g: &Group, m: Affine, opacity: f64, dst: &mut Image, budget: &mut SurfaceBudget) {
if budget.depth >= MAX_GROUP_DEPTH {
return;
}
budget.depth += 1;
draw_group_entered(g, m, opacity, dst, budget);
budget.depth -= 1;
}
fn draw_group_entered(g: &Group, m: Affine, opacity: f64, dst: &mut Image, budget: &mut SurfaceBudget) {
let m = m * g.transform;
let o = opacity * g.opacity;
if o <= 0.0 {
@@ -436,9 +471,158 @@ fn draw_group(g: &Group, m: Affine, opacity: f64, dst: &mut Image, budget: &mut
}
return;
}
let only_clip = !g.clip.is_empty() && g.mask.is_none() && g.blend == BlendMode::Normal && o >= 1.0 && !g.knockout;
let plain = only_clip && (budget.plain || !needs_backdrop(&g.children, MAX_GROUP_DEPTH.saturating_sub(budget.depth)));
if plain {
let outer = std::mem::replace(&mut budget.plain, true);
let left = MAX_GROUP_DEPTH.saturating_sub(budget.depth);
if clips_cover_content(g, m, dst.width, dst.height, left) {
for c in &g.children {
draw_node(c, m, 1.0, dst, budget);
}
} else {
draw_clip_local(g, m, dst, budget);
}
budget.plain = outer;
return;
}
draw_offscreen_group(g, m, o, dst, budget);
}
/// Whether every clip of `g` is a rectangle along the pixel grid's axes that fully covers each
/// pixel of a `w`×`h` image its children can draw on: the clips change nothing there, so the
/// children are drawn straight onto the image, without a surface (a page or artboard clip
/// around the artwork inside it, the outermost groups of most PDF pages). `levels`: how many
/// levels of groups below are drawn.
fn clips_cover_content(g: &Group, m: Affine, w: u32, h: u32, levels: usize) -> bool {
let Some(rects) = g.clip.iter().map(|(p, _)| axis_rect(p, m)).collect::<Option<Vec<_>>>() else { return false };
// Children that draw nothing need no clip.
let Some(b) = draw_bounds(&g.children, m, levels) else { return true };
let (fw, fh) = (f64::from(w), f64::from(h));
// The pixels the children can touch (a pixel of margin for anti-aliasing), on the image.
let (bx0, by0) = ((b.x0.floor() - 1.0).max(0.0), (b.y0.floor() - 1.0).max(0.0));
let (bx1, by1) = ((b.x1.ceil() + 1.0).min(fw), (b.y1.ceil() + 1.0).min(fh));
if !(bx0 < bx1 && by0 < by1) {
// Nothing reaches the image (or the bounds aren't numbers): keep the clip.
return false;
}
rects.iter().all(|r| r.x0.ceil() <= bx0 && bx1 <= r.x1.floor() && r.y0.ceil() <= by0 && by1 <= r.y1.floor())
}
/// A device-space rectangle holding every pixel `nodes` drawn with `m` can cover, `None` when
/// they draw nothing. Cheap rather than tight: a stroke counts as its path's bounds grown by half
/// its width times its miter limit (at least √2, for square caps), and anything it can't
/// bound (more than `levels` levels deep, a transform that isn't finite) as the whole plane.
fn draw_bounds(nodes: &[Node], m: Affine, levels: usize) -> Option<kurbo::Rect> {
let everything = kurbo::Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY);
if !m.as_coeffs().iter().all(|v| v.is_finite()) {
return Some(everything);
}
let mut out: Option<kurbo::Rect> = None;
for n in nodes {
let r = match n {
Node::Group(g) if levels == 0 => (!g.children.is_empty()).then_some(everything),
Node::Group(g) => {
let gm = m * g.transform;
let mut r = draw_bounds(&g.children, gm, levels - 1);
for (clip, _) in &g.clip {
r = r.map(|r| r.intersect(gm.transform_rect_bbox(clip.bounding_box())));
}
r
}
Node::Shape(s) => {
let sm = m * s.transform;
let b = s.geom.to_path().bounding_box();
let fill = s.fill.as_ref().map(|_| sm.transform_rect_bbox(b));
let stroke = s.stroke.as_ref().map(|st| {
let pad = (st.width.abs() * 0.5 * st.miter.max(std::f64::consts::SQRT_2)).max(0.0);
sm.transform_rect_bbox(b.inflate(pad, pad))
});
match (fill, stroke) {
(Some(a), Some(b)) => Some(a.union(b)),
(a, b) => a.or(b),
}
}
Node::Image(im) => Some((m * im.transform).transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))),
};
if let Some(r) = r {
let r = if [r.x0, r.y0, r.x1, r.y1].iter().any(|v| v.is_nan()) { everything } else { r };
out = Some(out.map_or(r, |o| o.union(r)));
}
}
out
}
/// The device-space rectangle a clip path is when it is one along the pixel grid's axes: a
/// move, three or four lines and an optional close, its sides alternately horizontal and
/// vertical.
pub(crate) fn axis_rect(path: &kurbo::BezPath, m: Affine) -> Option<kurbo::Rect> {
use kurbo::PathEl;
let els = path.elements();
let mut pts: Vec<Point> = Vec::with_capacity(5);
for (i, el) in els.iter().enumerate() {
match el {
PathEl::MoveTo(p) if i == 0 => pts.push(m * *p),
PathEl::LineTo(p) if i > 0 && pts.len() < 5 => pts.push(m * *p),
PathEl::ClosePath if i > 0 && i + 1 == els.len() => {}
_ => return None,
}
}
const EPS: f64 = 1e-6;
let same = |a: Point, b: Point| (a.x - b.x).abs() <= EPS && (a.y - b.y).abs() <= EPS;
if pts.len() == 5 && pts.first().zip(pts.last()).is_some_and(|(a, b)| same(*a, *b)) {
pts.pop();
}
let p: [Point; 4] = pts.try_into().ok()?;
let sides = [(p[0], p[1]), (p[1], p[2]), (p[2], p[3]), (p[3], p[0])];
// Each side horizontal or vertical (and not a point), the next one the other way.
let horizontal = |(a, b): (Point, Point)| -> Option<bool> {
let (dx, dy) = ((b.x - a.x).abs(), (b.y - a.y).abs());
match (dx > EPS, dy > EPS) {
(true, false) => Some(true),
(false, true) => Some(false),
_ => None,
}
};
let kinds = sides.map(horizontal);
let [Some(k0), Some(k1), Some(k2), Some(k3)] = kinds else { return None };
if k0 == k1 || k1 == k2 || k2 == k3 || k3 == k0 {
return None;
}
let r = kurbo::Rect::from_points(p[0], p[2]);
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r)
}
/// Whether drawing `nodes` reads what is below them beyond Normal compositing: a blend mode or
/// a knockout group anywhere inside. Past `levels` levels of groups the answer is yes.
fn needs_backdrop(nodes: &[Node], levels: usize) -> bool {
nodes.iter().any(|n| match n {
Node::Group(g) => levels == 0 || g.blend != BlendMode::Normal || g.knockout || needs_backdrop(&g.children, levels - 1),
Node::Shape(_) | Node::Image(_) => false,
})
}
/// A plain clipping group (no soft mask, blend mode, group opacity or knockout) whose content
/// composites Normal throughout: drawn into a surface the size of its clip's region and
/// composited over `dst`. With Normal content that is the same as drawing it over a copy of
/// the backdrop and keeping the clip (`(C over B)·c + B·(1 − c) = (C·c) over B`), without two
/// full-size copies per nesting level: a page continuously rasterised at 400 % lost its
/// nested clipped artwork to the surface budget (#2895).
fn draw_clip_local(g: &Group, m: Affine, dst: &mut Image, budget: &mut SurfaceBudget) {
let Some(region) = clip_region(g, m, dst.width, dst.height) else { return };
let Some(mut tmp) = budget.image(region.width(), region.height(), None) else { return };
let local = region.origin_shift() * m;
for c in &g.children {
draw_node(c, local, 1.0, &mut tmp, budget);
}
if let Some(clip) = clip_coverage(g, local, tmp.width, tmp.height, budget) {
apply_clip(&mut tmp, &clip);
budget.release_coverage(clip.reserved);
over_region(dst, &tmp, region, 1.0);
}
budget.release(&tmp);
}
/// Draws a group through an offscreen buffer, then composites it onto `dst`. A clipped group can
/// only change the region its clips touch, so it works on a region-sized crop of `dst` (with the
/// transform shifted to match) instead of a whole-canvas layer; the crop is written back after.
@@ -611,7 +795,10 @@ fn apply_soft_mask(sm: &SoftMask, m: Affine, tmp: &mut Image, budget: &mut Surfa
let Some(mut mk) = budget.image(tmp.width, tmp.height, None) else {
return false;
};
// The mask's content is a tree of its own: what is known of the masked group's isn't.
let plain = std::mem::replace(&mut budget.plain, false);
draw_group(&sm.content, m, 1.0, &mut mk, budget);
budget.plain = plain;
let bc = sm.backdrop.map(|v| v as f32);
let lum = sm.luminosity;
tmp.data.par_iter_mut().zip(mk.data.par_iter()).for_each(|(p, q)| {
@@ -1185,7 +1372,11 @@ fn paint_pattern(dst: &mut Image, cov: &Mask, region: Region, pattern: &Pattern,
fallback_paint(dst, budget);
return;
}
// The tile's content is a tree of its own, drawn on a fresh transparent tile: what is known
// of the enclosing groups (all Normal) says nothing about the backdrop inside it.
let plain = std::mem::replace(&mut budget.plain, false);
draw_group(&pattern.content, content_to_tile, 1.0, &mut tile, budget);
budget.plain = plain;
let shader = Shader::Pattern(pattern, &tile, device_to_pattern);
paint_shader(dst, cov, region, &shader, opacity);
budget.release(&tile);
+224
View File
@@ -1152,3 +1152,227 @@ fn nested_knockout_groups_stop_at_the_draw_budget() {
std::thread::spawn(move || tx.send(rasterize(&doc, 4, 4, 1.0).width).ok());
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(120)).expect("rendering finishes"), 4);
}
fn solid_rect(r: kurbo::Rect, c: [f64; 3]) -> Node {
Node::Shape(Shape {
name: "rect".into(),
geom: Geom::Rect { x: r.x0, y: r.y0, w: r.width(), h: r.height(), rx: 0.0, ry: 0.0 },
transform: Affine::IDENTITY,
fill: Some(Paint::Color(c)),
fill_opacity: 1.0,
fill_rule: FillRule::NonZero,
stroke: None,
opacity: 1.0,
})
}
/// A PDF-style clipping group (not isolated: blend modes inside reach the backdrop).
fn clip_group(r: kurbo::Rect, children: Vec<Node>) -> Node {
let mut g = Group::new("Clip Group");
g.clip.push((kurbo::Shape::to_path(&r, 0.1), FillRule::NonZero));
g.isolated = false;
g.children = children;
Node::Group(g)
}
fn doc_of(w: f64, h: f64, children: Vec<Node>) -> Doc {
let mut root = Group::new("page");
root.children = children;
Doc { width: w, height: h, root, skipped: vec![] }
}
/// Nested clipping groups over a backdrop: the content shows where every clip covers, half
/// where a clip edge halves a pixel, and the backdrop everywhere else (#2895: plain clipping
/// groups are drawn on surfaces the size of their clip).
#[test]
fn nested_clip_groups_keep_the_backdrop_outside_their_clips() {
let blue = [0.0, 0.0, 1.0];
let red = [1.0, 0.0, 0.0];
let inner = clip_group(kurbo::Rect::new(10.5, 0.0, 20.0, 40.0), vec![solid_rect(kurbo::Rect::new(0.0, 0.0, 40.0, 40.0), red)]);
let doc =
doc_of(40.0, 40.0, vec![solid_rect(kurbo::Rect::new(0.0, 0.0, 40.0, 40.0), blue), clip_group(kurbo::Rect::new(5.0, 5.0, 35.0, 35.0), vec![inner])]);
let img = rasterize(&doc, 40, 40, 1.0);
let (r, b) = ([1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]);
for (x, y, want) in [(15, 20, r), (11, 6, r), (19, 34, r), (25, 20, b), (15, 2, b), (15, 36, b), (9, 20, b), (21, 20, b)] {
assert!(near(px(&img, x, y), want, 1e-3), "({x}, {y}): {:?}", px(&img, x, y));
}
assert!(near(px(&img, 10, 20), [0.5, 0.0, 0.5, 1.0], 0.02), "half-covered edge pixel {:?}", px(&img, 10, 20));
// Scaled 4×: the clip edge at 10.5 lands on a pixel boundary (42), hard on both sides.
let big = rasterize(&doc, 160, 160, 4.0);
assert!(near(px(&big, 41, 80), b, 0.01) && near(px(&big, 42, 80), r, 0.01), "{:?} {:?}", px(&big, 41, 80), px(&big, 42, 80));
}
/// A clipping group whose content blends (Multiply) still composites with the real backdrop:
/// red multiplied over blue is black inside the clip, blue outside.
#[test]
fn a_blend_mode_inside_a_clip_group_reaches_the_backdrop() {
let mut multiply = Group::new("Multiply");
multiply.blend = BlendMode::Multiply;
multiply.children = vec![solid_rect(kurbo::Rect::new(0.0, 0.0, 20.0, 20.0), [1.0, 0.0, 0.0])];
let doc = doc_of(
20.0,
20.0,
vec![
solid_rect(kurbo::Rect::new(0.0, 0.0, 20.0, 20.0), [0.0, 0.0, 1.0]),
clip_group(kurbo::Rect::new(5.0, 5.0, 15.0, 15.0), vec![Node::Group(multiply)]),
],
);
let img = rasterize(&doc, 20, 20, 1.0);
assert!(near(px(&img, 10, 10), [0.0, 0.0, 0.0, 1.0], 1e-3), "{:?}", px(&img, 10, 10));
assert!(near(px(&img, 2, 10), [0.0, 0.0, 1.0, 1.0], 1e-3), "{:?}", px(&img, 2, 10));
}
/// A pattern tile is a tree of its own: a clip group inside it that blends (Multiply) against the
/// tile's backdrop must not be drawn as a plain clip just because the pattern fill sits inside an
/// outer plain clipping group. Red multiplied over the tile's blue is black inside the inner clip.
#[test]
fn a_pattern_inside_a_plain_clip_group_keeps_its_own_backdrop_analysis() {
let mut multiply = Group::new("Multiply");
multiply.blend = BlendMode::Multiply;
multiply.children = vec![solid_rect(kurbo::Rect::new(0.0, 0.0, 20.0, 20.0), [1.0, 0.0, 0.0])];
let mut content = Group::new("tile");
content.children = vec![
solid_rect(kurbo::Rect::new(0.0, 0.0, 20.0, 20.0), [0.0, 0.0, 1.0]),
clip_group(kurbo::Rect::new(8.0, 8.0, 12.0, 12.0), vec![Node::Group(multiply)]),
];
let pattern = Pattern {
x: 0.0,
y: 0.0,
width: 20.0,
height: 20.0,
pattern_units: PatternUnits::UserSpaceOnUse,
content_units: PatternUnits::UserSpaceOnUse,
transform: Affine::IDENTITY,
content: std::sync::Arc::new(content),
render_complexity: 4,
fallback: None,
};
let Node::Shape(mut filled) = solid_rect(kurbo::Rect::new(0.0, 0.0, 20.0, 20.0), [0.0; 3]) else { return };
filled.fill = Some(Paint::Pattern(pattern));
let doc = doc_of(20.0, 20.0, vec![clip_group(kurbo::Rect::new(2.0, 2.0, 18.0, 18.0), vec![Node::Shape(filled)])]);
let img = rasterize(&doc, 20, 20, 1.0);
assert!(near(px(&img, 10, 10), [0.0, 0.0, 0.0, 1.0], 1e-3), "inner clip {:?}", px(&img, 10, 10));
assert!(near(px(&img, 4, 10), [0.0, 0.0, 1.0, 1.0], 1e-3), "tile backdrop {:?}", px(&img, 4, 10));
assert!(px(&img, 0, 10)[3] < 1e-3, "outside the outer clip {:?}", px(&img, 0, 10));
}
/// A stroke reaches past its path's bounds by half its width: a horizontal line (a path
/// without height) stroked 4 px wide covers 4 rows, and its butt caps end at the path's ends.
#[test]
fn a_stroke_draws_its_full_width_past_the_path_bounds() {
let mut line = BezPath::new();
line.move_to((5.0, 20.0));
line.line_to((35.0, 20.0));
let shape = Node::Shape(Shape {
name: "line".into(),
geom: Geom::Path(line),
transform: Affine::IDENTITY,
fill: None,
fill_opacity: 1.0,
fill_rule: FillRule::NonZero,
stroke: Some(Stroke { paint: Paint::Color([0.0, 0.0, 0.0]), opacity: 1.0, width: 4.0, cap: Cap::Butt, join: Join::Miter, miter: 4.0, dash: None }),
opacity: 1.0,
});
let img = rasterize(&doc_of(40.0, 40.0, vec![shape]), 40, 40, 1.0);
for y in 18..22 {
assert!(px(&img, 20, y)[3] > 0.99, "row {y}: {:?}", px(&img, 20, y));
}
for (x, y) in [(20, 17), (20, 22), (3, 20), (36, 20)] {
assert!(px(&img, x, y)[3] < 0.01, "({x}, {y}): {:?}", px(&img, x, y));
}
}
/// Bytes of `n` RGBA f32 surfaces of `w`×`h` pixels (a surface budget for the tests below).
fn surfaces(n: f64, w: u32, h: u32) -> usize {
(n * f64::from(w) * f64::from(h) * 16.0) as usize
}
/// #2895: an A4 page continuously rasterised at 400 % is a 128 MB surface, and every nested
/// clipping group used to copy the backdrop and draw on a second surface of that size, so the
/// second level of clips ran past the 512 MB surface budget and its artwork was dropped. Clip
/// groups now draw on surfaces the size of their clip: with room for four canvas-size surfaces,
/// artwork inside four nested clips still draws (it used to need nine).
#[test]
fn deeply_clipped_artwork_draws_within_the_surface_budget() {
let red = [1.0, 0.0, 0.0];
let mut node = solid_rect(kurbo::Rect::new(0.0, 0.0, 300.0, 300.0), red);
for i in 1..=4 {
let inset = 10.0 * f64::from(i);
node = clip_group(kurbo::Rect::new(inset, inset, 300.0 - inset, 300.0 - inset), vec![node]);
}
let img = crate::raster::rasterize_with_budget(&doc_of(300.0, 300.0, vec![node]), 300, 300, Affine::IDENTITY, surfaces(4.0, 300, 300));
assert_eq!((img.width, img.height), (300, 300));
assert!(near(px(&img, 150, 150), [1.0, 0.0, 0.0, 1.0], 1e-3), "centre {:?}", px(&img, 150, 150));
assert!(near(px(&img, 45, 150), [1.0, 0.0, 0.0, 1.0], 1e-3), "just inside every clip {:?}", px(&img, 45, 150));
assert!(px(&img, 35, 150)[3] < 0.01, "outside the outermost clip {:?}", px(&img, 35, 150));
}
/// #2895: clips that cover the whole canvas around the artwork inside them (a page clip, an
/// artboard clip, the outermost groups of most PDF pages) change no pixel, so they are drawn
/// without a surface: with room for two and a half canvas-size surfaces, the artwork inside two
/// of them still draws, and an inner clip still cuts it.
#[test]
fn canvas_covering_clips_draw_without_a_surface() {
let red = [1.0, 0.0, 0.0];
let art = clip_group(kurbo::Rect::new(150.0, 0.0, 300.0, 350.0), vec![solid_rect(kurbo::Rect::new(100.0, 100.0, 250.0, 250.0), red)]);
let page = clip_group(kurbo::Rect::new(0.0, 0.0, 350.0, 350.0), vec![art]);
let outer = clip_group(kurbo::Rect::new(-1.0, -1.0, 351.0, 351.0), vec![page]);
let img = crate::raster::rasterize_with_budget(&doc_of(350.0, 350.0, vec![outer]), 350, 350, Affine::IDENTITY, surfaces(2.5, 350, 350));
assert_eq!((img.width, img.height), (350, 350));
for (x, y) in [(200, 200), (151, 101), (248, 248)] {
assert!(near(px(&img, x, y), [1.0, 0.0, 0.0, 1.0], 1e-3), "({x}, {y}): {:?}", px(&img, x, y));
}
for (x, y) in [(120, 200), (148, 200), (200, 90), (260, 200)] {
assert!(px(&img, x, y)[3] < 0.01, "({x}, {y}): {:?}", px(&img, x, y));
}
}
/// Take a tree apart without recursing (a deep one would overflow the stack when dropped).
fn dismantle(mut nodes: Vec<Node>) {
while let Some(n) = nodes.pop() {
if let Node::Group(mut g) = n {
nodes.append(&mut g.children);
}
}
}
/// Never crash: drawing recurses, and clipping groups nested twenty thousand deep (a crafted
/// file) are drawn without running out of stack, on a thread with a small one; groups past the
/// nesting limit are not drawn, shallower artwork is.
#[test]
fn clip_groups_nested_without_end_do_not_overflow_the_stack() {
let run = std::thread::Builder::new().stack_size(4 << 20).spawn(|| {
let mut node = solid_rect(kurbo::Rect::new(0.0, 0.0, 64.0, 64.0), [1.0, 0.0, 0.0]);
for _ in 0..20_000 {
node = clip_group(kurbo::Rect::new(0.0, 0.0, 64.0, 64.0), vec![node]);
}
let shallow = solid_rect(kurbo::Rect::new(0.0, 0.0, 8.0, 8.0), [0.0, 0.0, 1.0]);
let doc = doc_of(64.0, 64.0, vec![node, shallow]);
let img = rasterize(&doc, 64, 64, 1.0);
let out = (img.width, img.height, px(&img, 4, 4), px(&img, 40, 40));
dismantle(vec![Node::Group(doc.root)]);
out
});
let (w, h, shallow, deep) = run.unwrap().join().unwrap();
assert_eq!((w, h), (64, 64));
assert!(near(shallow, [0.0, 0.0, 1.0, 1.0], 1e-3), "{shallow:?}");
assert!(deep[3] < 0.01, "artwork past the nesting limit is not drawn: {deep:?}");
}
/// Only a rectangle along the pixel grid's axes counts as a clip that can be skipped: a
/// rotated square or a path that folds back on itself does not.
#[test]
fn axis_rect_recognises_only_axis_aligned_rectangles() {
use crate::raster::axis_rect;
let rect = kurbo::Shape::to_path(&kurbo::Rect::new(1.0, 2.0, 5.0, 7.0), 0.1);
assert_eq!(axis_rect(&rect, Affine::IDENTITY), Some(kurbo::Rect::new(1.0, 2.0, 5.0, 7.0)));
assert_eq!(axis_rect(&rect, Affine::scale(2.0)), Some(kurbo::Rect::new(2.0, 4.0, 10.0, 14.0)));
assert_eq!(axis_rect(&rect, Affine::rotate(0.3)), None);
let mut folded = BezPath::new();
folded.move_to((0.0, 0.0));
folded.line_to((10.0, 0.0));
folded.line_to((10.0, 10.0));
folded.line_to((10.0, 0.0));
folded.close_path();
assert_eq!(axis_rect(&folded, Affine::IDENTITY), None);
}
+10
View File
@@ -45,7 +45,17 @@ craft-update = { workspace = true }
pollster = { workspace = true }
sys-locale = { workspace = true }
[features]
# Tests only, never enable in a product: Settings ▸ General ▸ Language ▸ Match System resolves to
# English, so English label lookups pass on any system language (#3244). The self dev-dependency
# below turns it on wherever dev-dependencies are built: this crate's integration tests, its
# examples (`snapshot` shots are deterministic English unless a step sets a language) and
# workspace test builds of the apps (`cargo test --workspace`).
test-support = []
[dev-dependencies]
# This crate's own integration tests build it with `test-support` (see `[features]`).
effectcraft-ui-egui = { workspace = true, features = ["test-support"] }
# Fonts for kittest: the workspace `egui` features are what test roots resolve, but stating them
# here documents the requirement (kittest's own dev-dependencies do not propagate to consumers).
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
+1
View File
@@ -74,6 +74,7 @@ impl EffectcraftApp {
last_activity: (0.0, 0),
last_edit: (0.0, 0),
toast: None,
error_toasts: Default::default(),
viewer_tex: None,
passive_tex: std::collections::HashMap::new(),
viewer_native: None,
+26
View File
@@ -1,6 +1,32 @@
use super::{Dialog, EffectcraftApp};
impl EffectcraftApp {
pub(crate) fn push_error_toast(&mut self, toast: crate::ErrorToast) {
if self.error_toasts.len() >= crate::ErrorToast::MAX_PENDING {
// Preserve the visible notification and summarize the pending backlog.
let reports = self.error_toasts.drain(1..).fold(0usize, |sum, toast| sum.saturating_add(toast.reports));
self.error_toasts.push_back(crate::ErrorToast::omitted(reports));
}
self.error_toasts.push_back(toast);
}
/// Imports can succeed as commands while individual files fail before a job starts.
pub(crate) fn report_import_errors(&mut self, command: &str, result: &serde_json::Value) {
if !matches!(command, "file.import" | "file.importMultiple") {
return;
}
let errors: Vec<&str> = result["errors"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str).collect();
match errors.as_slice() {
[] => {}
[one] => self.ui.status = (*one).into(),
[first, rest @ ..] => self.ui.status = format!("{first} (and {} more)", rest.len()),
}
if !errors.is_empty() {
self.ui.status = crate::ErrorToast::bounded_text([self.ui.status.as_str()]);
self.push_error_toast(crate::ErrorToast::new(errors.iter().copied(), Some(&self.ui.status)));
}
}
/// Show the crash-recovery dialog for a previous run that didn't exit cleanly.
pub fn offer_recovery(&mut self, r: effectcraft_engine::autosave::Recovery) {
if r.autosave.is_some() {
+283 -6
View File
@@ -142,7 +142,13 @@ impl EffectcraftApp {
panels::viewers::on_open_comp(self, c);
self.ui.timeline.pps = None;
}
effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, self.now)),
effectcraft_engine::Event::Toast { message, error } => {
if error {
self.push_error_toast(crate::ErrorToast::new([message.as_str()], None));
} else {
self.toast = Some((message, self.now));
}
}
effectcraft_engine::Event::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
// Frames are keyed by content: an edit keeps those of comps it doesn't touch.
effectcraft_engine::Event::ProjectChanged { .. } => {}
@@ -509,6 +515,7 @@ impl EffectcraftApp {
crate::color_picker::note_dialog(&ctx, self.dialog);
// After the shortcuts, menus and header, which can replace the project (New, Open).
self.ui.timeline.scope_links(self.session.script_ui.project_epoch);
panels::effect_controls::scope_lock(self);
self.dock_area(ui, body);
#[cfg(not(target_arch = "wasm32"))]
prefs_live::dropped_files(self, ui, full);
@@ -566,21 +573,44 @@ impl EffectcraftApp {
if self.ui.status.is_empty() {
ui.data_mut(|d| d.remove::<(f64, String)>(egui::Id::unique("status-since")));
}
let msg = if !self.ui.status.is_empty() {
Some(self.ui.status.clone())
while self.error_toasts.front().is_some_and(|toast| toast.shown_at.is_some_and(|at| now - at >= 4.0)) {
self.error_toasts.pop_front();
}
let error = self.error_toasts.front_mut().and_then(|toast| toast.message_at(!self.ui.status.is_empty(), now)).map(str::to_owned);
let notice = self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(message, _)| crate::ErrorToast::bounded_text([message.as_str()]));
let mut msg = if !self.ui.status.is_empty() {
// A background result must get its display time after the foreground status.
// Keep its details available on hover while the status takes precedence.
let status = crate::ErrorToast::bounded_text([self.ui.status.as_str()]);
if let Some(details) = error { Some(format!("{status}\n{details}")) } else { Some(status) }
} else {
self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(m, _)| m.clone())
error.or_else(|| notice.clone())
};
if let Some(m) = &mut msg
&& let Some(notice) = &notice
&& m != notice
{
m.push('\n');
m.push_str(notice);
}
if let Some(m) = msg {
let t = &self.tokens;
let galley = ui.painter().layout_no_wrap(m.clone(), Tokens::ui(12.0), t.text);
let summary = m.lines().next().unwrap_or_default().to_owned();
let galley = ui.painter().layout_no_wrap(summary, Tokens::ui(12.0), t.text);
let r = egui::Rect::from_min_size(egui::pos2(full.min.x + 16.0, full.max.y - 44.0 - lift), galley.size() + egui::vec2(24.0, 14.0));
ui.painter().rect_filled(r, 6.0, t.panel_bg);
ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
ui.painter().galley(r.min + egui::vec2(12.0, 7.0), galley, t.text);
self.auto.add("toast", r, &m);
let resp = ui.interact(r, egui::Id::unique("toast"), egui::Sense::click());
let resp = ui.interact(r, egui::Id::unique("toast"), egui::Sense::click()).on_hover_text(&m);
if resp.clicked() {
if self.ui.status.is_empty() {
self.error_toasts.pop_front();
} else if let Some(index) = self.error_toasts.iter().rposition(|toast| toast.reported_by(&self.ui.status)) {
// The current status belongs to the latest matching import. Earlier
// imports can share its summary while carrying different details.
self.error_toasts.remove(index);
}
self.ui.status.clear();
self.toast = None;
}
@@ -710,3 +740,250 @@ impl EffectcraftApp {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dismissing_a_status_acknowledges_its_queued_error_behind_another() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.events.push(effectcraft_engine::Event::Toast { message: "Earlier background error".into(), error: true });
let ctx = egui::Context::default();
app.handle_events(&ctx);
app.report_import_errors("file.import", &json!({"errors":["Later import error"]}));
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
for pressed in [true, false] {
app.auto.elements.clear();
let events = vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(app.ui.status.is_empty());
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.label.contains("Earlier background error")));
app.now = 4.1;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(!app.auto.elements.iter().any(|e| e.id == "toast"), "the acknowledged later error must not reappear");
}
#[test]
fn matching_import_summaries_only_acknowledge_the_latest_details() {
for first in ["Shared error".to_owned(), "💥".repeat(20_000)] {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.report_import_errors("file.import", &json!({"errors":[first, "Earlier details"]}));
app.report_import_errors("file.import", &json!({"errors":[first, "Later details"]}));
let ctx = egui::Context::default();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
let pos = egui::pos2(r[0] + 4.0, r[1] + 4.0);
for pressed in [true, false] {
let events = vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(app.ui.status.is_empty());
assert_eq!(app.error_toasts.len(), 1, "only the latest matching import is acknowledged, including long statuses");
if first.len() < 100 {
assert!(app.error_toasts.front().unwrap().message.contains("Earlier details"));
}
}
}
#[test]
fn pending_error_notifications_are_bounded_and_report_omissions() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.events.extend((0..40).map(|i| effectcraft_engine::Event::Toast { message: format!("Error {i}"), error: true }));
let ctx = egui::Context::default();
app.handle_events(&ctx);
assert!(app.error_toasts.len() <= 32);
assert_eq!(app.error_toasts.front().unwrap().message, "Error 0");
assert_eq!(app.error_toasts.back().unwrap().message, "Error 39");
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
app.now += 4.1;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.label.contains("notifications omitted")));
let long = format!("a{}", "💥".repeat(20_000));
let toast = crate::ErrorToast::new([long.as_str()], None);
assert!(toast.message.starts_with("a💥"));
assert!(toast.message.len() < 20 << 10);
assert!(toast.message.capacity() < 64 << 10, "the large input allocation must not remain retained");
assert!(toast.message.contains("truncated"));
}
#[test]
fn consecutive_background_errors_are_each_shown_before_expiring_or_dismissal() {
for dismiss in [false, true] {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.events.extend([
effectcraft_engine::Event::Toast { message: "First.vectorcraft failed".into(), error: true },
effectcraft_engine::Event::Toast { message: "A routine notice".into(), error: false },
effectcraft_engine::Event::Toast { message: "Second.vectorcraft failed".into(), error: true },
]);
let ctx = egui::Context::default();
app.handle_events(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("First.vectorcraft")));
if dismiss {
let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
for pressed in [true, false] {
app.auto.elements.clear();
let events = vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
app.now = 0.1;
} else {
app.now = 4.1;
}
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("Second.vectorcraft")));
assert!(!app.auto.elements.iter().any(|e| e.label.contains("First.vectorcraft")));
app.now += 4.1;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
}
}
#[test]
fn an_unshown_error_survives_a_replacement_foreground_status() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.ui.status = "First foreground status".into();
app.session.events.push(effectcraft_engine::Event::Toast { message: "An unseen import error".into(), error: true });
let ctx = egui::Context::default();
app.handle_events(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
app.ui.status = "Another foreground status".into();
for now in [1.0, 3.0, 6.0, 6.1] {
app.now = now;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("unseen import error")));
}
#[test]
fn dismissing_a_status_keeps_an_unshown_background_error() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.ui.status = "A local drop failed".into();
app.session.events.push(effectcraft_engine::Event::Toast { message: "A later background import failed".into(), error: true });
let ctx = egui::Context::default();
app.handle_events(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
let click = |app: &mut EffectcraftApp| {
let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
for pressed in [true, false] {
app.auto.elements.clear();
let events = vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
};
click(&mut app);
assert!(app.ui.status.is_empty());
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("later background import failed")));
click(&mut app);
assert!(app.error_toasts.is_empty(), "the displayed error can be dismissed too");
app.report_import_errors("file.import", &json!({"errors": ["An immediate import error", "Another import error"]}));
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
click(&mut app);
assert!(app.ui.status.is_empty());
assert!(app.error_toasts.is_empty(), "dismissing an error status acknowledges its own details");
}
#[test]
fn a_later_status_does_not_extend_an_error_already_shown() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.events.push(effectcraft_engine::Event::Toast { message: "An earlier error".into(), error: true });
let ctx = egui::Context::default();
app.handle_events(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
app.ui.status = "An unrelated later status".into();
for now in [1.0, 4.0, 7.0, 7.1] {
app.now = now;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
}
#[test]
fn import_error_details_survive_a_warning_event() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.report_import_errors("file.import", &json!({"errors": ["first failed file", "second failed file"]}));
app.session.events.push(effectcraft_engine::Event::Toast { message: "Sequence has missing frames".into(), error: false });
let ctx = egui::Context::default();
app.handle_events(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("second failed file")));
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("missing frames")));
}
#[test]
fn a_foreground_status_does_not_extend_a_confirmation_toast() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.ui.status = "A foreground status".into();
app.toast = Some(("Saved".into(), 0.0));
let ctx = egui::Context::default();
for now in [0.0, 3.0, 6.0, 6.1] {
app.now = now;
app.auto.elements.clear();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
}
#[test]
fn a_new_status_does_not_revive_an_expired_toast() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.ui.status = "A new status".into();
app.toast = Some(("An old toast".into(), 0.0));
app.now = 8.0;
let ctx = egui::Context::default();
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().all(|e| !e.label.contains("old toast")));
app.ui.status.clear();
app.auto.elements.clear();
app.now = 8.1;
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
}
#[test]
fn a_status_message_does_not_expire_a_background_import_error() {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.ui.status = "A local drop failed".into();
app.session.events.push(effectcraft_engine::Event::Toast { message: "Imported 1 item. Failed first file\nFailed second file".into(), error: true });
let ctx = egui::Context::default();
app.handle_events(&ctx);
for now in [0.0, 3.0, 6.0] {
app.now = now;
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
}
assert!(app.ui.status.is_empty());
app.auto.elements.clear();
app.now = 6.1;
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("Failed second file")), "{:?}", app.auto.elements);
}
}
+6 -1
View File
@@ -447,7 +447,12 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut [f32; 3], original: [f32; 3])
if ch == Chan::H && v >= 360.0 {
v = 0.0;
}
let drag = egui::DragValue::new(&mut v).range(0.0..=scale).fixed_decimals(0).suffix(suffix).speed(scale / 255.0);
let drag = egui::DragValue::new(&mut v)
.range(0.0..=scale)
.fixed_decimals(0)
.suffix(suffix)
.speed(scale / 255.0)
.custom_parser(|text| crate::num_math::calc(text, None));
if ui.add_sized(vec2(56.0, 18.0), drag).labelled_by(radio.id).changed() {
pick = pick.set(ch, v.round() / scale);
}
+15
View File
@@ -344,6 +344,21 @@ fn set_ui(app: &mut EffectcraftApp, ctx: &egui::Context, p: &Value) -> Outcome {
{
return err(e);
}
// Effect Controls' tab lock: on locks it to the layer it shows. With no layer shown (the
// lock kept for a layer of another comp, nothing selected here) a lock request is an error
// and the kept lock stays.
if let Some(on) = p.get("effectControlsLocked").and_then(Value::as_bool) {
crate::panels::effect_controls::scope_lock(app);
let shown = crate::panels::effect_controls::shown_layer_id(app).is_some();
if (on && !shown) || crate::panels::effect_controls::set_lock(app, on) != on {
return err("effectControlsLocked: Effect Controls shows no layer to lock");
}
// Locked to a layer of another comp, the panel shows this comp's selection: the tab's
// lock reads locked and a click unlocks, so a lock request does not lock what is shown.
if on && app.ui.effect_controls_lock.is_some_and(|k| app.session.active_comp_id().is_none_or(|c| c.0 != k.comp)) {
return err("effectControlsLocked: Effect Controls is locked to a layer of another composition; unlock it first");
}
}
set_ui_layout(app, p)
}
+2 -2
View File
@@ -676,8 +676,8 @@ pub fn doc_tabs(
out
}
/// A viewer lock button (Composition viewers and the Timeline keep their comp while locked): a
/// closed padlock while locked, an open one while unlocked.
/// A panel lock button (Composition viewers and the Timeline keep their comp while locked,
/// Effect Controls its layer): a closed padlock while locked, an open one while unlocked.
/// Returns true when clicked. Automation: `panel.tab.<panel>.lock`.
pub fn lock_button(ui: &mut egui::Ui, rect: Rect, panel: PanelKind, locked: bool, t: &Tokens, reg: &mut crate::automation::Registry) -> bool {
let resp = ui.interact(rect, egui::Id::unique(("tab-lock", panel.id())), Sense::click());
+24 -6
View File
@@ -333,8 +333,11 @@ impl EffectcraftApp {
}
}
let Some(comp) = self.session.active_comp() else { return out };
if let Some(l) = self.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) {
// Effect Controls names the layer it shows (the one it is locked to, if any).
if let Some(l) = panels::effect_controls::shown_layer_id(self).and_then(|id| comp.layer(id)) {
out.push((PanelKind::EffectControls, format!("{} {}", crate::i18n::command_label("window.panel", "Effect Controls"), l.name)));
}
if let Some(l) = self.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) {
out.push((PanelKind::Properties, format!("{}: {}", crate::i18n::command_label("window.panel", "Properties"), l.name)));
}
out
@@ -492,7 +495,13 @@ impl EffectcraftApp {
}
}
for p in locks {
if !self.ui.locked_tabs.remove(&p.id()) {
if p == PanelKind::EffectControls {
// Locks on the layer the panel shows (nothing to lock without one).
let on = self.ui.effect_controls_lock.is_none();
if panels::effect_controls::set_lock(self, on) != on {
self.ui.status = crate::i18n::tr("Select a layer to lock Effect Controls").to_string();
}
} else if !self.ui.locked_tabs.remove(&p.id()) {
self.ui.locked_tabs.insert(p.id().to_string());
}
}
@@ -638,10 +647,19 @@ fn dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle {
style
}
/// Panels with a viewer lock: the Composition viewers and the Timeline keep their comp while
/// locked.
/// Panels with a lock: the Composition viewers and the Timeline keep their comp while locked,
/// Effect Controls its layer.
fn has_lock(panel: PanelKind) -> bool {
matches!(panel, PanelKind::Composition | PanelKind::Viewer(_) | PanelKind::Timeline)
matches!(panel, PanelKind::Composition | PanelKind::Viewer(_) | PanelKind::Timeline | PanelKind::EffectControls)
}
/// Whether `panel`'s tab lock is on. Effect Controls keeps the layer it is locked to
/// (`UiState::effect_controls_lock`), the others are in `UiState::locked_tabs`.
fn is_locked(app: &EffectcraftApp, panel: PanelKind) -> bool {
match panel {
PanelKind::EffectControls => app.ui.effect_controls_lock.is_some(),
_ => app.ui.locked_tabs.contains(&panel.id()),
}
}
/// EffectCraft's side of the dock area for one frame.
@@ -865,7 +883,7 @@ impl DockContent<PanelKind> for EffectContent<'_> {
let menu = Rect::from_min_max(pos2((header.max.x - MENU_W).max(header.min.x), header.min.y), header.max);
if has_lock(*active) {
let lock = Rect::from_center_size(pos2(menu.min.x - LOCK_W / 2.0, header.center().y), vec2(14.0, 14.0));
let locked = self.app.ui.locked_tabs.contains(&active.id());
let locked = is_locked(self.app, *active);
if dock::lock_button(ui, lock, *active, locked, &t, &mut self.app.auto) {
self.locks.push(*active);
}
+5 -2
View File
@@ -26,8 +26,11 @@ impl FileDialog {
}
}
/// Called with the paths a [`FileDialog`] picked (empty: cancelled), from any thread.
pub type DialogDone = Box<dyn FnOnce(Vec<String>) + Send>;
/// Called with the paths a [`FileDialog`] picked (empty: cancelled), from any thread, or with
/// why the dialog couldn't open: the status line shows that and the command doesn't run. On
/// macOS AppKit can fail to make the panel at all (`+[NSOpenPanel openPanel]` returned nil,
/// #3084); the host catches that and answers with the error instead of taking the app down.
pub type DialogDone = Box<dyn FnOnce(Result<Vec<String>, String>) + Send>;
/// Host hooks provided by the native app (file pickers etc.).
#[derive(Default)]
+23 -7
View File
@@ -84,7 +84,14 @@ pub(crate) fn swedish(app: &EffectcraftApp) -> bool {
/// Settings ▸ General ▸ Language ▸ Match System: the operating system's interface language
/// where EffectCraft has it, else English (#229), as After Effects installs in the system's
/// language. The browser build follows the locales its page passes in ([`set_system_locales`]).
///
/// Test builds (this crate's unit tests, and its integration tests through the `test-support`
/// feature) resolve Match System to English, so tests that look up English labels pass on any
/// system language (#3244); tests about a translation choose their language explicitly.
fn system_language() -> &'static str {
if cfg!(any(test, feature = "test-support")) {
return "en";
}
#[cfg(not(target_arch = "wasm32"))]
{
static LANGUAGE: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
@@ -9184,13 +9191,22 @@ mod tests {
}
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
assert_eq!(app.session.prefs.general.language, "system", "the default");
assert_eq!(japanese(&app), system_language() == "ja");
assert_eq!(simplified(&app), system_language() == "zh-hans");
assert_eq!(traditional(&app), system_language() == "zh-hant");
assert_eq!(spanish(&app), system_language() == "es");
assert_eq!(czech(&app), system_language() == "cs");
assert_eq!(polish(&app), system_language() == "pl");
assert_eq!(swedish(&app), system_language() == "sv");
assert_eq!(system_language(), "en", "test builds pin Match System to English (#3244)");
assert_eq!(language(&app), "en");
for (flag, name) in [
(japanese(&app), "ja"),
(simplified(&app), "zh-hans"),
(traditional(&app), "zh-hant"),
(ukrainian(&app), "uk"),
(spanish(&app), "es"),
(brazilian_portuguese(&app), "pt-br"),
(czech(&app), "cs"),
(polish(&app), "pl"),
(georgian(&app), "ka"),
(swedish(&app), "sv"),
] {
assert!(!flag, "Match System shows {name} in a test build");
}
app.session.execute("prefs.set", json!({"key":"general.language", "value":"ja"})).unwrap();
assert!(japanese(&app));
app.session.execute("prefs.set", json!({"key":"general.language", "value":"zh-hans"})).unwrap();
+76 -1
View File
@@ -36,6 +36,7 @@ pub mod icons;
pub mod menu_keys;
pub mod menus;
pub mod native_menu;
pub mod num_math;
pub mod panels;
mod pointer_wrap;
pub mod prefs_live;
@@ -169,7 +170,8 @@ pub(crate) struct DialogAnswer {
pub command: String,
pub key: &'static str,
pub params: serde_json::Value,
pub paths: Vec<String>,
/// The picked paths (empty: cancelled), or why the dialog couldn't open (#3084).
pub paths: Result<Vec<String>, String>,
}
#[derive(Default)]
@@ -266,6 +268,77 @@ impl Playback {
}
}
/// An error awaiting its first standalone display.
pub(crate) struct ErrorToast {
message: String,
shown_at: Option<f64>,
/// A status already reports this error; dismissing that same status acknowledges both.
reported_status: Option<String>,
reports: usize,
}
impl ErrorToast {
const MAX_PENDING: usize = 32;
const MAX_DETAILS: usize = 16 << 10;
fn bounded_text<'a>(messages: impl IntoIterator<Item = &'a str>) -> String {
let mut text = String::new();
let mut truncated = false;
for (index, part) in messages.into_iter().enumerate() {
let separator = usize::from(!text.is_empty());
let remaining = Self::MAX_DETAILS.saturating_sub(text.len() + separator);
if remaining == 0 || index >= Self::MAX_DETAILS {
truncated = true;
break;
}
if separator != 0 {
text.push('\n');
}
let end = part.floor_char_boundary(remaining.min(part.len()));
text.push_str(part.get(..end).unwrap_or_default());
if end < part.len() {
truncated = true;
break;
}
}
if truncated {
let marker = crate::i18n::ui::tr("Further error details were truncated.");
let marker = marker.get(..marker.floor_char_boundary(Self::MAX_DETAILS - 1)).unwrap_or_default();
text.truncate(text.floor_char_boundary(Self::MAX_DETAILS.saturating_sub(marker.len() + 1)));
text.push('\n');
text.push_str(marker);
}
text
}
fn new<'a>(messages: impl IntoIterator<Item = &'a str>, reported_status: Option<&str>) -> Self {
Self { message: Self::bounded_text(messages), shown_at: None, reported_status: reported_status.map(|status| Self::bounded_text([status])), reports: 1 }
}
fn omitted(reports: usize) -> Self {
let message = crate::i18n::ui::tr_args("Additional error notifications omitted: {}.", &[&reports.to_string()]);
Self { reports, ..Self::new([message.as_str()], None) }
}
fn reported_by(&self, status: &str) -> bool {
self.reported_status.as_deref().is_some_and(|reported| status == reported || status.strip_prefix(reported).is_some_and(|rest| rest.starts_with("; ")))
}
/// Pair the details with `status`, a later status line that reports the same errors.
fn restate(&mut self, status: &str) {
self.reported_status = Some(Self::bounded_text([status]));
}
fn message_at(&mut self, foreground_status: bool, now: f64) -> Option<&str> {
if self.shown_at.is_none() && !foreground_status {
// Only the first standalone display starts the timer. Later statuses cannot
// extend it, and an unseen error cannot expire behind a foreground status.
self.shown_at = Some(now);
}
self.shown_at.is_none_or(|at| now - at < 4.0).then_some(self.message.as_str())
}
}
pub struct EffectcraftApp {
pub session: Session,
pub ui: UiState,
@@ -325,6 +398,8 @@ pub struct EffectcraftApp {
/// When the project last changed, and its revision then (see [`Self::editing`]).
last_edit: (f64, u64),
pub(crate) toast: Option<(String, f64)>,
/// Error details survive routine notifications and wait for a foreground status to clear.
pub(crate) error_toasts: std::collections::VecDeque<ErrorToast>,
/// Texture of the last CPU frame shown in the viewer, the key it came from and the factor it
/// was averaged down by for the magnification (`panels::viewer::minify_factor`).
pub(crate) viewer_tex: Option<(egui::TextureHandle, FrameKey, usize)>,
+1 -1
View File
@@ -117,7 +117,7 @@ pub fn menu_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
}
if let Some((id, params)) = clicked.map(|(id, params)| menu_choice(app, id, params)) {
match invoke(app, &ctx, &id, if params.is_null() { json!({}) } else { params }) {
Ok(result) => super::frontend::show_result_errors(app, &result),
Ok(result) => super::frontend::show_command_result_errors(app, &id, &result),
Err(e) => app.ui.status = e,
}
}
+45 -6
View File
@@ -62,6 +62,9 @@ pub(crate) fn run_engine(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str
} else if COPY_COMMANDS.contains(&id) && app.session.state.text_edit.is_none() {
ctx.copy_text(clipboard_text(&app.session));
}
if let Ok(result) = &r {
app.report_import_errors(id, result);
}
// Frontend events below may show the Home screen again (Help ▸ In-App Tutorials).
leave_home_if_opened(app, before, r.is_ok());
let events = app.session.drain_events();
@@ -683,8 +686,10 @@ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) ->
"png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3", "flac", "ogg", "opus", "svg", "pdf", "ai",
"eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv",
];
// VectorCraft documents, read through the PDF they carry.
let media = [MEDIA, &["vectorcraft"]].concat();
let footage = |more: &[&'static str]| effectcraft_project::VIDEO_EXTENSIONS.iter().chain(more).copied().collect::<Vec<_>>();
let importable = |more: &[&'static str]| footage(MEDIA).into_iter().chain(more.iter().copied()).collect::<Vec<_>>();
let importable = |more: &[&'static str]| footage(&media).into_iter().chain(more.iter().copied()).collect::<Vec<_>>();
// A host whose blocking dialogs are unsafe inside this frame shows the dialog without
// blocking — macOS: the nested event loop re-entered winit's handler on a drag over the
// window and aborted the app (#511); Linux: the desktop portal's answer never gets pumped,
@@ -700,7 +705,7 @@ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) ->
Ask::Save(default) => crate::FileDialog::save(&default),
};
let tx = app.dialog_answers.0.clone();
let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Vec::new() };
let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Ok(Vec::new()) };
app.file_dialogs.opened();
spawn(
request,
@@ -750,11 +755,20 @@ fn picked_value(key: &str, paths: Vec<String>) -> Option<Value> {
}
/// A file dialog shown without blocking ([`crate::Hooks::file_dialog_async`]) answered: run its
/// command with the picked path (nothing when it was cancelled).
/// command with the picked path (nothing when it was cancelled). A dialog that couldn't open
/// says why in the status line, and the command doesn't run (#3084).
pub(crate) fn dialog_answered(app: &mut EffectcraftApp, answer: crate::DialogAnswer) {
let Some(v) = picked_value(answer.key, answer.paths) else { return };
let paths = match answer.paths {
Ok(paths) => paths,
// The host logged it.
Err(e) => {
app.ui.status = e;
return;
}
};
let Some(v) = picked_value(answer.key, paths) else { return };
match run_with_picked(app, &answer.command, answer.key, &answer.params, v) {
Ok(result) => show_result_errors(app, &result),
Ok(result) => show_command_result_errors(app, &answer.command, &result),
Err(e) => app.ui.status = e,
}
}
@@ -782,6 +796,27 @@ pub(crate) fn show_result_errors(app: &mut EffectcraftApp, result: &Value) {
app.ui.status = msg;
}
/// [`show_result_errors`] for the result of command `id`. An import has already queued its
/// details with the shorter status `report_import_errors` set; this status reports the same
/// errors in its place, so the details move to it and dismissing it still acknowledges them.
pub(crate) fn show_command_result_errors(app: &mut EffectcraftApp, id: &str, result: &Value) {
show_result_errors_after_import(app, matches!(id, "file.import" | "file.importMultiple"), result);
}
/// [`show_result_errors`]; when `reported` is set, `report_import_errors` has just queued the
/// details of the import whose result this is, last, with the status shown before this call.
fn show_result_errors_after_import(app: &mut EffectcraftApp, reported: bool, result: &Value) {
let previous = app.ui.status.clone();
show_result_errors(app, result);
if reported
&& app.ui.status != previous
&& let Some(toast) = app.error_toasts.back_mut().filter(|toast| toast.reported_by(&previous))
{
app.ui.status = crate::ErrorToast::bounded_text([app.ui.status.as_str()]);
toast.restate(&app.ui.status);
}
}
/// Run command `id` with the path picked for it in parameter `key`.
fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value, v: Value) -> Result<Value, String> {
if matches!(id, "file.import" | "file.importMultiple")
@@ -825,6 +860,9 @@ fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value
if let Err(e) = &r {
app.ui.status = e.clone();
}
if let Ok(result) = &r {
app.report_import_errors(id, result);
}
leave_home_if_opened(app, before, r.is_ok());
r
}
@@ -873,8 +911,9 @@ fn import_picked_with_aep(app: &mut EffectcraftApp, id: &str, key: &str, params:
result = json!({"result": result});
}
let own = result.get("errors").and_then(Value::as_array).cloned().unwrap_or_default();
let reported = !own.is_empty();
result["errors"] = Value::Array(errors.into_iter().map(Value::from).chain(own).collect());
show_result_errors(app, &result);
show_result_errors_after_import(app, reported, &result);
Ok(result)
}
Err(e) => {
+9 -3
View File
@@ -203,10 +203,16 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
}
// A new folder (File ▸ New, its shortcut, the Project panel's button and context menu) opens
// with its name ready to type, as in After Effects (#1658). The command selects it.
// `engine.execute` keeps the headless default.
if id == "project.newFolder" && no_params(&params) {
// `engine.execute` keeps the headless default. Items dropped on the New Folder button (only
// `items`, #3196) open the name too.
if id == "project.newFolder" && (no_params(&params) || params.as_object().is_some_and(|m| m.len() == 1 && m.contains_key("items"))) {
let dropped = params.get("items").is_some();
let r = run_engine(app, ctx, id, params);
if r.is_ok() {
if let Ok(v) = &r {
// Open a folder that items were dropped into, so they stay in view.
if dropped && let Some(f) = v.get("item").and_then(Value::as_u64) {
app.ui.project_open_folders.insert(f);
}
app.show_panel(PanelKind::Project);
crate::panels::project::begin_rename(app, ctx);
}
+182 -8
View File
@@ -384,7 +384,7 @@ fn file_dialogs_can_answer_on_a_later_frame() {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Answered.ecproj");
// Answered from another thread, as the host's dialog does.
std::thread::spawn(move || done(vec![path.to_string_lossy().to_string()])).join().unwrap();
std::thread::spawn(move || done(Ok(vec![path.to_string_lossy().to_string()]))).join().unwrap();
app.run_dialog_answers();
assert_eq!(app.session.path.as_deref(), Some(dir.join("Answered.ecproj").to_string_lossy().as_ref()));
assert!(dir.join("Answered.ecproj").is_file());
@@ -392,7 +392,7 @@ fn file_dialogs_can_answer_on_a_later_frame() {
invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();
let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");
assert_eq!(dialog, crate::FileDialog::Save { default: "Frame.png".into(), ext: "png".into(), project: false });
done(Vec::new());
done(Ok(Vec::new()));
app.run_dialog_answers();
assert!(!dir.join("Frame.png").exists());
let _ = std::fs::remove_dir_all(&dir);
@@ -423,7 +423,7 @@ fn file_dialogs_block_floating_windows_only_while_up() {
assert!(blocked(&mut app, true, 0.1), "blocked while the dialog takes the keyboard");
assert!(blocked(&mut app, false, 0.2));
let done = pending.lock().unwrap().pop().expect("a dialog was shown");
done(Vec::new());
done(Ok(Vec::new()));
app.run_dialog_answers();
assert!(!blocked(&mut app, false, 0.3));
// Save As asks again; the sheet ends without answering.
@@ -440,7 +440,7 @@ fn file_dialogs_block_floating_windows_only_while_up() {
assert!(!blocked(&mut app, true, 12.5));
// Answers of dialogs taken for gone arrive late: nothing stays blocked.
for done in pending.lock().unwrap().drain(..) {
done(Vec::new());
done(Ok(Vec::new()));
}
app.run_dialog_answers();
assert!(!blocked(&mut app, false, 13.0));
@@ -448,6 +448,71 @@ fn file_dialogs_block_floating_windows_only_while_up() {
assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again");
}
/// #3084: a host whose dialog couldn't open (macOS: `+[NSOpenPanel openPanel]` returned nil)
/// answers with the error. The status line says why, the command doesn't run and the dialog
/// no longer blocks floating windows; the next dialog opens as usual.
#[test]
fn a_dialog_that_cannot_open_reports_an_error() {
use std::sync::{Arc, Mutex};
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
let ctx = egui::Context::default();
let pending: Arc<Mutex<Vec<crate::DialogDone>>> = Arc::default();
let queue = pending.clone();
app.hooks.file_dialog_async = Some(Box::new(move |_dialog, done| queue.lock().unwrap().push(done)));
let blocked = |app: &mut EffectcraftApp, focused: bool, time: f64| {
let input = egui::RawInput { focused, time: Some(time), ..Default::default() };
let mut out = false;
ctx.run_ui(input, |ui| out = app.floats_blocked(ui.ctx())).textures_delta.clear();
out
};
let items = app.session.project.items.len();
assert_eq!(invoke(&mut app, &ctx, "file.importAep", json!({})).unwrap(), json!({"dialog": "file.importAep"}));
assert!(blocked(&mut app, true, 0.1));
let done = pending.lock().unwrap().pop().expect("a dialog was asked for");
std::thread::spawn(move || done(Err("The Open dialog couldn't open".into()))).join().unwrap();
app.run_dialog_answers();
assert_eq!(app.ui.status, "The Open dialog couldn't open");
assert_eq!(app.session.project.items.len(), items, "nothing was imported");
assert!(!blocked(&mut app, false, 0.2), "the failed dialog doesn't block floating windows");
invoke(&mut app, &ctx, "file.importAep", json!({})).unwrap();
assert_eq!(pending.lock().unwrap().len(), 1, "the next dialog opens");
}
/// Coverage for #3084 (not its regression test, which needs macOS): every enabled File ▸ Import
/// item that asks for a file asks through the host's one dialog path (`Hooks::file_dialog_async`
/// where the host has it), never through a blocking picker; After Effects Project is no
/// different from the others.
#[test]
fn every_import_item_asks_through_the_shared_dialog_path() {
use std::sync::{Arc, Mutex};
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
let ctx = egui::Context::default();
app.hooks.pick_files = Some(Box::new(|_: &[&str]| panic!("the blocking picker is not used")));
app.hooks.pick_open_project = Some(Box::new(|| panic!("the blocking picker is not used")));
app.hooks.pick_folder = Some(Box::new(|| panic!("the blocking picker is not used")));
let pending: Arc<Mutex<Vec<crate::FileDialog>>> = Arc::default();
let queue = pending.clone();
app.hooks.file_dialog_async = Some(Box::new(move |dialog, _done| queue.lock().unwrap().push(dialog)));
// Placeholder and Solid open a form of the app's own and ask for no file.
const IN_APP_FORM: &[&str] = &["file.importPlaceholder", "file.importSolid"];
let import: Vec<_> = effectcraft_engine::menus::entries()
.into_iter()
.filter(|(path, _)| path.iter().map(String::as_str).eq(["File", "Import"]))
.map(|(_, e)| e)
.filter(|e| app.session.is_enabled(&e.command) && !IN_APP_FORM.contains(&e.command.as_str()))
.collect();
assert!(import.iter().any(|e| e.command == "file.importAep"), "File ▸ Import has After Effects Project");
for entry in import {
let r = invoke(&mut app, &ctx, &entry.command, entry.params_or_empty());
assert_eq!(r, Ok(json!({"dialog": entry.command})), "{}", entry.command);
let dialog = pending.lock().unwrap().pop();
assert!(dialog.is_some(), "{}: asks through the shared dialog path", entry.command);
if entry.command == "file.importAep" {
assert_eq!(dialog, Some(crate::FileDialog::Open { exts: vec!["aep".into(), "aepx".into()], many: false }));
}
}
}
#[test]
fn tga_is_available_in_import_replace_and_proxy_dialogs() {
use std::sync::{Arc, Mutex};
@@ -463,6 +528,80 @@ fn tga_is_available_in_import_replace_and_proxy_dialogs() {
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn dropped_files_keep_import_errors_alongside_local_drop_errors() {
#[derive(Debug)]
struct Drop(std::path::PathBuf);
impl egui::DroppedFile for Drop {
fn path(&self) -> &std::path::Path {
&self.0
}
fn bytes(&self) -> Result<Vec<u8>, String> {
std::fs::read(&self.0).map_err(|e| e.to_string())
}
}
let folder = std::env::temp_dir().join(format!("effectcraft-mixed-drop-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("no-pdf.vectorcraft");
std::fs::write(&path, br#"{"format":"vectorcraft","version":4,"document":{"artboards":[],"layers":[]}}"#).unwrap();
let second = folder.join("also-no-pdf.vectorcraft");
std::fs::copy(&path, &second).unwrap();
let footage = folder.join("pending.png");
std::fs::write(&footage, b"not a PNG").unwrap();
for (bad_import, background) in [(false, false), (true, false), (true, true)] {
let mut app = EffectcraftApp::new(effectcraft_host::session());
app.session.prefs.import.drag_import_as = "comp".into();
let ctx = egui::Context::default();
let mut dropped_files: Vec<egui::DroppedFileHandle> = vec![std::sync::Arc::new(Drop("no-local-path".into()))];
if bad_import {
dropped_files.push(std::sync::Arc::new(Drop(path.clone())));
dropped_files.push(std::sync::Arc::new(Drop(second.clone())));
}
if background {
dropped_files.push(std::sync::Arc::new(Drop(footage.clone())));
}
ctx.run_ui(egui::RawInput { dropped_files, ..Default::default() }, |ui| {
crate::prefs_live::dropped_files(&mut app, ui, ui.max_rect());
})
.textures_delta
.clear();
assert!(app.ui.status.contains("without a local path"), "{}", app.ui.status);
if bad_import {
assert!(app.ui.status.contains("no-pdf.vectorcraft") && app.ui.status.contains("Create PDF-Compatible File"), "{}", app.ui.status);
let details = &app.error_toasts.back().expect("all import errors remain available").message;
assert!(details.contains("also-no-pdf.vectorcraft"), "{details}");
if background {
app.session.execute("jobs.wait", json!({})).unwrap();
app.handle_events(&ctx);
let details = &app.error_toasts.back().unwrap().message;
for name in ["no-pdf.vectorcraft", "also-no-pdf.vectorcraft", "pending.png"] {
assert!(details.contains(name), "{details}");
}
assert!(app.ui.status.contains("without a local path"));
}
} else {
assert!(!app.ui.status.contains(";"), "{}", app.ui.status);
}
}
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn importing_without_a_form_shows_immediate_file_errors() {
let folder = std::env::temp_dir().join(format!("effectcraft-drop-import-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("no-pdf.vectorcraft");
std::fs::write(&path, br#"{"format":"vectorcraft","version":4,"document":{"artboards":[],"layers":[]}}"#).unwrap();
let mut app = EffectcraftApp::new(effectcraft_host::session());
let ctx = egui::Context::default();
let r = invoke(&mut app, &ctx, "file.import", json!({"paths": [path], "importAs": "composition", "background": true, "drag": true})).unwrap();
assert!(app.dialog.is_none());
assert!(r["errors"][0].as_str().unwrap().contains("Create PDF-Compatible File"));
assert!(app.ui.status.contains("no-pdf.vectorcraft") && app.ui.status.contains("Create PDF-Compatible File"), "{}", app.ui.status);
std::fs::remove_dir_all(folder).unwrap();
}
/// Cmd+W with the Render Queue focused closes the queue; the composition next to it stays
/// open (it used to be closed, and the queue stayed).
#[test]
@@ -677,7 +816,10 @@ fn opening_a_project_leaves_the_home_screen_whatever_its_composition_id() {
assert!(!app.ui.start_screen, "File ▸ Open leaves the Home screen");
// The path picked in a file dialog (`run_with_picked`).
app.ui.start_screen = true;
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.open".into(), key: "path", params: json!({}), paths: vec![path.clone()] });
super::frontend::dialog_answered(
&mut app,
crate::DialogAnswer { command: "file.open".into(), key: "path", params: json!({}), paths: Ok(vec![path.clone()]) },
);
assert_eq!(app.session.active_comp_id(), comp);
assert!(!app.ui.start_screen, "a picked project leaves the Home screen");
let _ = std::fs::remove_dir_all(&dir);
@@ -701,6 +843,35 @@ fn bundle_result_errors_show_compactly_in_the_status_line() {
assert_eq!(app.ui.status, "a.wasm: already installed; b.wasm: does not load; c.wasm: cannot read it; +1 more");
}
/// A picked or menu import reports its errors twice: `report_import_errors` queues the details
/// with a short status, and the command's result then writes the longer status. Dismissing that
/// status still acknowledges the queued details, also when After Effects project errors lead it.
/// Another command's errors do not take over an import's details, even with the same text.
#[test]
fn an_import_status_rewritten_by_its_result_still_acknowledges_its_details() {
let long = format!("first failed file {}", "x".repeat(20_000));
for first in ["first failed file", "first failed file\nwith a second line", long.as_str()] {
let import = json!({"errors": [first, "second failed file"]});
let with_aep = json!({"errors": ["project.aep: cannot read it", first, "second failed file"]});
for result in [&import, &with_aep] {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.report_import_errors("file.import", &import);
super::frontend::show_command_result_errors(&mut app, "file.import", result);
assert!(app.ui.status.contains("first failed file"), "{}", app.ui.status);
assert_eq!(app.error_toasts.len(), 1);
assert!(app.error_toasts.back().unwrap().reported_by(&app.ui.status), "{first:.40}: {:.80}", app.ui.status);
}
}
let import = json!({"errors": ["first failed file", "second failed file"]});
for other in [json!({"errors": [{"file": "a.wasm", "error": "does not load"}]}), import.clone()] {
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.report_import_errors("file.import", &import);
super::frontend::show_command_result_errors(&mut app, "effect.installBundle", &other);
assert!(!app.ui.status.contains("(and"), "{}", app.ui.status);
assert!(!app.error_toasts.back().unwrap().reported_by(&app.ui.status), "{}", app.ui.status);
}
}
/// Effect ▸ Install Effect Plug-in… picks its dialog by params: a bundle asks for a folder,
/// a plain install asks for a `.wasm`, and with both given inline nothing asks at all.
#[test]
@@ -755,7 +926,7 @@ fn import_file_dialog_offers_and_imports_after_effects_projects() {
assert!(many && exts.iter().any(|e| e == "aep") && exts.iter().any(|e| e == "aepx"), "{exts:?}");
assert!(exts.iter().any(|e| e == "png"), "footage too");
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: vec![aep] });
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(vec![aep]) });
let comp = app.session.project.item(app.session.active_comp_id().expect("a composition is open")).unwrap();
assert_eq!(comp.name, "Intro");
assert_eq!(app.session.project.item(comp.parent.expect("in a folder")).unwrap().name, "Intro.aep");
@@ -816,7 +987,10 @@ fn picked_projects_report_every_error() {
std::fs::write(&aep, b"not an aep").unwrap();
std::fs::write(&ecproj, b"not a project").unwrap();
let paths = vec![aep.to_string_lossy().to_string(), ecproj.to_string_lossy().to_string()];
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: paths.clone() });
super::frontend::dialog_answered(
&mut app,
crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths.clone()) },
);
let status = &app.ui.status;
assert!(status.contains("broken.aep") && status.contains("broken.ecproj"), "{status}");
assert!(!status.contains('"'), "messages, not quoted JSON: {status}");
@@ -847,7 +1021,7 @@ fn a_picked_project_with_losses_asks_and_the_next_waits() {
source.execute("comp.new", json!({"name": "Intro", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();
source.execute("file.exportAep", json!({"path": intro, "allowLosses": true})).unwrap();
let paths = vec![lossy.to_string_lossy().to_string(), intro.clone()];
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths });
super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths) });
assert_eq!(app.dialog, Some(crate::Dialog::AepLosses));
assert_eq!(app.dialog_state.aep_losses.queue, [intro]);
assert!(app.session.project.items.is_empty(), "nothing imported before the answer");
+401
View File
@@ -0,0 +1,401 @@
//! Basic arithmetic typed into a number field (#3195): `960/2`, `(3+4)*2`, `100*2`, and, in a
//! field that knows the value it showed, a leading operator that applies to it: `*2` doubles,
//! `/2` halves, `+50` adds 50, as the issue's reporter describes for After Effects (not confirmed
//! in public docs). A leading `-` is a negative number (`-50`), not a subtraction. (Hot text used
//! to read `+50` as 50; it now adds 50.)
//!
//! This is a small parser for numbers and `+ - * / ( )` only: no names, no functions, nothing is
//! run as code (expressions, `crates/expr`, are a different thing). The text is bounded in
//! length and nesting, every step must stay finite, and a division by zero is no value. Text it
//! can't read is `None`, so the field keeps its value.
/// The longest text read as arithmetic (characters, after removing spaces).
const MAX_LEN: usize = 256;
/// How deeply brackets and signs (`-(-(…))`, `--5`) may nest.
const MAX_DEPTH: usize = 32;
/// A typed leading operator: what it does to the value the field showed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Step {
/// `+n`
Add(f64),
/// `*n`
Mul(f64),
/// `/n` (never zero)
Div(f64),
}
impl Step {
/// `current` changed by the step; `None` when that isn't a finite number.
pub fn apply(self, current: f64) -> Option<f64> {
match self {
Step::Add(n) => finite(current + n),
Step::Mul(k) => finite(current * k),
Step::Div(n) => divide(current, n),
}
}
/// The factor a `*` or `/` step multiplies by (`None` for `+`), for other layers that scale
/// their own value by it.
pub fn factor(self) -> Option<f64> {
match self {
Step::Add(_) => None,
Step::Mul(k) => finite(k),
Step::Div(n) => divide(1.0, n),
}
}
}
/// What typed text says: a value, or (with a leading `+`, `*` or `/`) a step from the value shown.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Typed {
Value(f64),
Step(Step),
}
/// Read typed `text`. With `steps`, a leading `+`, `*` or `/` is a [`Step`]; without (a field
/// that reads its text on every keystroke, where a step would compound) a leading `+` is a plain
/// sign and a leading `*` or `/` is no value. Spaces, including thousands groups, are ignored
/// (as egui's own parser did) and `−` (U+2212) is a minus. `,` is a decimal point: hot text
/// always read it so, and the dialog fields, whose egui parser rejected it, now do too (so
/// `1,5` is 1.5 and `1,000` is 1, not a thousand). `None` for anything else that isn't a finite
/// number.
pub fn read(text: &str, steps: bool) -> Option<Typed> {
let s: String = text
.chars()
.filter(|c| !c.is_whitespace())
.map(|c| match c {
'−' => '-',
',' => '.',
c => c,
})
.collect();
if s.is_empty() || s.chars().count() > MAX_LEN {
return None;
}
let first = s.chars().next()?;
if steps && matches!(first, '+' | '*' | '/') {
let operand = parse(s.get(first.len_utf8()..)?)?;
return Some(Typed::Step(match first {
'+' => Step::Add(operand),
'*' => Step::Mul(operand),
_ => Step::Div((operand != 0.0).then_some(operand)?),
}));
}
parse(&s).map(Typed::Value)
}
/// The value typed `text` stands for: [`read`], with a step applied to `current` (the value the
/// field showed; without it a leading `*` or `/` is no value and `+` only a sign).
pub fn calc(text: &str, current: Option<f64>) -> Option<f64> {
match read(text, current.is_some())? {
Typed::Value(v) => Some(v),
Typed::Step(step) => step.apply(current.filter(|c| c.is_finite())?),
}
}
/// The whole of `s` as an expression.
fn parse(s: &str) -> Option<f64> {
let mut p = Parser { chars: s.chars().peekable(), depth: 0 };
let v = p.expr()?;
if p.chars.next().is_some() {
return None;
}
finite(v)
}
/// `a / b`; `None` for a division by zero.
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
return None;
}
finite(a / b)
}
/// A finite result, or `None`.
fn finite(v: f64) -> Option<f64> {
v.is_finite().then_some(v)
}
/// A recursive-descent reader of `expr := term (('+'|'-') term)*`,
/// `term := factor (('*'|'/') factor)*`, `factor := ('+'|'-') factor | '(' expr ')' | number`.
struct Parser<'a> {
chars: std::iter::Peekable<std::str::Chars<'a>>,
/// The brackets and signs open around the current point.
depth: usize,
}
impl Parser<'_> {
/// Reads a sum or difference of terms, left to right.
/// Returns `None` on a syntax error or a non-finite result.
fn expr(&mut self) -> Option<f64> {
let mut v = self.term()?;
while let Some(&op) = self.chars.peek() {
match op {
'+' => {
self.chars.next();
v = finite(v + self.term()?)?;
}
'-' => {
self.chars.next();
v = finite(v - self.term()?)?;
}
_ => break,
}
}
Some(v)
}
/// Reads a product or quotient of factors, left to right.
/// Returns `None` on a syntax error, a division by zero or a non-finite result.
fn term(&mut self) -> Option<f64> {
let mut v = self.factor()?;
while let Some(&op) = self.chars.peek() {
match op {
'*' => {
self.chars.next();
v = finite(v * self.factor()?)?;
}
'/' => {
self.chars.next();
v = divide(v, self.factor()?)?;
}
_ => break,
}
}
Some(v)
}
/// Reads a signed factor, a bracketed expression or a number.
/// Nesting deeper than `MAX_DEPTH` gives `None`.
fn factor(&mut self) -> Option<f64> {
let c = *self.chars.peek()?;
match c {
'+' | '-' | '(' => {
self.depth = self.depth.checked_add(1)?;
if self.depth > MAX_DEPTH {
return None;
}
self.chars.next();
let v = if c == '(' {
let v = self.expr()?;
if self.chars.next() != Some(')') {
return None;
}
v
} else {
let v = self.factor()?;
if c == '-' { -v } else { v }
};
self.depth = self.depth.saturating_sub(1);
Some(v)
}
_ => self.number(),
}
}
/// Digits with at most one decimal point and an optional exponent (`12`, `1.5`, `.5`, `2.`,
/// `2e2`, `1.5E-3`).
fn number(&mut self) -> Option<f64> {
let mut text = String::new();
let mut point = false;
while let Some(&c) = self.chars.peek() {
if c.is_ascii_digit() {
text.push(c);
} else if c == '.' && !point {
point = true;
text.push(c);
} else {
break;
}
self.chars.next();
}
if !text.chars().any(|c| c.is_ascii_digit()) {
return None;
}
if let Some(&e) = self.chars.peek()
&& matches!(e, 'e' | 'E')
{
self.chars.next();
text.push('e');
if let Some(&sign) = self.chars.peek()
&& matches!(sign, '+' | '-')
{
self.chars.next();
text.push(sign);
}
let mut digits = false;
while let Some(&c) = self.chars.peek() {
if !c.is_ascii_digit() {
break;
}
digits = true;
text.push(c);
self.chars.next();
}
if !digits {
return None;
}
}
finite(text.parse::<f64>().ok()?)
}
}
#[cfg(test)]
mod tests {
use super::calc as eval;
/// Evaluates `text` with no current value, so a leading operator has nothing to apply to.
fn abs(text: &str) -> Option<f64> {
eval(text, None)
}
#[test]
fn plain_numbers_read_as_before() {
assert_eq!(abs("100"), Some(100.0));
assert_eq!(abs("-12.5"), Some(-12.5));
assert_eq!(abs(" 12,5 "), Some(12.5), "a decimal comma");
assert_eq!(abs("1 000"), Some(1000.0), "a thousands space");
assert_eq!(abs("−3"), Some(-3.0), "the minus sign U+2212");
assert_eq!(abs("1e3"), Some(1000.0));
assert_eq!(abs(".5"), Some(0.5));
}
#[test]
fn arithmetic() {
assert_eq!(abs("960/2"), Some(480.0));
assert_eq!(abs("100*2"), Some(200.0));
assert_eq!(abs("(3+4)*2"), Some(14.0));
assert_eq!(abs("3+4*2"), Some(11.0), "* before +");
assert_eq!(abs("10-2-3"), Some(5.0), "left to right");
assert_eq!(abs("8/4/2"), Some(1.0), "left to right");
assert_eq!(abs("-(2+3)"), Some(-5.0));
assert_eq!(abs("2*-3"), Some(-6.0));
assert_eq!(abs("1.5 * 2"), Some(3.0));
assert_eq!(abs("((((1))))"), Some(1.0));
assert_eq!(abs("100+50"), Some(150.0));
assert_eq!(abs("100-50"), Some(50.0));
assert_eq!(abs("2e2*2"), Some(400.0), "an exponent inside arithmetic");
assert_eq!(abs("1E-3*1000"), Some(1.0));
assert_eq!(abs("1e+2/4"), Some(25.0));
}
#[test]
fn steps_are_read_as_steps() {
use super::{Step, Typed, read};
assert_eq!(read("*2", true), Some(Typed::Step(Step::Mul(2.0))));
assert_eq!(read("/4", true), Some(Typed::Step(Step::Div(4.0))));
assert_eq!(read("+(1+2)", true), Some(Typed::Step(Step::Add(3.0))));
assert_eq!(read("-5", true), Some(Typed::Value(-5.0)));
assert_eq!(read("+5", false), Some(Typed::Value(5.0)));
assert_eq!(read("/0", true), None);
assert_eq!(Step::Div(4.0).factor(), Some(0.25));
assert_eq!(Step::Mul(3.0).factor(), Some(3.0));
assert_eq!(Step::Add(3.0).factor(), None);
assert_eq!(Step::Div(1e-320).factor(), None, "a factor that overflows");
assert_eq!(Step::Div(3.0).apply(3.0), Some(1.0), "a division, not a reciprocal factor");
}
#[test]
fn a_leading_operator_applies_to_the_current_value() {
assert_eq!(eval("*2", Some(100.0)), Some(200.0));
assert_eq!(eval("/2", Some(100.0)), Some(50.0));
assert_eq!(eval("+50", Some(100.0)), Some(150.0));
assert_eq!(eval("*(1+1)", Some(3.0)), Some(6.0));
assert_eq!(eval("+-50", Some(100.0)), Some(50.0));
// A leading minus is a negative number, not a subtraction.
assert_eq!(eval("-50", Some(100.0)), Some(-50.0));
assert_eq!(eval("-50*2", Some(100.0)), Some(-100.0));
// Without the current value there is nothing to apply it to; a `+` is only a sign.
assert_eq!(eval("*2", None), None);
assert_eq!(eval("/2", None), None);
assert_eq!(eval("+50", None), Some(50.0));
assert_eq!(eval("*2", Some(f64::NAN)), None);
assert_eq!(eval("+1", Some(f64::INFINITY)), None);
assert_eq!(eval("/0", Some(100.0)), None);
assert_eq!(eval("/(1-1)", Some(100.0)), None);
assert_eq!(eval("*", Some(100.0)), None);
assert_eq!(eval("*1e400", Some(1.0)), None);
// Overflow past the largest finite value.
assert_eq!(eval(&format!("*{}", "9".repeat(20)), Some(1e300)), None);
assert_eq!(eval("/0.0000000001", Some(1e300)), None);
}
#[test]
fn invalid_or_hostile_text_is_no_value() {
for text in [
"", " ", "*", "/", "1+", "+", "-", "2**3", "2//3", "1/0", "0/0", "-1/0", "1/(2-2)", "(1", "1)", "()", "(1+2", "abc", "NaN", "nan", "inf", "-inf",
"infinity", "1e999", "-1e999", "1..2", "1.2.3", ".", "1e", "2x", "x*2", "1+a", "5;rm", "1,2,3", "0x10", "1_000", "%", "50%",
] {
assert_eq!(abs(text), None, "{text:?}");
assert_eq!(eval(text, Some(10.0)), None, "{text:?} with a current value");
}
// Far too long: rejected by length before any reading.
assert_eq!(abs(&format!("{}1{}", "(".repeat(1000), ")".repeat(1000))), None);
assert_eq!(abs(&format!("{}5", "-".repeat(10_000))), None);
assert_eq!(abs(&"(".repeat(10_000)), None);
assert_eq!(abs(&"1".repeat(10_000)), None);
assert_eq!(abs(&"1+".repeat(5_000)), None);
// Short enough, but nested past the depth bound.
assert_eq!(abs(&format!("{}1{}", "(".repeat(100), ")".repeat(100))), None);
assert_eq!(abs(&format!("{}5", "-".repeat(200))), None);
assert_eq!(abs(&format!("2*{}5", "-+".repeat(100))), None);
// Nesting within the bound reads.
assert_eq!(abs(&format!("{}1{}", "(".repeat(20), ")".repeat(20))), Some(1.0));
assert_eq!(abs("--5"), Some(5.0));
// Overflow on the way is no value.
assert_eq!(abs("1e308*10"), None);
assert_eq!(abs("1e308+1e308"), None);
assert_eq!(abs("1e200*1e200/1e200"), None, "an infinite step is rejected even if the result would be finite");
// The largest numbers the length allows still multiply to a finite value.
let big = "9".repeat(120);
assert!(abs(&format!("{big}*{big}")).is_some_and(f64::is_finite));
}
/// The result is always finite (no NaN reaches a property).
#[test]
fn results_are_finite() {
for text in ["0*1e308", "1e-320/1e10", "0-0", "-0"] {
if let Some(v) = abs(text) {
assert!(v.is_finite(), "{text:?} → {v}");
}
}
}
/// A standard numeric editor (dialogs) reads typed arithmetic too.
/// (egui's own parser read `960/2` as no value, so the field stayed 10.)
#[test]
fn a_drag_value_reads_typed_arithmetic() {
use egui::{Context, Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
let ctx = Context::default();
let mut value = 10.0_f64;
let mut time = 0.0;
let field = Rect::from_min_size(pos2(100.0, 100.0), vec2(80.0, 20.0));
let mut frame = |events: Vec<Event>, value: &mut f64| {
time += 0.02;
let raw = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))),
time: Some(time),
events,
focused: true,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
ui.put(field, crate::widgets::drag_value(egui::DragValue::new(&mut *value).speed(1.0)));
});
out.textures_delta.clear();
};
let p = field.center();
frame(vec![], &mut value);
frame(
vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
&mut value,
);
frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], &mut value);
frame(vec![], &mut value);
frame(vec![Event::Text("960/2".into())], &mut value);
frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], &mut value);
frame(vec![], &mut value);
assert_eq!(value, 480.0);
}
}
+146 -19
View File
@@ -3,8 +3,18 @@
//! the viewer names the ID under the cursor, and a click picks it into the Selection: a plain
//! click replaces it, Shift adds, Alt or Ctrl (Option or Cmd on a Mac) removes. It stays armed
//! for the next click until Esc or the button again, and highlights the hovered ID's coverage.
//! Arming it whenever the effect is selected (After Effects' behaviour, #1811) would only need
//! to set the same pick.
//!
//! As in After Effects, the Selection tool picks the same way without arming anything while the
//! Cryptomatte effect is selected in Effect Controls (#2839, [`implicit_pick`]): over the
//! effect's layer (selected, so the viewer's press acts on it) a click picks and a drag moves nothing;
//! elsewhere the viewer keeps its clicks (selecting and moving layers). Esc has nothing to end.
//! "Over the layer" is its bounding quad, as the viewer's own hit test (not its alpha), less the
//! viewer's handles on it ([`super::viewer::grabs_at`]: bounding-box handles, mask vertices,
//! motion-path keys, guides), which keep scaling, reshaping and moving. A press in the very pass
//! the pointer leaves the layer is passed on to the viewer as a click; one in the pass it arrives
//! on the layer (a touch, a pen without hover) is claimed from the viewer and picks. While the effect is
//! selected (or the eyedropper armed), a double-click on the layer picks (one step: the second
//! click changes nothing) instead of opening its precomp or editing its text.
//!
//! The hover needs the frame's Cryptomatte probe ([`effectcraft_engine::Session::crypto_probe_job`]):
//! it is built off the UI thread, one at a time, not while playing or scrubbing; the chip says so
@@ -21,7 +31,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use effectcraft_engine::commands::CryptoProbeJob;
use effectcraft_engine::geom::Mat3;
use effectcraft_engine::project::Layer;
use effectcraft_engine::project::{GroupKind, Layer};
use effectcraft_engine::render::EvalCtx;
use egui::{Color32, Rect, Sense, vec2};
use serde_json::{Value, json};
@@ -35,6 +45,9 @@ use crate::theme::Tokens;
/// [`FxPick::kind`] of the Cryptomatte eyedropper.
pub const KIND: &str = "crypto";
/// The Cryptomatte effect's match name.
const EFFECT: &str = "ec.3d.cryptomatte";
/// How long the time must stay put before a probe is built for it (scrubbing).
const SETTLE: f64 = 0.1;
@@ -111,6 +124,15 @@ struct State {
seen: Option<((u64, u64), u64)>,
/// The hovered ID's highlight: its hash and probe query, coverage texture, size and uv.
mask: Option<HighlightMask>,
/// Picking with the Selection tool while the effect is selected ([`implicit_pick`]), not with
/// the armed eyedropper.
implicit: bool,
/// The last egui pass the overlay took clicks in (egui hands a press to what sensed it the
/// pass before).
sensed: Option<u64>,
/// The query of the last click queued: the second click of a double-click on the same pixel
/// with the same keys is not queued again.
last_click: Option<Value>,
}
/// Clears the busy flag and repaints when a build ends, a panic included.
@@ -185,9 +207,20 @@ pub fn upkeep(app: &mut EffectcraftApp, ctx: &egui::Context) {
}
ctx.data_mut(|d| d.insert_temp(eid, epoch));
}
if app.ui.fx_pick.as_ref().is_none_or(|p| p.kind != KIND) && ctx.data(|d| d.get_temp::<State>(sid)).is_some() {
// Picking with the Selection tool (the effect selected) keeps its state while the viewer runs
// it, every pass.
let old = ctx.data(|d| d.get_temp::<State>(sid));
let implicit = old.as_ref().is_some_and(|s| s.implicit && s.seen.is_some_and(|(_, n)| n == ctx.cumulative_pass_nr()));
if app.ui.fx_pick.as_ref().is_none_or(|p| p.kind != KIND)
&& !implicit
&& let Some(mut old) = old
{
ctx.data_mut(|d| d.remove::<State>(sid));
app.session.drop_crypto_probe();
// The effect deselected (or the tool changed) while clicks waited: say they're not made.
if old.implicit && !old.pending.is_empty() {
drop_waiting(app, ctx, &mut old);
}
}
// The clicks waiting in the viewer, after everything else this pass did (its keys, edits and
// frame steps included).
@@ -273,10 +306,20 @@ fn viewer_pan_and_secondary(app: &mut EffectcraftApp, ctx: &egui::Context, resp:
}
}
/// Whether Space / Hand / Zoom (`tools`) or middle/right buttons (`nav`) own the pointer.
struct PointerNav {
/// Whether Space / Hand / Zoom (`tools`) or middle/right buttons (`nav`) own the pointer, and
/// whether a press at a point is the overlay's (`owned`: the Selection tool picking only over the
/// effect's layer, off the viewer's own handles there).
struct PointerNav<'a> {
tools: bool,
nav: bool,
owned: &'a dyn Fn(egui::Pos2) -> bool,
/// The overlay took the pass's presses from the viewer (it sensed clicks the pass before):
/// one it does not own is passed on to the viewer ([`super::viewer::FORWARDED_PRIMARY`]).
forward: bool,
/// The overlay did not sense clicks the pass before, so egui hands the pass's presses to the
/// viewer: one it owns (a touch, or a pen without hover, arriving on the layer and pressing in
/// one pass) is claimed from the viewer ([`super::viewer::CLAIMED_PRIMARY`]).
claim: bool,
}
/// Queues Cryptomatte picks from primary presses and releases on the armed eyedropper overlay.
@@ -290,7 +333,7 @@ fn viewer_click_to_pick(
map: &super::viewer::ViewerMap,
ectx: &EvalCtx,
st: &mut State,
pointer: PointerNav,
pointer: PointerNav<'_>,
at: &dyn Fn(egui::Pos2) -> Option<Value>,
) {
let ctx = ui.ctx().clone();
@@ -320,7 +363,18 @@ fn viewer_click_to_pick(
continue;
};
if pressed {
let ours = map.area.contains(pos) && ctx.layer_id_at(pos) == Some(ui.layer_id());
let in_viewer = map.area.contains(pos) && ctx.layer_id_at(pos) == Some(ui.layer_id());
let ours = in_viewer && (pointer.owned)(pos);
// Taken from the viewer but not ours (the pointer left the layer in this very pass):
// the viewer clicks there next pass, so it isn't swallowed.
if pointer.forward && in_viewer && !ours && !pointer.nav {
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(super::viewer::FORWARDED_PRIMARY), (pos, keys, pass)));
}
// Handed to the viewer but ours: the viewer leaves it alone, so it only picks.
if pointer.claim && ours && !pointer.nav {
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(super::viewer::CLAIMED_PRIMARY), ()));
}
st.press = (!pointer.nav && ours).then(|| Press {
pos,
keys,
@@ -348,6 +402,11 @@ fn viewer_click_to_pick(
"replace"
});
let same_frame = q["time"].as_f64() == Some(ectx.time.seconds());
let double = ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary));
if double && st.last_click.as_ref() == Some(&q) {
// The second click of a double-click, same pixel and keys: it would change nothing.
continue;
}
if pos.distance(from) > SLOP {
app.say(&ctx, tr("Drag cancelled the pick").to_string());
} else if app.playback.playing && !(same_frame && app.session.crypto_probe_ready(&q).unwrap_or(false)) {
@@ -361,6 +420,7 @@ fn viewer_click_to_pick(
st.pending_rev = rev;
}
st.after_typing |= typing || ctx.text_edit_focused();
st.last_click = Some(q.clone());
st.pending.push(q);
}
}
@@ -522,7 +582,8 @@ fn handle_escape(app: &mut EffectcraftApp, ui: &mut egui::Ui, st: &mut State) {
}
}
/// The armed eyedropper's part of the viewer. `m` maps the layer's effect space to the comp.
/// The armed eyedropper's part of the viewer, or (`implicit`) the Selection tool's while the
/// effect is selected ([`implicit_pick`]). `m` maps the layer's effect space to the comp.
#[allow(clippy::too_many_arguments)]
pub fn viewer_hook(
app: &mut EffectcraftApp,
@@ -533,6 +594,7 @@ pub fn viewer_hook(
layer: &Layer,
m: &Mat3,
pick: &FxPick,
implicit: bool,
) {
let ctx = ui.ctx().clone();
let sid = pick_id();
@@ -540,7 +602,9 @@ pub fn viewer_hook(
reset_stale_state(app, &ctx, &mut st, pick);
// The Cryptomatte effect that owns the Selection (gone: the pick ends).
let Some(fx) = layer.effects().and_then(|f| f.groups().find(|g| g.find(pick.prop).is_some())).map(|g| g.uid) else {
app.ui.fx_pick = None;
if !implicit {
app.ui.fx_pick = None;
}
return;
};
let start = track_scrub_settle(app, &ctx, &mut st, ectx.time.seconds());
@@ -565,21 +629,84 @@ pub fn viewer_hook(
// The Hand and Zoom tools (Space held too) and other buttons keep their own clicks and drags.
let tools = super::space_hand(&ctx) || matches!(app.ui.tool, Tool::Hand | Tool::Zoom);
let nav = tools || ctx.input(|i| i.pointer.middle_down() || i.pointer.secondary_down());
// Drags too: a click that drifts must not move the layer under it. (egui hands a press to
// what sensed it the pass before, so middle and right presses land here: passed on below.)
let resp = ui.interact(map.area, egui::Id::unique("viewer-fx-pick"), if tools { Sense::hover() } else { Sense::click_and_drag() });
viewer_pan_and_secondary(app, &ctx, &resp);
app.auto.add("viewer.fxPick", map.area, &pick.name);
let mut reading = hover_read(app, &ctx, map, &mut st, &resp, start, &at);
viewer_click_to_pick(app, ui, map, ectx, &mut st, PointerNav { tools, nav }, &at);
let oid = egui::Id::unique("viewer-fx-pick");
// The Selection tool picks only over the effect's layer (#2839): the viewer's press there acts
// on it, a selected layer, even where layers in front cover it ([`super::viewer::pick`]).
// Elsewhere, and on the viewer's own handles there, the viewer keeps its clicks. The armed
// eyedropper picks anywhere.
let ui_layer = ui.layer_id();
let on_layer = |p: egui::Pos2| {
!implicit
|| (map.area.contains(p)
&& ctx.layer_id_at(p) == Some(ui_layer)
&& super::viewer::layer_hit(ectx, layer.id, map.to_comp(p))
&& !super::viewer::grabs_at(&ctx, p))
};
// A press the overlay holds (or its middle-button pan) stays its own wherever the pointer goes.
let panning = ctx.is_being_dragged(oid) && ctx.input(|i| i.pointer.middle_down());
let over = st.press.is_some() || panning || ctx.pointer_hover_pos().is_some_and(on_layer);
let pass = ctx.cumulative_pass_nr();
// Whether the overlay sensed clicks the pass before: egui handed it the pass's presses, not the
// viewer underneath (which would select or move the layer as well). If it didn't, a press of
// ours is claimed from the viewer; if it did, one not ours is passed on to the viewer.
let owned_before = !implicit || st.sensed.is_some_and(|n| n.saturating_add(1) == pass);
st.implicit = implicit;
let mut reading = false;
if !implicit || over {
// Drags too: a click that drifts must not move the layer under it. (egui hands a press to
// what sensed it the pass before, so middle and right presses land here: passed on below.)
let resp = ui.interact(map.area, oid, if tools { Sense::hover() } else { Sense::click_and_drag() });
if !tools {
st.sensed = Some(pass);
}
viewer_pan_and_secondary(app, &ctx, &resp);
app.auto.add(if implicit { "viewer.cryptoSelect" } else { "viewer.fxPick" }, map.area, &pick.name);
reading = hover_read(app, &ctx, map, &mut st, &resp, start, &at);
} else {
(st.asked, st.reply) = (None, None);
}
let pointer = PointerNav { tools, nav, owned: &on_layer, forward: implicit && owned_before, claim: implicit && !owned_before };
viewer_click_to_pick(app, ui, map, ectx, &mut st, pointer, &at);
// Clicks waiting for their probe ([`make_waiting`], at the end of the pass).
reading |= !st.pending.is_empty();
draw_coverage_highlight(app, &ctx, painter, map, m, &mut st);
draw_status_chip(app, &ctx, painter, map, &st, reading);
handle_escape(app, ui, &mut st);
if !implicit || over || reading {
draw_status_chip(app, &ctx, painter, map, &st, reading);
}
// (Selected, the effect has nothing for Esc to end.)
if !implicit {
handle_escape(app, ui, &mut st);
}
ctx.data_mut(|d| d.insert_temp(sid, st));
}
/// The Cryptomatte effect selected in Effect Controls with the Selection tool active (After
/// Effects: clicks in the Composition panel pick its IDs then, no eyedropper armed; #2839): the
/// pick for its Selection. The last selected item on a selected layer counts, and only the
/// effect itself (its header in Effect Controls or the Timeline): a press on one of its rows (the
/// eyedropper's button, the Selection field) selects that property instead. An armed eyedropper
/// or crosshair (of any kind) comes first.
pub fn implicit_pick(app: &EffectcraftApp, ctx: &egui::Context) -> Option<FxPick> {
if app.ui.tool != Tool::Selection || app.ui.fx_pick.is_some() || app.ui.text_color_pick.is_some() || crate::color_picker::eyedropper_armed(ctx) {
return None;
}
// Drawing a region of interest or a Free Transform box: the viewer keeps every press.
if app.ui.viewer.roi_draw || super::viewer_overlays::free_transform_target(ctx).is_some() {
return None;
}
let comp = app.session.active_comp()?;
let time = app.session.time();
let st = &app.session.state;
let (lid, uid) = st.selected_props.iter().rev().find(|(l, _)| st.selected_layers.contains(l))?;
let layer = comp.layer(*lid).filter(|l| l.is_active_at(time))?;
let fx = layer.effects()?.groups().find(|g| g.uid == *uid)?;
if !fx.enabled || !matches!(&fx.kind, GroupKind::Effect { effect } if effect == EFFECT) {
return None;
}
let prop = fx.get("selection")?;
Some(FxPick { kind: KIND.into(), layer: lid.0, prop: prop.uid, name: prop.name.clone() })
}
#[cfg(test)]
mod tests {
use super::*;
+9 -2
View File
@@ -1,6 +1,13 @@
//! Effect Controls: the selected layer's effects with all parameters, in After Effects'
//! conventions:
//!
//! - the tab's lock icon keeps the panel on the layer it shows whatever is selected next (a
//! pick whip from another layer's property can then reach its parameters); deleting that
//! layer or replacing the project unlocks it (see [`set_lock`]). The lock holds while the
//! locked layer's comp is the active comp: with another comp active the panel shows that
//! comp's selection (its edits address layers of the active comp), and the locked layer
//! again when its comp is back. The Effect menu of a right-click on empty space applies to
//! the selected layers, as in After Effects;
//! - effect headers with the fx switch, twirl, Reset and About…; click selects the effect
//! (Edit ▸ Copy / Paste / Duplicate and Delete then act on it), drag reorders the stack, the
//! context menu copies, pastes, duplicates, resets and removes;
@@ -34,8 +41,8 @@ mod panel;
mod rows;
mod viewer;
pub(crate) use common::gesture_key;
pub use common::{choose_files_after_apply, reveal_applied};
pub use common::{choose_files_after_apply, reveal_applied, set_lock};
pub(crate) use common::{gesture_key, scope_lock, shown_layer_id};
pub(crate) use panel::handle_disclosure_key;
pub use panel::{show, start_rename};
pub(crate) use rows::toggle_pick;
@@ -27,10 +27,70 @@ pub(super) fn effect_active(g: &PropGroup, layer: effectcraft_engine::project::L
selected.iter().any(|(l, uid)| *l == layer && contains(g, *uid, 0))
}
pub(super) fn selected_layer(app: &EffectcraftApp) -> Option<Layer> {
/// The layer Effect Controls shows: the layer it is locked to (its tab's lock) while that layer's
/// comp is the active comp, else the first selected layer of the active comp.
pub(crate) fn shown_layer_id(app: &EffectcraftApp) -> Option<effectcraft_engine::project::LayerId> {
let comp = app.session.active_comp()?;
let id = app.session.state.selected_layers.first()?;
comp.layer(*id).cloned()
if let Some(lock) = app.ui.effect_controls_lock
&& app.session.active_comp_id().is_some_and(|c| c.0 == lock.comp)
&& comp.layer(effectcraft_engine::project::LayerId(lock.layer)).is_some()
{
return Some(effectcraft_engine::project::LayerId(lock.layer));
}
app.session.state.selected_layers.first().copied().filter(|id| comp.layer(*id).is_some())
}
/// Returns the layer Effect Controls currently shows, locked or selected, or `None` when there is none.
pub(super) fn shown_layer(app: &EffectcraftApp) -> Option<Layer> {
let id = shown_layer_id(app)?;
app.session.active_comp()?.layer(id).cloned()
}
/// Lock Effect Controls on the layer it shows (`on`), or unlock it. Locking with no layer shown
/// does nothing; locking while already locked keeps the layer it is locked to. Returns whether
/// the panel is locked afterwards. The tab's lock icon and `ui.set {effectControlsLocked}`.
pub fn set_lock(app: &mut EffectcraftApp, on: bool) -> bool {
// A lock left from a replaced project is gone before this one is answered (a control
// request can run between the replacement and the next frame).
scope_lock(app);
if !on {
app.ui.effect_controls_lock = None;
return false;
}
if app.ui.effect_controls_lock.is_some() {
return true;
}
let Some(comp) = app.session.active_comp_id() else { return false };
let Some(layer) = shown_layer_id(app) else { return false };
app.ui.effect_controls_lock = Some(crate::state::EffectControlsLock { comp: comp.0, layer: layer.0 });
app.ui.effect_controls_lock_epoch = app.session.script_ui.project_epoch;
true
}
/// Once a frame: a lock made in another project (New, Open: the ids start over) or on a layer or
/// comp since deleted is dropped, whether or not Effect Controls is on screen.
pub(crate) fn scope_lock(app: &mut EffectcraftApp) {
let epoch = app.session.script_ui.project_epoch;
if app.ui.effect_controls_lock_epoch != epoch {
app.ui.effect_controls_lock_epoch = epoch;
app.ui.effect_controls_lock = None;
}
prune_lock(app);
}
/// A lock whose layer or comp no longer exists (deleted, or its comp deleted) is dropped, so the
/// panel follows the selection again and its tab shows it unlocked. Another comp being active
/// keeps the lock: the panel shows the locked layer again when its comp comes back.
pub(super) fn prune_lock(app: &mut EffectcraftApp) {
let Some(lock) = app.ui.effect_controls_lock else { return };
let alive = app
.session
.project
.comp(effectcraft_engine::project::ItemId(lock.comp))
.is_some_and(|c| c.layer(effectcraft_engine::project::LayerId(lock.layer)).is_some());
if !alive {
app.ui.effect_controls_lock = None;
}
}
/// An effect was just applied (`effect.apply` / `effect.applyLast` with `params`): Effect
@@ -39,10 +99,14 @@ pub(super) fn selected_layer(app: &EffectcraftApp) -> Option<Layer> {
pub fn reveal_applied(app: &mut EffectcraftApp, params: &serde_json::Value) {
// `effect.apply` selects the new effect on (the last of) the layers it went to.
let target = app.session.state.selected_props.last().map(|(l, _)| *l);
// Effect Controls locked to a layer of the active comp keeps showing that layer.
let locked = app.ui.effect_controls_lock.filter(|k| app.session.active_comp_id().is_some_and(|c| c.0 == k.comp));
if let Some(l) = target
&& !app.session.state.selected_layers.contains(&l)
&& params.get("comp").is_none()
&& app.session.active_comp().is_some_and(|c| c.layer(l).is_some())
// Dropped on the locked panel: it shows that layer already, the selection stays.
&& locked.is_none_or(|k| k.layer != l.0)
{
// Show that layer (dropped on an unselected one), keeping the new effect selected.
let props = app.session.state.selected_props.clone();
@@ -51,6 +115,14 @@ pub fn reveal_applied(app: &mut EffectcraftApp, params: &serde_json::Value) {
Err(e) => app.ui.status = e.to_string(),
}
}
// The effect went to another layer than the one the locked panel shows: say why it isn't
// there (After Effects opens another Effect Controls tab).
if let (Some(k), Some(l)) = (locked, target)
&& k.layer != l.0
&& let Some(name) = app.session.active_comp().and_then(|c| c.layer(effectcraft_engine::project::LayerId(k.layer))).map(|x| x.name.clone())
{
app.ui.status = crate::i18n::tr_args("Effect Controls is locked to {}", &[&name]);
}
app.raise_panel(crate::dock::PanelKind::EffectControls);
}
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more