mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-28 09:09:39 +01:00
Merge main into feat/import-photocraft
This commit is contained in:
commit
e2b17586c0
69 files changed
+2837
-1511
No files matched your search
Generated
+20
-109
@@ -147,21 +147,6 @@ dependencies = [
|
||||
"equator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -809,16 +794,6 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "6.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "built"
|
||||
version = "0.8.1"
|
||||
@@ -1397,39 +1372,6 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
|
||||
"craft-metadata",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
@@ -1482,18 +1424,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
@@ -1540,7 +1470,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ce2ec507c2e6a6a078a5f450f641487f8931816d#ce2ec507c2e6a6a078a5f450f641487f8931816d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1564,7 +1494,7 @@ name = "craft-raw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
|
||||
dependencies = [
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
|
||||
"craft-tiff",
|
||||
"miniz_oxide 0.9.1",
|
||||
"rayon",
|
||||
"serde",
|
||||
@@ -1576,10 +1506,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45#77686f24fe8665c21369f1b593f4d65a973e2a45"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45)",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
"quick-xml 0.41.0",
|
||||
@@ -1600,16 +1529,16 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1633,6 +1562,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb"
|
||||
dependencies = [
|
||||
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
@@ -1754,7 +1691,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45#77686f24fe8665c21369f1b593f4d65a973e2a45"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2275,6 +2212,7 @@ dependencies = [
|
||||
name = "effectcraft-interchange"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)",
|
||||
"effectcraft-color",
|
||||
"effectcraft-keyframe",
|
||||
"effectcraft-project",
|
||||
@@ -2379,6 +2317,7 @@ dependencies = [
|
||||
"effectcraft-raster",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"tiny-skia 0.12.0",
|
||||
]
|
||||
|
||||
@@ -3045,7 +2984,7 @@ version = "0.20.1"
|
||||
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
|
||||
dependencies = [
|
||||
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9)",
|
||||
"craft-jpeg",
|
||||
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
|
||||
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)",
|
||||
"craft-y4m",
|
||||
@@ -3077,7 +3016,7 @@ version = "0.20.1"
|
||||
source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c"
|
||||
dependencies = [
|
||||
"craft-raw",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)",
|
||||
"craft-tiff",
|
||||
"image",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3766,9 +3705,6 @@ name = "hayro-jpeg2000"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
@@ -4030,7 +3966,6 @@ dependencies = [
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -4181,12 +4116,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -5579,15 +5508,6 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
@@ -9013,15 +8933,6 @@ dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpegxl"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
|
||||
dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.0"
|
||||
|
||||
+3
-2
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/effectcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd8bed815b8366869a800d2bf22588ca62dcb", default-features = false }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
@@ -20,8 +21,8 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
|
||||
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
|
||||
|
||||
@@ -441,6 +441,8 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
menu: native_menu::NativeBar::new(&cc.egui_ctx),
|
||||
#[cfg(target_os = "macos")]
|
||||
menu_sync: Default::default(),
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: apple_events.connect(&cc.egui_ctx),
|
||||
app,
|
||||
file_dialogs,
|
||||
@@ -531,6 +533,8 @@ struct Desktop {
|
||||
dialog_errors: std::sync::mpsc::Receiver<String>,
|
||||
#[cfg(target_os = "macos")]
|
||||
menu: native_menu::NativeBar,
|
||||
#[cfg(target_os = "macos")]
|
||||
menu_sync: effectcraft_ui_egui::native_menu::MenuSync,
|
||||
/// Documents opened from Finder, the Dock or `open` (macOS).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: apple_events::Opened,
|
||||
@@ -547,7 +551,7 @@ impl eframe::App for Desktop {
|
||||
/// file dialogs asked for and, last, hand a close to the platform quit.
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
self.menu.update(&mut self.app, ctx);
|
||||
self.menu_sync.before(&mut self.app, |app| self.menu.update(app, ctx));
|
||||
self.app.tick(ctx, frame);
|
||||
self.app.finish_ime_logic(ctx);
|
||||
while let Ok(e) = self.dialog_errors.try_recv() {
|
||||
@@ -561,6 +565,9 @@ impl eframe::App for Desktop {
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
self.app.ui(ui, frame);
|
||||
// A file dialog this frame's commands opened (or one that closed) syncs the menu again.
|
||||
#[cfg(target_os = "macos")]
|
||||
self.menu_sync.after(&mut self.app, |app| self.menu.update(app, ui.ctx()));
|
||||
if let Some(asked) = &self.file_dialogs {
|
||||
file_dialogs::show_asked(asked, frame, ui.ctx());
|
||||
}
|
||||
|
||||
@@ -118,6 +118,12 @@ impl NativeBar {
|
||||
Role::Hide => PredefinedMenuItem::hide(Some(label)),
|
||||
Role::HideOthers => PredefinedMenuItem::hide_others(Some(label)),
|
||||
Role::ShowAll => PredefinedMenuItem::show_all(Some(label)),
|
||||
Role::SelectAll => PredefinedMenuItem::select_all(Some(label)),
|
||||
Role::Cut => PredefinedMenuItem::cut(Some(label)),
|
||||
Role::Copy => PredefinedMenuItem::copy(Some(label)),
|
||||
Role::Paste => PredefinedMenuItem::paste(Some(label)),
|
||||
Role::Undo => PredefinedMenuItem::undo(Some(label)),
|
||||
Role::Redo => PredefinedMenuItem::redo(Some(label)),
|
||||
};
|
||||
parent.append(&item)
|
||||
}
|
||||
|
||||
@@ -720,27 +720,17 @@ mod tests {
|
||||
/// issue is fixed; the test fails on a row that is no longer needed.
|
||||
#[rustfmt::skip]
|
||||
const KNOWN_NARROWER: &[(&str, &str, u32)] = &[
|
||||
("ec.blur.gaussian", "blurriness", 3460),
|
||||
("ec.blur.fastbox", "radius", 3461),
|
||||
("ec.blur.channel", "redBlurriness", 3462),
|
||||
("ec.blur.channel", "greenBlurriness", 3462),
|
||||
("ec.blur.channel", "blueBlurriness", 3462),
|
||||
("ec.blur.channel", "alphaBlurriness", 3462),
|
||||
("ec.obsolete.gaussianlegacy", "blurriness", 3463),
|
||||
("ec.perspective.dropshadow", "softness", 3464),
|
||||
("ec.blur.compound", "maximumBlur", 3465),
|
||||
("ec.blur.sharpen", "amount", 3466),
|
||||
("ec.blur.radial", "amount", 3467),
|
||||
("ec.blur.ccradial", "amount", 3468),
|
||||
("ec.distort.turbulentdisplace", "amount", 3469),
|
||||
("ec.time.pixelmotionblur", "shutterAngle", 3481),
|
||||
("ec.time.pixelmotionblur", "shutterSamples", 3482),
|
||||
("ec.noise.fractal", "subSettings/subInfluence", 3485),
|
||||
("ec.noise.fractal", "subSettings/subScaling", 3486),
|
||||
("ec.distort.ccpowerpin", "expandTop", 3492),
|
||||
("ec.distort.ccpowerpin", "expandLeft", 3492),
|
||||
("ec.distort.ccpowerpin", "expandRight", 3492),
|
||||
("ec.distort.ccpowerpin", "expandBottom", 3492),
|
||||
];
|
||||
|
||||
/// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from.
|
||||
|
||||
@@ -147,7 +147,7 @@ pub fn effects_markdown() -> String {
|
||||
- **Status**: {} implemented in full, {partial} partial (what is missing is listed).\n\n",
|
||||
r.len() - partial
|
||||
));
|
||||
s.push_str("Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`).\n\n");
|
||||
s.push_str("Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`). A parameter that was renamed keeps its old name working in expressions of older projects: `effect(\"CC Ball Action\")(\"Instability State\")` still reads Scatter Motion.\n\n");
|
||||
for cat in CATEGORIES {
|
||||
let list: Vec<_> = r.iter().filter(|e| e.category == *cat).collect();
|
||||
if list.is_empty() {
|
||||
|
||||
@@ -85,11 +85,24 @@ const TURBULENT_PINNING: [&str; 15] = [
|
||||
"Pin Bottom Locked",
|
||||
];
|
||||
|
||||
/// The largest Amount, in buffer pixels, Turbulent Displace displaces by: 2^24, exact in f32.
|
||||
/// Only an expression gets past the -10000..10000 hard range. At this bound nearly every sample
|
||||
/// already lands far outside any buffer, and the padding and the CPU and GPU samplers' integer
|
||||
/// pixel positions (the gradient kinds move up to 2.5 × Amount) stay in range.
|
||||
const TURBULENT_MAX_AMOUNT_PX: f64 = 16_777_216.0;
|
||||
|
||||
/// Turbulent Displace's Amount at `scale`, in buffer pixels, bounded to
|
||||
/// ±[`TURBULENT_MAX_AMOUNT_PX`]; `None` when nothing moves (zero, or not a number). Shared with
|
||||
/// the GPU path.
|
||||
pub fn turbulent_amount_px(ctx: &EffectCtx, scale: f64) -> Option<f64> {
|
||||
let amount = ctx.params.f("amount") * scale;
|
||||
(amount.abs() >= 1e-9).then(|| amount.clamp(-TURBULENT_MAX_AMOUNT_PX, TURBULENT_MAX_AMOUNT_PX))
|
||||
}
|
||||
|
||||
fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let amount = ctx.params.f("amount") * b.scale;
|
||||
if amount.abs() < 1e-9 {
|
||||
let Some(amount) = turbulent_amount_px(ctx, b.scale) else {
|
||||
return b;
|
||||
}
|
||||
};
|
||||
// TURBULENT_KINDS order: the "Smoother" variants (3, 4, 5) use a gentler octave falloff.
|
||||
let kind = ctx.params.e("displacement");
|
||||
let size = (ctx.params.f("size") * b.scale).max(1.0);
|
||||
@@ -110,6 +123,11 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let falloff = if (3..=5).contains(&kind) { 0.3 } else { 0.5 };
|
||||
let (lx, ly, lw, lh) = layer_rect(ctx, &b);
|
||||
let edge = (lw.min(lh) * if locked { 0.25 } else { 0.1 }).max(1.0);
|
||||
// Locked: samples stay between the outermost pixel centres, or at the centre of a layer under
|
||||
// a pixel across (a reduced resolution). Its bounds may still differ by rounding, so the
|
||||
// clamp is max/min, which `f64::clamp` would panic on.
|
||||
let (ix, iy) = (0.5f64.min(lw * 0.5), 0.5f64.min(lh * 0.5));
|
||||
let lock = (lx + ix, lx + lw - ix, ly + iy, ly + lh - iy);
|
||||
let seed = (ctx.seed ^ 0x7d15).wrapping_add((ctx.params.f("evolutionOptions/randomSeed") as i64 as u32).wrapping_mul(0x9e37_79b9));
|
||||
let n = |u: f64, v: f64, s: u32| {
|
||||
let s = seed.wrapping_add(s);
|
||||
@@ -156,7 +174,7 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
};
|
||||
let (sx, sy) = (x + dx * k, y + dy * k);
|
||||
if locked {
|
||||
return Some((sx.clamp(lx + 0.5, lx + lw - 0.5), sy.clamp(ly + 0.5, ly + lh - 0.5)));
|
||||
return Some((sx.max(lock.0).min(lock.1), sy.max(lock.2).min(lock.3)));
|
||||
}
|
||||
Some((sx, sy))
|
||||
});
|
||||
@@ -736,7 +754,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"Turbulent Displace",
|
||||
vec![
|
||||
p("displacement", "Displacement", Value::Enum(0), popup(&TURBULENT_KINDS)),
|
||||
p("amount", "Amount", num(50.0), slider(-1000.0, 1000.0, -200.0, 200.0, 1)),
|
||||
p("amount", "Amount", num(50.0), slider(-10000.0, 10000.0, -200.0, 200.0, 1)),
|
||||
p("size", "Size", num(100.0), slider(2.0, 4000.0, 2.0, 400.0, 1)),
|
||||
p("offset", "Offset (Turbulence)", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("complexity", "Complexity", num(1.0), slider(1.0, 10.0, 1.0, 10.0, 1)),
|
||||
@@ -1010,6 +1028,75 @@ mod tests {
|
||||
assert!(max_diff(&run("ec.distort.turbulentdisplace", &[], img.clone()).img, &img) > 1e-3);
|
||||
}
|
||||
|
||||
/// #3469: Amount's hard range is After Effects' recorded valid range, -10000..10000; the
|
||||
/// slider keeps its -200..200 scrub range.
|
||||
#[test]
|
||||
fn turbulent_displace_amount_takes_the_after_effects_range() {
|
||||
let spec = crate::find("ec.distort.turbulentdisplace").unwrap();
|
||||
let amount = spec.params.iter().find(|p| p.id == "amount").unwrap();
|
||||
let ParamUi::Slider { min, max, slider_min, slider_max, .. } = amount.ui else { panic!("{:?}", amount.ui) };
|
||||
assert_eq!((min, max, slider_min, slider_max), (-10000.0, 10000.0, -200.0, 200.0));
|
||||
}
|
||||
|
||||
/// #3469: at either end of Amount's range, with every displacement kind, resized or not and
|
||||
/// pinned or not, the output stays finite, in its alpha range and within the padding budget.
|
||||
#[test]
|
||||
fn turbulent_displace_extreme_amounts_stay_finite_and_bounded() {
|
||||
let img = test_img(32, 24);
|
||||
// Resize Layer grows the buffer to the padding budget (16 Mpx here), so it runs with two
|
||||
// kinds; the rest stay layer-sized.
|
||||
let cases = (0..9).flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 8, 0.0)]).chain([(0, 3, 1.0), (4, 14, 1.0)]);
|
||||
for amount in [-10000.0, 10000.0] {
|
||||
for (kind, pin, resize) in cases.clone() {
|
||||
let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))];
|
||||
let o = run("ec.distort.turbulentdisplace", &set, img.clone());
|
||||
let what = format!("amount {amount} kind {kind} pinning {pin} resize {resize}");
|
||||
assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite()) && (0.0..=1.0 + 1e-5).contains(&p[3])), "{what}");
|
||||
let area = u64::from(o.img.width) * u64::from(o.img.height);
|
||||
assert!(area <= 16_777_216, "{what}: {}x{}", o.img.width, o.img.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3469: an Amount past the hard range, which only an expression produces, renders without
|
||||
/// overflowing the padding or the sampler's pixel positions and stays finite (a plain, a
|
||||
/// gradient and the cross kind; unpinned, pinned and locked); one that is not a number leaves
|
||||
/// the layer as it is.
|
||||
#[test]
|
||||
fn turbulent_displace_unbounded_amounts_do_not_crash() {
|
||||
let img = test_img(32, 24);
|
||||
let cases = [0, 1, 8].into_iter().flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 11, 0.0)]).chain([(0, 1, 1.0)]);
|
||||
for amount in [1e12, -1e300, f64::MAX, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
for (kind, pin, resize) in cases.clone() {
|
||||
let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))];
|
||||
let o = run("ec.distort.turbulentdisplace", &set, img.clone());
|
||||
assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} kind {kind} pinning {pin} resize {resize}");
|
||||
}
|
||||
}
|
||||
for resize in [0.0, 1.0] {
|
||||
assert_eq!(run("ec.distort.turbulentdisplace", &[("amount", num(f64::NAN)), ("resizeLayer", num(resize))], img.clone()).img, img);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3469: a locked pinning on a layer under a buffer pixel across (a 1-pixel layer at half or
|
||||
/// third resolution, anywhere in the buffer) keeps samples inside it without its rounded
|
||||
/// bounds crossing, at any Amount.
|
||||
#[test]
|
||||
fn turbulent_displace_locked_pinning_on_a_subpixel_layer_does_not_crash() {
|
||||
let spec = crate::find("ec.distort.turbulentdisplace").unwrap();
|
||||
for amount in [-10000.0, 50.0, 10000.0] {
|
||||
let mut params = Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
params.values.insert("amount".into(), num(amount));
|
||||
params.values.insert("pinning".into(), Value::Enum(8));
|
||||
for (size, scale, offset) in [(1.0, 0.5, 0.0), (1.0, 1.0 / 3.0, -8.0), (1.0, 1.0 / 3.0, 7.0), (0.9, 1.0, -8.0), (f64::NAN, 1.0, 0.0)] {
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [size, size], seed: 3, adjustment: false, env: Default::default() };
|
||||
let o = crate::apply(spec, &ctx, Buf { img: test_img(2, 2), offset: [offset, offset], scale });
|
||||
// A layer size that is not a number only has to render without panicking.
|
||||
assert!(size.is_nan() || o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} {size} {scale} {offset}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn griddler_default_is_identity() {
|
||||
let img = test_img(32, 24);
|
||||
|
||||
@@ -955,10 +955,12 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("bottomRight", "Bottom Right", pt(1.0, 1.0), ParamUi::Point),
|
||||
p("perspective", "Perspective", num(100.0), pct()),
|
||||
p("unstretch", "Unstretch", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("expandTop", "Top", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandLeft", "Left", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandRight", "Right", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandBottom", "Bottom", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
|
||||
// Expansion: percent of the layer size each source edge moves out (After Effects'
|
||||
// valid range is -200..200; the maximum stays at 1000 so existing values are kept).
|
||||
p("expandTop", "Top", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandLeft", "Left", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandRight", "Right", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("expandBottom", "Bottom", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
|
||||
],
|
||||
cc_power_pin,
|
||||
),
|
||||
|
||||
@@ -250,6 +250,57 @@ fn power_pin_unstretch_expands_pinned_region() {
|
||||
assert!(maxd(&id.img, &im) < 1e-4);
|
||||
}
|
||||
|
||||
/// #3492: an Expansion side moves that edge of the source rectangle by a percent of the layer
|
||||
/// size. When two opposite sides add up to less than -100 % the edges cross and the rectangle
|
||||
/// flips: Top -200 and Bottom -100 take rows 40 down to 0 of a 20-row layer, a mirrored copy
|
||||
/// squeezed into the bottom half (the top half samples below the layer and is transparent).
|
||||
/// -100 for both (the most the old minimum allowed) mirrors the whole layer.
|
||||
#[test]
|
||||
fn power_pin_crossed_expansion_flips_the_source() {
|
||||
let im = img(20, 20);
|
||||
let o = run("ec.distort.ccpowerpin", &[("expandTop", num(-200.0)), ("expandBottom", num(-100.0))], im.clone(), &[]);
|
||||
assert_eq!((o.img.width, o.img.height), (20, 20));
|
||||
// Output row 15: v = 15.5 / 20, source y = 40 - 40 v = 9 (between rows 8 and 9).
|
||||
let px = o.img.get(10, 15);
|
||||
assert!((px[1] - 8.5 / 20.0).abs() < 1e-3, "{px:?}");
|
||||
assert_eq!(o.img.get(10, 5)[3], 0.0);
|
||||
let both = run("ec.distort.ccpowerpin", &[("expandTop", num(-100.0)), ("expandBottom", num(-100.0))], im.clone(), &[]);
|
||||
// Source y = 20 - 20 v = 4.5, row 4's centre.
|
||||
let px = both.img.get(10, 15);
|
||||
assert!((px[1] - 4.0 / 20.0).abs() < 1e-3, "{px:?}");
|
||||
}
|
||||
|
||||
/// #3492: the buffer is sized by the pins alone, and Expansions at the ends of -200..1000 render
|
||||
/// finite images: all sides at either end, flipped sources, a zero-size source (Top -50, Bottom
|
||||
/// -50), and Unstretch, which divides by the source size (a zero size renders transparent).
|
||||
#[test]
|
||||
fn power_pin_is_finite_at_the_expansion_extremes() {
|
||||
let im = img(24, 16);
|
||||
let pins = [("topLeft", pt(3.0, -4.0)), ("topRight", pt(26.0, 2.0)), ("bottomRight", pt(20.0, 18.0)), ("bottomLeft", pt(-2.0, 14.0))];
|
||||
let sides = ["expandTop", "expandLeft", "expandRight", "expandBottom"];
|
||||
let cases: &[[f64; 4]] =
|
||||
&[[-200.0; 4], [1000.0; 4], [-50.0, 0.0, 0.0, -50.0], [0.0, -200.0, -200.0, 0.0], [-200.0, 1000.0, -200.0, 1000.0], [-100.0, -150.0, 50.0, -200.0]];
|
||||
for unstretch in [false, true] {
|
||||
for perspective in [100.0, 40.0] {
|
||||
let mut base: Vec<(&str, Value)> = pins.to_vec();
|
||||
base.push(("unstretch", Value::Bool(unstretch)));
|
||||
base.push(("perspective", num(perspective)));
|
||||
let size = |o: &Buf| (o.img.width, o.img.height);
|
||||
let neutral = size(&run("ec.distort.ccpowerpin", &base, im.clone(), &[]));
|
||||
for ex in cases {
|
||||
let mut set = base.clone();
|
||||
set.extend(sides.iter().zip(ex).map(|(s, v)| (*s, num(*v))));
|
||||
let o = run("ec.distort.ccpowerpin", &set, im.clone(), &[]);
|
||||
let at = format!("{ex:?} unstretch {unstretch} perspective {perspective}");
|
||||
assert_eq!(size(&o), neutral, "{at}");
|
||||
for p in &o.img.data {
|
||||
assert!(p.iter().all(|c| c.is_finite()) && (0.0..=1.0).contains(&p[3]), "{at}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_opens_a_gap() {
|
||||
let im = img(40, 30);
|
||||
|
||||
@@ -84,7 +84,7 @@ pub use color_fx::{COLORAMA_PRESETS, ColoramaPalette};
|
||||
pub use color2::{Curve, auto_correct_settings, color_link_mode, color_link_sample, equalize_tables, luma_clip_points, shadow_highlight_amounts};
|
||||
pub use color3::OffsetCurve;
|
||||
pub use distort::{transform_grow, transform_matrix_px, transform_shutter};
|
||||
pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh};
|
||||
pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh, turbulent_amount_px};
|
||||
pub use distort3::{RESHAPE_POINTS, ReshapeSetup, SmearSetup, cc_smear_pad, reshape_setup, smear_setup, warp_inverse_map};
|
||||
pub use distort4::liquify_mesh;
|
||||
use effectcraft_keyframe::Value;
|
||||
@@ -92,8 +92,8 @@ use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
|
||||
pub use effectcraft_raster::{AuxChannels, Image};
|
||||
pub use misc::{
|
||||
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, radial_wipe_sigma,
|
||||
radial_wipe_wedge, venetian_cover, venetian_origin,
|
||||
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, drop_shadow_pad, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma,
|
||||
radial_wipe_sigma, radial_wipe_wedge, venetian_cover, venetian_origin,
|
||||
};
|
||||
pub use sim::particle_state;
|
||||
pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state};
|
||||
@@ -112,7 +112,7 @@ pub use transition::{GridWipe, place_layer};
|
||||
// effectcraft-gpu fx_noise.
|
||||
pub use keying2::{InnerOuterPlan, inner_outer_plan};
|
||||
pub use noise::remove_grain_level;
|
||||
pub use noise3::{FractalGpu, NOISE_CELL, fractal_gpu};
|
||||
pub use noise3::{FractalGpu, NOISE_CELL, OCTAVE_SCALE_MAX, fractal_gpu, sub_scaling_ratio};
|
||||
pub use stylize3::{BumpLight, HexTile, bump_layer_id};
|
||||
pub use textfx::{TextLayer, text_layer};
|
||||
pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time, time_frames, timewarp_crop, timewarp_plan};
|
||||
|
||||
@@ -44,6 +44,9 @@ pub const PARAM_ID_ALIASES: &[(&str, &str, &str)] = &[
|
||||
("ec.key.innerouter", "additionalBackground", "additionalBackground/background1"),
|
||||
// Generate: Radio Waves' growth speed was called Velocity; Velocity now moves the wave.
|
||||
("ec.generate.radiowaves", "velocity", "waveMotion/expansion"),
|
||||
// Simulation: CC Ball Action's Instability State is treated as the control After Effects
|
||||
// 24.2 calls Scatter Motion (#3197; an assumption: 24.2 shows no Instability State).
|
||||
("ec.sim.ccballaction", "instabilityState", "scatterMotion"),
|
||||
];
|
||||
|
||||
/// Popup option labels renamed since they were first saved:
|
||||
@@ -192,6 +195,14 @@ fn take_at(g: &mut PropGroup, id: &str) -> Option<Property> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The position of the property at spec id `id` (`a/b/param`) among its siblings.
|
||||
fn index_at(g: &PropGroup, id: &str) -> Option<usize> {
|
||||
match id.split_once('/') {
|
||||
None => g.children.iter().position(|c| matches!(c, Node::Prop(p) if p.match_id == id)),
|
||||
Some((first, rest)) => index_at(g.sub(first)?, rest),
|
||||
}
|
||||
}
|
||||
|
||||
fn prop_at<'a>(g: &'a mut PropGroup, id: &str) -> Option<&'a mut Property> {
|
||||
match id.split_once('/') {
|
||||
None => g.get_mut(id),
|
||||
@@ -279,6 +290,12 @@ pub fn upgrade_instance(spec: &EffectSpec, g: &mut PropGroup, ids: &mut Ids, lay
|
||||
// before it moved into a twirl-down group.
|
||||
let found = prop_at(g, ps.id).is_some();
|
||||
if !found {
|
||||
// A parameter renamed within its group keeps its place, so expressions that address
|
||||
// it by index still read it.
|
||||
let slot = PARAM_ID_ALIASES
|
||||
.iter()
|
||||
.filter(|(e, old, new)| *e == spec.id && *new == ps.id && old.rsplit_once('/').map(|(p, _)| p) == new.rsplit_once('/').map(|(p, _)| p))
|
||||
.find_map(|(_, old, _)| index_at(g, old));
|
||||
let moved = PARAM_ID_ALIASES.iter().filter(|(e, _, new)| *e == spec.id && *new == ps.id).find_map(|(_, old, _)| take_at(g, old)).or_else(|| {
|
||||
let leaf = ps.id.rsplit('/').next().unwrap_or(ps.id);
|
||||
// Not when the top-level leaf is an old id of another parameter (Radio
|
||||
@@ -300,9 +317,13 @@ pub fn upgrade_instance(spec: &EffectSpec, g: &mut PropGroup, ids: &mut Ids, lay
|
||||
pr
|
||||
}
|
||||
};
|
||||
let at = |sub: &mut PropGroup| match slot {
|
||||
Some(i) if i <= sub.children.len() => sub.children.insert(i, pr.into()),
|
||||
_ => sub.children.push(pr.into()),
|
||||
};
|
||||
match path.and_then(|path| group_at(g, ids, path)) {
|
||||
Some(sub) => sub.children.push(pr.into()),
|
||||
None => g.children.push(pr.into()),
|
||||
Some(sub) => at(sub),
|
||||
None => at(g),
|
||||
}
|
||||
}
|
||||
if let Some(pr) = prop_at(g, ps.id) {
|
||||
@@ -584,6 +605,27 @@ mod tests {
|
||||
assert_eq!((&pr.ui, &pr.value), (&ParamUi::Point, &Value::Vec2([20.0, -5.0])));
|
||||
}
|
||||
|
||||
/// #3197 review: an old CC Ball Action saved Instability State as its 8th property; renamed to
|
||||
/// Scatter Motion it keeps that place, so an expression that reads `effect(..)(8)` still gets
|
||||
/// the same control (new controls are appended after it).
|
||||
#[test]
|
||||
fn upgrade_renames_a_param_in_place_and_keeps_its_index() {
|
||||
let spec = find("ec.sim.ccballaction").unwrap();
|
||||
let mut next = 1;
|
||||
let mut g = instantiate(spec, &mut Ids(&mut next), "Ball Grid", [100.0, 50.0]);
|
||||
// The layout an earlier version saved: eight parameters, Instability State last.
|
||||
let old = ["scatter", "rotationAxis", "rotation", "twistProperty", "twistAngle", "gridSpacing", "ballSize", "scatterMotion"];
|
||||
let mut kept: Vec<Property> = old.iter().map(|id| take_prop(&mut g, id).unwrap()).collect();
|
||||
g.children.clear();
|
||||
kept[7].match_id = "instabilityState".into();
|
||||
kept[7].value = Value::Scalar(33.0);
|
||||
g.children.extend(kept.into_iter().map(Node::from));
|
||||
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), [100.0, 50.0]));
|
||||
let ids: Vec<&str> = g.children.iter().take(8).map(|c| c.match_id()).collect();
|
||||
assert_eq!(ids, ["scatter", "rotationAxis", "rotation", "twistProperty", "twistAngle", "gridSpacing", "ballSize", "scatterMotion"]);
|
||||
assert_eq!(g.get("scatterMotion").unwrap().value, Value::Scalar(33.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_moves_params_into_twirl_down_groups() {
|
||||
let spec = find(crate::warp_stab::ID).unwrap();
|
||||
|
||||
+216
-16
@@ -3,7 +3,7 @@
|
||||
use effectcraft_color::luminance;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, gaussian_blur, hash_noise};
|
||||
use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded_at, hash_noise};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
|
||||
@@ -283,6 +283,12 @@ fn glow(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
b
|
||||
}
|
||||
|
||||
/// The margin Drop Shadow asks for around a layer: its Distance and its blur's reach (three
|
||||
/// boxes of radius about σ = Softness / 2), both in buffer pixels. Shared with the GPU path.
|
||||
pub fn drop_shadow_pad(dist: f64, soft: f64) -> u32 {
|
||||
((dist + soft * 1.5).ceil() as u32).saturating_add(2)
|
||||
}
|
||||
|
||||
fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let color = ctx.params.color("color");
|
||||
let opacity = ctx.params.f("opacity") as f32 / 100.0;
|
||||
@@ -290,22 +296,41 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let dist = ctx.params.f("distance") * b.scale;
|
||||
let soft = ctx.params.f("softness") * b.scale;
|
||||
let only = ctx.params.b("shadowOnly");
|
||||
let pad = (dist + soft * 1.5).ceil() as u32 + 2;
|
||||
let pad = drop_shadow_pad(dist, soft);
|
||||
// Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a
|
||||
// large Softness (After Effects' range reaches 30000, #3464); the shadow is then blurred
|
||||
// before it is moved, as if the buffer went on with transparency, rather than dropping what
|
||||
// the move or the blur takes past the buffer's edge, which would leave it far too faint or
|
||||
// gone. An adjustment layer's buffer is the composition, as before.
|
||||
let mut holds_blur = true;
|
||||
if !ctx.adjustment {
|
||||
let (w0, h0) = (b.img.width, b.img.height);
|
||||
b.pad(pad);
|
||||
let need = pad.saturating_mul(2);
|
||||
holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need;
|
||||
}
|
||||
let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist);
|
||||
let mut sh = Image::new(b.img.width, b.img.height);
|
||||
let src = &b.img;
|
||||
sh.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3];
|
||||
*px = [color[0] * a, color[1] * a, color[2] * a, a];
|
||||
}
|
||||
});
|
||||
if soft > 0.0 {
|
||||
sh = gaussian_blur(&sh, soft / 2.0, soft / 2.0, false);
|
||||
}
|
||||
let shadow = |sh: &mut Image, (dx, dy): (f64, f64)| {
|
||||
sh.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3];
|
||||
*px = [color[0] * a, color[1] * a, color[2] * a, a];
|
||||
}
|
||||
});
|
||||
};
|
||||
let mut sh = if soft > 0.0 && !holds_blur {
|
||||
// Only the fraction of the move is sampled (into one more column and row); the blur
|
||||
// moves the rest.
|
||||
let (ix, iy) = (dx.floor(), dy.floor());
|
||||
let mut near = Image::new(src.width.saturating_add(1), src.height.saturating_add(1));
|
||||
shadow(&mut near, (dx - ix, dy - iy));
|
||||
gaussian_blur_unbounded_at(&near, soft / 2.0, soft / 2.0, [ix as i64, iy as i64], src.width, src.height)
|
||||
} else {
|
||||
let mut sh = Image::new(src.width, src.height);
|
||||
shadow(&mut sh, (dx, dy));
|
||||
if soft > 0.0 { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { sh }
|
||||
};
|
||||
if !only {
|
||||
sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| {
|
||||
let k = 1.0 - o[3];
|
||||
@@ -756,7 +781,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"Gaussian Blur",
|
||||
"Blur & Sharpen",
|
||||
vec![
|
||||
p("blurriness", "Blurriness", num(0.0), slider(0.0, 3000.0, 0.0, 50.0, 1)),
|
||||
p("blurriness", "Blurriness", num(0.0), slider(0.0, 30000.0, 0.0, 50.0, 1)),
|
||||
p("dimensions", "Blur Dimensions", Value::Enum(0), dims()),
|
||||
p("repeatEdge", "Repeat Edge Pixels", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
@@ -786,7 +811,8 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"Radial Blur",
|
||||
"Blur & Sharpen",
|
||||
vec![
|
||||
p("amount", "Amount", num(10.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
// After Effects accepts 0..1000; its slider shows 0..100 (#3467).
|
||||
p("amount", "Amount", num(10.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("center", "Center", Value::Vec2([0.5, 0.5]), ParamUi::Point),
|
||||
p("type", "Type", Value::Enum(0), popup(&["Spin", "Zoom"])),
|
||||
// Our blur is always fully anti-aliased; the choice is kept for compatibility.
|
||||
@@ -794,7 +820,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
],
|
||||
radial,
|
||||
),
|
||||
spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 0))], sharpen),
|
||||
spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 4000.0, 0.0, 100.0, 0))], sharpen),
|
||||
spec(
|
||||
"ec.blur.unsharp",
|
||||
"Unsharp Mask",
|
||||
@@ -871,7 +897,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("opacity", "Opacity", num(50.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
|
||||
p("direction", "Direction", num(135.0), ParamUi::Angle),
|
||||
p("distance", "Distance", num(5.0), slider(0.0, 32000.0, 0.0, 120.0, 1)),
|
||||
p("softness", "Softness", num(0.0), slider(0.0, 1000.0, 0.0, 250.0, 1)),
|
||||
p("softness", "Softness", num(0.0), slider(0.0, 30000.0, 0.0, 250.0, 1)),
|
||||
p("shadowOnly", "Shadow Only", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
drop_shadow,
|
||||
@@ -1036,6 +1062,134 @@ mod tests {
|
||||
assert_ne!(row(2.0), row(2.4));
|
||||
}
|
||||
|
||||
/// #3464: Softness takes After Effects' valid range, 0..30000; the slider still shows 0..250.
|
||||
#[test]
|
||||
fn drop_shadow_softness_takes_the_after_effects_range() {
|
||||
let spec = crate::find("ec.perspective.dropshadow").unwrap();
|
||||
let ui = &spec.params.iter().find(|p| p.id == "softness").unwrap().ui;
|
||||
assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1));
|
||||
}
|
||||
|
||||
/// #3464: a Softness far past the range (an expression can set one) used to overflow the
|
||||
/// padding's `u32` (a panic in debug builds). It renders, finite.
|
||||
#[test]
|
||||
fn drop_shadow_takes_a_huge_softness() {
|
||||
for softness in [1e12, f64::INFINITY] {
|
||||
let layer = effectcraft_raster::Image::filled(8, 8, [1.0, 1.0, 1.0, 1.0]);
|
||||
let out = run_fx("ec.perspective.dropshadow", &[("softness", num(softness))], layer, 0.0, EffectEnv::default());
|
||||
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3464: with the margin cut, a Distance that takes the whole layer past the buffer's edge
|
||||
/// still leaves the shadow's blur inside it. A 64 × 48 layer moved 3000 px right, Softness
|
||||
/// 8000: at the layer's centre the shadow is the Gaussian's share there (it was 0 when the
|
||||
/// layer was moved out of the buffer before the blur).
|
||||
#[test]
|
||||
fn drop_shadow_moved_past_a_cut_margin_keeps_its_blur() {
|
||||
let (w, h, dist, softness) = (64u32, 48u32, 3000.0, 8000.0);
|
||||
let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]);
|
||||
let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(dist)), ("direction", num(90.0)), ("shadowOnly", Value::Bool(true))];
|
||||
let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default());
|
||||
assert!(out.offset[0] + f64::from(w) + dist > f64::from(out.img.width), "the move takes the layer past the buffer");
|
||||
let sigma = softness / 2.0;
|
||||
// The Gaussian's share of a `len`-pixel side, at `d` pixels from its centre.
|
||||
let share = |len: u32, d: f64| {
|
||||
let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0 + d) / sigma).powi(2) / 2.0).exp()).sum();
|
||||
sum / (sigma * (2.0 * std::f64::consts::PI).sqrt())
|
||||
};
|
||||
let want = share(w, dist) * share(h, 0.0);
|
||||
let at = |v: f64, half: u32| (v + f64::from(half)) as i64;
|
||||
let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]);
|
||||
assert!((0.85..1.1).contains(&(got / want)), "centre alpha {got}, Gaussian {want}");
|
||||
}
|
||||
|
||||
/// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2)
|
||||
/// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share
|
||||
/// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the
|
||||
/// boxes spread past the buffer left it at 0.11 of that at 8000.
|
||||
#[test]
|
||||
fn drop_shadow_keeps_its_blur_past_the_padding_budget() {
|
||||
let (w, h) = (64u32, 48u32);
|
||||
for softness in [500.0, 4000.0, 8000.0, 30000.0] {
|
||||
let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]);
|
||||
let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(0.0)), ("shadowOnly", Value::Bool(true))];
|
||||
let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default());
|
||||
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}");
|
||||
let sigma = softness / 2.0;
|
||||
let share = |len: u32| {
|
||||
let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0) / sigma).powi(2) / 2.0).exp()).sum();
|
||||
sum / (sigma * (2.0 * std::f64::consts::PI).sqrt())
|
||||
};
|
||||
let want = share(w) * share(h);
|
||||
let at = |v: f64, half: u32| (v + f64::from(half)) as i64;
|
||||
let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]);
|
||||
assert!((0.85..1.02).contains(&(got / want)), "softness {softness}: centre alpha {got}, Gaussian {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3460: Blurriness goes up to After Effects' 30000. There the padding stays within the
|
||||
/// effect pixel budget, every pixel stays finite, and Repeat Edge Pixels still repeats the
|
||||
/// layer's edges: a layer white on the left and black on the right blurs to an even grey.
|
||||
#[test]
|
||||
fn gaussian_blur_at_the_highest_blurriness_is_bounded() {
|
||||
for repeat in [false, true] {
|
||||
let out = run_fx("ec.blur.gaussian", &[("blurriness", num(30000.0)), ("repeatEdge", Value::Bool(repeat))], edge(), 0.0, EffectEnv::default());
|
||||
let (w, h) = (out.img.width, out.img.height);
|
||||
assert!(f64::from(w) * f64::from(h) <= crate::pixel_budget(40.0, 8.0), "repeat {repeat}: {w} x {h}");
|
||||
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "repeat {repeat}");
|
||||
if repeat {
|
||||
assert_eq!((w, h), (40, 8));
|
||||
for p in &out.img.data {
|
||||
assert!(p[..3].iter().all(|v| (v - 0.5).abs() < 0.01) && (p[3] - 1.0).abs() < 1e-4, "{p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3466: Sharpen Amount takes After Effects' valid range, 0..4000, and keeps its 0..100
|
||||
/// slider. `prop.set` and the value editors clamp to the hard range.
|
||||
#[test]
|
||||
fn sharpen_amount_takes_the_after_effects_range() {
|
||||
let spec = crate::find("ec.blur.sharpen").unwrap();
|
||||
let ui = &spec.params.iter().find(|p| p.id == "amount").unwrap().ui;
|
||||
assert!(
|
||||
matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. }
|
||||
if *min == 0.0 && *max == 4000.0 && *slider_min == 0.0 && *slider_max == 100.0),
|
||||
"{ui:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// #3466: at the new top of the range the render stays linear in Amount and finite on 32 bpc
|
||||
/// over-range input: colour moves away from the blur by Amount / 50 of the difference
|
||||
/// (2000 → 4000 doubles it), never below 0, and alpha is untouched.
|
||||
#[test]
|
||||
fn sharpen_is_linear_and_finite_up_to_amount_4000() {
|
||||
let mut img = edge();
|
||||
for y in 0..8 {
|
||||
for x in 0..20 {
|
||||
img.set(x, y, [1000.0, 1000.0, 1000.0, 1.0]);
|
||||
}
|
||||
}
|
||||
let sharpen = |a: f64| run_fx("ec.blur.sharpen", &[("amount", num(a))], img.clone(), 0.0, EffectEnv::default()).img;
|
||||
let (half, top) = (sharpen(2000.0), sharpen(4000.0));
|
||||
for y in 0..8 {
|
||||
for x in 0..40 {
|
||||
let (i, h, t) = (img.get(x, y), half.get(x, y), top.get(x, y));
|
||||
assert_eq!(t[3], i[3], "alpha at {x}");
|
||||
for c in 0..3 {
|
||||
assert!(t[c].is_finite() && t[c] >= 0.0, "({x}, {y}): {t:?}");
|
||||
if t[c] > 0.0 && h[c] > 0.0 {
|
||||
let (dh, dt) = (h[c] - i[c], t[c] - i[c]);
|
||||
assert!((dt - 2.0 * dh).abs() <= 1e-3 * dt.abs().max(1.0), "({x}, {y}): {dh} {dt}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The bright side of the edge moves 80 × its difference from the blur: far past 10 × the input.
|
||||
assert!(top.get(19, 4)[0] > 1000.0 * 10.0, "{:?}", top.get(19, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_box_blur_radius_is_continuous() {
|
||||
let row = |v| blurred_row("ec.blur.fastbox", "radius", v);
|
||||
@@ -1147,6 +1301,52 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Amount takes After Effects' valid range up to 1000 (#3467), Zoom 1000 a spread of 10.
|
||||
/// Zoom samples along the ray from the centre through the pixel, never past the centre: on a
|
||||
/// layer white left of the centre and black right of it, the right half stays black (scales
|
||||
/// below 0 sampled the white half mirrored through the centre). Both Antialiasing settings (the
|
||||
/// renderer does not read it yet; the test keeps both covered).
|
||||
#[test]
|
||||
fn radial_blur_zoom_at_the_largest_amount_stays_on_its_side_of_the_centre() {
|
||||
let mut img = effectcraft_raster::Image::filled(64, 32, [0.0, 0.0, 0.0, 1.0]);
|
||||
img.rows_mut().for_each(|(_, row)| row.iter_mut().take(32).for_each(|px| *px = [1.0, 1.0, 1.0, 1.0]));
|
||||
for aa in 0..2 {
|
||||
let vals = [("amount", num(1000.0)), ("type", Value::Enum(1)), ("center", Value::Vec2([32.5, 16.5])), ("antialiasing", Value::Enum(aa))];
|
||||
let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default());
|
||||
for y in 0..32 {
|
||||
for x in 33..64 {
|
||||
let p = o.img.get(x, y);
|
||||
assert!(p[0].abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5, "aa {aa} ({x}, {y}): {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spin and Zoom at both ends of Amount (0..1000) and both Antialiasing settings give finite
|
||||
/// colours over an opaque layer and keep it opaque (#3467). It guards the newly accepted
|
||||
/// values; it passed before the Zoom fix too.
|
||||
#[test]
|
||||
fn radial_blur_is_finite_across_the_amount_range() {
|
||||
let mut img = effectcraft_raster::Image::new(48, 40);
|
||||
img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
*px = [x as f32 / 47.0, y as f32 / 39.0, 0.5, 1.0];
|
||||
}
|
||||
});
|
||||
for ty in 0..2 {
|
||||
for aa in 0..2 {
|
||||
for amount in [0.0, 100.0, 200.0, 1000.0] {
|
||||
let vals = [("amount", num(amount)), ("type", Value::Enum(ty)), ("center", Value::Vec2([10.0, 30.0])), ("antialiasing", Value::Enum(aa))];
|
||||
let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!((o.img.width, o.img.height), (48, 40));
|
||||
for p in &o.img.data {
|
||||
assert!(p.iter().all(|v| v.is_finite()) && (p[3] - 1.0).abs() < 1e-5, "type {ty} aa {aa} amount {amount}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After Effects 2026, Venetian Blinds Completion 40, Direction 30, Width 50, Feather 5 on
|
||||
/// an opaque 480 × 270 layer: alpha (0..255) along row y = 135. The transparent band starts
|
||||
/// at the layer centre's phase, both edges are Gaussian (σ = Feather / 2).
|
||||
|
||||
+129
-26
@@ -65,6 +65,33 @@ pub const NOISE_SOFT_LINEAR: u32 = 2;
|
||||
/// correlation length), not 100 px.
|
||||
pub const NOISE_CELL: f64 = 2.0 / 3.0;
|
||||
|
||||
/// Sub Scaling (percent, After Effects' valid 10..10000) as the size ratio of each octave to the
|
||||
/// one before it. Above 1 each octave is larger than the last.
|
||||
pub fn sub_scaling_ratio(percent: f64) -> f64 {
|
||||
(percent / 100.0).clamp(0.1, 100.0)
|
||||
}
|
||||
|
||||
/// Bound on an octave's frequency and on its Perspective Offset depth (and their inverses).
|
||||
/// Unbounded, at Sub Scaling 10000 and Complexity 20 they would reach 100^±19, and Perspective
|
||||
/// Offset multiplying the offset by the depth (and by Turbulence Factor's drift) overflowed to
|
||||
/// infinity (NaN noise, #3486). Sub Scaling 10..100 never reaches the bound (10^19 at most). Both
|
||||
/// stay each other's inverse inside it, so an octave's offset in lattice cells is unchanged; at a
|
||||
/// frequency of 1e-20 an octave spans under 1e-12 cells of any layer, so it has no detail either way.
|
||||
pub const OCTAVE_SCALE_MAX: f32 = 1e20;
|
||||
|
||||
/// Bound on an octave's scaled Offset Turbulence in pixels, so a huge offset times the depth stays
|
||||
/// finite. Times a frequency of at least 1 / [`OCTAVE_SCALE_MAX`], over cells of at most about
|
||||
/// 6700 px (Scale 10000 %), it is still over 10^12 lattice cells, past where the lattice index
|
||||
/// saturates (2^31), so the output is the same.
|
||||
const OCTAVE_OFFSET_MAX: f32 = 1e36;
|
||||
|
||||
/// The next octave's (frequency, depth) from this one's, for a Sub Scaling ratio `s`.
|
||||
#[inline]
|
||||
fn next_octave(f: f32, depth: f32, s: f32) -> (f32, f32) {
|
||||
let lo = 1.0 / OCTAVE_SCALE_MAX;
|
||||
((f / s).clamp(lo, OCTAVE_SCALE_MAX), (depth * s).clamp(lo, OCTAVE_SCALE_MAX))
|
||||
}
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Noise & Grain", params, render, gpu: false, float: true }
|
||||
}
|
||||
@@ -88,7 +115,7 @@ fn params(turbulent: bool) -> Vec<ParamSpec> {
|
||||
p("transform/perspectiveOffset", "Perspective Offset", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("complexity", "Complexity", num(6.0), slider(1.0, 20.0, 1.0, 10.0, 1)),
|
||||
p("subSettings/subInfluence", "Sub Influence (%)", num(70.0), slider(0.0, 100.0, 25.0, 100.0, 1)),
|
||||
p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 100.0, 25.0, 100.0, 1)),
|
||||
p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 10000.0, 25.0, 100.0, 1)),
|
||||
];
|
||||
if !turbulent {
|
||||
v.extend([
|
||||
@@ -158,7 +185,8 @@ pub fn typed_noise(x: f32, y: f32, z: f32, seed: u32, noise_type: u32) -> f32 {
|
||||
let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32);
|
||||
let l = |a: f32, b: f32, t: f32| a + (b - a) * t;
|
||||
let slice = |dz: i32| -> f32 {
|
||||
let c = |dx: i32, dy: i32| lattice(ix + dx, iy + dy, iz + dz, seed);
|
||||
// Coordinates past the i32 range saturate; the neighbours wrap, as on the GPU (#3486).
|
||||
let c = |dx: i32, dy: i32| lattice(ix.wrapping_add(dx), iy.wrapping_add(dy), iz.wrapping_add(dz), seed);
|
||||
match noise_type {
|
||||
0 => c(0, 0),
|
||||
1 => l(l(c(0, 0), c(1, 0), tx), l(c(0, 1), c(1, 1), tx), ty),
|
||||
@@ -195,7 +223,8 @@ pub(crate) struct Fractal {
|
||||
pub perspective: bool,
|
||||
pub octaves: f32,
|
||||
pub influence: f32,
|
||||
/// Sub Scaling as a fraction (each layer is this much smaller).
|
||||
/// Sub Scaling as a size ratio ([`sub_scaling_ratio`]: each octave is this much the size of the
|
||||
/// one before).
|
||||
pub sub_scaling: f32,
|
||||
pub sub_rotation: f32,
|
||||
/// Sub Offset in pixels.
|
||||
@@ -247,7 +276,7 @@ impl Fractal {
|
||||
perspective: pr.b("transform/perspectiveOffset"),
|
||||
octaves: pr.f("complexity").clamp(1.0, 20.0) as f32,
|
||||
influence: (pr.f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0),
|
||||
sub_scaling: (pr.f("subSettings/subScaling") as f32 / 100.0).clamp(0.1, 1.0),
|
||||
sub_scaling: sub_scaling_ratio(pr.f("subSettings/subScaling")) as f32,
|
||||
sub_rotation: (pr.f("subSettings/subRotation") as f32).to_radians(),
|
||||
sub_offset: [(so[0] * b.scale) as f32, (so[1] * b.scale) as f32],
|
||||
center_subscale: pr.b("subSettings/centerSubscale"),
|
||||
@@ -274,6 +303,23 @@ impl Fractal {
|
||||
}
|
||||
}
|
||||
|
||||
/// Octave `of`'s origin in pixels, at Perspective Offset `depth`: Perspective Offset moves finer
|
||||
/// (farther) layers less; turbulence makes them drift faster. The scaled offset stays within
|
||||
/// ±[`OCTAVE_OFFSET_MAX`] (#3486).
|
||||
#[inline]
|
||||
fn octave_origin(&self, of: f32, depth: f32) -> [f32; 2] {
|
||||
let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of);
|
||||
let mut org = self.origin;
|
||||
if k != 1.0 {
|
||||
let d = |i: usize| ((self.origin[i] - self.center[i]) * k).clamp(-OCTAVE_OFFSET_MAX, OCTAVE_OFFSET_MAX);
|
||||
org = [self.center[0] + d(0), self.center[1] + d(1)];
|
||||
}
|
||||
if !self.center_subscale {
|
||||
org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of];
|
||||
}
|
||||
org
|
||||
}
|
||||
|
||||
/// Raw fractal value (before contrast / overflow) at pixel centre (x, y).
|
||||
pub(crate) fn raw(&self, x: f32, y: f32) -> f32 {
|
||||
let n_oct = self.octaves.ceil() as usize;
|
||||
@@ -284,16 +330,7 @@ impl Fractal {
|
||||
for o in 0..n_oct {
|
||||
let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 };
|
||||
let of = o as f32;
|
||||
// This layer's origin: Perspective Offset moves finer (farther) layers less;
|
||||
// turbulence makes them drift faster.
|
||||
let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of);
|
||||
let mut org = self.origin;
|
||||
if k != 1.0 {
|
||||
org = [self.center[0] + (self.origin[0] - self.center[0]) * k, self.center[1] + (self.origin[1] - self.center[1]) * k];
|
||||
}
|
||||
if !self.center_subscale {
|
||||
org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of];
|
||||
}
|
||||
let org = self.octave_origin(of, depth);
|
||||
let (dx, dy) = (x - org[0], y - org[1]);
|
||||
let (mut u, mut v) = ((dx * cr + dy * sr) / self.size[0], (-dx * sr + dy * cr) / self.size[1]);
|
||||
if self.sub_rotation != 0.0 {
|
||||
@@ -323,8 +360,7 @@ impl Fractal {
|
||||
sum += n * amp * w;
|
||||
norm += amp * w;
|
||||
amp *= self.influence;
|
||||
f /= self.sub_scaling;
|
||||
depth *= self.sub_scaling;
|
||||
(f, depth) = next_octave(f, depth, self.sub_scaling);
|
||||
}
|
||||
if self.kind == 7 { best } else { sum / norm.max(1e-6) }
|
||||
}
|
||||
@@ -376,22 +412,14 @@ pub fn fractal_gpu(ctx: &EffectCtx, offset: [f64; 2], scale: f64, turbulent: boo
|
||||
for o in 0..n_oct {
|
||||
let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 };
|
||||
let of = o as f32;
|
||||
let k = if fr.perspective { depth } else { 1.0 } * (1.0 + fr.turbulence * of);
|
||||
let mut org = fr.origin;
|
||||
if k != 1.0 {
|
||||
org = [fr.center[0] + (fr.origin[0] - fr.center[0]) * k, fr.center[1] + (fr.origin[1] - fr.center[1]) * k];
|
||||
}
|
||||
if !fr.center_subscale {
|
||||
org = [org[0] + fr.sub_offset[0] * of, org[1] + fr.sub_offset[1] * of];
|
||||
}
|
||||
let org = fr.octave_origin(of, depth);
|
||||
let (s, c) = (fr.sub_rotation * of).sin_cos();
|
||||
let evo = fr.evolution * (1.0 + fr.turbulence * of);
|
||||
let dk = if fr.kind == 6 { 0.5 + of * 0.35 } else { 1.0 };
|
||||
octaves.push([org[0], org[1], s, c, f, amp, w, evo, of * 7.31, dk]);
|
||||
norm += amp * w;
|
||||
amp *= fr.influence;
|
||||
f /= fr.sub_scaling;
|
||||
depth *= fr.sub_scaling;
|
||||
(f, depth) = next_octave(f, depth, fr.sub_scaling);
|
||||
}
|
||||
let cycle = fr.cycle.map(|c| {
|
||||
let t = fr.evolution.rem_euclid(c);
|
||||
@@ -483,6 +511,37 @@ mod tests {
|
||||
run_fx(id, vals, Image::filled(40, 24, [0.2, 0.4, 0.6, 1.0]), 0.0, EffectEnv::default()).img
|
||||
}
|
||||
|
||||
/// #3486: lattice coordinates past the i32 range (an octave's frequency at Sub Scaling 10 % and
|
||||
/// high Complexity) saturate, and their neighbours wrap instead of overflowing.
|
||||
#[test]
|
||||
fn noise_past_the_i32_range_is_finite() {
|
||||
for noise_type in [0, 1, 2, 3] {
|
||||
for (x, y) in [(1e30, -1e30), (f32::MAX, f32::MIN), (3e9, 2.5e9)] {
|
||||
let n = typed_noise(x, y, 1e12, 7, noise_type);
|
||||
assert!(n.is_finite(), "type {noise_type} at ({x}, {y}): {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3486: octave frequency and depth stay each other's inverse and finite at 20 octaves of
|
||||
/// either end of Sub Scaling, and are unchanged inside the old 10..100 range.
|
||||
#[test]
|
||||
fn octave_scales_stay_finite_and_inverse() {
|
||||
for s in [0.1f32, 0.56, 1.0, 2.0, 100.0] {
|
||||
let (mut f, mut depth, (mut f0, mut d0)) = (1.0f32, 1.0f32, (1.0f32, 1.0f32));
|
||||
for _ in 0..19 {
|
||||
(f, depth) = next_octave(f, depth, s);
|
||||
(f0, d0) = (f0 / s, d0 * s);
|
||||
let lo = 1.0 / OCTAVE_SCALE_MAX;
|
||||
assert!((lo..=OCTAVE_SCALE_MAX).contains(&f) && (lo..=OCTAVE_SCALE_MAX).contains(&depth), "{s}: {f} {depth}");
|
||||
assert!((f * depth - 1.0).abs() < 1e-3, "{s}: {f} × {depth}");
|
||||
if s <= 1.0 {
|
||||
assert_eq!((f, depth), (f0, d0), "{s}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Evolution moves the noise at a constant rate: no ease in or out within a revolution.
|
||||
#[test]
|
||||
fn evolution_is_linear() {
|
||||
@@ -658,6 +717,50 @@ mod tests {
|
||||
assert_ne!(t0, t1);
|
||||
}
|
||||
|
||||
/// #3486: Sub Scaling takes After Effects' 10..10000 for both effects (the slider still shows
|
||||
/// 25..100), and the renderer uses values above 100 instead of capping them there.
|
||||
#[test]
|
||||
fn sub_scaling_takes_the_after_effects_range() {
|
||||
for id in ["ec.noise.fractal", "ec.noise.turbulent"] {
|
||||
let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == "subSettings/subScaling").unwrap().ui;
|
||||
assert!(
|
||||
matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. }
|
||||
if *min == 10.0 && *max == 10000.0 && *slider_min == 25.0 && *slider_max == 100.0),
|
||||
"{id}: {ui:?}"
|
||||
);
|
||||
let at = |v: f64| run(id, &[("subSettings/subScaling", num(v))]);
|
||||
assert_ne!(at(100.0), at(200.0), "{id}: 200 renders as 100");
|
||||
assert_ne!(at(200.0), at(10000.0), "{id}: 10000 renders as 200");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3486: above 100 %, each octave is larger than the last, so its scale grows as Sub
|
||||
/// Scaling^octave (100^19 at Complexity 20). Perspective Offset and Turbulence Factor multiply
|
||||
/// the offset by that, which overflowed to infinity and drew NaN, also for a huge offset. At
|
||||
/// 10 % the lattice coordinates pass the i32 range, whose neighbour index overflowed.
|
||||
#[test]
|
||||
fn extreme_sub_scaling_stays_finite() {
|
||||
for id in ["ec.noise.fractal", "ec.noise.turbulent"] {
|
||||
for sub in [10.0, 100.0, 9999.0, 10000.0] {
|
||||
for (perspective, offset) in [(false, [-3000.0, 2500.0]), (true, [-3000.0, 2500.0]), (true, [1e17, -1e17])] {
|
||||
let mut vals = vec![
|
||||
("subSettings/subScaling", num(sub)),
|
||||
("complexity", num(20.0)),
|
||||
("transform/perspectiveOffset", Value::Bool(perspective)),
|
||||
("transform/offset", Value::Vec2(offset)),
|
||||
("evolution", num(200.0)),
|
||||
("blendingMode", Value::Enum(BLEND_NONE)),
|
||||
];
|
||||
if id == "ec.noise.turbulent" {
|
||||
vals.push(("evolutionOptions/turbulenceFactor", num(10.0)));
|
||||
}
|
||||
let img = run(id, &vals);
|
||||
assert!(img.data.iter().flatten().all(|c| c.is_finite()), "{id} sub {sub} perspective {perspective} offset {offset:?}: non-finite output");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Turbulent Basic Fractal Noise drawn alone at `w` × `h`.
|
||||
fn turbulent_basic(w: u32, h: u32, vals: &[(&str, Value)]) -> Image {
|
||||
let mut all = vec![("fractalType", Value::Enum(2)), ("blendingMode", Value::Enum(BLEND_NONE))];
|
||||
|
||||
@@ -38,6 +38,11 @@ pub fn parse_spi3d(text: &str) -> Option<Lut> {
|
||||
|
||||
/// Parse an Autodesk `.3dl` lattice (integers, blue fastest; an optional input-mesh line).
|
||||
pub fn parse_3dl(text: &str) -> Option<Lut> {
|
||||
parse_3dl_limited(text, MAX_LATTICE)
|
||||
}
|
||||
|
||||
/// [`parse_3dl`] with the largest accepted lattice side as a parameter, so tests can reach it.
|
||||
pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option<Lut> {
|
||||
let mut mesh: Option<Vec<f64>> = None;
|
||||
let mut rows: Vec<[f64; 3]> = vec![];
|
||||
let mut out_bits: Option<u32> = None;
|
||||
@@ -48,34 +53,39 @@ pub fn parse_3dl(text: &str) -> Option<Lut> {
|
||||
}
|
||||
if l.starts_with(|c: char| c.is_ascii_alphabetic()) {
|
||||
// "Mesh <in bits> <out bits>" (Lustre header); other keywords are ignored.
|
||||
let t: Vec<&str> = l.split_whitespace().collect();
|
||||
let t: Vec<&str> = l.split_whitespace().take(3).collect();
|
||||
if t[0].eq_ignore_ascii_case("mesh") && t.len() >= 3 {
|
||||
out_bits = t[2].parse().ok();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let v: Vec<f64> = l.split_whitespace().filter_map(|t| t.parse().ok()).collect();
|
||||
let v: Vec<f64> = l.split_whitespace().filter_map(|t| t.parse().ok()).take(max_side.max(3).saturating_add(1)).collect();
|
||||
if v.len() > 3 && mesh.is_none() && rows.is_empty() {
|
||||
// The mesh length is the lattice side: refuse one no lattice reader accepts (#3830).
|
||||
if v.len() > max_side {
|
||||
return None;
|
||||
}
|
||||
mesh = Some(v);
|
||||
} else if v.len() == 3 {
|
||||
// One spare row while no mesh is known: a 3-entry mesh reads as a data row until the
|
||||
// count tells them apart below.
|
||||
if rows.len() >= max_side.saturating_pow(3).saturating_add(usize::from(mesh.is_none())) {
|
||||
return None;
|
||||
}
|
||||
rows.push([v[0], v[1], v[2]]);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let is_cube = |k: usize| {
|
||||
let n = (k as f64).cbrt().round() as usize;
|
||||
n * n * n == k
|
||||
};
|
||||
// A 3-entry input mesh (3³ lattice) looks like a data row: tell them apart by the count.
|
||||
if mesh.is_none() && !is_cube(rows.len()) && rows.len() == 28 {
|
||||
// A 3-entry input mesh (3³ lattice) looks like a data row: 28 rows are a mesh and 27.
|
||||
if mesh.is_none() && rows.len() == 28 {
|
||||
mesh = Some(rows.remove(0).to_vec());
|
||||
}
|
||||
let n = match &mesh {
|
||||
Some(m) => m.len(),
|
||||
None => (rows.len() as f64).cbrt().round() as usize,
|
||||
};
|
||||
if n < 2 || rows.len() != n * n * n {
|
||||
if !(2..=max_side).contains(&n) || n.checked_pow(3) != Some(rows.len()) {
|
||||
return None;
|
||||
}
|
||||
let maxv = rows.iter().flat_map(|r| r.iter()).fold(0.0f64, |m, &v| m.max(v));
|
||||
@@ -92,7 +102,7 @@ pub fn parse_3dl(text: &str) -> Option<Lut> {
|
||||
Some(Lut { n1: 0, d1: vec![], n3: n, d3, dmin: [0.0; 3], dmax: [1.0; 3] })
|
||||
}
|
||||
|
||||
/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`).
|
||||
/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`, `.3dl`).
|
||||
const MAX_LATTICE: usize = 129;
|
||||
/// Most entries of a 1D table (interpolated by index, so capped like the lattices: 2²⁴).
|
||||
const MAX_1D: usize = 1 << 24;
|
||||
|
||||
@@ -547,3 +547,45 @@ fn an_ocio_transform_file_is_read_again_once_it_changes() {
|
||||
assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap()));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3dl_with_a_hostile_mesh_is_refused_without_overflow() {
|
||||
// #3830: 2 642 246³ is past usize::MAX, so cubing the mesh length overflowed.
|
||||
let huge = "0 ".repeat(2_642_246) + "\n0 0 0\n";
|
||||
assert!(parse_file(&huge, "3dl").is_none());
|
||||
// A mesh whose rows run out.
|
||||
let short = (0..17).map(|i| (i * 64).to_string()).collect::<Vec<_>>().join(" ") + "\n0 0 0\n1 1 1\n";
|
||||
assert!(parse_file(&short, "3dl").is_none());
|
||||
// A normal small table still loads.
|
||||
let mut ok = String::from("0 511 1023\n");
|
||||
for k in 0..27 {
|
||||
ok += &format!("{} {} {}\n", k * 30, k * 30, k * 30);
|
||||
}
|
||||
assert!(matches!(parse_file(&ok, "3dl"), Some(FileXform::Lut { lut, .. }) if lut.n3 == 3 && lut.d3.len() == 27));
|
||||
}
|
||||
|
||||
/// A complete `.3dl` table of side `n`, with its input mesh line or without one.
|
||||
fn table_3dl(n: usize, mesh: bool) -> String {
|
||||
let mut text = if mesh { (0..n).map(|i| (i * 1023 / (n - 1)).to_string()).collect::<Vec<_>>().join(" ") + "\n" } else { String::new() };
|
||||
for k in 0..n * n * n {
|
||||
text += &format!("{} {} {}\n", k % 1024, k % 1024, k % 1024);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3dl_lattice_is_capped_at_the_largest_side() {
|
||||
// #3830: a complete table at the cap loads, and one a side larger is refused, with or without
|
||||
// its mesh line (without one, row collection stops at the cap's volume).
|
||||
for mesh in [true, false] {
|
||||
let at = lut::parse_3dl_limited(&table_3dl(4, mesh), 4);
|
||||
assert!(at.is_some_and(|l| l.n3 == 4 && l.d3.len() == 64), "mesh {mesh}");
|
||||
assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 4).is_none(), "mesh {mesh}");
|
||||
assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 5).is_some(), "mesh {mesh}");
|
||||
}
|
||||
// A 3-entry mesh reads as a 28th row until the count separates it, and a four-value row is
|
||||
// still refused at the smallest limit.
|
||||
assert!(lut::parse_3dl_limited(&table_3dl(3, true), 3).is_some_and(|l| l.n3 == 3));
|
||||
let four = table_3dl(2, false).replacen("7 7 7", "7 7 7 7", 1);
|
||||
assert!(lut::parse_3dl_limited(&four, 2).is_none());
|
||||
}
|
||||
@@ -93,6 +93,10 @@ pub enum Shape {
|
||||
Disc,
|
||||
/// Lit sphere (upper-left light, specular).
|
||||
Sphere,
|
||||
/// CC Ball Action's ball: [`Shape::Sphere`]'s light and shine scaled by `|shade|` (1 is the
|
||||
/// sphere's look, 0 a flat disc; callers keep it finite, the GPU draws the same); a negative
|
||||
/// `shade` mirrors the light's direction (lit from the lower right).
|
||||
Ball { shade: f32 },
|
||||
/// Disc fading linearly to its rim.
|
||||
Faded,
|
||||
/// Thin ring with a highlight.
|
||||
@@ -277,6 +281,24 @@ fn sprite_shade(s: &Sprite, x: f32, y: f32) -> Option<Px> {
|
||||
rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec];
|
||||
cv
|
||||
}
|
||||
Shape::Ball { shade } => {
|
||||
let d = (dx * dx + dy * dy).sqrt();
|
||||
let cv = aa(r - d);
|
||||
if cv <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let (nx, ny) = (dx / r, dy / r);
|
||||
let nz = (1.0 - nx * nx - ny * ny).max(0.0).sqrt();
|
||||
let m = if shade < 0.0 { -1.0 } else { 1.0 };
|
||||
let (lx, ly, lz) = (-0.48 * m, -0.58 * m, 0.66);
|
||||
let diff = (nx * lx + ny * ly + nz * lz).max(0.0);
|
||||
let rz = 2.0 * diff * nz - lz;
|
||||
let st = shade.abs();
|
||||
let spec = rz.max(0.0).powi(20) * 0.6 * st;
|
||||
let k = (1.0 - st * 0.8 * (1.0 - diff)).max(0.0);
|
||||
rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec];
|
||||
cv
|
||||
}
|
||||
Shape::Bubble => {
|
||||
let d = (dx * dx + dy * dy).sqrt() / r;
|
||||
if d > 1.0 + 1.0 / r {
|
||||
|
||||
@@ -4,10 +4,91 @@ use super::{Acc, Buf, EffectCtx, IntoParallelIterator, ParallelIterator, Post, S
|
||||
|
||||
// ------------------------------------------------------------------ CC Ball Action
|
||||
|
||||
/// CC Ball Action's Coloring: how a ball takes its colour from the layer under its grid cell.
|
||||
/// An approximation: After Effects' own meaning is not published beyond "how smooth the
|
||||
/// balls look". Crisp takes the nearest pixel, Medium keeps EffectCraft's earlier smooth
|
||||
/// sample at the cell centre (for compatibility), Smooth averages 16 samples over the cell.
|
||||
pub(super) const BALL_COLORING: &[&str] = &["Crisp", "Medium", "Smooth"];
|
||||
pub(super) const BALL_COLORING_MEDIUM: u32 = 1;
|
||||
/// CC Ball Action's default Shading: the lit sphere (`Shape::Sphere`); 0 draws flat discs.
|
||||
pub(super) const BALL_SHADING_DEFAULT: f64 = -75.0;
|
||||
/// CC Ball Action's Displace Property: what pushes a ball towards (high values) or away from
|
||||
/// (low values) the camera. The option names come from public descriptions; what Radius,
|
||||
/// Diamond and Spherize compute here is an assumption pending a comparison with After Effects.
|
||||
pub(super) const BALL_DISPLACE_PROPERTIES: &[&str] = &["Red", "Green", "Blue", "Brightness", "Saturation", "RGB", "Radius", "Diamond", "Spherize"];
|
||||
pub(super) const BALL_DISPLACE_BRIGHTNESS: u32 = 3;
|
||||
|
||||
pub(super) fn ball_action(ctx: &EffectCtx, b: Buf) -> Buf {
|
||||
ball_action_plan(ctx, &b).finish(b)
|
||||
}
|
||||
|
||||
/// A parameter's number, or `default` when the instance does not carry it.
|
||||
fn f_or(ctx: &EffectCtx, id: &str, default: f64) -> f64 {
|
||||
ctx.params.values.get(id).map(|v| v.as_f64()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The layer's straight colour and alpha for the ball of the grid cell centred on (`sx`, `sy`)
|
||||
/// (buffer pixels, cell `cell` buffer pixels wide), by Coloring `coloring`.
|
||||
fn ball_color(src: &effectcraft_raster::Image, sx: f64, sy: f64, cell: f64, coloring: u32) -> ([f32; 3], f32) {
|
||||
match coloring {
|
||||
// Crisp: the pixel under the cell centre.
|
||||
0 => unpremul(src.get(sx.floor() as i64, sy.floor() as i64)),
|
||||
// Smooth: the cell's average (4 × 4 samples, premultiplied).
|
||||
2 => {
|
||||
const N: u32 = 4;
|
||||
let mut acc = [0.0f32; 4];
|
||||
for j in 0..N {
|
||||
for i in 0..N {
|
||||
let ox = (f64::from(i) + 0.5) / f64::from(N) - 0.5;
|
||||
let oy = (f64::from(j) + 0.5) / f64::from(N) - 0.5;
|
||||
let p = src.sample_bilinear(sx + ox * cell, sy + oy * cell);
|
||||
for (a, v) in acc.iter_mut().zip(p) {
|
||||
*a += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = (N * N) as f32;
|
||||
unpremul([acc[0] / n, acc[1] / n, acc[2] / n, acc[3] / n])
|
||||
}
|
||||
// Medium: a smooth sample at the cell centre.
|
||||
_ => unpremul(src.sample_bilinear(sx, sy)),
|
||||
}
|
||||
}
|
||||
|
||||
/// CC Ball Action's Displace Property `prop` (0..1) for a ball of straight colour `c` at
|
||||
/// (`gx`, `gy`) on a `lw` × `lh` layer (`maxr`: half its diagonal). Assumed meanings (not
|
||||
/// compared with After Effects yet): Radius, Diamond and Spherize are shapes that peak at the
|
||||
/// layer centre.
|
||||
fn ball_displace_value(prop: u32, c: [f32; 3], gx: f32, gy: f32, lw: f32, lh: f32, maxr: f32) -> f32 {
|
||||
let (cx, cy) = (lw * 0.5, lh * 0.5);
|
||||
let v = match prop {
|
||||
0 => c[0],
|
||||
1 => c[1],
|
||||
2 => c[2],
|
||||
// Brightness: the brightest channel (HSB brightness).
|
||||
3 => c[0].max(c[1]).max(c[2]),
|
||||
// Saturation: HSB saturation.
|
||||
4 => {
|
||||
let mx = c[0].max(c[1]).max(c[2]);
|
||||
let mn = c[0].min(c[1]).min(c[2]);
|
||||
if mx > 0.0 { (mx - mn) / mx } else { 0.0 }
|
||||
}
|
||||
// RGB: the channels' mean.
|
||||
5 => (c[0] + c[1] + c[2]) / 3.0,
|
||||
// Radius: high at the centre, low at the corners.
|
||||
6 => 1.0 - (gx - cx).hypot(gy - cy) / maxr.max(1.0),
|
||||
// Diamond: high at the centre, falling linearly to the edge midpoints' diamond.
|
||||
7 => 1.0 - ((gx - cx).abs() / cx.max(0.5) + (gy - cy).abs() / cy.max(0.5)) * 0.5,
|
||||
// Spherize: a hemisphere over the largest centred circle.
|
||||
_ => {
|
||||
let rr = cx.min(cy).max(0.5);
|
||||
let d = (gx - cx).hypot(gy - cy) / rr;
|
||||
(1.0 - d * d).max(0.0).sqrt()
|
||||
}
|
||||
};
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// CC Ball Action's balls (far to near), coloured by the layer's pixels.
|
||||
fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
|
||||
let pr = ctx.params;
|
||||
@@ -18,7 +99,29 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
|
||||
let twist = pr.f("twistAngle").to_radians();
|
||||
let spacing = pr.f("gridSpacing").max(1.0) as f32;
|
||||
let size = pr.f("ballSize") as f32 / 100.0;
|
||||
let instab = pr.f("instabilityState").to_radians() as f32;
|
||||
// Scatter Motion, treated as the renamed Instability State (an assumption: After Effects
|
||||
// 24.2 shows Scatter Motion and no Instability State): turns each ball's scatter direction.
|
||||
let instab = pr.f("scatterMotion").to_radians() as f32;
|
||||
let coloring = pr.values.get("coloring").map(|v| v.as_enum()).unwrap_or(BALL_COLORING_MEDIUM);
|
||||
let shading = f_or(ctx, "shading", BALL_SHADING_DEFAULT);
|
||||
// Shading: -75 is the lit sphere as it always was, 0 flat discs; the magnitude scales the
|
||||
// light and shine (strength 1 at 75) and the sign mirrors the light's direction (positive
|
||||
// lights the balls from the lower right). How this compares with After Effects' sign
|
||||
// (described as concave versus convex) is unverified, as is the -100..100 range.
|
||||
let shape = if shading == BALL_SHADING_DEFAULT || !shading.is_finite() {
|
||||
Shape::Sphere
|
||||
} else if shading == 0.0 {
|
||||
Shape::Disc
|
||||
} else {
|
||||
// Clamped: a huge value would reach the GPU as an infinite strength (and NaN colours).
|
||||
Shape::Ball { shade: (-shading.clamp(-100.0, 100.0) / 75.0) as f32 }
|
||||
};
|
||||
// Displace: pushes each ball along z by its Displace Property (high values towards the
|
||||
// camera, pivoting at the property's middle value); 100 moves the extremes by half the
|
||||
// layer's diagonal. Scale, direction, pivot and range are EffectCraft's own choice,
|
||||
// pending a comparison with After Effects. Clamped so huge values stay finite.
|
||||
let displace = pr.f("displace").clamp(-1000.0, 1000.0) as f32;
|
||||
let displace_prop = pr.values.get("displaceProperty").map(|v| v.as_enum()).unwrap_or(BALL_DISPLACE_BRIGHTNESS);
|
||||
let seed = ctx.seed.wrapping_mul(0x2545f491);
|
||||
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
|
||||
let s = b.scale as f32;
|
||||
@@ -43,7 +146,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
|
||||
let gx = (i % nx) as f32 * spacing + spacing * 0.5;
|
||||
let gy = (i / nx) as f32 * spacing + spacing * 0.5;
|
||||
let (sx, sy) = b.to_px([gx as f64, gy as f64]);
|
||||
let (c, a) = unpremul(src.sample_bilinear(sx, sy));
|
||||
let (c, a) = ball_color(src, sx, sy, f64::from(spacing * s), coloring);
|
||||
if a <= 0.0 || size <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
@@ -54,11 +157,16 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
|
||||
_ => crate::util::rgb3([c[0], c[1], c[2], 0.0]).iter().sum::<f32>() / 3.0,
|
||||
} as f64;
|
||||
let ang = rot + twist * tp;
|
||||
// Scatter: random 3D offsets whose direction drifts with the instability state.
|
||||
// Scatter: random 3D offsets whose direction drifts with Scatter Motion.
|
||||
let ph = h(i, 1, seed) * std::f32::consts::TAU + instab;
|
||||
let sc = scatter * h(i, 2, seed);
|
||||
let off = [(sc * ph.cos()) as f64, (sc * ph.sin()) as f64, (scatter * hs(i, 3, seed)) as f64];
|
||||
let p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]];
|
||||
let mut p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]];
|
||||
// Only when set, so Displace 0 leaves every depth (and the far-to-near order) as is.
|
||||
if displace != 0.0 && displace.is_finite() {
|
||||
let v = ball_displace_value(displace_prop, c, gx, gy, lw, lh, maxr);
|
||||
p0[2] -= f64::from(displace / 100.0 * (v - 0.5) * 2.0 * maxr);
|
||||
}
|
||||
let m = rot_axis(ax, ang);
|
||||
let q: [f64; 3] = std::array::from_fn(|k| m[k][0] * p0[0] + m[k][1] * p0[1] + m[k][2] * p0[2]);
|
||||
if d + q[2] <= d * 0.05 {
|
||||
@@ -67,7 +175,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
|
||||
let persp = d / (d + q[2]);
|
||||
let (bx, by) = b.to_px([cx + q[0] * persp, cy + q[1] * persp]);
|
||||
let r = spacing * 0.5 * size * persp as f32 * s;
|
||||
Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], Shape::Sphere)))
|
||||
Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], shape)))
|
||||
})
|
||||
.collect();
|
||||
balls.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::foam::{FOAM_TEXTURES, foam};
|
||||
use super::pixels::{ball_action, pixel_polly, scatterize};
|
||||
use super::pixels::{
|
||||
BALL_COLORING, BALL_COLORING_MEDIUM, BALL_DISPLACE_BRIGHTNESS, BALL_DISPLACE_PROPERTIES, BALL_SHADING_DEFAULT, ball_action, pixel_polly, scatterize,
|
||||
};
|
||||
use super::shatter::{CD_PROPS, CD_SOURCES, SHATTER_PATTERNS, SHATTER_TEXTURE_MODES, card_dance, shatter};
|
||||
use super::surfaces::{caustics, wave_world};
|
||||
use super::{EffectSpec, ParamUi, Value, col, num, p, pct, popup, pt, slider, spec};
|
||||
@@ -80,15 +82,22 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
spec(
|
||||
"ec.sim.ccballaction",
|
||||
"Ball Grid",
|
||||
// After Effects' order and defaults since 24.2 (#3197). Scatter Motion is treated as
|
||||
// the renamed Instability State (an assumption, `migrate::PARAM_ID_ALIASES`). The
|
||||
// Shading range is not published; -100..100 is an assumption.
|
||||
vec![
|
||||
p("gridSpacing", "Grid Spacing", num(5.0), slider(1.0, 200.0, 1.0, 50.0, 0)),
|
||||
p("ballSize", "Ball Size", num(100.0), slider(0.0, 400.0, 0.0, 200.0, 1)),
|
||||
p("coloring", "Coloring", Value::Enum(BALL_COLORING_MEDIUM), popup(BALL_COLORING)),
|
||||
p("shading", "Shading", num(BALL_SHADING_DEFAULT), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
p("scatter", "Scatter", num(0.0), slider(0.0, 2000.0, 0.0, 300.0, 1)),
|
||||
p("scatterMotion", "Scatter Motion", num(0.0), ParamUi::Angle),
|
||||
p("displace", "Displace", num(0.0), slider(-1000.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("displaceProperty", "Displace Property", Value::Enum(BALL_DISPLACE_BRIGHTNESS), popup(BALL_DISPLACE_PROPERTIES)),
|
||||
p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle),
|
||||
p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])),
|
||||
p("rotationAxis", "Rotation Axis", Value::Enum(0), popup(&["X Axis", "Y Axis", "Z Axis", "XY Axis", "XZ Axis", "YZ Axis", "XYZ Axis"])),
|
||||
p("rotation", "Rotation", num(0.0), ParamUi::Angle),
|
||||
p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])),
|
||||
p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle),
|
||||
p("gridSpacing", "Grid Spacing", num(4.0), slider(1.0, 200.0, 1.0, 50.0, 0)),
|
||||
p("ballSize", "Ball Size", num(40.0), slider(0.0, 400.0, 0.0, 200.0, 1)),
|
||||
p("instabilityState", "Instability State", num(0.0), ParamUi::Angle),
|
||||
],
|
||||
ball_action,
|
||||
),
|
||||
|
||||
@@ -46,6 +46,138 @@ fn ball_action_draws_balls() {
|
||||
assert!(sum_diff(&a, &sc) > 1.0);
|
||||
}
|
||||
|
||||
/// #3197: CC Ball Action has After Effects' controls (since 24.2), in its order, with its
|
||||
/// defaults: Coloring, Shading, Scatter Motion (formerly Instability State), Displace and
|
||||
/// Displace Property were missing.
|
||||
#[test]
|
||||
fn ball_action_has_after_effects_controls() {
|
||||
let spec = crate::find("ec.sim.ccballaction").unwrap();
|
||||
let names: Vec<&str> = spec.params.iter().map(|p| p.name).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"Grid Spacing",
|
||||
"Ball Size",
|
||||
"Coloring",
|
||||
"Shading",
|
||||
"Scatter",
|
||||
"Scatter Motion",
|
||||
"Displace",
|
||||
"Displace Property",
|
||||
"Twist Angle",
|
||||
"Twist Property",
|
||||
"Rotation Axis",
|
||||
"Rotation"
|
||||
]
|
||||
);
|
||||
let sp = |id: &str| spec.params.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("no {id}"));
|
||||
assert_eq!(sp("gridSpacing").default, num(5.0));
|
||||
assert_eq!(sp("ballSize").default, num(100.0));
|
||||
assert_eq!(sp("coloring").default, Value::Enum(1));
|
||||
assert_eq!(sp("coloring").ui, ParamUi::Popup { options: vec!["Crisp".into(), "Medium".into(), "Smooth".into()] });
|
||||
assert_eq!(sp("shading").default, num(-75.0));
|
||||
assert!(matches!(sp("shading").ui, ParamUi::Slider { min, max, .. } if min <= -100.0 && max >= 100.0));
|
||||
assert_eq!(sp("scatterMotion").default, num(0.0));
|
||||
assert_eq!(sp("scatterMotion").ui, ParamUi::Angle);
|
||||
assert_eq!(sp("displace").default, num(0.0));
|
||||
let ParamUi::Popup { options } = &sp("displaceProperty").ui else { panic!("Displace Property is a popup") };
|
||||
let Value::Enum(d) = sp("displaceProperty").default else { panic!("Displace Property defaults to an option") };
|
||||
assert_eq!(options.get(d as usize).map(String::as_str), Some("Brightness"));
|
||||
// Old projects' Instability State becomes Scatter Motion through `PARAM_ID_ALIASES`; the
|
||||
// engine test `opening_an_old_project_upgrades_effect_instances` covers every alias.
|
||||
}
|
||||
|
||||
/// #3197: the new controls at After Effects' defaults draw exactly what CC Ball Action drew
|
||||
/// before (the lit sphere, a smooth colour sample, no displacement).
|
||||
#[test]
|
||||
fn ball_action_new_controls_at_defaults_keep_the_render() {
|
||||
let base = [("ballSize", num(80.0)), ("scatter", num(6.0)), ("rotationAxis", Value::Enum(1)), ("rotation", num(25.0))];
|
||||
let a = run("ec.sim.ccballaction", &base, ramp(32, 32), 0.0);
|
||||
let mut explicit = base.to_vec();
|
||||
explicit.extend([
|
||||
("coloring", Value::Enum(1)),
|
||||
("shading", num(-75.0)),
|
||||
("scatterMotion", num(0.0)),
|
||||
("displace", num(0.0)),
|
||||
("displaceProperty", Value::Enum(3)),
|
||||
]);
|
||||
assert_eq!(a, run("ec.sim.ccballaction", &explicit, ramp(32, 32), 0.0));
|
||||
}
|
||||
|
||||
/// #3197: Shading 0 removes the built-in light: every ball is the layer's flat colour. The
|
||||
/// default (-75) shades it; a smaller magnitude shades less, a positive value lights the balls
|
||||
/// from the other side.
|
||||
#[test]
|
||||
fn ball_action_shading_zero_is_flat() {
|
||||
let c = [0.6, 0.3, 0.2, 1.0];
|
||||
let shade = |v: f64| run("ec.sim.ccballaction", &[("ballSize", num(100.0)), ("gridSpacing", num(8.0)), ("shading", num(v))], Image::filled(32, 32, c), 0.0);
|
||||
let flat = shade(0.0);
|
||||
let covered: Vec<&[f32; 4]> = flat.data.iter().filter(|p| p[3] > 0.999).collect();
|
||||
assert!(!covered.is_empty(), "balls drawn");
|
||||
for p in &covered {
|
||||
for k in 0..3 {
|
||||
assert!((p[k] / p[3] - c[k]).abs() < 1e-4, "flat colour: {p:?}");
|
||||
}
|
||||
}
|
||||
let lit = shade(-75.0);
|
||||
assert!(lit.data.iter().any(|p| p[3] > 0.999 && (0..3).any(|k| (p[k] / p[3] - c[k]).abs() > 0.05)), "the default shading lights and darkens the balls");
|
||||
let soft = shade(-30.0);
|
||||
assert!(sum_diff(&flat, &soft) > 0.1 && sum_diff(&flat, &soft) < sum_diff(&flat, &lit), "less shading, closer to flat");
|
||||
assert!(sum_diff(&shade(75.0), &lit) > 1.0, "the sign moves the light");
|
||||
}
|
||||
|
||||
/// #3197: Coloring Crisp takes the pixel under each ball's cell centre; Medium samples
|
||||
/// smoothly between pixels. Grid Spacing 4 puts the cell centres on pixel corners (with the
|
||||
/// default 5 they fall on pixel centres, where Medium's sample equals Crisp's).
|
||||
#[test]
|
||||
fn ball_action_coloring_crisp_takes_the_pixel() {
|
||||
let mut src = Image::new(32, 32);
|
||||
for y in 0..32u32 {
|
||||
for x in 0..32u32 {
|
||||
src.set(x, y, [x as f32 / 32.0, y as f32 / 32.0, ((x * 7 + y * 3) % 5) as f32 / 4.0, 1.0]);
|
||||
}
|
||||
}
|
||||
let col = |m: u32| {
|
||||
let v = [("gridSpacing", num(4.0)), ("ballSize", num(100.0)), ("shading", num(0.0)), ("coloring", Value::Enum(m))];
|
||||
run("ec.sim.ccballaction", &v, src.clone(), 0.0)
|
||||
};
|
||||
let crisp = col(0);
|
||||
// Flat, opaque balls of radius 2 centred on (4i + 2, 4j + 2): the pixel to the lower right
|
||||
// of each centre is fully covered by its ball alone.
|
||||
for j in 0..8i64 {
|
||||
for i in 0..8i64 {
|
||||
let (x, y) = (4 * i + 2, 4 * j + 2);
|
||||
let (got, want) = (crisp.get(x, y), src.get(x, y));
|
||||
assert!((0..4).all(|k| (got[k] - want[k]).abs() < 1e-5), "ball ({i}, {j}): {got:?} vs the pixel {want:?}");
|
||||
}
|
||||
}
|
||||
assert!(sum_diff(&crisp, &col(1)) > 1.0, "medium blends the pixels");
|
||||
}
|
||||
|
||||
/// #3197: a huge Shading (typed or from an expression) is clamped, so the balls stay finite.
|
||||
#[test]
|
||||
fn ball_action_huge_shading_stays_finite() {
|
||||
for v in [1e45, -1e45, f64::MAX] {
|
||||
let o = run("ec.sim.ccballaction", &[("gridSpacing", num(8.0)), ("shading", num(v))], ramp(32, 32), 0.0);
|
||||
assert!(o.data.iter().all(|p| p.iter().all(|c| c.is_finite())), "shading {v}");
|
||||
assert!(o.data.iter().any(|p| p[3] > 0.0), "shading {v}: balls drawn");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3197: Displace pushes the balls along z by the chosen property (Radius: the centre comes
|
||||
/// towards the camera and grows); 0 leaves them in the layer's plane.
|
||||
#[test]
|
||||
fn ball_action_displace_moves_balls_in_depth() {
|
||||
let flat = run("ec.sim.ccballaction", &[("ballSize", num(80.0))], ramp(32, 32), 0.0);
|
||||
let d = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0);
|
||||
assert_eq!(d, run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0));
|
||||
assert!(sum_diff(&flat, &d) > 1.0);
|
||||
for prop in 0..9 {
|
||||
let o = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(400.0)), ("displaceProperty", Value::Enum(prop))], ramp(32, 32), 0.0);
|
||||
assert!(o.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "property {prop}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_polly_breaks_after_start() {
|
||||
let v = [("forceCenter", pt(16.0, 16.0)), ("gridSpacing", num(4.0))];
|
||||
|
||||
@@ -216,8 +216,16 @@ pub struct Lut {
|
||||
pub dmax: [f32; 3],
|
||||
}
|
||||
|
||||
// Cube LUT Specification 1.0 §§6–7 permits at most 65,536 1D rows and a 256³
|
||||
// lattice. Allow their sum for combined shaper + 3D files, regardless of header order.
|
||||
const MAX_CUBE_ROWS: usize = 65_536 + 256 * 256 * 256;
|
||||
|
||||
/// Parse `.cube` text (TITLE, LUT_1D_SIZE, LUT_3D_SIZE, DOMAIN_MIN/MAX, data red-fastest).
|
||||
pub fn parse_cube(text: &str) -> Option<Lut> {
|
||||
parse_cube_limited(text, MAX_CUBE_ROWS)
|
||||
}
|
||||
|
||||
fn parse_cube_limited(text: &str, max_rows: usize) -> Option<Lut> {
|
||||
let mut lut = Lut { n1: 0, d1: vec![], n3: 0, d3: vec![], dmin: [0.0; 3], dmax: [1.0; 3] };
|
||||
let mut rows: Vec<[f32; 3]> = Vec::new();
|
||||
let three = |it: &mut std::str::SplitWhitespace| -> Option<[f32; 3]> {
|
||||
@@ -259,16 +267,27 @@ pub fn parse_cube(text: &str) -> Option<Lut> {
|
||||
lut.dmax = [hi; 3];
|
||||
}
|
||||
k if k.starts_with(|c: char| c.is_ascii_alphabetic()) => continue,
|
||||
_ => rows.push(three(&mut it)?),
|
||||
_ => {
|
||||
if rows.len() == max_rows {
|
||||
return None;
|
||||
}
|
||||
let row = three(&mut it)?;
|
||||
// Make buffer growth fallible before push can allocate.
|
||||
rows.try_reserve(1).ok()?;
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
if lut.n3 > 256 {
|
||||
return None;
|
||||
}
|
||||
let need1 = lut.n1;
|
||||
let need3 = lut.n3 * lut.n3 * lut.n3;
|
||||
if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 {
|
||||
if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) {
|
||||
return None;
|
||||
}
|
||||
lut.d1 = rows[..need1].to_vec();
|
||||
lut.d3 = rows[need1..].to_vec();
|
||||
lut.d1 = rows.get(..need1)?.to_vec();
|
||||
lut.d3 = rows.get(need1..)?.to_vec();
|
||||
Some(lut)
|
||||
}
|
||||
|
||||
@@ -571,6 +590,10 @@ mod tests {
|
||||
fn bad_cube_is_passthrough() {
|
||||
assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none());
|
||||
assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none());
|
||||
// A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`.
|
||||
assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none());
|
||||
assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none());
|
||||
assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n{}", usize::MAX, "0 0 0\n".repeat(7))).is_none());
|
||||
let img = test_img();
|
||||
let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone());
|
||||
assert_eq!(out.img, img);
|
||||
@@ -686,6 +709,28 @@ mod tests {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cube_accepts_maximum_1d_shaper_with_3d_table() {
|
||||
let text = format!("LUT_1D_SIZE 65536\nLUT_3D_SIZE 2\n{}", "0 0 0\n".repeat(65_536 + 8));
|
||||
let lut = parse_cube(&text).unwrap();
|
||||
assert_eq!(lut.d1.len(), 65_536);
|
||||
assert_eq!(lut.d3.len(), 8);
|
||||
// Keep the parser's existing tolerance for headers following data.
|
||||
let text = format!("{}LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n", "0 0 0\n".repeat(10));
|
||||
let lut = parse_cube(&text).unwrap();
|
||||
assert_eq!(lut.d1, vec![[0.0; 3]; 2]);
|
||||
assert_eq!(lut.d3, vec![[0.0; 3]; 8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cube_row_collection_is_bounded() {
|
||||
assert_eq!(MAX_CUBE_ROWS, 65_536 + 256 * 256 * 256);
|
||||
let text = "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n";
|
||||
let lut = parse_cube_limited(text, 2).unwrap();
|
||||
assert_eq!(lut.d1, vec![[0.0; 3], [1.0; 3]]);
|
||||
assert!(parse_cube_limited("LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n", 2).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_d_lut_with_domain() {
|
||||
let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap();
|
||||
|
||||
@@ -192,7 +192,7 @@ fn cases() -> Vec<(&'static str, Vec<Set>)> {
|
||||
vec![
|
||||
vec![],
|
||||
vec![("scatter", n(20.0)), ("rotationAxis", e(6)), ("rotation", n(40.0)), ("twistProperty", e(3)), ("twistAngle", n(90.0))],
|
||||
vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))],
|
||||
vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))],
|
||||
],
|
||||
),
|
||||
(
|
||||
@@ -538,26 +538,26 @@ const GOLDEN: &[(&str, u64)] = &[
|
||||
("ec.sim.particleplayground/8/32bpc/t1.5", 0xb5b7f0281f26baad),
|
||||
("ec.sim.particleplayground/8/32bpc/t0.8", 0x8b6934363ef4dcfd),
|
||||
("ec.sim.particleplayground/8/32bpc/t2.2", 0x0a31c17e8e34b9f5),
|
||||
("ec.sim.ccballaction/0/8bpc/t0.5", 0x12698ec8353be38c),
|
||||
("ec.sim.ccballaction/0/8bpc/t1.5", 0x12698ec8353be38c),
|
||||
("ec.sim.ccballaction/0/8bpc/t0.8", 0x12698ec8353be38c),
|
||||
("ec.sim.ccballaction/0/8bpc/t2.2", 0x12698ec8353be38c),
|
||||
("ec.sim.ccballaction/0/32bpc/t0.5", 0x3fb733487e120261),
|
||||
("ec.sim.ccballaction/0/32bpc/t1.5", 0x3fb733487e120261),
|
||||
("ec.sim.ccballaction/0/32bpc/t0.8", 0x3fb733487e120261),
|
||||
("ec.sim.ccballaction/0/32bpc/t2.2", 0x3fb733487e120261),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t0.5", 0x4946070917cc0945),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t1.5", 0x4946070917cc0945),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t0.8", 0x4946070917cc0945),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t2.2", 0x4946070917cc0945),
|
||||
("ec.sim.ccballaction/1/8bpc/t0.5", 0xf34b3be38a4dd468),
|
||||
("ec.sim.ccballaction/1/8bpc/t1.5", 0xf34b3be38a4dd468),
|
||||
("ec.sim.ccballaction/1/8bpc/t0.8", 0xf34b3be38a4dd468),
|
||||
("ec.sim.ccballaction/1/8bpc/t2.2", 0xf34b3be38a4dd468),
|
||||
("ec.sim.ccballaction/1/32bpc/t0.5", 0x503b7238edf2912c),
|
||||
("ec.sim.ccballaction/1/32bpc/t1.5", 0x503b7238edf2912c),
|
||||
("ec.sim.ccballaction/1/32bpc/t0.8", 0x503b7238edf2912c),
|
||||
("ec.sim.ccballaction/1/32bpc/t2.2", 0x503b7238edf2912c),
|
||||
("ec.sim.ccballaction/0/8bpc/t0.5", 0x5f7401d3d1e5a513),
|
||||
("ec.sim.ccballaction/0/8bpc/t1.5", 0x5f7401d3d1e5a513),
|
||||
("ec.sim.ccballaction/0/8bpc/t0.8", 0x5f7401d3d1e5a513),
|
||||
("ec.sim.ccballaction/0/8bpc/t2.2", 0x5f7401d3d1e5a513),
|
||||
("ec.sim.ccballaction/0/32bpc/t0.5", 0x9cf15a7756ab88ed),
|
||||
("ec.sim.ccballaction/0/32bpc/t1.5", 0x9cf15a7756ab88ed),
|
||||
("ec.sim.ccballaction/0/32bpc/t0.8", 0x9cf15a7756ab88ed),
|
||||
("ec.sim.ccballaction/0/32bpc/t2.2", 0x9cf15a7756ab88ed),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t0.5", 0xe2e3a624434f8e88),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t1.5", 0xe2e3a624434f8e88),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t0.8", 0xe2e3a624434f8e88),
|
||||
("ec.sim.ccballaction/0/8bpc/half/t2.2", 0xe2e3a624434f8e88),
|
||||
("ec.sim.ccballaction/1/8bpc/t0.5", 0x07382912d068a625),
|
||||
("ec.sim.ccballaction/1/8bpc/t1.5", 0x07382912d068a625),
|
||||
("ec.sim.ccballaction/1/8bpc/t0.8", 0x07382912d068a625),
|
||||
("ec.sim.ccballaction/1/8bpc/t2.2", 0x07382912d068a625),
|
||||
("ec.sim.ccballaction/1/32bpc/t0.5", 0xa1e843936e72815f),
|
||||
("ec.sim.ccballaction/1/32bpc/t1.5", 0xa1e843936e72815f),
|
||||
("ec.sim.ccballaction/1/32bpc/t0.8", 0xa1e843936e72815f),
|
||||
("ec.sim.ccballaction/1/32bpc/t2.2", 0xa1e843936e72815f),
|
||||
("ec.sim.ccballaction/2/8bpc/t0.5", 0x0b6bf26753ee4582),
|
||||
("ec.sim.ccballaction/2/8bpc/t1.5", 0x0b6bf26753ee4582),
|
||||
("ec.sim.ccballaction/2/8bpc/t0.8", 0x0b6bf26753ee4582),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys
|
||||
//! those releases saved: if a type change alters this text, write that part out here.
|
||||
|
||||
use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid};
|
||||
use effectcraft_project::{Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, ParamUi, Project, PropGroup, Uid};
|
||||
|
||||
use super::fnv;
|
||||
|
||||
@@ -41,12 +41,40 @@ pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String {
|
||||
if g.uid == uid {
|
||||
break;
|
||||
}
|
||||
s.push_str(&format!("{g:?}"));
|
||||
s.push_str(&effect_text(g));
|
||||
}
|
||||
}
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
|
||||
/// Slider ranges as 0.22–0.24 gave them, for parameters whose range has changed since, as
|
||||
/// (effect, parameter path, [min, max, slider min, slider max], decimals). Those releases hashed
|
||||
/// each effect's UI hints into the Roto Brush Input Key, and opening a project replaces an
|
||||
/// instance's hints with the current ones, so [`effect_text`] puts these back. A range change
|
||||
/// above a Roto Brush would otherwise drop the analysis such a key kept: add a row with it.
|
||||
/// Not every range changed since 0.24.1 has its row yet (#3815).
|
||||
#[rustfmt::skip]
|
||||
const SLIDERS_0_24: &[(&str, &str, [f64; 4], u8)] = &[
|
||||
("ec.blur.gaussian", "blurriness", [0.0, 3000.0, 0.0, 50.0], 1),
|
||||
];
|
||||
|
||||
/// An effect instance as 0.22–0.24 wrote it into a Roto Brush Input Key: its derived `Debug`,
|
||||
/// with the [`SLIDERS_0_24`] ranges in place of today's.
|
||||
pub(crate) fn effect_text(g: &PropGroup) -> String {
|
||||
let GroupKind::Effect { effect } = &g.kind else { return format!("{g:?}") };
|
||||
let mut rows = SLIDERS_0_24.iter().filter(|r| r.0 == effect).peekable();
|
||||
if rows.peek().is_none() {
|
||||
return format!("{g:?}");
|
||||
}
|
||||
let mut g = g.clone();
|
||||
for &(_, path, [min, max, slider_min, slider_max], decimals) in rows {
|
||||
if let Some(p) = g.prop_mut(path).filter(|p| matches!(p.ui, ParamUi::Slider { .. })) {
|
||||
p.ui = ParamUi::Slider { min, max, slider_min, slider_max, decimals };
|
||||
}
|
||||
}
|
||||
format!("{g:?}")
|
||||
}
|
||||
|
||||
/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23),
|
||||
/// with `missing` in place of the item's.
|
||||
pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String {
|
||||
|
||||
@@ -5,7 +5,7 @@ use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
|
||||
use effectcraft_effects::roto::{FROZEN, INPUT_KEY};
|
||||
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{ItemId, LayerId, Project};
|
||||
use effectcraft_project::{GroupKind, ItemId, LayerId, ParamUi, Project};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
@@ -93,6 +93,19 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() {
|
||||
assert_eq!(saved(&s), before);
|
||||
}
|
||||
|
||||
/// 0.24 hashed each effect's UI hints into the Roto Brush's key, and opening a project takes the
|
||||
/// current ones: the legacy text puts back Gaussian Blur's 0.24 Blurriness range (#3460).
|
||||
#[test]
|
||||
fn legacy_roto_keys_hash_the_0_24_blurriness_range() {
|
||||
let s = open(ANALYSED_0_24);
|
||||
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let is_blur = |kind: &GroupKind| matches!(kind, GroupKind::Effect { effect } if effect == "ec.blur.gaussian");
|
||||
let blur = layer.effects().and_then(|fx| fx.groups().find(|g| is_blur(&g.kind))).expect("the fixture has a Gaussian Blur above the Roto Brush");
|
||||
let mut as_0_24 = blur.clone();
|
||||
as_0_24.get_mut("blurriness").unwrap().ui = ParamUi::Slider { min: 0.0, max: 3000.0, slider_min: 0.0, slider_max: 50.0, decimals: 1 };
|
||||
assert_eq!(crate::analysis::frames_key::legacy::effect_text(blur), format!("{as_0_24:?}"));
|
||||
}
|
||||
|
||||
/// The text keys are made from today, written field by field (#3536). It changes only when this
|
||||
/// test is changed with it: a new field of a type it writes doesn't compile until it is decided
|
||||
/// in `analysis::frames_key`, and renaming a field or variant doesn't change it.
|
||||
|
||||
@@ -60,6 +60,17 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[
|
||||
(3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0),
|
||||
(3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0),
|
||||
(3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0),
|
||||
(3464, "ec.perspective.dropshadow", "softness", 0.0, 30000.0),
|
||||
(3467, "ec.blur.radial", "amount", 0.0, 1000.0),
|
||||
(3460, "ec.blur.gaussian", "blurriness", 0.0, 30000.0),
|
||||
(3469, "ec.distort.turbulentdisplace", "amount", -10000.0, 10000.0),
|
||||
(3492, "ec.distort.ccpowerpin", "expandTop", -200.0, 1000.0),
|
||||
(3492, "ec.distort.ccpowerpin", "expandLeft", -200.0, 1000.0),
|
||||
(3492, "ec.distort.ccpowerpin", "expandRight", -200.0, 1000.0),
|
||||
(3492, "ec.distort.ccpowerpin", "expandBottom", -200.0, 1000.0),
|
||||
(3486, "ec.noise.fractal", "subSettings/subScaling", 10.0, 10000.0),
|
||||
(3486, "ec.noise.turbulent", "subSettings/subScaling", 10.0, 10000.0),
|
||||
(3466, "ec.blur.sharpen", "amount", 0.0, 4000.0),
|
||||
];
|
||||
|
||||
fn path(effect: &str, param: &str) -> String {
|
||||
@@ -161,6 +172,23 @@ fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3466: Sharpen Amount clamps just outside After Effects' 0..4000, and an undo after a
|
||||
/// clamped set restores the value from before it.
|
||||
#[test]
|
||||
fn sharpen_amount_clamps_outside_the_after_effects_range() {
|
||||
let (mut s, l, _) = session();
|
||||
let (e, p) = ("ec.blur.sharpen", "amount");
|
||||
for (v, want) in [(4001.0, 4000.0), (-1.0, 0.0)] {
|
||||
set(&mut s, l, e, p, 1000.0);
|
||||
assert_eq!(set(&mut s, l, e, p, v), json!(want), "{v}: prop.set reply");
|
||||
assert_eq!(read(&mut s, l, e, p), want, "{v}");
|
||||
assert!(s.undo());
|
||||
assert_eq!(read(&mut s, l, e, p), 1000.0, "{v}: undo");
|
||||
assert!(s.redo());
|
||||
assert_eq!(read(&mut s, l, e, p), want, "{v}: redo");
|
||||
}
|
||||
}
|
||||
|
||||
/// The property at `path` (`group/param`) in an effect instance.
|
||||
fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> {
|
||||
match path.split_once('/') {
|
||||
|
||||
@@ -192,7 +192,7 @@ fn an_overridden_lut_file_renders_again() {
|
||||
#[test]
|
||||
fn ocio_files_render_again_from_warm_caches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube"));
|
||||
let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts").join("grade.cube"));
|
||||
std::fs::create_dir_all(dir.path().join("luts")).unwrap();
|
||||
write(&lut, BLACK, 1_000);
|
||||
write(&grade, BLACK, 1_000);
|
||||
|
||||
@@ -11,6 +11,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-effects = { workspace = true }
|
||||
effectcraft-geom = { workspace = true }
|
||||
effectcraft-keyframe = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -25,5 +26,4 @@ boa_engine = { workspace = true, features = ["js"] }
|
||||
|
||||
[dev-dependencies]
|
||||
effectcraft-color = { workspace = true }
|
||||
effectcraft-effects = { workspace = true }
|
||||
effectcraft-text = { workspace = true }
|
||||
@@ -7,6 +7,7 @@
|
||||
//! the answers and runs the script again. Expressions are pure functions of these answers, so
|
||||
//! re-running is exact, and the runtime stays free of borrowed state.
|
||||
|
||||
use effectcraft_effects::migrate::PARAM_ID_ALIASES;
|
||||
use effectcraft_geom::{Mat3, Mat4};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ae_order::{self, AeChild};
|
||||
@@ -300,10 +301,24 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
|
||||
// An effect by its After Effects match name, an imported placeholder's effect id
|
||||
// (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`).
|
||||
.or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name)))
|
||||
// Last, so a legacy name never shadows a current one.
|
||||
.or_else(|| legacy_effect_child(g, &c))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter of an effect instance addressed by a name it had when the project was saved
|
||||
/// ([`PARAM_ID_ALIASES`]): `effect("CC Ball Action")("Instability State")` keeps reading the
|
||||
/// parameter that is now Scatter Motion. `c` is the compacted (lowercase, no spaces) name. Only
|
||||
/// renames inside the instance's own top-level group count; moves into twirl-downs do not.
|
||||
fn legacy_effect_child<'g>(g: &'g PropGroup, c: &str) -> Option<&'g Node> {
|
||||
let GroupKind::Effect { effect } = &g.kind else { return None };
|
||||
PARAM_ID_ALIASES
|
||||
.iter()
|
||||
.filter(|(e, old, new)| e == effect && !old.contains('/') && !new.contains('/') && compact(old) == c)
|
||||
.find_map(|(_, _, new)| g.children.iter().find(|n| n.match_id() == *new))
|
||||
}
|
||||
|
||||
impl<'a> Resolver<'a> {
|
||||
fn comp(&self, c: u64) -> Option<&'a Comp> {
|
||||
if c == self.ctx.comp_id.0 { Some(self.ctx.comp) } else { self.ctx.project.comp(ItemId(c)) }
|
||||
|
||||
@@ -870,14 +870,18 @@ Prop.prototype = {
|
||||
propertyGroup: function (n) { return __ancestor(this.__c, this.__l, this.__p, n); },
|
||||
__wrap: function (v) {
|
||||
var kind = this.__info[2];
|
||||
if (kind === 'layer') return v === null ? null : __layer(this.__c, v);
|
||||
// A layer parameter set to None is the layer it sits on, as in After Effects.
|
||||
if (kind === 'layer') return __layer(this.__c, v === null ? this.__l : v);
|
||||
if (kind === 'path' && v !== null) return new __Path(v[0], v[1], v[2], v[3]);
|
||||
return v;
|
||||
},
|
||||
get value() { return this.__self ? value : this.valueAtTime(time); },
|
||||
get value() { return this.__self ? this.__selfValue() : this.valueAtTime(time); },
|
||||
// The evaluated property's own value: a layer parameter reads as its layer here too.
|
||||
// (After posterizeTime, `value` may already be the layer.)
|
||||
__selfValue: function () { return this.__info[2] === 'layer' && !value?.__isLayer ? this.__wrap(value) : value; },
|
||||
valueAtTime: function (t) {
|
||||
t = __v(t);
|
||||
if (this.__self && t === time) return value;
|
||||
if (this.__self && t === time) return this.__selfValue();
|
||||
return this.__wrap(__h(__VALUE, this.__c, this.__l, this.__p, t, this.__self));
|
||||
},
|
||||
velocityAtTime: function (t) {
|
||||
|
||||
@@ -1928,6 +1928,52 @@ fn layer_control_property_stands_for_its_layer() {
|
||||
assert_close!(f.num("effect('Map')(1).value.name == 'B' ? 1 : 0", 0.0), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_layer_control_stands_for_its_own_layer() {
|
||||
// In After Effects a Layer Control set to None gives the layer the effect is on: truthy, named
|
||||
// and callable as that layer. Rigs test it with `L ? … : …` and then read `L.sourceRectAtTime`.
|
||||
let mut f = fx();
|
||||
let spec = effectcraft_effects::find("ec.control.layer").unwrap();
|
||||
let mut map = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Map", [20.0, 20.0]));
|
||||
map.prop_mut("layer").unwrap().value = Value::Layer(None);
|
||||
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(map.into());
|
||||
assert_close!(f.num("effect('Map')(1) ? 1 : 0", 0.0), 1.0);
|
||||
assert_close!(f.num("effect('Map')(1).name == thisLayer.name ? 1 : 0", 0.0), 1.0);
|
||||
assert_close!(f.num("effect('Map')(1).index", 0.0), 1.0);
|
||||
assert_close!(f.num("var L = effect('Map')(1); L ? L.transform.position[0] : -1", 0.0), 50.0);
|
||||
assert_close!(f.num("effect('Map')(1).sourceRectAtTime(time).width == thisLayer.sourceRectAtTime(time).width ? 1 : 0", 0.0), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_parameters_own_expression_reads_its_layer() {
|
||||
// An expression on the layer parameter itself: `thisProperty.value` and
|
||||
// `thisProperty.valueAtTime(time)` give the layer, as reads from other properties do.
|
||||
let mut f = fx();
|
||||
let spec = effectcraft_effects::find("ec.control.layer").unwrap();
|
||||
let mut empty = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Empty", [20.0, 20.0]));
|
||||
empty.prop_mut("layer").unwrap().value = Value::Layer(None);
|
||||
let mut set = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Set", [20.0, 20.0]));
|
||||
set.prop_mut("layer").unwrap().value = Value::Layer(Some(f.b.0));
|
||||
let fx_group = f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap();
|
||||
fx_group.children.push(empty.into());
|
||||
fx_group.children.push(set.into());
|
||||
let n = f.p.comp(f.cid).unwrap().layers[0].props.sub("effects").unwrap().children.len();
|
||||
let (empty_path, set_path) = (format!("effects/#{}/layer", n - 1), format!("effects/#{n}/layer"));
|
||||
// Each expression throws unless it reads the right layer's name.
|
||||
for (path, read, want) in [
|
||||
(&empty_path, "thisProperty.value", "A"),
|
||||
(&empty_path, "thisProperty.valueAtTime(time)", "A"),
|
||||
(&set_path, "thisProperty.value", "B"),
|
||||
(&set_path, "thisProperty.valueAtTime(time)", "B"),
|
||||
] {
|
||||
let e = format!("if ({read}.name !== '{want}') throw new Error('read ' + {read}); value");
|
||||
f.ev(f.a, path, &e, 0.0).unwrap_or_else(|err| panic!("{path} {read}: {err}"));
|
||||
// After posterizeTime moves the sample time, `value` already holds the layer.
|
||||
let e = format!("posterizeTime(1); if ({read}.name !== '{want}') throw new Error('read ' + {read}); value");
|
||||
f.ev(f.a, path, &e, 0.5).unwrap_or_else(|err| panic!("posterized {path} {read}: {err}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_to_frames_rounds_durations_away_from_zero() {
|
||||
let f = fx();
|
||||
@@ -2145,6 +2191,89 @@ fn bench_evaluation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer A with an old-format CC Ball Action: Scatter Motion saved as `instabilityState`
|
||||
/// ("Instability State"), opened through the migration (#3197). Scatter Motion is 37 and keyed
|
||||
/// 10 at 0 s, 50 at 2 s.
|
||||
fn old_ball_action() -> Fx {
|
||||
let mut f = fx();
|
||||
let spec = effectcraft_effects::find("ec.sim.ccballaction").unwrap();
|
||||
let mut g = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "CC Ball Action", [20.0, 20.0]));
|
||||
let sm = g.prop_mut("scatterMotion").unwrap();
|
||||
sm.value = Value::Scalar(37.0);
|
||||
sm.keys = vec![Keyframe::new(Tick::ZERO, Value::Scalar(10.0)), Keyframe::new(secs(2.0), Value::Scalar(50.0))];
|
||||
sm.match_id = "instabilityState".into();
|
||||
sm.name = "Instability State".into();
|
||||
let mut next = f.p.next_id;
|
||||
assert!(effectcraft_effects::migrate::upgrade_instance(spec, &mut g, &mut Ids(&mut next), [20.0, 20.0]));
|
||||
f.p.next_id = next;
|
||||
assert!(g.prop("scatterMotion").is_some(), "the migration renamed the parameter");
|
||||
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(g.into());
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_parameter_names_still_resolve_in_expressions() {
|
||||
let f = old_ball_action();
|
||||
for name in ["Instability State", "instabilityState", "instability state", "InstabilityState"] {
|
||||
// Keyframes still apply: the keyed value at 0 s, not the stored 37.
|
||||
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 0.0), 10.0);
|
||||
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 2.0), 50.0);
|
||||
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}').valueAtTime(2)"), 0.0), 50.0);
|
||||
}
|
||||
// Current names read the same property, unchanged.
|
||||
for name in ["Scatter Motion", "scatterMotion"] {
|
||||
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 0.0), 10.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_parameter_name_follows_the_parameter_expression() {
|
||||
let mut f = old_ball_action();
|
||||
let p = f.p.comp_mut(f.cid).unwrap().layers[0].props.prop_mut("effects/#2/scatterMotion");
|
||||
let p = match p {
|
||||
Some(p) => p,
|
||||
None => panic!("scatterMotion at effects/#2"),
|
||||
};
|
||||
p.expr = Some(Expression { text: "123".into(), enabled: true });
|
||||
assert_close!(f.num("effect('CC Ball Action')('Instability State')", 0.0), 123.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_parameter_names_still_fail() {
|
||||
let f = old_ball_action();
|
||||
assert!(f.ev(f.a, ROT, "effect('CC Ball Action')('No Such Thing')", 0.0).is_err());
|
||||
// Old names only exist on the effect they were renamed on.
|
||||
assert!(f.ev(f.a, ROT, "effect('Slider Control')('Instability State')", 0.0).is_err());
|
||||
}
|
||||
|
||||
/// Every in-group rename in the alias table keeps resolving by its old id and display name.
|
||||
#[test]
|
||||
fn every_in_group_alias_resolves_by_its_old_name() {
|
||||
let mut n = 0;
|
||||
for (effect, old, new) in effectcraft_effects::migrate::PARAM_ID_ALIASES {
|
||||
if old.contains('/') || new.contains('/') {
|
||||
continue;
|
||||
}
|
||||
let Some(spec) = effectcraft_effects::find(effect) else { continue };
|
||||
let mut f = fx();
|
||||
let g = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Probe", [20.0, 20.0]));
|
||||
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(g.into());
|
||||
let (new_name, kind) = {
|
||||
let l = &f.p.comp(f.cid).unwrap().layers[0];
|
||||
let p = l.props.prop(&format!("effects/#2/{new}")).unwrap();
|
||||
(p.name.clone(), p.value.clone())
|
||||
};
|
||||
if !matches!(kind, Value::Scalar(_)) {
|
||||
continue;
|
||||
}
|
||||
let a = f.ev(f.a, ROT, &format!("effect('Probe')('{old}')"), 0.0).unwrap();
|
||||
let b = f.ev(f.a, ROT, &format!("effect('Probe')('{new_name}')"), 0.0).unwrap();
|
||||
assert_eq!(a, b, "{effect}: {old}");
|
||||
n += 1;
|
||||
}
|
||||
assert!(n >= 1);
|
||||
}
|
||||
|
||||
/// Viewport clipping must never affect layer-space expression reads (#1388).
|
||||
#[test]
|
||||
fn sample_image_reads_3d_shape_behind_camera_before_and_after_effects() {
|
||||
|
||||
@@ -411,8 +411,12 @@ fn drop_shadow(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option<GBuf> {
|
||||
let dist = ctx.params.f("distance") * b.scale;
|
||||
let soft = ctx.params.f("softness") * b.scale;
|
||||
let only = ctx.params.b("shadowOnly");
|
||||
let pad = (dist + soft * 1.5).ceil() as u32 + 2;
|
||||
let pad = effectcraft_effects::drop_shadow_pad(dist, soft);
|
||||
if !ctx.adjustment {
|
||||
// A margin cut to the pixel budget: the CPU blurs on past the buffer's edge (#3464).
|
||||
if soft > 0.0 && effectcraft_effects::pad_within_budget(b.img.width, b.img.height, pad) < pad {
|
||||
return None;
|
||||
}
|
||||
b.pad(e, pad)?;
|
||||
}
|
||||
let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist);
|
||||
@@ -592,7 +596,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
|
||||
let (ox, oy) = b.to_px(pr.v2("transform/offset"));
|
||||
let s = f("transform/scale");
|
||||
let (sw, sh) = if pr.b("transform/uniformScaling") { (s, s) } else { (f("transform/scaleWidth"), f("transform/scaleHeight")) };
|
||||
let sub = (f("subSettings/subScaling") / 100.0).clamp(0.1, 1.0);
|
||||
let sub = effectcraft_effects::sub_scaling_ratio(f("subSettings/subScaling"));
|
||||
p.u[0] = [10, kind, octaves.ceil() as u32, f("evolutionOptions/seed") as u32 ^ 0x51ed];
|
||||
p.u[1] = [pr.b("invert") as u32, pr.e("overflow"), mode, 0];
|
||||
p.f[0] = [
|
||||
@@ -608,7 +612,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
|
||||
(f("opacity") as f32 / 100.0).clamp(0.0, 1.0),
|
||||
(sh * effectcraft_effects::NOISE_CELL * b.scale).max(1.0) as f32,
|
||||
];
|
||||
p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, 0.0, 0.0];
|
||||
p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, effectcraft_effects::OCTAVE_SCALE_MAX, 0.0];
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
|
||||
@@ -172,10 +172,9 @@ fn cc_lens(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
|
||||
}
|
||||
|
||||
fn turbulent(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option<GBuf> {
|
||||
let amount = ctx.params.f("amount") * b.scale;
|
||||
if amount.abs() < 1e-9 {
|
||||
let Some(amount) = effectcraft_effects::turbulent_amount_px(ctx, b.scale) else {
|
||||
return Some(b);
|
||||
}
|
||||
};
|
||||
let kind = ctx.params.e("displacement");
|
||||
let size = (ctx.params.f("size") * b.scale).max(1.0);
|
||||
if ctx.params.b("resizeLayer") && !ctx.adjustment {
|
||||
|
||||
@@ -100,14 +100,14 @@ fn radial_blur(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
|
||||
if amount.abs() < 1e-6 {
|
||||
return Some(b);
|
||||
}
|
||||
let n = 32usize;
|
||||
// The CPU's samples (`raster::radial_blur`).
|
||||
let n = effectcraft_raster::RADIAL_BLUR_SAMPLES;
|
||||
let mut data = Vec::with_capacity(2 * n);
|
||||
for i in 0..n {
|
||||
let t = i as f64 / (n - 1) as f64 - 0.5;
|
||||
if zoom {
|
||||
data.push((1.0 + t * amount) as f32);
|
||||
data.push(effectcraft_raster::radial_blur_zoom_scale(i, amount) as f32);
|
||||
} else {
|
||||
let (s, c) = (t * amount).to_radians().sin_cos();
|
||||
let (s, c) = effectcraft_raster::radial_blur_spin_degrees(i, amount).to_radians().sin_cos();
|
||||
data.extend([s as f32, c as f32]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,6 +228,8 @@ pub(crate) fn sprite_layer(e: &mut Enc, src: &GpuImage, plan: &SpritePlan) -> Op
|
||||
Shape::Square => (6.0, 0.0, 0.0),
|
||||
Shape::Tri => (7.0, 0.0, 0.0),
|
||||
Shape::Line { dx, dy } => (8.0, dx, dy),
|
||||
// The strength rides in the (otherwise unused) first segment slot.
|
||||
Shape::Ball { shade } => (9.0, shade, 0.0),
|
||||
};
|
||||
let mut rec = [kind, s.x, s.y, s.r, s.c[0], s.c[1], s.c[2], s.c[3], s.rot, dx, dy, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
match plan.tints.get(i).copied().unwrap_or(Tint::Fixed) {
|
||||
|
||||
@@ -145,6 +145,27 @@ fn fxm_sprite(at: u32, x: f32, y: f32) -> FxmShade {
|
||||
}
|
||||
cov = fxm_aa(m);
|
||||
}
|
||||
// sim::Shape::Ball (CC Ball Action's Shading): the sphere's light and shine scaled by
|
||||
// |shade| (data[at + 9]), lit from the lower right when shade < 0.
|
||||
case 9u: {
|
||||
let d = sqrt(dx * dx + dy * dy);
|
||||
let cv = fxm_aa(r - d);
|
||||
if (cv <= 0.0) {
|
||||
return fxm_none();
|
||||
}
|
||||
let shade = data[at + 9u];
|
||||
let nx = dx / r;
|
||||
let ny = dy / r;
|
||||
let nz = sqrt(max(1.0 - nx * nx - ny * ny, 0.0));
|
||||
let m = select(1.0, -1.0, shade < 0.0);
|
||||
let diff = max(nx * (-0.48 * m) + ny * (-0.58 * m) + nz * 0.66, 0.0);
|
||||
let rz = 2.0 * diff * nz - 0.66;
|
||||
let st = abs(shade);
|
||||
let spec = powz(max(rz, 0.0), 20.0) * 0.6 * st;
|
||||
let k = max(1.0 - st * 0.8 * (1.0 - diff), 0.0);
|
||||
rgb = rgb * k + spec;
|
||||
cov = cv;
|
||||
}
|
||||
default: {
|
||||
let lx = data[at + 9u];
|
||||
let ly = data[at + 10u];
|
||||
|
||||
@@ -289,9 +289,25 @@ fn box_pass(gid: vec3<u32>, horizontal: bool) {
|
||||
}
|
||||
let norm = 1.0 / f32(2 * r + 1);
|
||||
var acc = vec4<f32>(0.0);
|
||||
for (var i = b0 - r; i <= b0 + r; i++) {
|
||||
// The starting window, as the CPU sums it: the pixels inside the line once each, and the
|
||||
// repeated edge pixels counted rather than visited (a radius far past the line, such as
|
||||
// Gaussian Blur's at Blurriness 30000, would otherwise loop over it once per pixel).
|
||||
let lo = b0 - r;
|
||||
let hi = b0 + r;
|
||||
for (var i = max(lo, 0); i <= min(hi, n - 1); i++) {
|
||||
acc += line_get(horizontal, line, i, n, repeat);
|
||||
}
|
||||
if (repeat) {
|
||||
let before = f32(max(-lo, 0));
|
||||
let after = f32(max(hi - (n - 1), 0));
|
||||
// A zero count adds nothing (0 * NaN would be NaN).
|
||||
if (before > 0.0) {
|
||||
acc += line_get(horizontal, line, 0, n, repeat) * before;
|
||||
}
|
||||
if (after > 0.0) {
|
||||
acc += line_get(horizontal, line, n - 1, n, repeat) * after;
|
||||
}
|
||||
}
|
||||
let b1 = min(b0 + block, n);
|
||||
for (var i = b0; i < b1; i++) {
|
||||
if (horizontal) {
|
||||
@@ -618,7 +634,8 @@ fn straight(px: vec4<f32>) -> vec3<f32> {
|
||||
// 9 Gradient Ramp f[0] = (sx, sy, ex, ey); f[1] = start colour; f[2] = end colour;
|
||||
// f[3] = (len2, scatter, blend); u[0] = (_, radial, seed)
|
||||
// 10 Fractal Noise f[0] = (contrast, brightness, scale x, frac); f[1] = (ox, oy, sr, cr);
|
||||
// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling);
|
||||
// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling,
|
||||
// OCTAVE_SCALE_MAX);
|
||||
// u[0] = (_, kind, n_oct, seed); u[1] = (invert, overflow, normal blend)
|
||||
@compute @workgroup_size(16, 16)
|
||||
fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
@@ -856,6 +873,7 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let scale_y = P.f[2].w;
|
||||
let infl = P.f[3].x;
|
||||
let fmul = P.f[3].y;
|
||||
let fmax = P.f[3].z;
|
||||
let frac = P.f[0].w;
|
||||
let ox = P.f[1].x;
|
||||
let oy = P.f[1].y;
|
||||
@@ -888,7 +906,8 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
sum += n * amp * w;
|
||||
norm += amp * w;
|
||||
amp *= infl;
|
||||
f *= fmul;
|
||||
// noise3::next_octave: the frequency stays within OCTAVE_SCALE_MAX (#3486).
|
||||
f = clamp(f * fmul, 1.0 / fmax, fmax);
|
||||
}
|
||||
var val = sum / max(norm, 1e-6);
|
||||
val = (val - 0.5) * contrast + 0.5 + brightness;
|
||||
|
||||
@@ -760,6 +760,68 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU
|
||||
/// runs it and matches the CPU (1000, the old maximum, on a 70 × 44 layer). Once the pixel
|
||||
/// budget cuts the padding only the CPU blurs past the buffer's edge, so the GPU declines the
|
||||
/// effect; the render then takes it on the CPU at 8 and 32 bpc, with and without Shadow Only.
|
||||
#[test]
|
||||
fn drop_shadow_large_softness_matches_cpu() {
|
||||
effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]);
|
||||
let Some(g) = gpu() else { return };
|
||||
for only in [false, true] {
|
||||
let vals = [("distance", n(6.0)), ("softness", n(30000.0)), ("opacity", n(100.0)), ("shadowOnly", Value::Bool(only))];
|
||||
let spec = effectcraft_effects::find("ec.perspective.dropshadow").unwrap();
|
||||
let mut params = effectcraft_effects::Params {
|
||||
values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, [70.0, 44.0]))).collect(),
|
||||
};
|
||||
for (k, v) in &vals {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: [70.0, 44.0], seed: 11, adjustment: false, env: Default::default() };
|
||||
let buf = effectcraft_effects::Buf { img: pattern(7, 70, 44), offset: [0.0, 0.0], scale: 1.0 };
|
||||
let step = effectcraft_render::FxStep { spec, ctx };
|
||||
assert!(effectcraft_render::Accelerator::effects(g, &[step], &buf, None).is_none(), "the GPU hands a cut margin to the CPU");
|
||||
for depth in [BitDepth::Bpc8, BitDepth::Bpc32] {
|
||||
let mut s = Scene::new(depth);
|
||||
let bg = s.solid([0.15, 0.1, 0.2], 97, 61);
|
||||
s.push(bg);
|
||||
let mut l = s.footage(70, 44);
|
||||
s.effect(&mut l, "ec.perspective.dropshadow", &vals);
|
||||
s.push(l);
|
||||
check(&format!("drop shadow 30000 only {only} {depth:?}"), compare_at(&s, opts(), Tick::ZERO), 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3460: a box radius far past the image (Gaussian Blur's at Blurriness 30000 is about 15000 px)
|
||||
/// starts each running sum as the CPU does, the pixels inside once and the repeated edges
|
||||
/// counted, so the GPU matches it along rows and columns, with and without repeated edges.
|
||||
#[test]
|
||||
fn box_passes_with_a_radius_far_past_the_image_match_cpu() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let img = pattern(5, 96, 40);
|
||||
let up = g.ctx.upload_image(&img).expect("upload");
|
||||
let tol = tolerance(BitDepth::Bpc32);
|
||||
for repeat in [true, false] {
|
||||
let mut e = crate::context::Enc::new(&g.ctx);
|
||||
let r = [15_000usize; 3];
|
||||
let out = crate::effects::box_passes(&mut e, &up, &r, &r, repeat);
|
||||
let got = e.download(&out).expect("download");
|
||||
let want = effectcraft_raster::box_blur(&img, 15_000, 15_000, 3, repeat);
|
||||
assert_eq!((got.width, got.height), (want.width, want.height));
|
||||
let d = diff(&want, &got, tol);
|
||||
assert_eq!(d.over, 0, "repeat {repeat}: max {} at {:?} on {}", d.max, d.worst, g.ctx.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3460: Gaussian Blur's highest Blurriness, 30000, renders the same on the GPU as on the CPU,
|
||||
/// with the padding cut to the effect pixel budget and with Repeat Edge Pixels.
|
||||
#[test]
|
||||
fn gaussian_blur_at_the_highest_blurriness_matches_cpu() {
|
||||
effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0))]);
|
||||
effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0)), ("repeatEdge", Value::Bool(true))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_effects_match_cpu() {
|
||||
// Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939).
|
||||
|
||||
@@ -57,6 +57,14 @@ fn turbulent_displace_and_cc_lens() {
|
||||
],
|
||||
);
|
||||
effect_case("ec.distort.turbulentdisplace", &[("displacement", e(8)), ("size", n(15.0)), ("pinning", e(6))]);
|
||||
// #3469: both ends of After Effects' Amount range, resized and pinned, and an expression's
|
||||
// Amount past it.
|
||||
effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(10000.0))]);
|
||||
effect_case(
|
||||
"ec.distort.turbulentdisplace",
|
||||
&[("displacement", e(1)), ("size", n(25.0)), ("amount", n(-10000.0)), ("pinning", e(1)), ("resizeLayer", on())],
|
||||
);
|
||||
effect_case("ec.distort.turbulentdisplace", &[("displacement", e(7)), ("amount", n(f64::INFINITY)), ("pinning", e(2))]);
|
||||
// #943: Evolution moves the pattern at a constant rate on both paths, including steps of a
|
||||
// few degrees and angles past a whole revolution, where an eased evolution axis diverges.
|
||||
for evolution in [10.0, 37.0, 400.0, 725.5] {
|
||||
|
||||
@@ -24,6 +24,9 @@ fn radial_blur() {
|
||||
effect_case("ec.blur.radial", &[("amount", n(12.0))]);
|
||||
effect_case("ec.blur.radial", &[("amount", n(30.0)), ("type", e(1)), ("center", pt(20.3, 14.7))]);
|
||||
effect_case("ec.blur.radial", &[("amount", n(-45.0)), ("center", pt(50.0, 30.0))]);
|
||||
// Amount's largest value, 1000 (#3467): Spin over ±500°, Zoom from the centre outwards.
|
||||
effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("center", pt(20.3, 14.7))]);
|
||||
effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("type", e(1)), ("center", pt(20.3, 14.7)), ("antialiasing", e(1))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -75,6 +75,8 @@ fn edge_preserving_blurs() {
|
||||
fn sharpen_and_unsharp_mask() {
|
||||
effect_case("ec.blur.sharpen", &[("amount", n(60.0))]);
|
||||
effect_case("ec.blur.sharpen", &[("amount", n(250.0))]);
|
||||
// #3466: the top of After Effects' range (80 × the difference from the blur).
|
||||
effect_case("ec.blur.sharpen", &[("amount", n(4000.0))]);
|
||||
effect_case("ec.blur.unsharp", &[("amount", n(120.0)), ("radius", n(4.0))]);
|
||||
effect_case("ec.blur.unsharp", &[("amount", n(80.0)), ("radius", n(2.5)), ("threshold", n(12.0))]);
|
||||
}
|
||||
@@ -136,6 +138,24 @@ fn turbulent_noise() {
|
||||
effect_case("ec.noise.turbulent", &[("fractalType", e(7)), ("noiseType", e(0)), ("transform/perspectiveOffset", on()), ("opacity", n(70.0))]);
|
||||
}
|
||||
|
||||
/// #3486: Sub Scaling above 100 % on both GPU paths (the `pointwise` kernel for the plain
|
||||
/// settings, `fxn_fractal` for Perspective Offset and Turbulent Noise), up to After Effects'
|
||||
/// 10000 at the highest Complexity.
|
||||
#[test]
|
||||
fn fractal_noise_sub_scaling_above_100() {
|
||||
for sub in [200.0, 10000.0] {
|
||||
effect_case("ec.noise.fractal", &[("subSettings/subScaling", n(sub)), ("complexity", n(20.0))]);
|
||||
effect_case(
|
||||
"ec.noise.fractal",
|
||||
&[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("transform/perspectiveOffset", on()), ("evolution", n(90.0))],
|
||||
);
|
||||
effect_case(
|
||||
"ec.noise.turbulent",
|
||||
&[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("evolution", n(120.0)), ("evolutionOptions/turbulenceFactor", n(10.0))],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractal_noise_other_modes() {
|
||||
effect_case("ec.noise.fractal", &[("noiseType", e(3)), ("fractalType", e(4)), ("blendingMode", e(3))]);
|
||||
|
||||
@@ -141,7 +141,22 @@ fn ball_action_pixel_polly_scatterize() {
|
||||
0.0,
|
||||
0.0,
|
||||
);
|
||||
case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0);
|
||||
case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0);
|
||||
// #3197: Shading (flat, weaker, stronger, lit from the other side), Coloring, Displace.
|
||||
for shading in [0.0, -30.0, -100.0, 60.0, 1e45] {
|
||||
case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("shading", n(shading))], 0.0, 0.0);
|
||||
}
|
||||
for coloring in [0, 2] {
|
||||
case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("coloring", e(coloring))], 0.0, 0.0);
|
||||
}
|
||||
for prop in [3, 6, 8] {
|
||||
case(
|
||||
"ec.sim.ccballaction",
|
||||
&[("ballSize", n(80.0)), ("rotationAxis", e(1)), ("rotation", n(30.0)), ("displace", n(40.0)), ("displaceProperty", e(prop))],
|
||||
0.0,
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
for object in 0..4 {
|
||||
case("ec.sim.ccpixelpolly", &[("object", e(object)), ("gridSpacing", n(6.0))], 0.6, 0.0);
|
||||
}
|
||||
|
||||
@@ -218,6 +218,13 @@ fn twirl_legacy_ripple_pulse_power_pin() {
|
||||
// Perspective below 100 %: blended toward the bilinear inverse.
|
||||
effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(0.0))]);
|
||||
effect_case("ec.distort.ccpowerpin", &[("topLeft", pt(12.0, 6.0)), ("bottomRight", pt(75.0, 30.0)), ("perspective", n(40.0)), ("expandTop", n(15.0))]);
|
||||
// #3492: Expansion down to -200; opposite sides adding up to less than -100 % flip the source,
|
||||
// and Top -50 / Bottom -50 leave it zero high.
|
||||
effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("expandTop", n(-200.0)), ("expandBottom", n(-100.0)), ("expandLeft", n(-150.0))]);
|
||||
effect_case(
|
||||
"ec.distort.ccpowerpin",
|
||||
&[("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(40.0)), ("expandTop", n(-50.0)), ("expandBottom", n(-50.0)), ("expandRight", n(-200.0))],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,6 +10,7 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-timeline = { workspace = true }
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-color = { workspace = true }
|
||||
effectcraft-keyframe = { workspace = true }
|
||||
|
||||
@@ -49,78 +49,7 @@ pub struct ImportResult {
|
||||
/// a few levels per nested sequence; parsing several thousand levels overflowed the stack.
|
||||
pub const MAX_DEPTH: usize = 256;
|
||||
|
||||
/// The deepest element nesting of an XML document (a quick scan that skips comments, CDATA,
|
||||
/// processing instructions, declarations and quoted attribute values).
|
||||
pub(crate) fn xml_depth(b: &[u8]) -> usize {
|
||||
let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize);
|
||||
let skip_to = |from: usize, end: &[u8]| b.get(from..).and_then(|r| r.windows(end.len()).position(|w| w == end)).map_or(b.len(), |p| from + p + end.len());
|
||||
while let Some(&c) = b.get(i) {
|
||||
if c != b'<' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let rest = b.get(i..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = skip_to(i + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = skip_to(i + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = skip_to(i + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") {
|
||||
i = skip_to(i + 2, b">");
|
||||
} else if rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(1);
|
||||
i = skip_to(i + 2, b">");
|
||||
} else {
|
||||
// A start tag: find its end outside quotes; `/>` closes it at once.
|
||||
let mut j = i + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if c == b'"' || c == b'\'' => quote = Some(c),
|
||||
None if c == b'>' => break,
|
||||
None => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.wrapping_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
max = max.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
|
||||
/// The deepest array / object nesting of a JSON document (strings skipped).
|
||||
pub(crate) fn json_depth(b: &[u8]) -> usize {
|
||||
let (mut depth, mut max, mut in_str, mut esc) = (0usize, 0usize, false, false);
|
||||
for &c in b {
|
||||
if in_str {
|
||||
if esc {
|
||||
esc = false;
|
||||
} else if c == b'\\' {
|
||||
esc = true;
|
||||
} else if c == b'"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b'"' => in_str = true,
|
||||
b'[' | b'{' => {
|
||||
depth += 1;
|
||||
max = max.max(depth);
|
||||
}
|
||||
b']' | b'}' => depth = depth.saturating_sub(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
pub(crate) use craft_timeline::preflight::{json_depth, xml_depth};
|
||||
|
||||
pub fn import(
|
||||
project: &mut Project,
|
||||
|
||||
@@ -14,5 +14,6 @@ effectcraft-geom = { workspace = true }
|
||||
effectcraft-keyframe = { workspace = true }
|
||||
effectcraft-raster = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
log = { workspace = true }
|
||||
tiny-skia = { workspace = true }
|
||||
linesweeper = "0.5"
|
||||
+49
-5
@@ -351,14 +351,28 @@ fn round_sub(sub: &Sub, r: f64, out: &mut BezPath) {
|
||||
/// join. `copies` copies are made, copy *i* (0-based) offset by `amount · (i + 1 + copy_offset)`,
|
||||
/// all returned in the same compound path.
|
||||
pub fn offset(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64) -> Vec<BezPath> {
|
||||
let n = copies.round().clamp(1.0, 1000.0) as usize;
|
||||
offset_within(paths, amount, join, miter_limit, copies, copy_offset, MAX_OPERATOR_SEGMENTS)
|
||||
}
|
||||
|
||||
/// [`offset`] with each path's result held to `max` elements (its first copy aside).
|
||||
fn offset_within(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64, max: usize) -> Vec<BezPath> {
|
||||
let n = pieces_within_budget(paths, copies.round().clamp(1.0, 1000.0) as usize);
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut out = BezPath::new();
|
||||
for i in 0..n {
|
||||
let d = amount * (i as f64 + 1.0 + copy_offset);
|
||||
out.extend(crate::offset::offset_path(p, d, join, miter_limit).elements().iter().copied());
|
||||
let copy = crate::offset::offset_path(p, d, join, miter_limit);
|
||||
// The budget is spent on what `offset_path` returns (an open subpath comes back as
|
||||
// a closed outline of many segments; a zero offset as the path itself): the first
|
||||
// copy is always kept, and a copy that would pass the budget is not made, so the
|
||||
// work stays within a small multiple of it.
|
||||
if i > 0 && out.elements().len().saturating_add(copy.elements().len()) > max {
|
||||
log::warn!("path: Offset Paths made {i} of {n} copies; more would pass {max} segments");
|
||||
break;
|
||||
}
|
||||
out.extend(copy.elements().iter().copied());
|
||||
}
|
||||
out
|
||||
})
|
||||
@@ -387,6 +401,14 @@ pub fn twist(paths: &[BezPath], angle_deg: f64, center: [f64; 2]) -> Vec<BezPath
|
||||
return paths.to_vec();
|
||||
}
|
||||
let k = a / rmax;
|
||||
// The pieces a segment asks for; the uniform cap applies only when the requests together
|
||||
// would pass the budget (long segments keep their detail next to many short ones otherwise).
|
||||
let want = |len: f64| ((a.abs() * len / rmax) / 0.15 + len / 50.0).ceil().clamp(1.0, 64.0) as usize;
|
||||
let requested = paths
|
||||
.iter()
|
||||
.flat_map(subs)
|
||||
.fold(0usize, |n, sub| sub.segs.iter().fold(n.saturating_add(overhead_of(&sub)), |n, seg| n.saturating_add(want(seg.arclen(ACC)))));
|
||||
let most = if requested <= MAX_OPERATOR_SEGMENTS { 64 } else { pieces_within_budget(paths, 64) };
|
||||
let rot = |v: Vec2, th: f64| {
|
||||
let (s, co) = th.sin_cos();
|
||||
Vec2::new(v.x * co - v.y * s, v.x * s + v.y * co)
|
||||
@@ -414,7 +436,7 @@ pub fn twist(paths: &[BezPath], angle_deg: f64, center: [f64; 2]) -> Vec<BezPath
|
||||
for seg in &sub.segs {
|
||||
let cb = seg.to_cubic();
|
||||
let len = seg.arclen(ACC);
|
||||
let m = ((a.abs() * len / rmax) / 0.15 + len / 50.0).ceil().clamp(1.0, 64.0) as usize;
|
||||
let m = want(len).min(most);
|
||||
for i in 0..m {
|
||||
let q = cb.subsegment(i as f64 / m as f64..(i + 1) as f64 / m as f64);
|
||||
let (p0, p3) = (map(q.p0), map(q.p3));
|
||||
@@ -442,6 +464,28 @@ struct Sample {
|
||||
len_next: f64,
|
||||
}
|
||||
|
||||
/// Most segments an expanding operator (Zig Zag, Wiggle Paths, Twist, Offset Paths' copies)
|
||||
/// makes from its input. Operators stack, each expanding the previous one's output; capping each
|
||||
/// output keeps a short stack from multiplying a simple path into billions of points.
|
||||
pub const MAX_OPERATOR_SEGMENTS: usize = 1 << 20;
|
||||
|
||||
/// Elements a subpath adds besides its segments: a `MoveTo`, and a `ClosePath` only when closed.
|
||||
fn overhead_of(sub: &Sub) -> usize {
|
||||
if sub.closed { 2 } else { 1 }
|
||||
}
|
||||
|
||||
/// `want` pieces (or copies) per input segment, reduced so the whole output (segments times
|
||||
/// pieces, plus per-subpath overhead) stays within [`MAX_OPERATOR_SEGMENTS`] (never below 1, so the input itself always passes through).
|
||||
fn pieces_within_budget(paths: &[BezPath], want: usize) -> usize {
|
||||
// Count what is subdivided (drawn segments) and keep room for each subpath's own MoveTo/Close.
|
||||
let (mut segs, mut overhead) = (0usize, 0usize);
|
||||
for sub in paths.iter().flat_map(subs) {
|
||||
segs = segs.saturating_add(sub.segs.len());
|
||||
overhead = overhead.saturating_add(overhead_of(&sub));
|
||||
}
|
||||
want.min(MAX_OPERATOR_SEGMENTS.saturating_sub(overhead) / segs.max(1)).max(1)
|
||||
}
|
||||
|
||||
/// Split every segment into `m` pieces of equal arc length. Original vertices get the average of
|
||||
/// their incoming and outgoing tangents (so a corner's normal is its bisector).
|
||||
fn resample(sub: &Sub, m: usize) -> Vec<Sample> {
|
||||
@@ -503,7 +547,7 @@ fn emit(samples: &[Sample], disp: &[Vec2], closed: bool, smooth: bool, handle: f
|
||||
/// `smooth` makes rounded waves instead of sharp zig zags. A closed path with `n` segments ends up
|
||||
/// with `n · (ridges + 1)` vertices (open: one more).
|
||||
pub fn zigzag(paths: &[BezPath], size: f64, ridges: f64, smooth: bool) -> Vec<BezPath> {
|
||||
let m = ridges.round().clamp(0.0, 1000.0) as usize + 1;
|
||||
let m = pieces_within_budget(paths, ridges.round().clamp(0.0, 1000.0) as usize + 1);
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -586,7 +630,7 @@ pub fn wiggle(paths: &[BezPath], w: &WiggleParams, time_s: f64) -> Vec<BezPath>
|
||||
if w.size == 0.0 {
|
||||
return paths.to_vec();
|
||||
}
|
||||
let m = w.detail.round().clamp(0.0, 1000.0) as usize + 1;
|
||||
let m = pieces_within_budget(paths, w.detail.round().clamp(0.0, 1000.0) as usize + 1);
|
||||
let seed = w.seed.round() as i64 as u64;
|
||||
let t = time_s * w.speed + w.phase_deg / 360.0;
|
||||
let corr = (w.correlation / 100.0).clamp(0.0, 1.0);
|
||||
|
||||
@@ -182,6 +182,25 @@ fn offset_copies() {
|
||||
assert!(close(o[0].bounding_box().width(), 140.0, 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_copies_are_budgeted_by_the_output_they_return() {
|
||||
// An open one-segment subpath comes back as a closed outline of several elements, so the copies
|
||||
// stop when the returned elements pass the budget, not when the input segments would.
|
||||
let line = || {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((50.0, 0.0));
|
||||
p
|
||||
};
|
||||
let one = offset_within(&[line()], 5.0, Join::Round, 4.0, 1.0, 0.0, usize::MAX)[0].elements().len();
|
||||
assert!(one > 4, "{one}");
|
||||
let o = offset_within(&[line()], 5.0, Join::Round, 4.0, 50.0, 0.0, one * 3);
|
||||
let moves = o[0].elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count();
|
||||
assert!((1..50).contains(&moves) && o[0].elements().len() <= one * 4, "{moves} contours, {} elements", o[0].elements().len());
|
||||
// The first copy always comes back, however small the budget.
|
||||
assert!(!offset_within(&[line()], 5.0, Join::Round, 4.0, 5.0, 0.0, 0)[0].elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_open_path_outlines() {
|
||||
let mut l = BezPath::new();
|
||||
@@ -246,6 +265,22 @@ fn twist_of_centred_circle_keeps_it_round() {
|
||||
assert_eq!(id[0], sq(0.0, 0.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_keeps_requested_detail_when_the_whole_request_fits_the_budget() {
|
||||
// One long segment asks for 64 pieces; 20,000 tiny ones ask for one each. Together that is
|
||||
// far under the budget, so the long one is not cut to what a uniform 64 per segment would allow.
|
||||
let mut long = BezPath::new();
|
||||
long.move_to((0.0, 0.0));
|
||||
long.line_to((5000.0, 0.0));
|
||||
let mut tiny = BezPath::new();
|
||||
tiny.move_to((0.0, 1.0));
|
||||
for i in 1..=20_000 {
|
||||
tiny.line_to((i as f64 * 1e-3, 1.0));
|
||||
}
|
||||
let t = twist(&[long, tiny], 90.0, [0.0, 0.0]);
|
||||
assert_eq!(t[0].elements().len(), 1 + 64);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- zig zag
|
||||
|
||||
#[test]
|
||||
@@ -417,3 +452,48 @@ fn normalize_and_filled_area() {
|
||||
let n = crate::boolean::normalize(&p, FillRule::EvenOdd);
|
||||
assert!(close(n.area().abs(), 10000.0, 1e-6));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- operator budget
|
||||
|
||||
#[test]
|
||||
fn stacked_expanding_operators_stay_within_the_segment_budget() {
|
||||
// Three Zig Zags at 1000 ridges would turn a square into 4 · 1001³ segments; each output
|
||||
// is held to the budget instead, and the last operators still pass the geometry through.
|
||||
let mut p = vec![sq(0.0, 0.0, 100.0)];
|
||||
for _ in 0..3 {
|
||||
p = zigzag(&p, 1.0, 1000.0, false);
|
||||
let n: usize = p.iter().map(|q| q.elements().len()).sum();
|
||||
assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}");
|
||||
}
|
||||
let w = wiggle(&p, &WiggleParams { detail: 1000.0, ..Default::default() }, 0.0);
|
||||
let n: usize = w.iter().map(|q| q.elements().len()).sum();
|
||||
assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}");
|
||||
let o = offset(&[sq(0.0, 0.0, 100.0)], 1.0, Join::Miter, 4.0, 1000.0, 0.0);
|
||||
assert!(!o[0].elements().is_empty());
|
||||
// Within the budget nothing changes: 4 segments × 11 pieces.
|
||||
assert_eq!(vertex_count(&zigzag(&[sq(0.0, 0.0, 100.0)], 1.0, 10.0, false)[0]), 44);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_short_open_paths_keep_their_requested_detail_within_the_budget() {
|
||||
// 1000 open lines at 1000 ridges: 1,001,000 segments fit the budget, so nothing is reduced.
|
||||
let lines: Vec<BezPath> = (0..1000)
|
||||
.map(|i| {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, i as f64));
|
||||
p.line_to((100.0, i as f64));
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let z = zigzag(&lines, 1.0, 1000.0, false);
|
||||
assert!(z.iter().all(|q| q.elements().len() == 1 + 1001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_subpaths_reserve_one_element_of_overhead() {
|
||||
// 349,525 open lines: the move-to is the only extra element, so 2 copies fit the budget
|
||||
// (a closed subpath's extra close-path would leave room for 1).
|
||||
let line = BezPath::from_vec(vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::LineTo((1.0, 0.0).into())]);
|
||||
let lines = vec![line; 349_525];
|
||||
assert_eq!(pieces_within_budget(&lines, 3), 2);
|
||||
}
|
||||
+108
-114
@@ -42,8 +42,14 @@ pub enum RefItem {
|
||||
Class(String),
|
||||
Enum(String, String, String),
|
||||
Offset(String, i32),
|
||||
/// Identifier with the legacy unnamed `null` class.
|
||||
Identifier(i32),
|
||||
/// Index with the legacy unnamed `null` class.
|
||||
Index(i32),
|
||||
/// Identifier retaining the original class and its encoding.
|
||||
IdentifierWithClass(craft_psd::descriptor::Class, i32),
|
||||
/// Index retaining the original class and its encoding.
|
||||
IndexWithClass(craft_psd::descriptor::Class, i32),
|
||||
Name(String, String),
|
||||
}
|
||||
|
||||
@@ -108,14 +114,6 @@ impl Descriptor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A key or class id: length-prefixed string, or a 4-character code when the length is 0.
|
||||
pub(crate) fn read_id(r: &mut Reader) -> Result<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let n = if n == 0 { 4 } else { n };
|
||||
let b = r.bytes(n)?;
|
||||
Ok(String::from_utf8_lossy(b).into_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let mut v = Vec::with_capacity(n.min(r.remaining() / 2));
|
||||
@@ -128,122 +126,90 @@ pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
|
||||
Ok(String::from_utf16_lossy(&v))
|
||||
}
|
||||
|
||||
/// Read a descriptor (after its version field).
|
||||
/// Preserve the application parser's per-container limits in the shared parser.
|
||||
pub(crate) const PARSE_LIMITS: craft_psd::descriptor::ParseLimits =
|
||||
craft_psd::descriptor::ParseLimits { max_descriptor_items: 100_000, max_list_items: 1_000_000 };
|
||||
|
||||
/// Read a descriptor (after its version field) with [`craft_psd::descriptor::Descriptor::parse_prefix`].
|
||||
/// The public [`Descriptor`] / [`DValue`] types stay this crate's (engine interchange uses them).
|
||||
pub fn read_descriptor(r: &mut Reader) -> Result<Descriptor> {
|
||||
read_descriptor_at(r, 0)
|
||||
let rest = r.data.get(r.pos..).unwrap_or(&[]);
|
||||
let (d, used) = craft_psd::descriptor::Descriptor::parse_prefix_with_limits(rest, PARSE_LIMITS).map_err(desc_err)?;
|
||||
r.skip(used)?;
|
||||
Ok(from_craft_descriptor(d))
|
||||
}
|
||||
|
||||
/// [`read_descriptor`] nested `depth` values deep: the limit in [`read_value`] counts nested
|
||||
/// descriptors too, so a file can't recurse until the stack overflows.
|
||||
fn read_descriptor_at(r: &mut Reader, depth: usize) -> Result<Descriptor> {
|
||||
let class_name = read_unicode(r)?;
|
||||
let class_id = read_id(r)?;
|
||||
let n = r.u32()? as usize;
|
||||
if n > 100_000 {
|
||||
return Err(Error::Invalid("descriptor item count".into()));
|
||||
fn desc_err(e: craft_psd::PsdError) -> Error {
|
||||
match e {
|
||||
craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated,
|
||||
craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s),
|
||||
other => Error::Invalid(other.to_string()),
|
||||
}
|
||||
let mut items = Vec::with_capacity(n.min(64));
|
||||
for _ in 0..n {
|
||||
let key = read_id(r)?;
|
||||
let ty = r.tag()?;
|
||||
let v = read_value(r, &ty, depth)?;
|
||||
items.push((key, v));
|
||||
}
|
||||
Ok(Descriptor { class_name, class_id, items })
|
||||
}
|
||||
|
||||
fn read_value(r: &mut Reader, ty: &[u8; 4], depth: usize) -> Result<DValue> {
|
||||
if depth > 64 {
|
||||
return Err(Error::Invalid("descriptor nesting".into()));
|
||||
fn id_str(id: &craft_psd::descriptor::Id) -> String {
|
||||
String::from_utf8_lossy(id.as_bytes()).into_owned()
|
||||
}
|
||||
|
||||
fn unit_str(u: &[u8; 4]) -> String {
|
||||
String::from_utf8_lossy(u).into_owned()
|
||||
}
|
||||
|
||||
fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor {
|
||||
Descriptor {
|
||||
class_name: d.name.to_string_lossy(),
|
||||
class_id: id_str(&d.class_id),
|
||||
items: d.items.into_iter().map(|(k, v)| (id_str(&k), from_craft_value(v))).collect(),
|
||||
}
|
||||
Ok(match ty {
|
||||
b"Objc" | b"GlbO" => DValue::Descriptor(read_descriptor_at(r, depth + 1)?),
|
||||
b"VlLs" => {
|
||||
let n = r.u32()? as usize;
|
||||
if n > 1_000_000 {
|
||||
return Err(Error::Invalid("descriptor list length".into()));
|
||||
}
|
||||
|
||||
fn from_craft_value(v: craft_psd::descriptor::Value) -> DValue {
|
||||
use craft_psd::descriptor::Value;
|
||||
match v {
|
||||
Value::Descriptor(d) | Value::GlobalObject(d) => DValue::Descriptor(from_craft_descriptor(d)),
|
||||
Value::List(l) => DValue::List(l.into_iter().map(from_craft_value).collect()),
|
||||
Value::Double(x) => DValue::Double(if x.is_finite() { x } else { 0.0 }),
|
||||
Value::UnitFloat { unit, value } => DValue::UnitFloat(unit_str(&unit), if value.is_finite() { value } else { 0.0 }),
|
||||
Value::UnitFloats { unit, values } => DValue::UnitFloats(unit_str(&unit), values.into_iter().map(|x| if x.is_finite() { x } else { 0.0 }).collect()),
|
||||
Value::Text(s) => DValue::Text(s.to_string_lossy()),
|
||||
Value::Enumerated { type_id, value } => DValue::Enum(id_str(&type_id), id_str(&value)),
|
||||
Value::Integer(i) => DValue::Integer(i),
|
||||
Value::LargeInteger(i) => DValue::LargeInteger(i),
|
||||
Value::Boolean(b) => DValue::Bool(b),
|
||||
Value::Class(c) | Value::GlobalClass(c) => DValue::Class(c.name.to_string_lossy(), id_str(&c.class_id)),
|
||||
Value::Alias(b) | Value::Path(b) | Value::RawData(b) => DValue::Raw(b),
|
||||
Value::ObjectArray(o) => DValue::ObjectArray(o.prefix, from_craft_descriptor(o.body)),
|
||||
Value::Reference(items) => DValue::Reference(items.into_iter().map(from_craft_ref).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_reference_class(class: &craft_psd::descriptor::Class) -> bool {
|
||||
class.name.0 == [0] && class.class_id == craft_psd::descriptor::Id::Code(*b"null")
|
||||
}
|
||||
|
||||
fn from_craft_ref(it: craft_psd::descriptor::ReferenceItem) -> RefItem {
|
||||
use craft_psd::descriptor::ReferenceItem;
|
||||
match it {
|
||||
ReferenceItem::Property { class, key } => RefItem::Property(id_str(&class.class_id), id_str(&key)),
|
||||
ReferenceItem::Class(c) => RefItem::Class(id_str(&c.class_id)),
|
||||
ReferenceItem::Enumerated { class, type_id, value } => RefItem::Enum(id_str(&class.class_id), id_str(&type_id), id_str(&value)),
|
||||
ReferenceItem::Offset { class, offset } => RefItem::Offset(id_str(&class.class_id), offset),
|
||||
ReferenceItem::Identifier { class, id } => {
|
||||
if legacy_reference_class(&class) {
|
||||
RefItem::Identifier(id as i32)
|
||||
} else {
|
||||
RefItem::IdentifierWithClass(class, id as i32)
|
||||
}
|
||||
let mut v = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
let t = r.tag()?;
|
||||
v.push(read_value(r, &t, depth + 1)?);
|
||||
}
|
||||
ReferenceItem::Index { class, index } => {
|
||||
if legacy_reference_class(&class) {
|
||||
RefItem::Index(index as i32)
|
||||
} else {
|
||||
RefItem::IndexWithClass(class, index as i32)
|
||||
}
|
||||
DValue::List(v)
|
||||
}
|
||||
b"ObAr" => {
|
||||
let n = r.u32()?;
|
||||
DValue::ObjectArray(n, read_descriptor_at(r, depth + 1)?)
|
||||
}
|
||||
b"doub" => DValue::Double(r.f64_finite()?),
|
||||
b"UntF" => {
|
||||
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
|
||||
DValue::UnitFloat(unit, r.f64_finite()?)
|
||||
}
|
||||
b"UnFl" => {
|
||||
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
|
||||
let n = r.u32()? as usize;
|
||||
let mut v = Vec::with_capacity(n.min(1024));
|
||||
for _ in 0..n {
|
||||
v.push(r.f64_finite()?);
|
||||
}
|
||||
DValue::UnitFloats(unit, v)
|
||||
}
|
||||
b"TEXT" => DValue::Text(read_unicode(r)?),
|
||||
b"enum" => {
|
||||
let t = read_id(r)?;
|
||||
DValue::Enum(t, read_id(r)?)
|
||||
}
|
||||
b"long" => DValue::Integer(r.u32()? as i32),
|
||||
b"comp" => DValue::LargeInteger(r.u64()? as i64),
|
||||
b"bool" => DValue::Bool(r.u8()? != 0),
|
||||
b"type" | b"GlbC" => {
|
||||
let name = read_unicode(r)?;
|
||||
DValue::Class(name, read_id(r)?)
|
||||
}
|
||||
b"alis" | b"tdta" | b"Pth " => {
|
||||
let n = r.u32()? as usize;
|
||||
DValue::Raw(r.bytes(n)?.to_vec())
|
||||
}
|
||||
b"obj " => {
|
||||
let n = r.u32()? as usize;
|
||||
let mut items = Vec::with_capacity(n.min(16));
|
||||
for _ in 0..n {
|
||||
let t = r.tag()?;
|
||||
items.push(match &t {
|
||||
b"prop" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Property(class, read_id(r)?)
|
||||
}
|
||||
b"Clss" => {
|
||||
let _name = read_unicode(r)?;
|
||||
RefItem::Class(read_id(r)?)
|
||||
}
|
||||
b"Enmr" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
let ty = read_id(r)?;
|
||||
RefItem::Enum(class, ty, read_id(r)?)
|
||||
}
|
||||
b"rele" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Offset(class, r.u32()? as i32)
|
||||
}
|
||||
b"Idnt" => RefItem::Identifier(r.u32()? as i32),
|
||||
b"indx" => RefItem::Index(r.u32()? as i32),
|
||||
b"name" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Name(class, read_unicode(r)?)
|
||||
}
|
||||
other => return Err(Error::Invalid(format!("reference item `{}`", String::from_utf8_lossy(other)))),
|
||||
});
|
||||
}
|
||||
DValue::Reference(items)
|
||||
}
|
||||
other => return Err(Error::Invalid(format!("descriptor type `{}`", String::from_utf8_lossy(other)))),
|
||||
})
|
||||
ReferenceItem::Name { class, name } => RefItem::Name(id_str(&class.class_id), name.to_string_lossy()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
@@ -387,13 +353,28 @@ fn write_value(out: &mut Vec<u8>, v: &DValue) {
|
||||
out.extend_from_slice(&o.to_be_bytes());
|
||||
}
|
||||
RefItem::Identifier(i) => {
|
||||
// Photoshop stores a class before the id; craft-psd reads it that way.
|
||||
out.extend_from_slice(b"Idnt");
|
||||
put_unicode(out, "");
|
||||
put_id(out, "null");
|
||||
out.extend_from_slice(&i.to_be_bytes());
|
||||
}
|
||||
RefItem::Index(i) => {
|
||||
out.extend_from_slice(b"indx");
|
||||
put_unicode(out, "");
|
||||
put_id(out, "null");
|
||||
out.extend_from_slice(&i.to_be_bytes());
|
||||
}
|
||||
RefItem::IdentifierWithClass(class, id) => {
|
||||
out.extend_from_slice(b"Idnt");
|
||||
put_reference_class(out, class);
|
||||
out.extend_from_slice(&id.to_be_bytes());
|
||||
}
|
||||
RefItem::IndexWithClass(class, index) => {
|
||||
out.extend_from_slice(b"indx");
|
||||
put_reference_class(out, class);
|
||||
out.extend_from_slice(&index.to_be_bytes());
|
||||
}
|
||||
RefItem::Name(c, n) => {
|
||||
out.extend_from_slice(b"name");
|
||||
put_unicode(out, "");
|
||||
@@ -406,6 +387,19 @@ fn write_value(out: &mut Vec<u8>, v: &DValue) {
|
||||
}
|
||||
}
|
||||
|
||||
fn put_reference_class(out: &mut Vec<u8>, class: &craft_psd::descriptor::Class) {
|
||||
out.extend_from_slice(&(class.name.0.len() as u32).to_be_bytes());
|
||||
for unit in &class.name.0 {
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
let length = match &class.class_id {
|
||||
craft_psd::descriptor::Id::Code(_) => 0,
|
||||
craft_psd::descriptor::Id::Str(bytes) => bytes.len() as u32,
|
||||
};
|
||||
out.extend_from_slice(&length.to_be_bytes());
|
||||
out.extend_from_slice(class.class_id.as_bytes());
|
||||
}
|
||||
|
||||
fn tag4(s: &str) -> [u8; 4] {
|
||||
let mut t = *b" ";
|
||||
for (i, b) in s.bytes().take(4).enumerate() {
|
||||
|
||||
+15
-32
@@ -1,7 +1,5 @@
|
||||
use super::limits::{Error, Result};
|
||||
use super::model::{
|
||||
Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask,
|
||||
};
|
||||
use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask};
|
||||
use super::{Psd, Reader, descriptor, engine_data, placed};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -70,7 +68,7 @@ impl Psd {
|
||||
}
|
||||
if let Some(info) = &file.layer_info {
|
||||
psd.merged_alpha = info.merged_alpha;
|
||||
psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect();
|
||||
psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect::<Result<Vec<_>>>()?;
|
||||
}
|
||||
for b in &file.global_blocks {
|
||||
if let Some(stored) = b.stored.as_ref().filter(|_| linked(&b.key, 0)) {
|
||||
@@ -83,7 +81,7 @@ impl Psd {
|
||||
|
||||
/// One layer record of the model, its additional information read into [`Layer`].
|
||||
/// `splice` maps craft-psd's offsets back into `self.data` (see [`read_file`]).
|
||||
fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Layer {
|
||||
fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Result<Layer> {
|
||||
let channels = rec
|
||||
.channels
|
||||
.iter()
|
||||
@@ -113,10 +111,15 @@ impl Psd {
|
||||
}
|
||||
for b in &rec.blocks {
|
||||
l.keys.push(b.key);
|
||||
// A malformed block only loses that block's information.
|
||||
let _ = self.layer_block(&mut l, &b.key, &b.data);
|
||||
// A malformed optional block only loses that block's information.
|
||||
// Unsupported modern placement geometry must not silently become an
|
||||
// unwarped layer or fall back to a less expressive PlLd in either order.
|
||||
match self.layer_block(&mut l, &b.key, &b.data) {
|
||||
Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
l
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
/// The embedded bytes of linked file `uuid`.
|
||||
@@ -236,32 +239,12 @@ impl Psd {
|
||||
l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned()));
|
||||
}
|
||||
b"SoLd" | b"SoLE" => {
|
||||
let _id = r.tag()?;
|
||||
let _ver = r.u32()?;
|
||||
let _dver = r.u32()?;
|
||||
let d = descriptor::read_descriptor(&mut r)?;
|
||||
let uuid = d.text("Idnt").unwrap_or_default().to_string();
|
||||
let t = placed::eight(&d, "Trnf").unwrap_or([0.0; 8]);
|
||||
// The non-affine transform when present (perspective), else the transform.
|
||||
let t = placed::eight(&d, "nonAffineTransform").unwrap_or(t);
|
||||
let size = d.obj("Sz ").and_then(|s| Some([s.num("Wdth")?, s.num("Hght")?]));
|
||||
let warp = d.obj("warp").and_then(placed::Warp::read);
|
||||
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size, warp });
|
||||
l.smart_object = Some(placed::from_craft_smart(
|
||||
craft_psd::smart::SmartObject::from_placed_layer_data_with_limits(b, crate::descriptor::PARSE_LIMITS).map_err(|e| error(&e))?,
|
||||
));
|
||||
}
|
||||
b"PlLd" if l.smart_object.is_none() => {
|
||||
let _id = r.tag()?;
|
||||
let _ver = r.u32()?;
|
||||
let n = r.u8()? as usize;
|
||||
let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned();
|
||||
let _page = r.u32()?;
|
||||
let _pages = r.u32()?;
|
||||
let _aa = r.u32()?;
|
||||
let _ty = r.u32()?;
|
||||
let mut t = [0.0; 8];
|
||||
for v in &mut t {
|
||||
*v = r.f64_finite()?;
|
||||
}
|
||||
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size: None, warp: None });
|
||||
l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?));
|
||||
}
|
||||
b"vmsk" | b"vsms" => {
|
||||
let _ver = r.u32()?;
|
||||
|
||||
+43
-113
@@ -14,14 +14,7 @@ use crate::{Pixels, SmartObject};
|
||||
|
||||
/// The most pixels a baked smart object may have: 2^24 (256 MiB as float RGBA). The size comes
|
||||
/// from the file's transform, which is untrusted.
|
||||
pub const MAX_BAKE_PIXELS: u64 = 1 << 24;
|
||||
|
||||
/// The bake's rasterising budget, in bounding-box pixels visited over all mesh triangles, as a
|
||||
/// multiple of the output pixel count. A sane warp visits about 2× the output; a hostile mesh
|
||||
/// that makes every triangle cover the whole output would visit thousands of times more.
|
||||
const BAKE_WORK_FACTOR: u64 = 8;
|
||||
/// The smallest budget, so tiny outputs are never refused for rounding at the triangle edges.
|
||||
const MIN_BAKE_WORK: u64 = 1 << 20;
|
||||
pub const MAX_BAKE_PIXELS: u64 = craft_psd::smart::MAX_BAKE_PIXELS;
|
||||
|
||||
/// A placed layer's warp.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -61,14 +54,40 @@ pub(crate) fn floats(v: Option<&DValue>) -> Vec<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight.
|
||||
pub(crate) fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> {
|
||||
floats(d.get(key)).try_into().ok()
|
||||
pub(crate) fn from_craft_smart(s: craft_psd::smart::SmartObject) -> SmartObject {
|
||||
SmartObject { uuid: s.uuid, quad: s.quad, size: s.size, warp: s.warp.map(from_craft_warp) }
|
||||
}
|
||||
|
||||
/// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3.
|
||||
pub(crate) fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] {
|
||||
[[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]]
|
||||
fn from_craft_warp(w: craft_psd::smart::Warp) -> Warp {
|
||||
Warp {
|
||||
style: w.style,
|
||||
bend: w.bend,
|
||||
horizontal: w.horizontal,
|
||||
vertical: w.vertical,
|
||||
rotate_vertical: w.rotate_vertical,
|
||||
bounds: w.bounds,
|
||||
cols: w.cols,
|
||||
rows: w.rows,
|
||||
mesh: w.mesh,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_craft_smart(s: &SmartObject) -> craft_psd::smart::SmartObject {
|
||||
craft_psd::smart::SmartObject { uuid: s.uuid.clone(), quad: s.quad, size: s.size, warp: s.warp.as_ref().map(to_craft_warp) }
|
||||
}
|
||||
|
||||
fn to_craft_warp(w: &Warp) -> craft_psd::smart::Warp {
|
||||
craft_psd::smart::Warp {
|
||||
style: w.style.clone(),
|
||||
bend: w.bend,
|
||||
horizontal: w.horizontal,
|
||||
vertical: w.vertical,
|
||||
rotate_vertical: w.rotate_vertical,
|
||||
bounds: w.bounds,
|
||||
cols: w.cols,
|
||||
rows: w.rows,
|
||||
mesh: w.mesh.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Warp {
|
||||
@@ -111,7 +130,13 @@ impl Warp {
|
||||
|
||||
/// The warp of a content point (content pixels → content pixels).
|
||||
pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] {
|
||||
let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
// Keep the local mapping facade aligned with the shared bake evaluator.
|
||||
let valid_bounds = self.bounds.iter().all(|x| x.is_finite())
|
||||
&& (self.bounds[2] - self.bounds[0]).is_finite()
|
||||
&& self.bounds[2] > self.bounds[0]
|
||||
&& (self.bounds[3] - self.bounds[1]).is_finite()
|
||||
&& self.bounds[3] > self.bounds[1];
|
||||
let [l, t, r, b] = if valid_bounds { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
let (bw, bh) = (r - l, b - t);
|
||||
let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh);
|
||||
if self.style == "warpCustom" {
|
||||
@@ -313,105 +338,10 @@ impl SmartObject {
|
||||
/// `k` pixels per document pixel (into `size` pixels when given; see [`Self::placed_size`]).
|
||||
/// Returns the pixels and their document-space origin. `None` when the content is empty or
|
||||
/// the baked image would exceed [`MAX_BAKE_PIXELS`] or the mesh needs more rasterising work than
|
||||
/// the budget allows (see [`BAKE_WORK_FACTOR`]).
|
||||
/// the budget allows.
|
||||
pub fn render_placed(&self, content: &Pixels, k: f64, size: Option<(u32, u32)>) -> Option<(Pixels, [f64; 2])> {
|
||||
let (cw, ch) = (content.width as f64, content.height as f64);
|
||||
if content.width == 0 || content.height == 0 {
|
||||
return None;
|
||||
}
|
||||
// The quad is solved once for the bounds, the size and the whole grid.
|
||||
let m = square_to_quad(self.quad);
|
||||
let bb = self.bounds_with(&m, cw, ch);
|
||||
let (ow, oh) = match size {
|
||||
Some((w, h)) => (w.max(1), h.max(1)),
|
||||
None => size_for(bb, k),
|
||||
};
|
||||
let (ow, oh) = (ow as usize, oh as usize);
|
||||
let count = ow.checked_mul(oh).filter(|&c| c as u64 <= MAX_BAKE_PIXELS)?;
|
||||
// A forward grid, filled triangle by triangle with inverse barycentric sampling.
|
||||
let n = 48usize;
|
||||
let mut dst = Vec::with_capacity((n + 1) * (n + 1));
|
||||
let mut src = Vec::with_capacity((n + 1) * (n + 1));
|
||||
for j in 0..=n {
|
||||
for i in 0..=n {
|
||||
let s = [i as f64 / n as f64 * cw, j as f64 / n as f64 * ch];
|
||||
let d = self.map_with(&m, s, cw, ch);
|
||||
dst.push([(d[0] - bb[0]) * k, (d[1] - bb[1]) * k]);
|
||||
src.push(s);
|
||||
}
|
||||
}
|
||||
let mut out: Vec<[f32; 4]> = Vec::new();
|
||||
out.try_reserve_exact(count).ok()?;
|
||||
out.resize(count, [0.0; 4]);
|
||||
let sample = |x: f64, y: f64| -> [f32; 4] {
|
||||
let (fx, fy) = ((x - 0.5).clamp(0.0, cw - 1.0), (y - 0.5).clamp(0.0, ch - 1.0));
|
||||
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(content.width as usize - 1), (y0 + 1).min(content.height as usize - 1));
|
||||
let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
|
||||
let at = |x: usize, y: usize| {
|
||||
let p = content.data[y * content.width as usize + x];
|
||||
[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]
|
||||
};
|
||||
let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
|
||||
let mut o = [0.0; 4];
|
||||
for c in 0..4 {
|
||||
o[c] = (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b;
|
||||
}
|
||||
o
|
||||
};
|
||||
let idx = |i: usize, j: usize| j * (n + 1) + i;
|
||||
// A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to
|
||||
// whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so
|
||||
// allow each of the 2n² triangles about two cells' extent along each axis, with margin.
|
||||
let rounding = (4 * n as u64).saturating_mul((ow as u64).saturating_add(oh as u64).saturating_add(n as u64));
|
||||
let budget = (count as u64).saturating_mul(BAKE_WORK_FACTOR).max(MIN_BAKE_WORK).saturating_add(rounding);
|
||||
let mut work = 0u64;
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
for tri in [[idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)], [idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)]] {
|
||||
let [a, b, c] = tri.map(|t| dst[t]);
|
||||
let den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
|
||||
if den.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
// Loop-invariant per triangle: the source corners and the barycentric coefficients.
|
||||
let [sa, sb, sc] = tri.map(|t| src[t]);
|
||||
let (l1y, l1x) = (b[1] - c[1], c[0] - b[0]);
|
||||
let (l2y, l2x) = (c[1] - a[1], a[0] - c[0]);
|
||||
let x0 = a[0].min(b[0]).min(c[0]).floor().max(0.0) as usize;
|
||||
let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(ow);
|
||||
let y0 = a[1].min(b[1]).min(c[1]).floor().max(0.0) as usize;
|
||||
let y1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(oh);
|
||||
work = work.saturating_add((x1.saturating_sub(x0) as u64).saturating_mul(y1.saturating_sub(y0) as u64));
|
||||
if work > budget {
|
||||
return None;
|
||||
}
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let l1 = (l1y * (px - c[0]) + l1x * (py - c[1])) / den;
|
||||
let l2 = (l2y * (px - c[0]) + l2x * (py - c[1])) / den;
|
||||
let l3 = 1.0 - l1 - l2;
|
||||
if l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9 {
|
||||
continue;
|
||||
}
|
||||
let sx = sa[0] * l1 + sb[0] * l2 + sc[0] * l3;
|
||||
let sy = sa[1] * l1 + sb[1] * l2 + sc[1] * l3;
|
||||
out[y * ow + x] = sample(sx, sy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Back to straight alpha.
|
||||
for p in &mut out {
|
||||
if p[3] > 0.0 {
|
||||
for c in 0..3 {
|
||||
p[c] /= p[3];
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((Pixels { width: ow as u32, height: oh as u32, data: out }, [bb[0], bb[1]]))
|
||||
let (out, origin) = to_craft_smart(self).render_placed_pixels(content.width, content.height, &content.data, k, size)?;
|
||||
Some((Pixels { width: out.width, height: out.height, data: out.data }, origin))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,3 +92,51 @@ fn a_tiny_file_claiming_a_huge_image_is_refused_within_the_budget() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_modern_placement_does_not_fall_back_to_legacy_in_either_order() {
|
||||
use craft_psd::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor};
|
||||
let quad = [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]];
|
||||
let legacy = craft_psd::smart::SmartObject { uuid: "legacy".into(), quad, size: Some([20.0, 10.0]), warp: None }.to_placed_layer();
|
||||
let modern = |middle| {
|
||||
let floats = |values| Value::UnitFloats { unit: *b"#Pxl", values };
|
||||
let points = Descriptor::new("rationalPoint")
|
||||
.with("Hrzn", floats((0..4).flat_map(|_| (0..7).map(|i| i as f64 * 20.0 / 6.0)).collect()))
|
||||
.with("Vrtc", floats((0..4).flat_map(|j| [j as f64 * 10.0 / 3.0; 7]).collect()));
|
||||
let envelope = Descriptor::new("customEnvelopeWarp")
|
||||
.with("quiltSliceX", floats(vec![0.0, middle, 20.0]))
|
||||
.with("quiltSliceY", floats(vec![0.0, 10.0]))
|
||||
.with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 28, body: points }));
|
||||
let warp = Descriptor::new("quiltWarp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") })
|
||||
.with("customEnvelopeWarp", Value::Descriptor(envelope));
|
||||
let descriptor = Descriptor::new("null")
|
||||
.with("Idnt", Value::Text(UnicodeString::new("modern")))
|
||||
.with("Trnf", Value::List(quad.iter().flatten().map(|v| Value::Double(*v)).collect()))
|
||||
.with("quiltWarp", Value::Descriptor(warp));
|
||||
let mut bytes = b"soLD".to_vec();
|
||||
bytes.extend_from_slice(&4u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&VersionedDescriptor::new(descriptor).to_bytes());
|
||||
bytes
|
||||
};
|
||||
for key in [*b"SoLd", *b"SoLE"] {
|
||||
for legacy_first in [false, true] {
|
||||
for (bytes, expected) in [(modern(5.0), None), (modern(10.0), Some("modern")), (b"soLD".to_vec(), Some("legacy"))] {
|
||||
let mut blocks = vec![(key, bytes), (*b"PlLd", legacy.clone()), (*b"luni", vec![0])];
|
||||
if legacy_first {
|
||||
blocks.swap(0, 1);
|
||||
}
|
||||
let mut doc = WDoc::new(2, 2);
|
||||
doc.layers = vec![WLayer::empty("placement", blocks)];
|
||||
let result = Psd::parse(write(&doc));
|
||||
if let Some(uuid) = expected {
|
||||
let parsed = result.unwrap();
|
||||
assert_eq!(parsed.layers[0].smart_object.as_ref().unwrap().uuid, uuid);
|
||||
assert_eq!(parsed.layers[0].name, "placement", "malformed optional metadata still recovers");
|
||||
} else {
|
||||
assert!(matches!(result, Err(Error::Unsupported(_))), "unsupported modern placement must be reported");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
-3
@@ -641,11 +641,11 @@ fn placed_bake_solves_the_quad_once() {
|
||||
assert_eq!(counters::take(&QUAD), 1, "33×33 mapped points, one solve (was 1089)");
|
||||
so.placed_size(20.0, 10.0, 1.0);
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
// The bounds, the size and the 49×49 grid of one bake share a single solve (was 1089 × 2 + 2401).
|
||||
// The bake itself runs in craft-psd, so it no longer bumps this crate's quad counter.
|
||||
so.render_placed(&content(20, 10), 1.0, None).unwrap();
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
assert_eq!(counters::take(&QUAD), 0);
|
||||
so.render_placed(&content(20, 10), 1.0, Some((40, 40))).unwrap();
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
assert_eq!(counters::take(&QUAD), 0);
|
||||
// A single `map` still solves for itself.
|
||||
so.map([1.0, 1.0], 20.0, 10.0);
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
@@ -668,3 +668,107 @@ fn shared_unpredict_keeps_tail_bytes_and_refuses_unbudgeted_scratch() {
|
||||
assert!(p.unpredict(&mut bytes, 3, 2, &mut Budget::new(11)).is_err());
|
||||
assert_eq!(bytes, vec![0x31; 24], "budget refusal precedes mutation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_descriptor_parser_preserves_application_count_limits() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Value};
|
||||
let mut bytes = Shared::new("test").to_bytes();
|
||||
let end = bytes.len();
|
||||
bytes[end - 4..].copy_from_slice(&100_001u32.to_be_bytes());
|
||||
let error = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap_err();
|
||||
assert!(matches!(error, Error::Invalid(ref message) if message.contains("too many descriptor items")));
|
||||
let mut bytes = Shared::new("test").with("list", Value::List(vec![])).to_bytes();
|
||||
let end = bytes.len();
|
||||
bytes[end - 4..].copy_from_slice(&1_000_001u32.to_be_bytes());
|
||||
let error = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap_err();
|
||||
assert!(matches!(error, Error::Invalid(ref message) if message.contains("too many descriptor list items")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_bake_keeps_the_borrowed_source_available_on_rejection() {
|
||||
let object = SmartObject { uuid: String::new(), quad: [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]], size: None, warp: None };
|
||||
let source = Pixels { width: 2, height: 2, data: vec![[1.0, 0.5, 0.25, 0.5]; 4] };
|
||||
let original = source.data.clone();
|
||||
let ptr = source.data.as_ptr();
|
||||
assert!(object.render_placed(&source, 1.0, Some((u32::MAX, u32::MAX))).is_none());
|
||||
assert_eq!(source.data, original);
|
||||
assert_eq!(source.data.as_ptr(), ptr);
|
||||
assert!(object.render_placed(&source, 1.0, Some((2, 2))).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifier_and_index_references_preserve_non_null_classes_exactly() {
|
||||
use craft_psd::descriptor::{Class, Descriptor as Shared, Id, ReferenceItem, UnicodeString, Value};
|
||||
for class in [
|
||||
Class { name: UnicodeString(vec![0xD800, 0]), class_id: Id::Code(*b"Lyr ") },
|
||||
Class { name: UnicodeString::default(), class_id: Id::Code(*b"null") },
|
||||
Class { name: UnicodeString::default(), class_id: Id::Str(b"null".to_vec()) },
|
||||
Class { name: UnicodeString(vec![0]), class_id: Id::Code(*b"null") },
|
||||
] {
|
||||
let mut original = Shared::new("test")
|
||||
.with("refs", Value::Reference(vec![ReferenceItem::Identifier { class: class.clone(), id: u32::MAX }, ReferenceItem::Index { class, index: 7 }]));
|
||||
original.name = UnicodeString(vec![0]);
|
||||
let bytes = original.to_bytes();
|
||||
let local = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap();
|
||||
let mut out = Vec::new();
|
||||
crate::descriptor::write_descriptor(&mut out, &local);
|
||||
assert_eq!(Shared::from_bytes(&out).unwrap(), original);
|
||||
assert_eq!(out, bytes);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn shared_descriptor_nesting_preserves_the_application_boundary() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Value};
|
||||
for count in [33, 64, 65] {
|
||||
let mut value = Value::Integer(1);
|
||||
for _ in 0..count {
|
||||
value = Value::Descriptor(Shared::new("null").with("next", value));
|
||||
}
|
||||
let bytes = Shared::new("null").with("root", value).to_bytes();
|
||||
let result = crate::descriptor::read_descriptor(&mut Reader::new(&bytes));
|
||||
assert_eq!(result.is_ok(), count <= 64, "nested descriptor count {count}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_placed_layer_adapter_normalizes_before_warp_classification() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Id, Value};
|
||||
let warp = Shared::new("warp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpArc") })
|
||||
.with("warpValue", Value::Double(f64::NAN))
|
||||
.with("warpPerspective", Value::Double(f64::INFINITY))
|
||||
.with("warpPerspectiveOther", Value::Double(f64::NEG_INFINITY));
|
||||
let quad = [f64::NAN, 0.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0];
|
||||
let descriptor = Shared::new("null").with("Trnf", Value::List(quad.into_iter().map(Value::Double).collect())).with("warp", Value::Descriptor(warp));
|
||||
let mut bytes = b"soLD".to_vec();
|
||||
bytes.extend_from_slice(&4u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&16u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&descriptor.to_bytes());
|
||||
let shared = craft_psd::smart::SmartObject::from_placed_layer_data_with_limits(&bytes, crate::descriptor::PARSE_LIMITS).unwrap();
|
||||
let object = crate::placed::from_craft_smart(shared);
|
||||
assert_eq!(object.quad, [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]);
|
||||
assert!(object.warp.is_none(), "normalization must precede identity classification");
|
||||
assert!(!object.needs_bake());
|
||||
assert_eq!(object.map([10.0, 5.0], 20.0, 10.0), [10.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_and_shared_warp_mapping_agree_on_overflowing_bounds() {
|
||||
let mesh: Vec<_> = (0..4).flat_map(|j| (0..4).map(move |i| [i as f64 * 20.0 / 3.0, j as f64 * 10.0 / 3.0])).collect();
|
||||
for bounds in [[-f64::MAX, 0.0, f64::MAX, 10.0], [0.0, -f64::MAX, 20.0, f64::MAX]] {
|
||||
let shared = craft_psd::smart::SmartObject {
|
||||
uuid: String::new(),
|
||||
quad: [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]],
|
||||
size: Some([20.0, 10.0]),
|
||||
warp: Some(craft_psd::smart::Warp { style: "warpCustom".into(), bounds, cols: 1, rows: 1, mesh: mesh.clone(), ..Default::default() }),
|
||||
};
|
||||
let local = crate::placed::from_craft_smart(shared.clone());
|
||||
for point in [[5.0, 2.5], [10.0, 5.0], [15.0, 7.5]] {
|
||||
let actual = local.map(point, 20.0, 10.0);
|
||||
assert_eq!(actual, shared.map(point, 20.0, 10.0));
|
||||
for axis in 0..2 {
|
||||
assert!((actual[axis] - point[axis]).abs() < 1e-9, "{bounds:?} {point:?}: {actual:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+288
-4
@@ -182,6 +182,141 @@ pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> I
|
||||
box_passes(img, &rx, &ry, repeat)
|
||||
}
|
||||
|
||||
/// [`gaussian_blur`] with transparent edges, as if the image went on with transparency on
|
||||
/// every side: what a box pass spreads past the edge still feeds the passes after it, where
|
||||
/// [`gaussian_blur`] drops it. For blurs that reach past the buffer holding them (an effect's
|
||||
/// padding cut to its pixel budget), which [`gaussian_blur`] leaves far too faint once the
|
||||
/// boxes are wider than the buffer. A line costs O(length) whatever the sigma.
|
||||
pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image {
|
||||
gaussian_blur_unbounded_at(img, sigma_x, sigma_y, [0, 0], img.width, img.height)
|
||||
}
|
||||
|
||||
/// [`gaussian_blur_unbounded`] of `img` moved by `shift` pixels, seen through a `width` ×
|
||||
/// `height` window at the origin: output `(x, y)` is the blurred plane at
|
||||
/// `(x − shift[0], y − shift[1])`. Nothing is cut before the blur, so the tails of content
|
||||
/// that lands outside the window still reach into it.
|
||||
pub fn gaussian_blur_unbounded_at(img: &Image, sigma_x: f64, sigma_y: f64, shift: [i64; 2], width: u32, height: u32) -> Image {
|
||||
let (w, h, ow, oh) = (img.width as usize, img.height as usize, width as usize, height as usize);
|
||||
if w == 0 || h == 0 || ow == 0 || oh == 0 {
|
||||
return Image::new(width, height);
|
||||
}
|
||||
let (rx, ry) = (unbounded_radii(sigma_x).unwrap_or_default(), unbounded_radii(sigma_y).unwrap_or_default());
|
||||
// Horizontal: each source row into a row of the window's width.
|
||||
let mut rows = vec![[0.0f32; 4]; ow.saturating_mul(h)];
|
||||
rows.par_chunks_mut(ow).zip(img.data.par_chunks(w)).for_each(|(o, src)| boxes_unbounded(src, &rx, shift[0], o));
|
||||
// Vertical: each of those columns into a column of the window's height.
|
||||
let cols: Vec<Vec<Px>> = (0..ow)
|
||||
.into_par_iter()
|
||||
.map(|x| {
|
||||
let col: Vec<Px> = rows.iter().skip(x).step_by(ow).copied().collect();
|
||||
let mut o = vec![[0.0f32; 4]; oh];
|
||||
boxes_unbounded(&col, &ry, shift[1], &mut o);
|
||||
o
|
||||
})
|
||||
.collect();
|
||||
// At most three buffers at once: the rows go before the output comes.
|
||||
drop(rows);
|
||||
let mut out = Image::new(width, height);
|
||||
out.data.par_chunks_mut(ow).enumerate().for_each(|(y, row)| {
|
||||
for (o, col) in row.iter_mut().zip(&cols) {
|
||||
if let Some(v) = col.get(y) {
|
||||
*o = *v;
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Above this sigma (pixels) [`gaussian_blur_unbounded`] blurs as if it were this: far wider
|
||||
/// than any buffer ([`crate::MAX_PADDED_SIDE`]), and small enough for [`box_radii`]'s `i64`
|
||||
/// arithmetic (which overflows near 9e8).
|
||||
const UNBOUNDED_SIGMA_MAX: f64 = 1e7;
|
||||
|
||||
/// [`gaussian_blur`]'s box radii for `sigma` without the zero ones (each an identity), or
|
||||
/// `None` where it doesn't blur (and for a sigma that isn't a number).
|
||||
fn unbounded_radii(sigma: f64) -> Option<Vec<i64>> {
|
||||
if sigma.is_nan() || sigma <= 0.05 {
|
||||
return None;
|
||||
}
|
||||
let radii: Vec<i64> = box_radii(sigma.min(UNBOUNDED_SIGMA_MAX), 3).into_iter().filter_map(|r| i64::try_from(r).ok()).filter(|&r| r > 0).collect();
|
||||
(!radii.is_empty()).then_some(radii)
|
||||
}
|
||||
|
||||
/// Transparent-edged box passes of radii `r` (up to three, none zero) over `line`, as if it
|
||||
/// went on with zeros, moved by `shift`: `out[x]` is the blurred line at `x − shift`.
|
||||
///
|
||||
/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so `k` boxes
|
||||
/// are `2^k` signed terms of the `k`-th prefix sum `Sk` (`S0` is the line). Before the line
|
||||
/// every `Sk` is 0; past it, `j = m − n + 1` steps on with `T` the line's total, they are
|
||||
/// polynomials: `S0(m) = 0`, `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`,
|
||||
/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. The sums are `f64`. `Sk` grows like `n^k`,
|
||||
/// so the cancelling terms leave a rounding error near `ε·n^k / (2r + 1)^k` of the values:
|
||||
/// under 1e-8 for any line a blur too wide for its buffer runs on.
|
||||
fn boxes_unbounded(line: &[Px], r: &[i64], shift: i64, out: &mut [Px]) {
|
||||
let (n, k) = (line.len(), r.len());
|
||||
let Ok(n_i) = i64::try_from(n) else { return };
|
||||
if n == 0 || k > 3 {
|
||||
return;
|
||||
}
|
||||
// sums[o] = the (o + 1)-th prefix sum so far.
|
||||
let mut sums = [[0.0f64; 4]; 3];
|
||||
let mut sk = Vec::with_capacity(n);
|
||||
for p in line {
|
||||
let v = p.map(f64::from);
|
||||
for c in 0..4 {
|
||||
sums[0][c] += v[c];
|
||||
sums[1][c] += sums[0][c];
|
||||
sums[2][c] += sums[1][c];
|
||||
}
|
||||
sk.push(match k {
|
||||
0 => v,
|
||||
_ => sums[k - 1],
|
||||
});
|
||||
}
|
||||
let at = |m: i64| -> [f64; 4] {
|
||||
if m < 0 {
|
||||
return [0.0; 4];
|
||||
}
|
||||
if let Some(v) = usize::try_from(m).ok().and_then(|i| sk.get(i)) {
|
||||
return *v;
|
||||
}
|
||||
let j = (m - n_i + 1) as f64;
|
||||
std::array::from_fn(|c| match k {
|
||||
0 => 0.0,
|
||||
1 => sums[0][c],
|
||||
2 => sums[1][c] + j * sums[0][c],
|
||||
_ => sums[2][c] + j * sums[1][c] + sums[0][c] * j * (j + 1.0) / 2.0,
|
||||
})
|
||||
};
|
||||
// The offsets and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`.
|
||||
let terms: Vec<(i64, f64)> = (0..1usize << k)
|
||||
.map(|bits| {
|
||||
r.iter().enumerate().fold((0i64.saturating_sub(shift), 1.0f64), |(at, sign), (b, &ri)| {
|
||||
if bits >> b & 1 == 0 { (at.saturating_add(ri), sign) } else { (at.saturating_sub(ri.saturating_add(1)), -sign) }
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product();
|
||||
// The boxes read the line within `reach` of `x − shift`. Outside that the result is 0, and
|
||||
// the polynomials far past the line would only cancel to their rounding error.
|
||||
let reach = r.iter().fold(0i64, |s, &ri| s.saturating_add(ri));
|
||||
for (x, o) in (0i64..).zip(out.iter_mut()) {
|
||||
let c = x.saturating_sub(shift);
|
||||
if c.saturating_add(reach) < 0 || c.saturating_sub(reach) >= n_i {
|
||||
*o = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let mut v = [0.0f64; 4];
|
||||
for &(offset, sign) in &terms {
|
||||
let s = at(x.saturating_add(offset));
|
||||
for c in 0..4 {
|
||||
v[c] += sign * s[c];
|
||||
}
|
||||
}
|
||||
*o = v.map(|v| (v / norm) as f32);
|
||||
}
|
||||
}
|
||||
|
||||
/// Below this sigma (pixels) three integer-radius box passes are too coarse (sigma under ~0.6 is
|
||||
/// a no-op and the result steps between a few shapes), so [`gaussian_blur_exact`] is used instead.
|
||||
const EXACT_SIGMA_BELOW: f64 = 3.0;
|
||||
@@ -300,24 +435,50 @@ pub fn directional_blur(img: &Image, angle_deg: f64, length: f64) -> Image {
|
||||
out
|
||||
}
|
||||
|
||||
/// Samples [`radial_blur`] averages per pixel at every amount, so the work per pixel stays the
|
||||
/// same up to Radial Blur's largest Amount (1000). The GPU path takes the same count.
|
||||
pub const RADIAL_BLUR_SAMPLES: usize = 32;
|
||||
|
||||
/// Where sample `i` of [`RADIAL_BLUR_SAMPLES`] lies in the blur's spread, from −0.5 to 0.5.
|
||||
fn radial_blur_t(i: usize) -> f64 {
|
||||
i as f64 / (RADIAL_BLUR_SAMPLES - 1) as f64 - 0.5
|
||||
}
|
||||
|
||||
/// Spin sample `i`'s rotation in degrees for a spin of `amount` degrees.
|
||||
pub fn radial_blur_spin_degrees(i: usize, amount: f64) -> f64 {
|
||||
radial_blur_t(i) * amount
|
||||
}
|
||||
|
||||
/// Zoom sample `i`'s scale about the centre for a zoom of `amount` (a fraction of the distance
|
||||
/// to the centre): evenly over `1 ± amount / 2`. Past a spread of 2 (Radial Blur's Amount 200)
|
||||
/// that would reach below 0 and sample the point mirrored through the centre, so the samples
|
||||
/// spread evenly from the centre (0) to `1 + |amount| / 2` instead (#3467). That wider shape is
|
||||
/// EffectCraft's; After Effects has not been measured past Amount 200.
|
||||
pub fn radial_blur_zoom_scale(i: usize, amount: f64) -> f64 {
|
||||
let t = radial_blur_t(i);
|
||||
if amount.abs() <= 2.0 {
|
||||
return 1.0 + t * amount;
|
||||
}
|
||||
(t + 0.5) * (1.0 + amount.abs() / 2.0)
|
||||
}
|
||||
|
||||
/// Radial blur around `center`: `spin` (degrees) or zoom (`amount` as a fraction of distance).
|
||||
pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> Image {
|
||||
if amount.abs() < 1e-6 {
|
||||
return img.clone();
|
||||
}
|
||||
let n = 32usize;
|
||||
let n = RADIAL_BLUR_SAMPLES;
|
||||
let mut out = Image::new(img.width, img.height);
|
||||
out.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (vx, vy) = (x as f64 + 0.5 - center.0, y as f64 + 0.5 - center.1);
|
||||
let mut acc = [0.0f32; 4];
|
||||
for i in 0..n {
|
||||
let t = i as f64 / (n - 1) as f64 - 0.5;
|
||||
let (sx, sy) = if zoom {
|
||||
let k = 1.0 + t * amount;
|
||||
let k = radial_blur_zoom_scale(i, amount);
|
||||
(center.0 + vx * k, center.1 + vy * k)
|
||||
} else {
|
||||
let (s, c) = (t * amount).to_radians().sin_cos();
|
||||
let (s, c) = radial_blur_spin_degrees(i, amount).to_radians().sin_cos();
|
||||
(center.0 + vx * c - vy * s, center.1 + vx * s + vy * c)
|
||||
};
|
||||
// Samples outside the image repeat its edge: After Effects' Radial Blur keeps a
|
||||
@@ -337,6 +498,26 @@ pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Zoom spreads up to 2 keep `1 ± spread / 2` exactly as before (#3467); wider ones run
|
||||
/// from the centre (scale 0) out to `1 + spread / 2`, evenly and never below 0.
|
||||
#[test]
|
||||
fn radial_blur_zoom_scales_never_cross_the_centre() {
|
||||
let n = RADIAL_BLUR_SAMPLES;
|
||||
for amount in [0.2, 1.0, 2.0, -1.5] {
|
||||
for i in 0..n {
|
||||
let t = i as f64 / (n - 1) as f64 - 0.5;
|
||||
assert_eq!(radial_blur_zoom_scale(i, amount), 1.0 + t * amount, "amount {amount} sample {i}");
|
||||
}
|
||||
}
|
||||
for amount in [2.5, 10.0, -10.0] {
|
||||
let k: Vec<f64> = (0..n).map(|i| radial_blur_zoom_scale(i, amount)).collect();
|
||||
assert_eq!(k[0], 0.0, "amount {amount}");
|
||||
assert!((k[n - 1] - (1.0 + amount.abs() / 2.0)).abs() < 1e-12, "amount {amount}: {k:?}");
|
||||
let step = k[n - 1] / (n - 1) as f64;
|
||||
assert!(k.windows(2).all(|w| (w[1] - w[0] - step).abs() < 1e-12), "amount {amount}: {k:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampled Gaussian pass as it was (one pixel at a time, bounds-checked taps): the
|
||||
/// row-wise passes must match it to the bit.
|
||||
fn gauss_pass_per_pixel(img: &Image, sigma: f64, vertical: bool, repeat: bool) -> Image {
|
||||
@@ -520,4 +701,107 @@ mod tests {
|
||||
assert_eq!(r.len(), 3);
|
||||
assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}");
|
||||
}
|
||||
|
||||
/// #3464: moving the image before [`gaussian_blur_unbounded`] and blurring it moved with
|
||||
/// [`gaussian_blur_unbounded_at`] agree, also when the move puts all of it outside the window
|
||||
/// (its tails still reach in) and along an axis that isn't blurred.
|
||||
#[test]
|
||||
fn unbounded_gaussian_at_a_shift_matches_blurring_the_moved_image() {
|
||||
let mut img = Image::new(6, 5);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
let v = ((i * 37) % 11) as f32 / 11.0;
|
||||
*p = [v, 0.5 * v, 1.0 - v, 1.0];
|
||||
}
|
||||
let (ow, oh) = (14u32, 9u32);
|
||||
for (sx, sy, shift) in [(3.0, 2.0, [4i64, 2i64]), (5.0, 0.0, [-3, 1]), (12.0, 12.0, [-20, 16]), (8.0, 8.0, [25, -12])] {
|
||||
let got = gaussian_blur_unbounded_at(&img, sx, sy, shift, ow, oh);
|
||||
// The moved image in a canvas large enough to hold it and the window, blurred.
|
||||
let off = [40i64, 40i64];
|
||||
let mut canvas = Image::new(100, 100);
|
||||
for y in 0..img.height {
|
||||
for x in 0..img.width {
|
||||
let (cx, cy) = (i64::from(x) + shift[0] + off[0], i64::from(y) + shift[1] + off[1]);
|
||||
canvas.set(cx as u32, cy as u32, img.get(i64::from(x), i64::from(y)));
|
||||
}
|
||||
}
|
||||
let want = gaussian_blur_unbounded(&canvas, sx, sy).crop(off[0], off[1], ow, oh);
|
||||
assert!(got.data.iter().flatten().any(|v| *v > 1e-4), "{shift:?}: something reaches the window");
|
||||
for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) {
|
||||
assert!((a - b).abs() <= 1e-5, "σ ({sx}, {sy}) {shift:?}: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3464: a window the blur doesn't reach stays exactly transparent, however far the move
|
||||
/// (far past the line, the cancelling polynomials left a rounding residue of about 5).
|
||||
#[test]
|
||||
fn unbounded_gaussian_at_a_far_shift_is_exactly_transparent() {
|
||||
let img = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]);
|
||||
for shift in [[-1_000_000_030i64, 0i64], [0, 1_000_000_030], [i64::MIN, i64::MAX]] {
|
||||
let out = gaussian_blur_unbounded_at(&img, 1.5, 1.5, shift, 4, 3);
|
||||
assert!(out.data.iter().flatten().all(|v| *v == 0.0), "{shift:?}");
|
||||
}
|
||||
// Next to the window the tail still reaches in.
|
||||
assert!(gaussian_blur_unbounded_at(&img, 1.5, 1.5, [-1, 0], 4, 3).get(0, 0)[3] > 0.0);
|
||||
}
|
||||
|
||||
/// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no
|
||||
/// overflow in the radii. A NaN sigma leaves the axis alone.
|
||||
#[test]
|
||||
fn unbounded_gaussian_takes_any_sigma() {
|
||||
let mut img = Image::new(9, 7);
|
||||
img.set(4, 3, [1.0, 0.5, 0.25, 1.0]);
|
||||
let wide = gaussian_blur_unbounded(&img, 1e7, 1e7);
|
||||
for (sx, sy) in [(f64::INFINITY, f64::INFINITY), (1e300, 1e12)] {
|
||||
assert_eq!(gaussian_blur_unbounded(&img, sx, sy).data, wide.data, "σ ({sx}, {sy})");
|
||||
}
|
||||
assert!(wide.data.iter().flatten().all(|v| v.is_finite()));
|
||||
assert_eq!(gaussian_blur_unbounded(&img, f64::NAN, f64::NAN).data, img.data);
|
||||
}
|
||||
|
||||
/// #3464: [`gaussian_blur_unbounded`] is [`gaussian_blur`] on the image padded with enough
|
||||
/// transparency to hold every pass, cropped back: what a pass spreads past the edge comes
|
||||
/// back in the passes after it. Sigmas far wider than the image too, along each axis.
|
||||
#[test]
|
||||
fn unbounded_gaussian_matches_a_buffer_padded_past_its_reach() {
|
||||
let pattern = |w: u32, h: u32| {
|
||||
let mut img = Image::new(w, h);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
let v = ((i * 7919) % 101) as f32 / 101.0;
|
||||
*p = [v, v * 0.5, 1.0 - v, (v + 0.3).min(1.0)];
|
||||
}
|
||||
img
|
||||
};
|
||||
let cases = [
|
||||
(pattern(23, 17), 4.0f64, 0.0f64, 1e-4),
|
||||
(pattern(23, 17), 0.0, 6.0, 1e-4),
|
||||
(pattern(23, 17), 7.5, 3.2, 1e-4),
|
||||
(pattern(23, 17), 60.0, 45.0, 1e-4),
|
||||
// Zero radii (an identity) and one non-zero box among them.
|
||||
(pattern(23, 17), 0.5, 0.0, 1e-6),
|
||||
(pattern(23, 17), 0.0, 1.1, 1e-5),
|
||||
// The reference's f32 running sums drift over its 90 000-pixel line (by about 1.5e-4
|
||||
// of the value).
|
||||
(pattern(40, 1), 15000.0, 0.0, 1e-3),
|
||||
(pattern(1, 40), 0.0, 15000.0, 1e-3),
|
||||
];
|
||||
for (img, sx, sy, tol) in cases {
|
||||
// Three boxes of radius about σ each reach at most 3σ + 2. Padded by hand, along
|
||||
// the blurred axes only (`Image::padded` pads both and caps a side at 30000).
|
||||
let reach = |s: f64| if s > 0.0 { (s * 3.0 + 4.0).ceil() as u32 } else { 0 };
|
||||
let (px, py) = (reach(sx), reach(sy));
|
||||
let mut big = Image::new(img.width + 2 * px, img.height + 2 * py);
|
||||
for y in 0..img.height {
|
||||
for x in 0..img.width {
|
||||
big.set(x + px, y + py, img.get(x as i64, y as i64));
|
||||
}
|
||||
}
|
||||
let want = gaussian_blur(&big, sx, sy, false).crop(px as i64, py as i64, img.width, img.height);
|
||||
let got = gaussian_blur_unbounded(&img, sx, sy);
|
||||
let peak = want.data.iter().flatten().fold(0.0f32, |m, v| m.max(v.abs()));
|
||||
for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) {
|
||||
assert!((a - b).abs() <= tol * peak.max(1e-6), "σ ({sx}, {sy}) on {}×{}: {a} vs {b} (peak {peak})", img.width, img.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,10 @@ pub mod yuv;
|
||||
use effectcraft_color::{BlendMode, blend_pixel};
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur};
|
||||
pub use blur::{
|
||||
RADIAL_BLUR_SAMPLES, box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at,
|
||||
gaussian_is_exact, radial_blur, radial_blur_spin_degrees, radial_blur_zoom_scale,
|
||||
};
|
||||
pub use channels3d::AuxChannels;
|
||||
pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample};
|
||||
|
||||
|
||||
@@ -94,6 +94,11 @@ fn generates(l: &Layer) -> bool {
|
||||
audio_effect_groups(l).any(|(id, _)| audio_fx::generates_audio(id))
|
||||
}
|
||||
|
||||
/// Does an enabled audio effect (Backwards) play the layer's [in, out) span reversed?
|
||||
pub fn plays_backwards(l: &Layer) -> bool {
|
||||
audio_effect_groups(l).any(|(id, _)| audio_fx::reverses(id))
|
||||
}
|
||||
|
||||
/// Does the layer contribute to the mix (Audio switch on and something to hear)?
|
||||
pub fn audible(project: &Project, l: &Layer) -> bool {
|
||||
l.switches.audio
|
||||
@@ -291,7 +296,7 @@ impl MixEnv<'_> {
|
||||
if fx.is_empty() {
|
||||
return self.layer_raw(l, i0, n, false);
|
||||
}
|
||||
let reversed = fx.iter().any(|(id, _, _)| audio_fx::reverses(id));
|
||||
let reversed = plays_backwards(l);
|
||||
let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum::<f64>().clamp(0.0, MAX_PREROLL_SECONDS);
|
||||
let pre = (pre_s * self.rate as f64).ceil() as usize;
|
||||
let b0 = i0 - pre as i64;
|
||||
|
||||
+16
-246
@@ -1,250 +1,7 @@
|
||||
//! CSS colour values (CSS Color Module Level 3): keywords, `#rgb[a]`, `#rrggbb[aa]`, `rgb[a]()`,
|
||||
//! `hsl[a]()`.
|
||||
//! SVG paint colours use the shared precision-preserving compatibility parser.
|
||||
//! Paint references (`none`, `currentColor`, `url`) remain app policy.
|
||||
|
||||
/// The CSS colour keywords (CSS Color Module Level 3, §4.3 extended colour keywords).
|
||||
const NAMED: &[(&str, u32)] = &[
|
||||
("aliceblue", 0xF0F8FF),
|
||||
("antiquewhite", 0xFAEBD7),
|
||||
("aqua", 0x00FFFF),
|
||||
("aquamarine", 0x7FFFD4),
|
||||
("azure", 0xF0FFFF),
|
||||
("beige", 0xF5F5DC),
|
||||
("bisque", 0xFFE4C4),
|
||||
("black", 0x000000),
|
||||
("blanchedalmond", 0xFFEBCD),
|
||||
("blue", 0x0000FF),
|
||||
("blueviolet", 0x8A2BE2),
|
||||
("brown", 0xA52A2A),
|
||||
("burlywood", 0xDEB887),
|
||||
("cadetblue", 0x5F9EA0),
|
||||
("chartreuse", 0x7FFF00),
|
||||
("chocolate", 0xD2691E),
|
||||
("coral", 0xFF7F50),
|
||||
("cornflowerblue", 0x6495ED),
|
||||
("cornsilk", 0xFFF8DC),
|
||||
("crimson", 0xDC143C),
|
||||
("cyan", 0x00FFFF),
|
||||
("darkblue", 0x00008B),
|
||||
("darkcyan", 0x008B8B),
|
||||
("darkgoldenrod", 0xB8860B),
|
||||
("darkgray", 0xA9A9A9),
|
||||
("darkgreen", 0x006400),
|
||||
("darkgrey", 0xA9A9A9),
|
||||
("darkkhaki", 0xBDB76B),
|
||||
("darkmagenta", 0x8B008B),
|
||||
("darkolivegreen", 0x556B2F),
|
||||
("darkorange", 0xFF8C00),
|
||||
("darkorchid", 0x9932CC),
|
||||
("darkred", 0x8B0000),
|
||||
("darksalmon", 0xE9967A),
|
||||
("darkseagreen", 0x8FBC8F),
|
||||
("darkslateblue", 0x483D8B),
|
||||
("darkslategray", 0x2F4F4F),
|
||||
("darkslategrey", 0x2F4F4F),
|
||||
("darkturquoise", 0x00CED1),
|
||||
("darkviolet", 0x9400D3),
|
||||
("deeppink", 0xFF1493),
|
||||
("deepskyblue", 0x00BFFF),
|
||||
("dimgray", 0x696969),
|
||||
("dimgrey", 0x696969),
|
||||
("dodgerblue", 0x1E90FF),
|
||||
("firebrick", 0xB22222),
|
||||
("floralwhite", 0xFFFAF0),
|
||||
("forestgreen", 0x228B22),
|
||||
("fuchsia", 0xFF00FF),
|
||||
("gainsboro", 0xDCDCDC),
|
||||
("ghostwhite", 0xF8F8FF),
|
||||
("gold", 0xFFD700),
|
||||
("goldenrod", 0xDAA520),
|
||||
("gray", 0x808080),
|
||||
("grey", 0x808080),
|
||||
("green", 0x008000),
|
||||
("greenyellow", 0xADFF2F),
|
||||
("honeydew", 0xF0FFF0),
|
||||
("hotpink", 0xFF69B4),
|
||||
("indianred", 0xCD5C5C),
|
||||
("indigo", 0x4B0082),
|
||||
("ivory", 0xFFFFF0),
|
||||
("khaki", 0xF0E68C),
|
||||
("lavender", 0xE6E6FA),
|
||||
("lavenderblush", 0xFFF0F5),
|
||||
("lawngreen", 0x7CFC00),
|
||||
("lemonchiffon", 0xFFFACD),
|
||||
("lightblue", 0xADD8E6),
|
||||
("lightcoral", 0xF08080),
|
||||
("lightcyan", 0xE0FFFF),
|
||||
("lightgoldenrodyellow", 0xFAFAD2),
|
||||
("lightgray", 0xD3D3D3),
|
||||
("lightgreen", 0x90EE90),
|
||||
("lightgrey", 0xD3D3D3),
|
||||
("lightpink", 0xFFB6C1),
|
||||
("lightsalmon", 0xFFA07A),
|
||||
("lightseagreen", 0x20B2AA),
|
||||
("lightskyblue", 0x87CEFA),
|
||||
("lightslategray", 0x778899),
|
||||
("lightslategrey", 0x778899),
|
||||
("lightsteelblue", 0xB0C4DE),
|
||||
("lightyellow", 0xFFFFE0),
|
||||
("lime", 0x00FF00),
|
||||
("limegreen", 0x32CD32),
|
||||
("linen", 0xFAF0E6),
|
||||
("magenta", 0xFF00FF),
|
||||
("maroon", 0x800000),
|
||||
("mediumaquamarine", 0x66CDAA),
|
||||
("mediumblue", 0x0000CD),
|
||||
("mediumorchid", 0xBA55D3),
|
||||
("mediumpurple", 0x9370DB),
|
||||
("mediumseagreen", 0x3CB371),
|
||||
("mediumslateblue", 0x7B68EE),
|
||||
("mediumspringgreen", 0x00FA9A),
|
||||
("mediumturquoise", 0x48D1CC),
|
||||
("mediumvioletred", 0xC71585),
|
||||
("midnightblue", 0x191970),
|
||||
("mintcream", 0xF5FFFA),
|
||||
("mistyrose", 0xFFE4E1),
|
||||
("moccasin", 0xFFE4B5),
|
||||
("navajowhite", 0xFFDEAD),
|
||||
("navy", 0x000080),
|
||||
("oldlace", 0xFDF5E6),
|
||||
("olive", 0x808000),
|
||||
("olivedrab", 0x6B8E23),
|
||||
("orange", 0xFFA500),
|
||||
("orangered", 0xFF4500),
|
||||
("orchid", 0xDA70D6),
|
||||
("palegoldenrod", 0xEEE8AA),
|
||||
("palegreen", 0x98FB98),
|
||||
("paleturquoise", 0xAFEEEE),
|
||||
("palevioletred", 0xDB7093),
|
||||
("papayawhip", 0xFFEFD5),
|
||||
("peachpuff", 0xFFDAB9),
|
||||
("peru", 0xCD853F),
|
||||
("pink", 0xFFC0CB),
|
||||
("plum", 0xDDA0DD),
|
||||
("powderblue", 0xB0E0E6),
|
||||
("purple", 0x800080),
|
||||
("rebeccapurple", 0x663399),
|
||||
("red", 0xFF0000),
|
||||
("rosybrown", 0xBC8F8F),
|
||||
("royalblue", 0x4169E1),
|
||||
("saddlebrown", 0x8B4513),
|
||||
("salmon", 0xFA8072),
|
||||
("sandybrown", 0xF4A460),
|
||||
("seagreen", 0x2E8B57),
|
||||
("seashell", 0xFFF5EE),
|
||||
("sienna", 0xA0522D),
|
||||
("silver", 0xC0C0C0),
|
||||
("skyblue", 0x87CEEB),
|
||||
("slateblue", 0x6A5ACD),
|
||||
("slategray", 0x708090),
|
||||
("slategrey", 0x708090),
|
||||
("snow", 0xFFFAFA),
|
||||
("springgreen", 0x00FF7F),
|
||||
("steelblue", 0x4682B4),
|
||||
("tan", 0xD2B48C),
|
||||
("teal", 0x008080),
|
||||
("thistle", 0xD8BFD8),
|
||||
("tomato", 0xFF6347),
|
||||
("turquoise", 0x40E0D0),
|
||||
("violet", 0xEE82EE),
|
||||
("wheat", 0xF5DEB3),
|
||||
("white", 0xFFFFFF),
|
||||
("whitesmoke", 0xF5F5F5),
|
||||
("yellow", 0xFFFF00),
|
||||
("yellowgreen", 0x9ACD32),
|
||||
];
|
||||
|
||||
/// Parse a CSS colour into RGBA 0..1 (`transparent` is RGBA 0). `None` for anything else
|
||||
/// (`none`, `currentColor` and `url()` are handled by the caller).
|
||||
pub fn parse_color(s: &str) -> Option<[f64; 4]> {
|
||||
let s = s.trim();
|
||||
let lower = s.to_ascii_lowercase();
|
||||
if lower == "transparent" {
|
||||
return Some([0.0; 4]);
|
||||
}
|
||||
if let Some(h) = lower.strip_prefix('#') {
|
||||
let d: Vec<u32> = h.chars().map(|c| c.to_digit(16)).collect::<Option<_>>()?;
|
||||
let v = |i: usize| d[i] as f64 / 15.0;
|
||||
let w = |i: usize| (d[i] * 16 + d[i + 1]) as f64 / 255.0;
|
||||
return Some(match d.len() {
|
||||
3 => [v(0), v(1), v(2), 1.0],
|
||||
4 => [v(0), v(1), v(2), v(3)],
|
||||
6 => [w(0), w(2), w(4), 1.0],
|
||||
8 => [w(0), w(2), w(4), w(6)],
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
if let Some(args) = func(&lower, "rgba").or_else(|| func(&lower, "rgb")) {
|
||||
let a: Vec<&str> = split_args(args);
|
||||
if a.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let comp = |t: &str| -> Option<f64> {
|
||||
Some(if let Some(p) = t.strip_suffix('%') {
|
||||
p.trim().parse::<f64>().ok().filter(|v| v.is_finite())? / 100.0
|
||||
} else {
|
||||
t.parse::<f64>().ok().filter(|v| v.is_finite())? / 255.0
|
||||
})
|
||||
};
|
||||
let alpha = a.get(3).map_or(Some(1.0), |t| alpha(t))?;
|
||||
return Some([comp(a[0])?.clamp(0.0, 1.0), comp(a[1])?.clamp(0.0, 1.0), comp(a[2])?.clamp(0.0, 1.0), alpha]);
|
||||
}
|
||||
if let Some(args) = func(&lower, "hsla").or_else(|| func(&lower, "hsl")) {
|
||||
let a: Vec<&str> = split_args(args);
|
||||
if a.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let h = a[0].trim_end_matches("deg").parse::<f64>().ok().filter(|v| v.is_finite())?.rem_euclid(360.0) / 360.0;
|
||||
let s = a[1].trim_end_matches('%').parse::<f64>().ok().filter(|v| v.is_finite())?.clamp(0.0, 100.0) / 100.0;
|
||||
let l = a[2].trim_end_matches('%').parse::<f64>().ok().filter(|v| v.is_finite())?.clamp(0.0, 100.0) / 100.0;
|
||||
let al = a.get(3).map_or(Some(1.0), |t| alpha(t))?;
|
||||
let [r, g, b] = hsl(h, s, l);
|
||||
return Some([r, g, b, al]);
|
||||
}
|
||||
NAMED.iter().find(|(n, _)| *n == lower).map(|(_, v)| [((v >> 16) & 255) as f64 / 255.0, ((v >> 8) & 255) as f64 / 255.0, (v & 255) as f64 / 255.0, 1.0])
|
||||
}
|
||||
|
||||
fn func<'a>(s: &'a str, name: &str) -> Option<&'a str> {
|
||||
s.strip_prefix(name)?.trim_start().strip_prefix('(')?.strip_suffix(')')
|
||||
}
|
||||
|
||||
fn split_args(s: &str) -> Vec<&str> {
|
||||
s.split(|c: char| c == ',' || c == '/' || c.is_whitespace()).filter(|t| !t.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn alpha(t: &str) -> Option<f64> {
|
||||
Some(
|
||||
if let Some(p) = t.strip_suffix('%') {
|
||||
p.parse::<f64>().ok().filter(|v| v.is_finite())? / 100.0
|
||||
} else {
|
||||
t.parse::<f64>().ok().filter(|v| v.is_finite())?
|
||||
}
|
||||
.clamp(0.0, 1.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// CSS HSL → RGB (CSS Color 3 §4.2.4).
|
||||
fn hsl(h: f64, s: f64, l: f64) -> [f64; 3] {
|
||||
let m2 = if l <= 0.5 { l * (s + 1.0) } else { l + s - l * s };
|
||||
let m1 = l * 2.0 - m2;
|
||||
let hue = |mut h: f64| {
|
||||
if h < 0.0 {
|
||||
h += 1.0;
|
||||
}
|
||||
if h > 1.0 {
|
||||
h -= 1.0;
|
||||
}
|
||||
if h * 6.0 < 1.0 {
|
||||
m1 + (m2 - m1) * h * 6.0
|
||||
} else if h * 2.0 < 1.0 {
|
||||
m2
|
||||
} else if h * 3.0 < 2.0 {
|
||||
m1 + (m2 - m1) * (2.0 / 3.0 - h) * 6.0
|
||||
} else {
|
||||
m1
|
||||
}
|
||||
};
|
||||
[hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0)]
|
||||
}
|
||||
pub use craft_svg::color::parse_rgba_compat as parse_color;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -280,3 +37,16 @@ mod tests {
|
||||
assert_eq!(parse_color("nonsense"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_precision_tests {
|
||||
use super::parse_color;
|
||||
|
||||
#[test]
|
||||
fn shared_parser_keeps_float_channels_and_legacy_clamping() {
|
||||
assert_eq!(parse_color("rgb(100%,50%,0%)"), Some([1.0, 0.5, 0.0, 1.0]));
|
||||
assert_eq!(parse_color("rgba(0,0,255,0.123456789123)"), Some([0.0, 0.0, 1.0, 0.123456789123]));
|
||||
assert_eq!(parse_color("rgb(300,-1,0)"), Some([1.0, 0.0, 0.0, 1.0]));
|
||||
assert_eq!(parse_color("# fff"), None);
|
||||
}
|
||||
}
|
||||
+9
-251
@@ -425,186 +425,12 @@ enum PaintRef {
|
||||
Current,
|
||||
}
|
||||
|
||||
/// The most selectors (each entry of a comma list counts) the `<style>` sheets of a document may
|
||||
/// hold (#2140).
|
||||
const MAX_CSS_SELECTORS: usize = 20_000;
|
||||
/// The most declarations the `<style>` sheets of a document may hold, each block counted once.
|
||||
const MAX_CSS_DECLARATIONS: usize = 50_000;
|
||||
#[cfg(test)]
|
||||
use craft_svg::simple_css::{MAX_CSS_DECLARATIONS, MAX_CSS_SELECTORS};
|
||||
use craft_svg::simple_css::{MAX_CSS_WORK, StyleSheet};
|
||||
|
||||
/// The most matching work (candidate rules checked plus declarations applied) the elements of a
|
||||
/// document may cost, `<use>` copies included: a bound on elements x rules x declarations.
|
||||
const MAX_CSS_WORK: usize = 50_000_000;
|
||||
|
||||
/// A CSS rule: selector (type, class, id; `*`) with its specificity and declaration block.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Rule {
|
||||
tag: Option<String>,
|
||||
classes: Vec<String>,
|
||||
id: Option<String>,
|
||||
specificity: u32,
|
||||
order: usize,
|
||||
/// Index into [`StyleSheet::blocks`]: every selector of a comma list shares one block.
|
||||
block: usize,
|
||||
}
|
||||
|
||||
/// The rules of a document's `<style>` sheets, indexed by the part of the selector an element
|
||||
/// must have (id, else first class, else type) so an element only checks rules that can match.
|
||||
#[derive(Default, Debug)]
|
||||
struct StyleSheet {
|
||||
/// Distinct selector rules in source order.
|
||||
rules: Vec<Rule>,
|
||||
/// Declaration blocks; comma-list selectors share one block.
|
||||
blocks: Vec<Vec<(String, String)>>,
|
||||
/// Declarations over all blocks.
|
||||
decls: usize,
|
||||
/// Rules keyed by their id selector.
|
||||
by_id: HashMap<String, Vec<usize>>,
|
||||
/// Rules keyed by their first class selector.
|
||||
by_class: HashMap<String, Vec<usize>>,
|
||||
/// Rules keyed by their type selector.
|
||||
by_tag: HashMap<String, Vec<usize>>,
|
||||
/// Rules with no id, class or type to index on.
|
||||
universal: Vec<usize>,
|
||||
}
|
||||
|
||||
impl StyleSheet {
|
||||
/// Build the id, class, tag and universal lookup buckets from `rules`.
|
||||
fn index(&mut self) {
|
||||
for (i, r) in self.rules.iter().enumerate() {
|
||||
let bucket = if let Some(id) = &r.id {
|
||||
self.by_id.entry(id.clone()).or_default()
|
||||
} else if let Some(c) = r.classes.first() {
|
||||
self.by_class.entry(c.clone()).or_default()
|
||||
} else if let Some(t) = &r.tag {
|
||||
self.by_tag.entry(t.clone()).or_default()
|
||||
} else {
|
||||
&mut self.universal
|
||||
};
|
||||
bucket.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_decls(s: &str) -> Vec<(String, String)> {
|
||||
s.split(';')
|
||||
.filter_map(|d| {
|
||||
let (k, v) = d.split_once(':')?;
|
||||
let v = v.trim().trim_end_matches("!important").trim();
|
||||
Some((k.trim().to_ascii_lowercase(), v.to_string()))
|
||||
})
|
||||
.filter(|(k, _)| !k.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn strip_comments(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find("/*") {
|
||||
out.push_str(&rest[..i]);
|
||||
match rest[i + 2..].find("*/") {
|
||||
Some(j) => rest = &rest[i + 2 + j + 2..],
|
||||
None => return out,
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits one simple selector (`tag.class#id`) into its tag, classes and id.
|
||||
fn parse_compound(one: &str) -> (Option<String>, Vec<String>, Option<String>) {
|
||||
let mut tag = None;
|
||||
let mut classes = vec![];
|
||||
let mut id = None;
|
||||
let mut cur = String::new();
|
||||
let mut kind = 't';
|
||||
let flush = |kind: char, cur: &mut String, tag: &mut Option<String>, classes: &mut Vec<String>, id: &mut Option<String>| {
|
||||
if !cur.is_empty() {
|
||||
match kind {
|
||||
'.' => classes.push(std::mem::take(cur)),
|
||||
'#' => *id = Some(std::mem::take(cur)),
|
||||
_ => {
|
||||
if cur != "*" {
|
||||
*tag = Some(std::mem::take(cur));
|
||||
}
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
for c in one.chars() {
|
||||
if c == '.' || c == '#' {
|
||||
flush(kind, &mut cur, &mut tag, &mut classes, &mut id);
|
||||
kind = c;
|
||||
} else {
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
flush(kind, &mut cur, &mut tag, &mut classes, &mut id);
|
||||
(tag, classes, id)
|
||||
}
|
||||
|
||||
/// Add the rules of one `<style>` sheet. Errs once the sheets exceed [`MAX_CSS_SELECTORS`] or
|
||||
/// [`MAX_CSS_DECLARATIONS`] (#2140).
|
||||
fn parse_css(css: &str, sheet: &mut StyleSheet) -> Result<(), Error> {
|
||||
let css = strip_comments(css);
|
||||
let mut rest = css.as_str();
|
||||
while let Some(open) = rest.find('{') {
|
||||
let sel = rest[..open].trim();
|
||||
if sel.starts_with('@') {
|
||||
// Skip the whole at-rule block, matching nested braces by depth.
|
||||
let mut depth = 0usize;
|
||||
let mut end = None;
|
||||
for (i, c) in rest[open..].char_indices() {
|
||||
match c {
|
||||
'{' => depth = depth.saturating_add(1),
|
||||
'}' => {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
end = Some(open + i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(end) = end else { break };
|
||||
rest = &rest[end..];
|
||||
continue;
|
||||
}
|
||||
let Some(close) = rest[open..].find('}') else { break };
|
||||
let body = &rest[open + 1..open + close];
|
||||
rest = &rest[open + close + 1..];
|
||||
let mut decls = parse_decls(body);
|
||||
sheet.decls = sheet.decls.saturating_add(decls.len());
|
||||
if sheet.decls > MAX_CSS_DECLARATIONS {
|
||||
return Err(Error::Xml(format!("its <style> sheets hold more than {MAX_CSS_DECLARATIONS} declarations")));
|
||||
}
|
||||
// Stored with the rule's first accepted selector: a rule of unsupported selectors only
|
||||
// (`a b{}`, repeated) adds no block.
|
||||
let mut block = None;
|
||||
for one in sel.split(',') {
|
||||
let one = one.trim();
|
||||
// Only simple selectors (no combinators / pseudo-classes / attributes).
|
||||
if one.is_empty() || one.contains([' ', '>', '+', '~', ':', '[']) {
|
||||
continue;
|
||||
}
|
||||
if sheet.rules.len() >= MAX_CSS_SELECTORS {
|
||||
return Err(Error::Xml(format!("its <style> sheets hold more than {MAX_CSS_SELECTORS} selectors")));
|
||||
}
|
||||
let block = *block.get_or_insert_with(|| {
|
||||
let i = sheet.blocks.len();
|
||||
sheet.blocks.push(std::mem::take(&mut decls));
|
||||
i
|
||||
});
|
||||
let (tag, classes, id) = parse_compound(one);
|
||||
let specificity = (id.is_some() as u32 * 100)
|
||||
.saturating_add(u32::try_from(classes.len()).unwrap_or(u32::MAX).saturating_mul(10))
|
||||
.saturating_add(tag.is_some() as u32);
|
||||
let order = sheet.rules.len();
|
||||
sheet.rules.push(Rule { tag, classes, id, specificity, order, block });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
fn parse_css(text: &str, sheet: &mut StyleSheet) -> Result<(), Error> {
|
||||
craft_svg::simple_css::parse(text, sheet).map_err(|error| Error::Xml(error.to_string()))
|
||||
}
|
||||
|
||||
const PROPS: &[&str] = &[
|
||||
@@ -695,7 +521,7 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
}
|
||||
self.apply_rules(n, &mut out);
|
||||
if let Some(st) = n.attribute("style") {
|
||||
for (k, v) in parse_decls(st) {
|
||||
for (k, v) in craft_svg::simple_css::declarations(st) {
|
||||
out.insert(k, v);
|
||||
}
|
||||
}
|
||||
@@ -763,50 +589,9 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
self.charge_pattern_work(bytes.saturating_add(1))
|
||||
}
|
||||
|
||||
/// Apply the matching `<style>` rules to `out`, by specificity then source order.
|
||||
/// Apply the shared compatibility stylesheet rules under the document work budget.
|
||||
fn apply_rules(&self, n: roxmltree::Node, out: &mut HashMap<String, String>) {
|
||||
let css = &self.css;
|
||||
if css.rules.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Splitting and sorting the class list is work too: charge its length first.
|
||||
let class = n.attribute("class").unwrap_or_default();
|
||||
if !self.charge_css(class.len()) {
|
||||
return;
|
||||
}
|
||||
let tag = n.tag_name().name();
|
||||
let mut classes: Vec<&str> = class.split_whitespace().collect();
|
||||
classes.sort_unstable();
|
||||
classes.dedup();
|
||||
let id = n.attribute("id");
|
||||
// Each rule sits in exactly one bucket and the classes are distinct: no rule twice.
|
||||
let mut buckets: Vec<&Vec<usize>> = vec![&css.universal];
|
||||
buckets.extend(id.and_then(|i| css.by_id.get(i)));
|
||||
buckets.extend(classes.iter().filter_map(|c| css.by_class.get(*c)));
|
||||
buckets.extend(css.by_tag.get(tag));
|
||||
if !self.charge_css(buckets.iter().map(|b| b.len()).fold(0, usize::saturating_add)) {
|
||||
return;
|
||||
}
|
||||
let candidates = || buckets.iter().flat_map(|b| b.iter()).filter_map(|&i| css.rules.get(i));
|
||||
// A selector like `.z.z.z…` checks each of its classes: charge them too.
|
||||
if !self.charge_css(candidates().map(|r| r.classes.len()).fold(0, usize::saturating_add)) {
|
||||
return;
|
||||
}
|
||||
let mut matching: Vec<&Rule> = candidates()
|
||||
.filter(|r| {
|
||||
r.tag.as_deref().is_none_or(|t| t == tag)
|
||||
&& r.id.as_deref().is_none_or(|i| Some(i) == id)
|
||||
&& r.classes.iter().all(|c| classes.binary_search(&c.as_str()).is_ok())
|
||||
})
|
||||
.collect();
|
||||
matching.sort_by_key(|r| (r.specificity, r.order));
|
||||
let blocks: Vec<&Vec<(String, String)>> = matching.iter().filter_map(|r| css.blocks.get(r.block)).collect();
|
||||
if !self.charge_css(blocks.iter().map(|b| b.len()).fold(0, usize::saturating_add)) {
|
||||
return;
|
||||
}
|
||||
for (k, v) in blocks.into_iter().flatten() {
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
self.css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), out, |work| self.charge_css(work));
|
||||
}
|
||||
|
||||
fn length(&self, s: &str, axis: char, font: f64) -> Option<f64> {
|
||||
@@ -1668,34 +1453,7 @@ fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine {
|
||||
}
|
||||
|
||||
/// Parse a `transform` list.
|
||||
pub fn parse_transform(s: &str) -> Affine {
|
||||
let mut m = Affine::IDENTITY;
|
||||
let mut rest = s;
|
||||
while let Some(open) = rest.find('(') {
|
||||
let name = rest[..open].trim().trim_start_matches(',').trim();
|
||||
let Some(close) = rest[open..].find(')') else { break };
|
||||
let (a, too_many) = pathdata::numbers_bounded(&rest[open + 1..open + close], 6);
|
||||
rest = &rest[open + close + 1..];
|
||||
let t = if too_many {
|
||||
Affine::IDENTITY
|
||||
} else {
|
||||
match (name, a.as_slice()) {
|
||||
("matrix", [a0, a1, a2, a3, a4, a5]) => Affine::new([*a0, *a1, *a2, *a3, *a4, *a5]),
|
||||
("translate", [x]) => Affine::translate((*x, 0.0)),
|
||||
("translate", [x, y]) => Affine::translate((*x, *y)),
|
||||
("scale", [scale]) => Affine::scale(*scale),
|
||||
("scale", [x, y]) => Affine::scale_non_uniform(*x, *y),
|
||||
("rotate", [angle]) => Affine::rotate(angle.to_radians()),
|
||||
("rotate", [angle, x, y]) => Affine::translate((*x, *y)) * Affine::rotate(angle.to_radians()) * Affine::translate((-*x, -*y)),
|
||||
("skewX", [angle]) => Affine::new([1.0, 0.0, angle.to_radians().tan(), 1.0, 0.0, 0.0]),
|
||||
("skewY", [angle]) => Affine::new([1.0, angle.to_radians().tan(), 0.0, 1.0, 0.0, 0.0]),
|
||||
_ => Affine::IDENTITY,
|
||||
}
|
||||
};
|
||||
m *= t;
|
||||
}
|
||||
m
|
||||
}
|
||||
pub use craft_svg::transform_compat::parse_transform;
|
||||
|
||||
/// The deepest element nesting accepted. The XML parser recurses per level and overflowed a
|
||||
/// 2 MiB thread's stack (aborting the app) at a few thousand levels; real documents stay far
|
||||
|
||||
+4
-352
@@ -1,360 +1,12 @@
|
||||
//! SVG path data (SVG 1.1 §8.3 / SVG 2 §9.3): every command, implicit repeats, relative
|
||||
//! coordinates, smooth curves and elliptical arcs (converted to cubics through kurbo's `SvgArc`).
|
||||
//! Parsing stops at the first error, keeping what was read (as the specification asks).
|
||||
//! Prefix-preserving SVG path and numeric-list parsing is shared with craft-svg.
|
||||
//! App document budgets and geometry policy remain with the importer.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2};
|
||||
|
||||
/// Maximum path elements retained from one SVG path or point list.
|
||||
pub(crate) const MAX_PATH_ELEMENTS: usize = 100_000;
|
||||
|
||||
/// Tokenizer over numbers and command letters.
|
||||
struct Lex<'a> {
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Lex<'_> {
|
||||
fn skip_sep(&mut self) {
|
||||
while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == b',') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn command(&mut self) -> Option<u8> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
|
||||
self.i += 1;
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn at_number(&mut self) -> bool {
|
||||
self.skip_sep();
|
||||
self.b.get(self.i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
|
||||
}
|
||||
fn number(&mut self) -> Option<f64> {
|
||||
self.skip_sep();
|
||||
let start = self.i;
|
||||
let b = self.b;
|
||||
let mut i = self.i;
|
||||
if i < b.len() && matches!(b[i], b'-' | b'+') {
|
||||
i += 1;
|
||||
}
|
||||
let mut digits = false;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
if i < b.len() && b[i] == b'.' {
|
||||
i += 1;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return None;
|
||||
}
|
||||
if i < b.len() && matches!(b[i], b'e' | b'E') {
|
||||
let mut j = i + 1;
|
||||
if j < b.len() && matches!(b[j], b'-' | b'+') {
|
||||
j += 1;
|
||||
}
|
||||
if j < b.len() && b[j].is_ascii_digit() {
|
||||
while j < b.len() && b[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
self.i = i;
|
||||
let number = std::str::from_utf8(&b[start..i]).ok()?.parse::<f64>().ok()?;
|
||||
number.is_finite().then_some(number)
|
||||
}
|
||||
/// Arc flags may be written without separators ("a1 1 0 00 1 1").
|
||||
fn flag(&mut self) -> Option<bool> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
self.i += 1;
|
||||
match c {
|
||||
b'0' => Some(false),
|
||||
b'1' => Some(true),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse no more than `max_values`; the flag reports whether another valid value was present.
|
||||
pub(crate) fn numbers_bounded(s: &str, max_values: usize) -> (Vec<f64>, bool) {
|
||||
let mut l = Lex { b: s.as_bytes(), i: 0 };
|
||||
let mut v = vec![];
|
||||
while l.at_number() {
|
||||
if v.len() >= max_values {
|
||||
return (v, true);
|
||||
}
|
||||
match l.number() {
|
||||
Some(x) => v.push(x),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(v, false)
|
||||
}
|
||||
|
||||
/// Parse path data into a kurbo path, retaining at most [`MAX_PATH_ELEMENTS`] elements.
|
||||
/// Malformed or overlong input returns the prefix parsed before the problem.
|
||||
pub fn parse_path_data(d: &str) -> BezPath {
|
||||
parse_path_data_bounded(d, MAX_PATH_ELEMENTS).0
|
||||
}
|
||||
|
||||
/// Pen position and reflection state while parsing path commands.
|
||||
struct PathState {
|
||||
/// Current point.
|
||||
current: Point,
|
||||
/// Start of the current subpath.
|
||||
start: Point,
|
||||
/// Last cubic control point, for smooth curves.
|
||||
last_cubic: Option<Point>,
|
||||
/// Last quadratic control point, for smooth curves.
|
||||
last_quad: Option<Point>,
|
||||
/// Whether a subpath is open.
|
||||
open: bool,
|
||||
}
|
||||
|
||||
/// Cap on path elements and whether it has been hit.
|
||||
struct PathLimit {
|
||||
/// Maximum number of path elements.
|
||||
max_elements: usize,
|
||||
/// Set when the cap or a non-finite coordinate stopped output.
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
/// Parse at most `max_elements`, reporting when more path geometry was present.
|
||||
pub(crate) fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) {
|
||||
let mut l = Lex { b: d.as_bytes(), i: 0 };
|
||||
let mut p = BezPath::new();
|
||||
let mut state = PathState { current: Point::ZERO, start: Point::ZERO, last_cubic: None, last_quad: None, open: false };
|
||||
let mut limit = PathLimit { max_elements, exceeded: false };
|
||||
let mut cmd: Option<u8> = None;
|
||||
loop {
|
||||
if p.elements().len() >= limit.max_elements {
|
||||
l.skip_sep();
|
||||
limit.exceeded = l.i < l.b.len();
|
||||
break;
|
||||
}
|
||||
let c = match l.command() {
|
||||
Some(c) => c,
|
||||
None => match cmd {
|
||||
// Implicit repeat (a moveto repeats as lineto). Z takes no numbers, so a number
|
||||
// after it is an error: repeating Z would loop forever without consuming input.
|
||||
Some(c) if l.at_number() && !c.eq_ignore_ascii_case(&b'z') => match c {
|
||||
b'M' => b'L',
|
||||
b'm' => b'l',
|
||||
other => other,
|
||||
},
|
||||
_ => break,
|
||||
},
|
||||
};
|
||||
let rel = c.is_ascii_lowercase();
|
||||
let base = if rel { state.current.to_vec2() } else { Vec2::ZERO };
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
let ok = (|| -> Option<()> {
|
||||
match c.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
state.current = pt(&mut l)?;
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.start = state.current;
|
||||
state.open = true;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'Z' => {
|
||||
if state.open && !push_element(&mut p, PathEl::ClosePath, &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = state.start;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ if !state.open => {
|
||||
// A segment without a preceding moveto starts at the current point.
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.open = true;
|
||||
return segment(&mut l, c, base, &mut p, &mut state, &mut limit);
|
||||
}
|
||||
_ => return segment(&mut l, c, base, &mut p, &mut state, &mut limit),
|
||||
}
|
||||
Some(())
|
||||
})();
|
||||
if ok.is_none() {
|
||||
break;
|
||||
}
|
||||
if limit.exceeded {
|
||||
break;
|
||||
}
|
||||
cmd = Some(c);
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
// After Z a new segment starts from the subpath start (an unused move is dropped
|
||||
// below).
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.start), &mut limit) {
|
||||
break;
|
||||
}
|
||||
state.open = true;
|
||||
}
|
||||
}
|
||||
(strip_trailing_moves(p), limit.exceeded)
|
||||
}
|
||||
|
||||
/// Push an element if finite and under the cap; otherwise mark the limit exceeded and return false.
|
||||
fn push_element(p: &mut BezPath, element: PathEl, limit: &mut PathLimit) -> bool {
|
||||
let finite = match element {
|
||||
PathEl::MoveTo(point) | PathEl::LineTo(point) => point.x.is_finite() && point.y.is_finite(),
|
||||
PathEl::QuadTo(control, point) => [control.x, control.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::CurveTo(first, second, point) => [first.x, first.y, second.x, second.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::ClosePath => true,
|
||||
};
|
||||
if p.elements().len() >= limit.max_elements || !finite {
|
||||
limit.exceeded = true;
|
||||
return false;
|
||||
}
|
||||
p.push(element);
|
||||
true
|
||||
}
|
||||
|
||||
/// Parse one path command's arguments into `p`, returning `None` on malformed or over-limit input.
|
||||
fn segment(l: &mut Lex, c: u8, base: Vec2, p: &mut BezPath, state: &mut PathState, limit: &mut PathLimit) -> Option<()> {
|
||||
let num = |l: &mut Lex| l.number();
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
match c.to_ascii_uppercase() {
|
||||
b'L' => {
|
||||
let current = pt(l)?;
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
let x = num(l)? + base.x;
|
||||
let current = Point::new(x, state.current.y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
let y = num(l)? + base.y;
|
||||
let current = Point::new(state.current.x, y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, e) = (pt(l)?, pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = state.last_cubic.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let (c2, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'T' => {
|
||||
let q = state.last_quad.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let e = pt(l)?;
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'A' => {
|
||||
let rx = num(l)?.abs();
|
||||
let ry = num(l)?.abs();
|
||||
let rot = num(l)?;
|
||||
let large = l.flag()?;
|
||||
let sweep = l.flag()?;
|
||||
let e = pt(l)?;
|
||||
let arc = SvgArc { from: state.current, to: e, radii: Vec2::new(rx, ry), x_rotation: rot.to_radians(), large_arc: large, sweep };
|
||||
let mut last_end = None;
|
||||
if let Some(a) = kurbo::Arc::from_svg_arc(&arc) {
|
||||
// Scale tolerance with the radius so the segment count stays bounded.
|
||||
let tol = 0.1_f64.max(a.radii.x.max(a.radii.y) * 1e-4);
|
||||
a.to_cubic_beziers(tol, |c1, c2, end| {
|
||||
if limit.exceeded {
|
||||
return;
|
||||
}
|
||||
if push_element(p, PathEl::CurveTo(c1, c2, end), limit) {
|
||||
last_end = Some(end);
|
||||
}
|
||||
});
|
||||
}
|
||||
if limit.exceeded {
|
||||
return None;
|
||||
}
|
||||
// Degenerate arcs (e.g. huge radii) may emit nothing or stop short of the end point.
|
||||
if last_end.is_none_or(|q| (q - e).hypot() > 1e-3 * (1.0 + e.to_vec2().hypot())) && !push_element(p, PathEl::LineTo(e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = e;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Drop move-tos that start no segment (from closepath bookkeeping).
|
||||
fn strip_trailing_moves(p: BezPath) -> BezPath {
|
||||
use kurbo::PathEl;
|
||||
let els = p.elements();
|
||||
let mut out = BezPath::new();
|
||||
for (i, e) in els.iter().enumerate() {
|
||||
if let PathEl::MoveTo(_) = e {
|
||||
let next_is_seg = els.get(i + 1).is_some_and(|n| !matches!(n, PathEl::MoveTo(_)));
|
||||
if !next_is_seg {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(*e);
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_svg::prefix_path::{MAX_PATH_ELEMENTS, numbers_bounded, parse_path_data, parse_path_data_bounded};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::PathEl;
|
||||
use kurbo::{PathEl, Point};
|
||||
|
||||
#[test]
|
||||
/// Huge arc radii stay bounded.
|
||||
|
||||
@@ -878,27 +878,6 @@ fn selector_lists_keep_the_css_cascade() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comma_list_stores_its_declarations_once() {
|
||||
let sels = vec!["rect"; 1000].join(",");
|
||||
let decls: String = (0..50).map(|i| format!("p{i}:v;")).collect();
|
||||
let mut sheet = StyleSheet::default();
|
||||
parse_css(&format!("{sels}{{{decls}}}"), &mut sheet).unwrap();
|
||||
assert_eq!(sheet.rules.len(), 1000);
|
||||
assert_eq!(sheet.blocks.len(), 1);
|
||||
assert_eq!(sheet.decls, 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_of_unsupported_selectors_store_no_blocks() {
|
||||
let mut sheet = StyleSheet::default();
|
||||
parse_css(&"a b{}".repeat(100_000), &mut sheet).unwrap();
|
||||
parse_css("a b{fill:red} a>b, rect{fill:blue} c:hover, d{fill:red}", &mut sheet).unwrap();
|
||||
assert_eq!(sheet.rules.len(), 2);
|
||||
assert_eq!(sheet.blocks.len(), 2);
|
||||
assert!(sheet.rules.iter().all(|r| sheet.blocks.get(r.block).is_some_and(|b| b.len() == 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_class_lists_count_against_the_matching_budget() {
|
||||
// One rule, but a 1 MB class attribute re-split on each of 100 `<use>` copies (#2140).
|
||||
@@ -959,18 +938,6 @@ fn font_size_percentage_resolves_against_the_parent_font_size() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_rule_blocks_are_skipped_by_brace_depth() {
|
||||
let mut sheet = StyleSheet::default();
|
||||
parse_css("@media print { .a{fill:#ff0000} .b{fill:#0000ff} } .c{fill:red}", &mut sheet).unwrap();
|
||||
assert_eq!(sheet.rules.len(), 1);
|
||||
assert_eq!(sheet.rules[0].classes, vec!["c".to_string()]);
|
||||
let mut sheet = StyleSheet::default();
|
||||
parse_css("@media x { @supports y { .c{} } .d{} } .e{fill:red}", &mut sheet).unwrap();
|
||||
assert_eq!(sheet.rules.len(), 1);
|
||||
assert_eq!(sheet.rules[0].classes, vec!["e".to_string()]);
|
||||
}
|
||||
|
||||
/// Build a `w` x `h` document from `nodes` for sparse-content render tests.
|
||||
fn sparse_doc(w: f64, h: f64, nodes: Vec<Node>) -> Doc {
|
||||
let mut root = Group::new("root");
|
||||
|
||||
@@ -542,6 +542,11 @@ impl FileDialogsUp {
|
||||
self.count = self.count.saturating_sub(1);
|
||||
}
|
||||
|
||||
/// How many dialogs are up, as last checked ([`FileDialogsUp::up`] drops those taken for gone).
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Whether a dialog is up at `now`, `focused`: whether one of the app's windows has the
|
||||
/// keyboard.
|
||||
pub(crate) fn up(&mut self, focused: bool, now: f64) -> bool {
|
||||
|
||||
@@ -101,6 +101,12 @@ pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool>
|
||||
}
|
||||
|
||||
pub(crate) fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool {
|
||||
// A disabled macOS menu item lets its key through, so a native file dialog gets Cmd+A, C, V
|
||||
// (and Z) instead of the Edit menu acting on the window behind it (#1986). Only macOS: the
|
||||
// native menu bar owns the keys there, and Linux's portal dialog is a separate window.
|
||||
if cfg!(target_os = "macos") && e.command.starts_with("edit.") && app.file_dialogs.count() > 0 {
|
||||
return false;
|
||||
}
|
||||
// The Project-panel enabled rules mirror the invoke redirects, so they stand down for the
|
||||
// same reason (see the redirect block): while a text edit is open the menu items must be
|
||||
// enabled by what their routed command can do, or the menu grays out commands that work.
|
||||
|
||||
@@ -403,7 +403,7 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only
|
||||
if app.dialog.is_some() {
|
||||
continue;
|
||||
}
|
||||
if !mods.any() && crate::panels::effect_controls::handle_disclosure_key(app, key) {
|
||||
if !mods.any() && crate::panels::effect_controls::handle_arrow_key(app, ctx, key) {
|
||||
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -448,6 +448,41 @@ fn file_dialogs_block_floating_windows_only_while_up() {
|
||||
assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again");
|
||||
}
|
||||
|
||||
/// While a native file dialog is up, the Edit menu is disabled on macOS so the OS hands Cmd+A
|
||||
/// to the dialog instead of selecting in the Project panel behind it (#1986). Elsewhere the
|
||||
/// menu stays as it was.
|
||||
#[test]
|
||||
fn edit_menu_is_disabled_while_a_file_dialog_is_open() {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
|
||||
app.session.execute("file.openDemoProject", json!({})).unwrap();
|
||||
app.ui.focused = PanelKind::Project;
|
||||
let ctx = egui::Context::default();
|
||||
let entries = effectcraft_engine::menus::entries();
|
||||
let select_all = entries.iter().map(|(_, e)| e).find(|e| e.command == "edit.selectAll").expect("Select All is in the menu");
|
||||
let import = entries.iter().map(|(_, e)| e).find(|e| e.command == "file.import").expect("Import is in the menu");
|
||||
assert!(entry_enabled(&app, select_all));
|
||||
let steps_aside = cfg!(target_os = "macos");
|
||||
let pending: Arc<Mutex<Vec<crate::DialogDone>>> = Arc::default();
|
||||
let queue = pending.clone();
|
||||
app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done)));
|
||||
invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
|
||||
assert_eq!(!entry_enabled(&app, select_all), steps_aside, "Cmd+A must reach the dialog on macOS only");
|
||||
assert!(entry_enabled(&app, import), "only the Edit menu steps aside");
|
||||
// Cancelled: the menu is back.
|
||||
let done = pending.lock().unwrap().pop().expect("a dialog was shown");
|
||||
done(Ok(Vec::new()));
|
||||
app.run_dialog_answers();
|
||||
assert!(entry_enabled(&app, select_all));
|
||||
// Ended without answering: the menu is back once the dialog is taken for gone.
|
||||
invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
|
||||
assert_eq!(!entry_enabled(&app, select_all), steps_aside);
|
||||
let _ = app.file_dialogs.up(true, 0.0);
|
||||
let _ = app.file_dialogs.up(false, 0.1);
|
||||
let _ = app.file_dialogs.up(true, 0.2);
|
||||
assert!(entry_enabled(&app, select_all));
|
||||
}
|
||||
|
||||
/// #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.
|
||||
|
||||
@@ -29,6 +29,12 @@ pub enum Role {
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
SelectAll,
|
||||
Cut,
|
||||
Copy,
|
||||
Paste,
|
||||
Undo,
|
||||
Redo,
|
||||
}
|
||||
|
||||
/// One node of the native menu.
|
||||
@@ -151,9 +157,37 @@ pub fn build_now(app: &EffectcraftApp, ctx: &egui::Context) -> NativeMenu {
|
||||
}
|
||||
}
|
||||
let mut menu = build(app);
|
||||
if text_field_window(ctx).is_some() {
|
||||
// On macOS a file dialog takes the keys over the field behind it (#1986).
|
||||
let dialog = cfg!(target_os = "macos") && app.file_dialogs.count() > 0;
|
||||
if text_field_window(ctx).is_some() && !dialog {
|
||||
enable(app, &mut menu.menus);
|
||||
}
|
||||
if dialog {
|
||||
// The sandboxed open panel is a remote view: it gets Cmd+A, C, X, V, Z through the host's
|
||||
// standard Edit items (first-responder selectors), not through items that run our
|
||||
// commands, which swallow the key or leave the panel without one (#1986).
|
||||
fn standard(nodes: &mut [NativeNode]) {
|
||||
for node in nodes {
|
||||
match node {
|
||||
NativeNode::Item(item) => {
|
||||
let role = match item.command.as_str() {
|
||||
"edit.selectAll" => Role::SelectAll,
|
||||
"edit.cut" => Role::Cut,
|
||||
"edit.copy" => Role::Copy,
|
||||
"edit.paste" => Role::Paste,
|
||||
"edit.undo" => Role::Undo,
|
||||
"edit.redo" => Role::Redo,
|
||||
_ => continue,
|
||||
};
|
||||
*node = NativeNode::Predefined { role, label: item.label.clone(), command: item.command.clone() };
|
||||
}
|
||||
NativeNode::Submenu { children, .. } => standard(children),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
standard(&mut menu.menus);
|
||||
}
|
||||
menu
|
||||
}
|
||||
|
||||
@@ -374,12 +408,37 @@ pub fn state_key(app: &EffectcraftApp) -> u64 {
|
||||
s.keymaps.active.hash(&mut h);
|
||||
let v = &app.ui.viewer;
|
||||
(v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h);
|
||||
(app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h);
|
||||
(app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some(), app.file_dialogs.count()).hash(&mut h);
|
||||
// Window menu check marks: the panels on screen.
|
||||
crate::dock::PanelKind::ALL.iter().filter(|p| crate::menus::panel_shown(app, **p)).for_each(|p| p.hash(&mut h));
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Keeps the native menu in step with native file dialogs within a frame. The menu syncs at the
|
||||
/// frame's start, but a dialog opened by the frame's commands is counted only after that: sync
|
||||
/// again then, so its Edit items step aside before the next key (#1986). The second sync runs
|
||||
/// only when the dialog count changed.
|
||||
#[derive(Default)]
|
||||
pub struct MenuSync {
|
||||
/// Native file dialogs on screen at the last sync.
|
||||
dialogs: usize,
|
||||
}
|
||||
|
||||
impl MenuSync {
|
||||
/// The frame's sync, before its commands run.
|
||||
pub fn before(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) {
|
||||
update(app);
|
||||
self.dialogs = app.file_dialogs.count();
|
||||
}
|
||||
|
||||
/// After the frame's commands: sync again if a file dialog opened or closed meanwhile.
|
||||
pub fn after(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) {
|
||||
if app.file_dialogs.count() != self.dialogs {
|
||||
self.before(app, update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The window whose text field has the keyboard: a floating panel's own OS window, or the main
|
||||
/// window, where any widget that holds the keyboard counts (the Viewer's text editor is not an
|
||||
/// egui text field).
|
||||
@@ -490,9 +549,37 @@ mod tests {
|
||||
fn app() -> EffectcraftApp {
|
||||
let mut s = effectcraft_engine::Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
// The default is "Match System": pin English so the tests do not follow the machine's locale.
|
||||
s.execute("prefs.set", json!({"key": "general.language", "value": "en"})).unwrap();
|
||||
EffectcraftApp::new(s)
|
||||
}
|
||||
|
||||
/// A file dialog opened by the frame's commands syncs the menu a second time (#1986); a
|
||||
/// frame without one syncs it once.
|
||||
#[test]
|
||||
fn menu_syncs_again_when_a_frame_opens_a_file_dialog() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let pending: std::sync::Arc<std::sync::Mutex<Vec<crate::DialogDone>>> = Default::default();
|
||||
let queue = pending.clone();
|
||||
app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done)));
|
||||
let mut sync = MenuSync::default();
|
||||
// A fake menu: records the dialog count each update sees.
|
||||
let mut updates = Vec::new();
|
||||
let mut frame = |app: &mut EffectcraftApp, command: Option<&str>| {
|
||||
sync.before(app, |a| updates.push(a.file_dialogs.count()));
|
||||
if let Some(id) = command {
|
||||
crate::menus::invoke(app, &ctx, id, json!({})).unwrap();
|
||||
}
|
||||
sync.after(app, |a| updates.push(a.file_dialogs.count()));
|
||||
};
|
||||
frame(&mut app, None);
|
||||
frame(&mut app, Some("file.importMultiple"));
|
||||
frame(&mut app, None);
|
||||
assert_eq!(updates, [0, 0, 1, 1], "no dialog: one update; dialog opened: a second one that sees it");
|
||||
assert_eq!(pending.lock().unwrap().len(), 1, "a dialog was shown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_engine_entry_is_in_the_native_menu() {
|
||||
let app = app();
|
||||
@@ -822,6 +909,79 @@ mod tests {
|
||||
assert!(edits_text("edit.copy") && edits_text("edit.paste"));
|
||||
assert!(!edits_text("layer.newNull"));
|
||||
}
|
||||
/// #1986: a file dialog opened while a text field has the keyboard takes Cmd+A: the field
|
||||
/// behind it does not keep the Edit items enabled.
|
||||
#[test]
|
||||
fn a_file_dialog_takes_the_edit_keys_from_a_focused_text_field() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let mut text = String::new();
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| ui.text_edit_singleline(&mut text).request_focus());
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
let select_all = |m: &NativeMenu| m.items().into_iter().any(|i| i.command == "edit.selectAll" && i.enabled);
|
||||
assert!(select_all(&build_now(&app, &ctx)));
|
||||
app.hooks.file_dialog_async = Some(Box::new(|_, _| {}));
|
||||
crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
|
||||
assert_eq!(select_all(&build_now(&app, &ctx)), !cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
/// #1986: while a file dialog is open on macOS the Edit items for select-all, cut, copy,
|
||||
/// paste, undo and redo become the host's standard (predefined) items, keeping label and
|
||||
/// command; without a dialog they stay plain command items.
|
||||
#[test]
|
||||
fn a_file_dialog_turns_the_edit_keys_into_standard_items() {
|
||||
fn predefined(menu: &NativeMenu) -> Vec<(String, Role, String)> {
|
||||
fn rec(n: &[NativeNode], out: &mut Vec<(String, Role, String)>) {
|
||||
for x in n {
|
||||
match x {
|
||||
NativeNode::Predefined { role, label, command }
|
||||
if matches!(role, Role::SelectAll | Role::Cut | Role::Copy | Role::Paste | Role::Undo | Role::Redo) =>
|
||||
{
|
||||
out.push((command.clone(), *role, label.to_string()))
|
||||
}
|
||||
NativeNode::Submenu { children, .. } => rec(children, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
rec(&menu.menus, &mut out);
|
||||
out
|
||||
}
|
||||
fn by_command<'a>(menu: &'a NativeMenu, id: &str) -> Option<&'a NativeItem> {
|
||||
menu.items().into_iter().find(|i| i.command == id)
|
||||
}
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let ids = ["edit.selectAll", "edit.cut", "edit.copy", "edit.paste", "edit.undo", "edit.redo"];
|
||||
let before = build_now(&app, &ctx);
|
||||
assert!(predefined(&before).is_empty(), "no dialog: no standard edit items");
|
||||
let plain: Vec<_> = ids.iter().filter(|id| by_command(&before, id).is_some()).collect();
|
||||
app.hooks.file_dialog_async = Some(Box::new(|_, _| {}));
|
||||
crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap();
|
||||
let after = build_now(&app, &ctx);
|
||||
let got = predefined(&after);
|
||||
if cfg!(target_os = "macos") {
|
||||
let want = [Role::SelectAll, Role::Cut, Role::Copy, Role::Paste, Role::Undo, Role::Redo];
|
||||
for (id, role) in ids.iter().zip(want) {
|
||||
if !plain.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
let (_, r, label) = got.iter().find(|(c, _, _)| c == id).unwrap_or_else(|| panic!("{id} not predefined"));
|
||||
assert_eq!(*r, role, "{id}");
|
||||
assert_eq!(label, &by_command(&before, id).map(|i| i.label.to_string()).unwrap_or_default(), "{id} keeps its label");
|
||||
assert!(by_command(&after, id).is_none(), "{id} no longer runs our command");
|
||||
}
|
||||
assert_eq!(got.len(), plain.len());
|
||||
// Unrelated items are untouched.
|
||||
assert!(by_command(&after, "file.importMultiple").is_some());
|
||||
} else {
|
||||
assert!(got.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// #2459: while a text field has the keyboard the Edit menu's Undo and Redo act on the field and
|
||||
/// read plain "Undo" / "Redo"; the project history labels come back once focus leaves.
|
||||
#[test]
|
||||
|
||||
@@ -43,7 +43,7 @@ mod viewer;
|
||||
|
||||
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(crate) use panel::handle_arrow_key;
|
||||
pub use panel::{show, start_rename};
|
||||
pub(crate) use rows::toggle_pick;
|
||||
pub use viewer::viewer_hook;
|
||||
@@ -1,39 +1,66 @@
|
||||
use super::common::{Actions, PARAM_NAME_X, ROW, effect_active, prune_lock, shown_layer};
|
||||
use super::common::{Actions, PARAM_NAME_X, ROW, effect_active, prune_lock, shown_layer, shown_layer_id};
|
||||
use super::editors::{curves_editor, editor_height, histogram_only, levels_editor, object_matte_editor, roto_editor, warp_editor};
|
||||
use super::rows::{FxScope, group_rows, toggle_closed};
|
||||
use super::{Align2, Color32, EffectcraftApp, EvalCtx, GroupKind, Icon, Layer, PropGroup, Rect, Sense, Stroke, Tokens, json, pos2, vec2, widgets};
|
||||
use crate::dock::{PanelKind, WorkspaceExt as _};
|
||||
|
||||
/// Plain Right / Left Arrow expand / collapse the selected effects, as in After Effects, before
|
||||
/// the arrows' layer nudge runs. Only while Effect Controls has the focus and is on screen: the
|
||||
/// front tab of its frame, drawn last frame (a maximized frame hides every other frame and every
|
||||
/// floating window), not behind Home. With no effect header selected the arrows still nudge.
|
||||
pub(crate) fn handle_disclosure_key(app: &mut EffectcraftApp, key: egui::Key) -> bool {
|
||||
/// Plain arrows in Effect Controls, as in After Effects, before their layer nudge runs: Right /
|
||||
/// Left expand / collapse the selected effects, and Down / Up select the next / previous effect
|
||||
/// in the stacking order, from the lowest / highest selected one, stopping at the last / first.
|
||||
/// Only while Effect Controls has the focus and is on screen: the front tab of its frame, drawn
|
||||
/// last frame (a maximized frame hides every other frame and every floating window), not behind
|
||||
/// Home. Only the effect headers selected on the layer the panel shows (the locked one when it is
|
||||
/// locked) count: with none the arrows still nudge.
|
||||
pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, ctx: &egui::Context, key: egui::Key) -> bool {
|
||||
use egui::Key::{ArrowDown, ArrowLeft, ArrowRight, ArrowUp};
|
||||
let panel = PanelKind::EffectControls;
|
||||
if app.ui.focused != panel
|
||||
|| app.ui.start_screen
|
||||
|| app.session.state.text_edit.is_some()
|
||||
|| !app.ui.dock.is_visible(panel)
|
||||
|| !app.dock_rects.iter().any(|(p, _)| *p == panel)
|
||||
|| !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight)
|
||||
|| !matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(comp) = app.session.active_comp() else { return false };
|
||||
let Some(layer) = app.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) else { return false };
|
||||
let Some(effects) = layer.effects() else { return false };
|
||||
let mut handled = false;
|
||||
for g in effects.groups() {
|
||||
if matches!(&g.kind, GroupKind::Effect { .. }) && app.session.state.selected_props.contains(&(layer.id, g.uid)) {
|
||||
if key == egui::Key::ArrowLeft {
|
||||
app.ui.fx_closed.insert(g.uid);
|
||||
} else {
|
||||
app.ui.fx_closed.remove(&g.uid);
|
||||
let Some(layer_id) = shown_layer_id(app) else { return false };
|
||||
let Some(effects) = app.session.active_comp().and_then(|c| c.layer(layer_id)).and_then(|l| l.effects()) else { return false };
|
||||
let headers: Vec<u64> = effects.groups().filter(|g| matches!(&g.kind, GroupKind::Effect { .. })).map(|g| g.uid).collect();
|
||||
let selected = &app.session.state.selected_props;
|
||||
let picked: Vec<usize> = headers.iter().enumerate().filter(|(_, u)| selected.contains(&(layer_id, **u))).map(|(i, _)| i).collect();
|
||||
let (Some(&top), Some(&bottom)) = (picked.first(), picked.last()) else { return false };
|
||||
match key {
|
||||
ArrowUp | ArrowDown => {
|
||||
// Clamped at the ends, where the key still doesn't nudge the layer.
|
||||
let to = if key == ArrowUp { top.saturating_sub(1) } else { bottom.saturating_add(1).min(headers.len().saturating_sub(1)) };
|
||||
if let Some(&uid) = headers.get(to) {
|
||||
// A selection, as a click on the header makes it: no undo step.
|
||||
app.session.state.selected_props = vec![(layer_id, uid)];
|
||||
reveal_effect(ctx, uid);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for uid in picked.iter().filter_map(|i| headers.get(*i)) {
|
||||
if key == ArrowLeft {
|
||||
app.ui.fx_closed.insert(*uid);
|
||||
} else {
|
||||
app.ui.fx_closed.remove(uid);
|
||||
}
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
handled
|
||||
true
|
||||
}
|
||||
|
||||
/// The effect header the next Effect Controls pass scrolls into view.
|
||||
fn reveal_id() -> egui::Id {
|
||||
egui::Id::unique("ec-reveal")
|
||||
}
|
||||
|
||||
/// Scroll Effect Controls so effect `uid`'s header is in view, once it has been laid out.
|
||||
fn reveal_effect(ctx: &egui::Context, uid: u64) {
|
||||
ctx.data_mut(|d| d.insert_temp(reveal_id(), uid));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -434,7 +461,18 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
actions.extend(crate::menus::menu_contents(app, ui, "Effect"));
|
||||
});
|
||||
let content_h = y + scroll.offset - body.min.y;
|
||||
let offset = scroll.offset;
|
||||
scroll.end(ui, &mut app.auto, "effectControls.scroll", content_h, &t);
|
||||
// Up / Down picked an effect: bring its header into view from the next pass (after `end`,
|
||||
// which stores this pass's offset).
|
||||
if let Some(uid) = ctx.data_mut(|d| d.remove_temp::<u64>(reveal_id()))
|
||||
&& let Some(&(_, top)) = tops.iter().find(|(u, _)| *u == uid)
|
||||
{
|
||||
// (With the 4-point gap above it: the panel starts with one and every effect ends with one.)
|
||||
let top = top - body.min.y + offset;
|
||||
widgets::PanelScroll::reveal(&ctx, egui::Id::unique("ec-scroll"), top - 4.0, top + ROW + 2.0, body.height());
|
||||
ctx.request_repaint();
|
||||
}
|
||||
drop_payload(ui, rect, &p, &t, layer.id.0, &mut actions);
|
||||
if ui.input(|i| i.pointer.primary_down()) && actions.iter().any(|(id, _)| id == "prop.set") {
|
||||
app.ui.viewer.property_interacting = true;
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_engine::project::{ItemId, ItemKind, Layer, LayerSource, Project, Property};
|
||||
use effectcraft_engine::render::audio::db_to_gain;
|
||||
use effectcraft_engine::render::audio::{self, db_to_gain};
|
||||
use effectcraft_engine::time::Tick;
|
||||
use egui::{Color32, Painter, Rect, Stroke, pos2};
|
||||
|
||||
@@ -39,6 +39,40 @@ pub fn audio_item(project: &Project, l: &Layer) -> Option<ItemId> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the layer's [in, out) span play mirrored, as far as its waveform goes
|
||||
/// ([`audio::plays_backwards`])? A reversed layer (negative stretch) is audible and plays the
|
||||
/// source span backwards through its time mapping (#3239), which `Layer::layer_time` already
|
||||
/// gives, so only the Backwards effect adds a mirror, and on a reversed layer it undoes the
|
||||
/// reversal. The Audio switch and solo are not followed: a muted layer still shows its waveform.
|
||||
fn played(layer: &Layer) -> bool {
|
||||
audio::plays_backwards(layer)
|
||||
}
|
||||
|
||||
/// The summary bins under the Timeline column for comp times `ta .. tb` (seconds, limited to
|
||||
/// the layer's [in, out) span), as the layer plays them: mirrored over that span when `mirror`
|
||||
/// (see [`played`]), so the first column shows the last samples.
|
||||
fn column_bins<'a>(layer: &Layer, s: &'a Summary, ta: f64, tb: f64, mirror: bool) -> Option<&'a [[f32; 4]]> {
|
||||
let (i, o) = (layer.in_point.seconds(), layer.out_point.seconds());
|
||||
let (ta, tb) = (ta.max(i).min(o), tb.max(i).min(o));
|
||||
if tb <= ta {
|
||||
return None;
|
||||
}
|
||||
let span = i + o;
|
||||
let src = |t: f64| {
|
||||
let t = if mirror { span - t } else { t };
|
||||
layer.layer_time(Tick::from_seconds_f64(t)).seconds() * s.bins_per_sec as f64
|
||||
};
|
||||
let (u, v) = (src(ta), src(tb));
|
||||
let n = s.peaks.len() as i64;
|
||||
let ba = u.min(v).floor() as i64;
|
||||
let bb = (u.max(v).ceil() as i64).max(ba.saturating_add(1));
|
||||
let (ba, bb) = (ba.clamp(0, n), bb.clamp(0, n));
|
||||
if ba >= bb {
|
||||
return None;
|
||||
}
|
||||
s.peaks.get(ba as usize..bb as usize)
|
||||
}
|
||||
|
||||
/// The summary for `item`, starting its computation on first request.
|
||||
pub fn summary(app: &EffectcraftApp, ctx: &egui::Context, item: ItemId) -> Option<Arc<Summary>> {
|
||||
let mut m = app.waveforms.map.lock().ok()?;
|
||||
@@ -91,27 +125,23 @@ fn level_gains(layer: &Layer, levels: Option<&Property>, t: Tick) -> [f32; 2] {
|
||||
}
|
||||
|
||||
/// Draw `layer`'s waveform in `rect` (left channel above right), columns mapped through the
|
||||
/// timeline's time map and the layer's time mapping, limited to its [in, out) span.
|
||||
/// timeline's time map and the layer's time mapping, limited to its [in, out) span and drawn as
|
||||
/// the layer plays (see [`played`]).
|
||||
pub(crate) fn draw(p: &Painter, rect: Rect, tm: &TMap, layer: &Layer, s: &Summary, color: Color32) {
|
||||
let mid = [rect.min.y + rect.height() * 0.25, rect.min.y + rect.height() * 0.75];
|
||||
let half = rect.height() * 0.25 - 1.0;
|
||||
let x0 = tm.x(layer.in_point.seconds()).max(rect.min.x).floor() as i32;
|
||||
let x1 = tm.x(layer.out_point.seconds()).min(rect.max.x).ceil() as i32;
|
||||
let n = s.peaks.len() as i64;
|
||||
let levels = layer.props.sub("audio").and_then(|g| g.get("levels"));
|
||||
for c in 0..2 {
|
||||
p.line_segment([pos2(x0 as f32, mid[c]), pos2(x1 as f32, mid[c])], Stroke::new(1.0, color.gamma_multiply(0.5)));
|
||||
}
|
||||
let mirror = played(layer);
|
||||
for x in x0..x1 {
|
||||
let (ta, tb) = (tm.t(x as f32), tm.t(x as f32 + 1.0));
|
||||
let src = |t: f64| layer.layer_time(Tick::from_seconds_f64(t)).seconds() * s.bins_per_sec as f64;
|
||||
let (ba, bb) = (src(ta).floor() as i64, src(tb).ceil() as i64);
|
||||
let (ba, bb) = (ba.min(bb).clamp(0, n), ba.max(bb).max(ba + 1).clamp(0, n));
|
||||
if ba >= bb {
|
||||
continue;
|
||||
}
|
||||
let Some(bins) = column_bins(layer, s, ta, tb, mirror) else { continue };
|
||||
let mut agg = [0.0f32; 4];
|
||||
for b in &s.peaks[ba as usize..bb as usize] {
|
||||
for b in bins {
|
||||
agg[0] = agg[0].min(b[0]);
|
||||
agg[1] = agg[1].max(b[1]);
|
||||
agg[2] = agg[2].min(b[2]);
|
||||
@@ -202,3 +232,154 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod played_tests {
|
||||
use super::*;
|
||||
use effectcraft_engine::color::Label;
|
||||
use effectcraft_engine::project::{Comp, Footage, FootageKind, GroupKind, build};
|
||||
use effectcraft_engine::render::audio::{footage_peaks, mix_comp};
|
||||
use effectcraft_engine::render::{FootageSource, Image};
|
||||
use effectcraft_engine::time::FrameRate;
|
||||
|
||||
/// Footage audio equal to its source time (seconds) on both channels over [0, 2) s.
|
||||
struct Ramp;
|
||||
impl FootageSource for Ramp {
|
||||
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 t0 = start.seconds();
|
||||
Some(
|
||||
(0..frames)
|
||||
.flat_map(|k| {
|
||||
let t = t0 + k as f64 / rate as f64;
|
||||
let v = if (0.0..2.0).contains(&t) { t as f32 } else { 0.0 };
|
||||
[v, v]
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A project with a 2 s ramp clip and a comp holding one layer of it (start and in 0 s,
|
||||
/// out 1 s) changed by `edit`, and the clip's peak summary.
|
||||
fn setup(edit: &dyn Fn(&mut Layer)) -> (Project, ItemId, Layer, Summary) {
|
||||
let mut p = Project::default();
|
||||
let f = Footage {
|
||||
path: "ramp.wav".into(),
|
||||
kind: FootageKind::Audio,
|
||||
has_audio: true,
|
||||
frame_rate: FrameRate::new(25, 1),
|
||||
duration: Tick::from_seconds_f64(2.0),
|
||||
..Default::default()
|
||||
};
|
||||
let fid = p.add_item("ramp.wav", Label::SeaFoam, None, ItemKind::Footage(f.clone()));
|
||||
let mut comp = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0));
|
||||
let mut l = build::layer(&mut p, &comp, "a", LayerSource::Footage { item: fid }, (0, 0), None);
|
||||
(l.start_time, l.in_point, l.out_point) = (Tick::ZERO, Tick::ZERO, Tick::from_seconds_f64(1.0));
|
||||
edit(&mut l);
|
||||
comp.layers = vec![l.clone()].into();
|
||||
let cid = p.add_item("C", Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
let peaks = footage_peaks(&Ramp, fid, &f, f.duration, BINS_PER_SEC);
|
||||
(p, cid, l, Summary { bins_per_sec: BINS_PER_SEC, peaks })
|
||||
}
|
||||
|
||||
fn add_backwards(l: &mut Layer, enabled: bool) {
|
||||
let mut n = 1_000_000;
|
||||
let mut g = build::Ids(&mut n).group("backwards", "Backwards");
|
||||
g.kind = GroupKind::Effect { effect: "ec.audio.backwards".into() };
|
||||
g.enabled = enabled;
|
||||
l.props.group_mut("effects").expect("effects group").children.push(g.into());
|
||||
}
|
||||
|
||||
/// The loudest left-channel peak drawn in the column for comp times `ta .. tb`.
|
||||
fn drawn(l: &Layer, s: &Summary, ta: f64, tb: f64) -> Option<f32> {
|
||||
column_bins(l, s, ta, tb, played(l)).map(|bins| bins.iter().fold(f32::MIN, |m, b| m.max(b[1])))
|
||||
}
|
||||
|
||||
/// The left-channel sample the mix plays at comp time `t`.
|
||||
fn heard(p: &Project, cid: ItemId, t: f64) -> f32 {
|
||||
mix_comp(p, &Ramp, None, cid, Tick::from_seconds_f64(t), 1, 8000).first().copied().unwrap_or(f32::NAN)
|
||||
}
|
||||
|
||||
/// Columns of `l` over [0, 1) s: each drawn peak against what the mix plays at the column.
|
||||
fn assert_columns_match_the_mix(p: &Project, cid: ItemId, l: &Layer, s: &Summary, name: &str) {
|
||||
let mut max_drawn = 0.0f32;
|
||||
for k in 0..100 {
|
||||
let (ta, tb) = (k as f64 / 100.0, (k + 1) as f64 / 100.0);
|
||||
let d = drawn(l, s, ta, tb).unwrap_or_else(|| panic!("{name}: no column at {ta} s"));
|
||||
let h = heard(p, cid, (ta + tb) * 0.5);
|
||||
// The ramp rises 0.01 per column, so a column's peak is within a couple of steps.
|
||||
assert!((d - h).abs() < 0.03, "{name}: column at {ta} s draws {d}, heard {h}");
|
||||
max_drawn = max_drawn.max(d);
|
||||
}
|
||||
assert!(max_drawn > 0.9, "{name}: the waveform is drawn (loudest {max_drawn})");
|
||||
}
|
||||
|
||||
/// #3238/#3239: a time-reversed layer (Time-Reverse Layer: stretch -100 %, start time at its
|
||||
/// out point) is audible, and its waveform columns agree with the mix: loud first, quiet last.
|
||||
#[test]
|
||||
fn a_reversed_layer_draws_the_waveform_the_mix_plays() {
|
||||
let (p, cid, l, s) = setup(&|l| {
|
||||
l.stretch = -100.0;
|
||||
l.start_time = Tick::from_seconds_f64(1.0);
|
||||
});
|
||||
assert_columns_match_the_mix(&p, cid, &l, &s, "reversed");
|
||||
assert!(heard(&p, cid, 0.005) > 0.98, "the mix plays the clip's last samples first");
|
||||
assert!(heard(&p, cid, 0.995) < 0.02, "and its first samples last");
|
||||
}
|
||||
|
||||
/// Backwards on a reversed layer plays it forwards again, and the waveform follows.
|
||||
#[test]
|
||||
fn a_double_reversal_draws_the_waveform_forwards() {
|
||||
let (p, cid, l, s) = setup(&|l| {
|
||||
l.stretch = -100.0;
|
||||
l.start_time = Tick::from_seconds_f64(1.0);
|
||||
add_backwards(l, true);
|
||||
});
|
||||
assert_columns_match_the_mix(&p, cid, &l, &s, "double reversal");
|
||||
assert!(heard(&p, cid, 0.005) < 0.02, "the mix plays the clip's first samples first");
|
||||
assert!(heard(&p, cid, 0.995) > 0.98, "and its last samples last");
|
||||
}
|
||||
|
||||
/// #3238: with the Backwards audio effect the first column shows the clip's last samples
|
||||
/// and the last column its first, matching what the mix plays there.
|
||||
#[test]
|
||||
fn backwards_draws_the_waveform_mirrored_as_the_mix_plays_it() {
|
||||
let (p, cid, l, s) = setup(&|l| add_backwards(l, true));
|
||||
let first = drawn(&l, &s, 0.0, 0.005).expect("first column");
|
||||
let h = heard(&p, cid, 0.0);
|
||||
assert!(first > 0.98, "first column draws {first}, not the clip's last samples");
|
||||
assert!((first - h).abs() < 0.01, "first column {first}, heard {h}");
|
||||
let last = drawn(&l, &s, 0.995, 1.0).expect("last column");
|
||||
let h = heard(&p, cid, 0.995);
|
||||
assert!(last < 0.02, "last column draws {last}, not the clip's first samples");
|
||||
assert!((last - h).abs() < 0.01, "last column {last}, heard {h}");
|
||||
}
|
||||
|
||||
/// No Backwards effect, a disabled one, or the layer's Effects switch off: the mix plays
|
||||
/// forwards, and so the waveform is drawn.
|
||||
#[test]
|
||||
fn without_an_active_backwards_effect_the_waveform_runs_forwards() {
|
||||
let edits: [(&str, &dyn Fn(&mut Layer)); 3] = [
|
||||
("no effect", &|_| {}),
|
||||
("effect disabled", &|l| add_backwards(l, false)),
|
||||
("effects switch off", &|l| {
|
||||
add_backwards(l, true);
|
||||
l.switches.effects = false;
|
||||
}),
|
||||
];
|
||||
for (name, edit) in edits {
|
||||
let (p, cid, l, s) = setup(edit);
|
||||
let first = drawn(&l, &s, 0.0, 0.005).expect("first column");
|
||||
let h = heard(&p, cid, 0.004);
|
||||
assert!(first < 0.02, "{name}: first column draws {first}");
|
||||
assert!((first - h).abs() < 0.01, "{name}: first column {first}, heard {h}");
|
||||
// A column reaching past the out point draws only up to it.
|
||||
let edge = drawn(&l, &s, 0.998, 1.003).expect("edge column");
|
||||
assert!(edge < 1.001, "{name}: the edge column draws {edge}, past the out point");
|
||||
assert_eq!(drawn(&l, &s, 1.0, 1.005), None, "{name}: a column after the out point");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,6 +264,202 @@ fn effect_header_arrows_leave_viewer_text_editing_alone() {
|
||||
assert_eq!(h.state().ui.fx_closed.iter().copied().collect::<Vec<_>>(), vec![fx], "with the edit over, Left collapses the effect");
|
||||
}
|
||||
|
||||
/// The x and y of `lid`'s Position, which the arrows' layer nudge moves.
|
||||
fn position(h: &Harness<'_, EffectcraftApp>, lid: LayerId) -> [f64; 2] {
|
||||
let p = layer(&h.state().session, lid.0).props.prop("transform/position").unwrap().value.as_vec3();
|
||||
[p[0], p[1]]
|
||||
}
|
||||
|
||||
/// #3585: plain Down / Up select the next / previous effect, a collapsed one too, and stop at the
|
||||
/// last / first one without nudging the layer. Only the selection changes: not the document, the
|
||||
/// time, the history or what is open.
|
||||
#[test]
|
||||
fn effect_header_down_and_up_select_the_next_and_previous_effect() {
|
||||
let (mut h, lid, [(first, _), (second, _), (third, _)]) = header_arrow_harness();
|
||||
let at = rect_of(&h, &format!("effectControls.effect.{first}.name")).center();
|
||||
click(&mut h, at);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, first)]);
|
||||
h.state_mut().ui.fx_closed.insert(second);
|
||||
let project = serde_json::to_value(&h.state().session.project).unwrap();
|
||||
let time = h.state().session.time();
|
||||
let history = (h.state().session.history.undo.len(), h.state().session.history.redo.len());
|
||||
let closed = h.state().ui.fx_closed.clone();
|
||||
let (down, up) = (egui::Key::ArrowDown, egui::Key::ArrowUp);
|
||||
for (key, want) in [(down, second), (down, third), (down, third), (up, second), (up, first), (up, first)] {
|
||||
header_arrow_key(&mut h, key, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, want)], "{key:?}");
|
||||
assert_eq!(serde_json::to_value(&h.state().session.project).unwrap(), project, "{key:?}: the layer is not nudged");
|
||||
assert_eq!(h.state().session.time(), time, "{key:?}");
|
||||
assert_eq!((h.state().session.history.undo.len(), h.state().session.history.redo.len()), history, "{key:?}: no undo step");
|
||||
assert_eq!(h.state().ui.fx_closed, closed, "{key:?}: nothing opens or closes");
|
||||
assert_eq!(h.state().ui.focused, PanelKind::EffectControls);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3585: with several effects selected, Down goes on from the lowest one and Up from the highest,
|
||||
/// leaving one effect selected. Headers of other layers, stale ids and parameters don't count.
|
||||
#[test]
|
||||
fn effect_header_down_and_up_go_on_from_the_ends_of_a_multiple_selection() {
|
||||
let (mut h, lid, [(first, _), (second, prop), (third, _)]) = header_arrow_harness();
|
||||
for (picked, key, want) in [
|
||||
(vec![(lid, second), (lid, first)], egui::Key::ArrowDown, third),
|
||||
(vec![(lid, third), (lid, second)], egui::Key::ArrowUp, first),
|
||||
(vec![(lid, first), (lid, third)], egui::Key::ArrowDown, third),
|
||||
(vec![(lid, first), (lid, third)], egui::Key::ArrowUp, first),
|
||||
(vec![(LayerId(0), first), (lid, u64::MAX), (lid, prop), (lid, second)], egui::Key::ArrowDown, third),
|
||||
] {
|
||||
h.state_mut().session.state.selected_props = picked.clone();
|
||||
header_arrow_key(&mut h, key, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, want)], "{picked:?} {key:?}");
|
||||
}
|
||||
// A shift-click range, picked from the third effect up to the first, as a user would.
|
||||
let at = rect_of(&h, &format!("effectControls.effect.{third}.name")).center();
|
||||
click(&mut h, at);
|
||||
let at = rect_of(&h, &format!("effectControls.effect.{first}.name")).center();
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::SHIFT));
|
||||
click(&mut h, at);
|
||||
h.event(egui::Event::ModifiersChanged(Default::default()));
|
||||
h.step();
|
||||
assert_eq!(h.state().session.state.selected_props.len(), 3, "the range is selected");
|
||||
header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, first)]);
|
||||
}
|
||||
|
||||
/// #3585: without an effect header selected on the panel's layer, or with the panel or the
|
||||
/// keyboard elsewhere, plain Up / Down keep nudging the layer (or go to whoever owns the keys),
|
||||
/// and the effect selection stays.
|
||||
#[test]
|
||||
fn effect_header_down_and_up_leave_the_nudge_and_other_keyboard_owners_alone() {
|
||||
let (mut h, lid, [(first, _), (second, prop), _]) = header_arrow_harness();
|
||||
// A parameter, a stale header and another layer's header: the layer moves down, then up.
|
||||
let picked = vec![(lid, prop), (lid, u64::MAX), (LayerId(0), first)];
|
||||
h.state_mut().session.state.selected_props = picked.clone();
|
||||
let y = position(&h, lid)[1];
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
// (One pixel at the viewer's magnification.)
|
||||
let step = position(&h, lid)[1] - y;
|
||||
assert!(step > 0.0, "Down still nudges the layer");
|
||||
header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE);
|
||||
assert!((position(&h, lid)[1] - y).abs() < 1e-6, "Up still nudges the layer");
|
||||
assert_eq!(h.state().session.state.selected_props, picked);
|
||||
|
||||
// With an effect selected: Shift nudges ten pixels, Cmd/Ctrl keeps its own meaning.
|
||||
h.state_mut().session.state.selected_props = vec![(lid, second)];
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::SHIFT);
|
||||
assert!((position(&h, lid)[1] - (y + 10.0 * step)).abs() < 1e-6, "Shift+Down nudges ten pixels");
|
||||
header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::SHIFT);
|
||||
assert!((position(&h, lid)[1] - y).abs() < 1e-6);
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::COMMAND);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, second)], "Cmd/Ctrl+Down keeps the effect selection");
|
||||
|
||||
// Another panel, a dialog, the context menu and the rename field own the arrows.
|
||||
let stays = |h: &mut Harness<'_, EffectcraftApp>, why: &str| {
|
||||
for key in [egui::Key::ArrowDown, egui::Key::ArrowUp] {
|
||||
header_arrow_key(h, key, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, second)], "{why}: {key:?}");
|
||||
}
|
||||
};
|
||||
h.state_mut().ui.focused = PanelKind::Composition;
|
||||
stays(&mut h, "another panel");
|
||||
h.state_mut().ui.focused = PanelKind::EffectControls;
|
||||
h.state_mut().dialog = Some(effectcraft_ui_egui::Dialog::About);
|
||||
stays(&mut h, "a dialog");
|
||||
h.state_mut().dialog = None;
|
||||
h.run_steps(3);
|
||||
let at = rect_of(&h, &format!("effectControls.effect.{second}.name")).center();
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(egui::Popup::is_any_open(&h.ctx), "the effect context menu is open");
|
||||
stays(&mut h, "the context menu");
|
||||
header_arrow_key(&mut h, egui::Key::Escape, egui::Modifiers::NONE);
|
||||
h.run_steps(3);
|
||||
double_click(&mut h, at);
|
||||
h.run_steps(3);
|
||||
assert!(h.state().auto.find(&format!("effectControls.effect.{second}.nameEdit")).is_some(), "the rename field is open");
|
||||
stays(&mut h, "the rename field");
|
||||
assert!(h.state().auto.find(&format!("effectControls.effect.{second}.nameEdit")).is_some());
|
||||
}
|
||||
|
||||
/// #3585: a hidden Effect Controls (closed, under a maximized frame, behind Home) with the focus
|
||||
/// left on it doesn't take Up / Down: they nudge the layer.
|
||||
#[test]
|
||||
fn effect_header_down_and_up_ignore_a_hidden_panel() {
|
||||
for hidden in ["closed", "maximized", "home"] {
|
||||
let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness();
|
||||
h.state_mut().session.state.selected_props = vec![(lid, fx)];
|
||||
match hidden {
|
||||
"closed" => h.state_mut().close_panel(PanelKind::EffectControls),
|
||||
"maximized" => h.state_mut().toggle_maximize(PanelKind::Composition),
|
||||
_ => h.state_mut().ui.start_screen = true,
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.focused, PanelKind::EffectControls, "{hidden}: stale focus is preserved");
|
||||
let y = position(&h, lid)[1];
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, fx)], "{hidden}");
|
||||
assert!(position(&h, lid)[1] > y, "{hidden}: Down still nudges the layer");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3585: locked to a layer that isn't selected, Effect Controls' arrows act on the effects it
|
||||
/// shows: Down / Up select among them and Left / Right close and open them.
|
||||
#[test]
|
||||
fn effect_header_arrows_act_on_the_locked_layer() {
|
||||
let (mut h, lid, [(first, _), (second, _), _]) = header_arrow_harness();
|
||||
let comp = h.state().session.active_comp_id().unwrap().0;
|
||||
let other = h.state_mut().session.execute("layer.newSolid", json!({"name": "Other", "color": "#202020"})).unwrap()["layer"].as_u64().unwrap();
|
||||
h.state_mut().ui.effect_controls_lock = Some(effectcraft_ui_egui::state::EffectControlsLock { comp, layer: lid.0 });
|
||||
h.state_mut().session.state.selected_layers = vec![LayerId(other)];
|
||||
h.state_mut().session.state.selected_props = vec![(lid, first)];
|
||||
h.state_mut().ui.focused = PanelKind::EffectControls;
|
||||
h.run_steps(3);
|
||||
assert!(shows_effect(&h, first), "the locked panel shows the first layer");
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(lid, second)]);
|
||||
header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().ui.fx_closed.iter().copied().collect::<Vec<_>>(), vec![second], "Left closes the locked layer's effect");
|
||||
header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE);
|
||||
assert!(h.state().ui.fx_closed.is_empty());
|
||||
}
|
||||
|
||||
/// #3585: a long effect list scrolls so the effect Down / Up picks stays in view.
|
||||
#[test]
|
||||
fn effect_header_down_and_up_scroll_the_picked_effect_into_view() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Long", "width": 32, "height": 18, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let lid = s.execute("layer.newSolid", json!({"name": "Controls", "color": "#40b080"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let fx: Vec<u64> =
|
||||
(0..16).map(|_| s.execute("effect.apply", json!({"layers": [lid], "effect": "Point Control"})).unwrap()["effects"][0].as_u64().unwrap()).collect();
|
||||
s.state.selected_props = vec![(LayerId(lid), fx[0])];
|
||||
let mut app = EffectcraftApp::new(s);
|
||||
app.show_panel(PanelKind::EffectControls);
|
||||
app.toggle_maximize(PanelKind::EffectControls);
|
||||
app.ui.focused = PanelKind::EffectControls;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(800.0, 300.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
|
||||
h.run_steps(4);
|
||||
let panel = rect_of(&h, "panel.EffectControls");
|
||||
let last = fx[fx.len() - 1];
|
||||
assert!(!panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{last}"))), "the last effect starts out of view");
|
||||
for _ in 1..fx.len() {
|
||||
header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
h.run_steps(2);
|
||||
let (_, uid) = h.state().session.state.selected_props[0];
|
||||
assert!(panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{uid}"))), "Down keeps effect {uid} in view");
|
||||
}
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(LayerId(lid), last)]);
|
||||
for _ in 1..fx.len() {
|
||||
header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE);
|
||||
h.run_steps(2);
|
||||
let (_, uid) = h.state().session.state.selected_props[0];
|
||||
assert!(panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{uid}"))), "Up keeps effect {uid} in view");
|
||||
}
|
||||
assert_eq!(h.state().session.state.selected_props, vec![(LayerId(lid), fx[0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_controls_widgets_register_automation_ids() {
|
||||
let (app, x) = app();
|
||||
|
||||
@@ -64,6 +64,13 @@ the GPU is performance, not parity.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Where the padding budget cuts the margin, the shadow keeps its full blur (σ = Softness / 2) up to the buffer's edge, where it is cut; that case renders on the CPU |
|
||||
| 2026-11-17 | minor | Radial Blur: Amount takes After Effects' valid range 0..1000 (slider and default unchanged); Zoom past 200 spreads its samples from the centre outwards instead of sampling the layer mirrored through the centre (CPU and GPU; not yet measured against After Effects past Amount 200) |
|
||||
| 2026-11-17 | minor | Gaussian Blur: Blurriness takes After Effects' recorded valid range 0..30000 (was 0..3000; default and 0..50 slider unchanged). Padding stays within the effect pixel budget at the top of the range (CPU and GPU), and Roto Brush analyses 0.24 saved below a Gaussian Blur still match (#3460) |
|
||||
| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) Amount is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU). Locked pinning on a layer under a pixel across no longer crashes |
|
||||
| 2026-11-17 | minor | Fractal and Turbulent Noise: Sub Scaling takes After Effects' 10..10000 (slider and default unchanged), and above 100 each octave is larger than the last instead of being capped at 100; octave scales stay finite at Complexity 20 (CPU and GPU) |
|
||||
| 2026-11-17 | minor | CC Power Pin: Expansion (Top, Left, Right, Bottom) takes After Effects' minimum of −200 % (hard range −200..1000; defaults and sliders unchanged). When two opposite sides add up to less than −100 % the source rectangle flips (CPU and GPU) |
|
||||
| 2026-11-17 | minor | Sharpen: Amount takes After Effects' recorded valid range, 0..4000 (was 0..500; default and the 0..100 slider unchanged). Sharpen stays linear in Amount and finite up to 4000, CPU and GPU agree there |
|
||||
| 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) |
|
||||
| 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) |
|
||||
| 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) |
|
||||
|
||||
+3
-3
@@ -3,13 +3,13 @@
|
||||
<!-- Generated from the effect registry (crates/effects/src/catalog.rs); do not edit by hand.
|
||||
Regenerate: UPDATE_DOCS=1 cargo test -p effectcraft-effects --lib effects_doc_is_current -->
|
||||
|
||||
EffectCraft ships 308 effects with 2988 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
|
||||
EffectCraft ships 308 effects with 2992 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
|
||||
|
||||
- **GPU**: 280 effects also run on the GPU compositor with identical results.
|
||||
- **32**: 308 effects process 32-bit float (HDR, overbright) pixels without clamping.
|
||||
- **Status**: 308 implemented in full, 0 partial (what is missing is listed).
|
||||
|
||||
Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`).
|
||||
Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`). A parameter that was renamed keeps its old name working in expressions of older projects: `effect("CC Ball Action")("Instability State")` still reads Scatter Motion.
|
||||
|
||||
## 3D Channel
|
||||
|
||||
@@ -319,7 +319,7 @@ Effects are addressed by id (`ec.<category>.<name>`) or display name in commands
|
||||
|
||||
| Effect | Id | Params | GPU | 32 | Status |
|
||||
|---|---|---:|:-:|:-:|---|
|
||||
| Ball Grid | `ec.sim.ccballaction` | 8 | GPU | 32 | Implemented |
|
||||
| Ball Grid | `ec.sim.ccballaction` | 12 | GPU | 32 | Implemented |
|
||||
| Bubbles | `ec.sim.ccbubbles` | 7 | GPU | 32 | Implemented |
|
||||
| Card Dance | `ec.sim.carddance` | 53 | GPU | 32 | Implemented |
|
||||
| Caustics | `ec.sim.caustics` | 28 | GPU | 32 | Implemented |
|
||||
|
||||
Reference in new issue
Block a user