mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-29 17:44:05 +01:00
Merge main into menu-parity branch; point AE menu entries at main's real commands
- Integrate main (render queue, timeline/keys, time remap, masks/pen, 3D, MCP/CLI). - Menu tree now runs renderQueue.add, layer.enableTimeRemap, layer.timeReverse, layer.freezeFrame/OnLastFrame, prop.separateDimensions, mask.setClosed, layer.cameraSettings, view.3d.* / view.3d.last / view.reset3DView, main's layer.autoOrient and keyframe velocity/interpolation/time-stretch dialogs; matching stubs deleted (view.3d.default stays disabled). - Keyframe clipboard is main's (keys.copy/paste); Paste Reversed Keyframes reuses it. Animation-menu commands moved to commands/animation.rs. - Main's spec menu paths/labels aligned with AE (Camera Settings under Layer > Camera, "..." labels, Freeze On Last Frame). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
c99527708f
129 files changed
+27041
-1197
No files matched your search
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"effectcraft": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--demo"]
|
||||
},
|
||||
"effectcraft-app": {
|
||||
"command": "cargo",
|
||||
"args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--bridge", "9877"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ a command, everything is agent-drivable, and the quality gates (`cargo xtask ci`
|
||||
|
||||
## See also
|
||||
|
||||
- [CONTRIBUTING.md](CONTRIBUTING.md) and [docs/contributing.md](docs/contributing.md): setup, gates, commits, how to add things
|
||||
- [CONTRIBUTING.md](CONTRIBUTING.md): setup, gates, commits, how to add things
|
||||
- [docs/architecture.md](docs/architecture.md): layers, data model, commands, pipeline
|
||||
- [docs/testing.md](docs/testing.md): oracle tests, criteria, benchmarks
|
||||
- [docs/agents.md](docs/agents.md): driving EffectCraft over MCP / the control channel, and the agent work loop
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Contributing to EffectCraft
|
||||
|
||||
Thanks for helping. Please read [AGENTS.md](AGENTS.md) first: its rules on assets and clean-room
|
||||
work apply to everyone, people and AI agents alike, and they are not negotiable.
|
||||
|
||||
## Setup
|
||||
|
||||
You need [Rust](https://rustup.rs/) 1.95 or newer.
|
||||
|
||||
```sh
|
||||
cargo run -p effectcraft # the desktop app, with the demo project
|
||||
cargo test --workspace
|
||||
cargo xtask ci # what every commit must pass
|
||||
```
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Clean room.** Work from After Effects' public documentation and its observable behaviour only.
|
||||
Never use Adobe artwork, presets or code, and never copy GPL/LGPL/AGPL code.
|
||||
- **Every asset is attributed.** Add a `.attribution` sidecar and an [ATTRIBUTION.md](ATTRIBUTION.md)
|
||||
row; `cargo xtask assets` checks it.
|
||||
- **Layering.** Nothing below the interface layer depends on UI or OS crates; see
|
||||
[docs/architecture.md](docs/architecture.md).
|
||||
- **Everything is a command.** New features are engine commands with an id, label, menu path,
|
||||
shortcut and parameters, so the UI, the CLI and the MCP server get them at once. Interactive
|
||||
widgets register an automation id.
|
||||
- **Tests with every change**, and green `cargo xtask ci` before every commit. One task per commit.
|
||||
|
||||
## How to add…
|
||||
|
||||
- **An effect:** add an `EffectSpec` in `crates/effects` (AE display name, category, parameters
|
||||
with AE's names, defaults and ranges) and its render function, with a determinism test and a
|
||||
behaviour test. If it reads the clock directly, add it to `TIME_DEPENDENT`.
|
||||
- **A command:** register it with `cmd!` in `crates/engine/src/commands/`, place it in the menu
|
||||
tree in `crates/engine/src/menus.rs`, and test it including undo.
|
||||
- **A panel or dialog:** `crates/ui-egui/src/panels/`; look at the result with the headless
|
||||
snapshot tool described in [docs/testing.md](docs/testing.md).
|
||||
|
||||
## Talk to us
|
||||
|
||||
Questions, ideas and bug reports are welcome on [Discord](https://discord.gg/artcraft) and in
|
||||
GitHub issues.
|
||||
Generated
+79
-1
@@ -875,6 +875,16 @@ version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79"
|
||||
|
||||
[[package]]
|
||||
name = "cpu-time"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9e393a7668fe1fad3075085b86c781883000b4ede868f43627b34a87c8b7ded"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
@@ -1055,10 +1065,23 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-cli"
|
||||
name = "effectcraft-automation"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"effectcraft-engine",
|
||||
"image",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cpu-time",
|
||||
"effectcraft-automation",
|
||||
"effectcraft-engine",
|
||||
"effectcraft-host",
|
||||
"effectcraft-render",
|
||||
"effectcraft-time",
|
||||
"image",
|
||||
@@ -1106,6 +1129,27 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-export"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"effectcraft-color",
|
||||
"effectcraft-media",
|
||||
"effectcraft-project",
|
||||
"effectcraft-raster",
|
||||
"effectcraft-render",
|
||||
"effectcraft-time",
|
||||
"filmcraft-aac",
|
||||
"filmcraft-h264enc",
|
||||
"filmcraft-isobmff",
|
||||
"filmcraft-prores",
|
||||
"gif",
|
||||
"image",
|
||||
"log",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "effectcraft-expr"
|
||||
version = "0.1.0"
|
||||
@@ -1134,6 +1178,7 @@ name = "effectcraft-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"effectcraft-engine",
|
||||
"effectcraft-export",
|
||||
"effectcraft-expr",
|
||||
"effectcraft-media",
|
||||
"effectcraft-project",
|
||||
@@ -1221,6 +1266,7 @@ dependencies = [
|
||||
"kurbo",
|
||||
"log",
|
||||
"rayon",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1699,6 +1745,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filmcraft-h264enc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/filmcraft?rev=89cfbf24f698b0f0e538eb7795929f19bbfb1dbb#89cfbf24f698b0f0e538eb7795929f19bbfb1dbb"
|
||||
dependencies = [
|
||||
"filmcraft-bitstream",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filmcraft-hevc"
|
||||
version = "0.1.0"
|
||||
@@ -5043,6 +5099,22 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||
dependencies = [
|
||||
"winapi-i686-pc-windows-gnu",
|
||||
"winapi-x86_64-pc-windows-gnu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-i686-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
@@ -5052,6 +5124,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
|
||||
+18
-1
@@ -23,6 +23,7 @@ effectcraft-text = { path = "crates/text" }
|
||||
effectcraft-effects = { path = "crates/effects" }
|
||||
effectcraft-render = { path = "crates/render" }
|
||||
effectcraft-media = { path = "crates/media" }
|
||||
effectcraft-export = { path = "crates/export" }
|
||||
effectcraft-expr = { path = "crates/expr" }
|
||||
effectcraft-engine = { path = "crates/engine" }
|
||||
effectcraft-host = { path = "crates/host" }
|
||||
@@ -35,6 +36,7 @@ serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
rayon = "1"
|
||||
gif = "0.14"
|
||||
proptest = "1"
|
||||
|
||||
# scripting (expressions)
|
||||
@@ -48,12 +50,17 @@ harfrust = { version = "0.12", default-features = false, features = ["std"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
# media codecs + containers: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
|
||||
# Only `crates/media` (and later `crates/export`) may depend on these.
|
||||
# Only `crates/media` and `crates/export` may depend on these.
|
||||
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
# encoders + muxer (crates/export)
|
||||
filmcraft-h264enc = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-prores = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-aac = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
filmcraft-isobmff = { git = "https://github.com/storytold/filmcraft", rev = "89cfbf24f698b0f0e538eb7795929f19bbfb1dbb" }
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
@@ -68,6 +75,10 @@ rfd = "0.17"
|
||||
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
|
||||
# filmcraft-color = { path = "../filmcraft/crates/color" }
|
||||
# filmcraft-time = { path = "../filmcraft/crates/time" }
|
||||
# filmcraft-h264enc = { path = "../filmcraft/crates/h264enc" }
|
||||
# filmcraft-prores = { path = "../filmcraft/crates/prores" }
|
||||
# filmcraft-aac = { path = "../filmcraft/crates/aac" }
|
||||
# filmcraft-isobmff = { path = "../filmcraft/crates/isobmff" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -101,10 +112,16 @@ opt-level = 3
|
||||
[profile.dev.package.effectcraft-media]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.effectcraft-export]
|
||||
opt-level = 3
|
||||
|
||||
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
|
||||
[profile.dev.package.filmcraft-h264]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-h264enc]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.filmcraft-hevc]
|
||||
opt-level = 3
|
||||
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# Roadmap
|
||||
|
||||
EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written
|
||||
from scratch in Rust. This is where it stands. The milestones overlap; several are worked on at
|
||||
once.
|
||||
|
||||
| | Milestone | State |
|
||||
|---|---|---|
|
||||
| M0 | Skeleton: crates, compositor, the After Effects style shell, control channel, `cargo xtask` | Done (web build pending) |
|
||||
| M1 | Keyframes: temporal and spatial interpolation, Easy Ease, roving, velocity | Done |
|
||||
| M2 | Compositing: 38 blend modes, track mattes, parenting, adjustment layers | Done |
|
||||
| M3 | Project operations: settings dialogs, layer commands, `.ecproj`, undo, After Effects menu bar | Mostly done |
|
||||
| M4 | Preview: precomps, motion blur, cached playback | Mostly done |
|
||||
| M5 | Timeline depth: graph editor, keyframe clipboard and dialogs, time remapping, pick-whips, expression editor | Done |
|
||||
| M6 | Shapes, masks and footage: shape operators, masks and the pen tool, video and image import | Done |
|
||||
| M7 | 3D: 3D layers, cameras, lights, shadows, depth of field, 3D views and camera tools | In review |
|
||||
| M8 | Expressions with the After Effects object model | Done |
|
||||
| M9 | Text and effects: text animators, 241 effects | In progress (layer styles, more selectors) |
|
||||
| M10 | Export: render queue, H.264, ProRes, image sequences, GIF, audio | Done |
|
||||
| M11 | Animation tools: presets, Motion Sketch, Wiggler, Lottie, audio playback | Next |
|
||||
| M12 | Performance: layer cache and parallel compositing (done), GPU compositing, disk cache, motion tracking | In progress |
|
||||
| M13+ | Time effects, puppet, paint, roto, preferences and shortcut editor, the web app, a plugin API | Planned |
|
||||
| M14 | Built for agents: MCP server, command-line tool, control channel | Done |
|
||||
|
||||
Come tell us what matters most to you on [Discord](https://discord.gg/artcraft).
|
||||
@@ -14,7 +14,10 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
effectcraft-engine = { workspace = true }
|
||||
effectcraft-host = { workspace = true }
|
||||
effectcraft-automation = { workspace = true }
|
||||
effectcraft-render = { workspace = true }
|
||||
effectcraft-time = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
image = { workspace = true }
|
||||
cpu-time = "1"
|
||||
@@ -1,90 +1,666 @@
|
||||
//! EffectCraft headless CLI.
|
||||
//! EffectCraft headless CLI: one-shot agent commands, frame rendering and the MCP server.
|
||||
//!
|
||||
//! ```text
|
||||
//! effectcraft-cli frame [project.ecproj | --demo] [--comp NAME] [--time S | --frame N] [--scale K] --out out.png
|
||||
//! effectcraft-cli run [project.ecproj | --demo] '<command-id>' '<json params>' … (prints results)
|
||||
//! effectcraft-cli commands (lists commands)
|
||||
//! effectcraft-cli info project + engine summary
|
||||
//! effectcraft-cli commands [--filter TEXT] [--enabled] list engine commands
|
||||
//! effectcraft-cli exec <command-id> [--params JSON] run one command
|
||||
//! effectcraft-cli run <id> <json> [<id> <json> …] run several commands in order
|
||||
//! effectcraft-cli props <comp> <layer> [--flat] [--time S] a layer's property tree (with paths)
|
||||
//! effectcraft-cli get <comp> <layer> <path> [--time S] read a property
|
||||
//! effectcraft-cli set <comp> <layer> <path> <value> [--time S] [--expression E]
|
||||
//! effectcraft-cli render-frame [--comp C] [--time S|--frame N] [--max-side PX|--scale K] [--out F.png]
|
||||
//! effectcraft-cli render [--comp C] --out FILE [--format h264|prores|png|jpeg|tiff|exr|gif] [--start S] [--end S]
|
||||
//! [--work-area] [--fps N] [--resolution full|half|third|quarter|K] [--quality best|draft] [--channels rgb|rgba]
|
||||
//! [--jpeg-quality N] [--bitrate KBPS] [--prores proxy|lt|standard|hq|4444|4444xq] [--audio auto|on|off]
|
||||
//! effectcraft-cli render F.ecproj --queue render the project's Render Queue
|
||||
//! effectcraft-cli bench [--comp C] [--time S] [--scale K] [--n N] [--play N] render timings
|
||||
//! effectcraft-cli mcp [--bridge PORT] MCP server on stdio
|
||||
//!
|
||||
//! Project: --project F.ecproj (or a positional *.ecproj) | --demo | --empty (default: demo; mcp: empty)
|
||||
//! Saving: --save (back to --project) | --save-as F.ecproj
|
||||
//! Bridge: --bridge PORT drives a running `effectcraft --control PORT` instead of a headless session
|
||||
//! Output: --json for one compact JSON document on stdout (errors: {"error": …}, exit 1)
|
||||
//! ```
|
||||
//!
|
||||
//! `<comp>` is a comp id or name (`-` = the active comp); `<layer>` an id, `#n` or name; `<value>`
|
||||
//! is JSON (`50`, `[960,540]`, `"#ff0000"`) or a bare string. See `docs/agents.md`.
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
use effectcraft_render::RenderOpts;
|
||||
use effectcraft_time::Tick;
|
||||
use effectcraft_automation::tools::{self, Reply};
|
||||
use effectcraft_automation::{Backend, McpServer};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn usage() -> ! {
|
||||
eprintln!("usage: effectcraft-cli <frame|run|commands> [args] (see --help in source docs)");
|
||||
std::process::exit(2)
|
||||
const USAGE: &str = "usage: effectcraft-cli <info|commands|exec|run|props|get|set|render-frame|render|mcp> [args] [--json]
|
||||
info project + engine summary
|
||||
commands [--filter TEXT] [--enabled] list engine commands
|
||||
exec <command-id> [--params JSON] run one engine command
|
||||
run <id> <json> [<id> <json> ...] run several commands in order
|
||||
props <comp> <layer> [--flat] [--time S] a layer's property tree with paths
|
||||
get <comp> <layer> <path> [--time S] read a property
|
||||
set <comp> <layer> <path> <value> [--time S] [--expression E]
|
||||
render-frame [--comp C] [--time S | --frame N] [--max-side PX | --scale K] [--out F.png]
|
||||
render [--comp C] --out FILE [--format F] [--start S] [--end S] [--work-area] [--fps N]
|
||||
[--resolution full|half|third|quarter|K] [--quality best|draft] [--channels rgb|rgba]
|
||||
[--jpeg-quality N] [--bitrate KBPS] [--prores PROFILE] [--audio auto|on|off] | --queue
|
||||
bench [--comp C] [--time S] [--scale K] [--n N] [--play N] per-layer/effect render timings;
|
||||
--play N renders N consecutive frames with/without the layer cache
|
||||
mcp [--bridge PORT] MCP server (JSON-RPC over stdio)
|
||||
options: --project F.ecproj | --demo | --empty --save | --save-as F --bridge PORT --json
|
||||
<comp>: id or name, '-' = active comp; <layer>: id, '#n' or name; <value>: JSON or bare string";
|
||||
|
||||
/// Options that take a value.
|
||||
const VALUED: &[&str] = &[
|
||||
"--n",
|
||||
"--play",
|
||||
"--params",
|
||||
"--project",
|
||||
"--bridge",
|
||||
"--save-as",
|
||||
"--filter",
|
||||
"--time",
|
||||
"--frame",
|
||||
"--comp",
|
||||
"--max-side",
|
||||
"--scale",
|
||||
"--out",
|
||||
"--expression",
|
||||
"--depth",
|
||||
// render
|
||||
"--format",
|
||||
"--start",
|
||||
"--end",
|
||||
"--fps",
|
||||
"--resolution",
|
||||
"--quality",
|
||||
"--channels",
|
||||
"--jpeg-quality",
|
||||
"--bitrate",
|
||||
"--prores",
|
||||
"--audio",
|
||||
];
|
||||
|
||||
struct Args {
|
||||
pos: Vec<String>,
|
||||
opts: Vec<(String, Option<String>)>,
|
||||
/// `--project F` or a positional `*.ecproj`.
|
||||
project: Option<String>,
|
||||
}
|
||||
|
||||
fn open(s: &mut Session, args: &[String]) {
|
||||
if let Some(p) = args.iter().find(|a| a.ends_with(".ecproj")) {
|
||||
if let Err(e) = s.execute("file.open", json!({"path": p})) {
|
||||
eprintln!("effectcraft: {e}");
|
||||
std::process::exit(1);
|
||||
impl Args {
|
||||
fn parse(raw: Vec<String>) -> Result<Args, String> {
|
||||
let (mut pos, mut opts) = (vec![], vec![]);
|
||||
let mut it = raw.into_iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a.starts_with("--") && a.len() > 2 {
|
||||
let (k, inline) = match a.split_once('=') {
|
||||
Some((k, v)) => (k.to_string(), Some(v.to_string())),
|
||||
None => (a, None),
|
||||
};
|
||||
if VALUED.contains(&k.as_str()) {
|
||||
let v = inline.or_else(|| it.next()).ok_or_else(|| format!("{k} needs a value"))?;
|
||||
opts.push((k, Some(v)));
|
||||
} else {
|
||||
opts.push((k, None));
|
||||
}
|
||||
} else {
|
||||
pos.push(a);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No project given (with or without --demo): open the demo project.
|
||||
let _ = s.execute("file.openDemoProject", json!({}));
|
||||
let mut a = Args { pos, opts, project: None };
|
||||
a.project = match a.opt("--project") {
|
||||
Some(p) => Some(p.to_string()),
|
||||
None => a.pos.iter().position(|x| x.ends_with(".ecproj")).map(|i| a.pos.remove(i)),
|
||||
};
|
||||
Ok(a)
|
||||
}
|
||||
fn flag(&self, k: &str) -> bool {
|
||||
self.opts.iter().any(|(o, _)| o == k)
|
||||
}
|
||||
fn opt(&self, k: &str) -> Option<&str> {
|
||||
self.opts.iter().rev().find(|(o, _)| o == k).and_then(|(_, v)| v.as_deref())
|
||||
}
|
||||
fn num(&self, k: &str) -> Result<Option<f64>, String> {
|
||||
self.opt(k).map(|v| v.parse::<f64>().map_err(|_| format!("{k}: not a number: {v}"))).transpose()
|
||||
}
|
||||
}
|
||||
|
||||
fn opt<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
/// A comp/layer reference: number → id, `-` → none (active), else a name / `#n`.
|
||||
fn reference(s: &str) -> Option<Value> {
|
||||
match s {
|
||||
"-" | "" => None,
|
||||
_ => Some(s.parse::<u64>().map(Value::from).unwrap_or_else(|_| json!(s))),
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON if it parses, else the bare string.
|
||||
fn value_arg(s: &str) -> Value {
|
||||
serde_json::from_str(s).unwrap_or_else(|_| json!(s))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let Some(cmd) = args.first().cloned() else { usage() };
|
||||
let rest = &args[1..];
|
||||
let mut s = Session::default();
|
||||
match cmd.as_str() {
|
||||
"frame" => {
|
||||
open(&mut s, rest);
|
||||
if let Some(c) = opt(rest, "--comp") {
|
||||
let _ = s.execute("comp.open", json!({"comp": c}));
|
||||
let raw: Vec<String> = std::env::args().skip(1).collect();
|
||||
if raw.is_empty() || raw.iter().any(|a| a == "-h" || a == "--help") {
|
||||
println!("{USAGE}");
|
||||
std::process::exit(if raw.is_empty() { 2 } else { 0 });
|
||||
}
|
||||
let mut args = match Args::parse(raw) {
|
||||
Ok(a) => a,
|
||||
Err(e) => fail_usage(&e),
|
||||
};
|
||||
let json_out = args.flag("--json");
|
||||
if args.pos.is_empty() {
|
||||
fail_usage("missing subcommand");
|
||||
}
|
||||
let cmd = args.pos.remove(0);
|
||||
match run(&cmd, &args, json_out) {
|
||||
Ok(()) => {}
|
||||
Err(Failure::Usage(e)) => fail_usage(&e),
|
||||
Err(Failure::Error(e)) => {
|
||||
if json_out {
|
||||
println!("{}", json!({"error": e}));
|
||||
}
|
||||
let cid = s.active_comp_id().unwrap_or_else(|| {
|
||||
eprintln!("no composition");
|
||||
std::process::exit(1)
|
||||
});
|
||||
let comp = s.project.comp(cid).cloned().unwrap_or_else(|| std::process::exit(1));
|
||||
let t = if let Some(f) = opt(rest, "--frame").and_then(|f| f.parse().ok()) {
|
||||
comp.frame_rate.tick_of(f)
|
||||
} else {
|
||||
opt(rest, "--time").and_then(|v| v.parse().ok()).map(Tick::from_seconds_f64).unwrap_or(s.time())
|
||||
};
|
||||
let scale = opt(rest, "--scale").and_then(|v| v.parse().ok()).unwrap_or(1.0);
|
||||
let out = opt(rest, "--out").unwrap_or("frame.png");
|
||||
let t0 = std::time::Instant::now();
|
||||
let img = s.render(cid, t, RenderOpts { scale, ..Default::default() });
|
||||
let el = t0.elapsed();
|
||||
let bg = comp.background;
|
||||
let rgba = img.to_rgba8_over(bg);
|
||||
image::save_buffer(out, &rgba, img.width, img.height, image::ColorType::Rgba8).unwrap_or_else(|e| {
|
||||
eprintln!("cannot write {out}: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
eprintln!("rendered {}x{} at {:.3}s in {:.1} ms → {out}", img.width, img.height, t.seconds(), el.as_secs_f64() * 1000.0);
|
||||
eprintln!("effectcraft-cli {cmd}: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
"run" => {
|
||||
open(&mut s, rest);
|
||||
let pairs: Vec<&String> = rest.iter().filter(|a| !a.ends_with(".ecproj") && *a != "--demo").collect();
|
||||
for ch in pairs.chunks(2) {
|
||||
let params: Value = ch.get(1).and_then(|p| serde_json::from_str(p).ok()).unwrap_or(json!({}));
|
||||
match s.execute(ch[0], params) {
|
||||
Ok(v) => println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()),
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", ch[0]);
|
||||
std::process::exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn fail_usage(e: &str) -> ! {
|
||||
eprintln!("effectcraft-cli: {e}\n{USAGE}");
|
||||
std::process::exit(2)
|
||||
}
|
||||
|
||||
enum Failure {
|
||||
Usage(String),
|
||||
Error(String),
|
||||
}
|
||||
impl From<effectcraft_automation::Error> for Failure {
|
||||
fn from(e: effectcraft_automation::Error) -> Self {
|
||||
Failure::Error(e.to_string())
|
||||
}
|
||||
}
|
||||
impl From<String> for Failure {
|
||||
fn from(e: String) -> Self {
|
||||
Failure::Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_err<T>(m: &str) -> Result<T, Failure> {
|
||||
Err(Failure::Usage(m.to_string()))
|
||||
}
|
||||
|
||||
/// Build the backend: a bridge to the app, or a headless session with the requested project.
|
||||
fn backend(args: &Args, default_demo: bool) -> Result<Backend, Failure> {
|
||||
if let Some(addr) = args.opt("--bridge") {
|
||||
if args.project.is_some() || args.flag("--demo") {
|
||||
return usage_err("--bridge drives the running app's project; use `exec file.open` to open another");
|
||||
}
|
||||
return Ok(Backend::bridge(addr)?);
|
||||
}
|
||||
let mut b = Backend::headless(effectcraft_host::session());
|
||||
if let Some(p) = &args.project {
|
||||
b.exec("file.open", json!({"path": p}))?;
|
||||
} else if args.flag("--demo") || (default_demo && !args.flag("--empty")) {
|
||||
b.exec("file.openDemoProject", json!({}))?;
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// `--save` / `--save-as` after a mutating command.
|
||||
fn maybe_save(b: &mut Backend, args: &Args) -> Result<Option<String>, Failure> {
|
||||
let r = if let Some(p) = args.opt("--save-as") {
|
||||
b.exec("file.saveAs", json!({"path": p}))?
|
||||
} else if args.flag("--save") {
|
||||
b.exec("file.save", json!({})).map_err(|e| Failure::Error(format!("{e} (use --project F to save in place, or --save-as F)")))?
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(r.get("path").and_then(Value::as_str).map(str::to_string).or_else(|| args.opt("--save-as").map(str::to_string)))
|
||||
}
|
||||
|
||||
fn tool(b: &mut Backend, name: &str, a: Value) -> Result<Value, Failure> {
|
||||
match tools::run(b, name, &a)? {
|
||||
Reply::Json(v) => Ok(v),
|
||||
Reply::Image { info, .. } => Ok(info),
|
||||
}
|
||||
}
|
||||
|
||||
/// Print a result: compact JSON with `--json`, else pretty JSON.
|
||||
fn emit(v: &Value, json_out: bool) {
|
||||
if json_out {
|
||||
println!("{v}");
|
||||
} else {
|
||||
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> {
|
||||
match cmd {
|
||||
"render" => render(args, json_out)?,
|
||||
"bench" => bench_cmd(args)?,
|
||||
"info" => {
|
||||
let mut b = backend(args, true)?;
|
||||
let p = tool(&mut b, "get_project", json!({}))?;
|
||||
let comp = tool(&mut b, "get_comp", json!({})).ok();
|
||||
let info = json!({
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"mode": if b.is_bridge() { "bridge" } else { "headless" },
|
||||
"commands": effectcraft_engine::command_specs().len(),
|
||||
"effects": effectcraft_engine::effects::registry().len(),
|
||||
"project": p,
|
||||
"activeComp": comp,
|
||||
});
|
||||
if json_out {
|
||||
emit(&info, true);
|
||||
} else {
|
||||
println!(
|
||||
"EffectCraft {} ({}), {} commands, {} effects",
|
||||
info["version"].as_str().unwrap_or(""),
|
||||
info["mode"].as_str().unwrap_or(""),
|
||||
info["commands"],
|
||||
info["effects"]
|
||||
);
|
||||
println!("project: {}", p["path"].as_str().unwrap_or("(unsaved)"));
|
||||
for i in p["items"].as_array().into_iter().flatten() {
|
||||
println!(" item {:>3} {:<12} {}", i["id"], i["type"].as_str().unwrap_or(""), i["name"].as_str().unwrap_or(""));
|
||||
}
|
||||
if let Some(c) = comp {
|
||||
println!(
|
||||
"active comp {} \"{}\" {}x{} @ {} fps, {} s",
|
||||
c["id"],
|
||||
c["name"].as_str().unwrap_or(""),
|
||||
c["width"],
|
||||
c["height"],
|
||||
c["frameRate"],
|
||||
c["duration"]
|
||||
);
|
||||
for l in c["layers"].as_array().into_iter().flatten() {
|
||||
println!(" #{:<3} id {:<4} {:<10} {}", l["index"], l["id"], l["type"].as_str().unwrap_or(""), l["name"].as_str().unwrap_or(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"commands" => {
|
||||
for c in effectcraft_engine::command_specs() {
|
||||
println!("{:<36} {:<40} {}", c.id, c.label, c.shortcut.unwrap_or(""));
|
||||
let mut b = backend(args, false)?;
|
||||
let v = tool(&mut b, "list_commands", json!({"filter": args.opt("--filter"), "enabled_only": args.flag("--enabled")}))?;
|
||||
if json_out {
|
||||
emit(&v, true);
|
||||
} else {
|
||||
for c in v.as_array().into_iter().flatten() {
|
||||
println!(
|
||||
"{:<36} {:<36} {:<16} {}",
|
||||
c["id"].as_str().unwrap_or(""),
|
||||
c["label"].as_str().unwrap_or(""),
|
||||
c["shortcut"].as_str().unwrap_or(""),
|
||||
c["params"].as_str().unwrap_or("")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => usage(),
|
||||
"exec" => {
|
||||
let Some(id) = args.pos.first().cloned() else { return usage_err("exec needs a command id") };
|
||||
let params = match (args.opt("--params"), args.pos.get(1).map(String::as_str)) {
|
||||
(Some(p), _) | (None, Some(p)) => serde_json::from_str(p).map_err(|e| Failure::Usage(format!("params are not valid JSON: {e}")))?,
|
||||
(None, None) => json!({}),
|
||||
};
|
||||
let mut b = backend(args, true)?;
|
||||
let r = b.exec(&id, params)?;
|
||||
let saved = maybe_save(&mut b, args)?;
|
||||
emit(&with_saved(r, saved), json_out);
|
||||
}
|
||||
"run" => {
|
||||
if args.pos.is_empty() {
|
||||
return usage_err("run needs <command-id> [<json>] pairs");
|
||||
}
|
||||
let pairs = args.pos.clone();
|
||||
let mut b = backend(args, true)?;
|
||||
let mut results = vec![];
|
||||
let mut i = 0;
|
||||
while i < pairs.len() {
|
||||
let id = &pairs[i];
|
||||
let params = match pairs.get(i + 1).filter(|p| p.trim_start().starts_with('{')) {
|
||||
Some(p) => {
|
||||
i += 1;
|
||||
serde_json::from_str(p).map_err(|e| Failure::Usage(format!("{id}: params are not valid JSON: {e}")))?
|
||||
}
|
||||
None => json!({}),
|
||||
};
|
||||
i += 1;
|
||||
let r = b.exec(id, params).map_err(|e| Failure::Error(format!("{id}: {e}")))?;
|
||||
if !json_out {
|
||||
emit(&r, false);
|
||||
}
|
||||
results.push(json!({"command": id, "result": r}));
|
||||
}
|
||||
let saved = maybe_save(&mut b, args)?;
|
||||
if json_out {
|
||||
emit(&with_saved(json!(results), saved), true);
|
||||
}
|
||||
}
|
||||
"props" => {
|
||||
let [comp, layer] = positional::<2>(args, "props <comp> <layer>")?;
|
||||
let mut b = backend(args, true)?;
|
||||
let a = json!({"comp": reference(&comp), "layer": reference(&layer), "flat": args.flag("--flat") || !json_out, "time": args.num("--time")?, "depth": args.num("--depth")?});
|
||||
let v = tool(&mut b, "get_layer", a)?;
|
||||
if json_out {
|
||||
emit(&v, true);
|
||||
} else {
|
||||
println!("layer {} \"{}\" ({}) at {} s", v["id"], v["name"].as_str().unwrap_or(""), v["type"].as_str().unwrap_or(""), v["time"]);
|
||||
for p in v["properties"].as_array().into_iter().flatten() {
|
||||
let mut extra = String::new();
|
||||
if let Some(k) = p.get("keys") {
|
||||
extra += &format!(" [{k} keys]");
|
||||
}
|
||||
if let Some(e) = p.get("expression").and_then(Value::as_str) {
|
||||
extra += &format!(" expr: {e}");
|
||||
}
|
||||
println!(" {:<44} {:<8} {}{extra}", p["path"].as_str().unwrap_or(""), p["type"].as_str().unwrap_or(""), p["value"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
"get" => {
|
||||
let [comp, layer, path] = positional::<3>(args, "get <comp> <layer> <path>")?;
|
||||
let mut b = backend(args, true)?;
|
||||
let v = tool(&mut b, "get_property", json!({"comp": reference(&comp), "layer": reference(&layer), "path": path, "time": args.num("--time")?}))?;
|
||||
emit(&v, json_out);
|
||||
}
|
||||
"set" => {
|
||||
let expr = args.opt("--expression").map(str::to_string);
|
||||
let need = if expr.is_some() { 3 } else { 4 };
|
||||
if args.pos.len() < need {
|
||||
return usage_err("set <comp> <layer> <path> <value> [--time S] [--expression E]");
|
||||
}
|
||||
let (comp, layer, path) = (args.pos[0].clone(), args.pos[1].clone(), args.pos[2].clone());
|
||||
let value = args.pos.get(3).map(|v| value_arg(v));
|
||||
let mut b = backend(args, true)?;
|
||||
let a =
|
||||
json!({"comp": reference(&comp), "layer": reference(&layer), "path": path, "value": value, "time": args.num("--time")?, "expression": expr});
|
||||
let v = tool(&mut b, "set_property", a)?;
|
||||
let saved = maybe_save(&mut b, args)?;
|
||||
emit(&with_saved(v, saved), json_out);
|
||||
}
|
||||
"render-frame" | "frame" => {
|
||||
let mut b = backend(args, true)?;
|
||||
let comp = args.opt("--comp").and_then(reference);
|
||||
let mut time = args.num("--time")?;
|
||||
let mut max_side = args.num("--max-side")?.map(|m| m as u32).unwrap_or(0);
|
||||
let needs_info = args.opt("--frame").is_some() || args.opt("--scale").is_some();
|
||||
if needs_info {
|
||||
let c = tool(&mut b, "get_comp", json!({"comp": comp}))?;
|
||||
if let Some(f) = args.num("--frame")? {
|
||||
time = Some(f / c["frameRate"].as_f64().unwrap_or(30.0));
|
||||
}
|
||||
if let Some(k) = args.num("--scale")? {
|
||||
let long = c["width"].as_f64().unwrap_or(0.0).max(c["height"].as_f64().unwrap_or(0.0));
|
||||
max_side = (long * k).round().max(1.0) as u32;
|
||||
}
|
||||
}
|
||||
let out = args.opt("--out").unwrap_or("frame.png").to_string();
|
||||
let t0 = std::time::Instant::now();
|
||||
let f = b.render(comp.as_ref(), time, max_side)?;
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
std::fs::write(&out, &f.png).map_err(|e| format!("cannot write {out}: {e}"))?;
|
||||
let info = json!({"path": out, "comp": f.comp, "time": f.time, "width": f.width, "height": f.height, "ms": (ms * 10.0).round() / 10.0});
|
||||
if json_out {
|
||||
emit(&info, true);
|
||||
} else {
|
||||
eprintln!("rendered {}x{} at {:.3}s in {ms:.1} ms -> {out}", f.width, f.height, f.time);
|
||||
}
|
||||
}
|
||||
"mcp" => {
|
||||
let b = backend(args, false)?;
|
||||
McpServer::new(b).serve_stdio().map_err(|e| e.to_string())?;
|
||||
}
|
||||
other => return usage_err(&format!("unknown subcommand `{other}`")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn positional<const N: usize>(args: &Args, usage: &str) -> Result<[String; N], Failure> {
|
||||
if args.pos.len() < N {
|
||||
return usage_err(usage);
|
||||
}
|
||||
Ok(std::array::from_fn(|i| args.pos[i].clone()))
|
||||
}
|
||||
|
||||
fn with_saved(v: Value, saved: Option<String>) -> Value {
|
||||
match saved {
|
||||
None => v,
|
||||
Some(p) => json!({"result": v, "saved": p}),
|
||||
}
|
||||
}
|
||||
|
||||
/// `render`: queue `--comp` (or the active comp) with the given settings unless `--queue`, then
|
||||
/// render the queue with a progress line on stderr. Fails if any item fails.
|
||||
fn render(args: &Args, json_out: bool) -> Result<(), Failure> {
|
||||
use effectcraft_engine::project::render_queue::RenderStatus;
|
||||
if args.opt("--bridge").is_some() {
|
||||
return usage_err("render runs headless; use `exec renderQueue.add` / `renderQueue.render` with --bridge");
|
||||
}
|
||||
let mut s = effectcraft_host::session();
|
||||
match &args.project {
|
||||
Some(p) => s.execute("file.open", json!({"path": p})).map_err(|e| Failure::Error(e.to_string()))?,
|
||||
None => s.execute("file.openDemoProject", json!({})).map_err(|e| Failure::Error(e.to_string()))?,
|
||||
};
|
||||
let err = |e: effectcraft_engine::EngineError| Failure::Error(e.to_string());
|
||||
if !args.flag("--queue") {
|
||||
let Some(out) = args.opt("--out") else { return usage_err("render: --out FILE is required (or --queue)") };
|
||||
let mut p = json!({"output": out});
|
||||
if let Some(c) = args.opt("--comp") {
|
||||
p["comp"] = json!(c);
|
||||
}
|
||||
let ext = std::path::Path::new(out).extension().map(|e| e.to_string_lossy().to_string());
|
||||
if let Some(f) = args.opt("--format").map(str::to_string).or(ext) {
|
||||
p["format"] = json!(f);
|
||||
}
|
||||
match (args.num("--start")?, args.num("--end")?) {
|
||||
(None, None) => p["timeSpan"] = json!(if args.flag("--work-area") { "workArea" } else { "comp" }),
|
||||
(a, b) => {
|
||||
p["start"] = json!(a.unwrap_or(0.0));
|
||||
if let Some(b) = b {
|
||||
p["end"] = json!(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = args.num("--fps")? {
|
||||
p["frameRate"] = json!(v);
|
||||
}
|
||||
if let Some(r) = args.opt("--resolution").or(args.opt("--scale")) {
|
||||
p["resolution"] = r.parse::<f64>().map(|v| json!(v)).unwrap_or(json!(r));
|
||||
}
|
||||
for (flag, key) in [("--quality", "quality"), ("--channels", "channels"), ("--prores", "proresProfile"), ("--audio", "audio")] {
|
||||
if let Some(v) = args.opt(flag) {
|
||||
p[key] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = args.num("--jpeg-quality")? {
|
||||
p["quality"] = json!(v);
|
||||
}
|
||||
if let Some(v) = args.num("--bitrate")? {
|
||||
p["bitrate"] = json!(v);
|
||||
}
|
||||
// Render exactly this item: unqueue whatever the project's queue already holds.
|
||||
for k in 0..s.project.render_queue.len() {
|
||||
let _ = s.execute("renderQueue.setRender", json!({"index": k + 1, "render": false}));
|
||||
}
|
||||
let r = s.execute("renderQueue.add", p).map_err(err)?;
|
||||
eprintln!(
|
||||
"{} → {} ({}×{}, {} frames, {})",
|
||||
r["compName"].as_str().unwrap_or("?"),
|
||||
r["outputPath"].as_str().unwrap_or("?"),
|
||||
r["width"],
|
||||
r["height"],
|
||||
r["frames"],
|
||||
r["outputModuleSummary"].as_str().unwrap_or("")
|
||||
);
|
||||
}
|
||||
s.execute("renderQueue.render", json!({"wait": false})).map_err(err)?;
|
||||
let tty = std::io::IsTerminal::is_terminal(&std::io::stderr());
|
||||
while s.is_rendering() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
if tty && let Some(p) = s.render_progress() {
|
||||
let left = p.remaining.map(|r| format!(", ~{r:.1}s left")).unwrap_or_default();
|
||||
eprint!(
|
||||
"
|
||||
[{}/{}] frame {}/{} {:.1}s{left}\x1b[K",
|
||||
(p.items_done + 1).min(p.items_total),
|
||||
p.items_total,
|
||||
p.done,
|
||||
p.total,
|
||||
p.item_elapsed
|
||||
);
|
||||
}
|
||||
s.poll_render();
|
||||
}
|
||||
s.poll_render();
|
||||
if tty {
|
||||
eprintln!();
|
||||
}
|
||||
let mut results = vec![];
|
||||
let mut failed = vec![];
|
||||
for it in s.project.render_queue.iter().filter(|i| i.render && i.started.is_some()) {
|
||||
let name = s.project.item(it.comp).map(|i| i.name.clone()).unwrap_or_else(|| "?".into());
|
||||
match &it.status {
|
||||
RenderStatus::Done => {
|
||||
eprintln!("done: {name} → {} in {:.2}s", it.last_output.as_deref().unwrap_or("?"), it.render_time.unwrap_or(0.0));
|
||||
results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time}));
|
||||
}
|
||||
RenderStatus::Failed(e) => failed.push(format!("{name}: {e}")),
|
||||
other => failed.push(format!("{name}: {}", other.label())),
|
||||
}
|
||||
}
|
||||
if !failed.is_empty() {
|
||||
return Err(Failure::Error(failed.join("; ")));
|
||||
}
|
||||
if json_out {
|
||||
emit(&json!({"rendered": results}), true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `bench`: time one frame N times without the layer cache (per-layer and per-effect breakdown),
|
||||
/// and optionally `--play N` consecutive frames with and without the cache.
|
||||
fn bench_cmd(args: &Args) -> Result<(), Failure> {
|
||||
let mut s = effectcraft_host::session();
|
||||
match &args.project {
|
||||
Some(p) => s.execute("file.open", json!({"path": p})),
|
||||
None => s.execute("file.openDemoProject", json!({})),
|
||||
}
|
||||
.map_err(|e| Failure::Error(e.to_string()))?;
|
||||
if let Some(c) = args.opt("--comp") {
|
||||
s.execute("comp.open", json!({"comp": c})).map_err(|e| Failure::Error(e.to_string()))?;
|
||||
}
|
||||
let cid = s.active_comp_id().ok_or_else(|| Failure::Error("no composition".into()))?;
|
||||
let t = Tick::from_seconds_f64(args.num("--time")?.unwrap_or(3.0));
|
||||
let opts = RenderOpts { scale: args.num("--scale")?.unwrap_or(1.0), ..Default::default() };
|
||||
bench(&s, cid, t, opts, args.num("--n")?.unwrap_or(10.0).max(1.0) as usize);
|
||||
if let Some(n) = args.num("--play")? {
|
||||
bench_play(&s, cid, t, opts, n.max(1.0) as usize);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- benchmark helpers
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
use effectcraft_engine::project::ItemId;
|
||||
use effectcraft_render::{LayerCache, LayerTiming, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
|
||||
fn median(v: &mut [f64]) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
if v.is_empty() { 0.0 } else { v[v.len() / 2] }
|
||||
}
|
||||
|
||||
fn min(v: &[f64]) -> f64 {
|
||||
v.iter().copied().fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// CPU time of the whole process (all threads) in ms: a load-independent measure of work.
|
||||
fn cpu_ms() -> f64 {
|
||||
cpu_time::ProcessTime::try_now().map(|t| t.as_duration().as_secs_f64() * 1e3).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// One frame: (wall ms, CPU ms, per-layer timings).
|
||||
fn render_timed(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, cache: Option<&LayerCache>) -> (f64, f64, Vec<LayerTiming>) {
|
||||
let prof = std::sync::Mutex::new(Vec::<LayerTiming>::new());
|
||||
let mut r = Renderer::new(&s.project, s.footage.as_ref(), opts);
|
||||
r.expr = s.expr.as_deref();
|
||||
r.cache = cache;
|
||||
r.profile = Some(&prof);
|
||||
let c0 = cpu_ms();
|
||||
let t0 = std::time::Instant::now();
|
||||
let img = r.comp_frame(cid, t);
|
||||
let ms = t0.elapsed().as_secs_f64() * 1e3;
|
||||
let cpu = cpu_ms() - c0;
|
||||
std::hint::black_box(&img);
|
||||
(ms, cpu, prof.into_inner().unwrap_or_default())
|
||||
}
|
||||
|
||||
type LayerRow = (usize, String, Vec<f64>, Vec<f64>, Vec<(String, Vec<f64>)>);
|
||||
|
||||
/// `frame --bench N`: render the same frame N times without the layer cache (the full cost of a
|
||||
/// frame) and print min/median frame time plus min per-layer and per-effect times.
|
||||
fn bench(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, n: usize) {
|
||||
let mut totals = Vec::with_capacity(n);
|
||||
let mut cpus = Vec::with_capacity(n);
|
||||
let mut per_layer: Vec<LayerRow> = Vec::new();
|
||||
for _ in 0..n {
|
||||
let (ms, cpu, prof) = render_timed(s, cid, t, opts, None);
|
||||
totals.push(ms);
|
||||
cpus.push(cpu);
|
||||
for (i, lt) in prof.into_iter().enumerate() {
|
||||
if per_layer.len() <= i {
|
||||
per_layer.push((lt.depth, lt.layer.clone(), vec![], vec![], vec![]));
|
||||
}
|
||||
let e = &mut per_layer[i];
|
||||
e.2.push(lt.process_ms);
|
||||
e.3.push(lt.composite_ms);
|
||||
for (j, (id, ms)) in lt.effects.into_iter().enumerate() {
|
||||
if e.4.len() <= j {
|
||||
e.4.push((id, vec![]));
|
||||
}
|
||||
e.4[j].1.push(ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"bench (no cache): {n} runs at scale {}: wall min {:.2} ms, median {:.2} ms; CPU (all threads) min {:.2} ms",
|
||||
opts.scale,
|
||||
min(&totals),
|
||||
median(&mut totals),
|
||||
min(&cpus)
|
||||
);
|
||||
for (d, name, p, c, fx) in per_layer {
|
||||
eprintln!(" {:indent$}{name:<28} process {:8.2} ms composite {:8.2} ms (min)", "", min(&p), min(&c), indent = d * 2);
|
||||
for (id, v) in fx {
|
||||
eprintln!(" {:indent$} fx {id:<30} {:8.2} ms", "", min(&v), indent = d * 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `frame --bench-play N`: render N consecutive frames from `t` as playback does, without and
|
||||
/// with the layer cache, and print per-frame times.
|
||||
fn bench_play(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, n: usize) {
|
||||
let Some(comp) = s.project.comp(cid) else { return };
|
||||
let f0 = comp.frame_rate.frame_at(t);
|
||||
let cache = LayerCache::default();
|
||||
for (label, c) in [("no cache", None), ("layer cache", Some(&cache))] {
|
||||
let runs: Vec<(f64, f64)> = (0..n as i64)
|
||||
.map(|i| {
|
||||
let (ms, cpu, _) = render_timed(s, cid, comp.frame_rate.tick_of(f0 + i), opts, c);
|
||||
(ms, cpu)
|
||||
})
|
||||
.collect();
|
||||
let mut v: Vec<f64> = runs.iter().map(|r| r.0).collect();
|
||||
let mean = v.iter().sum::<f64>() / n as f64;
|
||||
let cpu = runs.iter().map(|r| r.1).sum::<f64>() / n as f64;
|
||||
eprintln!(
|
||||
"bench-play ({label}): {n} frames at scale {}: wall mean {mean:.2} ms, median {:.2} ms, min {:.2} ms; CPU mean {cpu:.2} ms",
|
||||
opts.scale,
|
||||
median(&mut v),
|
||||
min(&v)
|
||||
);
|
||||
}
|
||||
let st = cache.stats();
|
||||
eprintln!(" layer cache: {} hits, {} misses, {} entries, {:.1} MB", st.hits, st.misses, st.entries, st.bytes as f64 / 1e6);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! End-to-end tests of the agent CLI: JSON output, project round-trips, rendering and MCP over stdio.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn bin() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_effectcraft-cli"))
|
||||
}
|
||||
|
||||
/// Run with `--json`; returns (exit code, parsed stdout).
|
||||
fn run_json(args: &[&str]) -> (i32, Value) {
|
||||
let out = bin().args(args).arg("--json").output().unwrap();
|
||||
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||
let v =
|
||||
serde_json::from_str(stdout.trim()).unwrap_or_else(|e| panic!("{args:?}: not JSON ({e}): {stdout}\nstderr: {}", String::from_utf8_lossy(&out.stderr)));
|
||||
(out.status.code().unwrap_or(-1), v)
|
||||
}
|
||||
|
||||
fn ok_json(args: &[&str]) -> Value {
|
||||
let (code, v) = run_json(args);
|
||||
assert_eq!(code, 0, "{args:?}: {v}");
|
||||
v
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("ec-cli-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d.join(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_and_commands() {
|
||||
let v = ok_json(&["info"]);
|
||||
assert_eq!(v["mode"], "headless");
|
||||
assert!(v["commands"].as_u64().unwrap() > 50);
|
||||
assert!(v["activeComp"]["layers"].as_array().unwrap().len() > 1, "demo project by default");
|
||||
|
||||
let v = ok_json(&["commands", "--filter", "layer.new"]);
|
||||
let ids: Vec<&str> = v.as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();
|
||||
assert!(ids.contains(&"layer.newSolid") && ids.contains(&"layer.newText"));
|
||||
assert!(ids.iter().all(|i| i.contains("layer.new") || !i.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_set_get_with_saved_project() {
|
||||
let proj = tmp("edit.ecproj");
|
||||
let p = proj.to_str().unwrap();
|
||||
let v = ok_json(&["exec", "comp.new", "--params", r#"{"name":"Main","width":320,"height":180,"duration":3}"#, "--empty", "--save-as", p]);
|
||||
assert_eq!(v["saved"], p);
|
||||
// Positional params + positional project + in-place save.
|
||||
let v = ok_json(&["exec", "layer.newSolid", r##"{"color":"#00ff00","name":"Green"}"##, p, "--save"]);
|
||||
assert!(v["result"]["layer"].is_u64());
|
||||
|
||||
let v = ok_json(&["set", "Main", "Green", "transform/opacity", "25", "--project", p, "--save"]);
|
||||
assert_eq!(v["result"]["value"], 25.0);
|
||||
ok_json(&["set", "Main", "#1", "transform/position", "[0,90]", "--time", "0", p, "--save"]);
|
||||
ok_json(&["set", "Main", "#1", "transform/position", "[320,90]", "--time", "2", p, "--save"]);
|
||||
|
||||
let v = ok_json(&["get", "Main", "#1", "transform/position", "--time", "1", p]);
|
||||
assert_eq!(v["keys"].as_array().unwrap().len(), 2);
|
||||
assert!((v["value"][0].as_f64().unwrap() - 160.0).abs() < 1.0, "{v}");
|
||||
assert_eq!(ok_json(&["get", "-", "Green", "transform/opacity", p])["value"], 25.0);
|
||||
|
||||
let v = ok_json(&["props", "Main", "#1", p]);
|
||||
assert_eq!(v["name"], "Green");
|
||||
let tree = v["properties"]["children"].as_array().unwrap();
|
||||
assert!(!tree.is_empty());
|
||||
// The human (flat) listing shows paths.
|
||||
let out = bin().args(["props", "Main", "#1", p]).output().unwrap();
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("transform/position"));
|
||||
|
||||
// Several commands in one process.
|
||||
let v = ok_json(&["run", p, "time.set", r#"{"time":1}"#, "project.summary"]);
|
||||
assert_eq!(v[1]["result"]["time"], v[0]["result"]["time"], "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_writes_png() {
|
||||
let out = tmp("f.png");
|
||||
let o = out.to_str().unwrap();
|
||||
let v = ok_json(&["render-frame", "--time", "1", "--max-side", "240", "--out", o]);
|
||||
assert_eq!(v["width"], 240);
|
||||
assert_eq!(v["height"], 135);
|
||||
let png = std::fs::read(&out).unwrap();
|
||||
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
|
||||
let v = ok_json(&["render-frame", "--frame", "15", "--scale", "0.125", "--out", o]);
|
||||
assert_eq!(v["width"], 240);
|
||||
assert!((v["time"].as_f64().unwrap() - 0.5).abs() < 0.02, "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_are_json() {
|
||||
let (code, v) = run_json(&["exec", "no.such.command", "--empty"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(v["error"].as_str().unwrap().contains("unknown command"));
|
||||
let (code, v) = run_json(&["exec", "layer.select", r#"{"index":2}"#]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(v["error"].as_str().unwrap().contains("accepted: layers, add, toggle"), "{v}");
|
||||
let (code, v) = run_json(&["get", "-", "#99", "transform/opacity"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(v["error"].is_string());
|
||||
let out = bin().args(["get", "only-one-arg"]).output().unwrap();
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_over_stdio() {
|
||||
let mut child = bin().args(["mcp", "--demo"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
let msgs = [
|
||||
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "0"}}}),
|
||||
json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
|
||||
json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
|
||||
json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "get_property", "arguments": {"layer": "#1", "path": "transform/opacity"}}}),
|
||||
json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "render_frame", "arguments": {"max_side": 64}}}),
|
||||
];
|
||||
{
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for m in &msgs {
|
||||
writeln!(stdin, "{m}").unwrap();
|
||||
}
|
||||
} // EOF ends the server.
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(out.status.success());
|
||||
let replies: Vec<Value> = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), 4, "one reply per request, none for the notification");
|
||||
assert_eq!(replies[0]["result"]["serverInfo"]["name"], "effectcraft");
|
||||
assert!(replies[1]["result"]["tools"].as_array().unwrap().len() >= 13);
|
||||
assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]);
|
||||
assert_eq!(replies[3]["result"]["content"][0]["type"], "image");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "effectcraft-automation"
|
||||
description = "EffectCraft MCP server (JSON-RPC 2.0 over stdio) over a headless session or bridged to the running app's control channel"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-engine = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
image = { workspace = true }
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Where tools run: an in-process session, or the desktop app over its control channel.
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
use effectcraft_engine::time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{BridgeClient, Error, Result, base64, encode_png, recompress_png};
|
||||
|
||||
pub enum Backend {
|
||||
/// An in-process session (no window): engine commands, inspection and rendering.
|
||||
Headless(Box<Session>),
|
||||
/// A running desktop app reached over its control channel: everything, plus the live UI.
|
||||
Bridge(BridgeClient),
|
||||
}
|
||||
|
||||
/// A rendered comp frame.
|
||||
pub struct Frame {
|
||||
pub png: Vec<u8>,
|
||||
pub comp: Value,
|
||||
pub time: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub fn headless(session: Session) -> Self {
|
||||
Backend::Headless(Box::new(session))
|
||||
}
|
||||
|
||||
/// Bridge to the app's control channel at `addr` (`9877` or `127.0.0.1:9877`).
|
||||
pub fn bridge(addr: &str) -> Result<Self> {
|
||||
Ok(Backend::Bridge(BridgeClient::new(addr)?))
|
||||
}
|
||||
|
||||
pub fn is_bridge(&self) -> bool {
|
||||
matches!(self, Backend::Bridge(_))
|
||||
}
|
||||
|
||||
pub fn session(&mut self) -> Option<&mut Session> {
|
||||
match self {
|
||||
Backend::Headless(s) => Some(s),
|
||||
Backend::Bridge(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an engine command by id.
|
||||
pub fn exec(&mut self, id: &str, params: Value) -> Result<Value> {
|
||||
let params = if params.is_null() { json!({}) } else { params };
|
||||
match self {
|
||||
Backend::Headless(s) => {
|
||||
let r = s.execute_checked(id, params);
|
||||
s.drain_events();
|
||||
Ok(r?)
|
||||
}
|
||||
Backend::Bridge(b) => b.call("engine.execute", json!({"command": id, "params": params})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call a raw control-channel method (bridge only).
|
||||
pub fn control(&mut self, method: &str, params: Value) -> Result<Value> {
|
||||
match self {
|
||||
Backend::Bridge(b) => b.call(method, if params.is_null() { json!({}) } else { params }),
|
||||
Backend::Headless(_) => Err(Error::BadArgs(NEED_BRIDGE.into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a comp frame (comp time `time` seconds, default the CTI) as PNG, longest side at most
|
||||
/// `max_side` (0 = full size).
|
||||
pub fn render(&mut self, comp: Option<&Value>, time: Option<f64>, max_side: u32) -> Result<Frame> {
|
||||
match self {
|
||||
Backend::Headless(s) => {
|
||||
let cid = s.resolve_comp(comp).map_err(|_| no_comp(comp))?;
|
||||
let t = time.map(Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let (w, h, rgba) = s.render_rgba8(cid, t, max_side)?;
|
||||
let png = encode_png(w, h, rgba, max_side)?;
|
||||
Ok(Frame { png, comp: json!(cid.0), time: t.seconds(), width: w, height: h })
|
||||
}
|
||||
Backend::Bridge(b) => {
|
||||
let mut p = json!({"max_side": max_side, "base64": true});
|
||||
if let Some(t) = time {
|
||||
p["time"] = json!(t);
|
||||
}
|
||||
if let Some(c) = comp.filter(|c| !c.is_null()) {
|
||||
p["comp"] = c.clone();
|
||||
}
|
||||
let r = b.call("render.frame", p)?;
|
||||
let data = r.get("png").and_then(Value::as_str).ok_or_else(|| Error::App("render.frame returned no `png`".into()))?;
|
||||
let raw = base64::decode(data).ok_or_else(|| Error::App("render.frame: bad base64".into()))?;
|
||||
let (png, width, height) = recompress_png(&raw, max_side)?;
|
||||
Ok(Frame { png, comp: r["comp"].clone(), time: r["time"].as_f64().unwrap_or(0.0), width, height })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn no_comp(comp: Option<&Value>) -> Error {
|
||||
match comp.filter(|c| !c.is_null()) {
|
||||
Some(c) => Error::BadArgs(format!("no composition {c} (see get_project)")),
|
||||
None => Error::BadArgs("no active composition: create one (execute_command comp.new) or open a project".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub const NEED_BRIDGE: &str =
|
||||
"this tool drives the live app: start it with `effectcraft --control 9877` and run the MCP server as `effectcraft-cli mcp --bridge 9877`";
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Standard base64 (RFC 4648 §4, padded): MCP image content and the control channel's inline PNGs.
|
||||
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn encode(data: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
|
||||
for i in 0..4 {
|
||||
s.push(if i <= c.len() { A[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Decode, ignoring ASCII whitespace; `None` on any other invalid input.
|
||||
pub fn decode(s: &str) -> Option<Vec<u8>> {
|
||||
let val = |c: u8| -> Option<u32> {
|
||||
Some(match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return None,
|
||||
} as u32)
|
||||
};
|
||||
let bytes: Vec<u8> = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
|
||||
if !bytes.len().is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
|
||||
for (ci, c) in bytes.chunks(4).enumerate() {
|
||||
let last = ci == bytes.len() / 4 - 1;
|
||||
let pad = c.iter().rev().take_while(|b| **b == b'=').count();
|
||||
if pad > 2 || (pad > 0 && !last) {
|
||||
return None;
|
||||
}
|
||||
let mut n = 0u32;
|
||||
for &b in &c[..4 - pad] {
|
||||
n = n << 6 | val(b)?;
|
||||
}
|
||||
n <<= 6 * pad as u32;
|
||||
out.extend_from_slice(&[(n >> 16) as u8, (n >> 8) as u8, n as u8][..3 - pad]);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn rfc4648_vectors() {
|
||||
for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(super::encode(i.as_bytes()), o);
|
||||
assert_eq!(super::decode(o).unwrap(), i.as_bytes());
|
||||
}
|
||||
assert!(super::decode("Zm9v!").is_none());
|
||||
let all: Vec<u8> = (0..=255).collect();
|
||||
assert_eq!(super::decode(&super::encode(&all)).unwrap(), all);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Blocking client for the desktop app's JSON-lines control channel (`docs/control-protocol.md`).
|
||||
//! One persistent loopback connection, reconnected once if the app went away.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Slightly longer than the app's own 60 s per-request timeout, so its error reply wins.
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(65);
|
||||
|
||||
pub struct BridgeClient {
|
||||
addr: String,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl BridgeClient {
|
||||
/// `addr`: a port (`9877`) or `host:port` on loopback (`127.0.0.1`, `localhost`, `[::1]`).
|
||||
pub fn new(addr: &str) -> Result<Self> {
|
||||
let addr = if addr.parse::<u16>().is_ok() { format!("127.0.0.1:{addr}") } else { addr.to_string() };
|
||||
let host = addr.rsplit_once(':').map(|(h, _)| h).unwrap_or(&addr);
|
||||
if !matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "::1") {
|
||||
return Err(Error::BadArgs(format!("bridge address must be loopback (PORT or 127.0.0.1:PORT), got `{addr}`")));
|
||||
}
|
||||
Ok(Self { addr, conn: None, next_id: 1 })
|
||||
}
|
||||
|
||||
pub fn addr(&self) -> &str {
|
||||
&self.addr
|
||||
}
|
||||
|
||||
fn connect(&self) -> Result<(BufReader<TcpStream>, TcpStream)> {
|
||||
let sa = self
|
||||
.addr
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| Error::Bridge(format!("{}: {e}", self.addr)))?
|
||||
.next()
|
||||
.ok_or_else(|| Error::Bridge(format!("cannot resolve {}", self.addr)))?;
|
||||
let s = TcpStream::connect_timeout(&sa, Duration::from_secs(5))
|
||||
.map_err(|e| Error::Bridge(format!("cannot connect to {} ({e}); start the app with `effectcraft --control <port>`", self.addr)))?;
|
||||
s.set_read_timeout(Some(READ_TIMEOUT)).ok();
|
||||
s.set_nodelay(true).ok();
|
||||
let r = s.try_clone().map_err(|e| Error::Bridge(e.to_string()))?;
|
||||
Ok((BufReader::new(r), s))
|
||||
}
|
||||
|
||||
/// Call a control method; returns the reply's `result`, or the app's `error` as [`Error::App`].
|
||||
pub fn call(&mut self, method: &str, params: Value) -> Result<Value> {
|
||||
let mut last = Error::Bridge("not attempted".into());
|
||||
for attempt in 0..2 {
|
||||
if self.conn.is_none() {
|
||||
self.conn = Some(self.connect()?);
|
||||
}
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
let Some((r, w)) = self.conn.as_mut() else { continue };
|
||||
let line = format!("{}\n", json!({"id": id, "method": method, "params": params}));
|
||||
// `Ok(Err(_))`: the connection is dead before a reply (safe to resend once);
|
||||
// `Err(_)`: a timeout or bad reply (never resent: the app may have run the request).
|
||||
let res = (|| -> Result<std::result::Result<Value, Error>> {
|
||||
if let Err(e) = w.write_all(line.as_bytes()) {
|
||||
return Ok(Err(Error::Bridge(e.to_string())));
|
||||
}
|
||||
let mut buf = String::new();
|
||||
match r.read_line(&mut buf) {
|
||||
Ok(0) => return Ok(Err(Error::Bridge("connection closed by the app".into()))),
|
||||
Ok(_) => {}
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
|
||||
return Err(Error::Bridge(format!("no reply to `{method}` within {}s (is the app window running?)", READ_TIMEOUT.as_secs())));
|
||||
}
|
||||
Err(e) => return Ok(Err(Error::Bridge(e.to_string()))),
|
||||
}
|
||||
serde_json::from_str(&buf).map(Ok).map_err(|e| Error::Bridge(format!("bad reply: {e}")))
|
||||
})();
|
||||
match res {
|
||||
Ok(Ok(v)) if v.get("ok").and_then(Value::as_bool) == Some(true) => return Ok(v.get("result").cloned().unwrap_or(Value::Null)),
|
||||
Ok(Ok(v)) => return Err(Error::App(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string())),
|
||||
Ok(Err(e)) => {
|
||||
// Stale connection (app restarted): reconnect and resend once.
|
||||
self.conn = None;
|
||||
last = e;
|
||||
if attempt == 1 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// The stream may still deliver the late reply: start fresh next call.
|
||||
self.conn = None;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! # effectcraft-automation (L5)
|
||||
//!
|
||||
//! Makes EffectCraft drivable by AI agents. See `docs/agents.md`.
|
||||
//!
|
||||
//! * [`McpServer`]: a Model Context Protocol server (JSON-RPC 2.0, newline-delimited over stdio),
|
||||
//! hand-rolled on `serde_json`; no async runtime, starts instantly.
|
||||
//! * [`Backend`]: where tools run. **Headless** owns an in-process [`Session`] (no window);
|
||||
//! **bridge** forwards to a running desktop app over its JSON-lines control channel
|
||||
//! (`effectcraft --control 9877`, `docs/control-protocol.md`), adding screenshots and UI input.
|
||||
//! * [`tools`]: the tool catalogue (names, descriptions, JSON schemas) and their implementations,
|
||||
//! shared by the MCP server and `effectcraft-cli`'s one-shot subcommands.
|
||||
//!
|
||||
//! Layering: depends on `effectcraft-engine` only (never egui); the CLI injects a fully wired
|
||||
//! session (`effectcraft_host::session()`).
|
||||
|
||||
pub mod backend;
|
||||
pub mod base64;
|
||||
pub mod bridge;
|
||||
pub mod server;
|
||||
pub mod tools;
|
||||
|
||||
pub use backend::{Backend, Frame};
|
||||
pub use bridge::BridgeClient;
|
||||
pub use effectcraft_engine::Session;
|
||||
pub use server::McpServer;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Missing or malformed tool arguments.
|
||||
#[error("{0}")]
|
||||
BadArgs(String),
|
||||
#[error(transparent)]
|
||||
Engine(#[from] effectcraft_engine::EngineError),
|
||||
/// Transport problem talking to the desktop app.
|
||||
#[error("bridge: {0}")]
|
||||
Bridge(String),
|
||||
/// The desktop app replied with an error.
|
||||
#[error("{0}")]
|
||||
App(String),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Encode RGBA8 pixels as PNG (fast compression), downscaled so the longest side is at most
|
||||
/// `max_side` (0 = keep). Fully opaque images are written as RGB to save space.
|
||||
pub fn encode_png(w: u32, h: u32, rgba: Vec<u8>, max_side: u32) -> Result<Vec<u8>> {
|
||||
use image::ImageEncoder;
|
||||
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
|
||||
let mut img = image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| Error::Other("bad image buffer".into()))?;
|
||||
if max_side > 0 && w.max(h) > max_side {
|
||||
let s = max_side as f64 / w.max(h) as f64;
|
||||
let (nw, nh) = (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1));
|
||||
img = image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle);
|
||||
}
|
||||
let (w, h) = img.dimensions();
|
||||
let mut out = Vec::new();
|
||||
let enc = PngEncoder::new_with_quality(&mut out, CompressionType::Fast, FilterType::Adaptive);
|
||||
let raw = img.into_raw();
|
||||
let r = if raw.chunks_exact(4).all(|p| p[3] == 255) {
|
||||
let rgb: Vec<u8> = raw.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
enc.write_image(&rgb, w, h, image::ExtendedColorType::Rgb8)
|
||||
} else {
|
||||
enc.write_image(&raw, w, h, image::ExtendedColorType::Rgba8)
|
||||
};
|
||||
r.map_err(|e| Error::Other(format!("png: {e}")))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decode any PNG and re-encode it compressed and capped to `max_side`. Returns (png, w, h).
|
||||
pub fn recompress_png(bytes: &[u8], max_side: u32) -> Result<(Vec<u8>, u32, u32)> {
|
||||
let img = image::load_from_memory(bytes).map_err(|e| Error::Other(format!("png: {e}")))?.to_rgba8();
|
||||
let (w, h) = img.dimensions();
|
||||
let png = encode_png(w, h, img.into_raw(), max_side)?;
|
||||
let (w, h) = png_size(&png).unwrap_or((w, h));
|
||||
Ok((png, w, h))
|
||||
}
|
||||
|
||||
/// Width and height from a PNG's IHDR.
|
||||
pub fn png_size(png: &[u8]) -> Option<(u32, u32)> {
|
||||
if png.len() < 24 || &png[12..16] != b"IHDR" {
|
||||
return None;
|
||||
}
|
||||
let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]);
|
||||
Some((be(16), be(20)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,144 @@
|
||||
//! MCP server: JSON-RPC 2.0, one message per line (the MCP stdio transport). Implements
|
||||
//! `initialize`, `ping`, `tools/list` and `tools/call`; notifications are accepted and ignored.
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::tools::{self, Reply};
|
||||
use crate::{Backend, Error, base64};
|
||||
|
||||
/// Protocol revisions we speak, newest first. We answer with the client's if we know it.
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
const INSTRUCTIONS: &str = "EffectCraft is an After Effects-class motion graphics compositor. Everything is an engine command: list_commands discovers ids and params, execute_command runs them (undoable). Typical flow: execute_command comp.new -> execute_command layer.newText / layer.newSolid (returns the layer id) -> set_property / add_keyframe -> execute_command effect.apply -> render_frame to look at the result. Inspect with get_project, get_comp and get_layer (every property node carries its `path`, e.g. `transform/position`, `effects/#1/blurriness`). Times are seconds. In bridge mode (app started with `--control <port>`) screenshot and the ui_* tools show and operate the live window.";
|
||||
|
||||
// JSON-RPC error codes.
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
|
||||
pub struct McpServer {
|
||||
backend: Backend,
|
||||
}
|
||||
|
||||
impl McpServer {
|
||||
pub fn new(backend: Backend) -> Self {
|
||||
Self { backend }
|
||||
}
|
||||
|
||||
pub fn backend(&mut self) -> &mut Backend {
|
||||
&mut self.backend
|
||||
}
|
||||
|
||||
/// Handle one decoded message (request, notification or batch); `None` when no reply is due.
|
||||
pub fn handle(&mut self, msg: &Value) -> Option<Value> {
|
||||
if let Value::Array(batch) = msg {
|
||||
if batch.is_empty() {
|
||||
return Some(error(Value::Null, INVALID_REQUEST, "empty batch"));
|
||||
}
|
||||
let out: Vec<Value> = batch.iter().filter_map(|m| self.handle(m)).collect();
|
||||
return (!out.is_empty()).then_some(Value::Array(out));
|
||||
}
|
||||
let Some(method) = msg.get("method").and_then(Value::as_str) else {
|
||||
// A response from the client (we send no requests) or garbage.
|
||||
return msg
|
||||
.get("id")
|
||||
.filter(|_| msg.get("result").is_none() && msg.get("error").is_none())
|
||||
.map(|id| error(id.clone(), INVALID_REQUEST, "missing `method`"));
|
||||
};
|
||||
let Some(id) = msg.get("id").cloned() else {
|
||||
return None; // notification (notifications/initialized, notifications/cancelled, ...)
|
||||
};
|
||||
let params = msg.get("params").cloned().unwrap_or(json!({}));
|
||||
Some(match self.request(method, ¶ms) {
|
||||
Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
|
||||
Err((code, m)) => error(id, code, &m),
|
||||
})
|
||||
}
|
||||
|
||||
/// Handle one line of input; `None` when no reply is due.
|
||||
pub fn handle_line(&mut self, line: &str) -> Option<String> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let reply = match serde_json::from_str::<Value>(line) {
|
||||
Ok(msg) => self.handle(&msg)?,
|
||||
Err(e) => error(Value::Null, PARSE_ERROR, &format!("parse error: {e}")),
|
||||
};
|
||||
Some(reply.to_string())
|
||||
}
|
||||
|
||||
/// Serve until EOF on `input`.
|
||||
pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
|
||||
for line in input.lines() {
|
||||
if let Some(reply) = self.handle_line(&line?) {
|
||||
output.write_all(reply.as_bytes())?;
|
||||
output.write_all(b"\n")?;
|
||||
output.flush()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serve on stdin/stdout (the MCP stdio transport).
|
||||
pub fn serve_stdio(&mut self) -> std::io::Result<()> {
|
||||
self.serve(std::io::stdin().lock(), std::io::stdout().lock())
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: &Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => {
|
||||
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or("");
|
||||
let version = PROTOCOL_VERSIONS.iter().find(|v| **v == asked).copied().unwrap_or(PROTOCOL_VERSIONS[0]);
|
||||
let mode = if self.backend.is_bridge() { "bridge" } else { "headless" };
|
||||
Ok(json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": {"tools": {"listChanged": false}},
|
||||
"serverInfo": {"name": "effectcraft", "title": format!("EffectCraft ({mode})"), "version": env!("CARGO_PKG_VERSION")},
|
||||
"instructions": INSTRUCTIONS,
|
||||
}))
|
||||
}
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => {
|
||||
let tools: Vec<Value> = tools::available(self.backend.is_bridge()).map(|t| t.descriptor()).collect();
|
||||
Ok(json!({"tools": tools}))
|
||||
}
|
||||
"tools/call" => {
|
||||
let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?;
|
||||
if tools::available(self.backend.is_bridge()).all(|t| t.name != name) {
|
||||
let hint = if tools::find(name).is_some() { format!(" ({})", crate::backend::NEED_BRIDGE) } else { String::new() };
|
||||
return Err((INVALID_PARAMS, format!("unknown tool `{name}`{hint}")));
|
||||
}
|
||||
let args = params.get("arguments").cloned().unwrap_or(json!({}));
|
||||
Ok(call_result(tools::run(&mut self.backend, name, &args)))
|
||||
}
|
||||
// Advertised as absent, but answer politely for clients that probe anyway.
|
||||
"resources/list" => Ok(json!({"resources": []})),
|
||||
"resources/templates/list" => Ok(json!({"resourceTemplates": []})),
|
||||
"prompts/list" => Ok(json!({"prompts": []})),
|
||||
m => Err((METHOD_NOT_FOUND, format!("method not found: {m}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `tools/call` result: tool failures are reported in-band (`isError`) so the model can react.
|
||||
pub fn call_result(r: Result<Reply, Error>) -> Value {
|
||||
match r {
|
||||
Ok(Reply::Json(v)) => json!({"content": [{"type": "text", "text": v.to_string()}], "isError": false}),
|
||||
Ok(Reply::Image { png, info }) => json!({
|
||||
"content": [
|
||||
{"type": "image", "data": base64::encode(&png), "mimeType": "image/png"},
|
||||
{"type": "text", "text": info.to_string()},
|
||||
],
|
||||
"isError": false,
|
||||
}),
|
||||
Err(e) => json!({"content": [{"type": "text", "text": e.to_string()}], "isError": true}),
|
||||
}
|
||||
}
|
||||
|
||||
fn error(id: Value, code: i64, message: &str) -> Value {
|
||||
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! MCP protocol round-trips, in-process (headless) and against a fake control channel (bridge).
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, McpServer, Session, base64, png_size};
|
||||
|
||||
fn server() -> McpServer {
|
||||
McpServer::new(Backend::headless(Session::default()))
|
||||
}
|
||||
|
||||
/// Send a request, return its `result` (panics on a JSON-RPC error).
|
||||
fn rpc(s: &mut McpServer, id: u64, method: &str, params: Value) -> Value {
|
||||
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string();
|
||||
let reply: Value = serde_json::from_str(&s.handle_line(&line).expect("reply")).unwrap();
|
||||
assert_eq!(reply["jsonrpc"], "2.0");
|
||||
assert_eq!(reply["id"], id);
|
||||
assert!(reply.get("error").is_none(), "{method}: {reply}");
|
||||
reply["result"].clone()
|
||||
}
|
||||
|
||||
/// Call a tool; returns (content, isError).
|
||||
fn call(s: &mut McpServer, name: &str, args: Value) -> (Vec<Value>, bool) {
|
||||
let r = rpc(s, 99, "tools/call", json!({"name": name, "arguments": args}));
|
||||
(r["content"].as_array().unwrap().clone(), r["isError"].as_bool().unwrap())
|
||||
}
|
||||
|
||||
/// Call a tool that returns JSON text; panics if it failed.
|
||||
fn call_json(s: &mut McpServer, name: &str, args: Value) -> Value {
|
||||
let (c, err) = call(s, name, args.clone());
|
||||
assert!(!err, "{name} {args}: {c:?}");
|
||||
assert_eq!(c[0]["type"], "text");
|
||||
serde_json::from_str(c[0]["text"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_and_list_tools() {
|
||||
let mut s = server();
|
||||
let r = rpc(&mut s, 1, "initialize", json!({"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}));
|
||||
assert_eq!(r["protocolVersion"], "2025-03-26");
|
||||
assert_eq!(r["serverInfo"]["name"], "effectcraft");
|
||||
assert!(r["capabilities"]["tools"].is_object());
|
||||
// Unknown revision: we answer with our latest.
|
||||
let r = rpc(&mut s, 2, "initialize", json!({"protocolVersion": "1999-01-01"}));
|
||||
assert_eq!(r["protocolVersion"], crate::server::PROTOCOL_VERSIONS[0]);
|
||||
// Notifications get no reply.
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).is_none());
|
||||
assert_eq!(rpc(&mut s, 3, "ping", json!({})), json!({}));
|
||||
|
||||
let tools = rpc(&mut s, 4, "tools/list", json!({}))["tools"].as_array().unwrap().clone();
|
||||
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
for want in [
|
||||
"list_commands",
|
||||
"execute_command",
|
||||
"get_project",
|
||||
"get_comp",
|
||||
"get_layer",
|
||||
"get_property",
|
||||
"set_property",
|
||||
"add_keyframe",
|
||||
"render_frame",
|
||||
"open_project",
|
||||
"save_project",
|
||||
"undo",
|
||||
"redo",
|
||||
] {
|
||||
assert!(names.contains(&want), "missing {want}");
|
||||
}
|
||||
assert!(!names.contains(&"screenshot"), "bridge-only tools are hidden headless");
|
||||
for t in &tools {
|
||||
assert!(t["description"].as_str().unwrap().len() > 20);
|
||||
assert_eq!(t["inputSchema"]["type"], "object");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_errors() {
|
||||
let mut s = server();
|
||||
let r: Value = serde_json::from_str(&s.handle_line("{not json").unwrap()).unwrap();
|
||||
assert_eq!(r["error"]["code"], -32700);
|
||||
let r: Value = serde_json::from_str(&s.handle_line(r#"{"jsonrpc":"2.0","id":5,"method":"nope"}"#).unwrap()).unwrap();
|
||||
assert_eq!(r["error"]["code"], -32601);
|
||||
let r: Value = serde_json::from_str(&s.handle_line(r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"screenshot"}}"#).unwrap()).unwrap();
|
||||
assert_eq!(r["error"]["code"], -32602);
|
||||
// Batches.
|
||||
let r: Value =
|
||||
serde_json::from_str(&s.handle_line(r#"[{"jsonrpc":"2.0","id":7,"method":"ping"},{"jsonrpc":"2.0","method":"notifications/x"}]"#).unwrap()).unwrap();
|
||||
assert_eq!(r.as_array().unwrap().len(), 1);
|
||||
// Tool failures are in-band.
|
||||
let (c, err) = call(&mut s, "execute_command", json!({"command": "no.such"}));
|
||||
assert!(err);
|
||||
assert!(c[0]["text"].as_str().unwrap().contains("unknown command"));
|
||||
let (_, err) = call(&mut s, "render_frame", json!({}));
|
||||
assert!(err, "no comp yet");
|
||||
// Unknown params are rejected with the accepted keys, not silently ignored.
|
||||
let (c, err) = call(&mut s, "execute_command", json!({"command": "comp.new", "params": {"nmae": "X"}}));
|
||||
assert!(err);
|
||||
assert!(c[0]["text"].as_str().unwrap().contains("accepted: name, width"), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_workflow() {
|
||||
let mut s = server();
|
||||
rpc(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
|
||||
|
||||
let cmds = call_json(&mut s, "list_commands", json!({"filter": "layer.new"}));
|
||||
assert!(cmds.as_array().unwrap().iter().any(|c| c["id"] == "layer.newSolid"));
|
||||
|
||||
call_json(&mut s, "execute_command", json!({"command": "comp.new", "params": {"name": "Main", "width": 320, "height": 180, "duration": 4}}));
|
||||
let l =
|
||||
call_json(&mut s, "execute_command", json!({"command": "layer.newSolid", "params": "{\"color\":\"#ff0000\",\"width\":100,\"height\":100}"}))["layer"]
|
||||
.clone();
|
||||
assert!(l.is_u64());
|
||||
|
||||
let comp = call_json(&mut s, "get_comp", json!({"comp": "Main"}));
|
||||
assert_eq!(comp["width"], 320);
|
||||
assert_eq!(comp["layers"][0]["id"], l);
|
||||
|
||||
// Static set + read back.
|
||||
let p = call_json(&mut s, "set_property", json!({"layer": l, "path": "transform/opacity", "value": 50}));
|
||||
assert_eq!(p["value"], 50.0);
|
||||
assert_eq!(call_json(&mut s, "get_property", json!({"layer": "#1", "path": "transform/opacity"}))["value"], 50.0);
|
||||
|
||||
// Keyframes with easing.
|
||||
let p = call_json(
|
||||
&mut s,
|
||||
"add_keyframe",
|
||||
json!({"layer": l, "path": "transform/position", "keys": [{"time": 0, "value": [0, 90]}, {"time": 2, "value": [320, 90]}], "interpolation": "easyEase"}),
|
||||
);
|
||||
assert_eq!(p["keys"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(p["keys"][0]["out"], "Bezier");
|
||||
let mid = call_json(&mut s, "get_property", json!({"layer": l, "path": "transform/position", "time": 1.0}));
|
||||
assert!((mid["value"][0].as_f64().unwrap() - 160.0).abs() < 1.0, "{mid}");
|
||||
|
||||
// Expression via set_property.
|
||||
let p = call_json(&mut s, "set_property", json!({"layer": l, "path": "transform/rotation", "expression": "time * 90"}));
|
||||
assert_eq!(p["expression"], "time * 90");
|
||||
|
||||
// Property tree carries paths; flat mode too.
|
||||
let tree = call_json(&mut s, "get_layer", json!({"layer": l, "flat": true}));
|
||||
let props = tree["properties"].as_array().unwrap();
|
||||
assert!(props.iter().any(|p| p["path"] == "transform/position" && p["keys"] == 2));
|
||||
|
||||
// Render: an inline PNG at the requested size.
|
||||
let (c, err) = call(&mut s, "render_frame", json!({"time": 1.0, "max_side": 160}));
|
||||
assert!(!err, "{c:?}");
|
||||
assert_eq!(c[0]["type"], "image");
|
||||
assert_eq!(c[0]["mimeType"], "image/png");
|
||||
let png = base64::decode(c[0]["data"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(png_size(&png), Some((160, 90)));
|
||||
let info: Value = serde_json::from_str(c[1]["text"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(info["width"], 160);
|
||||
|
||||
// Undo / redo.
|
||||
let before = call_json(&mut s, "get_project", json!({}))["undo"].as_array().unwrap().len();
|
||||
let u = call_json(&mut s, "undo", json!({"steps": 2}));
|
||||
assert_eq!(u["steps"], 2);
|
||||
assert_eq!(u["undoStack"].as_array().unwrap().len(), before - 2);
|
||||
call_json(&mut s, "redo", json!({"steps": 2}));
|
||||
assert_eq!(call_json(&mut s, "get_project", json!({}))["undo"].as_array().unwrap().len(), before);
|
||||
|
||||
// Save + reopen.
|
||||
let dir = std::env::temp_dir().join(format!("ec-mcp-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("t.ecproj").to_string_lossy().into_owned();
|
||||
let saved = call_json(&mut s, "save_project", json!({"path": path}));
|
||||
assert_eq!(saved["dirty"], false);
|
||||
call_json(&mut s, "open_project", json!({"new": true}));
|
||||
assert!(call(&mut s, "get_comp", json!({})).1, "empty project has no comp");
|
||||
let proj = call_json(&mut s, "open_project", json!({"path": path}));
|
||||
assert_eq!(proj["items"].as_array().unwrap().len(), 3, "comp + Solids folder + solid: {proj}");
|
||||
let p = call_json(&mut s, "get_property", json!({"comp": "Main", "layer": "#1", "path": "transform/position"}));
|
||||
assert_eq!(p["keys"].as_array().unwrap().len(), 2);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_loop() {
|
||||
let mut s = server();
|
||||
let input = [
|
||||
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}),
|
||||
json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
|
||||
json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "open_project", "arguments": {"demo": true}}}),
|
||||
]
|
||||
.iter()
|
||||
.map(|v| v.to_string() + "\n")
|
||||
.collect::<String>();
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_bytes(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 2);
|
||||
assert_eq!(lines[1]["id"], 2);
|
||||
assert_eq!(lines[1]["result"]["isError"], false);
|
||||
}
|
||||
|
||||
/// A fake desktop control channel: answers `engine.execute` from a real session, and canned
|
||||
/// `render.frame` / `ui.screenshot` replies.
|
||||
fn fake_app() -> u16 {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = l.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
let (stream, _) = l.accept().unwrap();
|
||||
let mut out = stream.try_clone().unwrap();
|
||||
let mut session = Session::default();
|
||||
for line in BufReader::new(stream).lines() {
|
||||
let msg: Value = serde_json::from_str(&line.unwrap()).unwrap();
|
||||
let p = &msg["params"];
|
||||
let reply = match msg["method"].as_str().unwrap() {
|
||||
"engine.execute" => match session.execute(p["command"].as_str().unwrap(), p["params"].clone()) {
|
||||
Ok(v) => json!({"ok": true, "result": v}),
|
||||
Err(e) => json!({"ok": false, "error": e.to_string()}),
|
||||
},
|
||||
"render.frame" => {
|
||||
let png = crate::encode_png(4, 2, vec![255; 32], 0).unwrap();
|
||||
json!({"ok": true, "result": {"comp": 1, "time": 0.5, "width": 4, "height": 2, "png": base64::encode(&png)}})
|
||||
}
|
||||
"ui.screenshot" => {
|
||||
let png = crate::encode_png(8, 8, vec![128; 256], 0).unwrap();
|
||||
std::fs::write(p["path"].as_str().unwrap(), png).unwrap();
|
||||
json!({"ok": true, "result": {"path": p["path"]}})
|
||||
}
|
||||
"ui.key" => json!({"ok": true, "result": null}),
|
||||
m => json!({"ok": false, "error": format!("unknown method `{m}`")}),
|
||||
};
|
||||
let mut reply = reply;
|
||||
reply["id"] = msg["id"].clone();
|
||||
writeln!(out, "{reply}").unwrap();
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_forwards_to_control_channel() {
|
||||
let port = fake_app();
|
||||
let mut s = McpServer::new(Backend::bridge(&port.to_string()).unwrap());
|
||||
let r = rpc(&mut s, 1, "initialize", json!({}));
|
||||
assert!(r["serverInfo"]["title"].as_str().unwrap().contains("bridge"));
|
||||
let names: Vec<String> =
|
||||
rpc(&mut s, 2, "tools/list", json!({}))["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect();
|
||||
assert!(names.iter().any(|n| n == "screenshot") && names.iter().any(|n| n == "ui_click"));
|
||||
|
||||
call_json(&mut s, "execute_command", json!({"command": "comp.new", "params": {"name": "B", "width": 64, "height": 64}}));
|
||||
assert_eq!(call_json(&mut s, "get_comp", json!({}))["name"], "B");
|
||||
|
||||
let (c, err) = call(&mut s, "render_frame", json!({}));
|
||||
assert!(!err, "{c:?}");
|
||||
assert_eq!(png_size(&base64::decode(c[0]["data"].as_str().unwrap()).unwrap()), Some((4, 2)));
|
||||
|
||||
let (c, err) = call(&mut s, "screenshot", json!({"max_side": 4}));
|
||||
assert!(!err, "{c:?}");
|
||||
assert_eq!(png_size(&base64::decode(c[0]["data"].as_str().unwrap()).unwrap()), Some((4, 4)));
|
||||
|
||||
assert!(!call(&mut s, "ui_key", json!({"key": "Space"})).1);
|
||||
let (c, err) = call(&mut s, "control", json!({"method": "ui.nope"}));
|
||||
assert!(err && c[0]["text"].as_str().unwrap().contains("unknown method"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_rejects_non_loopback() {
|
||||
assert!(Backend::bridge("10.0.0.1:9877").is_err());
|
||||
assert!(Backend::bridge("localhost:9877").is_ok());
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! The tool catalogue: names, descriptions, JSON input schemas and implementations. Shared by the
|
||||
//! MCP server (`tools/list`, `tools/call`) and the CLI's one-shot subcommands, so both behave the
|
||||
//! same. Every tool maps onto engine commands (`Session::execute`) or control-channel methods.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::backend::NEED_BRIDGE;
|
||||
use crate::{Backend, Error, Result, recompress_png};
|
||||
|
||||
/// A tool's output.
|
||||
pub enum Reply {
|
||||
Json(Value),
|
||||
/// A PNG plus a JSON description of it (comp, time, size, path).
|
||||
Image {
|
||||
png: Vec<u8>,
|
||||
info: Value,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct ToolDef {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
/// Only listed (and usable) when bridged to the running app.
|
||||
pub bridge_only: bool,
|
||||
schema: fn() -> Value,
|
||||
run: fn(&mut Backend, &Value) -> Result<Reply>,
|
||||
}
|
||||
|
||||
impl ToolDef {
|
||||
/// The JSON Schema of the tool's arguments.
|
||||
pub fn input_schema(&self) -> Value {
|
||||
(self.schema)()
|
||||
}
|
||||
/// The MCP `Tool` object.
|
||||
pub fn descriptor(&self) -> Value {
|
||||
json!({"name": self.name, "description": self.description, "inputSchema": self.input_schema()})
|
||||
}
|
||||
}
|
||||
|
||||
/// All tools (headless + bridge-only).
|
||||
pub fn catalogue() -> &'static [ToolDef] {
|
||||
TOOLS
|
||||
}
|
||||
|
||||
pub fn find(name: &str) -> Option<&'static ToolDef> {
|
||||
TOOLS.iter().find(|t| t.name == name)
|
||||
}
|
||||
|
||||
/// The tools available on a backend (bridge-only tools are hidden in headless mode).
|
||||
pub fn available(bridge: bool) -> impl Iterator<Item = &'static ToolDef> {
|
||||
TOOLS.iter().filter(move |t| bridge || !t.bridge_only)
|
||||
}
|
||||
|
||||
/// Run a tool by name.
|
||||
pub fn run(b: &mut Backend, name: &str, args: &Value) -> Result<Reply> {
|
||||
let t = find(name).ok_or_else(|| Error::BadArgs(format!("unknown tool `{name}`")))?;
|
||||
if t.bridge_only && !b.is_bridge() {
|
||||
return Err(Error::BadArgs(NEED_BRIDGE.into()));
|
||||
}
|
||||
let empty = json!({});
|
||||
(t.run)(b, if args.is_null() { &empty } else { args })
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ schema fragments
|
||||
|
||||
fn schema(props: Value, required: &[&str]) -> Value {
|
||||
json!({"type": "object", "properties": props, "required": required})
|
||||
}
|
||||
fn comp_s() -> Value {
|
||||
json!({"type": ["integer", "string"], "description": "Composition item id or name; omit for the active comp."})
|
||||
}
|
||||
fn layer_s() -> Value {
|
||||
json!({"type": ["integer", "string"], "description": "Layer id (from get_comp), \"#n\" (1-based index from the top) or layer name."})
|
||||
}
|
||||
fn path_s() -> Value {
|
||||
json!({"type": "string", "description": "Property path from get_layer: match ids joined by `/`, `#n` for the nth child, or `@uid`. E.g. `transform/position`, `transform/opacity`, `transform/scale`, `transform/rotation`, `effects/#1/blurriness`, `masks/#1/feather`, `@57`."})
|
||||
}
|
||||
fn value_s() -> Value {
|
||||
json!({"description": "Number for 1-D properties (50), array for vectors ([960,540]), \"#rrggbb\" or [r,g,b,a] (0-1) for colours, bool for checkboxes, string for text/menus."})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
|
||||
/// Build a params object from the present, non-null entries.
|
||||
fn obj(entries: &[(&str, Option<&Value>)]) -> Value {
|
||||
let mut m = Map::new();
|
||||
for (k, v) in entries {
|
||||
if let Some(v) = v.filter(|v| !v.is_null()) {
|
||||
m.insert(k.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
fn get<'a>(a: &'a Value, k: &str) -> Option<&'a Value> {
|
||||
a.get(k).filter(|v| !v.is_null())
|
||||
}
|
||||
|
||||
fn need<'a>(a: &'a Value, k: &str) -> Result<&'a Value> {
|
||||
get(a, k).ok_or_else(|| Error::BadArgs(format!("missing `{k}`")))
|
||||
}
|
||||
|
||||
fn json_reply(v: Value) -> Result<Reply> {
|
||||
Ok(Reply::Json(v))
|
||||
}
|
||||
|
||||
/// Accept params given as a JSON string too (some clients stringify nested objects).
|
||||
fn params_of(v: Option<&Value>) -> Result<Value> {
|
||||
match v {
|
||||
None => Ok(json!({})),
|
||||
Some(Value::String(s)) if s.trim().is_empty() => Ok(json!({})),
|
||||
Some(Value::String(s)) => serde_json::from_str(s).map_err(|e| Error::BadArgs(format!("`params` is not valid JSON: {e}"))),
|
||||
Some(v) => Ok(v.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ engine tools
|
||||
|
||||
fn list_commands(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let r = b.exec("command.list", obj(&[("filter", get(a, "filter")), ("enabledOnly", get(a, "enabled_only"))]))?;
|
||||
// Drop empty fields to keep the listing compact.
|
||||
let list: Vec<Value> = r
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|mut c| {
|
||||
if let Some(o) = c.as_object_mut() {
|
||||
o.retain(|_, v| !(v.is_null() || v.as_array().is_some_and(Vec::is_empty) || v.as_str() == Some("{}")));
|
||||
}
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
json_reply(json!(list))
|
||||
}
|
||||
|
||||
fn execute_command(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let id = get(a, "command").or(get(a, "id")).and_then(Value::as_str).ok_or_else(|| Error::BadArgs("missing `command` (e.g. `comp.new`)".into()))?;
|
||||
let params = params_of(get(a, "params"))?;
|
||||
json_reply(b.exec(id, params)?)
|
||||
}
|
||||
|
||||
fn get_project(b: &mut Backend, _: &Value) -> Result<Reply> {
|
||||
json_reply(b.exec("project.summary", json!({}))?)
|
||||
}
|
||||
|
||||
fn get_comp(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
json_reply(b.exec("comp.info", obj(&[("comp", get(a, "comp"))]))?)
|
||||
}
|
||||
|
||||
/// Flatten a `layer.tree` property tree into `[{path, type, value, keys?, expression?}]`.
|
||||
fn flatten(node: &Value, out: &mut Vec<Value>) {
|
||||
match node.get("children").and_then(Value::as_array) {
|
||||
Some(ch) => ch.iter().for_each(|c| flatten(c, out)),
|
||||
None => {
|
||||
let mut o = json!({"path": node["path"], "type": node["type"], "value": node["value"]});
|
||||
if let Some(k) = node.get("keys").and_then(Value::as_array) {
|
||||
o["keys"] = json!(k.len());
|
||||
}
|
||||
if let Some(e) = node.get("expression") {
|
||||
o["expression"] = e.clone();
|
||||
}
|
||||
out.push(o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_layer(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let p = obj(&[("layer", Some(need(a, "layer")?)), ("comp", get(a, "comp")), ("depth", get(a, "depth")), ("time", get(a, "time"))]);
|
||||
let mut r = b.exec("layer.tree", p)?;
|
||||
if get(a, "flat").and_then(Value::as_bool) == Some(true) {
|
||||
let mut props = vec![];
|
||||
flatten(&r["properties"], &mut props);
|
||||
r["properties"] = json!(props);
|
||||
}
|
||||
json_reply(r)
|
||||
}
|
||||
|
||||
fn get_property(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let p = obj(&[("layer", Some(need(a, "layer")?)), ("path", Some(need(a, "path")?)), ("comp", get(a, "comp")), ("time", get(a, "time"))]);
|
||||
json_reply(b.exec("prop.get", p)?)
|
||||
}
|
||||
|
||||
fn set_property(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let (layer, path, comp, time) = (need(a, "layer")?, need(a, "path")?, get(a, "comp"), get(a, "time"));
|
||||
let (value, expr) = (get(a, "value"), get(a, "expression"));
|
||||
if value.is_none() && expr.is_none() {
|
||||
return Err(Error::BadArgs("give `value` and/or `expression`".into()));
|
||||
}
|
||||
let base = [("layer", Some(layer)), ("path", Some(path)), ("comp", comp)];
|
||||
if let Some(v) = value {
|
||||
let mut p = obj(&base);
|
||||
p["value"] = v.clone();
|
||||
match time {
|
||||
Some(t) => {
|
||||
p["time"] = t.clone();
|
||||
b.exec("prop.addKey", p)?;
|
||||
}
|
||||
None => {
|
||||
b.exec("prop.set", p)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(e) = expr {
|
||||
let mut p = obj(&base);
|
||||
p["expression"] = e.clone();
|
||||
b.exec("prop.setExpression", p)?;
|
||||
}
|
||||
json_reply(b.exec("prop.get", obj(&[("layer", Some(layer)), ("path", Some(path)), ("comp", comp), ("time", time)]))?)
|
||||
}
|
||||
|
||||
fn add_keyframe(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let (layer, path, comp) = (need(a, "layer")?, need(a, "path")?, get(a, "comp"));
|
||||
let keys: Vec<Value> = match get(a, "keys") {
|
||||
Some(Value::Array(k)) => k.clone(),
|
||||
Some(_) => return Err(Error::BadArgs("`keys` must be an array of {time, value?}".into())),
|
||||
None => vec![obj(&[("time", Some(need(a, "time")?)), ("value", get(a, "value"))])],
|
||||
};
|
||||
if keys.is_empty() {
|
||||
return Err(Error::BadArgs("no keys".into()));
|
||||
}
|
||||
let base = [("layer", Some(layer)), ("path", Some(path)), ("comp", comp)];
|
||||
for k in &keys {
|
||||
let mut p = obj(&base);
|
||||
p["time"] = need(k, "time")?.clone();
|
||||
if let Some(v) = get(k, "value") {
|
||||
p["value"] = v.clone();
|
||||
}
|
||||
b.exec("prop.addKey", p)?;
|
||||
}
|
||||
let info = b.exec("prop.get", obj(&base))?;
|
||||
if let Some(interp) = get(a, "interpolation").and_then(Value::as_str) {
|
||||
// Key selection works on the active comp.
|
||||
if let Some(c) = comp {
|
||||
b.exec("comp.open", json!({"comp": c}))?;
|
||||
}
|
||||
let sel: Vec<Value> = keys.iter().map(|k| json!({"layer": info["layer"], "prop": info["uid"], "time": k["time"]})).collect();
|
||||
b.exec("keys.select", json!({"keys": sel}))?;
|
||||
match interp.to_ascii_lowercase().as_str() {
|
||||
"easyease" | "ease" => b.exec("keys.easyEase", json!({}))?,
|
||||
"easyeasein" => b.exec("keys.easyEase", json!({"which": "in"}))?,
|
||||
"easyeaseout" => b.exec("keys.easyEase", json!({"which": "out"}))?,
|
||||
i @ ("linear" | "bezier" | "hold") => b.exec("keys.interpolation", json!({"interpolation": i}))?,
|
||||
other => return Err(Error::BadArgs(format!("unknown interpolation `{other}` (linear, bezier, hold, easyEase, easyEaseIn, easyEaseOut)"))),
|
||||
};
|
||||
return json_reply(b.exec("prop.get", obj(&base))?);
|
||||
}
|
||||
json_reply(info)
|
||||
}
|
||||
|
||||
fn render_frame(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let max_side = get(a, "max_side").and_then(Value::as_u64).unwrap_or(960) as u32;
|
||||
let f = b.render(get(a, "comp"), get(a, "time").and_then(Value::as_f64), max_side)?;
|
||||
let mut info = json!({"comp": f.comp, "time": f.time, "width": f.width, "height": f.height});
|
||||
if let Some(p) = get(a, "path").and_then(Value::as_str) {
|
||||
std::fs::write(p, &f.png).map_err(|e| Error::Other(format!("cannot write {p}: {e}")))?;
|
||||
info["path"] = json!(p);
|
||||
}
|
||||
if get(a, "inline").and_then(Value::as_bool) == Some(false) {
|
||||
return json_reply(info);
|
||||
}
|
||||
Ok(Reply::Image { png: f.png, info })
|
||||
}
|
||||
|
||||
fn open_project(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
if let Some(p) = get(a, "path") {
|
||||
b.exec("file.open", json!({"path": p}))?;
|
||||
} else if get(a, "demo").and_then(Value::as_bool) == Some(true) {
|
||||
b.exec("file.openDemoProject", json!({}))?;
|
||||
} else if get(a, "new").and_then(Value::as_bool) == Some(true) {
|
||||
b.exec("file.newProject", json!({}))?;
|
||||
} else {
|
||||
return Err(Error::BadArgs("give `path` (.ecproj), `demo: true` or `new: true`".into()));
|
||||
}
|
||||
get_project(b, &json!({}))
|
||||
}
|
||||
|
||||
fn save_project(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
match get(a, "path") {
|
||||
Some(p) => b.exec("file.saveAs", json!({"path": p}))?,
|
||||
None => b.exec("file.save", json!({}))?,
|
||||
};
|
||||
let s = b.exec("project.summary", json!({}))?;
|
||||
json_reply(json!({"path": s["path"], "dirty": s["dirty"]}))
|
||||
}
|
||||
|
||||
fn history(b: &mut Backend, a: &Value, id: &str) -> Result<Reply> {
|
||||
let steps = get(a, "steps").and_then(Value::as_u64).unwrap_or(1).max(1);
|
||||
let mut done = 0;
|
||||
for _ in 0..steps {
|
||||
match b.exec(id, json!({})) {
|
||||
Ok(_) => done += 1,
|
||||
Err(e) if done == 0 => return Err(e),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let s = b.exec("project.summary", json!({}))?;
|
||||
json_reply(json!({"steps": done, "undoStack": s["undo"]}))
|
||||
}
|
||||
|
||||
fn undo(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
history(b, a, "edit.undo")
|
||||
}
|
||||
|
||||
fn redo(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
history(b, a, "edit.redo")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bridge-only tools
|
||||
|
||||
fn screenshot(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let max_side = get(a, "max_side").and_then(Value::as_u64).unwrap_or(1600) as u32;
|
||||
let keep = get(a, "path").and_then(Value::as_str).map(str::to_string);
|
||||
let path =
|
||||
keep.clone().unwrap_or_else(|| std::env::temp_dir().join(format!("effectcraft-mcp-shot-{}.png", std::process::id())).to_string_lossy().into_owned());
|
||||
b.control("ui.screenshot", obj(&[("path", Some(&json!(path))), ("panel", get(a, "panel")), ("id", get(a, "id"))]))?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| Error::Other(format!("screenshot: {e}")))?;
|
||||
if keep.is_none() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
let (png, w, h) = recompress_png(&bytes, max_side)?;
|
||||
Ok(Reply::Image { png, info: json!({"width": w, "height": h, "path": keep}) })
|
||||
}
|
||||
|
||||
fn passthrough(b: &mut Backend, method: &str, a: &Value) -> Result<Reply> {
|
||||
json_reply(b.control(method, a.clone())?)
|
||||
}
|
||||
|
||||
fn ui_inspect(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.inspect", a)
|
||||
}
|
||||
fn ui_elements(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.elements", a)
|
||||
}
|
||||
fn ui_click(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.click", a)
|
||||
}
|
||||
fn ui_drag(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.drag", a)
|
||||
}
|
||||
fn ui_key(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.key", a)
|
||||
}
|
||||
fn ui_type(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.type", a)
|
||||
}
|
||||
fn ui_set(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
passthrough(b, "ui.set", a)
|
||||
}
|
||||
fn control(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let m = need(a, "method")?.as_str().ok_or_else(|| Error::BadArgs("`method` must be a string".into()))?;
|
||||
let p = params_of(get(a, "params"))?;
|
||||
json_reply(b.control(m, p)?)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the catalogue
|
||||
|
||||
static TOOLS: &[ToolDef] = &[
|
||||
ToolDef {
|
||||
name: "list_commands",
|
||||
description: "List engine commands: id, label, menu path, shortcut, `params` doc (e.g. `{name?, width?, height?, frameRate?, duration? (s)}`) and whether it can run now (`why` if not). Every menu item, shortcut and panel gesture maps to one of these ids; run them with execute_command. Narrow with `filter` (e.g. `layer.new`, `keys`, `effect`).",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"filter": {"type": "string", "description": "Only commands whose id or label contains this text (case-insensitive)."},
|
||||
"enabled_only": {"type": "boolean", "description": "Only commands that can run right now."}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
},
|
||||
run: list_commands,
|
||||
},
|
||||
ToolDef {
|
||||
name: "execute_command",
|
||||
description: "Run any engine command by id with JSON params; edits are undoable. Examples: comp.new {\"name\":\"Main\",\"width\":1920,\"height\":1080,\"frameRate\":30,\"duration\":5}; layer.newText {\"text\":\"Hello\",\"size\":120,\"fill\":\"#ffffff\"} (returns {\"layer\":id}); layer.newSolid {\"color\":\"#3366ff\"}; layer.newShape; effect.apply {\"layer\":3,\"effect\":\"Gaussian Blur\"}; time.set {\"time\":2.5}; layer.select {\"layers\":[3]}. Layers are referenced by id, \"#n\" or name; times are seconds.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"command": {"type": "string", "description": "Command id, e.g. `comp.new`, `layer.newText`, `effect.apply` (see list_commands)."},
|
||||
"params": {"type": "object", "description": "Command parameters as documented by list_commands.", "additionalProperties": true}
|
||||
}),
|
||||
&["command"],
|
||||
)
|
||||
},
|
||||
run: execute_command,
|
||||
},
|
||||
ToolDef {
|
||||
name: "get_project",
|
||||
description: "Project overview: file path, dirty flag, bit depth, every item (id, name, type Composition/Footage/Solid/Folder, size, duration, layer count), the active comp id, current time (s), selected layers and the undo stack.",
|
||||
bridge_only: false,
|
||||
schema: || schema(json!({}), &[]),
|
||||
run: get_project,
|
||||
},
|
||||
ToolDef {
|
||||
name: "get_comp",
|
||||
description: "A composition: id, name, size, frame rate, duration, work area, background and its layers top to bottom (id, index, name, type, in/out/start seconds, blend mode, parent, track matte, switches). Layer ids feed get_layer, get_property/set_property and commands.",
|
||||
bridge_only: false,
|
||||
schema: || schema(json!({"comp": comp_s()}), &[]),
|
||||
run: get_comp,
|
||||
},
|
||||
ToolDef {
|
||||
name: "get_layer",
|
||||
description: "A layer's property tree (transform, masks, effects, text, shape contents, ...): every node has a `path` usable with get_property/set_property/add_keyframe, plus uid, match id, name, type, value at `time`, keyframes and expression. `flat: true` returns just a list of {path, type, value, keys, expression} (compact).",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"layer": layer_s(), "comp": comp_s(),
|
||||
"time": {"type": "number", "description": "Comp time in seconds for values (default: current time)."},
|
||||
"depth": {"type": "integer", "description": "Group depth to expand (default all)."},
|
||||
"flat": {"type": "boolean", "description": "Return a flat list of properties instead of the tree."}
|
||||
}),
|
||||
&["layer"],
|
||||
)
|
||||
},
|
||||
run: get_layer,
|
||||
},
|
||||
ToolDef {
|
||||
name: "get_property",
|
||||
description: "Read one property: type, value at `time` (comp seconds; default the current time), whether it is animated, its keyframes (time, value, in/out interpolation) and expression.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({"layer": layer_s(), "path": path_s(), "comp": comp_s(), "time": {"type": "number", "description": "Comp time in seconds."}}),
|
||||
&["layer", "path"],
|
||||
)
|
||||
},
|
||||
run: get_property,
|
||||
},
|
||||
ToolDef {
|
||||
name: "set_property",
|
||||
description: "Set a property. Without `time`: sets the static value (or a key at the current time if already animated). With `time`: adds/replaces a keyframe there, turning the stopwatch on. `expression` sets an After Effects-style JS expression (\"\" removes it). Returns the property as get_property does. Examples: {\"layer\":3,\"path\":\"transform/opacity\",\"value\":50}; {\"layer\":\"Title\",\"path\":\"transform/position\",\"value\":[200,540],\"time\":0}; {\"layer\":3,\"path\":\"transform/rotation\",\"expression\":\"time*90\"}.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"layer": layer_s(), "path": path_s(), "value": value_s(), "comp": comp_s(),
|
||||
"time": {"type": "number", "description": "Keyframe time in seconds (layer time; equals comp time unless the layer is offset/stretched)."},
|
||||
"expression": {"type": "string", "description": "Expression text; empty string removes the expression."}
|
||||
}),
|
||||
&["layer", "path"],
|
||||
)
|
||||
},
|
||||
run: set_property,
|
||||
},
|
||||
ToolDef {
|
||||
name: "add_keyframe",
|
||||
description: "Add keyframes to a property (turns the stopwatch on): one with `time` (+ optional `value`, default the current value) or many with `keys: [{time, value}]`, then optionally set their `interpolation`: linear, bezier, hold, easyEase, easyEaseIn, easyEaseOut. Example: {\"layer\":1,\"path\":\"transform/position\",\"keys\":[{\"time\":0,\"value\":[0,540]},{\"time\":2,\"value\":[1920,540]}],\"interpolation\":\"easyEase\"}.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"layer": layer_s(), "path": path_s(), "comp": comp_s(),
|
||||
"time": {"type": "number", "description": "Key time in seconds (layer time)."},
|
||||
"value": value_s(),
|
||||
"keys": {"type": "array", "items": {"type": "object", "properties": {"time": {"type": "number"}, "value": value_s()}, "required": ["time"]}, "description": "Several keys at once."},
|
||||
"interpolation": {"type": "string", "enum": ["linear", "bezier", "hold", "easyEase", "easyEaseIn", "easyEaseOut"]}
|
||||
}),
|
||||
&["layer", "path"],
|
||||
)
|
||||
},
|
||||
run: add_keyframe,
|
||||
},
|
||||
ToolDef {
|
||||
name: "render_frame",
|
||||
description: "Render a composition frame (default: the active comp at the current time) and return it as a PNG image, longest side `max_side` (default 960, 0 = full size). `path` also writes the PNG to disk; `inline: false` returns only the metadata. Use it to check your work.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"comp": comp_s(),
|
||||
"time": {"type": "number", "description": "Comp time in seconds (default: current time)."},
|
||||
"max_side": {"type": "integer", "description": "Longest side in pixels (default 960; 0 = full comp size)."},
|
||||
"path": {"type": "string", "description": "Also write the PNG here."},
|
||||
"inline": {"type": "boolean", "description": "Include the image in the reply (default true)."}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
},
|
||||
run: render_frame,
|
||||
},
|
||||
ToolDef {
|
||||
name: "open_project",
|
||||
description: "Open a project: `path` to an .ecproj file, `demo: true` for the built-in demo project, or `new: true` for an empty project. Returns the project overview.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(json!({"path": {"type": "string", "description": "Path of an .ecproj file."}, "demo": {"type": "boolean"}, "new": {"type": "boolean"}}), &[])
|
||||
},
|
||||
run: open_project,
|
||||
},
|
||||
ToolDef {
|
||||
name: "save_project",
|
||||
description: "Save the project to its current file, or to `path` (Save As, .ecproj).",
|
||||
bridge_only: false,
|
||||
schema: || schema(json!({"path": {"type": "string", "description": "Destination .ecproj path (Save As)."}}), &[]),
|
||||
run: save_project,
|
||||
},
|
||||
ToolDef {
|
||||
name: "undo",
|
||||
description: "Undo the last `steps` edits (default 1). Returns the remaining undo stack.",
|
||||
bridge_only: false,
|
||||
schema: || schema(json!({"steps": {"type": "integer", "minimum": 1}}), &[]),
|
||||
run: undo,
|
||||
},
|
||||
ToolDef {
|
||||
name: "redo",
|
||||
description: "Redo `steps` undone edits (default 1).",
|
||||
bridge_only: false,
|
||||
schema: || schema(json!({"steps": {"type": "integer", "minimum": 1}}), &[]),
|
||||
run: redo,
|
||||
},
|
||||
ToolDef {
|
||||
name: "screenshot",
|
||||
description: "Screenshot of the live app window, or one panel (`Composition`, `Timeline`, `EffectControls`, `Project`, ...) or element id, as PNG (longest side `max_side`, default 1600). Use it to check what the UI looks like after an action.",
|
||||
bridge_only: true,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"panel": {"type": "string", "description": "Panel to crop to."},
|
||||
"id": {"type": "string", "description": "Element id (from ui_elements) to crop to."},
|
||||
"max_side": {"type": "integer"},
|
||||
"path": {"type": "string", "description": "Keep the full-size PNG at this path."}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
},
|
||||
run: screenshot,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_inspect",
|
||||
description: "UI state: window size, tool, workspace, panels, viewer and timeline view state, playback, active comp, selection, open dialog, render time.",
|
||||
bridge_only: true,
|
||||
schema: || schema(json!({}), &[]),
|
||||
run: ui_inspect,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_elements",
|
||||
description: "Interactive elements drawn in the last frame: id, label, rect [x,y,w,h] in points. Stable ids such as `tools.Selection`, `panel.Timeline`, `panel.tab.EffectControls`, `project.item.<id>`, `viewer.comp`, `timeline.layer.<id>.bar`, `timeline.prop.<uid>.stopwatch`, `timeline.cti`, `effects.item.<name>`. Filter with `prefix`.",
|
||||
bridge_only: true,
|
||||
schema: || schema(json!({"prefix": {"type": "string", "description": "Only ids starting with this, e.g. `tools.`, `timeline.layer.`."}}), &[]),
|
||||
run: ui_elements,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_click",
|
||||
description: "Click an element by `id` (from ui_elements) or at `x`,`y` (points). `button`: left|right|middle, `count`: 2 for double-click, `modifiers`: {shift, alt, command, ctrl}.",
|
||||
bridge_only: true,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"id": {"type": "string"}, "x": {"type": "number"}, "y": {"type": "number"},
|
||||
"button": {"type": "string", "enum": ["left", "right", "middle"]},
|
||||
"count": {"type": "integer"}, "modifiers": {"type": "object"}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
},
|
||||
run: ui_click,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_drag",
|
||||
description: "Press-move-release from `from` to `to`; each is {\"id\": element} (add fx/fy 0-1 for a spot inside it) or {\"x\",\"y\"}. Moves layers in the viewer, drags layer bars/keyframes/the CTI (`timeline.cti`), scrubs values, draws shapes with a shape tool.",
|
||||
bridge_only: true,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({"from": {"type": "object"}, "to": {"type": "object"}, "steps": {"type": "integer"}, "modifiers": {"type": "object"}}),
|
||||
&["from", "to"],
|
||||
)
|
||||
},
|
||||
run: ui_drag,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_key",
|
||||
description: "Press a key or shortcut: `Space` (play), `F9` (Easy Ease), `Cmd+Z`, `Cmd+N`, `PageDown`, `Escape`, `Enter` (`Cmd` = Ctrl off macOS).",
|
||||
bridge_only: true,
|
||||
schema: || schema(json!({"key": {"type": "string"}}), &["key"]),
|
||||
run: ui_key,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_type",
|
||||
description: "Type text into the focused field (text layer editing, search boxes, value fields).",
|
||||
bridge_only: true,
|
||||
schema: || schema(json!({"text": {"type": "string"}}), &["text"]),
|
||||
run: ui_type,
|
||||
},
|
||||
ToolDef {
|
||||
name: "ui_set",
|
||||
description: "Set UI state directly: tool, workspace, theme (dark|darker|light), focused panel, viewer {zoom, res, pan, grid, rulers, safeMargins, transparencyGrid}, timeline {pps, start, graphEditor, showModes, openLayers, openGroups}, menuBar, home.",
|
||||
bridge_only: true,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"tool": {"type": "string"}, "workspace": {"type": "string"}, "theme": {"type": "string"}, "focused": {"type": "string"},
|
||||
"viewer": {"type": "object"}, "timeline": {"type": "object"}, "menuBar": {"type": "boolean"}, "home": {"type": "boolean"}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
},
|
||||
run: ui_set,
|
||||
},
|
||||
ToolDef {
|
||||
name: "control",
|
||||
description: "Call any control-channel method (docs/control-protocol.md) with its params, e.g. ui.menu.list, ui.menu.invoke {id}, ui.panel.show {panel}, ui.scroll, ui.viewer.locate {x,y}, ui.timeline.locate {layer,time}, ui.playback {action}, ui.resize.",
|
||||
bridge_only: true,
|
||||
schema: || schema(json!({"method": {"type": "string"}, "params": {"type": "object", "additionalProperties": true}}), &["method"]),
|
||||
run: control,
|
||||
},
|
||||
];
|
||||
@@ -596,7 +596,15 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
],
|
||||
vector_blur,
|
||||
),
|
||||
spec("ec.blur.reduceflicker", "Reduce Interlace Flicker", vec![p("softness", "Softness", num(0.0), slider(0.0, 100.0, 0.0, 10.0, 2))], reduce_flicker),
|
||||
EffectSpec {
|
||||
category: "Obsolete",
|
||||
..spec(
|
||||
"ec.blur.reduceflicker",
|
||||
"Reduce Interlace Flicker",
|
||||
vec![p("softness", "Softness", num(0.0), slider(0.0, 100.0, 0.0, 10.0, 2))],
|
||||
reduce_flicker,
|
||||
)
|
||||
},
|
||||
spec(
|
||||
"ec.blur.cccross",
|
||||
"CC Cross Blur",
|
||||
@@ -621,7 +629,8 @@ mod tests {
|
||||
for (k, v) in over {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
(s.render)(&ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -425,7 +425,8 @@ mod tests {
|
||||
for (k, v) in over {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: true };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: true, env: Default::default() };
|
||||
apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
//! Channel effects, batch 2: layer-to-layer combinations (Blend, Calculations, Compound
|
||||
//! Arithmetic) and CC Composite. Second layers come from layer parameters through the effect
|
||||
//! host; with no layer chosen the effect uses the layer itself, as After Effects does.
|
||||
|
||||
use effectcraft_color::{BlendMode, blend_pixel, hsl_to_rgb, luminance, rgb_to_hsl};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{layer_or_self, lerp4, premul, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Channel", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
fn layer_param(id: &'static str, name: &'static str) -> crate::ParamSpec {
|
||||
p(id, name, Value::Layer(None), ParamUi::Layer)
|
||||
}
|
||||
|
||||
const SIZE_DIFF: [&str; 2] = ["Center", "Stretch to Fit"];
|
||||
|
||||
// ---------------------------------------------------------------- Blend
|
||||
|
||||
fn blend(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let mode = ctx.params.e("mode");
|
||||
let orig = (ctx.params.f("blendWithOriginal") as f32 / 100.0).clamp(0.0, 1.0);
|
||||
if orig >= 1.0 {
|
||||
return b;
|
||||
}
|
||||
let other = layer_or_self(ctx, &b, "blendWithLayer", true, ctx.params.e("ifLayerSizesDiffer") == 1);
|
||||
b.img.data.par_iter_mut().zip(other.data.par_iter()).for_each(|(px, &o)| {
|
||||
let src = *px;
|
||||
let blended = match mode {
|
||||
// Crossfade: the other layer replaces this one.
|
||||
0 => o,
|
||||
// Color Only / Tint Only: hue (and saturation) from the other layer, lightness kept.
|
||||
1 | 2 => {
|
||||
let (c, a) = unpremul(src);
|
||||
let (oc, oa) = unpremul(o);
|
||||
if a <= 0.0 || oa <= 0.0 {
|
||||
src
|
||||
} else {
|
||||
let (_, s, l) = rgb_to_hsl(c[0], c[1], c[2]);
|
||||
let (oh, os, _) = rgb_to_hsl(oc[0], oc[1], oc[2]);
|
||||
let (h2, s2) = if mode == 1 {
|
||||
(oh, os)
|
||||
} else if s > 1e-4 {
|
||||
(oh, s)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
};
|
||||
let (r, g, bb) = hsl_to_rgb(h2, s2, l);
|
||||
let t = oa;
|
||||
lerp4(src, premul([r, g, bb], a), t)
|
||||
}
|
||||
}
|
||||
3 => [src[0].min(o[0]), src[1].min(o[1]), src[2].min(o[2]), src[3]],
|
||||
_ => [src[0].max(o[0]), src[1].max(o[1]), src[2].max(o[2]), src[3].max(o[3])],
|
||||
};
|
||||
*px = lerp4(blended, src, orig);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Calculations
|
||||
|
||||
/// Blending modes offered by Calculations / CC Composite (menu order).
|
||||
const CALC_MODES: [BlendMode; 22] = [
|
||||
BlendMode::Normal,
|
||||
BlendMode::Darken,
|
||||
BlendMode::Multiply,
|
||||
BlendMode::ColorBurn,
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::Add,
|
||||
BlendMode::Lighten,
|
||||
BlendMode::Screen,
|
||||
BlendMode::ColorDodge,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::Overlay,
|
||||
BlendMode::SoftLight,
|
||||
BlendMode::HardLight,
|
||||
BlendMode::LinearLight,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::PinLight,
|
||||
BlendMode::HardMix,
|
||||
BlendMode::Difference,
|
||||
BlendMode::Exclusion,
|
||||
BlendMode::Hue,
|
||||
BlendMode::Saturation,
|
||||
BlendMode::Luminosity,
|
||||
];
|
||||
|
||||
fn calc_mode_names() -> Vec<&'static str> {
|
||||
CALC_MODES.iter().map(|m| m.label()).collect()
|
||||
}
|
||||
|
||||
const CHANNELS: [&str; 6] = ["RGBA", "Gray", "Red", "Green", "Blue", "Alpha"];
|
||||
|
||||
/// Extract channel `ch` (index into [`CHANNELS`]) of a premultiplied pixel as a premultiplied
|
||||
/// pixel: RGBA unchanged, single channels as opaque grey (Alpha as grey too).
|
||||
#[inline]
|
||||
fn extract(px: [f32; 4], ch: u32, invert: bool) -> [f32; 4] {
|
||||
let (c, a) = unpremul(px);
|
||||
let g = match ch {
|
||||
0 => {
|
||||
if invert {
|
||||
return premul([1.0 - c[0], 1.0 - c[1], 1.0 - c[2]], a);
|
||||
}
|
||||
return px;
|
||||
}
|
||||
1 => luminance(c[0], c[1], c[2]) * a,
|
||||
2 => c[0] * a,
|
||||
3 => c[1] * a,
|
||||
4 => c[2] * a,
|
||||
_ => a,
|
||||
};
|
||||
let g = if invert { 1.0 - g } else { g };
|
||||
[g, g, g, 1.0]
|
||||
}
|
||||
|
||||
fn calculations(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let in_ch = ctx.params.e("inputChannel");
|
||||
let in_inv = ctx.params.b("invertInput");
|
||||
let second = ctx.params.get("secondLayer").and_then(Value::as_layer).is_some();
|
||||
let sec_ch = ctx.params.e("secondLayerChannel");
|
||||
let sec_op = (ctx.params.f("secondLayerOpacity") as f32 / 100.0).clamp(0.0, 1.0);
|
||||
let sec_inv = ctx.params.b("invertSecondLayer");
|
||||
let mode = CALC_MODES[(ctx.params.e("blendingMode") as usize).min(CALC_MODES.len() - 1)];
|
||||
let keep_alpha = ctx.params.b("preserveTransparency");
|
||||
let other = if second { Some(layer_or_self(ctx, &b, "secondLayer", true, ctx.params.b("stretchSecondLayerToFit"))) } else { None };
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let orig_a = px[3];
|
||||
let mut o = extract(*px, in_ch, in_inv);
|
||||
if let Some(other) = &other {
|
||||
let s = extract(other.data[i], sec_ch, sec_inv).map(|v| v * sec_op);
|
||||
o = blend_pixel(mode, o, s, 0.5);
|
||||
}
|
||||
if keep_alpha && o[3] > 1e-6 {
|
||||
let (c, _) = unpremul(o);
|
||||
o = premul(c, orig_a);
|
||||
}
|
||||
o[3] = o[3].clamp(0.0, 1.0);
|
||||
*px = o;
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CC Composite
|
||||
|
||||
const CC_COMPOSITE_MODES: [&str; 16] = [
|
||||
"In Front",
|
||||
"In Back",
|
||||
"Add",
|
||||
"Multiply",
|
||||
"Screen",
|
||||
"Overlay",
|
||||
"Soft Light",
|
||||
"Hard Light",
|
||||
"Darken",
|
||||
"Lighten",
|
||||
"Difference",
|
||||
"Hue",
|
||||
"Saturation",
|
||||
"Color",
|
||||
"Luminosity",
|
||||
"Stencil Alpha",
|
||||
];
|
||||
|
||||
/// Composites the original over/under/with the effect result. The original is the image as it
|
||||
/// enters this effect (the host does not expose the pre-effect source).
|
||||
fn cc_composite(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let op = (ctx.params.f("opacity") as f32 / 100.0).clamp(0.0, 1.0);
|
||||
let m = ctx.params.e("compositeOriginal");
|
||||
let rgb_only = ctx.params.b("rgbOnly");
|
||||
let mode = match m {
|
||||
2 => BlendMode::Add,
|
||||
3 => BlendMode::Multiply,
|
||||
4 => BlendMode::Screen,
|
||||
5 => BlendMode::Overlay,
|
||||
6 => BlendMode::SoftLight,
|
||||
7 => BlendMode::HardLight,
|
||||
8 => BlendMode::Darken,
|
||||
9 => BlendMode::Lighten,
|
||||
10 => BlendMode::Difference,
|
||||
11 => BlendMode::Hue,
|
||||
12 => BlendMode::Saturation,
|
||||
13 => BlendMode::Color,
|
||||
14 => BlendMode::Luminosity,
|
||||
15 => BlendMode::StencilAlpha,
|
||||
_ => BlendMode::Normal,
|
||||
};
|
||||
b.img.data.par_iter_mut().for_each(|px| {
|
||||
let result = *px;
|
||||
let orig = result.map(|v| v * op);
|
||||
let mut o = if m == 1 { blend_pixel(BlendMode::Normal, orig, result, 0.5) } else { blend_pixel(mode, result, orig, 0.5) };
|
||||
o[3] = o[3].clamp(0.0, 1.0);
|
||||
if rgb_only {
|
||||
let (c, _) = unpremul(o);
|
||||
o = premul(c, result[3]);
|
||||
}
|
||||
*px = o;
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Compound Arithmetic
|
||||
|
||||
const OPERATORS: [&str; 15] =
|
||||
["Copy", "Add", "Subtract", "Multiply", "Difference", "And", "Or", "Xor", "Lighten", "Darken", "Minimum", "Maximum", "Screen", "Overlay", "Hard Light"];
|
||||
|
||||
/// One channel operation on straight values in 0..1 (may overflow).
|
||||
#[inline]
|
||||
fn arith(op: u32, a: f32, b: f32) -> f32 {
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u32;
|
||||
match op {
|
||||
0 => b,
|
||||
1 => a + b,
|
||||
2 => a - b,
|
||||
3 => a * b,
|
||||
4 => (a - b).abs(),
|
||||
5 => (q(a) & q(b)) as f32 / 255.0,
|
||||
6 => (q(a) | q(b)) as f32 / 255.0,
|
||||
7 => (q(a) ^ q(b)) as f32 / 255.0,
|
||||
8 | 11 => a.max(b),
|
||||
9 | 10 => a.min(b),
|
||||
12 => a + b - a * b,
|
||||
13 => {
|
||||
if a < 0.5 {
|
||||
2.0 * a * b
|
||||
} else {
|
||||
1.0 - 2.0 * (1.0 - a) * (1.0 - b)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if b < 0.5 {
|
||||
2.0 * a * b
|
||||
} else {
|
||||
1.0 - 2.0 * (1.0 - a) * (1.0 - b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overflow handling: 0 Clip, 1 Wrap, 2 Scale (map the operator's full range to 0..1).
|
||||
#[inline]
|
||||
fn overflow(op: u32, v: f32, how: u32) -> f32 {
|
||||
match how {
|
||||
0 => v.clamp(0.0, 1.0),
|
||||
1 => v.rem_euclid(1.0001).min(1.0),
|
||||
_ => match op {
|
||||
1 => v * 0.5,
|
||||
2 => (v + 1.0) * 0.5,
|
||||
_ => v.clamp(0.0, 1.0),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn compound_arithmetic(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let op = ctx.params.e("operator");
|
||||
let chans = ctx.params.e("operateOnChannels");
|
||||
let how = ctx.params.e("overflowBehavior");
|
||||
let orig = (ctx.params.f("blendWithOriginal") as f32 / 100.0).clamp(0.0, 1.0);
|
||||
if orig >= 1.0 {
|
||||
return b;
|
||||
}
|
||||
let other = layer_or_self(ctx, &b, "secondSource", true, ctx.params.b("stretchSecondSourceToFit"));
|
||||
b.img.data.par_iter_mut().zip(other.data.par_iter()).for_each(|(px, &o)| {
|
||||
let src = *px;
|
||||
let (c, a) = unpremul(src);
|
||||
let (oc, oa) = unpremul(o);
|
||||
let mut rc = c;
|
||||
let mut ra = a;
|
||||
if chans != 2 {
|
||||
for k in 0..3 {
|
||||
rc[k] = overflow(op, arith(op, c[k], oc[k]), how);
|
||||
}
|
||||
}
|
||||
if chans != 0 {
|
||||
ra = overflow(op, arith(op, a, oa), how);
|
||||
}
|
||||
let res = premul(rc, ra);
|
||||
*px = lerp4(res, src, orig);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let calc_modes = calc_mode_names();
|
||||
vec![
|
||||
spec(
|
||||
"ec.channel.blend",
|
||||
"Blend",
|
||||
vec![
|
||||
layer_param("blendWithLayer", "Blend With Layer"),
|
||||
p("mode", "Mode", Value::Enum(0), popup(&["Crossfade", "Color Only", "Tint Only", "Darken Only", "Lighten Only"])),
|
||||
p("blendWithOriginal", "Blend With Original", num(0.0), pct()),
|
||||
p("ifLayerSizesDiffer", "If Layer Sizes Differ", Value::Enum(0), popup(&SIZE_DIFF)),
|
||||
],
|
||||
blend,
|
||||
),
|
||||
spec(
|
||||
"ec.channel.calculations",
|
||||
"Calculations",
|
||||
vec![
|
||||
p("inputChannel", "Input Channel", Value::Enum(0), popup(&CHANNELS)),
|
||||
p("invertInput", "Invert Input", Value::Bool(false), ParamUi::Checkbox),
|
||||
layer_param("secondLayer", "Second Layer"),
|
||||
p("secondLayerChannel", "Second Layer Channel", Value::Enum(0), popup(&CHANNELS)),
|
||||
p("secondLayerOpacity", "Second Layer Opacity", num(100.0), pct()),
|
||||
p("invertSecondLayer", "Invert Second Layer", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("stretchSecondLayerToFit", "Stretch Second Layer to Fit", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("blendingMode", "Blending Mode", Value::Enum(0), ParamUi::Popup { options: calc_modes.iter().map(|s| s.to_string()).collect() }),
|
||||
p("preserveTransparency", "Preserve Transparency", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
calculations,
|
||||
),
|
||||
spec(
|
||||
"ec.channel.cccomposite",
|
||||
"CC Composite",
|
||||
vec![
|
||||
p("opacity", "Opacity", num(100.0), pct()),
|
||||
p("compositeOriginal", "Composite Original", Value::Enum(0), popup(&CC_COMPOSITE_MODES)),
|
||||
p("rgbOnly", "RGB Only", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
cc_composite,
|
||||
),
|
||||
spec(
|
||||
"ec.channel.compoundarithmetic",
|
||||
"Compound Arithmetic",
|
||||
vec![
|
||||
layer_param("secondSource", "Second Source Layer"),
|
||||
p("operator", "Operator", Value::Enum(0), popup(&OPERATORS)),
|
||||
p("operateOnChannels", "Operate On Channels", Value::Enum(0), popup(&["RGB", "ARGB", "Alpha"])),
|
||||
p("overflowBehavior", "Overflow Behavior", Value::Enum(0), popup(&["Clip", "Wrap", "Scale"])),
|
||||
p("stretchSecondSourceToFit", "Stretch Second Source to Fit", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("blendWithOriginal", "Blend With Original", num(0.0), pct()),
|
||||
],
|
||||
compound_arithmetic,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, EffectHost, LayerPixels, run_fx};
|
||||
use effectcraft_raster::Image;
|
||||
|
||||
/// A host that knows one other layer (id 7).
|
||||
pub(crate) struct FakeHost(pub Image);
|
||||
impl EffectHost for FakeHost {
|
||||
fn layer(&self, id: u64, _: bool) -> Option<LayerPixels> {
|
||||
(id == 7).then(|| LayerPixels { buf: Buf { img: self.0.clone(), offset: [0.0; 2], scale: 1.0 }, size: [self.0.width as f64, self.0.height as f64] })
|
||||
}
|
||||
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sample() -> Image {
|
||||
let mut img = Image::new(8, 6);
|
||||
for y in 0..6 {
|
||||
for x in 0..8 {
|
||||
let a = if x < 6 { 1.0 } else { 0.5 };
|
||||
img.set(x, y, [x as f32 / 8.0 * a, y as f32 / 6.0 * a, 0.4 * a, a]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn close(a: &Image, b: &Image, tol: f32) -> bool {
|
||||
a.data.iter().zip(b.data.iter()).all(|(p, q)| p.iter().zip(q.iter()).all(|(x, y)| (x - y).abs() <= tol))
|
||||
}
|
||||
|
||||
fn with_host<R>(other: Image, f: impl FnOnce(EffectEnv) -> R) -> R {
|
||||
let host = FakeHost(other);
|
||||
f(EffectEnv { host: Some(&host), ..Default::default() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_self_crossfade_is_identity_and_layer_crossfades() {
|
||||
let img = sample();
|
||||
let out = run_fx("ec.channel.blend", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!(close(&out.img, &img, 1e-6));
|
||||
let red = Image::filled(8, 6, [1.0, 0.0, 0.0, 1.0]);
|
||||
let out = with_host(red, |env| {
|
||||
run_fx("ec.channel.blend", &[("blendWithLayer", Value::Layer(Some(7))), ("blendWithOriginal", num(50.0))], img.clone(), 0.0, env)
|
||||
});
|
||||
let p = out.img.get(0, 0);
|
||||
assert!((p[0] - 0.5).abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5);
|
||||
let again = with_host(Image::filled(8, 6, [1.0, 0.0, 0.0, 1.0]), |env| {
|
||||
run_fx("ec.channel.blend", &[("blendWithLayer", Value::Layer(Some(7))), ("blendWithOriginal", num(50.0))], img.clone(), 0.0, env)
|
||||
});
|
||||
assert_eq!(out.img.data, again.img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculations_defaults_identity_and_gray() {
|
||||
let img = sample();
|
||||
let out = run_fx("ec.channel.calculations", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!(close(&out.img, &img, 1e-6));
|
||||
let g = run_fx("ec.channel.calculations", &[("inputChannel", Value::Enum(2))], img.clone(), 0.0, EffectEnv::default());
|
||||
let p = g.img.get(4, 2);
|
||||
assert!((p[0] - 0.5).abs() < 1e-5 && p[0] == p[1] && p[1] == p[2]);
|
||||
let m = with_host(Image::filled(8, 6, [0.5, 0.5, 0.5, 1.0]), |env| {
|
||||
run_fx("ec.channel.calculations", &[("secondLayer", Value::Layer(Some(7))), ("blendingMode", Value::Enum(2))], img.clone(), 0.0, env)
|
||||
});
|
||||
let q = m.img.get(4, 0);
|
||||
assert!((q[0] - 0.25).abs() < 1e-4, "{q:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cc_composite_in_front_is_identity_on_opaque() {
|
||||
let img = Image::filled(4, 4, [0.3, 0.6, 0.2, 1.0]);
|
||||
let out = run_fx("ec.channel.cccomposite", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!(close(&out.img, &img, 1e-6));
|
||||
let add = run_fx("ec.channel.cccomposite", &[("compositeOriginal", Value::Enum(2))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!((add.img.get(0, 0)[0] - 0.6).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_arithmetic_copy_self_identity_and_add() {
|
||||
let img = sample();
|
||||
let out = run_fx("ec.channel.compoundarithmetic", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!(close(&out.img, &img, 1e-5));
|
||||
let other = Image::filled(8, 6, [0.25, 0.25, 0.25, 1.0]);
|
||||
let add = with_host(other, |env| {
|
||||
run_fx("ec.channel.compoundarithmetic", &[("secondSource", Value::Layer(Some(7))), ("operator", Value::Enum(1))], img.clone(), 0.0, env)
|
||||
});
|
||||
let p = add.img.get(4, 3);
|
||||
assert!((p[0] - (0.5 + 0.25)).abs() < 1e-5 && (p[1] - 0.75).abs() < 1e-5, "{p:?}");
|
||||
let sc = with_host(Image::filled(8, 6, [1.0, 1.0, 1.0, 1.0]), |env| {
|
||||
run_fx(
|
||||
"ec.channel.compoundarithmetic",
|
||||
&[("secondSource", Value::Layer(Some(7))), ("operator", Value::Enum(1)), ("overflowBehavior", Value::Enum(2))],
|
||||
img.clone(),
|
||||
0.0,
|
||||
env,
|
||||
)
|
||||
});
|
||||
assert!((sc.img.get(4, 3)[0] - 0.75).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
@@ -886,7 +886,8 @@ mod tests {
|
||||
for (k, v) in over {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
(s.render)(&ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,575 @@
|
||||
//! Color Correction effects, batch 3: Change Color, Video Limiter, CC Color Neutralizer,
|
||||
//! PS Arbitrary Map and Lumetri Color (Basic Correction, Creative, Curves, Color Wheels,
|
||||
//! Vignette).
|
||||
|
||||
use effectcraft_color::{hsl_to_rgb, luminance, rgb_to_hsl};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{Plane, gauss_plane, layer_rect, lerp, premul, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Color Correction", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
fn bipolar() -> ParamUi {
|
||||
slider(-100.0, 100.0, -100.0, 100.0, 1)
|
||||
}
|
||||
|
||||
/// Apply `f(straight colour) -> straight colour` to every pixel, keeping alpha.
|
||||
fn map_colour(b: &mut Buf, f: impl Fn(usize, [f32; 3]) -> [f32; 3] + Sync) {
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(*px);
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
*px = premul(f(i, c), a);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Change Color
|
||||
|
||||
/// Similarity mask (1 = matches) of colour `c` to `key`.
|
||||
#[inline]
|
||||
fn colour_match(c: [f32; 3], key: [f32; 3], using: u32, tol: f32, soft: f32) -> f32 {
|
||||
let d = match using {
|
||||
0 => ((c[0] - key[0]).powi(2) + (c[1] - key[1]).powi(2) + (c[2] - key[2]).powi(2)).sqrt() / 3f32.sqrt(),
|
||||
1 => {
|
||||
let (h1, s1, _) = rgb_to_hsl(c[0], c[1], c[2]);
|
||||
let (h2, _, _) = rgb_to_hsl(key[0], key[1], key[2]);
|
||||
let dh = (h1 - h2).abs();
|
||||
let dh = dh.min(1.0 - dh) * 2.0;
|
||||
// Greys have no reliable hue.
|
||||
if s1 < 0.02 { 1.0 } else { dh }
|
||||
}
|
||||
_ => {
|
||||
let chroma = |c: [f32; 3]| {
|
||||
let s = (c[0] + c[1] + c[2]).max(1e-6);
|
||||
[c[0] / s, c[1] / s]
|
||||
};
|
||||
let (a, k) = (chroma(c), chroma(key));
|
||||
((a[0] - k[0]).powi(2) + (a[1] - k[1]).powi(2)).sqrt() * 1.5
|
||||
}
|
||||
};
|
||||
if d <= tol {
|
||||
1.0
|
||||
} else if soft <= 1e-6 {
|
||||
0.0
|
||||
} else {
|
||||
(1.0 - (d - tol) / soft).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn change_color(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let view_mask = ctx.params.e("view") == 1;
|
||||
let dh = (ctx.params.f("hueTransform") / 360.0) as f32;
|
||||
let dl = (ctx.params.f("lightnessTransform") / 100.0) as f32;
|
||||
let ds = (ctx.params.f("saturationTransform") / 100.0) as f32;
|
||||
let k = ctx.params.color("colorToChange");
|
||||
let key = [k[0], k[1], k[2]];
|
||||
let tol = (ctx.params.f("matchingTolerance") / 100.0) as f32;
|
||||
let soft = (ctx.params.f("matchingSoftness") / 100.0) as f32;
|
||||
let using = ctx.params.e("matchColors");
|
||||
let invert = ctx.params.b("invertColorCorrectionMask");
|
||||
if !view_mask && dh == 0.0 && dl == 0.0 && ds == 0.0 {
|
||||
return b;
|
||||
}
|
||||
map_colour(&mut b, |_, c| {
|
||||
let mut m = colour_match(c, key, using, tol, soft);
|
||||
if invert {
|
||||
m = 1.0 - m;
|
||||
}
|
||||
if view_mask {
|
||||
return [m; 3];
|
||||
}
|
||||
if m <= 0.0 {
|
||||
return c;
|
||||
}
|
||||
let (h, s, l) = rgb_to_hsl(c[0], c[1], c[2]);
|
||||
let h2 = (h + dh).rem_euclid(1.0);
|
||||
let s2 = (s + ds * if ds > 0.0 { 1.0 - s } else { s }).clamp(0.0, 1.0);
|
||||
let l2 = (l + dl * if dl > 0.0 { 1.0 - l } else { l }).clamp(0.0, 1.0);
|
||||
let (r, g, bb) = hsl_to_rgb(h2, s2, l2);
|
||||
[lerp(c[0], r, m), lerp(c[1], g, m), lerp(c[2], bb, m)]
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Video Limiter
|
||||
|
||||
const CLIP_LEVELS: [f32; 5] = [0.9, 0.95, 1.0, 1.05, 1.09];
|
||||
|
||||
/// Soft knee: values above `start` approach `limit` smoothly.
|
||||
#[inline]
|
||||
fn knee(v: f32, start: f32, limit: f32) -> f32 {
|
||||
if v <= start || limit <= start {
|
||||
return v.min(limit);
|
||||
}
|
||||
let r = limit - start;
|
||||
start + r * (1.0 - (-(v - start) / r).exp())
|
||||
}
|
||||
|
||||
fn video_limiter(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let level = CLIP_LEVELS[(ctx.params.e("clipLevel") as usize).min(CLIP_LEVELS.len() - 1)];
|
||||
let method = ctx.params.e("clipMethod");
|
||||
let comp = [0.0, 0.03, 0.05, 0.1, 0.2][(ctx.params.e("compressionBeforeClipping") as usize).min(4)];
|
||||
let warn = ctx.params.b("gamutWarning");
|
||||
let wc = ctx.params.color("gamutWarningColor");
|
||||
let start = level * (1.0 - comp);
|
||||
map_colour(&mut b, |_, c| {
|
||||
let y = luminance(c[0], c[1], c[2]);
|
||||
let mut o = c;
|
||||
// Luma: compress luminance, keep chroma offsets.
|
||||
if method != 1 {
|
||||
let y2 = knee(y.max(0.0), start, level);
|
||||
o = [o[0] - y + y2, o[1] - y + y2, o[2] - y + y2];
|
||||
}
|
||||
// Chroma: scale chroma towards luma until every channel is within 0..level.
|
||||
if method != 0 {
|
||||
let yl = luminance(o[0], o[1], o[2]);
|
||||
let mut t = 1.0f32;
|
||||
for &v in &o {
|
||||
if v > level && v - yl > 1e-6 {
|
||||
t = t.min((level - yl) / (v - yl));
|
||||
}
|
||||
if v < 0.0 && yl - v > 1e-6 {
|
||||
t = t.min(yl / (yl - v));
|
||||
}
|
||||
}
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
o = [yl + (o[0] - yl) * t, yl + (o[1] - yl) * t, yl + (o[2] - yl) * t];
|
||||
}
|
||||
let o = o.map(|v| v.clamp(0.0, level));
|
||||
if warn && (c.iter().zip(o.iter()).any(|(a, b)| (a - b).abs() > 1e-4)) {
|
||||
return [wc[0], wc[1], wc[2]];
|
||||
}
|
||||
o
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CC Color Neutralizer
|
||||
|
||||
fn color_neutralizer(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pairs = [("shadowsUnbalance", "shadowsBalance"), ("midtonesUnbalance", "midtonesBalance"), ("highlightsUnbalance", "highlightsBalance")];
|
||||
let off: Vec<[f32; 3]> = pairs
|
||||
.iter()
|
||||
.map(|(u, bal)| {
|
||||
let (u, v) = (ctx.params.color(u), ctx.params.color(bal));
|
||||
[v[0] - u[0], v[1] - u[1], v[2] - u[2]]
|
||||
})
|
||||
.collect();
|
||||
let pin = (ctx.params.f("pinning") / 100.0) as f32;
|
||||
let orig = (ctx.params.f("blendWOriginal") / 100.0) as f32;
|
||||
let contrast = (ctx.params.f("contrast") / 100.0) as f32;
|
||||
let darks = (ctx.params.f("darks") / 100.0) as f32;
|
||||
let brights = (ctx.params.f("brights") / 100.0) as f32;
|
||||
map_colour(&mut b, |_, c| {
|
||||
let l = luminance(c[0], c[1], c[2]).clamp(0.0, 1.0);
|
||||
let ws = 1.0 - smoothstep(0.0, 0.5, l);
|
||||
let wh = smoothstep(0.5, 1.0, l);
|
||||
let wm = 1.0 - ws - wh;
|
||||
// Pinning keeps pure black and pure white fixed.
|
||||
let keep = 1.0 - pin * (1.0 - 4.0 * l * (1.0 - l)).clamp(0.0, 1.0);
|
||||
let mut o = [0.0; 3];
|
||||
for k in 0..3 {
|
||||
let d = off[0][k] * ws + off[1][k] * wm + off[2][k] * wh;
|
||||
let mut v = c[k] + d * keep;
|
||||
v = 0.5 + (v - 0.5) * (1.0 + contrast);
|
||||
v += darks * 0.25 * (1.0 - l).powi(2) + brights * 0.25 * l * l;
|
||||
o[k] = v.max(0.0);
|
||||
}
|
||||
[lerp(o[0], c[0], orig), lerp(o[1], c[1], orig), lerp(o[2], c[2], orig)]
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- PS Arbitrary Map
|
||||
|
||||
/// Parse a map string of 256 comma/space separated values (0..255, or 0..1 floats). An empty or
|
||||
/// malformed map is the identity.
|
||||
fn parse_map(s: &str) -> Vec<f32> {
|
||||
let vals: Vec<f32> = s.split(|ch: char| ch == ',' || ch.is_whitespace()).filter(|t| !t.is_empty()).filter_map(|t| t.parse::<f32>().ok()).collect();
|
||||
if vals.len() < 2 {
|
||||
return (0..256).map(|i| i as f32 / 255.0).collect();
|
||||
}
|
||||
let max = vals.iter().cloned().fold(0.0f32, f32::max);
|
||||
let k = if max > 1.0 { 1.0 / 255.0 } else { 1.0 };
|
||||
vals.iter().map(|v| (v * k).clamp(0.0, 1.0)).collect()
|
||||
}
|
||||
|
||||
fn arbitrary_map(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let map = parse_map(ctx.params.s("map"));
|
||||
let phase = ctx.params.f("phase");
|
||||
let alpha = ctx.params.b("applyPhaseMapToAlpha");
|
||||
let n = map.len();
|
||||
let lookup = |v: f32| -> f32 {
|
||||
let x = (v.clamp(0.0, 1.0) as f64 * (n - 1) as f64 + phase * (n - 1) as f64 / 255.0).rem_euclid(n as f64);
|
||||
let i0 = x.floor() as usize % n;
|
||||
let i1 = if i0 + 1 < n { i0 + 1 } else { i0 };
|
||||
let t = (x - x.floor()) as f32;
|
||||
lerp(map[i0], map[i1], t)
|
||||
};
|
||||
b.img.data.par_iter_mut().for_each(|px| {
|
||||
let (c, a) = unpremul(*px);
|
||||
let o = c.map(lookup);
|
||||
let na = if alpha { lookup(a) } else { a };
|
||||
*px = premul(o, na);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Lumetri Color
|
||||
|
||||
/// Smooth tone-curve adjustment: offsets for shadows/midtones/highlights (each -1..1), with the
|
||||
/// end points fixed.
|
||||
#[inline]
|
||||
fn tone_curve(x: f32, s: f32, m: f32, h: f32) -> f32 {
|
||||
if s == 0.0 && m == 0.0 && h == 0.0 {
|
||||
return x;
|
||||
}
|
||||
let t = x.clamp(0.0, 1.0);
|
||||
let bump = |c: f32| {
|
||||
let d = (t - c) / 0.25;
|
||||
(1.0 - d * d).max(0.0).powi(2)
|
||||
};
|
||||
x + 0.25 * (s * bump(0.25) + m * bump(0.5) + h * bump(0.75))
|
||||
}
|
||||
|
||||
/// The colour part of a wheel/tint colour (offset from its own grey), 0 for neutral colours.
|
||||
#[inline]
|
||||
fn tint_offset(c: [f32; 4]) -> [f32; 3] {
|
||||
let l = (c[0] + c[1] + c[2]) / 3.0;
|
||||
[c[0] - l, c[1] - l, c[2] - l]
|
||||
}
|
||||
|
||||
fn lumetri(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let temp = (pr.f("temperature") / 100.0) as f32;
|
||||
let tint = (pr.f("tint") / 100.0) as f32;
|
||||
let expo = 2f32.powf(pr.f("exposure") as f32);
|
||||
let contrast = (pr.f("contrast") / 100.0) as f32;
|
||||
let (hi, sh, wh, bl) =
|
||||
((pr.f("highlights") / 100.0) as f32, (pr.f("shadows") / 100.0) as f32, (pr.f("whites") / 100.0) as f32, (pr.f("blacks") / 100.0) as f32);
|
||||
let sat = (pr.f("saturation") / 100.0) as f32;
|
||||
let intensity = (pr.f("lookIntensity") / 100.0) as f32;
|
||||
let faded = (pr.f("fadedFilm") / 100.0) as f32;
|
||||
let vib = (pr.f("vibrance") / 100.0) as f32;
|
||||
let csat = (pr.f("creativeSaturation") / 100.0) as f32;
|
||||
let st = tint_offset(pr.color("shadowTint"));
|
||||
let ht = tint_offset(pr.color("highlightTint"));
|
||||
let tbal = (pr.f("tintBalance") / 100.0) as f32;
|
||||
let curve = |k: &str| {
|
||||
[(pr.f(&format!("{k}Shadows")) / 100.0) as f32, (pr.f(&format!("{k}Midtones")) / 100.0) as f32, (pr.f(&format!("{k}Highlights")) / 100.0) as f32]
|
||||
};
|
||||
let (cm, cr, cg, cb) = (curve("curveMaster"), curve("curveRed"), curve("curveGreen"), curve("curveBlue"));
|
||||
let ws = tint_offset(pr.color("shadowsWheel"));
|
||||
let wm = tint_offset(pr.color("midtonesWheel"));
|
||||
let wh_ = tint_offset(pr.color("highlightsWheel"));
|
||||
let vig = pr.f("vignetteAmount") as f32;
|
||||
let vmid = (pr.f("vignetteMidpoint") / 100.0) as f32;
|
||||
let vround = (pr.f("vignetteRoundness") / 100.0) as f32;
|
||||
let vfeather = (pr.f("vignetteFeather") / 100.0) as f32;
|
||||
let sharpen = (pr.f("sharpen") / 100.0) as f32;
|
||||
let (lx, ly, lw, lh) = layer_rect(ctx, &b);
|
||||
let w = b.img.width as usize;
|
||||
let (cx, cy) = (lx + lw * 0.5, ly + lh * 0.5);
|
||||
map_colour(&mut b, |i, c| {
|
||||
let mut c = c;
|
||||
// Basic Correction: white balance, exposure, contrast, tone, saturation.
|
||||
if temp != 0.0 || tint != 0.0 {
|
||||
c = [c[0] * (1.0 + 0.25 * temp), c[1] * (1.0 - 0.25 * tint), c[2] * (1.0 - 0.25 * temp)];
|
||||
}
|
||||
if expo != 1.0 {
|
||||
c = c.map(|v| v * expo);
|
||||
}
|
||||
if contrast != 0.0 {
|
||||
c = c.map(|v| 0.5 + (v - 0.5) * (1.0 + contrast));
|
||||
}
|
||||
if hi != 0.0 || sh != 0.0 || wh != 0.0 || bl != 0.0 {
|
||||
let l = luminance(c[0], c[1], c[2]).max(0.0);
|
||||
let lt = l.min(1.0);
|
||||
let d = 0.25 * hi * smoothstep(0.5, 1.0, lt) + 0.25 * sh * (1.0 - smoothstep(0.0, 0.5, lt)) + 0.2 * wh * lt * lt + 0.2 * bl * (1.0 - lt).powi(2);
|
||||
c = c.map(|v| v + d);
|
||||
}
|
||||
let l = luminance(c[0], c[1], c[2]);
|
||||
if sat != 1.0 {
|
||||
c = c.map(|v| l + (v - l) * sat);
|
||||
}
|
||||
// Creative.
|
||||
if intensity != 0.0 && (faded != 0.0 || vib != 0.0 || csat != 1.0 || st != [0.0; 3] || ht != [0.0; 3]) {
|
||||
let mut d = c;
|
||||
if faded != 0.0 {
|
||||
d = d.map(|v| v * (1.0 - 0.25 * faded) + 0.12 * faded);
|
||||
}
|
||||
let l = luminance(d[0], d[1], d[2]);
|
||||
if vib != 0.0 {
|
||||
let mx = d[0].max(d[1]).max(d[2]);
|
||||
let mn = d[0].min(d[1]).min(d[2]);
|
||||
let s = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 };
|
||||
let k = 1.0 + vib * (1.0 - s.clamp(0.0, 1.0));
|
||||
d = d.map(|v| l + (v - l) * k);
|
||||
}
|
||||
if csat != 1.0 {
|
||||
d = d.map(|v| l + (v - l) * csat);
|
||||
}
|
||||
let pivot = (0.5 + 0.25 * tbal).clamp(0.05, 0.95);
|
||||
let lt = l.clamp(0.0, 1.0);
|
||||
let wsh = 1.0 - smoothstep(0.0, pivot, lt);
|
||||
let whi = smoothstep(pivot, 1.0, lt);
|
||||
for k in 0..3 {
|
||||
d[k] += 0.5 * (st[k] * wsh + ht[k] * whi);
|
||||
}
|
||||
c = [lerp(c[0], d[0], intensity), lerp(c[1], d[1], intensity), lerp(c[2], d[2], intensity)];
|
||||
}
|
||||
// Curves.
|
||||
c = c.map(|v| tone_curve(v, cm[0], cm[1], cm[2]));
|
||||
c = [tone_curve(c[0], cr[0], cr[1], cr[2]), tone_curve(c[1], cg[0], cg[1], cg[2]), tone_curve(c[2], cb[0], cb[1], cb[2])];
|
||||
// Color wheels.
|
||||
if ws != [0.0; 3] || wm != [0.0; 3] || wh_ != [0.0; 3] {
|
||||
let lt = luminance(c[0], c[1], c[2]).clamp(0.0, 1.0);
|
||||
let a = 1.0 - smoothstep(0.0, 0.5, lt);
|
||||
let z = smoothstep(0.5, 1.0, lt);
|
||||
let m = 1.0 - a - z;
|
||||
for k in 0..3 {
|
||||
c[k] += 0.5 * (ws[k] * a + wm[k] * m + wh_[k] * z);
|
||||
}
|
||||
}
|
||||
// Vignette.
|
||||
if vig != 0.0 {
|
||||
let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
|
||||
let nx = ((x - cx) / (lw * 0.5).max(1e-6)) as f32;
|
||||
let ny = ((y - cy) / (lh * 0.5).max(1e-6)) as f32;
|
||||
// Roundness: 0 follows the frame's aspect, +1 a circle, -1 squarer.
|
||||
let aspect = (lw / lh.max(1e-6)) as f32;
|
||||
let (nx, ny) = if vround > 0.0 { (nx * lerp(1.0, aspect.max(1.0), vround), ny * lerp(1.0, (1.0 / aspect).max(1.0), vround)) } else { (nx, ny) };
|
||||
let pw = 2.0 + (-vround).max(0.0) * 6.0;
|
||||
let r = (nx.abs().powf(pw) + ny.abs().powf(pw)).powf(1.0 / pw) / std::f32::consts::SQRT_2;
|
||||
let start = vmid * 0.9;
|
||||
let f = smoothstep(start, start + 0.05 + vfeather * (1.05 - start), r);
|
||||
let k = if vig < 0.0 { 1.0 + vig * 0.2 * f } else { 1.0 };
|
||||
c = c.map(|v| if vig > 0.0 { v + (1.0 - v) * (vig * 0.2 * f).min(1.0) } else { v * k.max(0.0) });
|
||||
}
|
||||
c.map(|v| v.max(0.0))
|
||||
});
|
||||
if sharpen != 0.0 {
|
||||
let luma = Plane::luma(&b.img);
|
||||
let blur = gauss_plane(&luma, 1.0 * b.scale, 1.0 * b.scale);
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(*px);
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let d = (luma.data[i] - blur.data[i]) * sharpen * 2.0;
|
||||
*px = premul(c.map(|v| (v + d).max(0.0)), a);
|
||||
});
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let grey = || col(0.5, 0.5, 0.5);
|
||||
let mut lum = vec![
|
||||
p("inputLut", "Input LUT", Value::Enum(0), popup(&["None"])),
|
||||
p("temperature", "Temperature", num(0.0), bipolar()),
|
||||
p("tint", "Tint", num(0.0), bipolar()),
|
||||
p("exposure", "Exposure", num(0.0), slider(-5.0, 5.0, -5.0, 5.0, 2)),
|
||||
p("contrast", "Contrast", num(0.0), bipolar()),
|
||||
p("highlights", "Highlights", num(0.0), bipolar()),
|
||||
p("shadows", "Shadows", num(0.0), bipolar()),
|
||||
p("whites", "Whites", num(0.0), bipolar()),
|
||||
p("blacks", "Blacks", num(0.0), bipolar()),
|
||||
p("saturation", "Saturation", num(100.0), slider(0.0, 200.0, 0.0, 200.0, 1)),
|
||||
p("look", "Look", Value::Enum(0), popup(&["None"])),
|
||||
p("lookIntensity", "Intensity", num(100.0), slider(0.0, 200.0, 0.0, 200.0, 1)),
|
||||
p("fadedFilm", "Faded Film", num(0.0), pct()),
|
||||
p("sharpen", "Sharpen", num(0.0), bipolar()),
|
||||
p("vibrance", "Vibrance", num(0.0), bipolar()),
|
||||
p("creativeSaturation", "Saturation", num(100.0), slider(0.0, 200.0, 0.0, 200.0, 1)),
|
||||
p("shadowTint", "Shadow Tint", grey(), ParamUi::Color),
|
||||
p("highlightTint", "Highlight Tint", grey(), ParamUi::Color),
|
||||
p("tintBalance", "Tint Balance", num(0.0), bipolar()),
|
||||
];
|
||||
const CURVES: [(&str, &str); 12] = [
|
||||
("curveMasterShadows", "RGB Curve Shadows"),
|
||||
("curveMasterMidtones", "RGB Curve Midtones"),
|
||||
("curveMasterHighlights", "RGB Curve Highlights"),
|
||||
("curveRedShadows", "Red Curve Shadows"),
|
||||
("curveRedMidtones", "Red Curve Midtones"),
|
||||
("curveRedHighlights", "Red Curve Highlights"),
|
||||
("curveGreenShadows", "Green Curve Shadows"),
|
||||
("curveGreenMidtones", "Green Curve Midtones"),
|
||||
("curveGreenHighlights", "Green Curve Highlights"),
|
||||
("curveBlueShadows", "Blue Curve Shadows"),
|
||||
("curveBlueMidtones", "Blue Curve Midtones"),
|
||||
("curveBlueHighlights", "Blue Curve Highlights"),
|
||||
];
|
||||
for (id, name) in CURVES {
|
||||
lum.push(p(id, name, num(0.0), bipolar()));
|
||||
}
|
||||
lum.extend([
|
||||
p("shadowsWheel", "Shadows", grey(), ParamUi::Color),
|
||||
p("midtonesWheel", "Midtones", grey(), ParamUi::Color),
|
||||
p("highlightsWheel", "Highlights", grey(), ParamUi::Color),
|
||||
p("vignetteAmount", "Amount", num(0.0), slider(-5.0, 5.0, -5.0, 5.0, 2)),
|
||||
p("vignetteMidpoint", "Midpoint", num(50.0), pct()),
|
||||
p("vignetteRoundness", "Roundness", num(0.0), bipolar()),
|
||||
p("vignetteFeather", "Feather", num(50.0), pct()),
|
||||
]);
|
||||
vec![
|
||||
spec(
|
||||
"ec.color.changecolor",
|
||||
"Change Color",
|
||||
vec![
|
||||
p("view", "View", Value::Enum(0), popup(&["Corrected Layer", "Color Correction Mask"])),
|
||||
p("hueTransform", "Hue Transform", num(0.0), slider(-360.0, 360.0, -180.0, 180.0, 1)),
|
||||
p("lightnessTransform", "Lightness Transform", num(0.0), bipolar()),
|
||||
p("saturationTransform", "Saturation Transform", num(0.0), bipolar()),
|
||||
p("colorToChange", "Color To Change", col(0.8, 0.2, 0.2), ParamUi::Color),
|
||||
p("matchingTolerance", "Matching Tolerance", num(15.0), pct()),
|
||||
p("matchingSoftness", "Matching Softness", num(0.0), pct()),
|
||||
p("matchColors", "Match colors", Value::Enum(1), popup(&["Using RGB", "Using Hue", "Using Chroma"])),
|
||||
p("invertColorCorrectionMask", "Invert Color Correction Mask", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
change_color,
|
||||
),
|
||||
spec(
|
||||
"ec.color.videolimiter",
|
||||
"Video Limiter",
|
||||
vec![
|
||||
p("clipLevel", "Clip Level", Value::Enum(2), popup(&["90%", "95%", "100%", "105%", "109%"])),
|
||||
p("clipMethod", "Clip Method", Value::Enum(2), popup(&["Luma", "Chroma", "Smart Limit"])),
|
||||
p("compressionBeforeClipping", "Compression before Clipping", Value::Enum(2), popup(&["None", "3%", "5%", "10%", "20%"])),
|
||||
p("gamutWarning", "Gamut Warning", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("gamutWarningColor", "Gamut Warning Color", col(1.0, 0.0, 0.0), ParamUi::Color),
|
||||
],
|
||||
video_limiter,
|
||||
),
|
||||
spec(
|
||||
"ec.color.cccolorneutralizer",
|
||||
"CC Color Neutralizer",
|
||||
vec![
|
||||
p("shadowsUnbalance", "Shadows Unbalance", col(0.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("shadowsBalance", "Shadows Balance", col(0.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("midtonesUnbalance", "Midtones Unbalance", grey(), ParamUi::Color),
|
||||
p("midtonesBalance", "Midtones Balance", grey(), ParamUi::Color),
|
||||
p("highlightsUnbalance", "Highlights Unbalance", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("highlightsBalance", "Highlights Balance", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("pinning", "Pinning", num(0.0), pct()),
|
||||
p("blendWOriginal", "Blend w. Original", num(0.0), pct()),
|
||||
p("darks", "Darks", num(0.0), bipolar()),
|
||||
p("brights", "Brights", num(0.0), bipolar()),
|
||||
p("contrast", "Contrast", num(0.0), bipolar()),
|
||||
],
|
||||
color_neutralizer,
|
||||
),
|
||||
spec(
|
||||
"ec.color.psarbitrarymap",
|
||||
"PS Arbitrary Map",
|
||||
vec![
|
||||
p("phase", "Phase", num(0.0), slider(-1000.0, 1000.0, 0.0, 255.0, 0)),
|
||||
p("applyPhaseMapToAlpha", "Apply Phase Map To Alpha", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("map", "Map", Value::Str(String::new()), ParamUi::Hidden),
|
||||
],
|
||||
arbitrary_map,
|
||||
),
|
||||
spec("ec.color.lumetri", "Lumetri Color", lum, lumetri),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
use effectcraft_raster::Image;
|
||||
|
||||
fn ramp() -> Image {
|
||||
let mut img = Image::new(16, 8);
|
||||
for y in 0..8 {
|
||||
for x in 0..16 {
|
||||
let a = if y < 7 { 1.0 } else { 0.5 };
|
||||
img.set(x, y, [x as f32 / 16.0 * a, (y as f32 / 8.0) * a, 0.3 * a, a]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn close(a: &Image, b: &Image, tol: f32) -> bool {
|
||||
a.data.iter().zip(b.data.iter()).all(|(p, q)| p.iter().zip(q.iter()).all(|(x, y)| (x - y).abs() <= tol))
|
||||
}
|
||||
|
||||
fn run(id: &str, vals: &[(&str, Value)], img: Image) -> Image {
|
||||
run_fx(id, vals, img, 0.0, EffectEnv::default()).img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_color_zero_is_identity_and_hue_shift_moves_red() {
|
||||
let img = ramp();
|
||||
assert!(close(&run("ec.color.changecolor", &[], img.clone()), &img, 0.0));
|
||||
let red = Image::filled(4, 4, [0.8, 0.2, 0.2, 1.0]);
|
||||
let out = run("ec.color.changecolor", &[("hueTransform", num(120.0))], red.clone());
|
||||
let p = out.get(1, 1);
|
||||
assert!(p[1] > p[0] && p[1] > p[2], "{p:?}");
|
||||
let blue = Image::filled(4, 4, [0.1, 0.2, 0.9, 1.0]);
|
||||
assert!(close(&run("ec.color.changecolor", &[("hueTransform", num(120.0))], blue.clone()), &blue, 1e-6));
|
||||
let mask = run("ec.color.changecolor", &[("view", Value::Enum(1))], red);
|
||||
assert!((mask.get(0, 0)[0] - 1.0).abs() < 1e-6);
|
||||
assert_eq!(out.data, run("ec.color.changecolor", &[("hueTransform", num(120.0))], Image::filled(4, 4, [0.8, 0.2, 0.2, 1.0])).data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn video_limiter_keeps_legal_and_limits_hot() {
|
||||
let mid = Image::filled(4, 4, [0.4, 0.5, 0.3, 1.0]);
|
||||
assert!(close(&run("ec.color.videolimiter", &[], mid.clone()), &mid, 1e-6));
|
||||
let hot = Image::filled(4, 4, [1.6, 1.2, 0.9, 1.0]);
|
||||
let out = run("ec.color.videolimiter", &[], hot);
|
||||
assert!(out.data.iter().all(|p| p[0] <= 1.0 + 1e-6 && p[1] <= 1.0 + 1e-6));
|
||||
let warn = run("ec.color.videolimiter", &[("gamutWarning", Value::Bool(true))], Image::filled(2, 2, [1.6, 1.2, 0.9, 1.0]));
|
||||
assert_eq!(warn.get(0, 0), [1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_neutralizer_defaults_identity_and_removes_cast() {
|
||||
let img = ramp();
|
||||
assert!(close(&run("ec.color.cccolorneutralizer", &[], img.clone()), &img, 1e-6));
|
||||
let cast = Image::filled(4, 4, [0.6, 0.5, 0.4, 1.0]);
|
||||
let out = run("ec.color.cccolorneutralizer", &[("midtonesUnbalance", col(0.6, 0.5, 0.4)), ("midtonesBalance", col(0.5, 0.5, 0.5))], cast);
|
||||
let p = out.get(0, 0);
|
||||
assert!((p[0] - p[2]).abs() < 0.1, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_map_identity_and_inverting_map() {
|
||||
let img = ramp();
|
||||
assert!(close(&run("ec.color.psarbitrarymap", &[], img.clone()), &img, 1e-5));
|
||||
let inv: Vec<String> = (0..256).map(|i| (255 - i).to_string()).collect();
|
||||
let out = run("ec.color.psarbitrarymap", &[("map", Value::Str(inv.join(",")))], Image::filled(2, 2, [0.25, 0.5, 1.0, 1.0]));
|
||||
let p = out.get(0, 0);
|
||||
assert!((p[0] - 0.75).abs() < 0.01 && p[2].abs() < 0.01, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lumetri_defaults_identity_and_controls_act() {
|
||||
let img = ramp();
|
||||
assert!(close(&run("ec.color.lumetri", &[], img.clone()), &img, 1e-5));
|
||||
let g = Image::filled(8, 8, [0.4, 0.4, 0.4, 1.0]);
|
||||
let e = run("ec.color.lumetri", &[("exposure", num(1.0))], g.clone());
|
||||
assert!((e.get(0, 0)[0] - 0.8).abs() < 1e-5);
|
||||
let warm = run("ec.color.lumetri", &[("temperature", num(50.0))], g.clone());
|
||||
assert!(warm.get(0, 0)[0] > warm.get(0, 0)[2]);
|
||||
let bw = run("ec.color.lumetri", &[("saturation", num(0.0))], img.clone());
|
||||
let p = bw.get(5, 3);
|
||||
assert!((p[0] - p[1]).abs() < 1e-5 && (p[1] - p[2]).abs() < 1e-5);
|
||||
let v = run("ec.color.lumetri", &[("vignetteAmount", num(-3.0))], g.clone());
|
||||
assert!(v.get(0, 0)[0] < v.get(4, 4)[0]);
|
||||
let c = run("ec.color.lumetri", &[("curveMasterMidtones", num(50.0))], g.clone());
|
||||
assert!(c.get(0, 0)[0] > 0.4);
|
||||
assert_eq!(c.data, run("ec.color.lumetri", &[("curveMasterMidtones", num(50.0))], g).data);
|
||||
}
|
||||
}
|
||||
@@ -690,7 +690,7 @@ mod tests {
|
||||
for (k, v) in set {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: ls, seed: 3, adjustment: false };
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: ls, seed: 3, adjustment: false, env: Default::default() };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -754,7 +754,7 @@ mod tests {
|
||||
for (k, v) in set {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: ls, seed: 3, adjustment: false };
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: ls, seed: 3, adjustment: false, env: Default::default() };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -485,7 +485,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
spec(
|
||||
"ec.key.luma",
|
||||
"Luma Key",
|
||||
"Keying",
|
||||
"Obsolete",
|
||||
vec![
|
||||
p("keyType", "Key Type", Value::Enum(1), popup(&["Key Out Brighter", "Key Out Darker", "Key Out Similar", "Key Out Dissimilar"])),
|
||||
p("threshold", "Threshold", num(0.0), b255()),
|
||||
@@ -560,7 +560,7 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
spec(
|
||||
"ec.key.spill",
|
||||
"Spill Suppressor",
|
||||
"Keying",
|
||||
"Obsolete",
|
||||
vec![
|
||||
p("colorToSuppress", "Color To Suppress", col(0.0, 0.0, 1.0), ParamUi::Color),
|
||||
p("suppression", "Suppression", num(100.0), slider(0.0, 200.0, 0.0, 100.0, 0)),
|
||||
@@ -617,7 +617,8 @@ mod tests {
|
||||
for (k, v) in over {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Keying effects, batch 2: Difference Matte (against another layer), Inner/Outer Key (mattes
|
||||
//! from masks with colour-based edge estimation and decontamination), Unmult and CC Simple
|
||||
//! Wire Removal.
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::gaussian_blur;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{Plane, dist_to_poly, gauss_plane, layer_or_self, lerp4, morph_frac, point_in_poly, premul, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Keying", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Difference Matte
|
||||
|
||||
fn difference_matte(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let view = ctx.params.e("view");
|
||||
if view == 1 {
|
||||
return b;
|
||||
}
|
||||
let tol = (ctx.params.f("matchingTolerance") / 100.0) as f32;
|
||||
let soft = (ctx.params.f("matchingSoftness") / 100.0) as f32;
|
||||
let blur = ctx.params.f("blurBeforeDifference") * b.scale;
|
||||
let other = layer_or_self(ctx, &b, "differenceLayer", true, ctx.params.e("ifLayerSizesDiffer") == 1);
|
||||
let (src, other) = if blur > 0.05 {
|
||||
(gaussian_blur(&b.img, blur * 0.5, blur * 0.5, true), gaussian_blur(&other, blur * 0.5, blur * 0.5, true))
|
||||
} else {
|
||||
(b.img.clone(), other)
|
||||
};
|
||||
let matte_only = view == 2;
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(src.data[i]);
|
||||
let (oc, oa) = unpremul(other.data[i]);
|
||||
let d = (c[0] - oc[0]).abs().max((c[1] - oc[1]).abs()).max((c[2] - oc[2]).abs()).max((a - oa).abs());
|
||||
let m = if d <= tol {
|
||||
0.0
|
||||
} else if soft <= 1e-6 {
|
||||
1.0
|
||||
} else {
|
||||
((d - tol) / soft).clamp(0.0, 1.0)
|
||||
};
|
||||
if matte_only {
|
||||
*px = [m * px[3], m * px[3], m * px[3], px[3]];
|
||||
} else {
|
||||
*px = px.map(|v| v * m);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Inner/Outer Key
|
||||
|
||||
fn mask_options() -> ParamUi {
|
||||
popup(&["None", "Mask 1", "Mask 2", "Mask 3", "Mask 4", "Mask 5", "Mask 6", "Mask 7", "Mask 8", "Mask 9", "Mask 10"])
|
||||
}
|
||||
|
||||
/// Coverage plane (1 inside) of the selected closed masks, in buffer pixels.
|
||||
fn mask_plane(ctx: &EffectCtx, b: &Buf, idx: &[u32]) -> Option<Plane> {
|
||||
let shapes: Vec<&crate::MaskShape> = idx.iter().filter(|&&i| i > 0).filter_map(|&i| ctx.env.masks.get(i as usize - 1)).collect();
|
||||
if shapes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let mut pl = Plane::new(w, h);
|
||||
let inv = 1.0 / b.scale.max(1e-9);
|
||||
pl.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
let lx = (x as f64 + 0.5 - b.offset[0]) * inv;
|
||||
let ly = (y as f64 + 0.5 - b.offset[1]) * inv;
|
||||
*v = if shapes.iter().any(|s| point_in_poly(&s.points, lx, ly)) { 1.0 } else { 0.0 };
|
||||
}
|
||||
});
|
||||
Some(pl)
|
||||
}
|
||||
|
||||
/// Signed distance (pixels, positive inside) to the selected mask outlines.
|
||||
fn mask_sdf(ctx: &EffectCtx, b: &Buf, idx: &[u32]) -> Option<Plane> {
|
||||
let shapes: Vec<&crate::MaskShape> = idx.iter().filter(|&&i| i > 0).filter_map(|&i| ctx.env.masks.get(i as usize - 1)).collect();
|
||||
if shapes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let mut pl = Plane::new(w, h);
|
||||
let inv = 1.0 / b.scale.max(1e-9);
|
||||
pl.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
let lx = (x as f64 + 0.5 - b.offset[0]) * inv;
|
||||
let ly = (y as f64 + 0.5 - b.offset[1]) * inv;
|
||||
let inside = shapes.iter().any(|s| point_in_poly(&s.points, lx, ly));
|
||||
let d = shapes.iter().map(|s| dist_to_poly(&s.points, true, lx, ly)).fold(f64::INFINITY, f64::min) * b.scale;
|
||||
*v = if inside { d as f32 } else { -d as f32 };
|
||||
}
|
||||
});
|
||||
Some(pl)
|
||||
}
|
||||
|
||||
fn inner_outer_key(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let fg_idx = [ctx.params.e("foreground"), ctx.params.e("additionalForeground")];
|
||||
let bg_idx = [ctx.params.e("background"), ctx.params.e("additionalBackground")];
|
||||
let radius = (ctx.params.f("singleMaskHighlightRadius") * b.scale) as f32;
|
||||
let thin = ctx.params.f("edgeThin") * b.scale;
|
||||
let feather = ctx.params.f("edgeFeather") * b.scale;
|
||||
let thr = (ctx.params.f("edgeThreshold") / 100.0) as f32;
|
||||
let invert = ctx.params.b("invertExtraction");
|
||||
let orig = (ctx.params.f("blendWithOriginal") / 100.0) as f32;
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
// Trimap: 1 = known foreground, 0 = known background, 0.5 = unknown.
|
||||
let fg = mask_plane(ctx, &b, &fg_idx);
|
||||
let bg = mask_plane(ctx, &b, &bg_idx);
|
||||
let tri: Plane = match (fg, bg) {
|
||||
(None, _) => return b,
|
||||
(Some(f), Some(bk)) => f.zip_map(&bk, |f, bk| {
|
||||
if f > 0.5 {
|
||||
1.0
|
||||
} else if bk > 0.5 {
|
||||
0.5
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}),
|
||||
(Some(f), None) => {
|
||||
if radius <= 0.0 {
|
||||
f
|
||||
} else {
|
||||
let sdf = mask_sdf(ctx, &b, &fg_idx).unwrap_or(f);
|
||||
sdf.map(|d| {
|
||||
if d > radius {
|
||||
1.0
|
||||
} else if d < -radius {
|
||||
0.0
|
||||
} else {
|
||||
0.5
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
let unknown = tri.data.par_iter().any(|&t| t > 0.25 && t < 0.75);
|
||||
let mut alpha = tri.clone();
|
||||
let mut colours: Option<Vec<[f32; 3]>> = None;
|
||||
if unknown {
|
||||
// Local foreground / background colour estimates: normalised blurs over known regions.
|
||||
let sigma = (radius.max(4.0) as f64).max(w.min(h) as f64 * 0.02);
|
||||
let known_f = tri.map(|t| if t > 0.75 { 1.0 } else { 0.0 });
|
||||
let known_b = tri.map(|t| if t < 0.25 { 1.0 } else { 0.0 });
|
||||
let straight: Vec<[f32; 3]> = b.img.data.par_iter().map(|&px| unpremul(px).0).collect();
|
||||
let est = |known: &Plane| -> Vec<[f32; 3]> {
|
||||
let wsum = gauss_plane(known, sigma, sigma);
|
||||
let chans: Vec<Plane> = (0..3)
|
||||
.map(|k| {
|
||||
let pl = Plane { w, h, data: straight.par_iter().zip(known.data.par_iter()).map(|(c, &m)| c[k] * m).collect() };
|
||||
gauss_plane(&pl, sigma, sigma)
|
||||
})
|
||||
.collect();
|
||||
(0..w * h).into_par_iter().map(|i| [0, 1, 2].map(|k| chans[k].data[i] / wsum.data[i].max(1e-6))).collect()
|
||||
};
|
||||
let fc = est(&known_f);
|
||||
let bc = est(&known_b);
|
||||
alpha.data.par_iter_mut().enumerate().for_each(|(i, a)| {
|
||||
if *a > 0.25 && *a < 0.75 {
|
||||
let c = straight[i];
|
||||
let d = [fc[i][0] - bc[i][0], fc[i][1] - bc[i][1], fc[i][2] - bc[i][2]];
|
||||
let dd = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
||||
*a = if dd < 1e-6 { 0.5 } else { (((c[0] - bc[i][0]) * d[0] + (c[1] - bc[i][1]) * d[1] + (c[2] - bc[i][2]) * d[2]) / dd).clamp(0.0, 1.0) };
|
||||
}
|
||||
});
|
||||
// Decontaminate edge colours: remove the background contribution.
|
||||
colours = Some(
|
||||
(0..w * h)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let a = alpha.data[i];
|
||||
let c = straight[i];
|
||||
if tri.data[i] > 0.25 && tri.data[i] < 0.75 && a > 0.02 {
|
||||
[0, 1, 2].map(|k| ((c[k] - (1.0 - a) * bc[i][k]) / a).clamp(0.0, 1.0))
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if thin.abs() > 0.01 {
|
||||
alpha = morph_frac(&alpha, thin.abs(), thin < 0.0);
|
||||
}
|
||||
if feather > 0.05 {
|
||||
alpha = gauss_plane(&alpha, feather * 0.5, feather * 0.5);
|
||||
}
|
||||
let src = b.img.clone();
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let mut m = alpha.data[i];
|
||||
if thr > 0.0 {
|
||||
m = if m < thr { 0.0 } else { m };
|
||||
}
|
||||
if invert {
|
||||
m = 1.0 - m;
|
||||
}
|
||||
let (c0, a) = unpremul(src.data[i]);
|
||||
let c = colours.as_ref().map(|v| v[i]).unwrap_or(c0);
|
||||
let keyed = premul(c, a * m);
|
||||
*px = lerp4(keyed, src.data[i], orig);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Unmult
|
||||
|
||||
/// Turns black into transparency: alpha becomes the brightest straight channel and colour is
|
||||
/// divided by it (premultiplied colour is unchanged).
|
||||
fn unmult(_: &EffectCtx, mut b: Buf) -> Buf {
|
||||
b.img.data.par_iter_mut().for_each(|px| {
|
||||
let (c, a) = unpremul(*px);
|
||||
let m = c[0].max(c[1]).max(c[2]).clamp(0.0, 1.0);
|
||||
if m <= 1e-6 {
|
||||
*px = [0.0; 4];
|
||||
return;
|
||||
}
|
||||
*px = premul([c[0] / m, c[1] / m, c[2] / m], a * m);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CC Simple Wire Removal
|
||||
|
||||
fn wire_removal(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pa = ctx.params.v2("pointA");
|
||||
let pb = ctx.params.v2("pointB");
|
||||
let style = ctx.params.e("removalStyle");
|
||||
let half = (ctx.params.f("thickness") * b.scale * 0.5).max(0.0);
|
||||
if half <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let slope = (ctx.params.f("slope") / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let mirror = (ctx.params.f("mirrorBlend") / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let (ax, ay) = b.to_px(pa);
|
||||
let (bx, by) = b.to_px(pb);
|
||||
let (dx, dy) = (bx - ax, by - ay);
|
||||
let len = (dx * dx + dy * dy).sqrt();
|
||||
if len < 1e-6 {
|
||||
return b;
|
||||
}
|
||||
let (tx, ty) = (dx / len, dy / len);
|
||||
let (nx, ny) = (-ty, tx);
|
||||
let src = b.img.clone();
|
||||
let soft_w = half * slope as f64;
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (qx, qy) = (x as f64 + 0.5 - ax, y as f64 + 0.5 - ay);
|
||||
let d = qx * nx + qy * ny;
|
||||
let ad = d.abs();
|
||||
if ad > half + soft_w {
|
||||
continue;
|
||||
}
|
||||
// Positions just outside the wire on both sides.
|
||||
let base = (x as f64 + 0.5 - d * nx, y as f64 + 0.5 - d * ny);
|
||||
let edge = half + 1.0;
|
||||
let pos = |s: f64| src.sample_bilinear_clamped(base.0 + nx * s, base.1 + ny * s);
|
||||
let repl = match style {
|
||||
0 => {
|
||||
let t = ((d + edge) / (2.0 * edge)) as f32;
|
||||
lerp4(pos(-edge), pos(edge), t.clamp(0.0, 1.0))
|
||||
}
|
||||
// Displace: shift the image across the wire from the nearer side.
|
||||
2 | 1 => {
|
||||
let s = if d >= 0.0 { d + 2.0 * (half - ad) + 1.0 } else { d - 2.0 * (half - ad) - 1.0 };
|
||||
let sh = pos(s);
|
||||
if mirror > 0.0 { lerp4(sh, pos(-s), mirror * 0.5) } else { sh }
|
||||
}
|
||||
_ => {
|
||||
// Displace Horizontal: sample left/right of the wire along x.
|
||||
let sx = if nx.abs() > 1e-6 { (half - ad + 1.0) / nx.abs() } else { 0.0 };
|
||||
let dir = if d * nx >= 0.0 { 1.0 } else { -1.0 };
|
||||
let sh = src.sample_bilinear_clamped(x as f64 + 0.5 + dir * sx, y as f64 + 0.5);
|
||||
let mi = src.sample_bilinear_clamped(x as f64 + 0.5 - dir * sx, y as f64 + 0.5);
|
||||
if mirror > 0.0 { lerp4(sh, mi, mirror * 0.5) } else { sh }
|
||||
}
|
||||
};
|
||||
let k = if ad <= half { 1.0 } else { 1.0 - smoothstep(half as f32, (half + soft_w) as f32, ad as f32) };
|
||||
*px = lerp4(*px, repl, k);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![
|
||||
spec(
|
||||
"ec.key.differencematte",
|
||||
"Difference Matte",
|
||||
vec![
|
||||
p("view", "View", Value::Enum(0), popup(&["Final Output", "Source Only", "Matte Only"])),
|
||||
p("differenceLayer", "Difference Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("ifLayerSizesDiffer", "If Layer Sizes Differ", Value::Enum(0), popup(&["Center", "Stretch to Fit"])),
|
||||
p("matchingTolerance", "Matching Tolerance", num(15.0), pct()),
|
||||
p("matchingSoftness", "Matching Softness", num(0.0), pct()),
|
||||
p("blurBeforeDifference", "Blur Before Difference", num(0.0), slider(0.0, 1000.0, 0.0, 20.0, 1)),
|
||||
],
|
||||
difference_matte,
|
||||
),
|
||||
spec(
|
||||
"ec.key.innerouter",
|
||||
"Inner/Outer Key",
|
||||
vec![
|
||||
p("foreground", "Foreground (Inside)", Value::Enum(0), mask_options()),
|
||||
p("additionalForeground", "Additional Foreground", Value::Enum(0), mask_options()),
|
||||
p("background", "Background (Outside)", Value::Enum(0), mask_options()),
|
||||
p("additionalBackground", "Additional Background", Value::Enum(0), mask_options()),
|
||||
p("singleMaskHighlightRadius", "Single Mask Highlight Radius", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
p("edgeThin", "Edge Thin", num(0.0), slider(-10.0, 10.0, -10.0, 10.0, 1)),
|
||||
p("edgeFeather", "Edge Feather", num(0.0), slider(0.0, 100.0, 0.0, 50.0, 1)),
|
||||
p("edgeThreshold", "Edge Threshold", num(0.0), pct()),
|
||||
p("invertExtraction", "Invert Extraction", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("blendWithOriginal", "Blend with Original", num(0.0), pct()),
|
||||
],
|
||||
inner_outer_key,
|
||||
),
|
||||
spec("ec.key.unmult", "Unmult", vec![], unmult),
|
||||
spec(
|
||||
"ec.key.ccsimplewireremoval",
|
||||
"CC Simple Wire Removal",
|
||||
vec![
|
||||
p("pointA", "Point A", Value::Vec2([0.25, 0.25]), ParamUi::Point),
|
||||
p("pointB", "Point B", Value::Vec2([0.75, 0.75]), ParamUi::Point),
|
||||
p("removalStyle", "Removal Style", Value::Enum(2), popup(&["Fade", "Frame Offset", "Displace", "Displace Horizontal"])),
|
||||
p("thickness", "Thickness", num(5.0), slider(0.0, 100.0, 0.0, 30.0, 1)),
|
||||
p("slope", "Slope", num(0.0), pct()),
|
||||
p("mirrorBlend", "Mirror Blend", num(0.0), pct()),
|
||||
p("frameOffset", "Frame Offset", num(0.0), slider(-100.0, 100.0, -10.0, 10.0, 0)),
|
||||
],
|
||||
wire_removal,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::channel2::tests::{FakeHost, sample};
|
||||
use crate::{EffectEnv, MaskShape, run_fx};
|
||||
use effectcraft_raster::Image;
|
||||
|
||||
#[test]
|
||||
fn difference_matte_self_is_transparent_and_other_keeps() {
|
||||
let img = sample();
|
||||
let out = run_fx("ec.key.differencematte", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!(out.img.data.iter().all(|p| p[3] == 0.0));
|
||||
let host = FakeHost(Image::filled(8, 6, [0.0, 0.0, 0.4, 1.0]));
|
||||
let env = EffectEnv { host: Some(&host), ..Default::default() };
|
||||
let out = run_fx("ec.key.differencematte", &[("differenceLayer", Value::Layer(Some(7)))], img.clone(), 0.0, env);
|
||||
assert_eq!(out.img.get(5, 5), img.get(5, 5));
|
||||
assert_eq!(out.img.get(0, 0)[3], 0.0, "matching pixel keyed out");
|
||||
let again = run_fx("ec.key.differencematte", &[("differenceLayer", Value::Layer(Some(7)))], img.clone(), 0.0, env);
|
||||
assert_eq!(out.img.data, again.img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inner_outer_key_inside_mask() {
|
||||
let img = Image::filled(20, 20, [0.8, 0.2, 0.2, 1.0]);
|
||||
let masks = vec![MaskShape { name: "Mask 1".into(), points: vec![[5.0, 5.0], [15.0, 5.0], [15.0, 15.0], [5.0, 15.0]], closed: true, inverted: false }];
|
||||
let env = EffectEnv { masks: &masks, ..Default::default() };
|
||||
let out = run_fx("ec.key.innerouter", &[("foreground", Value::Enum(1))], img.clone(), 0.0, env);
|
||||
assert!((out.img.get(10, 10)[3] - 1.0).abs() < 1e-6);
|
||||
assert_eq!(out.img.get(1, 1)[3], 0.0);
|
||||
// Two masks: unknown band estimated from colour.
|
||||
let mut img2 = Image::filled(20, 20, [0.0, 0.0, 1.0, 1.0]);
|
||||
for y in 0..20 {
|
||||
for x in 7..13 {
|
||||
img2.set(x, y, [1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
}
|
||||
let masks2 = vec![
|
||||
MaskShape { name: "in".into(), points: vec![[8.0, 0.0], [12.0, 0.0], [12.0, 20.0], [8.0, 20.0]], closed: true, inverted: false },
|
||||
MaskShape { name: "out".into(), points: vec![[4.0, 0.0], [16.0, 0.0], [16.0, 20.0], [4.0, 20.0]], closed: true, inverted: false },
|
||||
];
|
||||
let env2 = EffectEnv { masks: &masks2, ..Default::default() };
|
||||
let o2 = run_fx("ec.key.innerouter", &[("foreground", Value::Enum(1)), ("background", Value::Enum(2))], img2.clone(), 0.0, env2);
|
||||
assert!(o2.img.get(7, 10)[3] > 0.8, "{:?}", o2.img.get(7, 10));
|
||||
assert!(o2.img.get(5, 10)[3] < 0.2, "{:?}", o2.img.get(5, 10));
|
||||
assert_eq!(o2.img.get(1, 10)[3], 0.0);
|
||||
let o3 = run_fx("ec.key.innerouter", &[("foreground", Value::Enum(1)), ("background", Value::Enum(2))], img2, 0.0, env2);
|
||||
assert_eq!(o2.img.data, o3.img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmult_black_becomes_transparent() {
|
||||
let mut img = Image::filled(4, 4, [0.0, 0.0, 0.0, 1.0]);
|
||||
img.set(1, 1, [0.5, 0.25, 0.0, 1.0]);
|
||||
let out = run_fx("ec.key.unmult", &[], img, 0.0, EffectEnv::default());
|
||||
assert_eq!(out.img.get(0, 0), [0.0; 4]);
|
||||
let p = out.img.get(1, 1);
|
||||
assert!((p[3] - 0.5).abs() < 1e-6 && (p[0] - 0.5).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_removal_hides_a_wire() {
|
||||
let mut img = Image::filled(20, 20, [0.5, 0.5, 0.5, 1.0]);
|
||||
for y in 0..20 {
|
||||
img.set(10, y, [0.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
for style in 0..4u32 {
|
||||
let out = run_fx(
|
||||
"ec.key.ccsimplewireremoval",
|
||||
&[("pointA", Value::Vec2([10.5, 0.0])), ("pointB", Value::Vec2([10.5, 20.0])), ("removalStyle", Value::Enum(style)), ("thickness", num(3.0))],
|
||||
img.clone(),
|
||||
0.0,
|
||||
EffectEnv::default(),
|
||||
);
|
||||
assert!((out.img.get(10, 10)[0] - 0.5).abs() < 0.05, "style {style}: {:?}", out.img.get(10, 10));
|
||||
assert_eq!(out.img.get(2, 10), img.get(2, 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
+168
-1
@@ -8,22 +8,36 @@
|
||||
|
||||
mod blur2;
|
||||
mod channel;
|
||||
mod channel2;
|
||||
mod color2;
|
||||
mod color3;
|
||||
mod color_fx;
|
||||
mod controls;
|
||||
mod distort;
|
||||
mod distort2;
|
||||
mod distort3;
|
||||
mod generate;
|
||||
mod generate2;
|
||||
mod generate3;
|
||||
mod keying;
|
||||
mod keying2;
|
||||
mod matte;
|
||||
mod misc;
|
||||
mod noise;
|
||||
mod noise2;
|
||||
mod obsolete;
|
||||
mod perspective;
|
||||
mod perspective2;
|
||||
mod sim;
|
||||
mod sim2;
|
||||
mod stylize2;
|
||||
mod stylize3;
|
||||
mod textfx;
|
||||
mod transition;
|
||||
mod transition2;
|
||||
pub mod util;
|
||||
mod utility;
|
||||
mod utility2;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
@@ -122,6 +136,45 @@ impl Buf {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer mask at the current time, flattened to a polyline in layer coordinates.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MaskShape {
|
||||
pub name: String,
|
||||
pub points: Vec<[f64; 2]>,
|
||||
pub closed: bool,
|
||||
pub inverted: bool,
|
||||
}
|
||||
|
||||
/// Pixels of another layer referenced by a layer parameter: its buffer (layer space, see
|
||||
/// [`Buf`]) and its source size in layer pixels.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LayerPixels {
|
||||
pub buf: Buf,
|
||||
pub size: [f64; 2],
|
||||
}
|
||||
|
||||
/// Services the renderer offers effects that look beyond their own pixels.
|
||||
pub trait EffectHost: Sync {
|
||||
/// Layer `id` of the same composition at the current comp time. `masks_and_effects`
|
||||
/// selects "Effects & Masks" over "Source". `None` for missing/self/recursive references.
|
||||
fn layer(&self, id: u64, masks_and_effects: bool) -> Option<LayerPixels>;
|
||||
/// `frames` stereo sample frames (interleaved L R …) of layer `id`'s audio starting at comp
|
||||
/// time `start` seconds, at `rate` Hz. `None` when the layer has no audio.
|
||||
fn audio(&self, id: u64, start: f64, frames: usize, rate: u32) -> Option<Vec<f32>>;
|
||||
}
|
||||
|
||||
/// Extra context the renderer may supply (all optional; `Default` is "nothing known").
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct EffectEnv<'a> {
|
||||
/// The layer's masks (enabled ones, top to bottom).
|
||||
pub masks: &'a [MaskShape],
|
||||
pub host: Option<&'a dyn EffectHost>,
|
||||
/// Composition time in seconds.
|
||||
pub comp_time: f64,
|
||||
/// Composition frame rate (0 when unknown).
|
||||
pub frame_rate: f64,
|
||||
}
|
||||
|
||||
/// What an effect gets to render with.
|
||||
pub struct EffectCtx<'a> {
|
||||
pub params: &'a Params,
|
||||
@@ -133,6 +186,20 @@ pub struct EffectCtx<'a> {
|
||||
pub seed: u32,
|
||||
/// Rendering for an adjustment layer (operating on the comp below).
|
||||
pub adjustment: bool,
|
||||
/// Masks, other layers, audio, comp timing.
|
||||
pub env: EffectEnv<'a>,
|
||||
}
|
||||
|
||||
impl EffectCtx<'_> {
|
||||
/// The layer chosen in layer parameter `id`, via the host.
|
||||
pub fn layer_param(&self, id: &str, masks_and_effects: bool) -> Option<LayerPixels> {
|
||||
let lid = self.params.get(id)?.as_layer()?;
|
||||
self.env.host?.layer(lid, masks_and_effects)
|
||||
}
|
||||
/// Frame rate for frame-based maths (comp rate, else 30).
|
||||
pub fn fps(&self) -> f64 {
|
||||
if self.env.frame_rate > 0.0 { self.env.frame_rate } else { 30.0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub type RenderFn = fn(&EffectCtx, Buf) -> Buf;
|
||||
@@ -187,6 +254,20 @@ pub fn registry() -> &'static [EffectSpec] {
|
||||
v.extend(perspective::specs());
|
||||
v.extend(transition::specs());
|
||||
v.extend(utility::specs());
|
||||
v.extend(sim::specs());
|
||||
v.extend(sim2::specs());
|
||||
v.extend(distort3::specs());
|
||||
v.extend(perspective2::specs());
|
||||
v.extend(utility2::specs());
|
||||
v.extend(generate3::specs());
|
||||
v.extend(textfx::specs());
|
||||
v.extend(stylize3::specs());
|
||||
v.extend(transition2::specs());
|
||||
v.extend(channel2::specs());
|
||||
v.extend(keying2::specs());
|
||||
v.extend(noise2::specs());
|
||||
v.extend(color3::specs());
|
||||
v.extend(obsolete::specs());
|
||||
v.sort_by(|a, b| a.category.cmp(b.category).then(a.name.cmp(b.name)));
|
||||
v
|
||||
})
|
||||
@@ -222,15 +303,69 @@ pub fn instantiate(spec: &EffectSpec, ids: &mut Ids, instance_name: &str, layer_
|
||||
g
|
||||
}
|
||||
|
||||
/// Effects whose output depends on [`EffectCtx::time`] directly (not only through animated
|
||||
/// parameters). The renderer's layer cache folds the layer time into the key for these.
|
||||
/// The `time_dependence_is_declared` test checks the list against every registered effect.
|
||||
pub const TIME_DEPENDENT: &[&str] = &[
|
||||
"ec.distort.wavewarp",
|
||||
"ec.distort.ripple",
|
||||
"ec.generate.radiowaves",
|
||||
"ec.stylize.scatter",
|
||||
"ec.stylize.strobe",
|
||||
"ec.noise.noise",
|
||||
"ec.noise.addgrain",
|
||||
"ec.noise.noisealpha",
|
||||
"ec.noise.noisehlsauto",
|
||||
"ec.obsolete.lightning",
|
||||
"ec.text.timecode",
|
||||
"ec.text.numbers",
|
||||
];
|
||||
|
||||
/// See [`TIME_DEPENDENT`].
|
||||
pub fn is_time_dependent(id: &str) -> bool {
|
||||
// Simulations replay from layer time 0, so every frame differs even when the defaults
|
||||
// happen to look static at the test's two sample times.
|
||||
id.starts_with("ec.sim.") || TIME_DEPENDENT.contains(&id)
|
||||
}
|
||||
|
||||
/// Run an effect on a buffer.
|
||||
pub fn apply(spec: &EffectSpec, ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
(spec.render)(ctx, buf)
|
||||
}
|
||||
|
||||
/// Test helper: run effect `id` on `img` (scale 1, layer size = image size) with its defaults
|
||||
/// overridden by `vals`, at layer time `time`, with an optional environment.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn run_fx(id: &str, vals: &[(&str, Value)], img: Image, time: f64, env: EffectEnv) -> Buf {
|
||||
let s = find(id).unwrap_or_else(|| panic!("no effect {id}"));
|
||||
let mut params = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
for (k, v) in vals {
|
||||
assert!(params.values.contains_key(*k), "{id}: unknown param {k}");
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env };
|
||||
apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_fx_passthrough() {
|
||||
let img = Image::filled(4, 3, [0.5, 0.25, 0.125, 1.0]);
|
||||
let out = run_fx("ec.control.slider", &[("slider", num(3.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(out.img.data, img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn dump_registry() {
|
||||
for s in registry() {
|
||||
println!("{} | {} | {}", s.category, s.name, s.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_is_consistent() {
|
||||
let r = registry();
|
||||
@@ -259,10 +394,42 @@ mod tests {
|
||||
}
|
||||
for s in registry() {
|
||||
let params = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [48.0, 32.0], seed: 1, adjustment: false };
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [48.0, 32.0], seed: 1, adjustment: false, env: Default::default() };
|
||||
let out = apply(s, &ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 });
|
||||
assert!(!out.img.is_empty(), "{}", s.id);
|
||||
assert!(out.img.data.iter().all(|p| p[3].is_finite() && p[3] >= -1e-4 && p[3] <= 1.0001), "{} alpha out of range", s.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Effects that read the clock must be listed in `TIME_DEPENDENT`, or the layer cache would
|
||||
/// serve stale pixels. Render every effect at two times with default parameters (plus
|
||||
/// "random…" switches turned on) and require identical output from unlisted ones.
|
||||
#[test]
|
||||
fn time_dependence_is_declared() {
|
||||
let mut img = Image::new(40, 30);
|
||||
for y in 0..30 {
|
||||
for x in 0..40 {
|
||||
let a = if (6..34).contains(&x) && (5..25).contains(&y) { 1.0 } else { 0.3 };
|
||||
img.set(x, y, [((x * 7 + y * 3) % 11) as f32 / 11.0 * a, y as f32 / 30.0 * a, 0.4 * a, a]);
|
||||
}
|
||||
}
|
||||
let mut missing = vec![];
|
||||
for s in registry() {
|
||||
let mut params = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
for (k, v) in params.values.iter_mut() {
|
||||
if k.to_lowercase().contains("random") && matches!(v, Value::Bool(_)) {
|
||||
*v = Value::Bool(true);
|
||||
}
|
||||
}
|
||||
let run = |t: f64| {
|
||||
let ctx = EffectCtx { params: ¶ms, time: t, layer_size: [40.0, 30.0], seed: 7, adjustment: false, env: Default::default() };
|
||||
apply(s, &ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
};
|
||||
let (a, b) = (run(0.0), run(1.37));
|
||||
if a != b && !is_time_dependent(s.id) {
|
||||
missing.push(s.id);
|
||||
}
|
||||
}
|
||||
assert!(missing.is_empty(), "these depend on time but are not in TIME_DEPENDENT: {missing:?}");
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,8 @@ mod tests {
|
||||
for (k, v) in over {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: true };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: true, env: Default::default() };
|
||||
apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
|
||||
@@ -531,7 +531,7 @@ mod tests {
|
||||
for (k, v) in vals {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: [img.width as f64, img.height as f64], seed: 3, adjustment: false };
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: [img.width as f64, img.height as f64], seed: 3, adjustment: false, env: Default::default() };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
//! Noise & Grain effects, batch 2: Match Grain (grain statistics measured from another layer
|
||||
//! and synthesised onto this one), Median (Legacy) and Curl Noise (divergence-free flow
|
||||
//! distortion from the curl of a fractal noise potential).
|
||||
|
||||
use effectcraft_color::luminance;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::generate::value_noise;
|
||||
use crate::noise::{fbm, median_image};
|
||||
use crate::util::{Plane, gauss_plane, layer_or_self, premul, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Noise & Grain", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Match Grain
|
||||
|
||||
/// Grain statistics of an image: per-channel standard deviation of the high-pass residual
|
||||
/// (over opaque pixels) and a grain size from the lag-1 autocorrelation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct GrainStats {
|
||||
pub std: [f32; 3],
|
||||
pub size: f32,
|
||||
}
|
||||
|
||||
pub(crate) fn grain_stats(img: &Image) -> GrainStats {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
if w < 3 || h < 3 {
|
||||
return GrainStats::default();
|
||||
}
|
||||
let straight: Vec<([f32; 3], f32)> = img.data.par_iter().map(|&p| unpremul(p)).collect();
|
||||
let mut std = [0.0f32; 3];
|
||||
let mut rho_num = 0.0f64;
|
||||
let mut rho_den = 0.0f64;
|
||||
for (k, s) in std.iter_mut().enumerate() {
|
||||
let pl = Plane { w, h, data: straight.iter().map(|(c, _)| c[k]).collect() };
|
||||
let low = gauss_plane(&pl, 1.5, 1.5);
|
||||
let hp: Vec<f32> = pl.data.iter().zip(low.data.iter()).map(|(a, b)| a - b).collect();
|
||||
let (mut sum, mut sq, mut n) = (0.0f64, 0.0f64, 0.0f64);
|
||||
for (i, v) in hp.iter().enumerate() {
|
||||
if straight[i].1 > 0.5 {
|
||||
sum += *v as f64;
|
||||
sq += (*v as f64) * (*v as f64);
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
if n > 1.0 {
|
||||
let mean = sum / n;
|
||||
*s = ((sq / n - mean * mean).max(0.0)).sqrt() as f32;
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in 0..w - 1 {
|
||||
let i = y * w + x;
|
||||
if straight[i].1 > 0.5 && straight[i + 1].1 > 0.5 {
|
||||
rho_num += (hp[i] * hp[i + 1]) as f64;
|
||||
rho_den += (hp[i] * hp[i]) as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let rho = if rho_den > 1e-12 { (rho_num / rho_den).clamp(0.0, 0.95) } else { 0.0 };
|
||||
GrainStats { std, size: (1.0 / (1.0 - rho as f32)).clamp(0.5, 20.0) * 0.6 }
|
||||
}
|
||||
|
||||
fn match_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
if ctx.params.get("noiseSourceLayer").and_then(Value::as_layer).is_none() {
|
||||
return b;
|
||||
}
|
||||
let view = ctx.params.e("viewingMode");
|
||||
let source = layer_or_self(ctx, &b, "noiseSourceLayer", false, false);
|
||||
let src_stats = grain_stats(&source);
|
||||
let comp = (ctx.params.f("compensateForExistingNoise") / 100.0) as f32;
|
||||
let own = if comp > 0.0 { grain_stats(&b.img) } else { GrainStats::default() };
|
||||
let intensity = ctx.params.f("intensity") as f32;
|
||||
let chan = [ctx.params.f("redIntensity") as f32, ctx.params.f("greenIntensity") as f32, ctx.params.f("blueIntensity") as f32];
|
||||
let amp: [f32; 3] = [0, 1, 2].map(|k| {
|
||||
let s = src_stats.std[k];
|
||||
let e = own.std[k] * comp;
|
||||
(s * s - e * e).max(0.0).sqrt() * intensity * chan[k]
|
||||
});
|
||||
let size = (src_stats.size.max(0.5) * ctx.params.f("size") as f32 * b.scale as f32).max(0.05);
|
||||
let aspect = ctx.params.f("aspectRatio").max(0.05) as f32;
|
||||
let soft = ctx.params.f("softness") * b.scale;
|
||||
let mono = ctx.params.b("monochromatic");
|
||||
let sat = ctx.params.f("saturation") as f32;
|
||||
let blend_mode = ctx.params.e("blendingMode");
|
||||
let (ws, wm, wh) = (ctx.params.f("shadows") as f32, ctx.params.f("midtones") as f32, ctx.params.f("highlights") as f32);
|
||||
let seed = (ctx.params.f("randomSeed") as i64 as u32) ^ ctx.seed.wrapping_mul(0x9e37);
|
||||
let ft = ctx.time * 24.0 * ctx.params.f("animationSpeed");
|
||||
let frame = if ctx.params.b("animateSmoothly") { ft as f32 } else { ft.floor() as f32 };
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let nch = if mono { 1 } else { 3 };
|
||||
let mut planes: Vec<Plane> = (0..nch)
|
||||
.map(|k| {
|
||||
let mut pl = Plane::new(w, h);
|
||||
pl.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
*v = value_noise(x as f32 / size, y as f32 / (size * aspect), frame, seed.wrapping_add(k as u32 * 131)) - 0.5;
|
||||
}
|
||||
});
|
||||
pl
|
||||
})
|
||||
.collect();
|
||||
if soft > 0.05 {
|
||||
planes = planes.iter().map(|pl| gauss_plane(pl, soft, soft * aspect as f64)).collect();
|
||||
}
|
||||
// Normalise each synthetic plane to unit standard deviation so the measured stats transfer.
|
||||
for pl in planes.iter_mut() {
|
||||
let n = pl.data.len().max(1) as f64;
|
||||
let mean = pl.data.iter().map(|&v| v as f64).sum::<f64>() / n;
|
||||
let var = pl.data.iter().map(|&v| (v as f64 - mean).powi(2)).sum::<f64>() / n;
|
||||
let k = if var > 1e-12 { 1.0 / var.sqrt() } else { 0.0 };
|
||||
*pl = pl.map(|v| ((v as f64 - mean) * k) as f32);
|
||||
}
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(*px);
|
||||
let mut g = if mono { [planes[0].data[i]; 3] } else { [planes[0].data[i], planes[1].data[i], planes[2].data[i]] };
|
||||
let gm = (g[0] + g[1] + g[2]) / 3.0;
|
||||
g = g.map(|v| gm + (v - gm) * sat);
|
||||
let l = luminance(c[0], c[1], c[2]).clamp(0.0, 1.0);
|
||||
let s = 1.0 - smoothstep(0.0, 0.5, l);
|
||||
let hi = smoothstep(0.5, 1.0, l);
|
||||
let weight = ws * s + wm * (1.0 - s - hi) + wh * hi;
|
||||
match view {
|
||||
1 => {
|
||||
let o = [0, 1, 2].map(|k| (0.5 + g[k] * amp[k]).clamp(0.0, 1.0));
|
||||
*px = [o[0], o[1], o[2], 1.0];
|
||||
}
|
||||
2 => *px = [weight.clamp(0.0, 1.0), weight.clamp(0.0, 1.0), weight.clamp(0.0, 1.0), 1.0],
|
||||
_ => {
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let o = [0, 1, 2].map(|k| {
|
||||
let n = g[k] * amp[k] * weight;
|
||||
let v = match blend_mode {
|
||||
1 => c[k] * (1.0 + n * 2.0),
|
||||
2 => 1.0 - (1.0 - c[k]) * (1.0 - n * 2.0),
|
||||
_ => c[k] + n,
|
||||
};
|
||||
v.max(0.0)
|
||||
});
|
||||
*px = premul(o, a);
|
||||
}
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Median (Legacy)
|
||||
|
||||
fn median_legacy(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let r = (ctx.params.f("radius") * b.scale).round().max(0.0) as usize;
|
||||
if r == 0 {
|
||||
return b;
|
||||
}
|
||||
if ctx.params.b("operateOnAlphaChannel") {
|
||||
b.img = median_image(&b.img, r);
|
||||
return b;
|
||||
}
|
||||
// Colour only: median of straight colour, alpha kept.
|
||||
let mut straight = b.img.clone();
|
||||
straight.data.par_iter_mut().for_each(|px| {
|
||||
let (c, _) = unpremul(*px);
|
||||
*px = [c[0], c[1], c[2], 1.0];
|
||||
});
|
||||
let m = median_image(&straight, r);
|
||||
b.img.data.par_iter_mut().zip(m.data.par_iter()).for_each(|(px, q)| {
|
||||
*px = premul([q[0], q[1], q[2]], px[3]);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Curl Noise
|
||||
|
||||
fn curl_noise(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let amount = ctx.params.f("displacementAmount") * b.scale;
|
||||
let view = ctx.params.e("view");
|
||||
if amount.abs() < 1e-6 && view == 0 {
|
||||
return b;
|
||||
}
|
||||
let scale = (ctx.params.f("scale").max(1.0) * b.scale) as f32;
|
||||
let complexity = ctx.params.f("complexity") as f32;
|
||||
let rot = ctx.params.f("rotation").to_radians() as f32;
|
||||
let off = ctx.params.v2("offset");
|
||||
let (ox, oy) = ((off[0] * b.scale + b.offset[0]) as f32, (off[1] * b.scale + b.offset[1]) as f32);
|
||||
let evo = (ctx.params.f("evolution") / 360.0) as f32;
|
||||
let seed = ctx.params.f("randomSeed") as i64 as u32 ^ 0x51_7cc1;
|
||||
let steps = ctx.params.f("steps").clamp(1.0, 16.0) as usize;
|
||||
let edge_wrap = ctx.params.e("edgeBehavior") == 1;
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let (cr, sr) = (rot.cos(), rot.sin());
|
||||
// Potential field on the pixel grid.
|
||||
let mut pot = Plane::new(w, h);
|
||||
pot.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
let (dx, dy) = (x as f32 + 0.5 - ox, y as f32 + 0.5 - oy);
|
||||
let u = (dx * cr + dy * sr) / scale;
|
||||
let vv = (-dx * sr + dy * cr) / scale;
|
||||
*v = fbm(u, vv, evo * 4.0, seed, complexity);
|
||||
}
|
||||
});
|
||||
// Curl: v = (dψ/dy, -dψ/dx), normalised so the typical speed is ~1 px per unit amount.
|
||||
let mut vx = Plane::new(w, h);
|
||||
let mut vy = Plane::new(w, h);
|
||||
vx.data.par_chunks_mut(w.max(1)).zip(vy.data.par_chunks_mut(w.max(1))).enumerate().for_each(|(y, (rx, ry))| {
|
||||
for x in 0..w {
|
||||
let (xi, yi) = (x as i64, y as i64);
|
||||
let gx = (pot.get_clamped(xi + 1, yi) - pot.get_clamped(xi - 1, yi)) * 0.5;
|
||||
let gy = (pot.get_clamped(xi, yi + 1) - pot.get_clamped(xi, yi - 1)) * 0.5;
|
||||
rx[x] = gy * scale;
|
||||
ry[x] = -gx * scale;
|
||||
}
|
||||
});
|
||||
if view == 1 {
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (a, c) = (vx.data[i], vy.data[i]);
|
||||
*px = [(0.5 + a * 0.5).clamp(0.0, 1.0), (0.5 + c * 0.5).clamp(0.0, 1.0), 0.5, 1.0];
|
||||
});
|
||||
return b;
|
||||
}
|
||||
let src = b.img.clone();
|
||||
let dt = amount as f32 / steps as f32;
|
||||
let (wf, hf) = (w as f64, h as f64);
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (mut sx, mut sy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
for _ in 0..steps {
|
||||
// Trace the streamline backwards (semi-Lagrangian advection).
|
||||
let (u, v) = (vx.sample(sx, sy), vy.sample(sx, sy));
|
||||
sx -= (u * dt) as f64;
|
||||
sy -= (v * dt) as f64;
|
||||
}
|
||||
*px = if edge_wrap { src.sample_bilinear_clamped(sx.rem_euclid(wf), sy.rem_euclid(hf)) } else { src.sample_bilinear_clamped(sx, sy) };
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let mult = || slider(0.0, 10.0, 0.0, 2.0, 2);
|
||||
vec![
|
||||
spec(
|
||||
"ec.noise.matchgrain",
|
||||
"Match Grain",
|
||||
vec![
|
||||
p("viewingMode", "Viewing Mode", Value::Enum(0), popup(&["Final Output", "Noise Samples", "Blending Matte"])),
|
||||
p("noiseSourceLayer", "Noise Source Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("compensateForExistingNoise", "Compensate for Existing Noise", num(0.0), pct()),
|
||||
p("intensity", "Intensity", num(1.0), slider(0.0, 100.0, 0.0, 10.0, 2)),
|
||||
p("size", "Size", num(1.0), slider(0.05, 100.0, 0.1, 10.0, 2)),
|
||||
p("softness", "Softness", num(0.0), slider(0.0, 100.0, 0.0, 5.0, 2)),
|
||||
p("aspectRatio", "Aspect Ratio", num(1.0), slider(0.05, 20.0, 0.25, 4.0, 2)),
|
||||
p("redIntensity", "Red Intensity", num(1.0), mult()),
|
||||
p("greenIntensity", "Green Intensity", num(1.0), mult()),
|
||||
p("blueIntensity", "Blue Intensity", num(1.0), mult()),
|
||||
p("monochromatic", "Monochromatic", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("saturation", "Saturation", num(1.0), mult()),
|
||||
p("blendingMode", "Blending Mode", Value::Enum(0), popup(&["Normal", "Multiply", "Screen"])),
|
||||
p("shadows", "Shadows", num(1.0), mult()),
|
||||
p("midtones", "Midtones", num(1.0), mult()),
|
||||
p("highlights", "Highlights", num(1.0), mult()),
|
||||
p("animationSpeed", "Animation Speed", num(1.0), slider(0.0, 100.0, 0.0, 5.0, 2)),
|
||||
p("animateSmoothly", "Animate Smoothly", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("randomSeed", "Random Seed", num(0.0), slider(0.0, 100000.0, 0.0, 1000.0, 0)),
|
||||
],
|
||||
match_grain,
|
||||
),
|
||||
spec(
|
||||
"ec.noise.medianlegacy",
|
||||
"Median (Legacy)",
|
||||
vec![
|
||||
p("radius", "Radius", num(1.0), slider(0.0, 255.0, 0.0, 20.0, 0)),
|
||||
p("operateOnAlphaChannel", "Operate On Alpha Channel", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
median_legacy,
|
||||
),
|
||||
spec(
|
||||
"ec.noise.curlnoise",
|
||||
"Curl Noise",
|
||||
vec![
|
||||
p("view", "View", Value::Enum(0), popup(&["Final Output", "Flow Field"])),
|
||||
p("displacementAmount", "Displacement Amount", num(20.0), slider(-1000.0, 1000.0, -100.0, 100.0, 1)),
|
||||
p("scale", "Scale", num(100.0), slider(1.0, 10000.0, 10.0, 600.0, 1)),
|
||||
p("rotation", "Rotation", num(0.0), ParamUi::Angle),
|
||||
p("offset", "Offset Turbulence", Value::Vec2([0.5, 0.5]), ParamUi::Point),
|
||||
p("complexity", "Complexity", num(3.0), slider(1.0, 20.0, 1.0, 10.0, 1)),
|
||||
p("evolution", "Evolution", num(0.0), ParamUi::Angle),
|
||||
p("steps", "Flow Steps", num(4.0), slider(1.0, 16.0, 1.0, 16.0, 0)),
|
||||
p("edgeBehavior", "Edge Behavior", Value::Enum(0), popup(&["Clamp", "Wrap"])),
|
||||
p("randomSeed", "Random Seed", num(0.0), slider(0.0, 100000.0, 0.0, 1000.0, 0)),
|
||||
],
|
||||
curl_noise,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::channel2::tests::FakeHost;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
|
||||
fn noisy(w: u32, h: u32, amp: f32, seed: u32) -> Image {
|
||||
let mut img = Image::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let n = (crate::util::hash1(x, y, seed) - 0.5) * 2.0 * amp;
|
||||
img.set(x, y, [0.5 + n, 0.5 + n, 0.5 + n, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_grain_transfers_grain_strength() {
|
||||
let flat = Image::filled(48, 48, [0.5, 0.5, 0.5, 1.0]);
|
||||
let none = run_fx("ec.noise.matchgrain", &[], flat.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(none.img.data, flat.data);
|
||||
let host = FakeHost(noisy(48, 48, 0.1, 3));
|
||||
let env = EffectEnv { host: Some(&host), ..Default::default() };
|
||||
let out = run_fx("ec.noise.matchgrain", &[("noiseSourceLayer", Value::Layer(Some(7)))], flat.clone(), 0.5, env);
|
||||
let target = grain_stats(&host.0).std[0];
|
||||
let got = grain_stats(&out.img).std[0];
|
||||
assert!(got > target * 0.4 && got < target * 2.5, "target {target} got {got}");
|
||||
let again = run_fx("ec.noise.matchgrain", &[("noiseSourceLayer", Value::Layer(Some(7)))], flat, 0.5, env);
|
||||
assert_eq!(out.img.data, again.img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn median_legacy_radius_zero_identity_and_removes_speck() {
|
||||
let mut img = Image::filled(9, 9, [0.2, 0.2, 0.2, 1.0]);
|
||||
img.set(4, 4, [1.0, 1.0, 1.0, 1.0]);
|
||||
let id = run_fx("ec.noise.medianlegacy", &[("radius", num(0.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(id.img.data, img.data);
|
||||
let out = run_fx("ec.noise.medianlegacy", &[("radius", num(1.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert!((out.img.get(4, 4)[0] - 0.2).abs() < 0.01);
|
||||
let again = run_fx("ec.noise.medianlegacy", &[("radius", num(1.0))], img, 0.0, EffectEnv::default());
|
||||
assert_eq!(out.img.data, again.img.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curl_noise_zero_is_identity_and_flow_preserves_flat() {
|
||||
let img = crate::channel2::tests::sample();
|
||||
let id = run_fx("ec.noise.curlnoise", &[("displacementAmount", num(0.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(id.img.data, img.data);
|
||||
let flat = Image::filled(16, 16, [0.3, 0.6, 0.9, 1.0]);
|
||||
let out = run_fx("ec.noise.curlnoise", &[("displacementAmount", num(40.0)), ("scale", num(10.0))], flat.clone(), 0.0, EffectEnv::default());
|
||||
assert!(out.img.data.iter().all(|p| (p[1] - 0.6).abs() < 1e-5));
|
||||
let mut grad = Image::new(32, 32);
|
||||
for y in 0..32 {
|
||||
for x in 0..32 {
|
||||
grad.set(x, y, [x as f32 / 32.0, y as f32 / 32.0, 0.0, 1.0]);
|
||||
}
|
||||
}
|
||||
let a = run_fx("ec.noise.curlnoise", &[("displacementAmount", num(40.0)), ("scale", num(10.0))], grad.clone(), 0.0, EffectEnv::default());
|
||||
let b = run_fx("ec.noise.curlnoise", &[("displacementAmount", num(40.0)), ("scale", num(10.0))], grad.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(a.img.data, b.img.data);
|
||||
assert!(a.img.data.iter().zip(grad.data.iter()).any(|(p, q)| (p[0] - q[0]).abs() > 0.01));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Obsolete-category effects: Basic 3D (tilt/swivel the layer in a simple perspective space
|
||||
//! with an optional specular highlight) and Gaussian Blur (Legacy).
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::gaussian_blur;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::layer_rect;
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Obsolete", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Basic 3D
|
||||
|
||||
fn basic_3d(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let swivel = ctx.params.f("swivel").to_radians();
|
||||
let tilt = ctx.params.f("tilt").to_radians();
|
||||
let dist = ctx.params.f("distanceToImage") * b.scale;
|
||||
let spec_on = ctx.params.b("specularHighlight");
|
||||
let wire = ctx.params.b("drawPreviewWireframe");
|
||||
if swivel == 0.0 && tilt == 0.0 && dist == 0.0 && !spec_on && !wire {
|
||||
return b;
|
||||
}
|
||||
let (lx, ly, lw, lh) = layer_rect(ctx, &b);
|
||||
let (cx, cy) = (lx + lw * 0.5, ly + lh * 0.5);
|
||||
// Eye on the -z axis at a focal distance comparable to a 50 mm lens.
|
||||
let f = lw.max(lh).max(1.0) * 1.4;
|
||||
// Plane basis after Y (swivel) then X (tilt) rotations.
|
||||
let (cs, ss) = (swivel.cos(), swivel.sin());
|
||||
let (ct, st) = (tilt.cos(), tilt.sin());
|
||||
let ux = [cs, 0.0, -ss];
|
||||
let uy = [ss * st, ct, cs * st];
|
||||
let n = [ss * ct, -st, cs * ct];
|
||||
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
let src = b.img.clone();
|
||||
let light = {
|
||||
let l = [-0.5f64, -0.6, -1.0];
|
||||
let k = 1.0 / dot(l, l).sqrt();
|
||||
l.map(|v| v * k)
|
||||
};
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
// Ray from the eye (0, 0, -f) through the pixel on the z = 0 plane (centre-relative).
|
||||
let d = [x as f64 + 0.5 - cx, y as f64 + 0.5 - cy, f];
|
||||
let o = [0.0, 0.0, -f];
|
||||
let denom = dot(d, n);
|
||||
if denom.abs() < 1e-9 {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let pc = [0.0, 0.0, dist];
|
||||
let t = dot([pc[0] - o[0], pc[1] - o[1], pc[2] - o[2]], n) / denom;
|
||||
if t <= 0.0 {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let hit = [o[0] + d[0] * t - pc[0], o[1] + d[1] * t - pc[1], o[2] + d[2] * t - pc[2]];
|
||||
let (u, v) = (dot(hit, ux), dot(hit, uy));
|
||||
let mut c = src.sample_bilinear(cx + u, cy + v);
|
||||
if spec_on && c[3] > 0.0 {
|
||||
// Reflect the view direction about the normal and compare with the light.
|
||||
let dl = dot(d, d).sqrt();
|
||||
let dv = d.map(|v| v / dl);
|
||||
let k = 2.0 * dot(dv, n);
|
||||
let r = [dv[0] - k * n[0], dv[1] - k * n[1], dv[2] - k * n[2]];
|
||||
let s = (-dot(r, light)).max(0.0).powi(40) as f32;
|
||||
let a = c[3];
|
||||
for ch in c.iter_mut().take(3) {
|
||||
*ch += s * a * (1.0 - *ch / a.max(1e-6)).max(0.0);
|
||||
}
|
||||
}
|
||||
if wire {
|
||||
let e = (u.abs() - lw * 0.5).abs().min((v.abs() - lh * 0.5).abs());
|
||||
if e < 0.75 && u.abs() <= lw * 0.5 + 0.75 && v.abs() <= lh * 0.5 + 0.75 {
|
||||
c = [1.0, 1.0, 1.0, 1.0];
|
||||
}
|
||||
}
|
||||
*px = c;
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Gaussian Blur (Legacy)
|
||||
|
||||
fn gaussian_legacy(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let s = ctx.params.f("blurriness").max(0.0) * 0.5 * b.scale;
|
||||
if s <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let (kx, ky) = match ctx.params.e("blurDimensions") {
|
||||
1 => (1.0, 0.0),
|
||||
2 => (0.0, 1.0),
|
||||
_ => (1.0, 1.0),
|
||||
};
|
||||
if !ctx.adjustment {
|
||||
b.pad((s * 3.0).ceil() as u32);
|
||||
}
|
||||
b.img = gaussian_blur(&b.img, s * kx, s * ky, ctx.adjustment);
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![
|
||||
spec(
|
||||
"ec.obsolete.basic3d",
|
||||
"Basic 3D",
|
||||
vec![
|
||||
p("swivel", "Swivel", num(0.0), ParamUi::Angle),
|
||||
p("tilt", "Tilt", num(0.0), ParamUi::Angle),
|
||||
p("distanceToImage", "Distance to Image", num(0.0), slider(-1000.0, 30000.0, -100.0, 100.0, 1)),
|
||||
p("specularHighlight", "Specular Highlight", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("drawPreviewWireframe", "Draw Preview Wireframe", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
basic_3d,
|
||||
),
|
||||
spec(
|
||||
"ec.obsolete.gaussianlegacy",
|
||||
"Gaussian Blur (Legacy)",
|
||||
vec![
|
||||
p("blurriness", "Blurriness", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)),
|
||||
p("blurDimensions", "Blur Dimensions", Value::Enum(0), popup(&["Horizontal and Vertical", "Horizontal", "Vertical"])),
|
||||
],
|
||||
gaussian_legacy,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
use effectcraft_raster::Image;
|
||||
|
||||
fn ramp() -> Image {
|
||||
let mut img = Image::new(20, 12);
|
||||
for y in 0..12 {
|
||||
for x in 0..20 {
|
||||
img.set(x, y, [x as f32 / 20.0, y as f32 / 12.0, 0.5, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_3d_zero_identity_swivel_narrows_and_is_deterministic() {
|
||||
let img = ramp();
|
||||
let id = run_fx("ec.obsolete.basic3d", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(id.img.data, img.data);
|
||||
let flat =
|
||||
run_fx("ec.obsolete.basic3d", &[("distanceToImage", num(0.0)), ("specularHighlight", Value::Bool(false))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(flat.img.data, img.data);
|
||||
let sw = run_fx("ec.obsolete.basic3d", &[("swivel", num(60.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(sw.img.get(0, 6)[3], 0.0, "edges uncovered after swivel");
|
||||
assert!(sw.img.get(10, 6)[3] > 0.99);
|
||||
let again = run_fx("ec.obsolete.basic3d", &[("swivel", num(60.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(sw.img.data, again.img.data);
|
||||
let far = run_fx("ec.obsolete.basic3d", &[("distanceToImage", num(20.0))], img, 0.0, EffectEnv::default());
|
||||
assert_eq!(far.img.get(0, 0)[3], 0.0, "farther image is smaller");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_legacy_zero_identity_and_blurs() {
|
||||
let mut img = Image::new(15, 15);
|
||||
img.set(7, 7, [1.0, 1.0, 1.0, 1.0]);
|
||||
let id = run_fx("ec.obsolete.gaussianlegacy", &[], img.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(id.img.data, img.data);
|
||||
let out = run_fx("ec.obsolete.gaussianlegacy", &[("blurriness", num(4.0))], img.clone(), 0.0, EffectEnv::default());
|
||||
let total: f32 = out.img.data.iter().map(|p| p[3]).sum();
|
||||
assert!((total - 1.0).abs() < 1e-3, "{total}");
|
||||
let c = out.img.width / 2;
|
||||
assert!(out.img.get(c as i64, c as i64)[3] < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moved_effects_are_obsolete() {
|
||||
for id in ["ec.key.luma", "ec.key.spill", "ec.blur.reduceflicker"] {
|
||||
assert_eq!(crate::find(id).unwrap().category, "Obsolete", "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -452,7 +452,8 @@ mod tests {
|
||||
params.values.insert(ps.id.to_string(), Value::Vec2([f[0] * img.width as f64, f[1] * img.height as f64]));
|
||||
}
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
(s.render)(&ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Perspective effects, batch 2: CC Environment (reflection mapping of an environment layer
|
||||
//! onto the layer's luminance/alpha relief) and 3D Glasses (stereo pairs and anaglyphs from a
|
||||
//! left and right view layer).
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use effectcraft_color::luminance;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{Plane, fit_layer, gauss_plane, premul, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, LayerPixels, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Perspective", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CC Environment
|
||||
|
||||
/// Environment direction (x right, y down, z towards the viewer) → normalised map coordinates.
|
||||
fn env_uv(mapping: u32, r: [f64; 3]) -> (f64, f64) {
|
||||
match mapping {
|
||||
1 => {
|
||||
// Probe (mirror ball).
|
||||
let m = 2.0 * (r[0] * r[0] + r[1] * r[1] + (r[2] + 1.0).powi(2)).sqrt().max(1e-9);
|
||||
(0.5 + r[0] / m, 0.5 + r[1] / m)
|
||||
}
|
||||
2 => {
|
||||
// Vertical cross cube map: 3 faces wide, 4 tall.
|
||||
let (ax, ay, az) = (r[0].abs(), r[1].abs(), r[2].abs());
|
||||
let (col, row, u, v) = if ax >= ay && ax >= az {
|
||||
if r[0] > 0.0 { (2.0, 1.0, -r[2] / ax, r[1] / ax) } else { (0.0, 1.0, r[2] / ax, r[1] / ax) }
|
||||
} else if ay >= az {
|
||||
if r[1] < 0.0 { (1.0, 0.0, r[0] / ay, -r[2] / ay) } else { (1.0, 2.0, r[0] / ay, r[2] / ay) }
|
||||
} else if r[2] > 0.0 {
|
||||
(1.0, 1.0, r[0] / az, r[1] / az)
|
||||
} else {
|
||||
(1.0, 3.0, r[0] / az, -r[1] / az)
|
||||
};
|
||||
((col + (u + 1.0) * 0.5) / 3.0, (row + (v + 1.0) * 0.5) / 4.0)
|
||||
}
|
||||
_ => {
|
||||
// Spherical (equirectangular).
|
||||
let lon = r[0].atan2(r[2]);
|
||||
let lat = r[1].clamp(-1.0, 1.0).asin();
|
||||
(0.5 + lon / (2.0 * PI), 0.5 + lat / PI)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cc_environment(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let env = ctx.layer_param("environment", true).unwrap_or_else(|| LayerPixels { buf: b.clone(), size: ctx.layer_size });
|
||||
let env_img = if ctx.params.b("filterEnvironment") {
|
||||
let s = 2.0 * env.buf.scale;
|
||||
effectcraft_raster::gaussian_blur(&env.buf.img, s, s, true)
|
||||
} else {
|
||||
env.buf.img.clone()
|
||||
};
|
||||
let mapping = ctx.params.e("mapping");
|
||||
let height = ctx.params.f("height") / 100.0 * 20.0;
|
||||
// Relief: luminance inside, rounded off by the alpha edge.
|
||||
let relief = Plane::from_image(&b.img, |px| {
|
||||
let (c, a) = unpremul(px);
|
||||
(luminance(c[0], c[1], c[2]) * 0.5 + 0.5) * a
|
||||
});
|
||||
let soft = 1.5 * b.scale.max(0.25);
|
||||
let hmap = gauss_plane(&relief, soft, soft);
|
||||
let (es, eo, esz) = (env.buf.scale, env.buf.offset, env.size);
|
||||
let src = b.img.clone();
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let a = src.get(x as i64, y as i64)[3];
|
||||
if a <= 0.0 {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let (xi, yi) = (x as i64, y as i64);
|
||||
let gx = (hmap.get_clamped(xi + 1, yi) - hmap.get_clamped(xi - 1, yi)) as f64 * 0.5 / b.scale.max(1e-6);
|
||||
let gy = (hmap.get_clamped(xi, yi + 1) - hmap.get_clamped(xi, yi - 1)) as f64 * 0.5 / b.scale.max(1e-6);
|
||||
let n = [-gx * height, -gy * height, 1.0];
|
||||
let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
|
||||
let n = [n[0] / l, n[1] / l, n[2] / l];
|
||||
// Reflect the view ray (towards −z) about the normal.
|
||||
let d = -n[2];
|
||||
let r = [-2.0 * d * n[0], -2.0 * d * n[1], -1.0 - 2.0 * d * n[2]];
|
||||
let r = [r[0], r[1], -r[2]];
|
||||
let (u, v) = env_uv(mapping, r);
|
||||
let ex = u.rem_euclid(1.0) * esz[0] * es + eo[0];
|
||||
let ey = v.clamp(0.0, 1.0) * esz[1] * es + eo[1];
|
||||
let e = env_img.sample_bilinear_clamped(ex, ey);
|
||||
let (ec, _) = unpremul(e);
|
||||
*px = premul(ec, a);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3D Glasses
|
||||
|
||||
const VIEWS: [&str; 9] = [
|
||||
"Stereo Pair (Side by Side)",
|
||||
"Over Under",
|
||||
"Interlace Upper L Lower R",
|
||||
"Red Green LR",
|
||||
"Red Blue LR",
|
||||
"Balanced Colored Red Blue",
|
||||
"Balanced Red Green LR",
|
||||
"Balanced Red Blue LR",
|
||||
"Difference",
|
||||
];
|
||||
|
||||
fn shift(img: &Image, dx: f64, dy: f64) -> Image {
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
return img.clone();
|
||||
}
|
||||
crate::util::gen_image(img.width, img.height, |x, y| img.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy))
|
||||
}
|
||||
|
||||
fn lum(p: Px) -> f32 {
|
||||
luminance(p[0], p[1], p[2])
|
||||
}
|
||||
|
||||
fn glasses_3d(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let get = |id: &str| match ctx.layer_param(id, true) {
|
||||
Some(o) => fit_layer(ctx, &b, &o, false),
|
||||
None => b.img.clone(),
|
||||
};
|
||||
let (mut l, mut r) = (get("leftView"), get("rightView"));
|
||||
if ctx.params.b("leftRightSwap") {
|
||||
std::mem::swap(&mut l, &mut r);
|
||||
}
|
||||
let pct = ctx.params.e("units") == 1;
|
||||
let unit = if pct { ctx.layer_size[0] / 100.0 } else { 1.0 } * b.scale;
|
||||
let conv = ctx.params.f("sceneConvergence") * unit;
|
||||
let va = ctx.params.f("verticalAlignment") * unit;
|
||||
let l = shift(&l, conv * 0.5, 0.0);
|
||||
let r = shift(&r, -conv * 0.5, va);
|
||||
let view = ctx.params.e("view3d");
|
||||
let k = (ctx.params.f("balance") / 20.0).clamp(0.0, 1.0) as f32;
|
||||
let (w, h) = (b.img.width as f64, b.img.height as f64);
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
*px = match view {
|
||||
0 => {
|
||||
if fx < w * 0.5 {
|
||||
l.sample_bilinear(fx * 2.0, fy)
|
||||
} else {
|
||||
r.sample_bilinear((fx - w * 0.5) * 2.0, fy)
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
if fy < h * 0.5 {
|
||||
l.sample_bilinear(fx, fy * 2.0)
|
||||
} else {
|
||||
r.sample_bilinear(fx, (fy - h * 0.5) * 2.0)
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
if y % 2 == 0 {
|
||||
l.get(x as i64, y as i64)
|
||||
} else {
|
||||
r.get(x as i64, y as i64)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let lp = l.get(x as i64, y as i64);
|
||||
let rp = r.get(x as i64, y as i64);
|
||||
let (lc, la) = unpremul(lp);
|
||||
let (rc, ra) = unpremul(rp);
|
||||
let a = la.max(ra);
|
||||
let (ll, rl) = (lum(premul(lc, 1.0)), lum(premul(rc, 1.0)));
|
||||
let c = match view {
|
||||
3 => [ll, rl, 0.0],
|
||||
4 => [ll, 0.0, rl],
|
||||
5 => [lc[0] + (ll - lc[0]) * k, rc[1], rc[2]],
|
||||
6 => [ll * (1.0 - 0.5 * k) + lc[0] * 0.5 * k, rl, 0.0],
|
||||
7 => [ll * (1.0 - 0.5 * k) + lc[0] * 0.5 * k, 0.0, rl],
|
||||
_ => [(lc[0] - rc[0]).abs(), (lc[1] - rc[1]).abs(), (lc[2] - rc[2]).abs()],
|
||||
};
|
||||
premul(c, a)
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![
|
||||
spec(
|
||||
"ec.perspective.ccenvironment",
|
||||
"CC Environment",
|
||||
vec![
|
||||
p("environment", "Environment", Value::Layer(None), ParamUi::Layer),
|
||||
p("mapping", "Mapping", Value::Enum(0), popup(&["Spherical", "Probe", "Vertical Cross"])),
|
||||
p("filterEnvironment", "Filter Environment", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("height", "Height", num(10.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
|
||||
],
|
||||
cc_environment,
|
||||
),
|
||||
spec(
|
||||
"ec.perspective.3dglasses",
|
||||
"3D Glasses",
|
||||
vec![
|
||||
p("leftView", "Left View", Value::Layer(None), ParamUi::Layer),
|
||||
p("rightView", "Right View", Value::Layer(None), ParamUi::Layer),
|
||||
p("sceneConvergence", "Scene Convergence", num(0.0), slider(-1000.0, 1000.0, -100.0, 100.0, 1)),
|
||||
p("verticalAlignment", "Vertical Alignment", num(0.0), slider(-1000.0, 1000.0, -100.0, 100.0, 1)),
|
||||
p("units", "Units", Value::Enum(0), popup(&["Pixels", "% of Source"])),
|
||||
p("leftRightSwap", "Left Right Swap", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("view3d", "3D View", Value::Enum(5), popup(&VIEWS)),
|
||||
p("balance", "Balance", num(7.0), slider(0.0, 20.0, 0.0, 20.0, 1)),
|
||||
],
|
||||
glasses_3d,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, EffectHost, run_fx};
|
||||
|
||||
fn img() -> Image {
|
||||
crate::util::gen_image(32, 24, |x, y| {
|
||||
let a = if (4..28).contains(&x) && (4..20).contains(&y) { 1.0 } else { 0.0 };
|
||||
[x as f32 / 32.0 * a, y as f32 / 24.0 * a, 0.4 * a, a]
|
||||
})
|
||||
}
|
||||
|
||||
struct Host(LayerPixels);
|
||||
impl EffectHost for Host {
|
||||
fn layer(&self, _: u64, _: bool) -> Option<LayerPixels> {
|
||||
Some(self.0.clone())
|
||||
}
|
||||
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_reflects_env_layer() {
|
||||
// A flat layer reflects the environment straight back: with a uniform green environment,
|
||||
// opaque pixels become green, transparent stay transparent.
|
||||
let env = LayerPixels { buf: Buf { img: Image::filled(16, 8, [0.0, 1.0, 0.0, 1.0]), offset: [0.0; 2], scale: 1.0 }, size: [16.0, 8.0] };
|
||||
let host = Host(env);
|
||||
let e = EffectEnv { host: Some(&host), ..Default::default() };
|
||||
let o = run_fx("ec.perspective.ccenvironment", &[("environment", Value::Layer(Some(9)))], img(), 0.0, e);
|
||||
let px = o.img.get(16, 12);
|
||||
assert!((px[1] - 1.0).abs() < 1e-4 && px[0].abs() < 1e-4, "{px:?}");
|
||||
assert_eq!(o.img.get(0, 0)[3], 0.0);
|
||||
let again = run_fx("ec.perspective.ccenvironment", &[("environment", Value::Layer(Some(9)))], img(), 0.0, e);
|
||||
assert_eq!(o.img, again.img);
|
||||
for m in 0..3 {
|
||||
let o = run_fx("ec.perspective.ccenvironment", &[("mapping", Value::Enum(m))], img(), 0.0, EffectEnv::default());
|
||||
assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glasses_anaglyph_and_pairs() {
|
||||
let im = img();
|
||||
// Same view on both eyes: Red Blue LR puts the luminance in red and blue equally.
|
||||
let o = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(4))], im.clone(), 0.0, EffectEnv::default());
|
||||
let px = o.img.get(16, 12);
|
||||
assert!((px[0] - px[2]).abs() < 1e-5 && px[1] == 0.0 && px[0] > 0.0);
|
||||
// Difference of identical views is black.
|
||||
let o = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(8))], im.clone(), 0.0, EffectEnv::default());
|
||||
assert!(o.img.data.iter().all(|p| p[0].abs() < 1e-6 && p[1].abs() < 1e-6));
|
||||
// Convergence separates the eyes: difference becomes non-zero.
|
||||
let o = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(8)), ("sceneConvergence", num(4.0))], im.clone(), 0.0, EffectEnv::default());
|
||||
assert!(o.img.data.iter().any(|p| p[0] > 0.05));
|
||||
// Every view is deterministic.
|
||||
for v in 0..VIEWS.len() as u32 {
|
||||
let a = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(v))], im.clone(), 0.0, EffectEnv::default());
|
||||
let b = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(v))], im.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(a.img, b.img);
|
||||
}
|
||||
// Interlace: even rows = left view (self).
|
||||
let o = run_fx("ec.perspective.3dglasses", &[("view3d", Value::Enum(2))], im.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(o.img.get(10, 10), im.get(10, 10));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -698,7 +698,7 @@ mod tests {
|
||||
for (k, v) in vals {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
//! Stylize effects, batch 3: CC Block Load, CC Burn Film, CC Glass, CC HexTile, CC Mr. Smoothie
|
||||
//! and CC Plastic.
|
||||
//!
|
||||
//! Written from the public descriptions of what these effects do (progressive block loading,
|
||||
//! burning film, bump-mapped glass / plastic surfaces lit by an effect light, hexagonal tiling,
|
||||
//! a colour map sampled from the image itself); the maths is our own.
|
||||
|
||||
use effectcraft_color::rgb_to_hsl;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::noise::fbm;
|
||||
use crate::util::{Plane, gauss_plane, layer_or_self, lerp4, premul, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Stylize", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
fn pt(x: f64, y: f64) -> Value {
|
||||
Value::Vec2([x, y])
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Block Load
|
||||
|
||||
/// Mean colour of every `s`×`s` block (grid of `ceil(w/s)`×`ceil(h/s)`).
|
||||
fn block_means(img: &Image, s: usize) -> (usize, usize, Vec<Px>) {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let gw = w.div_ceil(s).max(1);
|
||||
let gh = h.div_ceil(s).max(1);
|
||||
let mut out = vec![[0.0f32; 4]; gw * gh];
|
||||
out.par_chunks_mut(gw).enumerate().for_each(|(by, row)| {
|
||||
for (bx, o) in row.iter_mut().enumerate() {
|
||||
let mut acc = [0.0f32; 4];
|
||||
let mut n = 0.0f32;
|
||||
for y in by * s..((by + 1) * s).min(h) {
|
||||
for x in bx * s..((bx + 1) * s).min(w) {
|
||||
let p = img.data[y * w + x];
|
||||
for c in 0..4 {
|
||||
acc[c] += p[c];
|
||||
}
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
if n > 0.0 {
|
||||
*o = acc.map(|v| v / n);
|
||||
}
|
||||
}
|
||||
});
|
||||
(gw, gh, out)
|
||||
}
|
||||
|
||||
/// Value of pixel (x, y) at block size `s` (nearest block, or bilinear between block centres).
|
||||
fn block_at(g: &(usize, usize, Vec<Px>), s: usize, x: usize, y: usize, bilinear: bool) -> Px {
|
||||
let (gw, gh, d) = g;
|
||||
if !bilinear || s == 1 {
|
||||
return d[(y / s).min(gh - 1) * gw + (x / s).min(gw - 1)];
|
||||
}
|
||||
let fx = (x as f32 + 0.5) / s as f32 - 0.5;
|
||||
let fy = (y as f32 + 0.5) / s as f32 - 0.5;
|
||||
let x0 = fx.floor();
|
||||
let y0 = fy.floor();
|
||||
let (tx, ty) = (fx - x0, fy - y0);
|
||||
let gx = |v: f32| (v as i64).clamp(0, *gw as i64 - 1) as usize;
|
||||
let gy = |v: f32| (v as i64).clamp(0, *gh as i64 - 1) as usize;
|
||||
let a = d[gy(y0) * gw + gx(x0)];
|
||||
let b = d[gy(y0) * gw + gx(x0 + 1.0)];
|
||||
let c = d[gy(y0 + 1.0) * gw + gx(x0)];
|
||||
let e = d[gy(y0 + 1.0) * gw + gx(x0 + 1.0)];
|
||||
lerp4(lerp4(a, b, tx), lerp4(c, e, tx), ty)
|
||||
}
|
||||
|
||||
fn block_load(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = (ctx.params.f("completion") / 100.0).clamp(0.0, 1.0);
|
||||
if c >= 1.0 {
|
||||
return b;
|
||||
}
|
||||
let scan = ctx.params.b("scanlines");
|
||||
let smooth = ctx.params.b("smoothing");
|
||||
let cleared = ctx.params.b("startCleared");
|
||||
let bilinear = ctx.params.b("bilinear");
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let nlev = (w.max(h).max(2) as f64).log2().ceil() as u32;
|
||||
// Levels 0..=nlev with block sizes 2^(nlev-k); level k is "loading" while p is in [k, k+1).
|
||||
let p = c * (nlev + 1) as f64;
|
||||
let done = p.floor() as u32;
|
||||
let frac = (p - done as f64) as f32;
|
||||
let size = |k: u32| 1usize << (nlev - k.min(nlev));
|
||||
let s_new = size(done);
|
||||
let new = block_means(&b.img, s_new);
|
||||
let old = if done > 0 { Some((size(done - 1), block_means(&b.img, size(done - 1)))) } else { None };
|
||||
let rows_new = h.div_ceil(s_new) as f32;
|
||||
let soft = if smooth { 1.5f32 } else { 0.0 };
|
||||
let mut out = Image::new(w as u32, h as u32);
|
||||
out.rows_mut().for_each(|(y, row)| {
|
||||
// Fraction of the new level present on this row.
|
||||
let t = if scan {
|
||||
let front = frac * (rows_new + soft) - soft * 0.5;
|
||||
let r = (y / s_new) as f32 + 0.5;
|
||||
if soft > 0.0 {
|
||||
smoothstep(r - soft * 0.5, r + soft * 0.5, front)
|
||||
} else if r < front {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
} else if smooth {
|
||||
frac
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let n = if t > 0.0 { block_at(&new, s_new, x, y, bilinear) } else { [0.0; 4] };
|
||||
let prev = match &old {
|
||||
Some((s, g)) => block_at(g, *s, x, y, bilinear),
|
||||
None if cleared => [0.0; 4],
|
||||
None => block_at(&new, s_new, x, y, bilinear),
|
||||
};
|
||||
*o = if t >= 1.0 {
|
||||
n
|
||||
} else if t <= 0.0 {
|
||||
prev
|
||||
} else {
|
||||
lerp4(prev, n, t)
|
||||
};
|
||||
}
|
||||
});
|
||||
b.img = out;
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Burn Film
|
||||
|
||||
fn burn_film(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let burn = (ctx.params.f("burn") / 100.0).clamp(0.0, 1.0) as f32;
|
||||
if burn <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let (cx, cy) = b.to_px(ctx.params.v2("center"));
|
||||
let seed = ctx.params.f("randomSeed").max(0.0) as u32;
|
||||
let s = b.scale;
|
||||
let diag = (ctx.layer_size[0].hypot(ctx.layer_size[1]) * s).max(1.0);
|
||||
let feat = (60.0 * s).max(1e-3);
|
||||
let th = 1.0 - burn * 1.25;
|
||||
let band = 0.12 * (burn * 10.0).min(1.0);
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let d = ((fx - cx).hypot(fy - cy) / diag) as f32;
|
||||
let n = fbm((fx / feat) as f32, (fy / feat) as f32, 0.0, seed.wrapping_add(17), 4.0);
|
||||
// High near the centre and where the noise is high; burning eats from the top down.
|
||||
let f = n * 0.65 + (1.0 - d.min(1.0)) * 0.35;
|
||||
if f > th + band {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
if f > th - band * 2.0 {
|
||||
let (c, a) = unpremul(*px);
|
||||
// Charred rim (scorched dark) with a hot orange edge right next to the hole.
|
||||
let k = smoothstep(th - band * 2.0, th, f);
|
||||
let hot = smoothstep(th, th + band, f);
|
||||
let char = 1.0 - k * 0.85;
|
||||
let mut o = [c[0] * char, c[1] * char, c[2] * char];
|
||||
o = [o[0] + (1.0 - o[0]) * hot * 0.9, o[1] + (0.45 - o[1]) * hot * 0.9, o[2] * (1.0 - hot)];
|
||||
let na = a * (1.0 - hot * 0.6);
|
||||
*px = premul(o, na);
|
||||
}
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bump-map surfaces (Glass, Plastic)
|
||||
|
||||
const BUMP_PROPS: [&str; 6] = ["Red", "Green", "Blue", "Alpha", "Luminance", "Lightness"];
|
||||
|
||||
/// Height field (0..1) from the bump-map layer (or the layer itself), softened.
|
||||
fn height_field(ctx: &EffectCtx, b: &Buf) -> Plane {
|
||||
let src = layer_or_self(ctx, b, "bumpMap", true, false);
|
||||
let prop = ctx.params.e("property");
|
||||
let mut pl = Plane::from_image(&src, |p| {
|
||||
let (c, a) = unpremul(p);
|
||||
let v = match prop {
|
||||
0 => c[0],
|
||||
1 => c[1],
|
||||
2 => c[2],
|
||||
3 => return a,
|
||||
4 => effectcraft_color::luminance(c[0], c[1], c[2]),
|
||||
_ => rgb_to_hsl(c[0], c[1], c[2]).2,
|
||||
};
|
||||
v * a
|
||||
});
|
||||
let soft = ctx.params.f("softness") * b.scale * 0.5;
|
||||
if soft > 0.05 {
|
||||
pl = gauss_plane(&pl, soft, soft);
|
||||
}
|
||||
pl
|
||||
}
|
||||
|
||||
struct Light {
|
||||
intensity: f32,
|
||||
color: [f32; 3],
|
||||
point: bool,
|
||||
pos: (f64, f64),
|
||||
/// Distant light direction (towards the light).
|
||||
dir: [f32; 3],
|
||||
height: f32,
|
||||
ambient: f32,
|
||||
diffuse: f32,
|
||||
specular: f32,
|
||||
shininess: f32,
|
||||
metal: f32,
|
||||
}
|
||||
|
||||
impl Light {
|
||||
fn from(ctx: &EffectCtx, b: &Buf) -> Light {
|
||||
let pr = &ctx.params;
|
||||
let elev = (pr.f("lightHeight").clamp(-100.0, 100.0) / 100.0 * 90.0).to_radians();
|
||||
let az = pr.f("lightDirection").to_radians();
|
||||
let dir = [(az.sin() * elev.cos()) as f32, (-az.cos() * elev.cos()) as f32, elev.sin() as f32];
|
||||
let c = pr.color("lightColor");
|
||||
let rough = pr.f("roughness").clamp(0.001, 1.0) as f32;
|
||||
Light {
|
||||
intensity: (pr.f("lightIntensity") / 100.0) as f32,
|
||||
color: [c[0], c[1], c[2]],
|
||||
point: pr.e("lightType") == 1,
|
||||
pos: b.to_px(pr.v2("lightPosition")),
|
||||
dir,
|
||||
height: (pr.f("lightHeight") / 100.0 * ctx.layer_size[0].max(ctx.layer_size[1]) * b.scale * 0.5) as f32,
|
||||
ambient: (pr.f("ambient") / 100.0) as f32,
|
||||
diffuse: (pr.f("diffuse") / 100.0) as f32,
|
||||
specular: (pr.f("specular") / 100.0) as f32,
|
||||
shininess: 1.0 / rough,
|
||||
metal: (pr.f("metal") / 100.0) as f32,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_light(&self, x: f64, y: f64) -> [f32; 3] {
|
||||
if self.point {
|
||||
let v = [(self.pos.0 - x) as f32, (self.pos.1 - y) as f32, self.height.max(1.0)];
|
||||
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);
|
||||
[v[0] / l, v[1] / l, v[2] / l]
|
||||
} else {
|
||||
self.dir
|
||||
}
|
||||
}
|
||||
|
||||
/// Lit straight colour for surface normal `n`. Diffuse is normalised so that a flat surface
|
||||
/// keeps its colour; highlights add on top.
|
||||
fn shade(&self, c: [f32; 3], n: [f32; 3], l: [f32; 3]) -> [f32; 3] {
|
||||
let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0);
|
||||
let flat = l[2].max(0.0);
|
||||
let base = self.ambient + self.diffuse * flat;
|
||||
let lit = if base > 1e-4 { (self.ambient + self.diffuse * ndl) / base } else { 1.0 };
|
||||
let lit = 1.0 + (lit - 1.0) * self.intensity;
|
||||
// Blinn half vector with the viewer straight above.
|
||||
let hv = [l[0], l[1], l[2] + 1.0];
|
||||
let hl = (hv[0] * hv[0] + hv[1] * hv[1] + hv[2] * hv[2]).sqrt().max(1e-6);
|
||||
let ndh = ((n[0] * hv[0] + n[1] * hv[1] + n[2] * hv[2]) / hl).max(0.0);
|
||||
let spec = self.specular * self.intensity * ndh.powf(self.shininess);
|
||||
let mut o = [0.0f32; 3];
|
||||
for i in 0..3 {
|
||||
let hl_col = self.color[i] * (1.0 - self.metal) + c[i] * self.color[i] * self.metal;
|
||||
o[i] = c[i] * lit * (1.0 + (self.color[i] - 1.0) * self.intensity.min(1.0)) + spec * hl_col;
|
||||
}
|
||||
o
|
||||
}
|
||||
}
|
||||
|
||||
/// Surface normal from a height field at pixel (x, y) with height scale `k`.
|
||||
#[inline]
|
||||
fn normal(h: &Plane, x: usize, y: usize, k: f32) -> [f32; 3] {
|
||||
let (xi, yi) = (x as i64, y as i64);
|
||||
let gx = (h.get_clamped(xi + 1, yi) - h.get_clamped(xi - 1, yi)) * 0.5 * k;
|
||||
let gy = (h.get_clamped(xi, yi + 1) - h.get_clamped(xi, yi - 1)) * 0.5 * k;
|
||||
let l = (gx * gx + gy * gy + 1.0).sqrt();
|
||||
[-gx / l, -gy / l, 1.0 / l]
|
||||
}
|
||||
|
||||
fn glass(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let hf = height_field(ctx, &b);
|
||||
let height = ctx.params.f("height") as f32 / 100.0;
|
||||
let k = height * 25.0;
|
||||
let disp = ctx.params.f("displacement") * b.scale * 0.25;
|
||||
let light = Light::from(ctx, &b);
|
||||
let src = b.img.clone();
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let n = normal(&hf, x, y, k);
|
||||
let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let s = if disp != 0.0 && height != 0.0 {
|
||||
src.sample_bilinear_clamped(fx + n[0] as f64 * disp, fy + n[1] as f64 * disp)
|
||||
} else {
|
||||
src.data[y * src.width as usize + x]
|
||||
};
|
||||
let a = src.data[y * src.width as usize + x][3];
|
||||
if a <= 0.0 {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let (c, sa) = unpremul(s);
|
||||
let c = if sa > 0.0 { c } else { unpremul(src.data[y * src.width as usize + x]).0 };
|
||||
let o = light.shade(c, n, light.to_light(fx, fy));
|
||||
*px = premul(o, a);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
fn plastic(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let mut hf = height_field(ctx, &b);
|
||||
let lo = (ctx.params.f("cutMin") / 100.0) as f32;
|
||||
let hi = (ctx.params.f("cutMax") / 100.0) as f32;
|
||||
if lo > 0.0 || hi < 1.0 {
|
||||
hf = hf.map(|v| v.clamp(lo.min(hi), hi.max(lo)));
|
||||
}
|
||||
let k = ctx.params.f("height") as f32 / 100.0 * 25.0;
|
||||
let light = Light::from(ctx, &b);
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
if px[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (c, a) = unpremul(*px);
|
||||
let n = normal(&hf, x, y, k);
|
||||
let o = light.shade(c, n, light.to_light(x as f64 + 0.5, y as f64 + 0.5));
|
||||
*px = premul(o, a);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC HexTile
|
||||
|
||||
/// Axial hex cell (pointy-top) containing (x, y) for circumradius `r`; returns the cell centre
|
||||
/// and integer cell coordinates.
|
||||
fn hex_cell(x: f64, y: f64, r: f64) -> ((f64, f64), (i64, i64)) {
|
||||
let q = (3f64.sqrt() / 3.0 * x - y / 3.0) / r;
|
||||
let rr = (2.0 / 3.0 * y) / r;
|
||||
// Cube rounding.
|
||||
let (cx, cz) = (q, rr);
|
||||
let cy = -cx - cz;
|
||||
let (mut rx, ry, mut rz) = (cx.round(), cy.round(), cz.round());
|
||||
let (dx, dy, dz) = ((rx - cx).abs(), (ry - cy).abs(), (rz - cz).abs());
|
||||
if dx > dy && dx > dz {
|
||||
rx = -ry - rz;
|
||||
} else if dy <= dz {
|
||||
rz = -rx - ry;
|
||||
}
|
||||
let px = r * 3f64.sqrt() * (rx + rz / 2.0);
|
||||
let py = r * 1.5 * rz;
|
||||
((px, py), (rx as i64, rz as i64))
|
||||
}
|
||||
|
||||
fn hextile(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let r = (ctx.params.f("radius") * b.scale).max(0.5);
|
||||
let (cx, cy) = b.to_px(ctx.params.v2("center"));
|
||||
let rot = ctx.params.f("rotate").to_radians();
|
||||
let (sn, cs) = rot.sin_cos();
|
||||
let smear = (ctx.params.f("smearing") / 100.0).clamp(0.0, 1.0);
|
||||
let mode = ctx.params.e("render");
|
||||
let src = b.img.clone();
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
|
||||
// Into the rotated tiling frame.
|
||||
let (u, v) = (dx * cs + dy * sn, -dx * sn + dy * cs);
|
||||
let ((hx, hy), (qi, ri)) = hex_cell(u, v, r);
|
||||
let (mut lu, lv) = (u - hx, v - hy);
|
||||
let odd = (qi + ri).rem_euclid(2) == 1;
|
||||
match mode {
|
||||
1 if odd => lu = -lu,
|
||||
2 if odd => lu = -lu,
|
||||
_ => {}
|
||||
}
|
||||
let lv = if mode == 2 && odd { -lv } else { lv };
|
||||
// Every tile shows the hexagon around the centre point.
|
||||
let (ox, oy) = (lu * cs - lv * sn, lu * sn + lv * cs);
|
||||
let (tx, ty) = (cx + ox, cy + oy);
|
||||
let (sx, sy) = (tx + (x as f64 + 0.5 - tx) * smear, ty + (y as f64 + 0.5 - ty) * smear);
|
||||
*px = src.sample_bilinear_clamped(sx, sy);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Mr. Smoothie
|
||||
|
||||
const SMOOTHIE_PROPS: [&str; 8] = ["Red", "Green", "Blue", "Alpha", "Luminance", "Lightness", "Hue", "Saturation"];
|
||||
|
||||
fn smoothie(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let flow = layer_or_self(ctx, &b, "flowLayer", true, false);
|
||||
let prop = ctx.params.e("property");
|
||||
let mut pl = Plane::from_image(&flow, |p| {
|
||||
let (c, a) = unpremul(p);
|
||||
match prop {
|
||||
0 => c[0],
|
||||
1 => c[1],
|
||||
2 => c[2],
|
||||
3 => a,
|
||||
4 => effectcraft_color::luminance(c[0], c[1], c[2]),
|
||||
5 => rgb_to_hsl(c[0], c[1], c[2]).2,
|
||||
6 => rgb_to_hsl(c[0], c[1], c[2]).0,
|
||||
_ => rgb_to_hsl(c[0], c[1], c[2]).1,
|
||||
}
|
||||
});
|
||||
let sm = ctx.params.f("smoothness") * b.scale * 0.5;
|
||||
if sm > 0.05 {
|
||||
pl = gauss_plane(&pl, sm, sm);
|
||||
}
|
||||
let (ax, ay) = b.to_px(ctx.params.v2("sampleA"));
|
||||
let (bx, by) = b.to_px(ctx.params.v2("sampleB"));
|
||||
// Colour palette sampled from the image along A→B.
|
||||
const N: usize = 256;
|
||||
let pal: Vec<Px> = (0..N)
|
||||
.map(|i| {
|
||||
let t = i as f64 / (N - 1) as f64;
|
||||
let p = b.img.sample_bilinear_clamped(ax + (bx - ax) * t, ay + (by - ay) * t);
|
||||
let (c, _) = unpremul(p);
|
||||
[c[0], c[1], c[2], 1.0]
|
||||
})
|
||||
.collect();
|
||||
let phase = (ctx.params.f("phase") / 360.0) as f32;
|
||||
let loops = (ctx.params.e("colorLoop") + 1) as f32;
|
||||
b.img.data.par_iter_mut().zip(pl.data.par_iter()).for_each(|(px, &v)| {
|
||||
if px[3] <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let t = (v * loops + phase).rem_euclid(1.0);
|
||||
// Ping-pong so the palette loops without seams.
|
||||
let t = if t < 0.5 { t * 2.0 } else { 2.0 - t * 2.0 };
|
||||
let f = t * (N - 1) as f32;
|
||||
let i = (f as usize).min(N - 2);
|
||||
let c = lerp4(pal[i], pal[i + 1], f - i as f32);
|
||||
*px = premul([c[0], c[1], c[2]], px[3]);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ specs
|
||||
|
||||
fn light_params() -> Vec<crate::ParamSpec> {
|
||||
vec![
|
||||
p("using", "Using", Value::Enum(0), popup(&["Effect Light", "AE Lights"])),
|
||||
p("lightIntensity", "Light Intensity", num(100.0), slider(0.0, 400.0, 0.0, 200.0, 1)),
|
||||
p("lightColor", "Light Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("lightType", "Light Type", Value::Enum(0), popup(&["Distant Light", "Point Light"])),
|
||||
p("lightHeight", "Light Height", num(50.0), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
p("lightPosition", "Light Position", pt(0.25, 0.25), ParamUi::Point),
|
||||
p("lightDirection", "Light Direction", num(-45.0), ParamUi::Angle),
|
||||
]
|
||||
}
|
||||
|
||||
fn shading_params(ambient: f64, diffuse: f64, specular: f64, roughness: f64, metal: f64) -> Vec<crate::ParamSpec> {
|
||||
vec![
|
||||
p("ambient", "Ambient", num(ambient), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("diffuse", "Diffuse", num(diffuse), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("specular", "Specular", num(specular), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("roughness", "Roughness", num(roughness), slider(0.001, 0.5, 0.001, 0.5, 3)),
|
||||
p("metal", "Metal", num(metal), pct()),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let mut glass_p = vec![
|
||||
p("bumpMap", "Bump Map", Value::Layer(None), ParamUi::Layer),
|
||||
p("property", "Property", Value::Enum(3), popup(&BUMP_PROPS)),
|
||||
p("softness", "Softness", num(10.0), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("height", "Height", num(50.0), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
p("displacement", "Displacement", num(100.0), slider(-500.0, 500.0, -200.0, 200.0, 1)),
|
||||
];
|
||||
glass_p.extend(light_params());
|
||||
glass_p.extend(shading_params(75.0, 32.0, 26.0, 0.05, 100.0));
|
||||
let mut plastic_p = vec![
|
||||
p("bumpLayer", "Bump Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("property", "Property", Value::Enum(3), popup(&BUMP_PROPS)),
|
||||
p("softness", "Softness", num(10.0), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("height", "Height", num(25.0), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
p("cutMin", "Cut Min", num(0.0), pct()),
|
||||
p("cutMax", "Cut Max", num(100.0), pct()),
|
||||
];
|
||||
plastic_p.extend(light_params());
|
||||
plastic_p.extend(shading_params(100.0, 70.0, 50.0, 0.05, 50.0));
|
||||
vec![
|
||||
spec(
|
||||
"ec.stylize.ccblockload",
|
||||
"CC Block Load",
|
||||
vec![
|
||||
p("completion", "Completion", num(0.0), pct()),
|
||||
p("scanlines", "Scanlines", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("smoothing", "Smoothing", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("startCleared", "Start Cleared", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("bilinear", "Bilinear", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
block_load,
|
||||
),
|
||||
spec(
|
||||
"ec.stylize.ccburnfilm",
|
||||
"CC Burn Film",
|
||||
vec![
|
||||
p("burn", "Burn", num(0.0), pct()),
|
||||
p("center", "Center", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("randomSeed", "Random Seed", num(0.0), slider(0.0, 10000.0, 0.0, 100.0, 0)),
|
||||
],
|
||||
burn_film,
|
||||
),
|
||||
spec("ec.stylize.ccglass", "CC Glass", glass_p, glass),
|
||||
spec(
|
||||
"ec.stylize.cchextile",
|
||||
"CC HexTile",
|
||||
vec![
|
||||
p("render", "Render", Value::Enum(0), popup(&["Normal", "Mirrored", "Rotated"])),
|
||||
p("radius", "Radius", num(50.0), slider(1.0, 4000.0, 2.0, 500.0, 1)),
|
||||
p("center", "Center", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("rotate", "Rotate", num(0.0), ParamUi::Angle),
|
||||
p("smearing", "Smearing", num(0.0), pct()),
|
||||
],
|
||||
hextile,
|
||||
),
|
||||
spec(
|
||||
"ec.stylize.ccmrsmoothie",
|
||||
"CC Mr. Smoothie",
|
||||
vec![
|
||||
p("flowLayer", "Flow Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("property", "Property", Value::Enum(4), popup(&SMOOTHIE_PROPS)),
|
||||
p("smoothness", "Smoothness", num(20.0), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("sampleA", "Sample A", pt(0.25, 0.5), ParamUi::Point),
|
||||
p("sampleB", "Sample B", pt(0.75, 0.5), ParamUi::Point),
|
||||
p("phase", "Phase", num(0.0), ParamUi::Angle),
|
||||
p("colorLoop", "Color Loop", Value::Enum(0), popup(&["1x", "2x", "3x", "4x"])),
|
||||
],
|
||||
smoothie,
|
||||
),
|
||||
spec("ec.stylize.ccplastic", "CC Plastic", plastic_p, plastic),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
|
||||
fn ramp(w: u32, h: u32) -> Image {
|
||||
let mut img = Image::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
img.set(x, y, [x as f32 / w as f32, y as f32 / h as f32, 0.3, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn bumpy(w: u32, h: u32) -> Image {
|
||||
let mut img = ramp(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let a = if (x as i32 - 20).pow(2) + (y as i32 - 16).pow(2) < 64 { 1.0 } else { 0.5 };
|
||||
let p = img.data[(y * w + x) as usize];
|
||||
img.set(x, y, [p[0] * a, p[1] * a, p[2] * a, a]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn run(id: &str, vals: &[(&str, Value)], img: Image) -> Buf {
|
||||
run_fx(id, vals, img, 0.0, EffectEnv::default())
|
||||
}
|
||||
|
||||
fn max_diff(a: &Image, b: &Image) -> f32 {
|
||||
a.data.iter().zip(&b.data).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
const ALL: [&str; 6] =
|
||||
["ec.stylize.ccblockload", "ec.stylize.ccburnfilm", "ec.stylize.ccglass", "ec.stylize.cchextile", "ec.stylize.ccmrsmoothie", "ec.stylize.ccplastic"];
|
||||
|
||||
#[test]
|
||||
fn all_deterministic() {
|
||||
for id in ALL {
|
||||
let vals: &[(&str, Value)] = match id {
|
||||
"ec.stylize.ccblockload" => &[("completion", num(40.0))],
|
||||
"ec.stylize.ccburnfilm" => &[("burn", num(50.0))],
|
||||
_ => &[],
|
||||
};
|
||||
let a = run(id, vals, bumpy(40, 32));
|
||||
let b = run(id, vals, bumpy(40, 32));
|
||||
assert_eq!(a.img.data, b.img.data, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_load_complete_is_identity_and_start_cleared() {
|
||||
let img = ramp(40, 30);
|
||||
assert_eq!(run("ec.stylize.ccblockload", &[("completion", num(100.0))], img.clone()).img.data, img.data);
|
||||
let o = run("ec.stylize.ccblockload", &[("completion", num(0.0))], img.clone());
|
||||
assert!(o.img.data.iter().all(|p| p[3] == 0.0));
|
||||
// Midway: blocky (fewer distinct colours than the source).
|
||||
let o = run("ec.stylize.ccblockload", &[("completion", num(50.0)), ("smoothing", Value::Bool(false))], img.clone());
|
||||
let mut cols: Vec<u32> = o.img.data.iter().map(|p| (p[0] * 1000.0) as u32).collect();
|
||||
cols.sort();
|
||||
cols.dedup();
|
||||
assert!(cols.len() < 40, "{}", cols.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burn_film_zero_identity_full_burns() {
|
||||
let img = ramp(40, 30);
|
||||
assert_eq!(run("ec.stylize.ccburnfilm", &[], img.clone()).img.data, img.data);
|
||||
let o = run("ec.stylize.ccburnfilm", &[("burn", num(100.0))], img);
|
||||
assert!(o.img.data.iter().all(|p| p[3] == 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glass_flat_without_highlight_is_identity() {
|
||||
let img = bumpy(40, 32);
|
||||
let o = run("ec.stylize.ccglass", &[("height", num(0.0)), ("specular", num(0.0))], img.clone());
|
||||
assert!(max_diff(&o.img, &img) < 1e-4, "{}", max_diff(&o.img, &img));
|
||||
let o = run("ec.stylize.ccglass", &[], img.clone());
|
||||
assert!(max_diff(&o.img, &img) > 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plastic_shades_bumps() {
|
||||
let img = bumpy(40, 32);
|
||||
let o = run("ec.stylize.ccplastic", &[("height", num(0.0)), ("specular", num(0.0))], img.clone());
|
||||
assert!(max_diff(&o.img, &img) < 1e-4);
|
||||
let o = run("ec.stylize.ccplastic", &[("height", num(80.0))], img.clone());
|
||||
assert!(max_diff(&o.img, &img) > 0.01);
|
||||
// Alpha is untouched.
|
||||
assert!(o.img.data.iter().zip(&img.data).all(|(a, b)| (a[3] - b[3]).abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hextile_repeats_centre() {
|
||||
let img = ramp(64, 64);
|
||||
let o = run("ec.stylize.cchextile", &[("radius", num(8.0)), ("center", pt(32.0, 32.0))], img.clone());
|
||||
assert!(max_diff(&o.img, &img) > 0.1);
|
||||
// Pixels at the centre are unchanged (inside the central tile).
|
||||
let c = (32 * 64 + 32) as usize;
|
||||
assert!((0..4).all(|i| (o.img.data[c][i] - img.data[c][i]).abs() < 1e-4));
|
||||
// Full smearing restores the source.
|
||||
let o = run("ec.stylize.cchextile", &[("radius", num(8.0)), ("smearing", num(100.0))], img.clone());
|
||||
assert!(max_diff(&o.img, &img) < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoothie_maps_to_sampled_palette() {
|
||||
let img = ramp(40, 30);
|
||||
let o = run("ec.stylize.ccmrsmoothie", &[("smoothness", num(0.0)), ("sampleA", pt(10.0, 15.0)), ("sampleB", pt(30.0, 15.0))], img.clone());
|
||||
// Every output colour lies on the palette line between A and B (blue stays 0.3, green ≈ 0.5).
|
||||
assert!(o.img.data.iter().all(|p| (p[2] - 0.3).abs() < 1e-3 && (p[1] - 0.5).abs() < 0.03));
|
||||
assert!(max_diff(&o.img, &img) > 0.1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,981 @@
|
||||
//! Text effects (Numbers, Timecode) and the obsolete generators Basic Text, Path Text and
|
||||
//! Lightning.
|
||||
//!
|
||||
//! Effects sit below the text engine in the crate layering, so text here is drawn with a small
|
||||
//! built-in single-stroke font (original work: capitals, digits and common punctuation laid out
|
||||
//! on a 4 × 6 unit grid; lowercase letters use the capitals) and rasterised as anti-aliased round
|
||||
//! strokes.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::generate3::{Seg, mask_px, poly_segs, raster_segs};
|
||||
use crate::util::{Plane, gauss_plane, hash1, poly_length, poly_point_at};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, category: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category, params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- stroke font
|
||||
|
||||
/// Glyph strokes on a grid x ∈ [0, 4], y ∈ [0, 6] (y down, baseline at 6): polylines separated
|
||||
/// by `;`, points by spaces. A single point is a dot.
|
||||
fn glyph_src(c: char) -> &'static str {
|
||||
match c.to_ascii_uppercase() {
|
||||
'0' => "1,0 3,0 4,1 4,5 3,6 1,6 0,5 0,1 1,0; 3.6,0.6 0.4,5.4",
|
||||
'1' => "1,1 2,0 2,6; 1,6 3,6",
|
||||
'2' => "0,1 1,0 3,0 4,1 4,2 0,6 4,6",
|
||||
'3' => "0,0 4,0 2,2.5 3,2.5 4,3.5 4,5 3,6 1,6 0,5",
|
||||
'4' => "3,6 3,0 0,4 4,4",
|
||||
'5' => "4,0 0,0 0,2.5 3,2.5 4,3.5 4,5 3,6 0,6",
|
||||
'6' => "3.5,0 1,0 0,1 0,5 1,6 3,6 4,5 4,3.5 3,2.5 0,2.5",
|
||||
'7' => "0,0 4,0 1.5,6",
|
||||
'8' => "1,0 3,0 4,1 4,2 3,3 1,3 0,2 0,1 1,0; 1,3 0,4 0,5 1,6 3,6 4,5 4,4 3,3",
|
||||
'9' => "4,3.5 1,3.5 0,2.5 0,1 1,0 3,0 4,1 4,5 3,6 0.5,6",
|
||||
'A' => "0,6 2,0 4,6; 0.7,4 3.3,4",
|
||||
'B' => "0,0 0,6 3,6 4,5 4,4 3,3 0,3; 0,0 3,0 4,1 4,2 3,3",
|
||||
'C' => "4,1 3,0 1,0 0,1 0,5 1,6 3,6 4,5",
|
||||
'D' => "0,0 0,6 2.5,6 4,4.5 4,1.5 2.5,0 0,0",
|
||||
'E' => "4,0 0,0 0,6 4,6; 0,3 3,3",
|
||||
'F' => "4,0 0,0 0,6; 0,3 3,3",
|
||||
'G' => "4,1 3,0 1,0 0,1 0,5 1,6 3,6 4,5 4,3.5 2.5,3.5",
|
||||
'H' => "0,0 0,6; 4,0 4,6; 0,3 4,3",
|
||||
'I' => "1,0 3,0; 2,0 2,6; 1,6 3,6",
|
||||
'J' => "4,0 4,5 3,6 1,6 0,5",
|
||||
'K' => "0,0 0,6; 4,0 0,4; 1.3,3 4,6",
|
||||
'L' => "0,0 0,6 4,6",
|
||||
'M' => "0,6 0,0 2,3 4,0 4,6",
|
||||
'N' => "0,6 0,0 4,6 4,0",
|
||||
'O' => "1,0 3,0 4,1 4,5 3,6 1,6 0,5 0,1 1,0",
|
||||
'P' => "0,6 0,0 3,0 4,1 4,2 3,3 0,3",
|
||||
'Q' => "1,0 3,0 4,1 4,5 3,6 1,6 0,5 0,1 1,0; 2.5,4.5 4,6.3",
|
||||
'R' => "0,6 0,0 3,0 4,1 4,2 3,3 0,3; 2,3 4,6",
|
||||
'S' => "4,1 3,0 1,0 0,1 0,2 1,3 3,3 4,4 4,5 3,6 1,6 0,5",
|
||||
'T' => "0,0 4,0; 2,0 2,6",
|
||||
'U' => "0,0 0,5 1,6 3,6 4,5 4,0",
|
||||
'V' => "0,0 2,6 4,0",
|
||||
'W' => "0,0 1,6 2,2 3,6 4,0",
|
||||
'X' => "0,0 4,6; 4,0 0,6",
|
||||
'Y' => "0,0 2,3 4,0; 2,3 2,6",
|
||||
'Z' => "0,0 4,0 0,6 4,6",
|
||||
':' => "2,2; 2,5",
|
||||
';' => "2,2; 2,5 1.5,6.8",
|
||||
'.' => "2,6",
|
||||
',' => "2,5.6 1.5,6.8",
|
||||
'-' => "1,3.5 3,3.5",
|
||||
'+' => "0.5,3.5 3.5,3.5; 2,2 2,5",
|
||||
'/' => "4,0 0,6",
|
||||
'(' => "2.5,-0.3 1.5,1.2 1.5,4.8 2.5,6.3",
|
||||
')' => "1.5,-0.3 2.5,1.2 2.5,4.8 1.5,6.3",
|
||||
'\'' => "2,0 2,1.5",
|
||||
'"' => "1.4,0 1.4,1.5; 2.6,0 2.6,1.5",
|
||||
'!' => "2,0 2,4.2; 2,6",
|
||||
'?' => "0,1 1,0 3,0 4,1 4,2 2,3.5 2,4.4; 2,6",
|
||||
'%' => "0,6 4,0; 0.6,0.6; 3.4,5.4",
|
||||
'=' => "0.5,2.5 3.5,2.5; 0.5,4.5 3.5,4.5",
|
||||
'#' => "1.3,0.5 1,5.5; 3,0.5 2.7,5.5; 0,2 4,2; 0,4 4,4",
|
||||
'&' => "4,6 1,2 1,0.8 1.8,0 2.8,0.8 2.8,1.8 0,4 0,5.2 1,6 2.5,6 4,4",
|
||||
'*' => "2,1 2,4; 0.7,1.8 3.3,3.2; 3.3,1.8 0.7,3.2",
|
||||
'_' => "0,6.5 4,6.5",
|
||||
'<' => "4,1 0,3.5 4,6",
|
||||
'>' => "0,1 4,3.5 0,6",
|
||||
'@' => "3,4 3,2 1.8,2 1.2,3 1.8,4 3,4 4,3.5 4,1 3,0 1,0 0,1 0,5 1,6 3.5,6",
|
||||
'$' => "4,1 3,0.5 1,0.5 0,1.5 1,3 3,3 4,4.5 3,5.5 1,5.5 0,5; 2,-0.3 2,6.3",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_glyph(c: char) -> Vec<Vec<[f64; 2]>> {
|
||||
glyph_src(c)
|
||||
.split(';')
|
||||
.map(|s| {
|
||||
s.split_whitespace()
|
||||
.filter_map(|pt| {
|
||||
let (x, y) = pt.split_once(',')?;
|
||||
Some([x.parse().ok()?, y.parse().ok()?])
|
||||
})
|
||||
.collect::<Vec<[f64; 2]>>()
|
||||
})
|
||||
.filter(|v| !v.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Advance width in grid units (glyph ink + 1.6 units of side bearing).
|
||||
fn advance(c: char, proportional: bool) -> f64 {
|
||||
if c == ' ' {
|
||||
return 3.0;
|
||||
}
|
||||
if !proportional {
|
||||
return 5.6;
|
||||
}
|
||||
let g = parse_glyph(c);
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
for s in &g {
|
||||
for q in s {
|
||||
lo = lo.min(q[0]);
|
||||
hi = hi.max(q[0]);
|
||||
}
|
||||
}
|
||||
if lo > hi { 3.0 } else { (hi - lo) + 1.6 }
|
||||
}
|
||||
|
||||
/// Left ink edge of a glyph (so proportional glyphs start at their ink).
|
||||
fn ink_left(c: char, proportional: bool) -> f64 {
|
||||
if !proportional {
|
||||
return 0.8;
|
||||
}
|
||||
parse_glyph(c).iter().flatten().map(|q| q[0]).fold(f64::INFINITY, f64::min).min(4.0) - 0.8
|
||||
}
|
||||
|
||||
/// Text metrics: grid unit in px for a font size (cap height ≈ 0.7 em) and stroke radius.
|
||||
fn unit(size: f64) -> f64 {
|
||||
size * 0.7 / 6.0
|
||||
}
|
||||
fn weight(size: f64) -> f64 {
|
||||
(size * 0.045).max(0.35)
|
||||
}
|
||||
|
||||
/// Width of a line of text in px (tracking in px between characters).
|
||||
fn line_width(text: &str, size: f64, tracking: f64, proportional: bool) -> f64 {
|
||||
let u = unit(size);
|
||||
let n = text.chars().count();
|
||||
if n == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
text.chars().map(|c| advance(c, proportional) * u).sum::<f64>() + tracking * (n as f64 - 1.0) - 1.6 * u
|
||||
}
|
||||
|
||||
/// Polylines (px) of a line of text whose baseline starts at `origin`.
|
||||
fn layout_line(text: &str, origin: [f64; 2], size: f64, tracking: f64, proportional: bool, out: &mut Vec<Vec<[f64; 2]>>) {
|
||||
let u = unit(size);
|
||||
let mut x = origin[0];
|
||||
for c in text.chars() {
|
||||
let left = ink_left(c, proportional);
|
||||
for s in parse_glyph(c) {
|
||||
out.push(s.iter().map(|q| [x + (q[0] - left - 0.8) * u, origin[1] + (q[1] - 6.0) * u]).collect());
|
||||
}
|
||||
x += advance(c, proportional) * u + tracking;
|
||||
}
|
||||
}
|
||||
|
||||
/// How text paints: fill/stroke display option, colours, and compositing.
|
||||
struct TextLook {
|
||||
display: u32,
|
||||
fill: [f32; 4],
|
||||
stroke: [f32; 4],
|
||||
stroke_w: f64,
|
||||
on_original: bool,
|
||||
opacity: f32,
|
||||
}
|
||||
|
||||
fn over(dst: Px, src: Px) -> Px {
|
||||
let k = 1.0 - src[3];
|
||||
[src[0] + dst[0] * k, src[1] + dst[1] * k, src[2] + dst[2] * k, src[3] + dst[3] * k]
|
||||
}
|
||||
|
||||
fn tint(c: [f32; 4], a: f32) -> Px {
|
||||
let a = (a * c[3]).clamp(0.0, 1.0);
|
||||
[c[0] * a, c[1] * a, c[2] * a, a]
|
||||
}
|
||||
|
||||
/// Draw text polylines with the given look (`r` = glyph stroke radius in px).
|
||||
fn draw_text(b: &mut Buf, polys: &[Vec<[f64; 2]>], r: f64, look: &TextLook) {
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let segs_at = |rad: f64| {
|
||||
let mut s = Vec::new();
|
||||
for pl in polys {
|
||||
poly_segs(pl, false, rad.max(0.05), 1.0, &mut s);
|
||||
}
|
||||
s
|
||||
};
|
||||
let fill = raster_segs(w, h, &segs_at(r), 1.0);
|
||||
let sw = look.stroke_w.max(0.0);
|
||||
let ring = if look.display == 0 || sw <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
let outer = raster_segs(w, h, &segs_at(r + sw * 0.5), 1.0);
|
||||
let inner = if r - sw * 0.5 > 0.05 { raster_segs(w, h, &segs_at(r - sw * 0.5), 1.0) } else { Plane::new(w, h) };
|
||||
Some(outer.zip_map(&inner, |a, b| (a - b).max(0.0)))
|
||||
};
|
||||
let op = look.opacity;
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let mut out = if look.on_original { *px } else { [0.0; 4] };
|
||||
let f = fill.data[i] * op;
|
||||
let s = ring.as_ref().map(|r| r.data[i]).unwrap_or(0.0) * op;
|
||||
match look.display {
|
||||
1 => out = over(out, tint(look.stroke, s)),
|
||||
2 => {
|
||||
out = over(out, tint(look.stroke, s));
|
||||
out = over(out, tint(look.fill, f));
|
||||
}
|
||||
3 => {
|
||||
out = over(out, tint(look.fill, f));
|
||||
out = over(out, tint(look.stroke, s));
|
||||
}
|
||||
_ => out = over(out, tint(look.fill, f)),
|
||||
}
|
||||
*px = out;
|
||||
});
|
||||
}
|
||||
|
||||
fn look_from(ctx: &EffectCtx, b: &Buf, on_original_id: &str) -> TextLook {
|
||||
let pr = ctx.params;
|
||||
TextLook {
|
||||
display: pr.e("displayOptions"),
|
||||
fill: pr.color("fillColor"),
|
||||
stroke: pr.color("strokeColor"),
|
||||
stroke_w: pr.f("strokeWidth") * b.scale,
|
||||
on_original: pr.b(on_original_id),
|
||||
opacity: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Numbers
|
||||
|
||||
const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||
const DAYS: [&str; 7] = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
|
||||
|
||||
/// Proleptic Gregorian date from a day count since 2000-01-01 (a Saturday).
|
||||
fn date_from_days(days: i64) -> (i64, u32, u32, usize) {
|
||||
// Days since 0000-03-01 based civil calendar conversion.
|
||||
let z = days + 730_425; // 2000-01-01 relative to 0000-03-01
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
let y = if m <= 2 { y + 1 } else { y };
|
||||
(y, m, d, days.rem_euclid(7) as usize)
|
||||
}
|
||||
|
||||
fn timecode(frames: i64, fps: f64) -> String {
|
||||
let fr = fps.round().max(1.0) as i64;
|
||||
let neg = frames < 0;
|
||||
let f = frames.abs();
|
||||
let s = format!("{:02}:{:02}:{:02}:{:02}", f / (fr * 3600), (f / (fr * 60)) % 60, (f / fr) % 60, f % fr);
|
||||
if neg { format!("-{s}") } else { s }
|
||||
}
|
||||
|
||||
fn numbers_text(ctx: &EffectCtx) -> String {
|
||||
let pr = ctx.params;
|
||||
let kind = pr.e("type");
|
||||
let dp = pr.f("decimalPlaces").round().clamp(0.0, 10.0) as usize;
|
||||
let mut v = pr.f("value");
|
||||
if pr.b("randomValues") {
|
||||
let frame = (ctx.time * ctx.fps()).floor() as i64 as u32;
|
||||
v = hash1(frame, 17, ctx.seed) as f64 * pr.f("value");
|
||||
}
|
||||
let cur = pr.b("currentTimeDate");
|
||||
let t = if cur { ctx.time + v } else { v };
|
||||
match kind {
|
||||
1 => {
|
||||
let s = format!("{:.*}", dp, v.abs());
|
||||
let (ip, fp) = s.split_once('.').map(|(a, b)| (a.to_string(), format!(".{b}"))).unwrap_or((s.clone(), String::new()));
|
||||
format!("{}{:0>5}{}", if v < 0.0 { "-" } else { "" }, ip, fp)
|
||||
}
|
||||
2..=4 => {
|
||||
let fps = [30.0, 25.0, 24.0][(kind - 2) as usize];
|
||||
timecode((t * fps + 1e-6).floor() as i64, fps)
|
||||
}
|
||||
5 => {
|
||||
let s = t.floor() as i64;
|
||||
let a = s.abs();
|
||||
format!("{}{:02}:{:02}:{:02}", if s < 0 { "-" } else { "" }, a / 3600, (a / 60) % 60, a % 60)
|
||||
}
|
||||
6..=8 => {
|
||||
let (y, m, d, wd) = date_from_days(v.floor() as i64);
|
||||
match kind {
|
||||
6 => format!("{:02}/{:02}/{:02}", m, d, y.rem_euclid(100)),
|
||||
7 => format!("{} {}, {}", &MONTHS[m as usize - 1][..3], d, y),
|
||||
_ => format!("{}, {} {}, {}", DAYS[wd], MONTHS[m as usize - 1], d, y),
|
||||
}
|
||||
}
|
||||
9 => {
|
||||
let i = v.round() as i64;
|
||||
if i < 0 { format!("-{:X}", -i) } else { format!("{i:X}") }
|
||||
}
|
||||
_ => format!("{:.*}", dp, if cur { t } else { v }),
|
||||
}
|
||||
}
|
||||
|
||||
fn numbers(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let text = numbers_text(ctx);
|
||||
let size = (pr.f("size") * b.scale).max(0.5);
|
||||
let tracking = pr.f("tracking") * b.scale;
|
||||
let prop = pr.b("proportionalSpacing");
|
||||
let pos = b.to_px(pr.v2("position"));
|
||||
let wdt = line_width(&text, size, tracking, prop);
|
||||
let mut polys = Vec::new();
|
||||
layout_line(&text, [pos.0 - wdt * 0.5, pos.1 + unit(size) * 3.0], size, tracking, prop, &mut polys);
|
||||
let look = look_from(ctx, &b, "compositeOnOriginal");
|
||||
draw_text(&mut b, &polys, weight(size), &look);
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Timecode
|
||||
|
||||
/// SMPTE drop-frame label for nominal 30/60 fps rates.
|
||||
fn drop_frame(frames: i64, nominal: i64) -> String {
|
||||
let drop = nominal / 15; // 2 at 30, 4 at 60
|
||||
let per_min = nominal * 60 - drop;
|
||||
let per_10 = per_min * 10 + drop;
|
||||
let f = frames.max(0);
|
||||
let d = f / per_10;
|
||||
let m = f % per_10;
|
||||
let adj = if m > drop { f + drop * 9 * d + drop * ((m - drop) / per_min) } else { f + drop * 9 * d };
|
||||
format!("{:02};{:02};{:02};{:02}", adj / (nominal * 3600), (adj / (nominal * 60)) % 60, (adj / nominal) % 60, adj % nominal)
|
||||
}
|
||||
|
||||
fn timecode_fx(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let src = pr.e("timeSource");
|
||||
let (t, fps) = match src {
|
||||
1 => (ctx.env.comp_time, ctx.fps()),
|
||||
2 => (ctx.time, pr.f("timeUnits").max(1.0)),
|
||||
_ => (ctx.time, ctx.fps()),
|
||||
};
|
||||
let mut frame = (t * fps + 1e-6).floor() as i64;
|
||||
if src == 2 {
|
||||
frame += pr.f("startingFrame").round() as i64;
|
||||
}
|
||||
let nominal = fps.round() as i64;
|
||||
let text = match pr.e("displayFormat") {
|
||||
1 => format!("{frame}"),
|
||||
2 => format!("{}+{:02}", frame.div_euclid(16), frame.rem_euclid(16)),
|
||||
3 => format!("{}+{:02}", frame.div_euclid(40), frame.rem_euclid(40)),
|
||||
_ => {
|
||||
if pr.b("dropFrame") && (nominal == 30 || nominal == 60) {
|
||||
drop_frame(frame, nominal)
|
||||
} else {
|
||||
timecode(frame, fps)
|
||||
}
|
||||
}
|
||||
};
|
||||
let size = (pr.f("textSize") * b.scale).max(0.5);
|
||||
let pos = b.to_px(pr.v2("textPosition"));
|
||||
let wdt = line_width(&text, size, 0.0, false);
|
||||
let op = (pr.f("opacity") / 100.0) as f32;
|
||||
if !pr.b("renderOnOriginal") {
|
||||
b.img = Image::new(b.img.width, b.img.height);
|
||||
}
|
||||
if pr.b("showBox") {
|
||||
let bc = pr.color("boxColor");
|
||||
let pad = size * 0.25;
|
||||
let (x0, x1) = (pos.0 - wdt * 0.5 - pad, pos.0 + wdt * 0.5 + pad);
|
||||
let (y0, y1) = (pos.1 - size * 0.5, pos.1 + size * 0.5);
|
||||
let a = op * bc[3];
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
let fy = y as f64 + 0.5;
|
||||
let cy = ((fy - y0 + 0.5).clamp(0.0, 1.0) * (y1 - fy + 0.5).clamp(0.0, 1.0)) as f32;
|
||||
if cy <= 0.0 {
|
||||
return;
|
||||
}
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let fx = x as f64 + 0.5;
|
||||
let cx = ((fx - x0 + 0.5).clamp(0.0, 1.0) * (x1 - fx + 0.5).clamp(0.0, 1.0)) as f32;
|
||||
let k = cx * cy * a;
|
||||
if k > 0.0 {
|
||||
*px = over(*px, [bc[0] * k, bc[1] * k, bc[2] * k, k]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut polys = Vec::new();
|
||||
layout_line(&text, [pos.0 - wdt * 0.5, pos.1 + unit(size) * 3.0], size, 0.0, false, &mut polys);
|
||||
let look = TextLook { display: 0, fill: pr.color("textColor"), stroke: [0.0; 4], stroke_w: 0.0, on_original: true, opacity: op };
|
||||
draw_text(&mut b, &polys, weight(size), &look);
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Basic Text
|
||||
|
||||
fn basic_text(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let size = (pr.f("size") * b.scale).max(0.5);
|
||||
let tracking = pr.f("tracking") * b.scale;
|
||||
let lead = size * pr.f("lineSpacing") / 100.0 * 1.2;
|
||||
let pos = b.to_px(pr.v2("position"));
|
||||
let align = pr.e("alignment");
|
||||
let lines: Vec<&str> = pr.s("text").split(['\n', '\r']).collect();
|
||||
let n = lines.len() as f64;
|
||||
let mut polys = Vec::new();
|
||||
for (i, l) in lines.iter().enumerate() {
|
||||
let wdt = line_width(l, size, tracking, true);
|
||||
let x = match align {
|
||||
0 => pos.0,
|
||||
2 => pos.0 - wdt,
|
||||
_ => pos.0 - wdt * 0.5,
|
||||
};
|
||||
let y = pos.1 + unit(size) * 3.0 + (i as f64 - (n - 1.0) * 0.5) * lead;
|
||||
layout_line(l, [x, y], size, tracking, true, &mut polys);
|
||||
}
|
||||
let look = look_from(ctx, &b, "compositeOnOriginal");
|
||||
draw_text(&mut b, &polys, weight(size), &look);
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Path Text
|
||||
|
||||
fn path_text(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let px = |id: &str| {
|
||||
let q = b.to_px(pr.v2(id));
|
||||
[q.0, q.1]
|
||||
};
|
||||
let (mut path, mut closed) = match mask_px(ctx, &b, pr.f("customPath").round() as usize) {
|
||||
Some((p, c, _)) => (p, c),
|
||||
None => match pr.e("shapeType") {
|
||||
1 | 2 => {
|
||||
let c = px("vertex1");
|
||||
let s = px("tangent1");
|
||||
let r = ((s[0] - c[0]).powi(2) + (s[1] - c[1]).powi(2)).sqrt().max(1.0);
|
||||
let a0 = (s[1] - c[1]).atan2(s[0] - c[0]);
|
||||
let n = 128;
|
||||
(
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let a = a0 + 2.0 * PI * i as f64 / n as f64;
|
||||
[c[0] + a.cos() * r, c[1] + a.sin() * r]
|
||||
})
|
||||
.collect(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
3 => (vec![px("vertex1"), px("vertex2")], false),
|
||||
_ => {
|
||||
let (v1, t1, t2, v2) = (px("vertex1"), px("tangent1"), px("tangent2"), px("vertex2"));
|
||||
(
|
||||
(0..=64)
|
||||
.map(|i| {
|
||||
let t = i as f64 / 64.0;
|
||||
let u = 1.0 - t;
|
||||
let f = |k: usize| u * u * u * v1[k] + 3.0 * u * u * t * t1[k] + 3.0 * u * t * t * t2[k] + t * t * t * v2[k];
|
||||
[f(0), f(1)]
|
||||
})
|
||||
.collect(),
|
||||
false,
|
||||
)
|
||||
}
|
||||
},
|
||||
};
|
||||
if pr.b("reversePath") {
|
||||
path.reverse();
|
||||
}
|
||||
if path.len() < 2 {
|
||||
closed = false;
|
||||
}
|
||||
let len = poly_length(&path, closed);
|
||||
let text: String = pr.s("text").chars().take(pr.f("visibleCharacters").max(0.0) as usize).collect();
|
||||
let size = (pr.f("size") * b.scale).max(0.5);
|
||||
let u = unit(size);
|
||||
let tracking = pr.f("tracking") * b.scale;
|
||||
let lm = pr.f("leftMargin") * b.scale;
|
||||
let rm = pr.f("rightMargin") * b.scale;
|
||||
let shift = pr.f("baselineShift") * b.scale;
|
||||
let rot = pr.f("characterRotation").to_radians();
|
||||
let n = text.chars().count();
|
||||
let advs: Vec<f64> = text.chars().map(|c| advance(c, true) * u).collect();
|
||||
let natural: f64 = advs.iter().sum::<f64>() + tracking * (n.max(1) as f64 - 1.0);
|
||||
let avail = (len - lm - rm).max(0.0);
|
||||
let (mut cursor, extra) = match pr.e("alignment") {
|
||||
1 => (len - rm - natural, 0.0),
|
||||
2 => (lm + (avail - natural) * 0.5, 0.0),
|
||||
3 => (lm, if n > 1 { (avail - natural) / (n as f64 - 1.0) } else { 0.0 }),
|
||||
_ => (lm, 0.0),
|
||||
};
|
||||
let mut polys = Vec::new();
|
||||
for (c, adv) in text.chars().zip(advs) {
|
||||
let mid = cursor + adv * 0.5;
|
||||
cursor += adv + tracking + extra;
|
||||
if !closed && (mid < 0.0 || mid > len) {
|
||||
continue;
|
||||
}
|
||||
let (q, d) = poly_point_at(&path, closed, if closed { mid.rem_euclid(len.max(1e-9)) } else { mid });
|
||||
let ang = d[1].atan2(d[0]) + rot;
|
||||
let (s, co) = ang.sin_cos();
|
||||
let left = ink_left(c, true);
|
||||
for st in parse_glyph(c) {
|
||||
polys.push(
|
||||
st.iter()
|
||||
.map(|g| {
|
||||
let lx = (g[0] - left - 0.8) * u - adv * 0.5 + 0.8 * u;
|
||||
let ly = (g[1] - 6.0) * u - shift;
|
||||
[q[0] + lx * co - ly * s, q[1] + lx * s + ly * co]
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let look = look_from(ctx, &b, "compositeOnOriginal");
|
||||
draw_text(&mut b, &polys, weight(size), &look);
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Lightning (obsolete)
|
||||
|
||||
/// Smooth 1-D value noise in [-1, 1].
|
||||
fn vnoise(i: u32, t: f64, seed: u32) -> f64 {
|
||||
let k = t.floor();
|
||||
let f = t - k;
|
||||
let a = hash1(i, k as i64 as u32, seed) as f64 * 2.0 - 1.0;
|
||||
let c = hash1(i, (k as i64 + 1) as u32, seed) as f64 * 2.0 - 1.0;
|
||||
let s = f * f * (3.0 - 2.0 * f);
|
||||
a + (c - a) * s
|
||||
}
|
||||
|
||||
struct Bolt<'a> {
|
||||
seed: u32,
|
||||
phase: f64,
|
||||
stability: f64,
|
||||
detail: u32,
|
||||
detail_amp: f64,
|
||||
pull: [f64; 2],
|
||||
out: &'a mut Vec<Seg>,
|
||||
counter: u32,
|
||||
}
|
||||
|
||||
impl Bolt<'_> {
|
||||
/// One bolt from `a` to `z` with `n` segments of amplitude `amp`; returns its points.
|
||||
fn path(&mut self, a: [f64; 2], z: [f64; 2], n: usize, amp: f64, fixed_end: bool) -> Vec<[f64; 2]> {
|
||||
let (dx, dy) = (z[0] - a[0], z[1] - a[1]);
|
||||
let len = (dx * dx + dy * dy).sqrt().max(1e-9);
|
||||
let nrm = [-dy / len, dx / len];
|
||||
let id = self.counter;
|
||||
self.counter += 1;
|
||||
let mut pts = Vec::with_capacity(n + 1);
|
||||
for i in 0..=n {
|
||||
let t = i as f64 / n as f64;
|
||||
let env = if fixed_end { (t * PI).sin() } else { t.sqrt() };
|
||||
let off = vnoise(id * 1000 + i as u32, self.phase * (1.0 - self.stability * 0.9) + i as f64 * 0.37, self.seed) * amp * env;
|
||||
let pull = t * t * len * 0.25;
|
||||
pts.push([a[0] + dx * t + nrm[0] * off + self.pull[0] * pull, a[1] + dy * t + nrm[1] * off + self.pull[1] * pull]);
|
||||
}
|
||||
// Detail: midpoint displacement.
|
||||
for lvl in 0..self.detail {
|
||||
let mut nx = Vec::with_capacity(pts.len() * 2);
|
||||
for (j, w) in pts.windows(2).enumerate() {
|
||||
let (p0, p1) = (w[0], w[1]);
|
||||
let (ex, ey) = (p1[0] - p0[0], p1[1] - p0[1]);
|
||||
let l = (ex * ex + ey * ey).sqrt();
|
||||
let o = vnoise(id * 7919 + lvl * 131 + j as u32, self.phase * 1.7 + j as f64 * 0.61, self.seed ^ 0x55) * l * self.detail_amp;
|
||||
nx.push(p0);
|
||||
nx.push([(p0[0] + p1[0]) * 0.5 - ey / l.max(1e-9) * o, (p0[1] + p1[1]) * 0.5 + ex / l.max(1e-9) * o]);
|
||||
}
|
||||
nx.push(*pts.last().unwrap_or(&a));
|
||||
pts = nx;
|
||||
}
|
||||
pts
|
||||
}
|
||||
}
|
||||
|
||||
fn lightning(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let s = b.to_px(pr.v2("startPoint"));
|
||||
let e = b.to_px(pr.v2("endPoint"));
|
||||
let sc = b.scale;
|
||||
let rerun = pr.b("rerunAtEachFrame");
|
||||
let speed = pr.f("speed");
|
||||
let frame = (ctx.time * ctx.fps()).floor();
|
||||
let seed = (pr.f("randomSeed") as i64 as u32) ^ ctx.seed ^ if rerun { (frame as i64 as u32).wrapping_mul(2_654_435_761) } else { 0 };
|
||||
let phase = if rerun { 0.0 } else { ctx.time * speed * 0.25 };
|
||||
let pd = (pr.f("pullDirection") - 90.0).to_radians();
|
||||
let pf = pr.f("pullForce") / 100.0;
|
||||
let width = (pr.f("width") * sc).max(0.2);
|
||||
let wvar = pr.f("widthVariation").clamp(0.0, 1.0);
|
||||
let core = pr.f("coreWidth").clamp(0.0, 1.0);
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
let mut bolt = Bolt {
|
||||
seed,
|
||||
phase,
|
||||
stability: pr.f("stability").clamp(0.0, 1.0),
|
||||
detail: pr.f("detailLevel").round().clamp(0.0, 6.0) as u32,
|
||||
detail_amp: pr.f("detailAmplitude").clamp(0.0, 1.0) * 0.5,
|
||||
pull: [pd.cos() * pf, pd.sin() * pf],
|
||||
out: &mut segs,
|
||||
counter: 0,
|
||||
};
|
||||
let nseg = pr.f("segments").round().clamp(1.0, 64.0) as usize;
|
||||
let amp = pr.f("amplitude") * sc;
|
||||
let main = bolt.path([s.0, s.1], [e.0, e.1], nseg, amp, pr.b("fixedEndpoint"));
|
||||
let branching = pr.f("branching").clamp(0.0, 1.0);
|
||||
let rebranch = pr.f("rebranching").clamp(0.0, 1.0);
|
||||
let bang = pr.f("branchAngle").to_radians();
|
||||
let bseg_len = pr.f("branchSegLength").max(0.0);
|
||||
let bsegs = pr.f("branchSegments").round().clamp(1.0, 32.0) as usize;
|
||||
let bwidth = pr.f("branchWidth").clamp(0.0, 1.0);
|
||||
let main_len = poly_length(&main, false);
|
||||
let seg_len = main_len / nseg as f64;
|
||||
let mut lines: Vec<(Vec<[f64; 2]>, f64)> = vec![(main.clone(), 1.0)];
|
||||
let mut queue: Vec<(Vec<[f64; 2]>, f64, u32)> = vec![(main, 1.0, 0)];
|
||||
while let Some((pts, w, depth)) = queue.pop() {
|
||||
if depth >= 3 || lines.len() > 256 {
|
||||
continue;
|
||||
}
|
||||
let prob = if depth == 0 { branching } else { rebranch };
|
||||
for (i, wpair) in pts.windows(2).enumerate() {
|
||||
if hash1(i as u32 + depth * 977, lines.len() as u32, seed ^ 0xB7) as f64 >= prob * 0.35 {
|
||||
continue;
|
||||
}
|
||||
let (p0, p1) = (wpair[0], wpair[1]);
|
||||
let base = (p1[1] - p0[1]).atan2(p1[0] - p0[0]);
|
||||
let side = if hash1(i as u32, depth + 3, seed) < 0.5 { -1.0 } else { 1.0 };
|
||||
let a = base + side * bang * (0.5 + hash1(i as u32, depth + 9, seed) as f64);
|
||||
let l = seg_len * bseg_len * bsegs as f64;
|
||||
let z = [p0[0] + a.cos() * l, p0[1] + a.sin() * l];
|
||||
let br = bolt.path(p0, z, bsegs, amp * 0.5, false);
|
||||
let bw = w * bwidth;
|
||||
lines.push((br.clone(), bw));
|
||||
queue.push((br, bw, depth + 1));
|
||||
}
|
||||
}
|
||||
for (li, (pts, w)) in lines.iter().enumerate() {
|
||||
for (i, wpair) in pts.windows(2).enumerate() {
|
||||
let v = 1.0 - wvar * hash1(i as u32, li as u32, seed ^ 0x77) as f64;
|
||||
bolt.out.push(Seg { a: wpair[0], b: wpair[1], r: width * 0.5 * w * v, v: 1.0 });
|
||||
}
|
||||
}
|
||||
let (wd, ht) = (b.img.width as usize, b.img.height as usize);
|
||||
let outer = raster_segs(wd, ht, &segs, 0.0);
|
||||
let core_segs: Vec<Seg> = segs.iter().map(|g| Seg { r: (g.r * core).max(0.3), ..*g }).collect();
|
||||
let inner = raster_segs(wd, ht, &core_segs, 0.6);
|
||||
let glow = gauss_plane(&outer, width * 0.5, width * 0.5);
|
||||
let oc = pr.color("outsideColor");
|
||||
let ic = pr.color("insideColor");
|
||||
let mode = pr.e("blendingMode");
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let o = outer.data[i].max(glow.data[i] * 0.8);
|
||||
let c = inner.data[i];
|
||||
let a = o.max(c).min(1.0);
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let t = if a > 0.0 { c / a } else { 0.0 };
|
||||
let colr = [oc[0] + (ic[0] - oc[0]) * t, oc[1] + (ic[1] - oc[1]) * t, oc[2] + (ic[2] - oc[2]) * t];
|
||||
*px = match mode {
|
||||
1 => [px[0] + colr[0] * a, px[1] + colr[1] * a, px[2] + colr[2] * a, (px[3] + a * (1.0 - px[3])).min(1.0)],
|
||||
2 => {
|
||||
let sc = |d: f32, s: f32| d + s - d * s;
|
||||
[sc(px[0], colr[0] * a), sc(px[1], colr[1] * a), sc(px[2], colr[2] * a), sc(px[3], a)]
|
||||
}
|
||||
_ => over(*px, [colr[0] * a, colr[1] * a, colr[2] * a, a]),
|
||||
};
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- registry
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let ang = || ParamUi::Angle;
|
||||
let check = |id: &'static str, name: &'static str, v: bool| p(id, name, Value::Bool(v), ParamUi::Checkbox);
|
||||
let pt = |x: f64, y: f64| Value::Vec2([x, y]);
|
||||
let display = || popup(&["Fill Only", "Stroke Only", "Fill Over Stroke", "Stroke Over Fill"]);
|
||||
let size = || slider(0.0, 512.0, 0.0, 200.0, 1);
|
||||
vec![
|
||||
spec(
|
||||
"ec.text.numbers",
|
||||
"Numbers",
|
||||
"Text",
|
||||
vec![
|
||||
p(
|
||||
"type",
|
||||
"Format: Type",
|
||||
Value::Enum(0),
|
||||
popup(&[
|
||||
"Number",
|
||||
"Number [Leading Zeros]",
|
||||
"Timecode [30]",
|
||||
"Timecode [25]",
|
||||
"Timecode [24]",
|
||||
"Time",
|
||||
"Numerical Date",
|
||||
"Short Date",
|
||||
"Long Date",
|
||||
"Hexadecimal",
|
||||
]),
|
||||
),
|
||||
check("randomValues", "Format: Random Values", false),
|
||||
p("value", "Format: Value/Offset/Random Max", num(0.0), slider(-30000.0, 30000.0, -1000.0, 1000.0, 3)),
|
||||
p("decimalPlaces", "Format: Decimal Places", num(2.0), slider(0.0, 10.0, 0.0, 10.0, 0)),
|
||||
check("currentTimeDate", "Format: Current Time/Date", false),
|
||||
p("position", "Fill and Stroke: Position", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("displayOptions", "Fill and Stroke: Display Options", Value::Enum(0), display()),
|
||||
p("fillColor", "Fill and Stroke: Fill Color", col(1.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("strokeColor", "Fill and Stroke: Stroke Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("strokeWidth", "Fill and Stroke: Stroke Width", num(2.0), slider(0.0, 50.0, 0.0, 50.0, 1)),
|
||||
p("size", "Size", num(36.0), size()),
|
||||
p("tracking", "Tracking", num(0.0), slider(-100.0, 100.0, -20.0, 50.0, 1)),
|
||||
check("proportionalSpacing", "Proportional Spacing", true),
|
||||
check("compositeOnOriginal", "Composite On Original", true),
|
||||
],
|
||||
numbers,
|
||||
),
|
||||
spec(
|
||||
"ec.text.timecode",
|
||||
"Timecode",
|
||||
"Text",
|
||||
vec![
|
||||
p("displayFormat", "Display Format", Value::Enum(0), popup(&["SMPTE HH:MM:SS:FF", "Frames", "Feet + Frames (35mm)", "Feet + Frames (16mm)"])),
|
||||
p("timeSource", "Time Source", Value::Enum(0), popup(&["Layer Source", "Composition", "Custom"])),
|
||||
p("timeUnits", "Time Units", num(30.0), slider(1.0, 120.0, 1.0, 60.0, 2)),
|
||||
check("dropFrame", "Drop Frame", false),
|
||||
p("startingFrame", "Starting Frame", num(0.0), slider(-1_000_000.0, 1_000_000.0, 0.0, 10_000.0, 0)),
|
||||
p("textPosition", "Text Position", pt(0.5, 0.9), ParamUi::Point),
|
||||
p("textSize", "Text Size", num(36.0), size()),
|
||||
p("textColor", "Text Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
check("showBox", "Show Box", true),
|
||||
p("boxColor", "Box Color", col(0.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("opacity", "Opacity", num(100.0), pct()),
|
||||
check("renderOnOriginal", "Render On Original", true),
|
||||
],
|
||||
timecode_fx,
|
||||
),
|
||||
spec(
|
||||
"ec.obsolete.basictext",
|
||||
"Basic Text",
|
||||
"Obsolete",
|
||||
vec![
|
||||
p("text", "Text", Value::Str("Text".into()), ParamUi::Text),
|
||||
p("alignment", "Alignment", Value::Enum(1), popup(&["Left", "Center", "Right"])),
|
||||
p("position", "Position", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("displayOptions", "Fill and Stroke: Display Options", Value::Enum(0), display()),
|
||||
p("fillColor", "Fill and Stroke: Fill Color", col(1.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("strokeColor", "Fill and Stroke: Stroke Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("strokeWidth", "Fill and Stroke: Stroke Width", num(2.0), slider(0.0, 50.0, 0.0, 50.0, 1)),
|
||||
p("size", "Size", num(36.0), size()),
|
||||
p("tracking", "Tracking", num(0.0), slider(-100.0, 100.0, -20.0, 50.0, 1)),
|
||||
p("lineSpacing", "Line Spacing", num(100.0), slider(0.0, 1000.0, 0.0, 300.0, 1)),
|
||||
check("compositeOnOriginal", "Composite On Original", true),
|
||||
],
|
||||
basic_text,
|
||||
),
|
||||
spec(
|
||||
"ec.obsolete.pathtext",
|
||||
"Path Text",
|
||||
"Obsolete",
|
||||
vec![
|
||||
p("text", "Text", Value::Str("Text".into()), ParamUi::Text),
|
||||
p("shapeType", "Path Options: Shape Type", Value::Enum(0), popup(&["Bezier", "Circle", "Loop", "Line"])),
|
||||
p("tangent1", "Control Points: Tangent 1/Circle Point", pt(0.3, 0.3), ParamUi::Point),
|
||||
p("vertex1", "Control Points: Vertex 1/Circle Center", pt(0.1, 0.6), ParamUi::Point),
|
||||
p("tangent2", "Control Points: Tangent 2", pt(0.7, 0.3), ParamUi::Point),
|
||||
p("vertex2", "Control Points: Vertex 2/Line Right", pt(0.9, 0.6), ParamUi::Point),
|
||||
p("customPath", "Path Options: Custom Path", num(0.0), slider(0.0, 32.0, 0.0, 8.0, 0)),
|
||||
check("reversePath", "Path Options: Reverse Path", false),
|
||||
p("displayOptions", "Fill and Stroke: Options", Value::Enum(0), display()),
|
||||
p("fillColor", "Fill and Stroke: Fill Color", col(1.0, 0.0, 0.0), ParamUi::Color),
|
||||
p("strokeColor", "Fill and Stroke: Stroke Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("strokeWidth", "Fill and Stroke: Stroke Width", num(2.0), slider(0.0, 50.0, 0.0, 50.0, 1)),
|
||||
p("size", "Character: Size", num(36.0), size()),
|
||||
p("tracking", "Character: Tracking", num(0.0), slider(-100.0, 100.0, -20.0, 50.0, 1)),
|
||||
p("characterRotation", "Character: Orientation: Character Rotation", num(0.0), ang()),
|
||||
p("alignment", "Paragraph: Alignment", Value::Enum(0), popup(&["Left", "Right", "Center", "Force"])),
|
||||
p("leftMargin", "Paragraph: Left Margin", num(0.0), slider(-10000.0, 10000.0, -500.0, 500.0, 1)),
|
||||
p("rightMargin", "Paragraph: Right Margin", num(0.0), slider(-10000.0, 10000.0, -500.0, 500.0, 1)),
|
||||
p("baselineShift", "Paragraph: Baseline Shift", num(0.0), slider(-1000.0, 1000.0, -100.0, 100.0, 1)),
|
||||
p("visibleCharacters", "Advanced: Visible Characters", num(1024.0), slider(0.0, 1024.0, 0.0, 1024.0, 0)),
|
||||
check("compositeOnOriginal", "Composite On Original", true),
|
||||
],
|
||||
path_text,
|
||||
),
|
||||
spec(
|
||||
"ec.obsolete.lightning",
|
||||
"Lightning",
|
||||
"Obsolete",
|
||||
vec![
|
||||
p("startPoint", "Start Point", pt(0.1, 0.5), ParamUi::Point),
|
||||
p("endPoint", "End Point", pt(0.9, 0.5), ParamUi::Point),
|
||||
p("segments", "Segments", num(7.0), slider(1.0, 64.0, 1.0, 32.0, 0)),
|
||||
p("amplitude", "Amplitude", num(10.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("detailLevel", "Detail Level", num(2.0), slider(0.0, 6.0, 0.0, 6.0, 0)),
|
||||
p("detailAmplitude", "Detail Amplitude", num(0.3), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("branching", "Branching", num(0.4), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("rebranching", "Rebranching", num(0.3), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("branchAngle", "Branch Angle", num(20.0), ang()),
|
||||
p("branchSegLength", "Branch Seg. Length", num(0.5), slider(0.0, 2.0, 0.0, 2.0, 3)),
|
||||
p("branchSegments", "Branch Segments", num(4.0), slider(1.0, 32.0, 1.0, 16.0, 0)),
|
||||
p("branchWidth", "Branch Width", num(0.7), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("speed", "Speed", num(10.0), slider(-100.0, 100.0, -50.0, 50.0, 1)),
|
||||
p("stability", "Stability", num(0.3), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
check("fixedEndpoint", "Fixed Endpoint", true),
|
||||
p("width", "Width", num(10.0), slider(0.0, 100.0, 0.0, 50.0, 1)),
|
||||
p("widthVariation", "Width Variation", num(0.25), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("coreWidth", "Core Width", num(0.4), slider(0.0, 1.0, 0.0, 1.0, 3)),
|
||||
p("outsideColor", "Outside Color", col(0.36, 0.25, 0.9), ParamUi::Color),
|
||||
p("insideColor", "Inside Color", col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("pullForce", "Pull Force", num(0.0), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
p("pullDirection", "Pull Direction", num(0.0), ang()),
|
||||
p("randomSeed", "Random Seed", num(1.0), slider(0.0, 10000.0, 0.0, 100.0, 0)),
|
||||
p("blendingMode", "Blending Mode", Value::Enum(0), popup(&["Normal", "Add", "Screen"])),
|
||||
check("rerunAtEachFrame", "Rerun At Each Frame", false),
|
||||
],
|
||||
lightning,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, MaskShape, Params};
|
||||
|
||||
fn run_env(id: &str, set: &[(&str, Value)], img: Image, time: f64, env: EffectEnv) -> Buf {
|
||||
let s = crate::find(id).unwrap();
|
||||
let ls = [img.width as f64, img.height as f64];
|
||||
let mut params = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
for p in &s.params {
|
||||
if let (ParamUi::Point, Value::Vec2(v)) = (&p.ui, &p.default) {
|
||||
params.values.insert(p.id.to_string(), Value::Vec2([v[0] * ls[0], v[1] * ls[1]]));
|
||||
}
|
||||
}
|
||||
for (k, v) in set {
|
||||
assert!(params.values.contains_key(*k), "{id}: unknown {k}");
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time, layer_size: ls, seed: 3, adjustment: false, env };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
fn run(id: &str, set: &[(&str, Value)], img: Image, time: f64) -> Buf {
|
||||
run_env(id, set, img, time, EffectEnv::default())
|
||||
}
|
||||
|
||||
fn ink(img: &Image) -> f32 {
|
||||
img.data.iter().map(|p| p[3]).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_glyph_parses_within_grid() {
|
||||
for c in (b'!'..=b'~').map(|c| c as char) {
|
||||
for s in parse_glyph(c) {
|
||||
for q in s {
|
||||
assert!((-0.5..=4.5).contains(&q[0]) && (-0.5..=7.0).contains(&q[1]), "{c}: {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(!parse_glyph('A').is_empty() && !parse_glyph('a').is_empty() && parse_glyph(' ').is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_formats() {
|
||||
let params = |vals: &[(&str, Value)]| {
|
||||
let s = crate::find("ec.text.numbers").unwrap();
|
||||
let mut p = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
|
||||
for (k, v) in vals {
|
||||
p.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
p
|
||||
};
|
||||
let txt = |vals: &[(&str, Value)], t: f64| {
|
||||
let pr = params(vals);
|
||||
let ctx = EffectCtx { params: &pr, time: t, layer_size: [10.0, 10.0], seed: 1, adjustment: false, env: Default::default() };
|
||||
numbers_text(&ctx)
|
||||
};
|
||||
assert_eq!(txt(&[("value", num(8.0))], 0.0), "8.00");
|
||||
assert_eq!(txt(&[("value", num(42.5)), ("type", Value::Enum(1))], 0.0), "00042.50");
|
||||
assert_eq!(txt(&[("value", num(3661.5)), ("type", Value::Enum(2))], 0.0), "01:01:01:15");
|
||||
assert_eq!(txt(&[("value", num(255.0)), ("type", Value::Enum(9))], 0.0), "FF");
|
||||
assert_eq!(txt(&[("value", num(0.0)), ("type", Value::Enum(6))], 0.0), "01/01/00");
|
||||
assert_eq!(txt(&[("value", num(60.0)), ("type", Value::Enum(8))], 0.0), "Wednesday, March 1, 2000");
|
||||
assert_eq!(txt(&[("value", num(1.0)), ("currentTimeDate", Value::Bool(true)), ("decimalPlaces", num(1.0))], 2.0), "3.0");
|
||||
assert_ne!(
|
||||
txt(&[("value", num(100.0)), ("randomValues", Value::Bool(true))], 0.0),
|
||||
txt(&[("value", num(100.0)), ("randomValues", Value::Bool(true))], 1.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_draws_glyph_at_position() {
|
||||
let img = Image::new(80, 60);
|
||||
let a = run("ec.text.numbers", &[("value", num(8.0)), ("decimalPlaces", num(0.0))], img.clone(), 0.0);
|
||||
assert_eq!(a.img.data, run("ec.text.numbers", &[("value", num(8.0)), ("decimalPlaces", num(0.0))], img.clone(), 0.0).img.data);
|
||||
// Ink only around the centre.
|
||||
let mut inside = 0.0;
|
||||
let mut outside = 0.0;
|
||||
for y in 0..60 {
|
||||
for x in 0..80 {
|
||||
let v = a.img.get(x, y)[3];
|
||||
if (25..55).contains(&x) && (10..50).contains(&y) {
|
||||
inside += v;
|
||||
} else {
|
||||
outside += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(inside > 20.0 && outside < 0.5, "{inside} {outside}");
|
||||
let stroke = run("ec.text.numbers", &[("value", num(8.0)), ("displayOptions", Value::Enum(2))], img, 0.0);
|
||||
assert!(stroke.img.data.iter().any(|p| p[3] > 0.5 && p[1] > 0.5 * p[3]), "white stroke visible");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timecode_changes_over_time() {
|
||||
let img = Image::filled(120, 60, [0.2, 0.2, 0.2, 1.0]);
|
||||
let a = run("ec.text.timecode", &[], img.clone(), 0.0);
|
||||
let b = run("ec.text.timecode", &[], img.clone(), 1.0);
|
||||
assert_eq!(a.img.data, run("ec.text.timecode", &[], img.clone(), 0.0).img.data);
|
||||
assert_ne!(a.img.data, b.img.data);
|
||||
assert_eq!(timecode(30 * 61 + 5, 30.0), "00:01:01:05");
|
||||
assert_eq!(drop_frame(1800, 30), "00;01;00;02");
|
||||
assert_eq!(drop_frame(17982, 30), "00;10;00;00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_text_draws_and_respects_composite() {
|
||||
let img = Image::filled(100, 50, [0.0, 0.0, 1.0, 1.0]);
|
||||
let a = run("ec.obsolete.basictext", &[("text", Value::Str("Hi".into()))], img.clone(), 0.0);
|
||||
assert_eq!(a.img.get(1, 1), [0.0, 0.0, 1.0, 1.0]);
|
||||
assert!(a.img.data.iter().any(|p| p[0] > 0.9));
|
||||
let t = run("ec.obsolete.basictext", &[("text", Value::Str("Hi".into())), ("compositeOnOriginal", Value::Bool(false))], img, 0.0);
|
||||
assert_eq!(t.img.get(1, 1)[3], 0.0);
|
||||
assert!(ink(&t.img) > 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_text_follows_line_and_mask() {
|
||||
let img = Image::new(120, 60);
|
||||
let line = run(
|
||||
"ec.obsolete.pathtext",
|
||||
&[("shapeType", Value::Enum(3)), ("vertex1", Value::Vec2([5.0, 50.0])), ("vertex2", Value::Vec2([115.0, 50.0])), ("size", num(20.0))],
|
||||
img.clone(),
|
||||
0.0,
|
||||
);
|
||||
assert!(ink(&line.img) > 10.0);
|
||||
// Text sits above the baseline at y = 50.
|
||||
let below: f32 = (52..60).flat_map(|y| (0..120).map(move |x| (x, y))).map(|(x, y)| line.img.get(x, y)[3]).sum();
|
||||
assert!(below < 1.0);
|
||||
let masks = vec![MaskShape { name: "M".into(), points: vec![[10.0, 20.0], [110.0, 20.0]], closed: false, inverted: false }];
|
||||
let env = EffectEnv { masks: &masks, ..Default::default() };
|
||||
let m = run_env("ec.obsolete.pathtext", &[("customPath", num(1.0)), ("size", num(20.0))], img.clone(), 0.0, env);
|
||||
let near: f32 = (0..24).flat_map(|y| (0..120).map(move |x| (x, y))).map(|(x, y)| m.img.get(x, y)[3]).sum();
|
||||
assert!(near > 10.0 && (ink(&m.img) - near).abs() < 1.0);
|
||||
let circle = run("ec.obsolete.pathtext", &[("shapeType", Value::Enum(1)), ("text", Value::Str("CIRCLE TEXT".into()))], img, 0.0);
|
||||
assert!(ink(&circle.img) > 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightning_deterministic_and_animates() {
|
||||
let img = Image::new(96, 64);
|
||||
let a = run("ec.obsolete.lightning", &[], img.clone(), 0.5);
|
||||
let b = run("ec.obsolete.lightning", &[], img.clone(), 0.5);
|
||||
assert_eq!(a.img.data, b.img.data);
|
||||
assert!(a.img.get(48, 32)[3] > 0.0 || ink(&a.img) > 50.0);
|
||||
let c = run("ec.obsolete.lightning", &[], img.clone(), 1.5);
|
||||
assert_ne!(a.img.data, c.img.data);
|
||||
let r1 = run("ec.obsolete.lightning", &[("rerunAtEachFrame", Value::Bool(true))], img.clone(), 0.5);
|
||||
let r2 = run("ec.obsolete.lightning", &[("rerunAtEachFrame", Value::Bool(true))], img, 0.5);
|
||||
assert_eq!(r1.img.data, r2.img.data);
|
||||
}
|
||||
}
|
||||
@@ -486,7 +486,8 @@ mod tests {
|
||||
for (k, v) in set {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 7, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 7, adjustment: false, env: Default::default() };
|
||||
(s.render)(&ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 }).img
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
//! Transition effects, batch 2: CC Glass Wipe, CC Image Wipe, CC Jaws, CC Line Sweep,
|
||||
//! CC Twister and CC WarpoMatic.
|
||||
//!
|
||||
//! Written from the public descriptions of these transitions (gradient-driven wipes with glass
|
||||
//! refraction or warping, jagged "jaws" opening, staggered line sweeps, a ribbon twist that
|
||||
//! reveals a back side); the maths is our own. Completion 0 leaves the layer untouched;
|
||||
//! completion 100 leaves it fully transparent (or showing the revealed / back-side layer).
|
||||
|
||||
use effectcraft_color::rgb_to_hsl;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{Plane, fit_layer, gauss_plane, layer_or_self, lerp4, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
fn spec(id: &'static str, name: &'static str, params: Vec<crate::ParamSpec>, render: crate::RenderFn) -> EffectSpec {
|
||||
EffectSpec { id, name, category: "Transition", params, render, gpu: false, float: true }
|
||||
}
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
fn pt(x: f64, y: f64) -> Value {
|
||||
Value::Vec2([x, y])
|
||||
}
|
||||
|
||||
fn completion(ctx: &EffectCtx) -> f32 {
|
||||
(ctx.params.f("completion") / 100.0).clamp(0.0, 1.0) as f32
|
||||
}
|
||||
|
||||
/// The layer in layer parameter `id` fitted to `b`, if one is chosen.
|
||||
fn reveal(ctx: &EffectCtx, b: &Buf, id: &str) -> Option<Image> {
|
||||
ctx.layer_param(id, true).map(|o| fit_layer(ctx, b, &o, false))
|
||||
}
|
||||
|
||||
const GRAD_PROPS: [&str; 7] = ["Red", "Green", "Blue", "Alpha", "Luminance", "Lightness", "Saturation"];
|
||||
|
||||
fn prop_plane(img: &Image, prop: u32) -> Plane {
|
||||
Plane::from_image(img, |p| {
|
||||
let (c, a) = unpremul(p);
|
||||
match prop {
|
||||
0 => c[0] * a,
|
||||
1 => c[1] * a,
|
||||
2 => c[2] * a,
|
||||
3 => a,
|
||||
4 => effectcraft_color::luminance(c[0], c[1], c[2]) * a,
|
||||
5 => rgb_to_hsl(c[0], c[1], c[2]).2 * a,
|
||||
_ => rgb_to_hsl(c[0], c[1], c[2]).1 * a,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Fraction of a pixel with gradient value `g` that has transitioned, for a soft band of
|
||||
/// half-width `w`: none at completion 0, all at completion 1.
|
||||
#[inline]
|
||||
fn wipe_t(g: f32, c: f32, w: f32) -> f32 {
|
||||
let w = w.max(1e-3);
|
||||
let edge = c * (1.0 + 2.0 * w) - w;
|
||||
1.0 - smoothstep(edge - w, edge + w, g)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn grad(pl: &Plane, x: usize, y: usize) -> (f32, f32) {
|
||||
let (xi, yi) = (x as i64, y as i64);
|
||||
((pl.get_clamped(xi + 1, yi) - pl.get_clamped(xi - 1, yi)) * 0.5, (pl.get_clamped(xi, yi + 1) - pl.get_clamped(xi, yi - 1)) * 0.5)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Glass Wipe
|
||||
|
||||
fn glass_wipe(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx);
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let gimg = layer_or_self(ctx, &b, "gradientLayer", true, false);
|
||||
let mut g = prop_plane(&gimg, 4);
|
||||
let soft = (ctx.params.f("softness") / 100.0) as f32;
|
||||
let sm = ctx.params.f("softness") * b.scale * 0.2;
|
||||
if sm > 0.05 {
|
||||
g = gauss_plane(&g, sm, sm);
|
||||
}
|
||||
let disp = (ctx.params.f("displacementAmount") * b.scale * 4.0) as f32;
|
||||
let rev = reveal(ctx, &b, "layerToReveal");
|
||||
let src = b.img.clone();
|
||||
let w = soft * 0.5 + 0.01;
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let t = wipe_t(g.get(x, y), c, w);
|
||||
let band = 4.0 * t * (1.0 - t);
|
||||
let (gx, gy) = grad(&g, x, y);
|
||||
let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let (ox, oy) = ((gx * disp * band) as f64 * 10.0, (gy * disp * band) as f64 * 10.0);
|
||||
let a = if band > 1e-4 { src.sample_bilinear(fx + ox, fy + oy) } else { src.data[y * src.width as usize + x] };
|
||||
let r = match &rev {
|
||||
Some(r) if band > 1e-4 => r.sample_bilinear(fx - ox, fy - oy),
|
||||
Some(r) => r.data[y * r.width as usize + x],
|
||||
None => [0.0; 4],
|
||||
};
|
||||
*px = lerp4(a, r, t);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Image Wipe
|
||||
|
||||
fn image_wipe(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx);
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let gimg = layer_or_self(ctx, &b, "layer", true, false);
|
||||
let mut g = prop_plane(&gimg, ctx.params.e("property"));
|
||||
let bl = ctx.params.f("blur") * b.scale * 0.5;
|
||||
if bl > 0.05 {
|
||||
g = gauss_plane(&g, bl, bl);
|
||||
}
|
||||
if ctx.params.b("inverseGradient") {
|
||||
g = g.map(|v| 1.0 - v);
|
||||
}
|
||||
let mut w = (ctx.params.f("borderSoftness") / 100.0) as f32 * 0.5;
|
||||
if ctx.params.b("autoSoftness") {
|
||||
w = w.max(0.02);
|
||||
}
|
||||
b.img.data.par_iter_mut().zip(g.data.par_iter()).for_each(|(px, &gv)| {
|
||||
let k = 1.0 - wipe_t(gv, c, w);
|
||||
*px = px.map(|v| v * k);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Jaws
|
||||
|
||||
fn jaws(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx) as f64;
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let s = b.scale;
|
||||
let (cx, cy) = b.to_px(ctx.params.v2("center"));
|
||||
let ang = ctx.params.f("direction").to_radians();
|
||||
let (sn, cs) = ang.sin_cos();
|
||||
let width = (ctx.params.f("width") * s).max(1.0);
|
||||
let amp = ctx.params.f("height") / 100.0 * width * 0.5;
|
||||
let shape = ctx.params.e("shape");
|
||||
// Far enough at completion 1 that both halves (teeth included) have left the buffer.
|
||||
let (bw, bh) = (b.img.width as f64, b.img.height as f64);
|
||||
let vmax = [(0.0, 0.0), (bw, 0.0), (0.0, bh), (bw, bh)].iter().map(|&(x, y)| (-(x - cx) * sn + (y - cy) * cs).abs()).fold(0.0, f64::max);
|
||||
let d = c * (vmax + 2.0 * amp + 2.0);
|
||||
// Tooth profile in [-amp, amp] along the cut.
|
||||
let profile = move |u: f64| -> f64 {
|
||||
let ph = (u / width).rem_euclid(1.0);
|
||||
match shape {
|
||||
0 => amp * (1.0 - 4.0 * (ph - 0.5).abs()),
|
||||
1 => {
|
||||
// RoboJaw: square teeth with sloped flanks.
|
||||
let t = (1.0 - 4.0 * (ph - 0.5).abs()) * 2.0;
|
||||
amp * t.clamp(-1.0, 1.0)
|
||||
}
|
||||
2 => {
|
||||
if ph < 0.5 {
|
||||
amp
|
||||
} else {
|
||||
-amp
|
||||
}
|
||||
}
|
||||
_ => amp * (ph * std::f64::consts::TAU).sin(),
|
||||
}
|
||||
};
|
||||
let src = b.img.clone();
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
|
||||
// u along the cut, v across it.
|
||||
let (u, v) = (dx * cs + dy * sn, -dx * sn + dy * cs);
|
||||
let f = profile(u);
|
||||
let back = |vs: f64| {
|
||||
let (sx, sy) = (u * cs - vs * sn + cx, u * sn + vs * cs + cy);
|
||||
src.sample_bilinear(sx, sy)
|
||||
};
|
||||
*px = if v + d < f {
|
||||
back(v + d)
|
||||
} else if v - d >= f {
|
||||
back(v - d)
|
||||
} else {
|
||||
[0.0; 4]
|
||||
};
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Line Sweep
|
||||
|
||||
fn line_sweep(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx) as f64;
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let s = b.scale;
|
||||
let ang = ctx.params.f("direction").to_radians();
|
||||
let (sn, cs) = ang.sin_cos();
|
||||
let thick = (ctx.params.f("thickness") * s).max(1.0);
|
||||
let slant = ctx.params.f("slant") * s;
|
||||
let flip = ctx.params.b("flipDirection");
|
||||
// Projected extents of the buffer along the sweep (u) and across it (v).
|
||||
let (w, h) = (b.img.width as f64, b.img.height as f64);
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)];
|
||||
let proj = |x: f64, y: f64| (x * cs + y * sn, -x * sn + y * cs);
|
||||
let (mut u0, mut u1, mut v0, mut v1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN);
|
||||
for (x, y) in corners {
|
||||
let (u, v) = proj(x, y);
|
||||
u0 = u0.min(u);
|
||||
u1 = u1.max(u);
|
||||
v0 = v0.min(v);
|
||||
v1 = v1.max(v);
|
||||
}
|
||||
let nstr = ((v1 - v0) / thick).ceil().max(1.0);
|
||||
let total = (u1 - u0) + slant.abs() * nstr + 1.0;
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (u, v) = proj(x as f64 + 0.5, y as f64 + 0.5);
|
||||
let k = ((v - v0) / thick).floor();
|
||||
let k = if flip { nstr - 1.0 - k } else { k };
|
||||
let stagger = if slant >= 0.0 { k } else { nstr - 1.0 - k };
|
||||
let front = u0 + c * total - slant.abs() * stagger;
|
||||
if u < front {
|
||||
*px = [0.0; 4];
|
||||
}
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC Twister
|
||||
|
||||
fn twister(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx) as f64;
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let (cx, cy) = b.to_px(ctx.params.v2("center"));
|
||||
let ang = ctx.params.f("axis").to_radians();
|
||||
let (sn, cs) = ang.sin_cos();
|
||||
let shading = ctx.params.b("shading");
|
||||
let half = (b.img.width as f64).hypot(b.img.height as f64) * 0.5;
|
||||
let src = b.img.clone();
|
||||
let back = reveal(ctx, &b, "backside");
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
|
||||
// u along the twist axis, v across it.
|
||||
let (u, v) = (dx * cs + dy * sn, -dx * sn + dy * cs);
|
||||
let s01 = ((u / half) * 0.5 + 0.5).clamp(0.0, 1.0);
|
||||
let th = std::f64::consts::PI * (c * 2.0 - s01).clamp(0.0, 1.0);
|
||||
let k = th.cos();
|
||||
if k.abs() < 1e-4 {
|
||||
*px = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let vs = v / k;
|
||||
let (sx, sy) = (u * cs - vs * sn + cx, u * sn + vs * cs + cy);
|
||||
let mut o: Px = if k > 0.0 {
|
||||
src.sample_bilinear(sx, sy)
|
||||
} else {
|
||||
// Back side: the layer itself is seen from behind (mirrored across the axis); a
|
||||
// Backside layer is mapped so it reads upright when fully flipped.
|
||||
match &back {
|
||||
Some(bk) => bk.sample_bilinear(u * cs + vs * sn + cx, u * sn - vs * cs + cy),
|
||||
None => src.sample_bilinear(sx, sy),
|
||||
}
|
||||
};
|
||||
if shading {
|
||||
let l = (0.4 + 0.6 * k.abs()) as f32;
|
||||
o = [o[0] * l, o[1] * l, o[2] * l, o[3]];
|
||||
}
|
||||
*px = o;
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CC WarpoMatic
|
||||
|
||||
fn warpomatic(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let c = completion(ctx);
|
||||
if c <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let rimg = layer_or_self(ctx, &b, "reactorLayer", true, false);
|
||||
let mut m = prop_plane(&rimg, 4);
|
||||
let sm = ctx.params.f("smoothness") * b.scale * 0.5;
|
||||
if sm > 0.05 {
|
||||
m = gauss_plane(&m, sm, sm);
|
||||
}
|
||||
m = match ctx.params.e("reactor") {
|
||||
1 => {
|
||||
// Contrast differences: distance from the local mean.
|
||||
let mean = gauss_plane(&m, 8.0 * b.scale, 8.0 * b.scale);
|
||||
m.zip_map(&mean, |a, b| ((a - b).abs() * 4.0).min(1.0))
|
||||
}
|
||||
2 => {
|
||||
// Local differences: gradient magnitude.
|
||||
let mut o = Plane::new(m.w, m.h);
|
||||
o.data.par_chunks_mut(m.w.max(1)).enumerate().for_each(|(y, row)| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
let (gx, gy) = grad(&m, x, y);
|
||||
*v = ((gx * gx + gy * gy).sqrt() * 8.0).min(1.0);
|
||||
}
|
||||
});
|
||||
o
|
||||
}
|
||||
_ => m,
|
||||
};
|
||||
let amt = (ctx.params.f("warpAmount") * b.scale) as f32 * 20.0;
|
||||
let dir = ctx.params.e("warpDirection");
|
||||
let span = (ctx.params.f("blendSpan") / 100.0) as f32 * 0.5;
|
||||
let rev = reveal(ctx, &b, "layerToReveal");
|
||||
let src = b.img.clone();
|
||||
b.img.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let q = wipe_t(m.get(x, y), c, span);
|
||||
let (gx, gy) = grad(&m, x, y);
|
||||
let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let (ox, oy) = ((gx * amt * q) as f64, (gy * amt * q) as f64);
|
||||
let (ix, iy) = ((gx * amt * (1.0 - q)) as f64, (gy * amt * (1.0 - q)) as f64);
|
||||
let (ix, iy) = match dir {
|
||||
1 => (-ix, -iy),
|
||||
2 => (-iy, ix),
|
||||
_ => (ix, iy),
|
||||
};
|
||||
let out = if q < 1.0 { src.sample_bilinear(fx + ox, fy + oy) } else { [0.0; 4] };
|
||||
let inc = match &rev {
|
||||
Some(r) if q > 0.0 => r.sample_bilinear(fx + ix, fy + iy),
|
||||
_ => [0.0; 4],
|
||||
};
|
||||
*px = lerp4(out, inc, q);
|
||||
}
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ specs
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let done = || p("completion", "Completion", num(0.0), pct());
|
||||
vec![
|
||||
spec(
|
||||
"ec.transition.ccglasswipe",
|
||||
"CC Glass Wipe",
|
||||
vec![
|
||||
done(),
|
||||
p("layerToReveal", "Layer to Reveal", Value::Layer(None), ParamUi::Layer),
|
||||
p("gradientLayer", "Gradient Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("softness", "Softness", num(10.0), pct()),
|
||||
p("displacementAmount", "Displacement Amount", num(10.0), slider(-100.0, 100.0, -100.0, 100.0, 1)),
|
||||
],
|
||||
glass_wipe,
|
||||
),
|
||||
spec(
|
||||
"ec.transition.ccimagewipe",
|
||||
"CC Image Wipe",
|
||||
vec![
|
||||
done(),
|
||||
p("borderSoftness", "Border Softness", num(0.0), pct()),
|
||||
p("autoSoftness", "Auto Softness", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("layer", "Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("property", "Property", Value::Enum(4), popup(&GRAD_PROPS)),
|
||||
p("blur", "Blur", num(0.0), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("inverseGradient", "Inverse Gradient", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
image_wipe,
|
||||
),
|
||||
spec(
|
||||
"ec.transition.ccjaws",
|
||||
"CC Jaws",
|
||||
vec![
|
||||
done(),
|
||||
p("center", "Center", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("direction", "Direction", num(0.0), ParamUi::Angle),
|
||||
p("height", "Height", num(50.0), pct()),
|
||||
p("width", "Width", num(50.0), slider(1.0, 1000.0, 1.0, 200.0, 1)),
|
||||
p("shape", "Shape", Value::Enum(0), popup(&["Spikes", "RoboJaw", "Block", "Waves"])),
|
||||
],
|
||||
jaws,
|
||||
),
|
||||
spec(
|
||||
"ec.transition.cclinesweep",
|
||||
"CC Line Sweep",
|
||||
vec![
|
||||
done(),
|
||||
p("direction", "Direction", num(0.0), ParamUi::Angle),
|
||||
p("thickness", "Thickness", num(20.0), slider(1.0, 500.0, 1.0, 100.0, 1)),
|
||||
p("slant", "Slant", num(20.0), slider(-500.0, 500.0, -100.0, 100.0, 1)),
|
||||
p("flipDirection", "Flip Direction", Value::Bool(false), ParamUi::Checkbox),
|
||||
],
|
||||
line_sweep,
|
||||
),
|
||||
spec(
|
||||
"ec.transition.cctwister",
|
||||
"CC Twister",
|
||||
vec![
|
||||
done(),
|
||||
p("backside", "Backside", Value::Layer(None), ParamUi::Layer),
|
||||
p("shading", "Shading", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("center", "Center", pt(0.5, 0.5), ParamUi::Point),
|
||||
p("axis", "Axis", num(45.0), ParamUi::Angle),
|
||||
],
|
||||
twister,
|
||||
),
|
||||
spec(
|
||||
"ec.transition.ccwarpomatic",
|
||||
"CC WarpoMatic",
|
||||
vec![
|
||||
done(),
|
||||
p("layerToReveal", "Layer to Reveal", Value::Layer(None), ParamUi::Layer),
|
||||
p("reactorLayer", "Reactor Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("reactor", "Reactor", Value::Enum(0), popup(&["Brightness", "Contrast Differences", "Local Differences"])),
|
||||
p("smoothness", "Smoothness", num(10.0), slider(0.0, 200.0, 0.0, 100.0, 1)),
|
||||
p("warpAmount", "Warp Amount", num(50.0), slider(-1000.0, 1000.0, -200.0, 200.0, 1)),
|
||||
p("warpDirection", "Warp Direction", Value::Enum(0), popup(&["Joint", "Opposing", "Twisting"])),
|
||||
p("blendSpan", "Blend Span", num(10.0), pct()),
|
||||
],
|
||||
warpomatic,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
|
||||
fn ramp(w: u32, h: u32) -> Image {
|
||||
let mut img = Image::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
img.set(x, y, [x as f32 / w as f32, y as f32 / h as f32, 0.3, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn run(id: &str, vals: &[(&str, Value)], img: Image) -> Buf {
|
||||
run_fx(id, vals, img, 0.0, EffectEnv::default())
|
||||
}
|
||||
|
||||
const ALL: [&str; 6] = [
|
||||
"ec.transition.ccglasswipe",
|
||||
"ec.transition.ccimagewipe",
|
||||
"ec.transition.ccjaws",
|
||||
"ec.transition.cclinesweep",
|
||||
"ec.transition.cctwister",
|
||||
"ec.transition.ccwarpomatic",
|
||||
];
|
||||
|
||||
fn centre(id: &str) -> Vec<(&'static str, Value)> {
|
||||
match id {
|
||||
"ec.transition.ccjaws" => vec![("center", pt(20.0, 16.0)), ("width", num(10.0))],
|
||||
"ec.transition.cctwister" => vec![("center", pt(20.0, 16.0))],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_completion_is_identity() {
|
||||
let img = ramp(40, 32);
|
||||
for id in ALL {
|
||||
let o = run(id, ¢re(id), img.clone());
|
||||
assert_eq!(o.img.data, img.data, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_completion_is_transparent() {
|
||||
let img = ramp(40, 32);
|
||||
for id in ALL {
|
||||
if id == "ec.transition.cctwister" {
|
||||
continue;
|
||||
}
|
||||
let mut v = centre(id);
|
||||
v.push(("completion", num(100.0)));
|
||||
let o = run(id, &v, img.clone());
|
||||
assert!(o.img.data.iter().all(|p| p[3].abs() < 1e-5), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midway_deterministic_and_partial() {
|
||||
let img = ramp(40, 32);
|
||||
for id in ALL {
|
||||
let mut v = centre(id);
|
||||
v.push(("completion", num(50.0)));
|
||||
let a = run(id, &v, img.clone());
|
||||
let b = run(id, &v, img.clone());
|
||||
assert_eq!(a.img.data, b.img.data, "{id}");
|
||||
let opaque = a.img.data.iter().filter(|p| p[3] > 0.99).count();
|
||||
let clear = a.img.data.iter().filter(|p| p[3] < 0.01).count();
|
||||
if id != "ec.transition.cctwister" {
|
||||
assert!(opaque > 0 && clear > 0, "{id}: {opaque} {clear}");
|
||||
}
|
||||
assert_ne!(a.img.data, img.data, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twister_full_shows_mirrored_back() {
|
||||
let img = ramp(40, 32);
|
||||
let o = run(
|
||||
"ec.transition.cctwister",
|
||||
&[("completion", num(100.0)), ("shading", Value::Bool(false)), ("axis", num(0.0)), ("center", pt(20.0, 16.0))],
|
||||
img.clone(),
|
||||
);
|
||||
// Axis horizontal through the centre: the back is the source flipped vertically.
|
||||
for (x, y) in [(5usize, 4usize), (30, 20), (12, 27)] {
|
||||
let got = o.img.data[y * 40 + x];
|
||||
let want = img.data[(31 - y) * 40 + x];
|
||||
assert!((got[1] - want[1]).abs() < 1e-3 && (got[0] - want[0]).abs() < 1e-3, "{x},{y} {got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_sweep_flip_reverses_stagger() {
|
||||
let img = ramp(40, 32);
|
||||
let a = run("ec.transition.cclinesweep", &[("completion", num(40.0))], img.clone());
|
||||
let b = run("ec.transition.cclinesweep", &[("completion", num(40.0)), ("flipDirection", Value::Bool(true))], img.clone());
|
||||
let cleared = |o: &Buf, y: usize| (0..40).filter(|&x| o.img.data[y * 40 + x][3] < 0.01).count();
|
||||
// Unflipped: lower stripes trail; flipped: upper stripes trail.
|
||||
assert!(cleared(&a, 2) > cleared(&a, 30));
|
||||
assert!(cleared(&b, 2) < cleared(&b, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_wipe_follows_gradient() {
|
||||
let img = ramp(40, 32);
|
||||
let o = run("ec.transition.ccimagewipe", &[("completion", num(50.0)), ("property", Value::Enum(0))], img.clone());
|
||||
// Red ramps left→right: dark (left) side goes first.
|
||||
assert!(o.img.data[16 * 40 + 2][3] < 0.01);
|
||||
assert!(o.img.data[16 * 40 + 37][3] > 0.99);
|
||||
}
|
||||
}
|
||||
@@ -427,10 +427,253 @@ pub fn layer_rect(ctx: &crate::EffectCtx, b: &crate::Buf) -> (f64, f64, f64, f64
|
||||
(b.offset[0], b.offset[1], ctx.layer_size[0] * b.scale, ctx.layer_size[1] * b.scale)
|
||||
}
|
||||
|
||||
/// Resample another layer (a layer parameter) into `b`'s pixel grid. With `stretch` the other
|
||||
/// layer is scaled to this layer's size ("Stretch to Fit"); otherwise it is centred.
|
||||
pub fn fit_layer(ctx: &crate::EffectCtx, b: &crate::Buf, other: &crate::LayerPixels, stretch: bool) -> Image {
|
||||
let ls = ctx.layer_size;
|
||||
let os = other.size;
|
||||
let (sx, sy) = if stretch && ls[0] > 0.0 && ls[1] > 0.0 { (os[0] / ls[0], os[1] / ls[1]) } else { (1.0, 1.0) };
|
||||
let (dx, dy) = if stretch { (0.0, 0.0) } else { ((os[0] - ls[0]) * 0.5, (os[1] - ls[1]) * 0.5) };
|
||||
let inv = 1.0 / b.scale.max(1e-9);
|
||||
gen_image(b.img.width, b.img.height, |x, y| {
|
||||
let px = (x as f64 + 0.5 - b.offset[0]) * inv;
|
||||
let py = (y as f64 + 0.5 - b.offset[1]) * inv;
|
||||
let qx = px * sx + dx;
|
||||
let qy = py * sy + dy;
|
||||
other.buf.img.sample_bilinear(qx * other.buf.scale + other.buf.offset[0], qy * other.buf.scale + other.buf.offset[1])
|
||||
})
|
||||
}
|
||||
|
||||
/// The layer chosen in layer parameter `id` fitted to `b` (see [`fit_layer`]), or a copy of
|
||||
/// `b`'s own pixels when none is chosen / available (After Effects' "self" behaviour).
|
||||
pub fn layer_or_self(ctx: &crate::EffectCtx, b: &crate::Buf, id: &str, masks_and_effects: bool, stretch: bool) -> Image {
|
||||
match ctx.layer_param(id, masks_and_effects) {
|
||||
Some(o) => fit_layer(ctx, b, &o, stretch),
|
||||
None => b.img.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stable hash of an effect instance's evaluated parameters, seed, layer size and buffer
|
||||
/// scale (cache key for simulations).
|
||||
pub fn params_key(ctx: &crate::EffectCtx, b: &crate::Buf, salt: u64) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
let mut keys: Vec<&String> = ctx.params.values.keys().collect();
|
||||
keys.sort();
|
||||
for k in keys {
|
||||
k.hash(&mut h);
|
||||
format!("{:?}", ctx.params.values[k]).hash(&mut h);
|
||||
}
|
||||
ctx.seed.hash(&mut h);
|
||||
ctx.layer_size[0].to_bits().hash(&mut h);
|
||||
ctx.layer_size[1].to_bits().hash(&mut h);
|
||||
b.scale.to_bits().hash(&mut h);
|
||||
salt.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Checkpointed, deterministic, time-seekable simulation cache.
|
||||
///
|
||||
/// A simulation is a state advanced in fixed steps from layer time 0. [`SimCache::run`] returns
|
||||
/// the state after `target` steps, starting from the nearest cached checkpoint at or before it
|
||||
/// (so scrubbing forward is incremental and seeking anywhere gives the same answer as
|
||||
/// simulating from scratch). Entries are keyed by [`params_key`]; the least recently used key
|
||||
/// is evicted beyond `cap` keys.
|
||||
pub struct SimCache<S> {
|
||||
inner: std::sync::Mutex<Vec<SimEntry<S>>>,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
struct SimEntry<S> {
|
||||
key: u64,
|
||||
used: u64,
|
||||
checkpoints: Vec<(u64, std::sync::Arc<S>)>,
|
||||
}
|
||||
|
||||
/// Checkpoint every this many steps.
|
||||
pub const SIM_CHECKPOINT: u64 = 15;
|
||||
|
||||
impl<S: Clone> SimCache<S> {
|
||||
pub const fn new(cap: usize) -> SimCache<S> {
|
||||
SimCache { inner: std::sync::Mutex::new(Vec::new()), cap }
|
||||
}
|
||||
|
||||
/// State after `target` steps. `init` builds step 0; `step(state, i)` advances from step
|
||||
/// `i` to `i + 1`.
|
||||
pub fn run(&self, key: u64, target: u64, init: impl FnOnce() -> S, mut step: impl FnMut(&mut S, u64)) -> std::sync::Arc<S> {
|
||||
use std::sync::Arc;
|
||||
let start = {
|
||||
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let tick = g.iter().map(|e| e.used).max().unwrap_or(0) + 1;
|
||||
g.iter_mut().find(|e| e.key == key).and_then(|e| {
|
||||
e.used = tick;
|
||||
e.checkpoints.iter().filter(|(s, _)| *s <= target).max_by_key(|(s, _)| *s).map(|(s, st)| (*s, st.clone()))
|
||||
})
|
||||
};
|
||||
let had_start = start.is_some();
|
||||
let (mut i, mut st) = match start {
|
||||
Some((s, st)) if s == target => return st,
|
||||
Some((s, st)) => (s, (*st).clone()),
|
||||
None => (0, init()),
|
||||
};
|
||||
let mut fresh: Vec<(u64, Arc<S>)> = Vec::new();
|
||||
if !had_start {
|
||||
fresh.push((0, Arc::new(st.clone())));
|
||||
}
|
||||
while i < target {
|
||||
step(&mut st, i);
|
||||
i += 1;
|
||||
if i % SIM_CHECKPOINT == 0 && i != target {
|
||||
fresh.push((i, Arc::new(st.clone())));
|
||||
}
|
||||
}
|
||||
let out = Arc::new(st);
|
||||
fresh.push((target, out.clone()));
|
||||
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let tick = g.iter().map(|e| e.used).max().unwrap_or(0) + 1;
|
||||
let idx = match g.iter().position(|e| e.key == key) {
|
||||
Some(ix) => ix,
|
||||
None => {
|
||||
if g.len() >= self.cap.max(1) {
|
||||
let old = g.iter().enumerate().min_by_key(|(_, e)| e.used).map(|(ix, _)| ix).unwrap_or(0);
|
||||
g.remove(old);
|
||||
}
|
||||
g.push(SimEntry { key, used: tick, checkpoints: Vec::new() });
|
||||
g.len() - 1
|
||||
}
|
||||
};
|
||||
let e = &mut g[idx];
|
||||
e.used = tick;
|
||||
for (s, st) in fresh {
|
||||
if !e.checkpoints.iter().any(|(c, _)| *c == s) {
|
||||
e.checkpoints.push((s, st));
|
||||
}
|
||||
}
|
||||
// Keep memory bounded: drop unaligned (exact-target) checkpoints first, then thin.
|
||||
if e.checkpoints.len() > 256 {
|
||||
e.checkpoints.retain(|(s, _)| s % SIM_CHECKPOINT == 0);
|
||||
e.checkpoints.sort_by_key(|(s, _)| *s);
|
||||
let mut k = 0;
|
||||
e.checkpoints.retain(|_| {
|
||||
k += 1;
|
||||
k % 2 == 1
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Point-in-polygon (even-odd) for a closed polyline.
|
||||
pub fn point_in_poly(pts: &[[f64; 2]], x: f64, y: f64) -> bool {
|
||||
let n = pts.len();
|
||||
if n < 3 {
|
||||
return false;
|
||||
}
|
||||
let mut inside = false;
|
||||
let mut j = n - 1;
|
||||
for i in 0..n {
|
||||
let (a, b) = (pts[i], pts[j]);
|
||||
if (a[1] > y) != (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// Distance from a point to a polyline (closed adds the last→first segment).
|
||||
pub fn dist_to_poly(pts: &[[f64; 2]], closed: bool, x: f64, y: f64) -> f64 {
|
||||
let n = pts.len();
|
||||
if n == 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
if n == 1 {
|
||||
return ((pts[0][0] - x).powi(2) + (pts[0][1] - y).powi(2)).sqrt();
|
||||
}
|
||||
let segs = if closed { n } else { n - 1 };
|
||||
let mut best = f64::INFINITY;
|
||||
for i in 0..segs {
|
||||
let a = pts[i];
|
||||
let b = pts[(i + 1) % n];
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let t = if l2 > 0.0 { (((x - a[0]) * dx + (y - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (px, py) = (a[0] + dx * t, a[1] + dy * t);
|
||||
best = best.min((px - x).powi(2) + (py - y).powi(2));
|
||||
}
|
||||
best.sqrt()
|
||||
}
|
||||
|
||||
/// Total length of a polyline.
|
||||
pub fn poly_length(pts: &[[f64; 2]], closed: bool) -> f64 {
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
return 0.0;
|
||||
}
|
||||
let segs = if closed { n } else { n - 1 };
|
||||
(0..segs)
|
||||
.map(|i| {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Point and unit tangent at arc length `s` along a polyline.
|
||||
pub fn poly_point_at(pts: &[[f64; 2]], closed: bool, s: f64) -> ([f64; 2], [f64; 2]) {
|
||||
let n = pts.len();
|
||||
if n == 0 {
|
||||
return ([0.0; 2], [1.0, 0.0]);
|
||||
}
|
||||
if n == 1 {
|
||||
return (pts[0], [1.0, 0.0]);
|
||||
}
|
||||
let segs = if closed { n } else { n - 1 };
|
||||
let mut rem = s.max(0.0);
|
||||
for i in 0..segs {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
let l = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
|
||||
if rem <= l || i == segs - 1 {
|
||||
let t = if l > 0.0 { (rem / l).min(1.0) } else { 0.0 };
|
||||
let d = if l > 0.0 { [(b[0] - a[0]) / l, (b[1] - a[1]) / l] } else { [1.0, 0.0] };
|
||||
return ([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], d);
|
||||
}
|
||||
rem -= l;
|
||||
}
|
||||
(pts[n - 1], [1.0, 0.0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sim_cache_is_seek_consistent() {
|
||||
static C: SimCache<u64> = SimCache::new(2);
|
||||
let step = |s: &mut u64, i: u64| *s = s.wrapping_mul(6364136223846793005).wrapping_add(i);
|
||||
let direct = *C.run(1, 100, || 7, step);
|
||||
let fresh: SimCache<u64> = SimCache::new(2);
|
||||
let a = *fresh.run(1, 40, || 7, step);
|
||||
let b = *fresh.run(1, 100, || 7, step);
|
||||
let c = *fresh.run(1, 40, || 7, step);
|
||||
let d = *fresh.run(1, 77, || 7, step);
|
||||
let e = *C.run(1, 77, || 7, step);
|
||||
assert_eq!(b, direct);
|
||||
assert_eq!(a, c);
|
||||
assert_eq!(d, e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poly_helpers() {
|
||||
let sq = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
|
||||
assert!(point_in_poly(&sq, 5.0, 5.0));
|
||||
assert!(!point_in_poly(&sq, 15.0, 5.0));
|
||||
assert!((poly_length(&sq, true) - 40.0).abs() < 1e-9);
|
||||
assert!((dist_to_poly(&sq, true, 5.0, 5.0) - 5.0).abs() < 1e-9);
|
||||
let (pt, _) = poly_point_at(&sq, true, 15.0);
|
||||
assert!((pt[0] - 10.0).abs() < 1e-9 && (pt[1] - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minmax_matches_brute_force() {
|
||||
let src: Vec<f32> = (0..37).map(|i| ((i * 7919) % 31) as f32).collect();
|
||||
|
||||
@@ -363,7 +363,8 @@ mod tests {
|
||||
for (k, v) in vals {
|
||||
params.values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false };
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: Default::default() };
|
||||
crate::apply(s, &ctx, Buf { img, offset: [0.0, 0.0], scale: 1.0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Utility effects, batch 2: HDR Compander.
|
||||
//!
|
||||
//! HDR Compander squeezes high-dynamic-range values into 0–1 (Compress Range) so 8/16 bpc
|
||||
//! effects can process them, and restores them afterwards (Expand Range) with the same Gain and
|
||||
//! Gamma; the two modes are exact inverses.
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{premul, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
#[inline]
|
||||
fn spow(v: f32, e: f32) -> f32 {
|
||||
v.signum() * v.abs().powf(e)
|
||||
}
|
||||
|
||||
fn hdr_compander(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let expand = ctx.params.e("mode") == 1;
|
||||
let gain = ctx.params.f("gain").max(1e-6) as f32;
|
||||
let gamma = ctx.params.f("gamma").max(1e-3) as f32;
|
||||
b.img.data.par_iter_mut().for_each(|px| {
|
||||
let (c, a) = unpremul(*px);
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let c = c.map(|v| if expand { spow(v, gamma) * gain } else { spow(v / gain, 1.0 / gamma) });
|
||||
*px = premul(c, a);
|
||||
});
|
||||
b
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![EffectSpec {
|
||||
id: "ec.utility.hdrcompander",
|
||||
name: "HDR Compander",
|
||||
category: "Utility",
|
||||
params: vec![
|
||||
p("mode", "Mode", Value::Enum(0), popup(&["Compress Range", "Expand Range"])),
|
||||
p("gain", "Gain", num(1.0), slider(1.0, 100.0, 1.0, 100.0, 2)),
|
||||
p("gamma", "Gamma", num(1.0), slider(0.1, 10.0, 0.1, 3.0, 2)),
|
||||
],
|
||||
render: hdr_compander,
|
||||
gpu: false,
|
||||
float: true,
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EffectEnv, run_fx};
|
||||
use effectcraft_raster::Image;
|
||||
|
||||
fn hdr() -> Image {
|
||||
crate::util::gen_image(8, 4, |x, y| {
|
||||
let v = x as f32 * 0.6 + y as f32 * 0.1;
|
||||
[v * 0.8, v * 0.4, v * 0.2, 0.8]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_are_identity_and_deterministic() {
|
||||
let im = hdr();
|
||||
let a = run_fx("ec.utility.hdrcompander", &[], im.clone(), 0.0, EffectEnv::default());
|
||||
let b = run_fx("ec.utility.hdrcompander", &[], im.clone(), 0.0, EffectEnv::default());
|
||||
assert_eq!(a.img, b.img);
|
||||
assert!(a.img.data.iter().zip(&im.data).all(|(p, q)| (0..4).all(|i| (p[i] - q[i]).abs() < 1e-5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compress_then_expand_round_trips() {
|
||||
let im = hdr();
|
||||
let set = [("gain", num(5.0)), ("gamma", num(2.2))];
|
||||
let c = run_fx("ec.utility.hdrcompander", &set, im.clone(), 0.0, EffectEnv::default());
|
||||
// Compressed values fit in 0–1.
|
||||
assert!(c.img.data.iter().all(|p| p[0] <= p[3] + 1e-5));
|
||||
let e = run_fx("ec.utility.hdrcompander", &[set[0].clone(), set[1].clone(), ("mode", Value::Enum(1))], c.img, 0.0, EffectEnv::default());
|
||||
for (p, q) in e.img.data.iter().zip(&im.data) {
|
||||
for i in 0..4 {
|
||||
assert!((p[i] - q[i]).abs() < 1e-3, "{p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+373
-387
@@ -1,428 +1,414 @@
|
||||
//! Animation menu: animation presets (EffectCraft's own JSON format), Add Keyframe, Keyframe
|
||||
//! Assistant (Exponential Scale, Time-Reverse Keyframes), text animators/selectors, and the
|
||||
//! Reveal Properties commands.
|
||||
//! Keyframe clipboard, selection, nudging, direct key/ease edits (Graph Editor handles) and key
|
||||
//! inspection for the Keyframe Velocity / Keyframe Interpolation dialogs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use effectcraft_keyframe::{Interp, Keyframe, Value as KV};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{GroupKind, LayerId, Node, PropGroup, Property, Uid};
|
||||
use effectcraft_keyframe::{Ease, Interp, Keyframe, key_at, retime_roving, side_ease};
|
||||
use effectcraft_project::{LayerId, Property, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, frontend, has_comp, has_keys, has_layers, layer_mut, layer_p, layers_p, match_path_of, selected_leaf_props, str_p};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd};
|
||||
use super::prop::{edit_keys, prop_ref};
|
||||
use super::{CommandSpec, bad, comp_id, f_p, has_comp, has_keys, layers_p, merge_p, str_p, time_p};
|
||||
use crate::{EngineError, KeyClip, KeyRef, Result, Session, cmd, query};
|
||||
|
||||
/// Preset file format version tag (`*.ecpreset`, JSON).
|
||||
pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
|
||||
|
||||
fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
|
||||
fn has_key_clip(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)?;
|
||||
if selected_leaf_props(s).is_empty() && selected_effects(s).is_empty() { Err("select properties or effects first".into()) } else { Ok(()) }
|
||||
if s.state.key_clipboard.is_empty() { Err("no keyframes have been copied".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn has_text_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
has_layers(s)?;
|
||||
let c = s.active_comp().ok_or("no composition")?;
|
||||
if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| l.props.group("text/animators").is_some()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("select a text layer".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Selected effect groups (layer, effect group).
|
||||
fn selected_effects(s: &Session) -> Vec<(LayerId, PropGroup)> {
|
||||
let Some(c) = s.active_comp() else { return vec![] };
|
||||
s.state
|
||||
.selected_props
|
||||
.iter()
|
||||
.filter_map(|(l, u)| {
|
||||
let layer = c.layer(*l)?;
|
||||
let fx = layer.effects()?;
|
||||
fx.groups().find(|g| g.uid == *u).map(|g| (*l, g.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- presets
|
||||
|
||||
fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_p(p, "path").ok_or_else(|| bad("anim.savePreset", "missing `path`"))?.to_string();
|
||||
/// Copy the selected keyframes (Edit ▸ Copy with keys selected).
|
||||
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let t = s.time();
|
||||
let effects: Vec<(LayerId, PropGroup)> = selected_effects(s);
|
||||
let effect_uids: Vec<Uid> = effects.iter().map(|(_, g)| g.uid).collect();
|
||||
let mut props = vec![];
|
||||
for (lid, uid) in selected_leaf_props(s) {
|
||||
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
|
||||
for k in &s.state.selected_keys {
|
||||
groups.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
// Earliest selected key in comp time: pasted keys keep their offsets from it.
|
||||
let mut earliest: Option<Tick> = None;
|
||||
for ((lid, _), times) in &groups {
|
||||
if let Some(l) = comp.layer(*lid) {
|
||||
for t in times {
|
||||
let ct = l.comp_time(*t);
|
||||
earliest = Some(earliest.map_or(ct, |e: Tick| e.min(ct)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let earliest = earliest.ok_or_else(|| bad("keys.copy", "select keyframes first"))?;
|
||||
let mut clip = vec![];
|
||||
for ((lid, uid), times) in groups {
|
||||
let Some(l) = comp.layer(lid) else { continue };
|
||||
// Properties inside a saved effect travel with the effect.
|
||||
if l.effects().is_some_and(|fx| fx.groups().any(|g| effect_uids.contains(&g.uid) && g.find(uid).is_some())) {
|
||||
continue;
|
||||
let Some(pr) = l.props.find(uid) else { continue };
|
||||
let Some(path) = l.props.match_path_of(uid) else { continue };
|
||||
let mut keys: Vec<Keyframe> = pr.keys.iter().filter(|k| times.contains(&k.time)).cloned().collect();
|
||||
for k in &mut keys {
|
||||
k.time = l.comp_time(k.time) - earliest;
|
||||
}
|
||||
let (Some(pr), Some(mp)) = (l.props.find(uid), match_path_of(&l.props, uid)) else { continue };
|
||||
props.push((l.layer_time(t), mp, pr.clone()));
|
||||
clip.push(KeyClip { layer: lid, path, keys });
|
||||
}
|
||||
if props.is_empty() && effects.is_empty() {
|
||||
return Err(bad("anim.savePreset", "select properties or effects to save"));
|
||||
}
|
||||
// Key times are stored relative to the earliest key so the preset applies at the CTI.
|
||||
let first = props.iter().flat_map(|(_, _, pr)| pr.keys.iter().map(|k| k.time)).min().unwrap_or(Tick::ZERO);
|
||||
let props_json: Vec<Value> = props
|
||||
.iter()
|
||||
.map(|(_, mp, pr)| {
|
||||
let mut pr = pr.clone();
|
||||
for k in &mut pr.keys {
|
||||
k.time -= first;
|
||||
}
|
||||
json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr})
|
||||
})
|
||||
.collect();
|
||||
let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
|
||||
let name = str_p(p, "name")
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
|
||||
let doc = json!({PRESET_TAG: 1, "name": name, "properties": props_json, "effects": fx_json});
|
||||
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
|
||||
s.services.write_file(&path, text.as_bytes()).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
|
||||
Ok(json!({"path": path, "properties": props.len(), "effects": effects.len()}))
|
||||
let n: usize = clip.iter().map(|c| c.keys.len()).sum();
|
||||
s.state.key_clipboard = clip;
|
||||
s.state.clip_is_keys = true;
|
||||
Ok(json!(n))
|
||||
}
|
||||
|
||||
fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc: Value = match (p.get("preset"), str_p(p, "path")) {
|
||||
(Some(v), _) => v.clone(),
|
||||
(None, Some(path)) => {
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
serde_json::from_slice(&bytes).map_err(|e| bad("anim.applyPreset", format!("not a preset: {e}")))?
|
||||
}
|
||||
_ => return Err(bad("anim.applyPreset", "missing `path` (or inline `preset`)")),
|
||||
};
|
||||
if doc.get(PRESET_TAG).is_none() {
|
||||
return Err(bad("anim.applyPreset", "not an EffectCraft animation preset"));
|
||||
}
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("anim.applyPreset", "select a layer"));
|
||||
}
|
||||
let effects: Vec<PropGroup> =
|
||||
doc["effects"].as_array().map(|a| a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect()).unwrap_or_default();
|
||||
let props: Vec<(String, Property)> = doc["properties"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| {
|
||||
let path = v["path"].as_str()?.to_string();
|
||||
let value: KV = serde_json::from_value(v["value"].clone()).ok()?;
|
||||
let keys: Vec<Keyframe> = serde_json::from_value(v["keys"].clone()).unwrap_or_default();
|
||||
let expr = serde_json::from_value(v["expression"].clone()).ok().flatten();
|
||||
let mut pr = Property::new(0, "", "", value);
|
||||
pr.keys = keys;
|
||||
pr.expr = expr;
|
||||
Some((path, pr))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let t = s.time();
|
||||
let mut applied = 0;
|
||||
let mut skipped = vec![];
|
||||
s.edit("Apply Animation Preset", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
for lid in &ids {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
if let Some(fx) = l.props.sub_mut("effects") {
|
||||
for g in &effects {
|
||||
let mut g = g.clone();
|
||||
g.reassign_uids(&mut next);
|
||||
next += 1;
|
||||
fx.children.push(Node::Group(g));
|
||||
applied += 1;
|
||||
}
|
||||
}
|
||||
for (path, src) in &props {
|
||||
match l.props.prop_mut(path) {
|
||||
Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
|
||||
pr.value = src.value.clone();
|
||||
pr.keys = src
|
||||
.keys
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut k| {
|
||||
k.time += lt;
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
if src.expr.is_some() {
|
||||
pr.expr = src.expr.clone();
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
_ => skipped.push(path.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
proj.next_id = next;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"applied": applied, "skipped": skipped}))
|
||||
/// Values of the same kind (and dimensionality) can receive each other's keys.
|
||||
fn compatible(a: &Property, b: &effectcraft_keyframe::Value) -> bool {
|
||||
a.value.kind_name() == b.kind_name() && a.value.components().len() == b.components().len()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- keyframes
|
||||
|
||||
fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let targets = selected_leaf_props(s);
|
||||
/// Paste copied keyframes at the current time into the target layers' properties.
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let clip = s.state.key_clipboard.clone();
|
||||
if clip.is_empty() {
|
||||
return Err(bad("keys.paste", "no keyframes have been copied"));
|
||||
}
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let t = time_p(s, p, Some(comp));
|
||||
let (_, mut targets) = layers_p(s, p)?;
|
||||
if targets.is_empty() {
|
||||
return Err(bad("anim.addKeyframe", "select properties first"));
|
||||
targets = clip.iter().map(|c| c.layer).collect();
|
||||
targets.dedup();
|
||||
}
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let t = s.time();
|
||||
let n = s.edit("Add Keyframe", None, |proj, _| {
|
||||
let mut n = 0;
|
||||
for (lid, uid) in &targets {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
let explicit = p.get("prop").and_then(Value::as_u64).or_else(|| {
|
||||
let path = str_p(p, "path")?;
|
||||
comp.layer(*targets.first()?)?.props.prop(path).map(|pr| pr.uid)
|
||||
});
|
||||
// (layer, prop uid, clip index)
|
||||
let mut plan: Vec<(LayerId, Uid, usize)> = vec![];
|
||||
for lid in &targets {
|
||||
let Some(l) = comp.layer(*lid) else { continue };
|
||||
for (ci, c) in clip.iter().enumerate() {
|
||||
let Some(sample) = c.keys.first().map(|k| &k.value) else { continue };
|
||||
let target = if clip.len() == 1 {
|
||||
explicit
|
||||
.and_then(|u| l.props.find(u))
|
||||
.or_else(|| {
|
||||
s.state.selected_props.iter().filter(|(sl, _)| sl == lid).filter_map(|(_, u)| l.props.find(*u)).find(|pr| compatible(pr, sample))
|
||||
})
|
||||
.or_else(|| l.props.prop(&c.path))
|
||||
} else {
|
||||
l.props.prop(&c.path)
|
||||
};
|
||||
if let Some(pr) = target.filter(|pr| compatible(pr, sample) && !pr.static_only) {
|
||||
plan.push((*lid, pr.uid, ci));
|
||||
}
|
||||
}
|
||||
}
|
||||
if plan.is_empty() {
|
||||
return Err(bad("keys.paste", "no compatible property to paste into (select a property of the same type)"));
|
||||
}
|
||||
s.edit("Paste Keyframes", None, |proj, st| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let mut sel = vec![];
|
||||
for (lid, uid, ci) in &plan {
|
||||
let Some(l) = comp.layer_mut(*lid) else { continue };
|
||||
let times: Vec<Tick> = clip[*ci].keys.iter().map(|k| l.layer_time(t + k.time)).collect();
|
||||
let Some(pr) = l.props.find_mut(*uid) else { continue };
|
||||
if pr.static_only {
|
||||
for (k, lt) in clip[*ci].keys.iter().zip(times) {
|
||||
let mut k = k.clone();
|
||||
k.time = lt;
|
||||
if let Some(v) = pr.value.coerce_json(&k.value.to_json()) {
|
||||
k.value = v;
|
||||
}
|
||||
if pr.hold_only {
|
||||
k = k.hold();
|
||||
}
|
||||
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
|
||||
Ok(i) => pr.keys[i] = k,
|
||||
Err(i) => pr.keys.insert(i, k),
|
||||
}
|
||||
sel.push(KeyRef { layer: *lid, prop: *uid, time: lt });
|
||||
}
|
||||
retime_roving(&mut pr.keys, pr.spatial);
|
||||
}
|
||||
st.selected_keys = sel;
|
||||
Ok(json!(st.selected_keys.len()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Select every keyframe of the selected properties, or of the given / selected layers.
|
||||
fn select_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, mut layers) = layers_p(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let mut sel = vec![];
|
||||
if p.get("layers").is_none() && p.get("layer").is_none() && !s.state.selected_props.is_empty() {
|
||||
for (lid, uid) in &s.state.selected_props {
|
||||
if let Some(pr) = comp.layer(*lid).and_then(|l| l.props.find(*uid)) {
|
||||
sel.extend(pr.keys.iter().map(|k| KeyRef { layer: *lid, prop: *uid, time: k.time }));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if layers.is_empty() {
|
||||
layers = comp.layers.iter().map(|l| l.id).collect();
|
||||
}
|
||||
for l in comp.layers.iter().filter(|l| layers.contains(&l.id)) {
|
||||
l.props.walk("", &mut |_, pr| sel.extend(pr.keys.iter().map(|k| KeyRef { layer: l.id, prop: pr.uid, time: k.time })));
|
||||
}
|
||||
}
|
||||
s.state.selected_keys = sel;
|
||||
Ok(json!(s.state.selected_keys.len()))
|
||||
}
|
||||
|
||||
/// Move the selected keys by whole frames (Alt+→ / Alt+←, Shift for 10 frames).
|
||||
fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frames = p.get("frames").and_then(Value::as_i64).ok_or_else(|| bad("keys.nudge", "missing `frames`"))?;
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let d = Tick(comp.frame_duration().0 * frames);
|
||||
edit_keys(s, "Nudge Keyframes", merge_p(p), move |_, _, t| {
|
||||
*t += d;
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Edit one key directly: move it in time and/or set its value (Graph Editor drags).
|
||||
fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "keys.set")?;
|
||||
let t = Tick::from_seconds_f64(f_p(p, "time").ok_or_else(|| bad("keys.set", "missing `time` (layer time of the key)"))?);
|
||||
let new_t = f_p(p, "newTime").map(Tick::from_seconds_f64);
|
||||
let value = p.get("value").cloned();
|
||||
let fr = s.project.comp(cid).map(|c| c.frame_rate);
|
||||
s.edit("Edit Keyframe", merge_p(p), |proj, st| {
|
||||
let l = super::layer_mut(proj, cid, lid)?;
|
||||
let pr = l.props.find_mut(uid).ok_or_else(|| bad("keys.set", "no property"))?;
|
||||
let i = nearest_key(&pr.keys, t).ok_or_else(|| bad("keys.set", "the property has no keyframes"))?;
|
||||
let old_t = pr.keys[i].time;
|
||||
if let Some(v) = &value {
|
||||
let nv = pr.keys[i].value.coerce_json(v).ok_or_else(|| bad("keys.set", format!("can't use {v} here")))?;
|
||||
pr.keys[i].value = nv;
|
||||
}
|
||||
let mut nt = old_t;
|
||||
if let Some(n) = new_t {
|
||||
nt = fr.map(|r| r.snap_nearest(n)).unwrap_or(n);
|
||||
// Keys can't pass their neighbours or share a time.
|
||||
let lo = if i > 0 { pr.keys[i - 1].time.0 + 1 } else { i64::MIN };
|
||||
let hi = if i + 1 < pr.keys.len() { pr.keys[i + 1].time.0 - 1 } else { i64::MAX };
|
||||
nt = Tick(nt.0.clamp(lo, hi));
|
||||
pr.keys[i].time = nt;
|
||||
}
|
||||
retime_roving(&mut pr.keys, pr.spatial);
|
||||
let nt = pr.keys.get(i).map(|k| k.time).unwrap_or(nt);
|
||||
for k in st.selected_keys.iter_mut().filter(|k| k.layer == lid && k.prop == uid && k.time == old_t) {
|
||||
k.time = nt;
|
||||
}
|
||||
Ok(json!({"time": nt.seconds()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn nearest_key(keys: &[Keyframe], t: Tick) -> Option<usize> {
|
||||
if let Some(i) = key_at(keys, t) {
|
||||
return Some(i);
|
||||
}
|
||||
keys.iter().enumerate().min_by_key(|(_, k)| (k.time.0 - t.0).abs()).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Set one side's temporal ease of a key (Graph Editor handle drags, scripting).
|
||||
fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "keys.setEase")?;
|
||||
let t = Tick::from_seconds_f64(f_p(p, "time").ok_or_else(|| bad("keys.setEase", "missing `time`"))?);
|
||||
let out = match str_p(p, "side") {
|
||||
Some("in") => false,
|
||||
Some("out") => true,
|
||||
_ => return Err(bad("keys.setEase", "`side` must be in or out")),
|
||||
};
|
||||
let dim = p.get("dim").and_then(Value::as_u64).map(|d| d as usize);
|
||||
let speed = f_p(p, "speed");
|
||||
let influence = f_p(p, "influence").map(|v| (v / 100.0).clamp(0.001, 1.0));
|
||||
s.edit("Keyframe Velocity", merge_p(p), |proj, _| {
|
||||
let l = super::layer_mut(proj, cid, lid)?;
|
||||
let pr = l.props.find_mut(uid).ok_or_else(|| bad("keys.setEase", "no property"))?;
|
||||
let i = nearest_key(&pr.keys, t).ok_or_else(|| bad("keys.setEase", "no keyframes"))?;
|
||||
let spatial = pr.spatial;
|
||||
let n = if spatial && matches!(pr.keys[i].value, effectcraft_keyframe::Value::Vec2(_) | effectcraft_keyframe::Value::Vec3(_)) {
|
||||
1
|
||||
} else {
|
||||
pr.keys[i].value.dims().max(1)
|
||||
};
|
||||
// Start from what the side presents now so untouched dimensions keep their shape.
|
||||
let cur: Vec<Ease> = (0..n).map(|d| side_ease(&pr.keys, i, d, spatial, out).unwrap_or_default()).collect();
|
||||
let k = &mut pr.keys[i];
|
||||
let list = if out { &mut k.out_ease } else { &mut k.in_ease };
|
||||
if list.len() != n {
|
||||
*list = cur.clone();
|
||||
}
|
||||
for (d, e) in list.iter_mut().enumerate() {
|
||||
if dim.is_some_and(|x| x != d) && n > 1 {
|
||||
continue;
|
||||
}
|
||||
if pr.keys.is_empty() {
|
||||
pr.set_animated(true, lt);
|
||||
} else {
|
||||
let v = pr.value_at(lt);
|
||||
pr.set_value_at(lt, v);
|
||||
if let Some(v) = speed {
|
||||
e.speed = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
})?;
|
||||
Ok(json!({"keys": n}))
|
||||
}
|
||||
|
||||
/// Selected keys grouped by (layer, property).
|
||||
fn keys_by_prop(s: &Session) -> BTreeMap<(LayerId, Uid), Vec<Tick>> {
|
||||
let mut m: BTreeMap<(LayerId, Uid), Vec<Tick>> = BTreeMap::new();
|
||||
for k in &s.state.selected_keys {
|
||||
m.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn exponential_scale(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let fd = comp.frame_duration();
|
||||
let groups = keys_by_prop(s);
|
||||
let mut done = 0;
|
||||
let mut work = vec![];
|
||||
for ((lid, uid), mut times) in groups {
|
||||
let Some(l) = comp.layer(lid) else { continue };
|
||||
if l.transform().and_then(|tr| tr.get("scale")).map(|p| p.uid) != Some(uid) {
|
||||
continue;
|
||||
}
|
||||
times.sort();
|
||||
if times.len() >= 2 {
|
||||
work.push((lid, uid, times[0], *times.last().unwrap_or(×[0])));
|
||||
}
|
||||
}
|
||||
if work.is_empty() {
|
||||
return Err(bad("keys.exponentialScale", "select two Scale keyframes"));
|
||||
}
|
||||
s.edit("Exponential Scale", None, |proj, st| {
|
||||
for (lid, uid, a, b) in &work {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let Some(pr) = l.props.find_mut(*uid) else { continue };
|
||||
let (va, vb) = (pr.value_at(*a).as_vec3(), pr.value_at(*b).as_vec3());
|
||||
pr.keys.retain(|k| k.time <= *a || k.time >= *b);
|
||||
let n = ((*b - *a).0 / fd.0.max(1)).max(1);
|
||||
for i in 0..=n {
|
||||
let u = i as f64 / n as f64;
|
||||
let t = if i == n { *b } else { *a + Tick(fd.0 * i) };
|
||||
let f = |x: f64, y: f64| if x.abs() < 1e-9 || y.abs() < 1e-9 || x.signum() != y.signum() { x + (y - x) * u } else { x * (y / x).powf(u) };
|
||||
let v = [f(va[0], vb[0]), f(va[1], vb[1]), f(va[2], vb[2])];
|
||||
let mut k = Keyframe::new(t, KV::Vec3(v));
|
||||
k.in_interp = Interp::Linear;
|
||||
k.out_interp = Interp::Linear;
|
||||
effectcraft_keyframe::set_key(&mut pr.keys, k);
|
||||
st.selected_keys.push(KeyRef { layer: *lid, prop: *uid, time: t });
|
||||
}
|
||||
done += 1;
|
||||
}
|
||||
st.selected_keys.sort_by_key(|k| (k.layer.0, k.prop, k.time));
|
||||
st.selected_keys.dedup();
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"properties": done}))
|
||||
}
|
||||
|
||||
fn time_reverse_keys(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let groups = keys_by_prop(s);
|
||||
let n = groups.len();
|
||||
s.edit("Time-Reverse Keyframes", None, |proj, st| {
|
||||
st.selected_keys.clear();
|
||||
for ((lid, uid), times) in &groups {
|
||||
let (Some(lo), Some(hi)) = (times.iter().min().copied(), times.iter().max().copied()) else { continue };
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let Some(pr) = l.props.find_mut(*uid) else { continue };
|
||||
let (mut moved, rest): (Vec<Keyframe>, Vec<Keyframe>) = pr.keys.drain(..).partition(|k| times.contains(&k.time));
|
||||
for k in &mut moved {
|
||||
k.time = lo + hi - k.time;
|
||||
std::mem::swap(&mut k.in_interp, &mut k.out_interp);
|
||||
std::mem::swap(&mut k.in_ease, &mut k.out_ease);
|
||||
std::mem::swap(&mut k.spatial_in, &mut k.spatial_out);
|
||||
st.selected_keys.push(KeyRef { layer: *lid, prop: *uid, time: k.time });
|
||||
}
|
||||
pr.keys = rest;
|
||||
for k in moved {
|
||||
effectcraft_keyframe::set_key(&mut pr.keys, k);
|
||||
if let Some(v) = influence {
|
||||
e.influence = v;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"properties": n}))
|
||||
if out {
|
||||
k.out_interp = Interp::Bezier;
|
||||
} else {
|
||||
k.in_interp = Interp::Bezier;
|
||||
}
|
||||
k.auto_bezier = false;
|
||||
// Continuous Bezier keys keep matching speeds on both sides.
|
||||
if k.continuous {
|
||||
let src = if out { k.out_ease.clone() } else { k.in_ease.clone() };
|
||||
let other = if out { &mut k.in_ease } else { &mut k.out_ease };
|
||||
if other.len() != src.len() {
|
||||
*other = src.clone();
|
||||
}
|
||||
for (o, sv) in other.iter_mut().zip(&src) {
|
||||
o.speed = sv.speed;
|
||||
}
|
||||
k.in_interp = Interp::Bezier;
|
||||
k.out_interp = Interp::Bezier;
|
||||
}
|
||||
Ok(Value::Null)
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- text animators
|
||||
|
||||
fn add_selector(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").unwrap_or("range");
|
||||
if kind != "range" {
|
||||
return Err(bad("text.addSelector", "only Range selectors are available"));
|
||||
/// Speed units for a property (Keyframe Velocity dialog).
|
||||
fn units(pr: &Property) -> &'static str {
|
||||
use effectcraft_project::ParamUi;
|
||||
if pr.spatial {
|
||||
return "pixels/sec";
|
||||
}
|
||||
let (cid, lid) = layer_p(s, p, "text.addSelector")?;
|
||||
// Target: a selected animator (or anything inside one), else the last animator.
|
||||
let sel: Vec<Uid> = s.state.selected_props.iter().filter(|(l, _)| *l == lid).map(|(_, u)| *u).collect();
|
||||
let uid = s.edit("Add Text Selector", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let anims = l.props.group_mut("text/animators").ok_or_else(|| bad("text.addSelector", "not a text layer"))?;
|
||||
if anims.children.is_empty() {
|
||||
return Err(bad("text.addSelector", "the layer has no text animators (use Animate Text first)"));
|
||||
}
|
||||
let idx = anims
|
||||
.children
|
||||
match pr.ui {
|
||||
ParamUi::Angle => "degrees/sec",
|
||||
ParamUi::Percent => "%/sec",
|
||||
ParamUi::Slider { .. } if pr.match_id == "opacity" => "%/sec",
|
||||
_ if pr.match_id == "opacity" => "%/sec",
|
||||
ParamUi::Pixels => "pixels/sec",
|
||||
_ => "units/sec",
|
||||
}
|
||||
}
|
||||
|
||||
fn interp_name(i: Interp) -> &'static str {
|
||||
match i {
|
||||
Interp::Linear => "linear",
|
||||
Interp::Bezier => "bezier",
|
||||
Interp::Hold => "hold",
|
||||
}
|
||||
}
|
||||
|
||||
/// Describe the selected (or given) keys: interpolation, eases per side and dimension, units.
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let refs: Vec<KeyRef> = match p.get("keys") {
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.position(|c| c.as_group().is_some_and(|g| sel.contains(&g.uid) || sel.iter().any(|u| g.find(*u).is_some() || g.find_group(*u).is_some())))
|
||||
.unwrap_or(anims.children.len() - 1);
|
||||
let Some(Node::Group(anim)) = anims.children.get_mut(idx) else { return Err(bad("text.addSelector", "no animator")) };
|
||||
let sels = anim.sub_mut("selectors").ok_or_else(|| bad("text.addSelector", "animator has no selectors group"))?;
|
||||
let mut ids = Ids(&mut next);
|
||||
let g = build::range_selector(&mut ids, &format!("Range Selector {}", sels.children.len() + 1));
|
||||
let uid = g.uid;
|
||||
sels.children.push(g.into());
|
||||
proj.next_id = next;
|
||||
Ok(uid)
|
||||
})?;
|
||||
Ok(json!({"selector": uid}))
|
||||
}
|
||||
|
||||
fn remove_all_animators(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
s.edit("Remove All Text Animators", None, |proj, _| {
|
||||
for lid in &ids {
|
||||
if let Some(a) = layer_mut(proj, cid, *lid)?.props.group_mut("text/animators") {
|
||||
a.children.clear();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- reveal
|
||||
|
||||
/// Whether a static property differs from the value a fresh layer would have. Transform
|
||||
/// defaults depend on the source size and comp size.
|
||||
fn modified(pr: &Property, group: &str, default_anchor: [f64; 2], comp_center: [f64; 2]) -> bool {
|
||||
if pr.is_animated() || pr.expr.is_some() {
|
||||
return true;
|
||||
}
|
||||
let v = &pr.value;
|
||||
let near = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6);
|
||||
match (group, pr.match_id.as_str()) {
|
||||
("transform", "anchor") => !near(&v.as_vec2(), &default_anchor),
|
||||
("transform", "position") => !near(&v.as_vec2(), &comp_center) || v.as_vec3()[2].abs() > 1e-6,
|
||||
("transform", "scale") => !near(&v.as_vec3(), &[100.0; 3]),
|
||||
("transform", "opacity") => (v.as_f64() - 100.0).abs() > 1e-6,
|
||||
("transform", "orientation") => !near(&v.as_vec3(), &[0.0; 3]),
|
||||
("transform", _) => v.as_f64().abs() > 1e-6,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").unwrap_or("keyframes").to_string();
|
||||
let cid = super::comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layers: Vec<LayerId> = if s.state.selected_layers.is_empty() { comp.layers.iter().map(|l| l.id).collect() } else { s.state.selected_layers.clone() };
|
||||
.filter_map(|k| {
|
||||
let l = super::resolve_layer(comp, k.get("layer")?)?;
|
||||
Some(KeyRef { layer: l, prop: k.get("prop")?.as_u64()?, time: Tick::from_seconds_f64(k.get("time")?.as_f64()?) })
|
||||
})
|
||||
.collect(),
|
||||
_ => s.state.selected_keys.clone(),
|
||||
};
|
||||
let mut out = vec![];
|
||||
for lid in &layers {
|
||||
let Some(l) = comp.layer(*lid) else { continue };
|
||||
let (w, h) = effectcraft_render::source_size(&s.project, l);
|
||||
let anchor = [w as f64 / 2.0, h as f64 / 2.0];
|
||||
let center = [comp.width as f64 / 2.0, comp.height as f64 / 2.0];
|
||||
for top in l.props.groups() {
|
||||
let hit = |pr: &Property| match kind.as_str() {
|
||||
"keyframes" => pr.is_animated(),
|
||||
"animation" => pr.is_animated() || pr.has_expression(),
|
||||
_ => modified(pr, &top.match_id, anchor, center),
|
||||
};
|
||||
let mut found = vec![];
|
||||
top.walk("", &mut |_, pr| {
|
||||
if hit(pr) {
|
||||
found.push(pr.uid);
|
||||
}
|
||||
});
|
||||
// Modified: effects and masks count as modifications in full (AE reveals them).
|
||||
if kind == "modified" && matches!(top.match_id.as_str(), "effects" | "masks") {
|
||||
for g in top.groups() {
|
||||
found.push(g.uid);
|
||||
}
|
||||
}
|
||||
if kind == "modified" && top.match_id == "text" {
|
||||
for g in top.group("animators").into_iter().flat_map(|a| a.groups()) {
|
||||
found.push(g.uid);
|
||||
}
|
||||
}
|
||||
out.extend(found.into_iter().map(|u| json!({"layer": lid.0, "prop": u})));
|
||||
}
|
||||
for r in refs {
|
||||
let Some(l) = comp.layer(r.layer) else { continue };
|
||||
let Some(pr) = l.props.find(r.prop) else { continue };
|
||||
let Some(i) = nearest_key(&pr.keys, r.time) else { continue };
|
||||
let k = &pr.keys[i];
|
||||
let spatial = pr.spatial && matches!(k.value, effectcraft_keyframe::Value::Vec2(_) | effectcraft_keyframe::Value::Vec3(_));
|
||||
let dims = if spatial { 1 } else { k.value.dims().max(1).min(if pr.shown_dims > 0 && !l.is_3d() { pr.shown_dims as usize } else { 4 }) };
|
||||
let side = |out: bool| -> Value {
|
||||
json!(
|
||||
(0..dims)
|
||||
.map(|d| side_ease(&pr.keys, i, d, pr.spatial, out)
|
||||
.map(|e| json!({"speed": e.speed, "influence": e.influence * 100.0}))
|
||||
.unwrap_or(Value::Null))
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
};
|
||||
let temporal = if k.auto_bezier {
|
||||
"autoBezier"
|
||||
} else if k.continuous {
|
||||
"continuousBezier"
|
||||
} else if k.in_interp == k.out_interp {
|
||||
interp_name(k.in_interp)
|
||||
} else {
|
||||
"mixed"
|
||||
};
|
||||
let spatial_kind = if !spatial {
|
||||
Value::Null
|
||||
} else if k.spatial_auto {
|
||||
json!("autoBezier")
|
||||
} else if k.spatial_continuous {
|
||||
json!("continuousBezier")
|
||||
} else if k.spatial_in == [0.0; 3] && k.spatial_out == [0.0; 3] {
|
||||
json!("linear")
|
||||
} else {
|
||||
json!("bezier")
|
||||
};
|
||||
out.push(json!({
|
||||
"layer": l.id.0, "prop": pr.uid, "name": pr.name, "path": l.props.match_path_of(pr.uid),
|
||||
"time": k.time.seconds(), "compTime": l.comp_time(k.time).seconds(), "value": k.value.to_json(),
|
||||
"in": interp_name(k.in_interp), "out": interp_name(k.out_interp), "temporal": temporal,
|
||||
"autoBezier": k.auto_bezier, "continuous": k.continuous, "roving": k.roving, "spatial": spatial_kind,
|
||||
"dims": dims, "units": units(pr), "inEase": side(false), "outEase": side(true),
|
||||
}));
|
||||
}
|
||||
frontend(s, "timeline.revealProps", &json!({"props": out, "kind": kind}))?;
|
||||
Ok(json!({"props": out}))
|
||||
Ok(json!(out))
|
||||
}
|
||||
|
||||
/// Is `g` an effect/mask group kind (used by tests).
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn is_indexed(g: &PropGroup) -> bool {
|
||||
matches!(g.kind, GroupKind::Indexed | GroupKind::Mask { .. } | GroupKind::Effect { .. })
|
||||
/// Keyframe Assistant ▸ Time-Reverse Keyframes: mirror the selected keys of each property.
|
||||
fn time_reverse(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let sel = s.state.selected_keys.clone();
|
||||
s.edit("Time-Reverse Keyframes", None, |proj, st| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
|
||||
for k in &sel {
|
||||
groups.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
let mut new_sel = vec![];
|
||||
for ((lid, uid), times) in groups {
|
||||
let Some(pr) = comp.layer_mut(lid).and_then(|l| l.props.find_mut(uid)) else { continue };
|
||||
let (mut picked, rest): (Vec<Keyframe>, Vec<Keyframe>) = pr.keys.drain(..).partition(|k| times.contains(&k.time));
|
||||
effectcraft_keyframe::time_reverse(&mut picked);
|
||||
new_sel.extend(picked.iter().map(|k| KeyRef { layer: lid, prop: uid, time: k.time }));
|
||||
pr.keys = rest;
|
||||
for k in picked {
|
||||
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
|
||||
Ok(i) => pr.keys[i] = k,
|
||||
Err(i) => pr.keys.insert(i, k),
|
||||
}
|
||||
}
|
||||
}
|
||||
st.selected_keys = new_sel;
|
||||
Ok(json!(st.selected_keys.len()))
|
||||
})
|
||||
}
|
||||
|
||||
fn keys_or_layers(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("keys.copy", "Copy Keyframes", [], None, "{}", has_keys, copy),
|
||||
cmd!("keys.paste", "Paste Keyframes", [], None, "{layers?, prop?|path?, time?}", has_key_clip, paste),
|
||||
cmd!("keys.selectAll", "Select All Keyframes", [], Some("Cmd+Alt+A"), "{layers?}", keys_or_layers, select_all),
|
||||
cmd!("keys.nudge", "Nudge Keyframes", [], None, "{frames, merge?}", has_keys, nudge),
|
||||
cmd!("keys.nudgeForward", "Move Keyframes 1 Frame Later", [], Some("Alt+ArrowRight"), "{}", has_keys, |s, _| nudge(s, &json!({"frames": 1}))),
|
||||
cmd!("keys.nudgeBackward", "Move Keyframes 1 Frame Earlier", [], Some("Alt+ArrowLeft"), "{}", has_keys, |s, _| nudge(s, &json!({"frames": -1}))),
|
||||
cmd!("keys.nudgeForward10", "Move Keyframes 10 Frames Later", [], Some("Alt+Shift+ArrowRight"), "{}", has_keys, |s, _| nudge(
|
||||
s,
|
||||
&json!({"frames": 10})
|
||||
)),
|
||||
cmd!("keys.nudgeBackward10", "Move Keyframes 10 Frames Earlier", [], Some("Alt+Shift+ArrowLeft"), "{}", has_keys, |s, _| nudge(
|
||||
s,
|
||||
&json!({"frames": -10})
|
||||
)),
|
||||
cmd!("keys.set", "Edit Keyframe", [], None, "{layer?, path|prop, time (layer s), newTime?, value?, merge?}", has_comp, set_key),
|
||||
cmd!(
|
||||
"anim.savePreset",
|
||||
"Save Animation Preset...",
|
||||
["Animation"],
|
||||
"keys.setEase",
|
||||
"Set Keyframe Ease",
|
||||
[],
|
||||
None,
|
||||
"{path (.ecpreset), name?} — saves the selected properties/effects",
|
||||
has_selected_props,
|
||||
save_preset
|
||||
"{layer?, path|prop, time (layer s), side: in|out, dim?, speed?, influence? %, merge?}",
|
||||
has_comp,
|
||||
set_ease
|
||||
),
|
||||
cmd!("anim.applyPreset", "Apply Animation Preset...", ["Animation"], None, "{path | preset, layers?}", has_layers, apply_preset),
|
||||
cmd!("anim.addKeyframe", "Add Keyframe", ["Animation"], None, "{} — keys the selected properties at the CTI", has_selected_props, add_keyframe),
|
||||
cmd!(
|
||||
"keys.exponentialScale",
|
||||
"Exponential Scale",
|
||||
["Animation", "Keyframe Assistant"],
|
||||
None,
|
||||
"{} — two selected Scale keys",
|
||||
has_keys,
|
||||
exponential_scale
|
||||
),
|
||||
cmd!("keys.timeReverse", "Time-Reverse Keyframes", ["Animation", "Keyframe Assistant"], None, "{}", has_keys, time_reverse_keys),
|
||||
cmd!("text.addSelector", "Add Text Selector", [], None, "{layer?, kind: range}", has_text_layer, add_selector),
|
||||
cmd!("text.removeAllAnimators", "Remove All Text Animators", ["Animation"], None, "{layers?}", has_text_layer, remove_all_animators),
|
||||
cmd!("anim.reveal", "Reveal Properties", [], None, "{kind: keyframes|animation|modified}", has_comp, reveal),
|
||||
cmd!("keys.timeReverse", "Time-Reverse Keyframes", ["Animation", "Keyframe Assistant"], None, "{}", has_keys, time_reverse),
|
||||
query!("keys.info", "Keyframe Info", "{keys?: [{layer, prop, time}]}", info),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Animation menu: animation presets (EffectCraft's own JSON format), Add Keyframe, Keyframe
|
||||
//! Assistant (Exponential Scale), text animators/selectors, and the
|
||||
//! Reveal Properties commands.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use effectcraft_keyframe::{Interp, Keyframe, Value as KV};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{GroupKind, LayerId, Node, PropGroup, Property, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, frontend, has_comp, has_keys, has_layers, layer_mut, layer_p, layers_p, match_path_of, selected_leaf_props, str_p};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd};
|
||||
|
||||
/// Preset file format version tag (`*.ecpreset`, JSON).
|
||||
pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
|
||||
|
||||
fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)?;
|
||||
if selected_leaf_props(s).is_empty() && selected_effects(s).is_empty() { Err("select properties or effects first".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn has_text_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
has_layers(s)?;
|
||||
let c = s.active_comp().ok_or("no composition")?;
|
||||
if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| l.props.group("text/animators").is_some()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("select a text layer".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Selected effect groups (layer, effect group).
|
||||
fn selected_effects(s: &Session) -> Vec<(LayerId, PropGroup)> {
|
||||
let Some(c) = s.active_comp() else { return vec![] };
|
||||
s.state
|
||||
.selected_props
|
||||
.iter()
|
||||
.filter_map(|(l, u)| {
|
||||
let layer = c.layer(*l)?;
|
||||
let fx = layer.effects()?;
|
||||
fx.groups().find(|g| g.uid == *u).map(|g| (*l, g.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- presets
|
||||
|
||||
fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_p(p, "path").ok_or_else(|| bad("anim.savePreset", "missing `path`"))?.to_string();
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let t = s.time();
|
||||
let effects: Vec<(LayerId, PropGroup)> = selected_effects(s);
|
||||
let effect_uids: Vec<Uid> = effects.iter().map(|(_, g)| g.uid).collect();
|
||||
let mut props = vec![];
|
||||
for (lid, uid) in selected_leaf_props(s) {
|
||||
let Some(l) = comp.layer(lid) else { continue };
|
||||
// Properties inside a saved effect travel with the effect.
|
||||
if l.effects().is_some_and(|fx| fx.groups().any(|g| effect_uids.contains(&g.uid) && g.find(uid).is_some())) {
|
||||
continue;
|
||||
}
|
||||
let (Some(pr), Some(mp)) = (l.props.find(uid), match_path_of(&l.props, uid)) else { continue };
|
||||
props.push((l.layer_time(t), mp, pr.clone()));
|
||||
}
|
||||
if props.is_empty() && effects.is_empty() {
|
||||
return Err(bad("anim.savePreset", "select properties or effects to save"));
|
||||
}
|
||||
// Key times are stored relative to the earliest key so the preset applies at the CTI.
|
||||
let first = props.iter().flat_map(|(_, _, pr)| pr.keys.iter().map(|k| k.time)).min().unwrap_or(Tick::ZERO);
|
||||
let props_json: Vec<Value> = props
|
||||
.iter()
|
||||
.map(|(_, mp, pr)| {
|
||||
let mut pr = pr.clone();
|
||||
for k in &mut pr.keys {
|
||||
k.time -= first;
|
||||
}
|
||||
json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr})
|
||||
})
|
||||
.collect();
|
||||
let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
|
||||
let name = str_p(p, "name")
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
|
||||
let doc = json!({PRESET_TAG: 1, "name": name, "properties": props_json, "effects": fx_json});
|
||||
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
|
||||
s.services.write_file(&path, text.as_bytes()).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
|
||||
Ok(json!({"path": path, "properties": props.len(), "effects": effects.len()}))
|
||||
}
|
||||
|
||||
fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc: Value = match (p.get("preset"), str_p(p, "path")) {
|
||||
(Some(v), _) => v.clone(),
|
||||
(None, Some(path)) => {
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
serde_json::from_slice(&bytes).map_err(|e| bad("anim.applyPreset", format!("not a preset: {e}")))?
|
||||
}
|
||||
_ => return Err(bad("anim.applyPreset", "missing `path` (or inline `preset`)")),
|
||||
};
|
||||
if doc.get(PRESET_TAG).is_none() {
|
||||
return Err(bad("anim.applyPreset", "not an EffectCraft animation preset"));
|
||||
}
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("anim.applyPreset", "select a layer"));
|
||||
}
|
||||
let effects: Vec<PropGroup> =
|
||||
doc["effects"].as_array().map(|a| a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect()).unwrap_or_default();
|
||||
let props: Vec<(String, Property)> = doc["properties"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| {
|
||||
let path = v["path"].as_str()?.to_string();
|
||||
let value: KV = serde_json::from_value(v["value"].clone()).ok()?;
|
||||
let keys: Vec<Keyframe> = serde_json::from_value(v["keys"].clone()).unwrap_or_default();
|
||||
let expr = serde_json::from_value(v["expression"].clone()).ok().flatten();
|
||||
let mut pr = Property::new(0, "", "", value);
|
||||
pr.keys = keys;
|
||||
pr.expr = expr;
|
||||
Some((path, pr))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let t = s.time();
|
||||
let mut applied = 0;
|
||||
let mut skipped = vec![];
|
||||
s.edit("Apply Animation Preset", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
for lid in &ids {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
if let Some(fx) = l.props.sub_mut("effects") {
|
||||
for g in &effects {
|
||||
let mut g = g.clone();
|
||||
g.reassign_uids(&mut next);
|
||||
next += 1;
|
||||
fx.children.push(Node::Group(g));
|
||||
applied += 1;
|
||||
}
|
||||
}
|
||||
for (path, src) in &props {
|
||||
match l.props.prop_mut(path) {
|
||||
Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
|
||||
pr.value = src.value.clone();
|
||||
pr.keys = src
|
||||
.keys
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut k| {
|
||||
k.time += lt;
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
if src.expr.is_some() {
|
||||
pr.expr = src.expr.clone();
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
_ => skipped.push(path.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
proj.next_id = next;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"applied": applied, "skipped": skipped}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- keyframes
|
||||
|
||||
fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let targets = selected_leaf_props(s);
|
||||
if targets.is_empty() {
|
||||
return Err(bad("anim.addKeyframe", "select properties first"));
|
||||
}
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let t = s.time();
|
||||
let n = s.edit("Add Keyframe", None, |proj, _| {
|
||||
let mut n = 0;
|
||||
for (lid, uid) in &targets {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
let Some(pr) = l.props.find_mut(*uid) else { continue };
|
||||
if pr.static_only {
|
||||
continue;
|
||||
}
|
||||
if pr.keys.is_empty() {
|
||||
pr.set_animated(true, lt);
|
||||
} else {
|
||||
let v = pr.value_at(lt);
|
||||
pr.set_value_at(lt, v);
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
})?;
|
||||
Ok(json!({"keys": n}))
|
||||
}
|
||||
|
||||
/// Selected keys grouped by (layer, property).
|
||||
fn keys_by_prop(s: &Session) -> BTreeMap<(LayerId, Uid), Vec<Tick>> {
|
||||
let mut m: BTreeMap<(LayerId, Uid), Vec<Tick>> = BTreeMap::new();
|
||||
for k in &s.state.selected_keys {
|
||||
m.entry((k.layer, k.prop)).or_default().push(k.time);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn exponential_scale(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let fd = comp.frame_duration();
|
||||
let groups = keys_by_prop(s);
|
||||
let mut done = 0;
|
||||
let mut work = vec![];
|
||||
for ((lid, uid), mut times) in groups {
|
||||
let Some(l) = comp.layer(lid) else { continue };
|
||||
if l.transform().and_then(|tr| tr.get("scale")).map(|p| p.uid) != Some(uid) {
|
||||
continue;
|
||||
}
|
||||
times.sort();
|
||||
if times.len() >= 2 {
|
||||
work.push((lid, uid, times[0], *times.last().unwrap_or(×[0])));
|
||||
}
|
||||
}
|
||||
if work.is_empty() {
|
||||
return Err(bad("keys.exponentialScale", "select two Scale keyframes"));
|
||||
}
|
||||
s.edit("Exponential Scale", None, |proj, st| {
|
||||
for (lid, uid, a, b) in &work {
|
||||
let l = layer_mut(proj, cid, *lid)?;
|
||||
let Some(pr) = l.props.find_mut(*uid) else { continue };
|
||||
let (va, vb) = (pr.value_at(*a).as_vec3(), pr.value_at(*b).as_vec3());
|
||||
pr.keys.retain(|k| k.time <= *a || k.time >= *b);
|
||||
let n = ((*b - *a).0 / fd.0.max(1)).max(1);
|
||||
for i in 0..=n {
|
||||
let u = i as f64 / n as f64;
|
||||
let t = if i == n { *b } else { *a + Tick(fd.0 * i) };
|
||||
let f = |x: f64, y: f64| if x.abs() < 1e-9 || y.abs() < 1e-9 || x.signum() != y.signum() { x + (y - x) * u } else { x * (y / x).powf(u) };
|
||||
let v = [f(va[0], vb[0]), f(va[1], vb[1]), f(va[2], vb[2])];
|
||||
let mut k = Keyframe::new(t, KV::Vec3(v));
|
||||
k.in_interp = Interp::Linear;
|
||||
k.out_interp = Interp::Linear;
|
||||
effectcraft_keyframe::set_key(&mut pr.keys, k);
|
||||
st.selected_keys.push(KeyRef { layer: *lid, prop: *uid, time: t });
|
||||
}
|
||||
done += 1;
|
||||
}
|
||||
st.selected_keys.sort_by_key(|k| (k.layer.0, k.prop, k.time));
|
||||
st.selected_keys.dedup();
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"properties": done}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- text animators
|
||||
|
||||
fn add_selector(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").unwrap_or("range");
|
||||
if kind != "range" {
|
||||
return Err(bad("text.addSelector", "only Range selectors are available"));
|
||||
}
|
||||
let (cid, lid) = layer_p(s, p, "text.addSelector")?;
|
||||
// Target: a selected animator (or anything inside one), else the last animator.
|
||||
let sel: Vec<Uid> = s.state.selected_props.iter().filter(|(l, _)| *l == lid).map(|(_, u)| *u).collect();
|
||||
let uid = s.edit("Add Text Selector", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let anims = l.props.group_mut("text/animators").ok_or_else(|| bad("text.addSelector", "not a text layer"))?;
|
||||
if anims.children.is_empty() {
|
||||
return Err(bad("text.addSelector", "the layer has no text animators (use Animate Text first)"));
|
||||
}
|
||||
let idx = anims
|
||||
.children
|
||||
.iter()
|
||||
.position(|c| c.as_group().is_some_and(|g| sel.contains(&g.uid) || sel.iter().any(|u| g.find(*u).is_some() || g.find_group(*u).is_some())))
|
||||
.unwrap_or(anims.children.len() - 1);
|
||||
let Some(Node::Group(anim)) = anims.children.get_mut(idx) else { return Err(bad("text.addSelector", "no animator")) };
|
||||
let sels = anim.sub_mut("selectors").ok_or_else(|| bad("text.addSelector", "animator has no selectors group"))?;
|
||||
let mut ids = Ids(&mut next);
|
||||
let g = build::range_selector(&mut ids, &format!("Range Selector {}", sels.children.len() + 1));
|
||||
let uid = g.uid;
|
||||
sels.children.push(g.into());
|
||||
proj.next_id = next;
|
||||
Ok(uid)
|
||||
})?;
|
||||
Ok(json!({"selector": uid}))
|
||||
}
|
||||
|
||||
fn remove_all_animators(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
s.edit("Remove All Text Animators", None, |proj, _| {
|
||||
for lid in &ids {
|
||||
if let Some(a) = layer_mut(proj, cid, *lid)?.props.group_mut("text/animators") {
|
||||
a.children.clear();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- reveal
|
||||
|
||||
/// Whether a static property differs from the value a fresh layer would have. Transform
|
||||
/// defaults depend on the source size and comp size.
|
||||
fn modified(pr: &Property, group: &str, default_anchor: [f64; 2], comp_center: [f64; 2]) -> bool {
|
||||
if pr.is_animated() || pr.expr.is_some() {
|
||||
return true;
|
||||
}
|
||||
let v = &pr.value;
|
||||
let near = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6);
|
||||
match (group, pr.match_id.as_str()) {
|
||||
("transform", "anchor") => !near(&v.as_vec2(), &default_anchor),
|
||||
("transform", "position") => !near(&v.as_vec2(), &comp_center) || v.as_vec3()[2].abs() > 1e-6,
|
||||
("transform", "scale") => !near(&v.as_vec3(), &[100.0; 3]),
|
||||
("transform", "opacity") => (v.as_f64() - 100.0).abs() > 1e-6,
|
||||
("transform", "orientation") => !near(&v.as_vec3(), &[0.0; 3]),
|
||||
("transform", _) => v.as_f64().abs() > 1e-6,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").unwrap_or("keyframes").to_string();
|
||||
let cid = super::comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layers: Vec<LayerId> = if s.state.selected_layers.is_empty() { comp.layers.iter().map(|l| l.id).collect() } else { s.state.selected_layers.clone() };
|
||||
let mut out = vec![];
|
||||
for lid in &layers {
|
||||
let Some(l) = comp.layer(*lid) else { continue };
|
||||
let (w, h) = effectcraft_render::source_size(&s.project, l);
|
||||
let anchor = [w as f64 / 2.0, h as f64 / 2.0];
|
||||
let center = [comp.width as f64 / 2.0, comp.height as f64 / 2.0];
|
||||
for top in l.props.groups() {
|
||||
let hit = |pr: &Property| match kind.as_str() {
|
||||
"keyframes" => pr.is_animated(),
|
||||
"animation" => pr.is_animated() || pr.has_expression(),
|
||||
_ => modified(pr, &top.match_id, anchor, center),
|
||||
};
|
||||
let mut found = vec![];
|
||||
top.walk("", &mut |_, pr| {
|
||||
if hit(pr) {
|
||||
found.push(pr.uid);
|
||||
}
|
||||
});
|
||||
// Modified: effects and masks count as modifications in full (AE reveals them).
|
||||
if kind == "modified" && matches!(top.match_id.as_str(), "effects" | "masks") {
|
||||
for g in top.groups() {
|
||||
found.push(g.uid);
|
||||
}
|
||||
}
|
||||
if kind == "modified" && top.match_id == "text" {
|
||||
for g in top.group("animators").into_iter().flat_map(|a| a.groups()) {
|
||||
found.push(g.uid);
|
||||
}
|
||||
}
|
||||
out.extend(found.into_iter().map(|u| json!({"layer": lid.0, "prop": u})));
|
||||
}
|
||||
}
|
||||
frontend(s, "timeline.revealProps", &json!({"props": out, "kind": kind}))?;
|
||||
Ok(json!({"props": out}))
|
||||
}
|
||||
|
||||
/// Is `g` an effect/mask group kind (used by tests).
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn is_indexed(g: &PropGroup) -> bool {
|
||||
matches!(g.kind, GroupKind::Indexed | GroupKind::Mask { .. } | GroupKind::Effect { .. })
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"anim.savePreset",
|
||||
"Save Animation Preset...",
|
||||
["Animation"],
|
||||
None,
|
||||
"{path (.ecpreset), name?} — saves the selected properties/effects",
|
||||
has_selected_props,
|
||||
save_preset
|
||||
),
|
||||
cmd!("anim.applyPreset", "Apply Animation Preset...", ["Animation"], None, "{path | preset, layers?}", has_layers, apply_preset),
|
||||
cmd!("anim.addKeyframe", "Add Keyframe", ["Animation"], None, "{} — keys the selected properties at the CTI", has_selected_props, add_keyframe),
|
||||
cmd!(
|
||||
"keys.exponentialScale",
|
||||
"Exponential Scale",
|
||||
["Animation", "Keyframe Assistant"],
|
||||
None,
|
||||
"{} — two selected Scale keys",
|
||||
has_keys,
|
||||
exponential_scale
|
||||
),
|
||||
cmd!("text.addSelector", "Add Text Selector", [], None, "{layer?, kind: range}", has_text_layer, add_selector),
|
||||
cmd!("text.removeAllAnimators", "Remove All Text Animators", ["Animation"], None, "{layers?}", has_text_layer, remove_all_animators),
|
||||
cmd!("anim.reveal", "Reveal Properties", [], None, "{kind: keyframes|animation|modified}", has_comp, reveal),
|
||||
]
|
||||
}
|
||||
@@ -13,18 +13,57 @@ pub(crate) fn rate_p(p: &Value) -> Option<FrameRate> {
|
||||
}
|
||||
|
||||
fn apply_settings(c: &mut Comp, p: &Value) {
|
||||
let (ow, oh) = (c.width, c.height);
|
||||
if let Some(w) = p.get("width").and_then(Value::as_u64) {
|
||||
c.width = (w as u32).clamp(4, 30000);
|
||||
}
|
||||
if let Some(h) = p.get("height").and_then(Value::as_u64) {
|
||||
c.height = (h as u32).clamp(4, 30000);
|
||||
}
|
||||
// Advanced › Anchor: where the old frame sits in the resized one (0 = top left … 4 = center …
|
||||
// 8 = bottom right). Unparented layers (and all their position keys) move by that offset.
|
||||
if (c.width, c.height) != (ow, oh) {
|
||||
let a = p.get("anchor").and_then(Value::as_u64).unwrap_or(4).min(8);
|
||||
let dx = (c.width as f64 - ow as f64) * (a % 3) as f64 / 2.0;
|
||||
let dy = (c.height as f64 - oh as f64) * (a / 3) as f64 / 2.0;
|
||||
if dx != 0.0 || dy != 0.0 {
|
||||
for l in c.layers.iter_mut().filter(|l| l.parent.is_none()) {
|
||||
let Some(pr) = l.props.prop_mut("transform/position") else { continue };
|
||||
let shift = |v: &mut effectcraft_keyframe::Value| {
|
||||
if let effectcraft_keyframe::Value::Vec2(x) = v {
|
||||
x[0] += dx;
|
||||
x[1] += dy;
|
||||
} else if let effectcraft_keyframe::Value::Vec3(x) = v {
|
||||
x[0] += dx;
|
||||
x[1] += dy;
|
||||
}
|
||||
};
|
||||
shift(&mut pr.value);
|
||||
for k in &mut pr.keys {
|
||||
shift(&mut k.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = f_p(p, "startTime") {
|
||||
c.display_start = Tick::from_seconds_f64(t);
|
||||
} else if let Some(tc) = str_p(p, "startTimecode")
|
||||
&& let Ok(f) = effectcraft_time::parse_timecode(tc, c.frame_rate, c.frame_rate.supports_drop_frame(), 0)
|
||||
{
|
||||
c.display_start = c.frame_rate.tick_of(f);
|
||||
}
|
||||
match str_p(p, "renderer").map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("classic3d" | "classic") => c.renderer = effectcraft_project::Renderer::Classic3D,
|
||||
Some("advanced3d" | "advanced") => c.renderer = effectcraft_project::Renderer::Advanced3D,
|
||||
_ => {}
|
||||
}
|
||||
if let Some(r) = rate_p(p) {
|
||||
c.frame_rate = r;
|
||||
}
|
||||
if let Some(d) = f_p(p, "duration") {
|
||||
let old = c.duration;
|
||||
c.duration = Tick::from_seconds_f64(d.max(c.frame_rate.frame_duration().seconds()));
|
||||
// Whole frames, at least one.
|
||||
c.duration = c.frame_rate.snap_nearest(Tick::from_seconds_f64(d)).max(c.frame_rate.frame_duration());
|
||||
if c.work_area.1 == old {
|
||||
c.work_area.1 = c.duration;
|
||||
}
|
||||
@@ -53,7 +92,7 @@ fn apply_settings(c: &mut Comp, p: &Value) {
|
||||
fn new_comp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_p(p, "name").unwrap_or("Comp 1").to_string();
|
||||
let rate = rate_p(p).unwrap_or(FrameRate::FPS_29_97);
|
||||
let mut c = Comp::new(1920, 1080, rate, Tick::from_seconds_f64(10.0));
|
||||
let mut c = Comp::new(1920, 1080, rate, rate.snap_nearest(Tick::from_seconds_f64(10.0)));
|
||||
apply_settings(&mut c, p);
|
||||
let id = s.edit("New Composition", None, |proj, st| {
|
||||
let mut name = name.clone();
|
||||
@@ -205,7 +244,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Composition...",
|
||||
["Composition"],
|
||||
Some("Cmd+N"),
|
||||
"{name?, width?, height?, frameRate?, duration? (s), background? [r,g,b]|#hex, open?}",
|
||||
"{name?, width?, height?, frameRate?, duration? (s), startTime? (s) | startTimecode?, background? [r,g,b]|#hex, pixelAspect?, shutterAngle?, shutterPhase?, motionBlurSamples?, renderer? classic3D|advanced3D, anchor?, open?}",
|
||||
always,
|
||||
new_comp
|
||||
),
|
||||
@@ -214,7 +253,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composition Settings...",
|
||||
["Composition"],
|
||||
Some("Cmd+K"),
|
||||
"{comp?, name?, width?, height?, frameRate?, duration?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?}",
|
||||
"{comp?, name?, width?, height?, anchor? 0-8 (resize anchor, 4 = center), frameRate?, duration?, startTime? (s) | startTimecode?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?, pixelAspect?, renderer? classic3D|advanced3D}",
|
||||
has_comp,
|
||||
settings
|
||||
),
|
||||
|
||||
@@ -6,7 +6,7 @@ use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, has_comp, has_layers, layers_p, match_path_of, selected_leaf_props, str_p};
|
||||
use crate::{EngineError, KeyClip, LinkClip, Result, Session, cmd};
|
||||
use crate::{EngineError, LinkClip, Result, Session, cmd};
|
||||
|
||||
fn can_undo(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.history.undo.is_empty() { Err("nothing to undo".into()) } else { Ok(()) }
|
||||
@@ -58,6 +58,7 @@ fn deselect_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.state.selected_layers.clear();
|
||||
s.state.selected_props.clear();
|
||||
s.state.selected_keys.clear();
|
||||
s.state.selected_vertices.clear();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -91,10 +92,13 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Keyframes selected → delete keys; else layers.
|
||||
// Keyframes selected → delete keys; mask vertices → delete them; else layers.
|
||||
if !s.state.selected_keys.is_empty() && p.get("layers").is_none() {
|
||||
return s.execute("keys.delete", json!({}));
|
||||
}
|
||||
if !s.state.selected_vertices.is_empty() && p.get("layers").is_none() {
|
||||
return s.execute("mask.deleteVertices", json!({}));
|
||||
}
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
s.edit("Clear", None, |proj, st| {
|
||||
let comp = proj.comp_mut(cid).ok_or(crate::EngineError::NoComp)?;
|
||||
@@ -119,34 +123,18 @@ fn clear_clipboards(s: &mut Session) {
|
||||
s.state.clipboard.clear();
|
||||
s.state.key_clipboard.clear();
|
||||
s.state.link_clipboard = None;
|
||||
s.state.clip_is_keys = false;
|
||||
}
|
||||
|
||||
/// Edit ▸ Copy: selected keyframes (when any) go to the keyframe clipboard, else layers.
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.state.selected_keys.is_empty() && p.get("layers").is_none() && p.get("layer").is_none() {
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let mut clips: Vec<KeyClip> = vec![];
|
||||
let earliest = s.state.selected_keys.iter().map(|k| k.time).min().unwrap_or(Tick::ZERO);
|
||||
for k in &s.state.selected_keys {
|
||||
let Some(l) = comp.layer(k.layer) else { continue };
|
||||
let (Some(pr), Some(path)) = (l.props.find(k.prop), match_path_of(&l.props, k.prop)) else { continue };
|
||||
let Some(key) = pr.keys.iter().find(|x| x.time == k.time) else { continue };
|
||||
let mut key = key.clone();
|
||||
key.time -= earliest;
|
||||
match clips.iter_mut().find(|c| c.path == path) {
|
||||
Some(c) => c.keys.push(key),
|
||||
None => clips.push(KeyClip { path, keys: vec![key] }),
|
||||
}
|
||||
}
|
||||
for c in &mut clips {
|
||||
c.keys.sort_by_key(|k| k.time);
|
||||
}
|
||||
let n: usize = clips.iter().map(|c| c.keys.len()).sum();
|
||||
clear_clipboards(s);
|
||||
s.state.key_clipboard = clips;
|
||||
return Ok(json!({"keys": n}));
|
||||
// Keyframes selected → copy keys (pasted at the CTI).
|
||||
if !s.state.selected_keys.is_empty() && p.get("layers").is_none() {
|
||||
s.state.link_clipboard = None;
|
||||
return s.execute("keys.copy", json!({}));
|
||||
}
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
s.state.clip_is_keys = false;
|
||||
let comp = s.project.comp(cid).ok_or(crate::EngineError::NoComp)?;
|
||||
let layers: Vec<Layer> = comp.layers.iter().filter(|l| ids.contains(&l.id)).cloned().collect();
|
||||
clear_clipboards(s);
|
||||
@@ -313,6 +301,10 @@ fn paste_links(s: &mut Session, clip: LinkClip) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.state.selected_keys.is_empty() && p.get("layers").is_none() {
|
||||
s.execute("keys.copy", json!({}))?;
|
||||
return s.execute("keys.delete", json!({}));
|
||||
}
|
||||
copy(s, p)?;
|
||||
delete(s, p)
|
||||
}
|
||||
@@ -321,8 +313,8 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(clip) = s.state.link_clipboard.clone() {
|
||||
return paste_links(s, clip);
|
||||
}
|
||||
if !s.state.key_clipboard.is_empty() {
|
||||
return paste_keys(s, false);
|
||||
if s.state.clip_is_keys && !s.state.key_clipboard.is_empty() {
|
||||
return s.execute("keys.paste", p.clone());
|
||||
}
|
||||
let cid = super::comp_id(s, p)?;
|
||||
let clip = s.state.clipboard.clone();
|
||||
@@ -523,8 +515,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, undo),
|
||||
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, redo),
|
||||
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{layers?}", has_layers, cut),
|
||||
cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{layers?} (copies the selected keyframes when any, else layers)", has_props_or_layers, copy),
|
||||
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{layers?} (keyframes when keys are selected)", layers_or_keys, cut),
|
||||
cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{layers?} (keyframes when keys are selected)", layers_or_keys, copy),
|
||||
cmd!(
|
||||
"edit.copyWithPropertyLinks",
|
||||
"Copy with Property Links",
|
||||
@@ -546,7 +538,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("edit.copyExpressionOnly", "Copy Expression Only", ["Edit"], None, "{}", has_props_or_layers, copy_expression_only),
|
||||
cmd!("edit.paste", "Paste", ["Edit"], Some("Cmd+V"), "{} (layers, keyframes at the CTI, or property links / expressions)", has_clip, paste),
|
||||
cmd!("edit.pasteReversedKeyframes", "Paste Reversed Keyframes", ["Edit"], None, "{}", has_key_clip, paste_reversed),
|
||||
cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{layers?}", has_layers, delete),
|
||||
cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{layers?}", layers_or_keys, delete),
|
||||
cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+D"), "{layers?}", has_layers, duplicate),
|
||||
cmd!("edit.splitLayer", "Split Layer", ["Edit"], Some("Cmd+Shift+D"), "{layers?}", has_layers, split),
|
||||
cmd!("edit.liftWorkArea", "Lift Work Area", ["Edit"], None, "{layers?}", has_comp, lift),
|
||||
@@ -561,6 +553,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn layers_or_keys(s: &Session) -> std::result::Result<(), String> {
|
||||
if !s.state.selected_keys.is_empty() || !s.state.selected_vertices.is_empty() { super::has_comp(s) } else { has_layers(s) }
|
||||
}
|
||||
|
||||
fn always_ok(_: &Session) -> std::result::Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use effectcraft_color::{BlendMode, Label};
|
||||
use effectcraft_keyframe::{Justify, ShapePath, TextDoc, Value as KV};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{
|
||||
Comp, FrameBlend, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MaskMode, MatteKind, Project, PropGroup, Quality, Solid, TrackMatte,
|
||||
Comp, FrameBlend, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, MaskMode, MatteKind, Project, PropGroup, Quality, Solid, TrackMatte,
|
||||
};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
@@ -12,7 +12,7 @@ use serde_json::{Value, json};
|
||||
use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, resolve_layer, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
fn color_p(p: &Value, k: &str) -> Option<[f32; 3]> {
|
||||
pub(crate) fn color_p(p: &Value, k: &str) -> Option<[f32; 3]> {
|
||||
match p.get(k)? {
|
||||
Value::String(s) => effectcraft_color::Rgba::from_hex(s).map(|c| [c.r, c.g, c.b]),
|
||||
Value::Array(a) => {
|
||||
@@ -24,7 +24,7 @@ fn color_p(p: &Value, k: &str) -> Option<[f32; 3]> {
|
||||
}
|
||||
|
||||
/// Insert a new layer above the selection (or at the top) and select it.
|
||||
fn insert_layer(proj: &mut Project, st: &mut crate::EditorState, cid: ItemId, layer: Layer) -> Result<LayerId> {
|
||||
pub(crate) fn insert_layer(proj: &mut Project, st: &mut crate::EditorState, cid: ItemId, layer: Layer) -> Result<LayerId> {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let at = st.selected_layers.first().and_then(|id| comp.layers.iter().position(|l| l.id == *id)).unwrap_or(0);
|
||||
let id = layer.id;
|
||||
@@ -110,6 +110,21 @@ fn text_doc_from(p: &Value, base: TextDoc) -> TextDoc {
|
||||
if let Some(v) = b_p(p, "allCaps") {
|
||||
d.all_caps = v;
|
||||
}
|
||||
if let Some(v) = b_p(p, "smallCaps") {
|
||||
d.small_caps = v;
|
||||
}
|
||||
if let Some(v) = f_p(p, "hScale") {
|
||||
d.h_scale = v.clamp(1.0, 1000.0);
|
||||
}
|
||||
if let Some(v) = f_p(p, "vScale") {
|
||||
d.v_scale = v.clamp(1.0, 1000.0);
|
||||
}
|
||||
if let Some(v) = f_p(p, "baselineShift") {
|
||||
d.baseline_shift = v;
|
||||
}
|
||||
if let Some(v) = b_p(p, "strokeOverFill") {
|
||||
d.stroke_over_fill = v;
|
||||
}
|
||||
if let Some(v) = b_p(p, "fauxBold") {
|
||||
d.faux_bold = v;
|
||||
}
|
||||
@@ -222,13 +237,6 @@ fn new_simple(s: &mut Session, p: &Value, src: LayerSource, name: &str, label: &
|
||||
fn new_null(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
new_simple(s, p, LayerSource::Null, "Null 1", "New Null Object")
|
||||
}
|
||||
fn new_camera(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
new_simple(s, p, LayerSource::Camera, "Camera 1", "New Camera")
|
||||
}
|
||||
fn new_light(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = str_p(p, "kind").and_then(|k| LightKind::ALL.into_iter().find(|l| l.label().eq_ignore_ascii_case(k))).unwrap_or(LightKind::Point);
|
||||
new_simple(s, p, LayerSource::Light { kind }, "Light 1", "New Light")
|
||||
}
|
||||
|
||||
fn add_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
@@ -248,12 +256,13 @@ fn add_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ItemKind::Solid(so) => (LayerSource::Solid { item }, (so.width, so.height), None),
|
||||
ItemKind::Folder => return Err(bad("layer.addItem", "folders can't be layers")),
|
||||
};
|
||||
let start = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(Tick::ZERO);
|
||||
let fr = comp.frame_rate;
|
||||
let start = fr.snap_nearest(f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(Tick::ZERO));
|
||||
let id = s.edit("Add Footage to Comp", None, |proj, st| {
|
||||
let mut l = build::layer(proj, &comp, &it.name, src, size, dur);
|
||||
l.start_time = start;
|
||||
l.in_point = start;
|
||||
l.out_point = (start + dur.unwrap_or(comp.duration)).min(comp.duration);
|
||||
l.out_point = fr.snap_nearest((start + dur.unwrap_or(comp.duration)).min(comp.duration)).max(start + fr.frame_duration());
|
||||
insert_layer(proj, st, cid, l)
|
||||
})?;
|
||||
Ok(json!({"layer": id.0}))
|
||||
@@ -287,6 +296,8 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.state.selected_layers = ids;
|
||||
s.state.selected_props.clear();
|
||||
s.state.selected_keys.clear();
|
||||
let keep = s.state.selected_layers.clone();
|
||||
s.state.selected_vertices.retain(|v| keep.contains(&v.layer));
|
||||
}
|
||||
Ok(json!(s.state.selected_layers.iter().map(|l| l.0).collect::<Vec<_>>()))
|
||||
}
|
||||
@@ -383,13 +394,43 @@ fn set_switch_value(l: &mut Layer, name: &str, v: bool) {
|
||||
"frameBlend" => sw.frame_blend = if v { FrameBlend::FrameMix } else { FrameBlend::Off },
|
||||
"motionBlur" => sw.motion_blur = v,
|
||||
"adjustment" => sw.adjustment = v,
|
||||
"threeD" | "3d" | "3D" => sw.three_d = v,
|
||||
"threeD" | "3d" | "3D" => {
|
||||
if sw.three_d && !v {
|
||||
drop_3d_values(l);
|
||||
}
|
||||
l.switches.three_d = v;
|
||||
}
|
||||
"guide" => sw.guide = v,
|
||||
"preserveTransparency" => l.preserve_transparency = v,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Turning the 3D switch off discards Z values, Orientation and X/Y Rotation (as in AE).
|
||||
fn drop_3d_values(l: &mut Layer) {
|
||||
let Some(tr) = l.transform_mut() else { return };
|
||||
for (m, keep) in [("position", 0.0), ("anchor", 0.0), ("scale", 100.0)] {
|
||||
if let Some(pr) = tr.get_mut(m) {
|
||||
let flat = |v: &mut KV| {
|
||||
if let KV::Vec3(a) = v {
|
||||
a[2] = keep;
|
||||
}
|
||||
};
|
||||
flat(&mut pr.value);
|
||||
for k in &mut pr.keys {
|
||||
flat(&mut k.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (m, zero) in [("orientation", KV::Vec3([0.0; 3])), ("rotationX", KV::Scalar(0.0)), ("rotationY", KV::Scalar(0.0))] {
|
||||
if let Some(pr) = tr.get_mut(m) {
|
||||
pr.keys.clear();
|
||||
pr.expr = None;
|
||||
pr.value = zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "layer.rename")?;
|
||||
let name = str_p(p, "name").ok_or_else(|| bad("layer.rename", "missing `name`"))?.to_string();
|
||||
@@ -469,10 +510,62 @@ fn set_parent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cur = comp.layer(c).and_then(|l| l.parent);
|
||||
}
|
||||
}
|
||||
// Like AE's pick-whip, parenting keeps the layer where it is: its transform is re-expressed
|
||||
// in the new parent's space (Position, Rotation, Scale), unless `compensate: false`.
|
||||
let compensate = b_p(p, "compensate").unwrap_or(true);
|
||||
let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: s.time(), expr: s.expr.as_deref() };
|
||||
let space = |id: Option<LayerId>| -> effectcraft_geom::Mat3 {
|
||||
id.and_then(|i| comp.layer(i)).filter(|l| !l.is_3d()).map(|l| ectx.layer_to_comp(l).0).unwrap_or(effectcraft_geom::Mat3::IDENTITY)
|
||||
};
|
||||
let decompose = |m: &effectcraft_geom::Mat3| {
|
||||
let a = m.0;
|
||||
let sx = (a[0][0] * a[0][0] + a[1][0] * a[1][0]).sqrt();
|
||||
let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
|
||||
(a[1][0].atan2(a[0][0]).to_degrees(), sx, if sx > 1e-12 { det / sx } else { 0.0 })
|
||||
};
|
||||
// Per layer: (id, position transform, rotation delta, scale factors).
|
||||
let mut fixes: Vec<(LayerId, effectcraft_geom::Mat3, f64, [f64; 2])> = vec![];
|
||||
if compensate {
|
||||
let new_m = space(parent);
|
||||
for l in comp.layers.iter().filter(|l| ids.contains(&l.id) && !l.is_3d() && l.parent != parent) {
|
||||
let old_m = space(l.parent);
|
||||
let Some(inv) = new_m.inverse() else { continue };
|
||||
let (ro, sxo, syo) = decompose(&old_m);
|
||||
let (rn, sxn, syn) = decompose(&new_m);
|
||||
let k = [if sxn.abs() > 1e-12 { sxo / sxn } else { 1.0 }, if syn.abs() > 1e-12 { syo / syn } else { 1.0 }];
|
||||
fixes.push((l.id, inv * old_m, ro - rn, k));
|
||||
}
|
||||
}
|
||||
s.edit("Parent", None, |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
l.parent = parent;
|
||||
let Some((_, m, dr, k)) = fixes.iter().find(|f| f.0 == l.id) else { continue };
|
||||
let Some(tr) = l.props.sub_mut("transform") else { continue };
|
||||
let map = |pr: &mut effectcraft_project::Property, f: &dyn Fn(&KV) -> KV| {
|
||||
pr.value = f(&pr.value);
|
||||
for key in &mut pr.keys {
|
||||
key.value = f(&key.value);
|
||||
}
|
||||
};
|
||||
if tr.get("positionX").is_none()
|
||||
&& let Some(pr) = tr.get_mut("position")
|
||||
{
|
||||
map(pr, &|v| {
|
||||
let c = v.as_vec3();
|
||||
let q = m.apply(effectcraft_geom::vec2(c[0], c[1]));
|
||||
KV::Vec3([q.x, q.y, c[2]])
|
||||
});
|
||||
}
|
||||
if let Some(pr) = tr.get_mut("rotation") {
|
||||
map(pr, &|v| KV::Scalar(v.as_f64() + dr));
|
||||
}
|
||||
if let Some(pr) = tr.get_mut("scale") {
|
||||
map(pr, &|v| {
|
||||
let c = v.as_vec3();
|
||||
KV::Vec3([c[0] * k[0], c[1] * k[1], c[2]])
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -483,10 +576,10 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let t = s.time();
|
||||
let op = str_p(p, "op").unwrap_or("set").to_string();
|
||||
let delta = f_p(p, "delta").map(Tick::from_seconds_f64);
|
||||
let start = f_p(p, "start").map(Tick::from_seconds_f64);
|
||||
let inp = f_p(p, "in").map(Tick::from_seconds_f64);
|
||||
let outp = f_p(p, "out").map(Tick::from_seconds_f64);
|
||||
// Layer times stay on frame boundaries of the comp (as in AE).
|
||||
let fr = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_rate;
|
||||
let snap = |k: &str| f_p(p, k).map(|v| fr.snap_nearest(Tick::from_seconds_f64(v)));
|
||||
let (delta, start, inp, outp) = (snap("delta"), snap("start"), snap("in"), snap("out"));
|
||||
s.edit("Layer Timing", merge_p(p), |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let fd = comp.frame_duration();
|
||||
@@ -803,36 +896,14 @@ fn transform_op(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let reverse = str_p(p, "op") == Some("reverse");
|
||||
let pct = f_p(p, "percent");
|
||||
s.edit(if reverse { "Time-Reverse Layer" } else { "Time Stretch" }, None, |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
let old = l.stretch;
|
||||
let new = if reverse { -old } else { pct.unwrap_or(old) };
|
||||
if new.abs() < 1.0 {
|
||||
continue;
|
||||
}
|
||||
// Keep the in point fixed: the layer's source span scales around it.
|
||||
let lin = l.layer_time(l.in_point);
|
||||
let lout = l.layer_time(l.out_point);
|
||||
l.stretch = new;
|
||||
if reverse {
|
||||
l.start_time = l.in_point + Tick((lout.0 as f64 * new.abs() / 100.0) as i64);
|
||||
} else {
|
||||
l.start_time = l.in_point - Tick((lin.0 as f64 * new / 100.0) as i64);
|
||||
l.out_point = l.comp_time(lout);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn layer_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "layer.settings")?;
|
||||
// Cameras and lights open their own settings (Camera Settings / Light Settings).
|
||||
match s.project.comp(cid).and_then(|c| c.layer(lid)).map(|l| l.source.clone()) {
|
||||
Some(LayerSource::Camera) => return s.execute("layer.cameraSettings", with_layer(p, lid)),
|
||||
Some(LayerSource::Light { .. }) => return s.execute("layer.lightSettings", with_layer(p, lid)),
|
||||
_ => {}
|
||||
}
|
||||
let color = color_p(p, "color");
|
||||
let w = p.get("width").and_then(Value::as_u64).map(|v| v as u32);
|
||||
let h = p.get("height").and_then(Value::as_u64).map(|v| v as u32);
|
||||
@@ -862,12 +933,16 @@ fn layer_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn with_layer(p: &Value, lid: LayerId) -> Value {
|
||||
let mut p = if p.is_object() { p.clone() } else { json!({}) };
|
||||
p["layer"] = json!(lid.0);
|
||||
p
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("layer.newText", "Text", ["Layer", "New"], Some("Cmd+Alt+Shift+T"), "{text?, size?, font?, fill?, position? [x,y], justify?}", has_comp, new_text),
|
||||
cmd!("layer.newSolid", "Solid...", ["Layer", "New"], Some("Cmd+Y"), "{name?, color? #hex|[r,g,b], width?, height?}", has_comp, new_solid),
|
||||
cmd!("layer.newLight", "Light...", ["Layer", "New"], Some("Cmd+Alt+Shift+L"), "{kind?: Parallel|Spot|Point|Ambient}", has_comp, new_light),
|
||||
cmd!("layer.newCamera", "Camera...", ["Layer", "New"], Some("Cmd+Alt+Shift+C"), "{name?}", has_comp, new_camera),
|
||||
cmd!("layer.newNull", "Null Object", ["Layer", "New"], Some("Cmd+Alt+Shift+Y"), "{name?}", has_comp, new_null),
|
||||
cmd!(
|
||||
"layer.newShape",
|
||||
@@ -940,7 +1015,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Text",
|
||||
[],
|
||||
None,
|
||||
"{layer?, text?, size?, font?, style?, fill?, stroke?, applyFill?, applyStroke?, strokeWidth?, tracking?, leading?: px|\"auto\", justify?: left|center|right|justifyLeft|justifyCenter|justifyRight|justifyAll, allCaps?, fauxBold?, fauxItalic?}",
|
||||
"{layer?, text?, size?, font?, style?, fill?, stroke?, applyFill?, applyStroke?, strokeWidth?, tracking?, leading?: px|\"auto\", justify?: left|center|right|justifyLeft|justifyCenter|justifyRight|justifyAll, allCaps?, smallCaps?, fauxBold?, fauxItalic?, hScale? %, vScale? %, baselineShift? px, strokeOverFill?}",
|
||||
has_layers,
|
||||
set_text
|
||||
),
|
||||
@@ -962,7 +1037,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layers,
|
||||
transform_op
|
||||
),
|
||||
cmd!("layer.timeStretch", "Time Stretch...", ["Layer", "Time"], None, "{layers?, percent?, op?: reverse}", has_layers, time_stretch),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
//! layers, markers, track matte shortcuts, open/reveal, and Keyframe Assistant ▸ Sequence Layers.
|
||||
|
||||
use effectcraft_keyframe::{Keyframe, ShapePath, Value as KV};
|
||||
use effectcraft_project::{
|
||||
AutoOrient, FrameBlend, GroupKind, ItemId, LayerId, LayerSource, Marker, MaskMode, MatteKind, Node, Quality, Sampling, TrackMatte, Uid,
|
||||
};
|
||||
use effectcraft_project::{FrameBlend, GroupKind, ItemId, LayerId, LayerSource, Marker, MaskMode, MatteKind, Node, Quality, Sampling, TrackMatte, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -254,24 +252,6 @@ fn center_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"layers": centers.len()}))
|
||||
}
|
||||
|
||||
fn auto_orient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let mode = match str_p(p, "mode").ok_or_else(|| bad("layer.autoOrient", "missing `mode`"))? {
|
||||
"off" => AutoOrient::Off,
|
||||
"alongPath" => AutoOrient::AlongPath,
|
||||
"towardsCamera" => AutoOrient::TowardsCamera,
|
||||
"towardsPointOfInterest" => AutoOrient::TowardsPointOfInterest,
|
||||
m => return Err(bad("layer.autoOrient", format!("mode: off|alongPath|towardsCamera|towardsPointOfInterest, not `{m}`"))),
|
||||
};
|
||||
s.edit("Auto-Orient", None, |proj, _| {
|
||||
for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
l.auto_orient = mode;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- masks
|
||||
|
||||
/// Masks the command applies to: `mask` (index / uid / name) on `layer`, else selected masks,
|
||||
@@ -785,15 +765,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layers,
|
||||
center_anchor
|
||||
),
|
||||
cmd!(
|
||||
"layer.autoOrient",
|
||||
"Auto-Orient...",
|
||||
["Layer", "Transform"],
|
||||
Some("Cmd+Alt+O"),
|
||||
"{layers?, mode: off|alongPath|towardsCamera|towardsPointOfInterest}",
|
||||
has_layers,
|
||||
auto_orient
|
||||
),
|
||||
cmd!(
|
||||
"layer.mask.shape",
|
||||
"Mask Shape...",
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Layer ▸ Time: Time Stretch, Time-Reverse Layer, Enable Time Remapping, Freeze Frame and
|
||||
//! Freeze on Last Frame.
|
||||
//!
|
||||
//! Time Remap is a `timeRemap` property at the top of the layer's tree whose value is the
|
||||
//! source time (seconds) to show; its keys live in layer time like every other property.
|
||||
|
||||
use effectcraft_keyframe::{Keyframe, Value as KV};
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{Layer, LayerSource, Node, ParamUi, Property};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_layers, layers_p, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// Layers whose source has its own time (precomps and footage) can be remapped.
|
||||
fn remappable(l: &Layer) -> bool {
|
||||
matches!(l.source, LayerSource::Comp { .. } | LayerSource::Footage { .. })
|
||||
}
|
||||
|
||||
fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let reverse = str_p(p, "op") == Some("reverse");
|
||||
let pct = f_p(p, "percent");
|
||||
let dur = f_p(p, "duration");
|
||||
let hold = str_p(p, "hold").unwrap_or("in").to_string();
|
||||
let cti = s.time();
|
||||
let comp_rate = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_rate;
|
||||
let fd = comp_rate.frame_duration();
|
||||
s.edit(if reverse { "Time-Reverse Layer" } else { "Time Stretch" }, None, |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
let old = l.stretch;
|
||||
if reverse {
|
||||
// Keep the in/out points; play the visible span backwards.
|
||||
let last = l.layer_time(l.out_point - fd);
|
||||
l.stretch = -old;
|
||||
l.start_time = l.in_point - Tick((last.0 as f64 * l.stretch / 100.0).round() as i64);
|
||||
continue;
|
||||
}
|
||||
let span = (l.out_point - l.in_point).seconds();
|
||||
let new = match (pct, dur) {
|
||||
(Some(v), _) => v,
|
||||
(None, Some(d)) if span > 0.0 => old * d / span,
|
||||
_ => old,
|
||||
};
|
||||
if new.abs() < 1.0 {
|
||||
return Err(bad("layer.timeStretch", "the stretch factor must be at least 1 %"));
|
||||
}
|
||||
// The hold point keeps showing the same layer time.
|
||||
let h = match hold.as_str() {
|
||||
"current" => cti,
|
||||
"out" => l.out_point,
|
||||
_ => l.in_point,
|
||||
};
|
||||
let lt_h = l.layer_time(h);
|
||||
let (lin, lout) = (l.layer_time(l.in_point), l.layer_time(l.out_point));
|
||||
l.stretch = new;
|
||||
l.start_time = h - Tick((lt_h.0 as f64 * new / 100.0).round() as i64);
|
||||
let (a, b) = (l.comp_time(lin), l.comp_time(lout));
|
||||
let fr = comp_rate;
|
||||
l.in_point = fr.snap_nearest(a.min(b));
|
||||
l.out_point = fr.snap_nearest(a.max(b)).max(l.in_point + fr.frame_duration());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn remap_prop(ids: &mut Ids) -> Property {
|
||||
let mut p = ids.prop("timeRemap", "Time Remap", KV::Scalar(0.0)).with_ui(ParamUi::Number);
|
||||
p.ui = ParamUi::Number;
|
||||
p
|
||||
}
|
||||
|
||||
/// Source time (seconds) a layer shows at comp time `t` without remapping.
|
||||
fn source_secs(l: &Layer, t: Tick) -> f64 {
|
||||
l.layer_time(t).seconds()
|
||||
}
|
||||
|
||||
fn enable_time_remap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let want = b_p(p, "value");
|
||||
let fd = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_duration();
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
if !comp.layers.iter().filter(|l| ids.contains(&l.id)).any(remappable) {
|
||||
return Err(bad("layer.enableTimeRemap", "time remapping needs a footage or composition layer"));
|
||||
}
|
||||
let on = s.edit("Enable Time Remapping", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
let mut on = false;
|
||||
for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id) && remappable(l)) {
|
||||
let has = l.props.get("timeRemap").is_some();
|
||||
let target = want.unwrap_or(!has);
|
||||
on |= target;
|
||||
if target && !has {
|
||||
let mut pr = remap_prop(&mut Ids(&mut next));
|
||||
let (lin, lout) = (l.layer_time(l.in_point), l.layer_time(l.out_point));
|
||||
let (a, b) = (lin.min(lout), lin.max(lout));
|
||||
pr.value = KV::Scalar(source_secs(l, l.in_point));
|
||||
pr.keys = vec![Keyframe::new(a, KV::Scalar(a.seconds())), Keyframe::new(b, KV::Scalar(b.seconds()))];
|
||||
if lin > lout {
|
||||
// Reversed layers keep showing what they showed.
|
||||
pr.keys[0].value = KV::Scalar(source_secs(l, l.out_point - fd));
|
||||
pr.keys[1].value = KV::Scalar(source_secs(l, l.in_point));
|
||||
}
|
||||
l.props.children.insert(0, Node::Prop(pr));
|
||||
} else if !target && has {
|
||||
l.props.children.retain(|c| c.match_id() != "timeRemap");
|
||||
}
|
||||
}
|
||||
proj.next_id = next;
|
||||
Ok(on)
|
||||
})?;
|
||||
Ok(json!(on))
|
||||
}
|
||||
|
||||
/// Freeze Frame: time remapping holding the current source frame for the whole layer.
|
||||
fn freeze(s: &mut Session, p: &Value, last: bool) -> Result<Value> {
|
||||
let (cid, ids) = layers_p(s, p)?;
|
||||
let cti = s.time();
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let (fd, cdur) = (comp.frame_duration(), comp.duration);
|
||||
if !comp.layers.iter().filter(|l| ids.contains(&l.id)).any(remappable) {
|
||||
return Err(bad("layer.freezeFrame", "freezing needs a footage or composition layer"));
|
||||
}
|
||||
// What each layer shows now (honouring an existing remap) — evaluated before the edit.
|
||||
let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: cti, expr: s.expr.as_deref() };
|
||||
let now: Vec<(effectcraft_project::LayerId, f64)> = comp
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| ids.contains(&l.id) && remappable(l))
|
||||
.map(|l| {
|
||||
let at = if last { ectx.at(l.out_point - fd) } else { ectx };
|
||||
(l.id, at.source_time(l).seconds())
|
||||
})
|
||||
.collect();
|
||||
s.edit(if last { "Freeze On Last Frame" } else { "Freeze Frame" }, None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for (lid, src) in &now {
|
||||
let Some(l) = comp.layer_mut(*lid) else { continue };
|
||||
if l.props.get("timeRemap").is_none() {
|
||||
l.props.children.insert(0, Node::Prop(remap_prop(&mut Ids(&mut next))));
|
||||
}
|
||||
let lt = if last { l.layer_time(l.out_point - fd) } else { l.layer_time(cti) };
|
||||
let lin = l.layer_time(l.in_point);
|
||||
let pr = l.props.get_mut("timeRemap").ok_or(EngineError::NoComp)?;
|
||||
pr.value = KV::Scalar(*src);
|
||||
if last {
|
||||
// Play normally up to the last frame, then hold it to the end of the comp.
|
||||
let mut end = Keyframe::new(lt.max(lin), KV::Scalar(*src));
|
||||
end.out_interp = effectcraft_keyframe::Interp::Hold;
|
||||
pr.keys = vec![Keyframe::new(lin.min(lt), KV::Scalar(lin.min(lt).seconds())), end];
|
||||
pr.keys.dedup_by_key(|k| k.time);
|
||||
l.out_point = cdur;
|
||||
} else {
|
||||
pr.keys = vec![Keyframe::new(lt, KV::Scalar(*src)).hold()];
|
||||
}
|
||||
}
|
||||
proj.next_id = next;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"layer.timeStretch",
|
||||
"Time Stretch...",
|
||||
["Layer", "Time"],
|
||||
None,
|
||||
"{layers?, percent?|duration? (s), hold?: in|current|out, op?: reverse}",
|
||||
has_layers,
|
||||
time_stretch
|
||||
),
|
||||
cmd!("layer.timeReverse", "Time-Reverse Layer", ["Layer", "Time"], Some("Cmd+Alt+R"), "{layers?}", has_layers, |s, p| {
|
||||
let mut p = p.clone();
|
||||
p["op"] = json!("reverse");
|
||||
time_stretch(s, &p)
|
||||
}),
|
||||
cmd!("layer.enableTimeRemap", "Enable Time Remapping", ["Layer", "Time"], Some("Cmd+Alt+T"), "{layers?, value?}", has_layers, enable_time_remap),
|
||||
cmd!("layer.freezeFrame", "Freeze Frame", ["Layer", "Time"], None, "{layers?}", has_layers, |s, p| freeze(s, p, false)),
|
||||
cmd!("layer.freezeOnLastFrame", "Freeze On Last Frame", ["Layer", "Time"], None, "{layers?}", has_layers, |s, p| freeze(s, p, true)),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Separate Dimensions and the property pick-whip (AE-style reference expressions).
|
||||
|
||||
use effectcraft_keyframe::{Ease, Interp, Keyframe, Value as KV};
|
||||
use effectcraft_project::{Comp, Layer, Node, ParamUi, Property, Uid};
|
||||
use effectcraft_time::{TICKS_PER_SECOND, Tick};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::prop::prop_ref;
|
||||
use super::{CommandSpec, b_p, bad, has_layers, layer_mut, layer_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
const AXES: [(&str, &str); 3] = [("positionX", "X Position"), ("positionY", "Y Position"), ("positionZ", "Z Position")];
|
||||
|
||||
/// Per-dimension scalar keys from a (spatial) position key list: same times and interpolation;
|
||||
/// Bezier sides get the per-dimension velocity the combined property had at the key.
|
||||
fn split_keys(keys: &[Keyframe], spatial: bool, d: usize) -> Vec<Keyframe> {
|
||||
let h = Tick(TICKS_PER_SECOND / 2000);
|
||||
keys.iter()
|
||||
.map(|k| {
|
||||
let mut s = Keyframe::new(k.time, KV::Scalar(k.value.components().get(d).copied().unwrap_or(0.0)));
|
||||
s.in_interp = k.in_interp;
|
||||
s.out_interp = k.out_interp;
|
||||
s.auto_bezier = k.auto_bezier;
|
||||
s.continuous = k.continuous;
|
||||
s.roving = false;
|
||||
let vel = |t: Tick| effectcraft_keyframe::velocity(keys, t, spatial).get(d).copied().unwrap_or(0.0);
|
||||
if k.in_interp == Interp::Bezier {
|
||||
let inf = k.in_ease.first().map(|e| e.influence).unwrap_or(1.0 / 3.0);
|
||||
s.in_ease = vec![Ease { speed: vel(k.time - h), influence: inf }];
|
||||
}
|
||||
if k.out_interp == Interp::Bezier {
|
||||
let inf = k.out_ease.first().map(|e| e.influence).unwrap_or(1.0 / 3.0);
|
||||
s.out_ease = vec![Ease { speed: vel(k.time + h), influence: inf }];
|
||||
}
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn separate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "prop.separateDimensions")?;
|
||||
let want = b_p(p, "value");
|
||||
let on = s.edit("Separate Dimensions", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let tr = l.props.sub_mut("transform").ok_or_else(|| bad("prop.separateDimensions", "this layer has no Transform"))?;
|
||||
let has = tr.get("positionX").is_some();
|
||||
let target = want.unwrap_or(!has);
|
||||
if target && !has {
|
||||
let pos = tr.get("position").ok_or_else(|| bad("prop.separateDimensions", "no Position"))?.clone();
|
||||
let at = tr.children.iter().position(|c| c.uid() == pos.uid).map(|i| i + 1).unwrap_or(tr.children.len());
|
||||
let comps = pos.value.components();
|
||||
for (d, (m, name)) in AXES.iter().enumerate().rev() {
|
||||
let mut pr = Property::new(next, m, name, KV::Scalar(comps.get(d).copied().unwrap_or(0.0))).with_ui(ParamUi::Number);
|
||||
next += 1;
|
||||
pr.three_d_only = d == 2;
|
||||
pr.keys = split_keys(&pos.keys, pos.spatial, d);
|
||||
tr.children.insert(at, Node::Prop(pr));
|
||||
}
|
||||
} else if !target && has {
|
||||
let parts: Vec<Property> = AXES.iter().filter_map(|(m, _)| tr.get(m).cloned()).collect();
|
||||
let mut times: Vec<Tick> = parts.iter().flat_map(|p| p.keys.iter().map(|k| k.time)).collect();
|
||||
times.sort();
|
||||
times.dedup();
|
||||
let at = |t: Tick| KV::Vec3([0, 1, 2].map(|d| parts.get(d).map(|p| p.value_at(t).as_f64()).unwrap_or(0.0)));
|
||||
let pos = tr.get_mut("position").ok_or_else(|| bad("prop.separateDimensions", "no Position"))?;
|
||||
pos.value = at(Tick::ZERO);
|
||||
pos.keys = times.iter().map(|t| Keyframe::new(*t, at(*t))).collect();
|
||||
if pos.keys.is_empty() {
|
||||
pos.value = KV::Vec3([0, 1, 2].map(|d| parts.get(d).map(|p| p.value.as_f64()).unwrap_or(0.0)));
|
||||
}
|
||||
tr.children.retain(|c| !AXES.iter().any(|(m, _)| c.match_id() == *m));
|
||||
}
|
||||
proj.next_id = next;
|
||||
Ok(target)
|
||||
})?;
|
||||
Ok(json!(on))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pick-whip
|
||||
|
||||
/// `X Position` → `xPosition`, `Mask Path` → `maskPath`.
|
||||
fn camel(name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for (i, w) in name.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).enumerate() {
|
||||
let mut cs = w.chars();
|
||||
if let Some(f) = cs.next() {
|
||||
if i == 0 {
|
||||
out.extend(f.to_lowercase());
|
||||
} else {
|
||||
out.extend(f.to_uppercase());
|
||||
}
|
||||
out.push_str(cs.as_str());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn quote(s: &str) -> String {
|
||||
serde_json::to_string(s).unwrap_or_else(|_| format!("\"{s}\""))
|
||||
}
|
||||
|
||||
/// The AE expression reference to property `uid` of `target` as seen from a property of `from`.
|
||||
pub(crate) fn reference(comp: &Comp, from: &Layer, target: &Layer, uid: Uid) -> Option<String> {
|
||||
let chain = target.props.node_chain(uid)?;
|
||||
let mut parts: Vec<String> = vec![];
|
||||
let mut pending: Option<&str> = None;
|
||||
let mut in_effect = false;
|
||||
for n in chain {
|
||||
if let Some(f) = pending.take() {
|
||||
parts.push(format!("{f}({})", quote(n.name())));
|
||||
in_effect |= f == "effect";
|
||||
continue;
|
||||
}
|
||||
match (n, n.match_id()) {
|
||||
(Node::Group(_), "masks") => pending = Some("mask"),
|
||||
(Node::Group(_), "effects") => pending = Some("effect"),
|
||||
(Node::Group(_), "contents") => pending = Some("content"),
|
||||
(Node::Group(_), "transform") if !in_effect => parts.push("transform".into()),
|
||||
(Node::Group(_), "text") if !in_effect => parts.push("text".into()),
|
||||
(Node::Prop(_), "sourceText") => parts.push("sourceText".into()),
|
||||
_ if in_effect => parts.push(format!("({})", quote(n.name()))),
|
||||
_ => parts.push(camel(n.name())),
|
||||
}
|
||||
}
|
||||
let mut out = if from.id == target.id { String::new() } else { format!("thisComp.layer({}).", quote(&target.name)) };
|
||||
let _ = comp;
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
if i > 0 && !p.starts_with('(') {
|
||||
out.push('.');
|
||||
}
|
||||
out.push_str(p);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Dimensions an expression sees (2D layers see 2D Position/Scale/Anchor).
|
||||
fn dims(l: &Layer, p: &Property) -> usize {
|
||||
match &p.value {
|
||||
KV::Vec3(_) if p.shown_dims == 2 && !l.is_3d() => 2,
|
||||
v => v.components().len().max(1),
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_whip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.pickWhip")?;
|
||||
let t = p.get("target").ok_or_else(|| bad("prop.pickWhip", "missing `target` {layer, path|prop}"))?;
|
||||
let (_, tl, tu) = prop_ref(s, t, "prop.pickWhip")?;
|
||||
if (tl, tu) == (lid, uid) {
|
||||
return Err(bad("prop.pickWhip", "a property can't reference itself"));
|
||||
}
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let from = comp.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
let target = comp.layer(tl).ok_or(EngineError::NoComp)?;
|
||||
let r = reference(comp, from, target, tu).ok_or_else(|| bad("prop.pickWhip", "no such target property"))?;
|
||||
let (me, them) = (from.props.find(uid).ok_or(EngineError::NoComp)?, target.props.find(tu).ok_or(EngineError::NoComp)?);
|
||||
let (dm, dt) = (dims(from, me), dims(target, them));
|
||||
let text = if dt == 1 && dm > 1 {
|
||||
format!("temp = {r};\n[{}]", vec!["temp"; dm].join(", "))
|
||||
} else if dt > 1 && dm == 1 {
|
||||
format!("{r}[0]")
|
||||
} else {
|
||||
r
|
||||
};
|
||||
s.execute("prop.setExpression", json!({"layer": lid.0, "prop": uid, "expression": text}))?;
|
||||
Ok(json!(text))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("prop.separateDimensions", "Separate Dimensions", ["Animation"], None, "{layer?, value?}", has_layers, separate),
|
||||
cmd!(
|
||||
"prop.pickWhip",
|
||||
"Pick Whip (Link Property)",
|
||||
[],
|
||||
None,
|
||||
"{layer?, path|prop, target: {layer, path|prop}} → sets an AE reference expression",
|
||||
has_layers,
|
||||
pick_whip
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Masks drawn and edited in the viewer: Pen tool (new mask, add vertex, Bezier tangents, close
|
||||
//! path), vertex selection, moving and deleting vertices, and Layer ▸ Mask ▸ Remove (All).
|
||||
//!
|
||||
//! Coordinates are in layer space. Edits of an animated Mask Path set a key at the current time.
|
||||
|
||||
use effectcraft_keyframe::{ShapePath, Value as KV};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{Layer, MaskMode, PropGroup, Uid};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, has_comp, has_layers, layer_mut, layer_p, merge_p, resolve_layer, str_p};
|
||||
use crate::{EngineError, Result, Session, VertexRef, cmd};
|
||||
|
||||
fn pt(v: Option<&Value>) -> Option<[f64; 2]> {
|
||||
let a = v?.as_array()?;
|
||||
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])
|
||||
}
|
||||
|
||||
fn pts(v: Option<&Value>) -> Vec<[f64; 2]> {
|
||||
v.and_then(Value::as_array).map(|a| a.iter().filter_map(|p| pt(Some(p))).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Find a mask group by uid, 1-based index or name.
|
||||
fn find_mask<'a>(masks: &'a mut PropGroup, key: &Value) -> Option<&'a mut PropGroup> {
|
||||
let i = match key {
|
||||
Value::Number(n) => {
|
||||
let n = n.as_u64()?;
|
||||
masks.children.iter().position(|c| c.uid() == n).or_else(|| (n as usize).checked_sub(1).filter(|i| *i < masks.children.len()))?
|
||||
}
|
||||
Value::String(s) => masks.children.iter().position(|c| c.name() == s)?,
|
||||
_ => return None,
|
||||
};
|
||||
masks.children.get_mut(i)?.as_group_mut()
|
||||
}
|
||||
|
||||
/// Edit the mask path of (layer, mask) at the current time.
|
||||
fn edit_path<T>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut ShapePath) -> Result<T>) -> Result<(Uid, T)> {
|
||||
let (cid, lid) = layer_p(s, p, label)?;
|
||||
let key = p.get("mask").cloned().ok_or_else(|| bad(label, "missing `mask` (uid, index or name)"))?;
|
||||
let t = s.time();
|
||||
s.edit(label, merge_p(p), |proj, _| {
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
let masks = l.props.sub_mut("masks").ok_or_else(|| bad(label, "this layer has no masks"))?;
|
||||
let g = find_mask(masks, &key).ok_or_else(|| bad(label, "no such mask"))?;
|
||||
let uid = g.uid;
|
||||
let pr = g.get_mut("path").ok_or_else(|| bad(label, "mask has no path"))?;
|
||||
let KV::Path(mut sp) = pr.value_at(lt) else { return Err(bad(label, "not a path")) };
|
||||
let r = f(&mut sp)?;
|
||||
pr.set_value_at(lt, KV::Path(sp));
|
||||
Ok((uid, r))
|
||||
})
|
||||
}
|
||||
|
||||
/// Pen tool: a new (open by default) mask from points.
|
||||
fn new_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "mask.new")?;
|
||||
let v = pts(p.get("vertices"));
|
||||
if v.is_empty() {
|
||||
return Err(bad("mask.new", "need `vertices` [[x,y], …] in layer space"));
|
||||
}
|
||||
let n = v.len();
|
||||
let mut ins = pts(p.get("inTangents"));
|
||||
let mut outs = pts(p.get("outTangents"));
|
||||
ins.resize(n, [0.0; 2]);
|
||||
outs.resize(n, [0.0; 2]);
|
||||
let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false) };
|
||||
let mode = str_p(p, "mode").and_then(MaskMode::from_name).unwrap_or(MaskMode::Add);
|
||||
let uid = s.edit("New Mask", None, |proj, st| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let masks = l.props.sub_mut("masks").ok_or_else(|| bad("mask.new", "this layer can't have masks"))?;
|
||||
let k = masks.children.len();
|
||||
let g = build::mask(&mut Ids(&mut next), &format!("Mask {}", k + 1), path, mode, build::MASK_COLORS[k % build::MASK_COLORS.len()]);
|
||||
let uid = g.uid;
|
||||
masks.children.push(g.into());
|
||||
proj.next_id = next;
|
||||
st.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: n - 1 }];
|
||||
Ok(uid)
|
||||
})?;
|
||||
Ok(json!({"mask": uid}))
|
||||
}
|
||||
|
||||
fn add_vertex(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let point = pt(p.get("point")).ok_or_else(|| bad("mask.addVertex", "missing `point` [x,y]"))?;
|
||||
let tin = pt(p.get("in")).unwrap_or([0.0; 2]);
|
||||
let tout = pt(p.get("out")).unwrap_or([0.0; 2]);
|
||||
let at = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
|
||||
let (_, lid) = layer_p(s, p, "mask.addVertex")?;
|
||||
let (uid, i) = edit_path(s, p, "mask.addVertex", |sp| {
|
||||
let i = at.unwrap_or(sp.vertices.len()).min(sp.vertices.len());
|
||||
sp.vertices.insert(i, point);
|
||||
sp.in_tangents.insert(i, tin);
|
||||
sp.out_tangents.insert(i, tout);
|
||||
Ok(i)
|
||||
})?;
|
||||
s.state.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: i }];
|
||||
Ok(json!(i))
|
||||
}
|
||||
|
||||
fn set_vertex(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("mask.setVertex", "missing `index`"))? as usize;
|
||||
let (point, tin, tout) = (pt(p.get("point")), pt(p.get("in")), pt(p.get("out")));
|
||||
edit_path(s, p, "mask.setVertex", |sp| {
|
||||
if i >= sp.vertices.len() {
|
||||
return Err(bad("mask.setVertex", "no such vertex"));
|
||||
}
|
||||
if let Some(v) = point {
|
||||
sp.vertices[i] = v;
|
||||
}
|
||||
if let Some(v) = tin {
|
||||
sp.in_tangents[i] = v;
|
||||
}
|
||||
if let Some(v) = tout {
|
||||
sp.out_tangents[i] = v;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn set_closed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = b_p(p, "closed").unwrap_or(true);
|
||||
edit_path(s, p, "mask.setClosed", |sp| {
|
||||
sp.closed = c;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!(c))
|
||||
}
|
||||
|
||||
/// Selected (or given) vertices grouped per (layer, mask).
|
||||
fn vertex_groups(s: &Session, p: &Value) -> Result<std::collections::BTreeMap<(u64, Uid), Vec<usize>>> {
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let mut g: std::collections::BTreeMap<(u64, Uid), Vec<usize>> = Default::default();
|
||||
if let Some(Value::Array(a)) = p.get("vertices") {
|
||||
for v in a {
|
||||
let l = v.get("layer").and_then(|x| resolve_layer(comp, x)).ok_or_else(|| bad("mask", "vertex needs `layer`"))?;
|
||||
let m = v.get("mask").and_then(Value::as_u64).ok_or_else(|| bad("mask", "vertex needs `mask` uid"))?;
|
||||
let i = v.get("index").and_then(Value::as_u64).ok_or_else(|| bad("mask", "vertex needs `index`"))?;
|
||||
g.entry((l.0, m)).or_default().push(i as usize);
|
||||
}
|
||||
} else {
|
||||
for v in &s.state.selected_vertices {
|
||||
g.entry((v.layer.0, v.mask)).or_default().push(v.index);
|
||||
}
|
||||
}
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
fn select_vertices(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = vertex_groups(s, &json!({"vertices": p.get("vertices").cloned().unwrap_or(json!([]))}))?;
|
||||
let sel: Vec<VertexRef> =
|
||||
g.into_iter().flat_map(|((l, m), is)| is.into_iter().map(move |i| VertexRef { layer: effectcraft_project::LayerId(l), mask: m, index: i })).collect();
|
||||
if b_p(p, "add").unwrap_or(false) {
|
||||
for v in sel {
|
||||
if let Some(i) = s.state.selected_vertices.iter().position(|x| *x == v) {
|
||||
if b_p(p, "toggle").unwrap_or(false) {
|
||||
s.state.selected_vertices.remove(i);
|
||||
}
|
||||
} else {
|
||||
s.state.selected_vertices.push(v);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
s.state.selected_vertices = sel;
|
||||
}
|
||||
Ok(json!(s.state.selected_vertices.len()))
|
||||
}
|
||||
|
||||
fn has_vertices(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)?;
|
||||
if s.state.selected_vertices.is_empty() { Err("select mask vertices first".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Apply `f` to the selected vertices' paths (each mask once).
|
||||
fn edit_vertices(s: &mut Session, p: &Value, label: &str, f: impl Fn(&mut ShapePath, &[usize])) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let groups = vertex_groups(s, p)?;
|
||||
let t = s.time();
|
||||
s.edit(label, merge_p(p), |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for ((l, m), idx) in &groups {
|
||||
let Some(layer) = comp.layer_mut(effectcraft_project::LayerId(*l)) else { continue };
|
||||
let lt = layer.layer_time(t);
|
||||
let Some(pr) = layer.props.sub_mut("masks").and_then(|ms| ms.find_group_mut(*m)).and_then(|g| g.get_mut("path")) else { continue };
|
||||
let KV::Path(mut sp) = pr.value_at(lt) else { continue };
|
||||
f(&mut sp, idx);
|
||||
pr.set_value_at(lt, KV::Path(sp));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!(groups.values().map(Vec::len).sum::<usize>()))
|
||||
}
|
||||
|
||||
fn move_vertices(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = pt(p.get("delta")).ok_or_else(|| bad("mask.moveVertices", "missing `delta` [dx,dy] (layer space)"))?;
|
||||
edit_vertices(s, p, "Move Mask Vertices", |sp, idx| {
|
||||
for &i in idx {
|
||||
if let Some(v) = sp.vertices.get_mut(i) {
|
||||
v[0] += d[0];
|
||||
v[1] += d[1];
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_vertices(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = edit_vertices(s, p, "Delete Mask Vertices", |sp, idx| {
|
||||
let mut idx = idx.to_vec();
|
||||
idx.sort_unstable();
|
||||
idx.dedup();
|
||||
for &i in idx.iter().rev() {
|
||||
if i < sp.vertices.len() {
|
||||
sp.vertices.remove(i);
|
||||
sp.in_tangents.remove(i);
|
||||
sp.out_tangents.remove(i);
|
||||
}
|
||||
}
|
||||
if sp.vertices.len() < 3 {
|
||||
sp.closed = false;
|
||||
}
|
||||
})?;
|
||||
s.state.selected_vertices.clear();
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn remove_masks(s: &mut Session, p: &Value, all: bool) -> Result<Value> {
|
||||
let (cid, lid) = layer_p(s, p, "mask.remove")?;
|
||||
let key = p.get("mask").cloned();
|
||||
if !all && key.is_none() {
|
||||
return Err(bad("mask.remove", "missing `mask`"));
|
||||
}
|
||||
s.edit(if all { "Remove All Masks" } else { "Remove Mask" }, None, |proj, st| {
|
||||
let l: &mut Layer = layer_mut(proj, cid, lid)?;
|
||||
let masks = l.props.sub_mut("masks").ok_or_else(|| bad("mask.remove", "this layer has no masks"))?;
|
||||
if all {
|
||||
masks.children.clear();
|
||||
} else if let Some(k) = &key {
|
||||
let uid = find_mask(masks, k).map(|g| g.uid).ok_or_else(|| bad("mask.remove", "no such mask"))?;
|
||||
masks.children.retain(|c| c.uid() != uid);
|
||||
}
|
||||
st.selected_vertices.retain(|v| v.layer != lid);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("mask.new", "New Mask from Points", [], None, "{layer?, vertices: [[x,y]…], inTangents?, outTangents?, closed?, mode?}", has_layers, new_mask),
|
||||
cmd!("mask.addVertex", "Add Mask Vertex", [], None, "{layer?, mask, point: [x,y], in?, out?, index?}", has_layers, add_vertex),
|
||||
cmd!("mask.setVertex", "Set Mask Vertex", [], None, "{layer?, mask, index, point?, in?, out?, merge?}", has_layers, set_vertex),
|
||||
cmd!("mask.setClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{layer?, mask, closed?}", has_layers, set_closed),
|
||||
cmd!("mask.selectVertices", "Select Mask Vertices", [], None, "{vertices: [{layer, mask, index}], add?, toggle?}", has_comp, select_vertices),
|
||||
cmd!("mask.moveVertices", "Move Mask Vertices", [], None, "{vertices?: [{layer, mask, index}], delta: [dx,dy], merge?}", has_vertices, move_vertices),
|
||||
cmd!("mask.deleteVertices", "Delete Mask Vertices", [], None, "{vertices?}", has_vertices, delete_vertices),
|
||||
cmd!("mask.remove", "Remove Mask", [], None, "{layer?, mask}", has_layers, |s, p| remove_masks(s, p, false)),
|
||||
cmd!("mask.removeAll", "Remove All Masks", [], None, "{layer?}", has_layers, |s, p| remove_masks(s, p, true)),
|
||||
]
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! shortcut and viewer/timeline gesture maps to one of these.
|
||||
|
||||
mod anim;
|
||||
mod animation;
|
||||
mod comp;
|
||||
mod comp_more;
|
||||
mod edit;
|
||||
@@ -12,9 +13,14 @@ mod frontend;
|
||||
mod help;
|
||||
mod layer;
|
||||
mod layer_menu;
|
||||
mod layer_time;
|
||||
mod link;
|
||||
mod mask;
|
||||
mod prop;
|
||||
mod query;
|
||||
mod render_queue;
|
||||
mod stubs;
|
||||
mod three_d;
|
||||
mod time;
|
||||
mod view;
|
||||
|
||||
@@ -75,13 +81,19 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(edit::specs());
|
||||
v.extend(comp::specs());
|
||||
v.extend(layer::specs());
|
||||
v.extend(three_d::specs());
|
||||
v.extend(layer_time::specs());
|
||||
v.extend(prop::specs());
|
||||
v.extend(anim::specs());
|
||||
v.extend(link::specs());
|
||||
v.extend(mask::specs());
|
||||
v.extend(effect::specs());
|
||||
v.extend(time::specs());
|
||||
v.extend(render_queue::specs());
|
||||
v.extend(help::specs());
|
||||
v.extend(query::specs());
|
||||
v.extend(layer_menu::specs());
|
||||
v.extend(anim::specs());
|
||||
v.extend(animation::specs());
|
||||
v.extend(view::specs());
|
||||
v.extend(file_more::specs());
|
||||
v.extend(comp_more::specs());
|
||||
@@ -95,6 +107,65 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
// ---------- parameter validation (agents) ----------
|
||||
|
||||
/// Top-level keys accepted by a params doc such as `{layers: [id|name|#n], add?, toggle?}` or
|
||||
/// `{time? (s) | frame? | timecode?}`; `None` when the doc isn't a `{…}` key list.
|
||||
pub fn accepted_params(doc: &str) -> Option<Vec<String>> {
|
||||
let body = doc.trim().strip_prefix('{')?;
|
||||
// Top-level pieces up to the matching close brace, split at `,` and `|`; `:` starts a value.
|
||||
let (mut keys, mut cur, mut depth, mut in_value) = (Vec::new(), String::new(), 0i32, false);
|
||||
let push = |cur: &mut String, keys: &mut Vec<String>| {
|
||||
let k: String = cur.trim().chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
|
||||
if !k.is_empty() && !keys.contains(&k) {
|
||||
keys.push(k);
|
||||
}
|
||||
cur.clear();
|
||||
};
|
||||
for c in body.chars() {
|
||||
match c {
|
||||
'{' | '[' | '(' => depth += 1,
|
||||
']' | ')' => depth -= 1,
|
||||
'}' if depth == 0 => {
|
||||
push(&mut cur, &mut keys);
|
||||
return Some(keys);
|
||||
}
|
||||
'}' => depth -= 1,
|
||||
',' if depth == 0 => {
|
||||
push(&mut cur, &mut keys);
|
||||
in_value = false;
|
||||
}
|
||||
'|' if depth == 0 && !in_value => push(&mut cur, &mut keys),
|
||||
':' if depth == 0 => {
|
||||
push(&mut cur, &mut keys);
|
||||
in_value = true;
|
||||
}
|
||||
_ if depth == 0 && !in_value => cur.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Keys every command understands (comp targeting, gesture merging) and accepted aliases.
|
||||
const ALWAYS_OK: &[&str] = &["comp", "merge"];
|
||||
const ALIASES: &[(&str, &str)] = &[("layers", "layer"), ("layer", "layers"), ("time", "frame"), ("frameRate", "fps"), ("properties", "property")];
|
||||
|
||||
/// Reject unknown top-level parameters (typos, guessed names) with the list of accepted keys.
|
||||
pub fn check_params(spec: &CommandSpec, params: &Value) -> Result<()> {
|
||||
let (Some(obj), Some(accepted)) = (params.as_object(), accepted_params(spec.params)) else { return Ok(()) };
|
||||
let ok = |k: &str| ALWAYS_OK.contains(&k) || accepted.iter().any(|a| a == k || ALIASES.iter().any(|(doc, alias)| doc == a && *alias == k));
|
||||
let unknown: Vec<&str> = obj.keys().map(String::as_str).filter(|k| !ok(k)).collect();
|
||||
if unknown.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let list = if accepted.is_empty() { "none".to_string() } else { accepted.join(", ") };
|
||||
Err(bad(
|
||||
spec.id,
|
||||
format!("unknown parameter(s) {}; accepted: {list} (doc: {})", unknown.iter().map(|k| format!("`{k}`")).collect::<Vec<_>>().join(", "), spec.params),
|
||||
))
|
||||
}
|
||||
|
||||
// ---------- enablement ----------
|
||||
|
||||
pub fn always(_: &Session) -> std::result::Result<(), String> {
|
||||
|
||||
@@ -6,10 +6,10 @@ use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_comp, has_keys, has_layers, layer_mut, layer_p, merge_p, str_p};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd, query};
|
||||
|
||||
/// Resolve `{layer, path}` (or `{layer, prop: uid}`) to (comp, layer, prop uid).
|
||||
fn prop_ref(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
|
||||
pub(crate) fn prop_ref(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let layer = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
if let Some(u) = p.get("prop").and_then(Value::as_u64) {
|
||||
@@ -38,10 +38,44 @@ fn with_prop<T>(
|
||||
})
|
||||
}
|
||||
|
||||
/// An explicit key time (layer seconds) moved onto the nearest comp frame.
|
||||
fn snapped_key_time(s: &Session, cid: ItemId, lid: LayerId, p: &Value) -> Option<Tick> {
|
||||
let t = Tick::from_seconds_f64(f_p(p, "time")?);
|
||||
let comp = s.project.comp(cid)?;
|
||||
let l = comp.layer(lid)?;
|
||||
Some(l.layer_time(comp.frame_rate.snap_nearest(l.comp_time(t))))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.set")?;
|
||||
// Position with Separate Dimensions: write the X/Y/Z Position properties instead.
|
||||
if let Some(l) = s.project.comp(cid).and_then(|c| c.layer(lid))
|
||||
&& let Some(tr) = l.transform()
|
||||
&& tr.get("position").is_some_and(|pr| pr.uid == uid)
|
||||
&& tr.get("positionX").is_some()
|
||||
&& let Some(Value::Array(a)) = p.get("value")
|
||||
{
|
||||
let mut out = vec![];
|
||||
let three = l.is_3d();
|
||||
for (d, m) in ["positionX", "positionY", "positionZ"].iter().enumerate() {
|
||||
if d == 2 && (!three || a.len() < 3) {
|
||||
continue;
|
||||
}
|
||||
if let Some(v) = a.get(d) {
|
||||
let mut q = p.clone();
|
||||
q["path"] = json!(format!("transform/{m}"));
|
||||
q["layer"] = json!(lid.0);
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("prop");
|
||||
}
|
||||
q["value"] = v.clone();
|
||||
out.push(set(s, &q)?);
|
||||
}
|
||||
}
|
||||
return Ok(json!(out));
|
||||
}
|
||||
let v = p.get("value").ok_or_else(|| bad("prop.set", "missing `value`"))?.clone();
|
||||
let at = f_p(p, "time").map(Tick::from_seconds_f64);
|
||||
let at = snapped_key_time(s, cid, lid, p);
|
||||
let out = with_prop(s, "Change Property", merge_p(p), cid, lid, uid, |pr, lt| {
|
||||
let cur = pr.value_at(lt);
|
||||
let mut nv = cur.coerce_json(&v).ok_or_else(|| bad("prop.set", format!("can't use {v} for a {} property", cur.kind_name())))?;
|
||||
@@ -57,6 +91,21 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read one property: value at `time` (comp seconds, default the CTI), keyframes and expression.
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.get")?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let pr = l.props.find(uid).ok_or_else(|| bad("prop.get", "property vanished"))?;
|
||||
let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let keys: Vec<Value> =
|
||||
pr.keys.iter().map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()})).collect();
|
||||
Ok(json!({
|
||||
"layer": lid.0, "uid": pr.uid, "match": pr.match_id, "name": pr.name, "type": pr.value.kind_name(),
|
||||
"time": t.seconds(), "value": pr.value_at(l.layer_time(t)).to_json(), "animated": !pr.keys.is_empty(),
|
||||
"keys": keys, "expression": pr.expr.as_ref().map(|e| e.text.clone()),
|
||||
}))
|
||||
}
|
||||
|
||||
fn toggle_anim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.toggleAnimation")?;
|
||||
let on = b_p(p, "value");
|
||||
@@ -72,7 +121,7 @@ fn toggle_anim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn add_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.addKey")?;
|
||||
let at = f_p(p, "time").map(Tick::from_seconds_f64);
|
||||
let at = snapped_key_time(s, cid, lid, p);
|
||||
let value = p.get("value").cloned();
|
||||
with_prop(s, "Add Keyframe", None, cid, lid, uid, |pr, lt| {
|
||||
let t = at.unwrap_or(lt);
|
||||
@@ -113,8 +162,18 @@ fn toggle_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn set_expr(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, uid) = prop_ref(s, p, "prop.setExpression")?;
|
||||
let text = p.get("expression").and_then(Value::as_str).map(str::to_string);
|
||||
let enabled = b_p(p, "enabled");
|
||||
with_prop(s, "Expression", merge_p(p), cid, lid, uid, |pr, _| {
|
||||
let mut enabled = b_p(p, "enabled");
|
||||
// A syntax error keeps the text but disables the expression (AE shows the warning bar).
|
||||
let error = match (&text, s.expr_check) {
|
||||
(Some(t), Some(check)) if !t.trim().is_empty() => check(t).err(),
|
||||
_ => None,
|
||||
};
|
||||
if error.is_some() {
|
||||
enabled = Some(false);
|
||||
}
|
||||
// Alt-click on a stopwatch starts with the property's own reference (`transform.opacity`).
|
||||
let def = s.project.comp(cid).and_then(|c| c.layer(lid).and_then(|l| super::link::reference(c, l, l, uid))).unwrap_or_else(|| "value".into());
|
||||
let r = with_prop(s, "Expression", merge_p(p), cid, lid, uid, |pr, _| {
|
||||
match (&text, enabled) {
|
||||
(Some(t), _) if t.trim().is_empty() => pr.expr = None,
|
||||
(Some(t), e) => pr.expr = Some(effectcraft_project::Expression { text: t.clone(), enabled: e.unwrap_or(true) }),
|
||||
@@ -122,20 +181,20 @@ fn set_expr(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(x) = &mut pr.expr {
|
||||
x.enabled = e;
|
||||
} else if e {
|
||||
pr.expr = Some(effectcraft_project::Expression { text: default_expr(pr), enabled: true });
|
||||
pr.expr = Some(effectcraft_project::Expression { text: def.clone(), enabled: true });
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
pr.expr = if pr.expr.is_some() { None } else { Some(effectcraft_project::Expression { text: default_expr(pr), enabled: true }) };
|
||||
pr.expr = if pr.expr.is_some() { None } else { Some(effectcraft_project::Expression { text: def.clone(), enabled: true }) };
|
||||
}
|
||||
}
|
||||
Ok(json!(pr.expr.as_ref().map(|e| e.text.clone())))
|
||||
})
|
||||
}
|
||||
|
||||
fn default_expr(pr: &Property) -> String {
|
||||
let _ = pr;
|
||||
"value".to_string()
|
||||
})?;
|
||||
if let Some(e) = error {
|
||||
s.toast(format!("Expression disabled: {e}"));
|
||||
return Ok(json!({"expression": r, "error": e}));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -210,7 +269,7 @@ fn select_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Apply `f` to every selected key; keeps the selection pointing at moved keys.
|
||||
fn edit_keys(s: &mut Session, label: &str, merge: Option<&str>, f: impl Fn(&mut Vec<Keyframe>, usize, &mut Tick) -> bool) -> Result<Value> {
|
||||
pub(crate) fn edit_keys(s: &mut Session, label: &str, merge: Option<&str>, f: impl Fn(&mut Vec<Keyframe>, usize, &mut Tick) -> bool) -> Result<Value> {
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let sel = s.state.selected_keys.clone();
|
||||
s.edit(label, merge, |proj, st| {
|
||||
@@ -247,8 +306,14 @@ fn edit_keys(s: &mut Session, label: &str, merge: Option<&str>, f: impl Fn(&mut
|
||||
for t in keep_times {
|
||||
new_sel.push(KeyRef { layer: lid, prop: uid, time: t });
|
||||
}
|
||||
if pr.keys.is_empty() {
|
||||
// Deleting every key leaves the value at the last key.
|
||||
// Roving keys follow their neighbours: re-time and keep the selection on them.
|
||||
let before: Vec<Tick> = pr.keys.iter().map(|k| k.time).collect();
|
||||
if effectcraft_keyframe::retime_roving(&mut pr.keys, pr.spatial) {
|
||||
for r in new_sel.iter_mut().filter(|r| r.layer == lid && r.prop == uid) {
|
||||
if let Some(i) = before.iter().position(|t| *t == r.time) {
|
||||
r.time = pr.keys[i].time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
st.selected_keys = new_sel;
|
||||
@@ -304,8 +369,56 @@ fn interpolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let both = parse("interpolation");
|
||||
let inn = parse("in").or(both);
|
||||
let out = parse("out").or(both);
|
||||
let auto = b_p(p, "autoBezier");
|
||||
// Temporal interpolation by dialog name: linear|bezier|continuousBezier|autoBezier|hold.
|
||||
let temporal = str_p(p, "interpolation").map(|v| v.to_ascii_lowercase());
|
||||
let mut auto = b_p(p, "autoBezier");
|
||||
let mut continuous = b_p(p, "continuous");
|
||||
match temporal.as_deref() {
|
||||
Some("autobezier" | "auto") => auto = Some(true),
|
||||
Some("continuousbezier" | "continuous") => {
|
||||
continuous = Some(true);
|
||||
auto = Some(false);
|
||||
}
|
||||
Some("linear" | "bezier" | "hold") => {
|
||||
auto = auto.or(Some(false));
|
||||
continuous = continuous.or(Some(false));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let inn = if matches!(temporal.as_deref(), Some("autobezier" | "auto" | "continuousbezier" | "continuous")) { inn.or(Some(Interp::Bezier)) } else { inn };
|
||||
let out = if matches!(temporal.as_deref(), Some("autobezier" | "auto" | "continuousbezier" | "continuous")) { out.or(Some(Interp::Bezier)) } else { out };
|
||||
let spatial = str_p(p, "spatial").map(|v| v.to_ascii_lowercase());
|
||||
let roving = b_p(p, "roving");
|
||||
edit_keys(s, "Keyframe Interpolation", None, move |keys, i, _| {
|
||||
if let Some(sp) = spatial.as_deref() {
|
||||
let (tin, tout) = effectcraft_keyframe::spatial_tangents(keys, i);
|
||||
let k = &mut keys[i];
|
||||
match sp {
|
||||
"linear" => {
|
||||
k.spatial_auto = false;
|
||||
k.spatial_continuous = false;
|
||||
k.spatial_in = [0.0; 3];
|
||||
k.spatial_out = [0.0; 3];
|
||||
}
|
||||
"bezier" | "continuous" | "continuousbezier" => {
|
||||
k.spatial_auto = false;
|
||||
k.spatial_in = tin;
|
||||
k.spatial_out = tout;
|
||||
k.spatial_continuous = sp != "bezier";
|
||||
}
|
||||
"auto" | "autobezier" => {
|
||||
k.spatial_auto = true;
|
||||
k.spatial_continuous = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(r) = roving {
|
||||
keys[i].roving = r;
|
||||
}
|
||||
if let Some(c) = continuous {
|
||||
keys[i].continuous = c;
|
||||
}
|
||||
let n = keys[i].value.dims().max(1);
|
||||
if let Some(x) = inn {
|
||||
keys[i].in_interp = x;
|
||||
@@ -324,6 +437,24 @@ fn interpolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if a {
|
||||
keys[i].in_interp = Interp::Bezier;
|
||||
keys[i].out_interp = Interp::Bezier;
|
||||
keys[i].continuous = false;
|
||||
}
|
||||
}
|
||||
if keys[i].continuous && !keys[i].auto_bezier {
|
||||
// Continuous Bezier: one speed through the key (average of both sides).
|
||||
let k = &mut keys[i];
|
||||
k.in_interp = Interp::Bezier;
|
||||
k.out_interp = Interp::Bezier;
|
||||
if k.in_ease.len() != n {
|
||||
k.in_ease = vec![Ease::default(); n];
|
||||
}
|
||||
if k.out_ease.len() != n {
|
||||
k.out_ease = vec![Ease::default(); n];
|
||||
}
|
||||
for d in 0..n {
|
||||
let sp = (k.in_ease[d].speed + k.out_ease[d].speed) / 2.0;
|
||||
k.in_ease[d].speed = sp;
|
||||
k.out_ease[d].speed = sp;
|
||||
}
|
||||
}
|
||||
false
|
||||
@@ -338,41 +469,67 @@ fn toggle_hold(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A number or a per-dimension array of numbers.
|
||||
fn nums_p(p: &Value, k: &str, scale: f64) -> Option<Vec<f64>> {
|
||||
match p.get(k)? {
|
||||
Value::Array(a) => Some(a.iter().filter_map(Value::as_f64).map(|v| v * scale).collect()),
|
||||
v => v.as_f64().map(|v| vec![v * scale]),
|
||||
}
|
||||
}
|
||||
|
||||
fn velocity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let in_speed = f_p(p, "inSpeed");
|
||||
let in_inf = f_p(p, "inInfluence").map(|v| v / 100.0);
|
||||
let out_speed = f_p(p, "outSpeed");
|
||||
let out_inf = f_p(p, "outInfluence").map(|v| v / 100.0);
|
||||
let mut in_speed = nums_p(p, "inSpeed", 1.0);
|
||||
let mut in_inf = nums_p(p, "inInfluence", 0.01);
|
||||
let mut out_speed = nums_p(p, "outSpeed", 1.0);
|
||||
let mut out_inf = nums_p(p, "outInfluence", 0.01);
|
||||
// "Continuous" in the dialog: outgoing velocity follows incoming.
|
||||
let continuous = b_p(p, "continuous");
|
||||
if continuous == Some(true) {
|
||||
if out_speed.is_none() {
|
||||
out_speed = in_speed.clone();
|
||||
}
|
||||
if in_speed.is_none() {
|
||||
in_speed = out_speed.clone();
|
||||
}
|
||||
if out_inf.is_none() {
|
||||
out_inf = in_inf.clone();
|
||||
}
|
||||
if in_inf.is_none() {
|
||||
in_inf = out_inf.clone();
|
||||
}
|
||||
}
|
||||
edit_keys(s, "Keyframe Velocity", merge_p(p), move |keys, i, _| {
|
||||
let n = keys[i].value.dims().max(1);
|
||||
// Current presentation of each side, so unspecified parts keep their values.
|
||||
let cur = |keys: &[Keyframe], out: bool| -> Vec<Ease> {
|
||||
(0..n).map(|d| effectcraft_keyframe::side_ease(keys, i, d, false, out).unwrap_or(Ease::EASY)).collect()
|
||||
};
|
||||
let cur_in = cur(keys, false);
|
||||
let cur_out = cur(keys, true);
|
||||
let k = &mut keys[i];
|
||||
if in_speed.is_some() || in_inf.is_some() {
|
||||
k.in_interp = Interp::Bezier;
|
||||
if k.in_ease.is_empty() {
|
||||
k.in_ease = vec![Ease::default(); n];
|
||||
let apply = |list: &mut Vec<Ease>, base: Vec<Ease>, sp: &Option<Vec<f64>>, inf: &Option<Vec<f64>>| {
|
||||
if list.len() != n {
|
||||
*list = base;
|
||||
}
|
||||
for e in &mut k.in_ease {
|
||||
if let Some(v) = in_speed {
|
||||
e.speed = v;
|
||||
for (d, e) in list.iter_mut().enumerate() {
|
||||
if let Some(v) = sp.as_ref().and_then(|v| v.get(d).or(v.first())) {
|
||||
e.speed = *v;
|
||||
}
|
||||
if let Some(v) = in_inf {
|
||||
if let Some(v) = inf.as_ref().and_then(|v| v.get(d).or(v.first())) {
|
||||
e.influence = v.clamp(0.001, 1.0);
|
||||
}
|
||||
}
|
||||
};
|
||||
if in_speed.is_some() || in_inf.is_some() {
|
||||
k.in_interp = Interp::Bezier;
|
||||
apply(&mut k.in_ease, cur_in, &in_speed, &in_inf);
|
||||
}
|
||||
if out_speed.is_some() || out_inf.is_some() {
|
||||
k.out_interp = Interp::Bezier;
|
||||
if k.out_ease.is_empty() {
|
||||
k.out_ease = vec![Ease::default(); n];
|
||||
}
|
||||
for e in &mut k.out_ease {
|
||||
if let Some(v) = out_speed {
|
||||
e.speed = v;
|
||||
}
|
||||
if let Some(v) = out_inf {
|
||||
e.influence = v.clamp(0.001, 1.0);
|
||||
}
|
||||
}
|
||||
apply(&mut k.out_ease, cur_out, &out_speed, &out_inf);
|
||||
}
|
||||
if let Some(c) = continuous {
|
||||
k.continuous = c;
|
||||
}
|
||||
k.auto_bezier = false;
|
||||
false
|
||||
@@ -404,6 +561,7 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
query!("prop.get", "Get Property", "{layer?, path|prop, time? (comp s)}", get),
|
||||
cmd!("prop.set", "Set Property Value", [], None, "{layer?, path|prop, value, time?, merge?}", has_layers, set),
|
||||
cmd!("prop.toggleAnimation", "Toggle Stopwatch", [], None, "{layer?, path|prop, value?}", has_layers, toggle_anim),
|
||||
cmd!("prop.addKey", "Add Keyframe", [], None, "{layer?, path|prop, time?, value?}", has_layers, add_key),
|
||||
@@ -435,7 +593,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Keyframe Interpolation...",
|
||||
["Animation"],
|
||||
Some("Cmd+Alt+K"),
|
||||
"{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}",
|
||||
"{interpolation?: linear|bezier|continuousBezier|autoBezier|hold, in?|out?: linear|bezier|hold, autoBezier?, continuous?, spatial?: linear|bezier|continuousBezier|autoBezier, roving?}",
|
||||
has_keys,
|
||||
interpolation
|
||||
),
|
||||
@@ -444,7 +602,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Keyframe Velocity...",
|
||||
["Animation"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{inSpeed?, inInfluence? %, outSpeed?, outInfluence? %}",
|
||||
"{inSpeed?, inInfluence? %, outSpeed?, outInfluence? % (numbers or per-dimension arrays), continuous?}",
|
||||
has_keys,
|
||||
velocity
|
||||
),
|
||||
|
||||
@@ -76,33 +76,51 @@ fn comp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
fn group_json(g: &PropGroup, l: &Layer, t: effectcraft_time::Tick, depth: usize, max_depth: usize) -> Value {
|
||||
/// The path segment that addresses child `i` of `g` (see `effectcraft_project::parse_path`): the match
|
||||
/// id (with `#n` when it is not the first sibling matching it), or `#index` when the match id is not
|
||||
/// path-safe (effects and other ids containing `.`).
|
||||
fn segment(g: &PropGroup, i: usize) -> String {
|
||||
let c = &g.children[i];
|
||||
let m = c.match_id();
|
||||
if m.is_empty() || m.contains(['/', '.', '#', '@']) || m.parse::<u64>().is_ok() {
|
||||
return format!("#{}", i + 1);
|
||||
}
|
||||
let n = g.children[..i].iter().filter(|x| x.match_id() == m || x.name().eq_ignore_ascii_case(m)).count() + 1;
|
||||
if n == 1 { m.to_string() } else { format!("{m}#{n}") }
|
||||
}
|
||||
|
||||
fn group_json(g: &PropGroup, path: &str, l: &Layer, t: effectcraft_time::Tick, depth: usize, max_depth: usize) -> Value {
|
||||
let children: Vec<Value> = if depth >= max_depth {
|
||||
vec![]
|
||||
} else {
|
||||
g.children
|
||||
.iter()
|
||||
.map(|c| match c {
|
||||
Node::Prop(p) => {
|
||||
let mut o = json!({"uid": p.uid, "match": p.match_id, "name": p.name, "value": p.value_at(l.layer_time(t)).to_json()});
|
||||
if !p.keys.is_empty() {
|
||||
o["keys"] = json!(
|
||||
p.keys
|
||||
.iter()
|
||||
.map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()}))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let seg = segment(g, i);
|
||||
let cpath = if path.is_empty() { seg } else { format!("{path}/{seg}") };
|
||||
match c {
|
||||
Node::Prop(p) => {
|
||||
let mut o = json!({"path": cpath, "uid": p.uid, "match": p.match_id, "name": p.name, "type": p.value.kind_name(), "value": p.value_at(l.layer_time(t)).to_json()});
|
||||
if !p.keys.is_empty() {
|
||||
o["keys"] = json!(
|
||||
p.keys
|
||||
.iter()
|
||||
.map(|k| json!({"time": k.time.seconds(), "value": k.value.to_json(), "in": k.in_interp.label(), "out": k.out_interp.label()}))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
if let Some(e) = &p.expr {
|
||||
o["expression"] = json!(e.text);
|
||||
}
|
||||
o
|
||||
}
|
||||
if let Some(e) = &p.expr {
|
||||
o["expression"] = json!(e.text);
|
||||
}
|
||||
o
|
||||
Node::Group(g) => group_json(g, &cpath, l, t, depth + 1, max_depth),
|
||||
}
|
||||
Node::Group(g) => group_json(g, l, t, depth + 1, max_depth),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut o = json!({"uid": g.uid, "match": g.match_id, "name": g.name, "enabled": g.enabled, "children": children});
|
||||
let mut o = json!({"path": path, "uid": g.uid, "match": g.match_id, "name": g.name, "enabled": g.enabled, "children": children});
|
||||
match &g.kind {
|
||||
GroupKind::Mask { mode, inverted, .. } => {
|
||||
o["mask"] = json!({"mode": mode.label(), "inverted": inverted});
|
||||
@@ -121,8 +139,10 @@ fn layer_tree(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = c.index_of(lid).unwrap_or(0);
|
||||
let l = c.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
let depth = p.get("depth").and_then(Value::as_u64).unwrap_or(16) as usize;
|
||||
let t = p.get("time").and_then(Value::as_f64).map(effectcraft_time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let mut o = layer_json(l, idx);
|
||||
o["properties"] = group_json(&l.props, l, s.time(), 0, depth);
|
||||
o["time"] = json!(t.seconds());
|
||||
o["properties"] = group_json(&l.props, "", l, t, 0, depth);
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
@@ -135,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
query!("command.list", "List Commands", "{filter?, enabledOnly?}", list),
|
||||
query!("project.summary", "Project Summary", "{}", summary),
|
||||
query!("comp.info", "Composition Info", "{comp?}", comp_info),
|
||||
query!("layer.tree", "Layer Property Tree", "{layer?, depth?}", layer_tree),
|
||||
query!("layer.tree", "Layer Property Tree", "{layer?, comp?, depth?, time? (comp s)} → nodes with `path`", layer_tree),
|
||||
query!("editor.state", "Editor State", "{}", state),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Render Queue: Composition ▸ Add to Render Queue, the queue's Render Settings / Output Module /
|
||||
//! Output To, Render and Stop.
|
||||
//!
|
||||
//! Items are addressed by `item` (the stable id from `renderQueue.add` / `renderQueue.list`) or
|
||||
//! `index` (1-based, the # column).
|
||||
|
||||
use effectcraft_project::render_queue::{
|
||||
AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderQuality, RenderQueueItem, RenderSettings, RenderStatus, TimeSpan,
|
||||
};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, f_p, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd, query};
|
||||
|
||||
fn can_add(s: &Session) -> std::result::Result<(), String> {
|
||||
not_rendering(s)?;
|
||||
if s.comp_for_queue(&Value::Null).is_some() { Ok(()) } else { Err("select or open a composition".into()) }
|
||||
}
|
||||
fn not_rendering(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.is_rendering() { Err("the render queue is rendering".into()) } else { Ok(()) }
|
||||
}
|
||||
fn has_items(s: &Session) -> std::result::Result<(), String> {
|
||||
not_rendering(s)?;
|
||||
if s.project.render_queue.is_empty() { Err("the render queue is empty".into()) } else { Ok(()) }
|
||||
}
|
||||
fn has_queued(s: &Session) -> std::result::Result<(), String> {
|
||||
not_rendering(s)?;
|
||||
if s.exporter.is_none() {
|
||||
return Err("export is not available in this build".into());
|
||||
}
|
||||
if s.project.render_queue.iter().any(RenderQueueItem::is_queued) { Ok(()) } else { Err("nothing is queued".into()) }
|
||||
}
|
||||
fn rendering(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.is_rendering() { Ok(()) } else { Err("not rendering".into()) }
|
||||
}
|
||||
|
||||
/// Index of the item named by `item` (id) or `index` (1-based).
|
||||
fn item_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
let q = &s.project.render_queue;
|
||||
if let Some(id) = p.get("item").and_then(Value::as_u64) {
|
||||
return q.iter().position(|i| i.id == id).ok_or_else(|| bad(cmd, format!("no render queue item {id}")));
|
||||
}
|
||||
if let Some(n) = p.get("index").and_then(Value::as_u64) {
|
||||
return (n as usize).checked_sub(1).filter(|i| *i < q.len()).ok_or_else(|| bad(cmd, format!("no render queue item #{n}")));
|
||||
}
|
||||
if q.len() == 1 {
|
||||
return Ok(0);
|
||||
}
|
||||
Err(bad(cmd, "pass `item` (id) or `index` (1-based)"))
|
||||
}
|
||||
|
||||
fn time_p(p: &Value, k: &str) -> Option<Tick> {
|
||||
f_p(p, k).map(Tick::from_seconds_f64)
|
||||
}
|
||||
|
||||
/// Apply Render Settings parameters.
|
||||
fn apply_settings(rs: &mut RenderSettings, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let mut any = false;
|
||||
if let Some(q) = str_p(p, "quality") {
|
||||
rs.quality = match q.to_ascii_lowercase().as_str() {
|
||||
"best" => RenderQuality::Best,
|
||||
"draft" => RenderQuality::Draft,
|
||||
_ => return Err(bad(cmd, "quality: best|draft")),
|
||||
};
|
||||
any = true;
|
||||
}
|
||||
match p.get("resolution") {
|
||||
Some(Value::String(r)) => {
|
||||
rs.resolution = match r.to_ascii_lowercase().as_str() {
|
||||
"full" => 1.0,
|
||||
"half" => 0.5,
|
||||
"third" => 1.0 / 3.0,
|
||||
"quarter" => 0.25,
|
||||
_ => return Err(bad(cmd, "resolution: full|half|third|quarter|<scale>")),
|
||||
};
|
||||
any = true;
|
||||
}
|
||||
Some(Value::Number(n)) => {
|
||||
rs.resolution = n.as_f64().unwrap_or(1.0).clamp(0.01, 4.0);
|
||||
any = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let (start, end) = (time_p(p, "start"), time_p(p, "end"));
|
||||
if let Some(ts) = str_p(p, "timeSpan") {
|
||||
rs.time_span = match ts.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
|
||||
"workarea" | "workareaonly" => TimeSpan::WorkArea,
|
||||
"comp" | "lengthofcomp" | "full" => TimeSpan::LengthOfComp,
|
||||
"custom" => TimeSpan::Custom { start: start.unwrap_or(Tick::ZERO), end: end.unwrap_or(Tick::from_seconds_f64(1.0)) },
|
||||
_ => return Err(bad(cmd, "timeSpan: workArea|comp|custom")),
|
||||
};
|
||||
any = true;
|
||||
} else if start.is_some() || end.is_some() {
|
||||
let (a, b) = match rs.time_span {
|
||||
TimeSpan::Custom { start, end } => (start, end),
|
||||
_ => (Tick::ZERO, Tick(i64::MAX / 4)),
|
||||
};
|
||||
rs.time_span = TimeSpan::Custom { start: start.unwrap_or(a), end: end.unwrap_or(b) };
|
||||
any = true;
|
||||
}
|
||||
if let TimeSpan::Custom { start, end } = rs.time_span
|
||||
&& end <= start
|
||||
{
|
||||
return Err(bad(cmd, "end must be after start"));
|
||||
}
|
||||
match p.get("frameRate") {
|
||||
Some(Value::Null) => {
|
||||
rs.frame_rate = None;
|
||||
any = true;
|
||||
}
|
||||
Some(v) => {
|
||||
let f = v.as_f64().filter(|f| *f > 0.0 && *f <= 1000.0).ok_or_else(|| bad(cmd, "frameRate: fps > 0 or null (comp rate)"))?;
|
||||
rs.frame_rate = Some(FrameRate::from_f64(f));
|
||||
any = true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(b) = b_p(p, "motionBlur") {
|
||||
rs.motion_blur = b;
|
||||
any = true;
|
||||
}
|
||||
if let Some(b) = b_p(p, "skipExisting") {
|
||||
rs.skip_existing = b;
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
}
|
||||
|
||||
/// Apply Output Module parameters.
|
||||
fn apply_output(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let mut any = false;
|
||||
if let Some(f) = str_p(p, "format") {
|
||||
let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|prores|png|jpeg|tiff|exr|gif"))?;
|
||||
om.set_format(f);
|
||||
any = true;
|
||||
}
|
||||
if let Some(c) = str_p(p, "channels") {
|
||||
om.channels = match c.to_ascii_lowercase().replace([' ', '+'], "").as_str() {
|
||||
"rgb" => Channels::Rgb,
|
||||
"rgba" | "rgbalpha" => Channels::Rgba,
|
||||
_ => return Err(bad(cmd, "channels: rgb|rgba")),
|
||||
};
|
||||
if om.channels == Channels::Rgba && !om.format.supports_alpha() {
|
||||
return Err(bad(cmd, format!("{} has no alpha channel", om.format.label())));
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
if let Some(q) = f_p(p, "quality") {
|
||||
om.quality = q.clamp(1.0, 100.0) as u8;
|
||||
any = true;
|
||||
}
|
||||
if let Some(b) = f_p(p, "bitrate") {
|
||||
om.bitrate_kbps = b.clamp(100.0, 500_000.0) as u32;
|
||||
any = true;
|
||||
}
|
||||
if let Some(pp) = str_p(p, "proresProfile") {
|
||||
om.prores_profile = ProResProfile::from_name(pp).ok_or_else(|| bad(cmd, "proresProfile: proxy|lt|standard|hq|4444|4444xq"))?;
|
||||
any = true;
|
||||
}
|
||||
if let Some(a) = p.get("audio") {
|
||||
om.audio = match a {
|
||||
Value::Bool(true) => AudioOutput::On,
|
||||
Value::Bool(false) => AudioOutput::Off,
|
||||
Value::String(s) => match s.to_ascii_lowercase().as_str() {
|
||||
"auto" => AudioOutput::Auto,
|
||||
"on" => AudioOutput::On,
|
||||
"off" => AudioOutput::Off,
|
||||
_ => return Err(bad(cmd, "audio: auto|on|off")),
|
||||
},
|
||||
_ => return Err(bad(cmd, "audio: auto|on|off")),
|
||||
};
|
||||
any = true;
|
||||
}
|
||||
if let Some(r) = p.get("sampleRate").and_then(Value::as_u64) {
|
||||
om.audio_sample_rate = (r as u32).clamp(8_000, 192_000);
|
||||
any = true;
|
||||
}
|
||||
if let Some(l) = b_p(p, "loop") {
|
||||
om.gif_loop = l;
|
||||
any = true;
|
||||
}
|
||||
if let Some(o) = str_p(p, "output").or(str_p(p, "path")) {
|
||||
om.output = o.to_string();
|
||||
if p.get("format").is_none()
|
||||
&& let Some(f) = OutputFormat::from_path(o).filter(|f| *f != om.format && !o.contains("[fileExtension]"))
|
||||
{
|
||||
// `out.mov` with an H.264 module → ProRes, like picking a file type in Output To.
|
||||
let keep = om.output.clone();
|
||||
om.set_format(f);
|
||||
om.output = keep;
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
}
|
||||
|
||||
/// A finished item that is edited goes back to Queued (AE re-queues on change).
|
||||
fn requeue(it: &mut RenderQueueItem) {
|
||||
if it.render && !matches!(it.status, RenderStatus::Rendering) {
|
||||
it.status = RenderStatus::Queued;
|
||||
}
|
||||
}
|
||||
|
||||
fn item_json(s: &Session, it: &RenderQueueItem, index: usize) -> Value {
|
||||
let comp = s.project.comp(it.comp);
|
||||
let name = s.project.item(it.comp).map(|i| i.name.clone());
|
||||
let (w, h) = comp.map(|c| it.settings.output_size(c)).map(|(w, h)| it.output.format.coded_size(w, h)).unwrap_or((0, 0));
|
||||
let frames = comp.map(|c| it.settings.frame_count(c)).unwrap_or(0);
|
||||
let mut v = serde_json::to_value(it).unwrap_or(Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("index".into(), json!(index + 1));
|
||||
o.insert("compName".into(), json!(name));
|
||||
o.insert("statusLabel".into(), json!(it.status.label()));
|
||||
o.insert("outputPath".into(), json!(s.resolve_output(it)));
|
||||
o.insert("renderSettingsSummary".into(), json!(it.settings.summary()));
|
||||
o.insert("outputModuleSummary".into(), json!(it.output.summary()));
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
o.insert("frames".into(), json!(frames));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = s.comp_for_queue(p).ok_or(EngineError::NoComp)?;
|
||||
let mut it = RenderQueueItem::new(0, cid);
|
||||
if let Some(f) = str_p(p, "format") {
|
||||
let f = OutputFormat::from_name(f).ok_or_else(|| bad("renderQueue.add", "format: h264|prores|png|jpeg|tiff|exr|gif"))?;
|
||||
it.output = OutputModule::for_format(f);
|
||||
}
|
||||
apply_settings(&mut it.settings, p, "renderQueue.add")?;
|
||||
let mut op = p.clone();
|
||||
if let Some(o) = op.as_object_mut() {
|
||||
o.remove("format");
|
||||
}
|
||||
apply_output(&mut it.output, &op, "renderQueue.add")?;
|
||||
let id = s.edit("Add to Render Queue", None, |proj, _| {
|
||||
it.id = proj.render_queue.iter().map(|i| i.id).max().unwrap_or(0) + 1;
|
||||
let id = it.id;
|
||||
proj.render_queue.push(it);
|
||||
Ok(id)
|
||||
})?;
|
||||
let idx = s.project.render_queue.len() - 1;
|
||||
let mut v = item_json(s, &s.project.render_queue[idx], idx);
|
||||
v["item"] = json!(id);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.remove")?;
|
||||
s.edit("Remove from Render Queue", None, |proj, _| {
|
||||
proj.render_queue.remove(i);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"remaining": s.project.render_queue.len()}))
|
||||
}
|
||||
|
||||
fn set_render(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.setRender")?;
|
||||
let on = b_p(p, "render").unwrap_or(!s.project.render_queue[i].render);
|
||||
s.edit("Render Queue: Render", None, |proj, _| {
|
||||
let it = &mut proj.render_queue[i];
|
||||
it.render = on;
|
||||
it.status = if on { RenderStatus::Queued } else { RenderStatus::Unqueued };
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"render": on}))
|
||||
}
|
||||
|
||||
fn set_render_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.setRenderSettings")?;
|
||||
let mut rs = s.project.render_queue[i].settings.clone();
|
||||
if !apply_settings(&mut rs, p, "renderQueue.setRenderSettings")? {
|
||||
return Err(bad("renderQueue.setRenderSettings", "nothing to change"));
|
||||
}
|
||||
s.edit("Render Settings", None, |proj, _| {
|
||||
let it = &mut proj.render_queue[i];
|
||||
it.settings = rs;
|
||||
requeue(it);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(item_json(s, &s.project.render_queue[i], i))
|
||||
}
|
||||
|
||||
fn set_output_module(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.setOutputModule")?;
|
||||
let mut om = s.project.render_queue[i].output.clone();
|
||||
if !apply_output(&mut om, p, "renderQueue.setOutputModule")? {
|
||||
return Err(bad("renderQueue.setOutputModule", "nothing to change"));
|
||||
}
|
||||
s.edit("Output Module Settings", None, |proj, _| {
|
||||
let it = &mut proj.render_queue[i];
|
||||
it.output = om;
|
||||
requeue(it);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(item_json(s, &s.project.render_queue[i], i))
|
||||
}
|
||||
|
||||
fn set_output(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.setOutput")?;
|
||||
let path = str_p(p, "path").or(str_p(p, "output")).ok_or_else(|| bad("renderQueue.setOutput", "pass `path` (file path or template)"))?;
|
||||
let mut om = s.project.render_queue[i].output.clone();
|
||||
apply_output(&mut om, &json!({"output": path}), "renderQueue.setOutput")?;
|
||||
s.edit("Output To", None, |proj, _| {
|
||||
let it = &mut proj.render_queue[i];
|
||||
it.output = om;
|
||||
requeue(it);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(item_json(s, &s.project.render_queue[i], i))
|
||||
}
|
||||
|
||||
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.move")?;
|
||||
let n = s.project.render_queue.len();
|
||||
let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("renderQueue.move", "pass `to` (1-based position)"))? as usize;
|
||||
let to = to.clamp(1, n) - 1;
|
||||
s.edit("Reorder Render Queue", None, |proj, _| {
|
||||
let it = proj.render_queue.remove(i);
|
||||
proj.render_queue.insert(to, it);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"index": to + 1}))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = item_index(s, p, "renderQueue.duplicate")?;
|
||||
let id = s.edit("Duplicate Render Item", None, |proj, _| {
|
||||
let mut it = proj.render_queue[i].clone();
|
||||
it.id = proj.render_queue.iter().map(|i| i.id).max().unwrap_or(0) + 1;
|
||||
it.render = true;
|
||||
it.status = RenderStatus::Queued;
|
||||
it.started = None;
|
||||
it.render_time = None;
|
||||
it.last_output = None;
|
||||
let id = it.id;
|
||||
proj.render_queue.insert(i + 1, it);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({"item": id, "index": i + 2}))
|
||||
}
|
||||
|
||||
fn render(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let wait = b_p(p, "wait").unwrap_or(true);
|
||||
let ids = s.start_render(wait).map_err(EngineError::Other)?;
|
||||
let items: Vec<Value> = s.project.render_queue.iter().enumerate().filter(|(_, i)| ids.contains(&i.id)).map(|(k, i)| item_json(s, i, k)).collect();
|
||||
Ok(json!({"rendering": s.is_rendering(), "items": items}))
|
||||
}
|
||||
|
||||
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"stopped": s.stop_render()}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.poll_render();
|
||||
let items: Vec<Value> = s.project.render_queue.iter().enumerate().map(|(k, i)| item_json(s, i, k)).collect();
|
||||
Ok(json!({"items": items, "rendering": s.is_rendering(), "progress": s.render_progress()}))
|
||||
}
|
||||
|
||||
fn formats(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let avail = s.exporter.as_ref().map(|e| e.formats()).unwrap_or_default();
|
||||
let v: Vec<Value> = OutputFormat::ALL
|
||||
.iter()
|
||||
.map(|f| {
|
||||
json!({
|
||||
"id": format!("{f:?}"),
|
||||
"label": f.label(),
|
||||
"extension": f.extension(),
|
||||
"sequence": f.is_sequence(),
|
||||
"alpha": f.supports_alpha(),
|
||||
"audio": f.supports_audio(),
|
||||
"available": avail.contains(f),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"formats": v, "proresProfiles": ProResProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"renderQueue.add",
|
||||
"Add to Render Queue",
|
||||
["Composition"],
|
||||
Some("Cmd+M"),
|
||||
"{comp?: id|name, format?: h264|prores|png|jpeg|tiff|exr|gif, output?: path|template, …renderSettings, …outputModule}",
|
||||
can_add,
|
||||
add
|
||||
),
|
||||
cmd!("renderQueue.remove", "Remove from Render Queue", [], None, "{item?: id, index?: n}", has_items, remove),
|
||||
cmd!("renderQueue.setRender", "Render Queue: Render Checkbox", [], None, "{item?|index?, render?: bool (toggles)}", has_items, set_render),
|
||||
cmd!(
|
||||
"renderQueue.setRenderSettings",
|
||||
"Render Settings...",
|
||||
[],
|
||||
None,
|
||||
"{item?|index?, quality?: best|draft, resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool}",
|
||||
has_items,
|
||||
set_render_settings
|
||||
),
|
||||
cmd!(
|
||||
"renderQueue.setOutputModule",
|
||||
"Output Module Settings...",
|
||||
[],
|
||||
None,
|
||||
"{item?|index?, format?, channels?: rgb|rgba, quality?: 1-100, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, audio?: auto|on|off, sampleRate?, loop?: bool, output?}",
|
||||
has_items,
|
||||
set_output_module
|
||||
),
|
||||
cmd!(
|
||||
"renderQueue.setOutput",
|
||||
"Output To...",
|
||||
[],
|
||||
None,
|
||||
"{item?|index?, path: file path or template like [compName].[fileExtension]}",
|
||||
has_items,
|
||||
set_output
|
||||
),
|
||||
cmd!("renderQueue.move", "Move in Render Queue", [], None, "{item?|index?, to: n (1-based)}", has_items, move_item),
|
||||
cmd!("renderQueue.duplicate", "Duplicate Render Item", [], None, "{item?|index?}", has_items, duplicate),
|
||||
cmd!("renderQueue.render", "Render", [], None, "{wait?: bool (default true; the UI renders in the background)}", has_queued, render),
|
||||
cmd!("renderQueue.stop", "Stop Rendering", [], None, "{}", rendering, stop),
|
||||
query!("renderQueue.list", "Render Queue Items", "{}", list),
|
||||
query!("renderQueue.formats", "Output Formats", "{}", formats),
|
||||
]
|
||||
}
|
||||
@@ -21,7 +21,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("app.hideOthers", "Hide Others", [], "{}"),
|
||||
stub!("app.showAll", "Show All", [], "{}"),
|
||||
// Render queue / export (export milestone).
|
||||
stub!("render.addToQueue", "Add to Render Queue", ["Composition"], "Cmd+M", "{comp?}"),
|
||||
stub!("render.addOutputModule", "Add Output Module", ["Composition"], "{}"),
|
||||
stub!("render.preRender", "Pre-render...", ["Composition"], "{}"),
|
||||
stub!("render.saveCurrentPreview", "Save Current Preview...", ["Composition"], "{path}"),
|
||||
@@ -44,16 +43,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("layer.mask.featherFalloff", "Feather Falloff", [], "{mode: smooth|linear}"),
|
||||
stub!("layer.mask.hideLocked", "Hide Locked Masks", ["Layer", "Mask"], "{}"),
|
||||
stub!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], "{}"),
|
||||
stub!("path.closed", "Closed", ["Layer", "Mask and Shape Path"], "{}"),
|
||||
stub!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], "{}"),
|
||||
stub!("path.groupShapes", "Group Shapes", ["Layer", "Mask and Shape Path"], "Cmd+G", "{}"),
|
||||
stub!("path.ungroupShapes", "Ungroup Shapes", ["Layer", "Mask and Shape Path"], "Cmd+Shift+G", "{}"),
|
||||
stub!("path.setFirstVertex", "Set First Vertex", ["Layer", "Mask and Shape Path"], "{}"),
|
||||
stub!("path.freeTransform", "Free Transform Points", ["Layer", "Mask and Shape Path"], "{}"),
|
||||
// Time (timeline milestone).
|
||||
stub!("layer.timeRemap", "Enable Time Remapping", ["Layer", "Time"], "Cmd+Alt+T", "{layers?}"),
|
||||
stub!("layer.freezeFrame", "Freeze Frame", ["Layer", "Time"], "{layers?}"),
|
||||
stub!("layer.freezeOnLastFrame", "Freeze On Last Frame", ["Layer", "Time"], "{layers?}"),
|
||||
stub!("layer.alignVideoToData", "Align Video to Data", ["Layer", "Time"], "{}"),
|
||||
stub!("layer.environment", "Environment Layer", ["Layer"], "{}"),
|
||||
stub!("layer.updateMarkersFromSource", "Update Markers From Source", ["Layer", "Markers"], "{}"),
|
||||
@@ -69,8 +64,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("camera.linkFocusToPoi", "Link Focus Distance to Point of Interest", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.linkFocusToLayer", "Link Focus Distance to Layer", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.setFocusToLayer", "Set Focus Distance to Layer", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.settings", "Camera Settings...", ["Layer", "Camera"], "{}"),
|
||||
stub!("view.reset3dView", "Reset 3D View", ["Layer", "Camera"], "{}"),
|
||||
stub!("light.fromModel", "Create Lights from 3D Model", ["Layer", "Light"], "{}"),
|
||||
stub!("light.controlWithCamera", "Control Light with Camera", ["Layer", "Light"], "{}"),
|
||||
stub!("light.environmentBackground", "Create Environment Light Background Layer", ["Layer", "Light"], "{}"),
|
||||
@@ -79,8 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("material.duplicateAssign", "Duplicate and Assign Material", ["Layer", "Material"], "{}"),
|
||||
stub!("view.layout", "Switch View Layout", [], "{views: 1|2|4}"),
|
||||
stub!("view.shareViewOptions", "Share View Options", ["View", "Switch View Layout"], "{}"),
|
||||
stub!("view.3d", "Switch 3D View", [], "{view}"),
|
||||
stub!("view.last3dView", "Switch to Last 3D View", ["View"], "Escape", "{}"),
|
||||
stub!("view.3d.default", "Default", ["View", "Switch 3D View"], "{}"),
|
||||
stub!("view.lookAtSelected", "Look at Selected Layers", ["View"], "Cmd+Alt+Shift+\\", "{}"),
|
||||
stub!("view.lookAtAll", "Look at All Layers", ["View"], "{}"),
|
||||
stub!("view.splitLockedViewer", "Split with New Locked Viewer", ["View"], "{}"),
|
||||
@@ -97,7 +89,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("text.animatorFontAxes", "Variable Font Axes", ["Animation", "Animate Text"], "{}"),
|
||||
stub!("text.addWigglySelector", "Wiggly", ["Animation", "Add Text Selector"], "{}"),
|
||||
stub!("text.addExpressionSelector", "Expression", ["Animation", "Add Text Selector"], "{}"),
|
||||
stub!("prop.separateDimensions", "Separate Dimensions", ["Animation"], "{}"),
|
||||
stub!("track.camera", "Track Camera", ["Animation"], "{}"),
|
||||
stub!("track.warpStabilizer", "Warp Stabilizer VFX", ["Animation"], "{}"),
|
||||
stub!("track.motion", "Track Motion", ["Animation"], "{}"),
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
//! 3D: cameras (Layer ▸ New ▸ Camera, Camera Settings), lights (Layer ▸ New ▸ Light, Light
|
||||
//! Settings), the viewer's 3D views (View ▸ Switch 3D View, Reset 3D View) and the camera tools
|
||||
//! (Orbit, Pan, Dolly) acting on the current 3D view.
|
||||
|
||||
use effectcraft_geom::{Mat4, Vec3, vec3};
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::build;
|
||||
use effectcraft_project::{AutoOrient, Comp, ItemId, Layer, LayerId, LayerSource, LightKind};
|
||||
use effectcraft_render::EvalCtx;
|
||||
use effectcraft_render::three_d::camera::{self, PRESETS, Rig, View3D, ViewCam, Views3D, orientation_for, zoom_for_focal};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::layer::{color_p, insert_layer};
|
||||
use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, layer_mut, layer_p, merge_p, str_p, time_p};
|
||||
use crate::{EngineError, Result, Session, cmd, query};
|
||||
|
||||
fn v3_p(p: &Value, k: &str) -> Option<[f64; 3]> {
|
||||
let a = p.get(k)?.as_array()?;
|
||||
let g = |i: usize| a.get(i).and_then(Value::as_f64);
|
||||
Some([g(0)?, g(1)?, g(2).unwrap_or(0.0)])
|
||||
}
|
||||
|
||||
/// Set a property at comp time `t` (adds a key when it is animated).
|
||||
fn set_at(l: &mut Layer, path: &str, t: Tick, v: KV) {
|
||||
let lt = l.layer_time(t);
|
||||
if let Some(pr) = l.props.prop_mut(path) {
|
||||
pr.set_value_at(lt, v);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_at(l: &Layer, path: &str, t: Tick) -> Option<KV> {
|
||||
l.props.prop(path).map(|pr| pr.value_at(l.layer_time(t)))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- cameras
|
||||
|
||||
/// Parse a camera type: `oneNode`/`twoNode` (or "One-Node Camera"…). Some(true) = two-node.
|
||||
fn two_node_p(p: &Value) -> Option<bool> {
|
||||
let t = str_p(p, "type")?.to_ascii_lowercase().replace(['-', ' ', '_'], "");
|
||||
if t.starts_with("one") {
|
||||
Some(false)
|
||||
} else if t.starts_with("two") {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Zoom from `zoom`, `preset` ("50mm"), `focalLength` (mm) or `angleOfView` (degrees).
|
||||
fn zoom_p(p: &Value, comp_w: f64) -> Result<Option<f64>> {
|
||||
if let Some(z) = f_p(p, "zoom") {
|
||||
return Ok(Some(z.max(0.1)));
|
||||
}
|
||||
if let Some(pr) = p.get("preset") {
|
||||
let focal = match pr {
|
||||
Value::Number(n) => n.as_f64(),
|
||||
Value::String(s) => {
|
||||
let k = s.trim().to_ascii_lowercase();
|
||||
PRESETS.iter().find(|(n, _)| n.eq_ignore_ascii_case(&k)).map(|(_, f)| *f).or_else(|| k.trim_end_matches("mm").trim().parse().ok())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| bad("layer.newCamera", format!("unknown preset {pr}; use one of 15mm, 20mm, 24mm, 28mm, 35mm, 50mm, 80mm, 135mm, 200mm")))?;
|
||||
return Ok(Some(zoom_for_focal(comp_w, focal)));
|
||||
}
|
||||
if let Some(f) = f_p(p, "focalLength") {
|
||||
return Ok(Some(zoom_for_focal(comp_w, f)));
|
||||
}
|
||||
if let Some(a) = f_p(p, "angleOfView") {
|
||||
return Ok(Some(comp_w * 0.5 / (a.clamp(0.1, 179.0).to_radians() * 0.5).tan()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Apply Camera Settings parameters to a camera layer at comp time `t`.
|
||||
fn apply_camera(l: &mut Layer, comp: &Comp, p: &Value, t: Tick, cmd: &str) -> Result<()> {
|
||||
let w = comp.width as f64;
|
||||
if let Some(z) = zoom_p(p, w)? {
|
||||
set_at(l, "cameraOptions/zoom", t, KV::Scalar(z));
|
||||
// "Lock to Zoom" (default): the focus distance follows the zoom unless one is given.
|
||||
if b_p(p, "lockToZoom").unwrap_or(true) && f_p(p, "focusDistance").is_none() {
|
||||
set_at(l, "cameraOptions/focusDistance", t, KV::Scalar(z));
|
||||
}
|
||||
}
|
||||
if let Some(v) = b_p(p, "dof").or_else(|| b_p(p, "depthOfField")) {
|
||||
set_at(l, "cameraOptions/dof", t, KV::Bool(v));
|
||||
}
|
||||
for (k, path) in [("focusDistance", "cameraOptions/focusDistance"), ("aperture", "cameraOptions/aperture"), ("blurLevel", "cameraOptions/blurLevel")] {
|
||||
if let Some(v) = f_p(p, k) {
|
||||
set_at(l, path, t, KV::Scalar(v.max(0.0)));
|
||||
}
|
||||
}
|
||||
if let Some(fs) = f_p(p, "fStop") {
|
||||
// F-Stop = focal length / aperture, apertures in mm scaled like the presets (25.3 mm at 1920 px).
|
||||
let z = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
|
||||
let focal = camera::focal_for_zoom(w, z);
|
||||
set_at(l, "cameraOptions/aperture", t, KV::Scalar(focal / fs.max(0.01) * w / 1920.0));
|
||||
}
|
||||
if let Some(pos) = v3_p(p, "position") {
|
||||
set_at(l, "transform/position", t, KV::Vec3(pos));
|
||||
}
|
||||
if let Some(poi) = v3_p(p, "poi").or_else(|| v3_p(p, "pointOfInterest")) {
|
||||
set_at(l, "transform/poi", t, KV::Vec3(poi));
|
||||
}
|
||||
if let Some(two) = two_node_p(p) {
|
||||
let was = l.auto_orient == AutoOrient::TowardsPointOfInterest;
|
||||
if two != was {
|
||||
let pos = Vec3::from(get_at(l, "transform/position", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]));
|
||||
let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
|
||||
if two {
|
||||
// Keep the view: put the POI where the camera looks, clear the orientation.
|
||||
let o = get_at(l, "transform/orientation", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]);
|
||||
let fwd = Mat4::orientation(Vec3::from(o)).apply_vec(vec3(0.0, 0.0, 1.0));
|
||||
let poi = pos + fwd * zoom;
|
||||
set_at(l, "transform/poi", t, KV::Vec3([poi.x, poi.y, poi.z]));
|
||||
set_at(l, "transform/orientation", t, KV::Vec3([0.0; 3]));
|
||||
l.auto_orient = AutoOrient::TowardsPointOfInterest;
|
||||
} else {
|
||||
let poi = Vec3::from(get_at(l, "transform/poi", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]));
|
||||
set_at(l, "transform/orientation", t, KV::Vec3(orientation_for(poi - pos)));
|
||||
l.auto_orient = AutoOrient::Off;
|
||||
}
|
||||
}
|
||||
} else if p.get("type").is_some() {
|
||||
return Err(bad(cmd, "type: oneNode|twoNode"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_camera(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let name = str_p(p, "name").unwrap_or("Camera 1").to_string();
|
||||
let t = time_p(s, p, Some(&comp));
|
||||
let id = s.edit("New Camera", None, |proj, st| {
|
||||
let mut l = build::layer(proj, &comp, &name, LayerSource::Camera, (comp.width, comp.height), None);
|
||||
apply_camera(&mut l, &comp, p, t, "layer.newCamera")?;
|
||||
insert_layer(proj, st, cid, l)
|
||||
})?;
|
||||
Ok(json!({"layer": id.0}))
|
||||
}
|
||||
|
||||
/// The camera or light layer a settings command targets.
|
||||
fn target(s: &Session, p: &Value, cmd: &str, want_camera: bool) -> Result<(ItemId, LayerId)> {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let ok = if want_camera { l.is_camera() } else { l.is_light() };
|
||||
if !ok {
|
||||
return Err(bad(cmd, format!("layer `{}` is not a {}", l.name, if want_camera { "camera" } else { "light" })));
|
||||
}
|
||||
Ok((cid, lid))
|
||||
}
|
||||
|
||||
fn camera_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = target(s, p, "layer.cameraSettings", true)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let t = time_p(s, p, Some(&comp));
|
||||
let name = str_p(p, "name").map(str::to_string);
|
||||
s.edit("Camera Settings", None, |proj, _| {
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
if let Some(n) = &name {
|
||||
l.name = n.clone();
|
||||
}
|
||||
apply_camera(l, &comp, p, t, "layer.cameraSettings")
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lights
|
||||
|
||||
fn light_kind_p(p: &Value, k: &str) -> Option<LightKind> {
|
||||
let v = str_p(p, k)?;
|
||||
LightKind::ALL.into_iter().find(|l| l.label().eq_ignore_ascii_case(v.trim()))
|
||||
}
|
||||
|
||||
fn apply_light(l: &mut Layer, p: &Value, t: Tick, cmd: &str) -> Result<()> {
|
||||
if let Some(c) = color_p(p, "color") {
|
||||
set_at(l, "lightOptions/color", t, KV::Color([c[0] as f64, c[1] as f64, c[2] as f64, 1.0]));
|
||||
}
|
||||
for k in ["intensity", "coneAngle", "coneFeather", "radius", "falloffDistance", "shadowDarkness", "shadowDiffusion"] {
|
||||
if let Some(v) = f_p(p, k) {
|
||||
set_at(l, &format!("lightOptions/{k}"), t, KV::Scalar(v));
|
||||
}
|
||||
}
|
||||
if let Some(v) = b_p(p, "castsShadows") {
|
||||
set_at(l, "lightOptions/castsShadows", t, KV::Bool(v));
|
||||
}
|
||||
if let Some(f) = p.get("falloff") {
|
||||
let i = match f {
|
||||
Value::Number(n) => n.as_u64().map(|v| v as u32),
|
||||
Value::String(s) => {
|
||||
let k = s.to_ascii_lowercase();
|
||||
if k.starts_with("none") {
|
||||
Some(0)
|
||||
} else if k.starts_with("smooth") {
|
||||
Some(1)
|
||||
} else if k.starts_with("inverse") {
|
||||
Some(2)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
.filter(|i| *i <= 2)
|
||||
.ok_or_else(|| bad(cmd, "falloff: None|Smooth|Inverse Square Clamped"))?;
|
||||
set_at(l, "lightOptions/falloff", t, KV::Enum(i));
|
||||
}
|
||||
if let Some(pos) = v3_p(p, "position") {
|
||||
set_at(l, "transform/position", t, KV::Vec3(pos));
|
||||
}
|
||||
if let Some(poi) = v3_p(p, "poi").or_else(|| v3_p(p, "pointOfInterest")) {
|
||||
set_at(l, "transform/poi", t, KV::Vec3(poi));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_light(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let kind = match p.get("kind").or_else(|| p.get("type")) {
|
||||
Some(_) => light_kind_p(p, "kind").or_else(|| light_kind_p(p, "type")).ok_or_else(|| bad("layer.newLight", "kind: Parallel|Spot|Point|Ambient"))?,
|
||||
None => LightKind::Spot,
|
||||
};
|
||||
let name = str_p(p, "name").unwrap_or("Light 1").to_string();
|
||||
let t = time_p(s, p, Some(&comp));
|
||||
let id = s.edit("New Light", None, |proj, st| {
|
||||
let mut l = build::layer(proj, &comp, &name, LayerSource::Light { kind }, (comp.width, comp.height), None);
|
||||
apply_light(&mut l, p, t, "layer.newLight")?;
|
||||
insert_layer(proj, st, cid, l)
|
||||
})?;
|
||||
Ok(json!({"layer": id.0}))
|
||||
}
|
||||
|
||||
fn light_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid) = target(s, p, "layer.lightSettings", false)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let t = time_p(s, p, Some(&comp));
|
||||
let name = str_p(p, "name").map(str::to_string);
|
||||
let kind = match p.get("kind").or_else(|| p.get("type")) {
|
||||
Some(_) => {
|
||||
Some(light_kind_p(p, "kind").or_else(|| light_kind_p(p, "type")).ok_or_else(|| bad("layer.lightSettings", "kind: Parallel|Spot|Point|Ambient"))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
s.edit("Light Settings", None, |proj, _| {
|
||||
let old = proj.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or(EngineError::NoComp)?;
|
||||
let mut l = old.clone();
|
||||
if let Some(k) = kind
|
||||
&& old.source != (LayerSource::Light { kind: k })
|
||||
{
|
||||
// Light Type change: rebuild the light's groups, carrying over shared values.
|
||||
let fresh = build::layer(proj, &comp, &old.name, LayerSource::Light { kind: k }, (comp.width, comp.height), None);
|
||||
l.source = fresh.source.clone();
|
||||
l.auto_orient = fresh.auto_orient;
|
||||
l.props = fresh.props;
|
||||
for path in [
|
||||
"transform/position",
|
||||
"transform/poi",
|
||||
"transform/orientation",
|
||||
"transform/rotationX",
|
||||
"transform/rotationY",
|
||||
"transform/rotation",
|
||||
"lightOptions/intensity",
|
||||
"lightOptions/color",
|
||||
"lightOptions/coneAngle",
|
||||
"lightOptions/coneFeather",
|
||||
"lightOptions/falloff",
|
||||
"lightOptions/radius",
|
||||
"lightOptions/falloffDistance",
|
||||
"lightOptions/castsShadows",
|
||||
"lightOptions/shadowDarkness",
|
||||
"lightOptions/shadowDiffusion",
|
||||
] {
|
||||
if let (Some(src), Some(dst)) = (old.props.prop(path), l.props.prop_mut(path)) {
|
||||
dst.value = src.value.clone();
|
||||
dst.keys = src.keys.clone();
|
||||
dst.expr = src.expr.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(n) = &name {
|
||||
l.name = n.clone();
|
||||
}
|
||||
apply_light(&mut l, p, t, "layer.lightSettings")?;
|
||||
*layer_mut(proj, cid, lid)? = l;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3D views
|
||||
|
||||
fn views(s: &mut Session, cid: ItemId) -> &mut Views3D {
|
||||
s.state.views3d.entry(cid).or_default()
|
||||
}
|
||||
|
||||
fn view_p(p: &Value, cmd: &str) -> Result<View3D> {
|
||||
let v = str_p(p, "view").ok_or_else(|| bad(cmd, "missing `view` (activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3)"))?;
|
||||
View3D::from_id(v).ok_or_else(|| bad(cmd, format!("unknown view `{v}`")))
|
||||
}
|
||||
|
||||
fn switch_view(s: &mut Session, cid: ItemId, v: View3D) -> Value {
|
||||
let vs = views(s, cid);
|
||||
if vs.current != v {
|
||||
vs.last = vs.current;
|
||||
vs.current = v;
|
||||
}
|
||||
json!({"view": v.id()})
|
||||
}
|
||||
|
||||
fn set_3d_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let v = view_p(p, "view.set3DView")?;
|
||||
Ok(switch_view(s, cid, v))
|
||||
}
|
||||
|
||||
macro_rules! view_cmd {
|
||||
($f:ident, $v:expr) => {
|
||||
fn $f(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
Ok(switch_view(s, cid, $v))
|
||||
}
|
||||
};
|
||||
}
|
||||
view_cmd!(view_active, View3D::ActiveCamera);
|
||||
view_cmd!(view_front, View3D::Front);
|
||||
view_cmd!(view_left, View3D::Left);
|
||||
view_cmd!(view_top, View3D::Top);
|
||||
view_cmd!(view_back, View3D::Back);
|
||||
view_cmd!(view_right, View3D::Right);
|
||||
view_cmd!(view_bottom, View3D::Bottom);
|
||||
view_cmd!(view_custom1, View3D::Custom1);
|
||||
view_cmd!(view_custom2, View3D::Custom2);
|
||||
view_cmd!(view_custom3, View3D::Custom3);
|
||||
|
||||
fn last_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let last = views(s, cid).last;
|
||||
Ok(switch_view(s, cid, last))
|
||||
}
|
||||
|
||||
fn reset_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let cur = views(s, cid).current;
|
||||
if cur != View3D::ActiveCamera {
|
||||
views(s, cid).cams.remove(&cur);
|
||||
return Ok(json!({"view": cur.id()}));
|
||||
}
|
||||
// Active camera: back to the default framing (50 mm-style distance, looking at the centre).
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
|
||||
let cam = comp.active_camera(t).map(|l| l.id).ok_or_else(|| bad("view.reset3DView", "the comp has no camera layer"))?;
|
||||
let (w, h) = (comp.width as f64, comp.height as f64);
|
||||
s.edit("Reset 3D View", None, |proj, _| {
|
||||
let l = layer_mut(proj, cid, cam)?;
|
||||
let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(effectcraft_geom::default_camera_zoom(w));
|
||||
set_at(l, "transform/position", t, KV::Vec3([w / 2.0, h / 2.0, -zoom]));
|
||||
set_at(l, "transform/poi", t, KV::Vec3([w / 2.0, h / 2.0, 0.0]));
|
||||
set_at(l, "transform/orientation", t, KV::Vec3([0.0; 3]));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"view": "activeCamera"}))
|
||||
}
|
||||
|
||||
fn set_view_camera(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let v = view_p(p, "view.set3DViewCamera")?;
|
||||
if v == View3D::ActiveCamera {
|
||||
return Err(bad("view.set3DViewCamera", "edit the camera layer for the active camera view"));
|
||||
}
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let (w, h) = (comp.width as f64, comp.height as f64);
|
||||
let vs = views(s, cid);
|
||||
let mut c = vs.cam(v, w, h);
|
||||
if let Some(e) = v3_p(p, "eye") {
|
||||
c.eye = e;
|
||||
}
|
||||
if let Some(e) = v3_p(p, "poi") {
|
||||
c.poi = e;
|
||||
}
|
||||
if let Some(z) = f_p(p, "zoom") {
|
||||
c.zoom = z.max(1e-3);
|
||||
}
|
||||
vs.cams.insert(v, c);
|
||||
Ok(json!({"view": v.id()}))
|
||||
}
|
||||
|
||||
fn get_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let (w, h) = (comp.width as f64, comp.height as f64);
|
||||
let vs = s.state.views3d.get(&cid).cloned().unwrap_or_default();
|
||||
let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
|
||||
let cam = vs.override_camera(w, h).unwrap_or_else(|| camera::active_camera(&ctx));
|
||||
let f = cam.forward();
|
||||
let lights: Vec<Value> = comp
|
||||
.layers
|
||||
.iter()
|
||||
.filter_map(|l| match l.source {
|
||||
LayerSource::Light { kind } => Some(json!({"id": l.id.0, "name": l.name, "kind": kind.label()})),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let active = comp.active_camera(t).map(|l| json!({"id": l.id.0, "name": l.name, "twoNode": camera::is_two_node(l)}));
|
||||
Ok(json!({
|
||||
"view": vs.current.id(),
|
||||
"label": vs.current.label(),
|
||||
"views": View3D::ALL.iter().map(|v| v.id()).collect::<Vec<_>>(),
|
||||
"camera": {"eye": [cam.eye.x, cam.eye.y, cam.eye.z], "forward": [f.x, f.y, f.z], "zoom": cam.zoom, "ortho": cam.ortho},
|
||||
"activeCameraLayer": active,
|
||||
"lights": lights,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- camera tools
|
||||
|
||||
enum ToolOp {
|
||||
Orbit(f64, f64),
|
||||
Pan(f64, f64),
|
||||
Dolly(f64),
|
||||
}
|
||||
|
||||
fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let (w, h) = (comp.width as f64, comp.height as f64);
|
||||
let cur = s.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default();
|
||||
let apply = |r: &mut Rig, layer: bool| match op {
|
||||
ToolOp::Orbit(yaw, pitch) => r.orbit(yaw, pitch),
|
||||
ToolOp::Pan(dx, dy) => r.pan(dx, dy),
|
||||
ToolOp::Dolly(a) => r.dolly(a, layer),
|
||||
};
|
||||
if cur != View3D::ActiveCamera {
|
||||
let vs = views(s, cid);
|
||||
let vc = vs.cam(cur, w, h);
|
||||
let mut r = Rig::from_view(&vc);
|
||||
apply(&mut r, false);
|
||||
let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc };
|
||||
vs.cams.insert(cur, nc);
|
||||
return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom}));
|
||||
}
|
||||
let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
|
||||
let cam = match p.get("layer") {
|
||||
Some(v) => super::resolve_layer(&comp, v).filter(|id| comp.layer(*id).is_some_and(|l| l.is_camera())),
|
||||
None => comp.active_camera(t).map(|l| l.id),
|
||||
}
|
||||
.ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?;
|
||||
let merge = merge_p(p).map(str::to_string);
|
||||
let r = s.edit(label, merge.as_deref(), |proj, _| {
|
||||
let l = layer_mut(proj, cid, cam)?;
|
||||
let pos = Vec3::from(get_at(l, "transform/position", t).map(|v| v.as_vec3()).unwrap_or([w / 2.0, h / 2.0, -1000.0]));
|
||||
let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
|
||||
let two = camera::is_two_node(l);
|
||||
let o = get_at(l, "transform/orientation", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]);
|
||||
let rx = get_at(l, "transform/rotationX", t).map(|v| v.as_f64()).unwrap_or(0.0);
|
||||
let ry = get_at(l, "transform/rotationY", t).map(|v| v.as_f64()).unwrap_or(0.0);
|
||||
let poi = if two {
|
||||
Vec3::from(get_at(l, "transform/poi", t).map(|v| v.as_vec3()).unwrap_or([w / 2.0, h / 2.0, 0.0]))
|
||||
} else {
|
||||
let fwd = (Mat4::orientation(Vec3::from(o)) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx)).apply_vec(vec3(0.0, 0.0, 1.0));
|
||||
pos + fwd * zoom
|
||||
};
|
||||
let mut rig = Rig { eye: pos, poi, zoom, ortho: false };
|
||||
apply(&mut rig, true);
|
||||
set_at(l, "transform/position", t, KV::Vec3(camera::arr(rig.eye)));
|
||||
if two {
|
||||
set_at(l, "transform/poi", t, KV::Vec3(camera::arr(rig.poi)));
|
||||
} else {
|
||||
set_at(l, "transform/orientation", t, KV::Vec3(orientation_for(rig.poi - rig.eye)));
|
||||
set_at(l, "transform/rotationX", t, KV::Scalar(0.0));
|
||||
set_at(l, "transform/rotationY", t, KV::Scalar(0.0));
|
||||
}
|
||||
Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi)}))
|
||||
})?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
camera_tool(
|
||||
s,
|
||||
p,
|
||||
ToolOp::Orbit(f_p(p, "yaw").or_else(|| f_p(p, "dx")).unwrap_or(0.0), f_p(p, "pitch").or_else(|| f_p(p, "dy")).unwrap_or(0.0)),
|
||||
"camera.orbit",
|
||||
"Orbit Camera",
|
||||
)
|
||||
}
|
||||
fn pan(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
camera_tool(s, p, ToolOp::Pan(f_p(p, "dx").unwrap_or(0.0), f_p(p, "dy").unwrap_or(0.0)), "camera.pan", "Pan Camera")
|
||||
}
|
||||
fn dolly(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
camera_tool(s, p, ToolOp::Dolly(f_p(p, "amount").or_else(|| f_p(p, "dz")).unwrap_or(0.0)), "camera.dolly", "Dolly Camera")
|
||||
}
|
||||
|
||||
/// Layer ▸ Transform ▸ Auto-Orient: off | alongPath | towardsCamera (3D layers) |
|
||||
/// towardsPointOfInterest (cameras and spot/parallel lights).
|
||||
fn auto_orient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, ids) = super::layers_p(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("layer.autoOrient", "select a layer first"));
|
||||
}
|
||||
let raw = str_p(p, "mode").ok_or_else(|| bad("layer.autoOrient", "missing `mode` (off|alongPath|towardsCamera|towardsPointOfInterest)"))?;
|
||||
let k = raw.to_ascii_lowercase().replace([' ', '-', '_'], "");
|
||||
let mode = match k.as_str() {
|
||||
"off" => AutoOrient::Off,
|
||||
"alongpath" | "orientalongpath" => AutoOrient::AlongPath,
|
||||
"towardscamera" | "orienttowardscamera" => AutoOrient::TowardsCamera,
|
||||
"towardspointofinterest" | "towardspoi" | "orienttowardspointofinterest" => AutoOrient::TowardsPointOfInterest,
|
||||
_ => return Err(bad("layer.autoOrient", format!("unknown mode `{raw}`"))),
|
||||
};
|
||||
s.edit("Auto-Orient", None, |proj, _| {
|
||||
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
|
||||
let rig = l.is_camera() || l.is_light();
|
||||
let ok = match mode {
|
||||
AutoOrient::Off | AutoOrient::AlongPath => true,
|
||||
AutoOrient::TowardsCamera => !rig,
|
||||
AutoOrient::TowardsPointOfInterest => rig && l.transform().is_some_and(|t| t.get("poi").is_some()),
|
||||
};
|
||||
if !ok {
|
||||
return Err(bad("layer.autoOrient", format!("`{raw}` is not available for layer `{}`", l.name)));
|
||||
}
|
||||
l.auto_orient = mode;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"layer.autoOrient",
|
||||
"Auto-Orient...",
|
||||
["Layer", "Transform"],
|
||||
Some("Cmd+Alt+O"),
|
||||
"{mode: off|alongPath|towardsCamera|towardsPointOfInterest, layers?}",
|
||||
super::has_layers,
|
||||
auto_orient
|
||||
),
|
||||
cmd!(
|
||||
"layer.newLight",
|
||||
"Light...",
|
||||
["Layer", "New"],
|
||||
Some("Cmd+Alt+Shift+L"),
|
||||
"{kind?: Parallel|Spot|Point|Ambient (default Spot), name?, color?, intensity?, coneAngle?, coneFeather?, falloff?: None|Smooth|Inverse Square Clamped, radius?, falloffDistance?, castsShadows?, shadowDarkness?, shadowDiffusion?, position? [x,y,z], poi? [x,y,z]}",
|
||||
has_comp,
|
||||
new_light
|
||||
),
|
||||
cmd!(
|
||||
"layer.newCamera",
|
||||
"Camera...",
|
||||
["Layer", "New"],
|
||||
Some("Cmd+Alt+Shift+C"),
|
||||
"{name?, type?: oneNode|twoNode (default twoNode), preset?: 15mm|20mm|24mm|28mm|35mm|50mm|80mm|135mm|200mm, zoom?, focalLength? mm, angleOfView? deg, dof?, focusDistance?, aperture?, fStop?, blurLevel?, lockToZoom?, position? [x,y,z], poi? [x,y,z]}",
|
||||
has_comp,
|
||||
new_camera
|
||||
),
|
||||
cmd!(
|
||||
"layer.cameraSettings",
|
||||
"Camera Settings...",
|
||||
["Layer", "Camera"],
|
||||
None,
|
||||
"{layer?, name?, type?, preset?, zoom?, focalLength?, angleOfView?, dof?, focusDistance?, aperture?, fStop?, blurLevel?, position?, poi?}",
|
||||
has_comp,
|
||||
camera_settings
|
||||
),
|
||||
cmd!(
|
||||
"layer.lightSettings",
|
||||
"Light Settings...",
|
||||
[],
|
||||
None,
|
||||
"{layer?, name?, kind?, color?, intensity?, coneAngle?, coneFeather?, falloff?, radius?, falloffDistance?, castsShadows?, shadowDarkness?, shadowDiffusion?, position?, poi?}",
|
||||
has_comp,
|
||||
light_settings
|
||||
),
|
||||
cmd!(
|
||||
"view.set3DView",
|
||||
"Switch 3D View",
|
||||
[],
|
||||
None,
|
||||
"{view: activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3, comp?}",
|
||||
has_comp,
|
||||
set_3d_view
|
||||
),
|
||||
cmd!("view.3d.activeCamera", "Active Camera", ["View", "Switch 3D View"], Some("F12"), "{comp?}", has_comp, view_active),
|
||||
cmd!("view.3d.front", "Front", ["View", "Switch 3D View"], Some("F10"), "{comp?}", has_comp, view_front),
|
||||
cmd!("view.3d.left", "Left", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_left),
|
||||
cmd!("view.3d.top", "Top", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_top),
|
||||
cmd!("view.3d.back", "Back", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_back),
|
||||
cmd!("view.3d.right", "Right", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_right),
|
||||
cmd!("view.3d.bottom", "Bottom", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_bottom),
|
||||
cmd!("view.3d.custom1", "Custom View 1", ["View", "Switch 3D View"], Some("F11"), "{comp?}", has_comp, view_custom1),
|
||||
cmd!("view.3d.custom2", "Custom View 2", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_custom2),
|
||||
cmd!("view.3d.custom3", "Custom View 3", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_custom3),
|
||||
cmd!("view.3d.last", "Switch to Last 3D View", ["View"], None, "{comp?}", has_comp, last_view),
|
||||
cmd!("view.reset3DView", "Reset 3D View", ["View"], None, "{comp?}", has_comp, reset_view),
|
||||
cmd!("view.set3DViewCamera", "Set 3D View Camera", [], None, "{view, eye? [x,y,z], poi? [x,y,z], zoom?}", has_comp, set_view_camera),
|
||||
cmd!(
|
||||
"camera.orbit",
|
||||
"Orbit Camera",
|
||||
[],
|
||||
None,
|
||||
"{yaw|dx deg, pitch|dy deg, layer?, merge?} — current 3D view (camera layer in Active Camera)",
|
||||
has_comp,
|
||||
orbit
|
||||
),
|
||||
cmd!("camera.pan", "Pan Camera", [], None, "{dx, dy (comp px), layer?, merge?}", has_comp, pan),
|
||||
cmd!("camera.dolly", "Dolly Camera", [], None, "{amount (px, + = forward), layer?, merge?}", has_comp, dolly),
|
||||
query!("view.get3D", "3D View State", "{comp?} → current 3D view, view camera, active camera layer, lights", get_3d),
|
||||
]
|
||||
}
|
||||
+136
-2
@@ -1,6 +1,8 @@
|
||||
//! The demo project: an animated title sequence built entirely from procedural content (original
|
||||
//! work, MIT OR Apache-2.0): gradient background, orbiting shape rings with trim paths and a
|
||||
//! repeater burst, an animated title with a text animator and glow, a lower-third precomp.
|
||||
//! repeater burst, an animated title with a text animator and glow, a lower-third precomp; and a
|
||||
//! "3D Showcase" comp: a two-node camera move with depth of field over lit, shadow-casting 3D
|
||||
//! cards, intersecting planes and a gridded floor.
|
||||
|
||||
use effectcraft_color::BlendMode;
|
||||
use effectcraft_color::Label;
|
||||
@@ -10,9 +12,11 @@ use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project, P
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
pub const MAIN_COMP: &str = "EffectCraft Intro";
|
||||
pub const SHOWCASE_3D: &str = "3D Showcase";
|
||||
|
||||
/// Seconds → the nearest frame of the demo's 29.97 fps comps (AE keeps times frame-aligned).
|
||||
fn t(s: f64) -> Tick {
|
||||
Tick::from_seconds_f64(s)
|
||||
FrameRate::FPS_29_97.snap_nearest(Tick::from_seconds_f64(s))
|
||||
}
|
||||
|
||||
fn hex(h: &str) -> [f64; 4] {
|
||||
@@ -121,6 +125,134 @@ fn lower_third(p: &mut Project) -> Comp {
|
||||
c
|
||||
}
|
||||
|
||||
fn solid_sized(p: &mut Project, comp: &Comp, folder: ItemId, name: &str, color: [f32; 3], w: u32, h: u32) -> Layer {
|
||||
let sid = p.add_item(name, Label::Red, Some(folder), ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: 1.0 }));
|
||||
build::layer(p, comp, name, LayerSource::Solid { item: sid }, (w, h), None)
|
||||
}
|
||||
|
||||
/// A 3D card: a solid with a diagonal gradient and a thin border grid.
|
||||
fn card(p: &mut Project, comp: &Comp, folder: ItemId, name: &str, a: &str, b: &str, size: (u32, u32), pos: [f64; 3], rot_y: f64) -> Layer {
|
||||
let mut l = solid_sized(p, comp, folder, name, [1.0, 1.0, 1.0], size.0, size.1);
|
||||
let (w, h) = (size.0 as f64, size.1 as f64);
|
||||
effect(
|
||||
p,
|
||||
&mut l,
|
||||
"ec.generate.gradientramp",
|
||||
[w, h],
|
||||
&[("start", Value::Vec2([0.0, 0.0])), ("end", Value::Vec2([w, h])), ("startColor", Value::Color(hex(a))), ("endColor", Value::Color(hex(b)))],
|
||||
);
|
||||
effect(
|
||||
p,
|
||||
&mut l,
|
||||
"ec.generate.grid",
|
||||
[w, h],
|
||||
&[("width", Value::Scalar(w)), ("height", Value::Scalar(h)), ("border", Value::Scalar(10.0)), ("opacity", Value::Scalar(35.0))],
|
||||
);
|
||||
l.switches.three_d = true;
|
||||
set(&mut l, "transform/position", Value::Vec3(pos));
|
||||
set(&mut l, "transform/rotationY", Value::Scalar(rot_y));
|
||||
set(&mut l, "materialOptions/castsShadows", Value::Enum(1));
|
||||
set(&mut l, "materialOptions/specularIntensity", Value::Scalar(35.0));
|
||||
set(&mut l, "materialOptions/specularShininess", Value::Scalar(40.0));
|
||||
l
|
||||
}
|
||||
|
||||
/// The "3D Showcase" comp: camera move, key + fill lights, shadows, DOF, intersecting planes.
|
||||
fn showcase_3d(p: &mut Project, solids: ItemId) -> Comp {
|
||||
let mut c = Comp::new(1920, 1080, FrameRate::FPS_29_97, t(10.0));
|
||||
c.background = [0.02, 0.02, 0.035];
|
||||
// Floor: a gridded plane laid flat (X rotation 90°) below the cards.
|
||||
let mut floor = solid_sized(p, &c, solids, "Floor", [0.16, 0.17, 0.22], 1000, 1000);
|
||||
effect(
|
||||
p,
|
||||
&mut floor,
|
||||
"ec.generate.grid",
|
||||
[1000.0, 1000.0],
|
||||
&[
|
||||
("width", Value::Scalar(100.0)),
|
||||
("height", Value::Scalar(100.0)),
|
||||
("border", Value::Scalar(3.0)),
|
||||
("color", Value::Color(hex("#6F7BB8"))),
|
||||
("opacity", Value::Scalar(45.0)),
|
||||
],
|
||||
);
|
||||
floor.switches.three_d = true;
|
||||
set(&mut floor, "transform/position", Value::Vec3([960.0, 800.0, 500.0]));
|
||||
set(&mut floor, "transform/scale", Value::Vec3([400.0, 400.0, 100.0]));
|
||||
set(&mut floor, "transform/rotationX", Value::Scalar(90.0));
|
||||
set(&mut floor, "materialOptions/specularIntensity", Value::Scalar(10.0));
|
||||
|
||||
// Cards at different depths and angles; the centre pair intersects.
|
||||
let left = card(p, &c, solids, "Card Blue", "#2E7BF0", "#7A4DFF", (520, 340), [520.0, 560.0, 120.0], 28.0);
|
||||
let right = card(p, &c, solids, "Card Coral", "#FF6A5C", "#FFB347", (520, 340), [1420.0, 560.0, 260.0], -32.0);
|
||||
let mut x1 = card(p, &c, solids, "Cross A", "#1FD1A5", "#2E7BF0", (460, 460), [960.0, 470.0, 520.0], 40.0);
|
||||
set(&mut x1, "materialOptions/lightTransmission", Value::Scalar(30.0));
|
||||
let x2 = card(p, &c, solids, "Cross B", "#F0E14A", "#FF6A5C", (460, 460), [960.0, 470.0, 520.0], -40.0);
|
||||
// Hero title in 3D space, gently turning.
|
||||
let mut title = text_layer(
|
||||
p,
|
||||
&c,
|
||||
"3D Title",
|
||||
TextDoc { text: "CLASSIC 3D".into(), size: 150.0, style: "Bold".into(), tracking: 60.0, justify: Justify::Center, ..Default::default() },
|
||||
[960.0, 560.0],
|
||||
);
|
||||
title.switches.three_d = true;
|
||||
set(&mut title, "transform/position", Value::Vec3([960.0, 600.0, -160.0]));
|
||||
anim(&mut title, "transform/rotationY", keys(&[(0.0, Value::Scalar(-18.0)), (10.0, Value::Scalar(18.0))]));
|
||||
set(&mut title, "materialOptions/castsShadows", Value::Enum(1));
|
||||
|
||||
// Camera: two-node, 35 mm, sweeping around the set with depth of field on the title.
|
||||
let mut cam = build::layer(p, &c, "Camera 1", LayerSource::Camera, (1920, 1080), None);
|
||||
let zoom = 1920.0 * 35.0 / 36.0;
|
||||
set(&mut cam, "cameraOptions/zoom", Value::Scalar(zoom));
|
||||
set(&mut cam, "cameraOptions/dof", Value::Bool(true));
|
||||
set(&mut cam, "cameraOptions/aperture", Value::Scalar(40.0));
|
||||
set(&mut cam, "cameraOptions/blurLevel", Value::Scalar(100.0));
|
||||
set(&mut cam, "transform/poi", Value::Vec3([960.0, 560.0, 150.0]));
|
||||
anim(
|
||||
&mut cam,
|
||||
"transform/position",
|
||||
keys(&[(0.0, Value::Vec3([-200.0, 160.0, -1500.0])), (5.0, Value::Vec3([1100.0, 80.0, -1850.0])), (10.0, Value::Vec3([2150.0, 220.0, -1300.0]))]),
|
||||
);
|
||||
anim(&mut cam, "cameraOptions/focusDistance", keys(&[(0.0, Value::Scalar(1700.0)), (5.0, Value::Scalar(1900.0)), (10.0, Value::Scalar(1650.0))]));
|
||||
|
||||
// Key light: warm spot casting soft shadows. Fill: cool ambient.
|
||||
let mut key = build::layer(p, &c, "Key Light", LayerSource::Light { kind: effectcraft_project::LightKind::Spot }, (1920, 1080), None);
|
||||
set(&mut key, "transform/position", Value::Vec3([500.0, -500.0, -700.0]));
|
||||
set(&mut key, "transform/poi", Value::Vec3([960.0, 600.0, 300.0]));
|
||||
set(&mut key, "lightOptions/intensity", Value::Scalar(150.0));
|
||||
set(&mut key, "lightOptions/color", Value::Color(hex("#FFE6C7")));
|
||||
set(&mut key, "lightOptions/coneAngle", Value::Scalar(110.0));
|
||||
set(&mut key, "lightOptions/coneFeather", Value::Scalar(60.0));
|
||||
set(&mut key, "lightOptions/castsShadows", Value::Bool(true));
|
||||
set(&mut key, "lightOptions/shadowDarkness", Value::Scalar(70.0));
|
||||
set(&mut key, "lightOptions/shadowDiffusion", Value::Scalar(12.0));
|
||||
let mut fill = build::layer(p, &c, "Fill Light", LayerSource::Light { kind: effectcraft_project::LightKind::Ambient }, (1920, 1080), None);
|
||||
set(&mut fill, "lightOptions/intensity", Value::Scalar(35.0));
|
||||
set(&mut fill, "lightOptions/color", Value::Color(hex("#B9C8FF")));
|
||||
|
||||
// 2D caption on top (2D layers break 3D groups, so it always draws over the 3D scene).
|
||||
let mut caption = text_layer(
|
||||
p,
|
||||
&c,
|
||||
"Caption",
|
||||
TextDoc {
|
||||
text: "CAMERAS · LIGHTS · SHADOWS · DEPTH OF FIELD".into(),
|
||||
size: 30.0,
|
||||
style: "Medium".into(),
|
||||
tracking: 220.0,
|
||||
fill: [0.78, 0.83, 1.0, 1.0],
|
||||
justify: Justify::Center,
|
||||
..Default::default()
|
||||
},
|
||||
[960.0, 1000.0],
|
||||
);
|
||||
anim(&mut caption, "transform/opacity", keys(&[(0.3, Value::Scalar(0.0)), (1.2, Value::Scalar(100.0))]));
|
||||
|
||||
c.layers = vec![caption, cam, key, fill, title, left, right, x1, x2, floor];
|
||||
c
|
||||
}
|
||||
|
||||
/// Build the demo project.
|
||||
pub fn demo_project() -> Project {
|
||||
let mut p = Project::default();
|
||||
@@ -318,6 +450,8 @@ pub fn demo_project() -> Project {
|
||||
}
|
||||
comp.work_area = (Tick::ZERO, t(10.0));
|
||||
p.add_item(MAIN_COMP, Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
let show = showcase_3d(&mut p, solids);
|
||||
p.add_item(SHOWCASE_3D, Label::Sandstone, None, ItemKind::Comp(show.into()));
|
||||
p.fix_next_id();
|
||||
p
|
||||
}
|
||||
+98
-12
@@ -12,12 +12,13 @@ pub mod commands;
|
||||
pub mod demo;
|
||||
pub mod links;
|
||||
pub mod menus;
|
||||
pub mod render_queue;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_project::{Comp, ItemId, Layer, LayerId, Project, Uid};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{ExprHost, FootageSource, NoFootage, RenderOpts, Renderer};
|
||||
use effectcraft_render::{ExprHost, FootageSource, LayerCache, NoFootage, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -30,6 +31,7 @@ pub use effectcraft_keyframe as keyframe;
|
||||
pub use effectcraft_project as project;
|
||||
pub use effectcraft_render as render;
|
||||
pub use effectcraft_time as time;
|
||||
pub use render_queue::{ExportJob, ExportResult, Exporter, JobState};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
@@ -92,6 +94,24 @@ pub struct KeyRef {
|
||||
pub time: Tick,
|
||||
}
|
||||
|
||||
/// Keyframes of one property on the keyframe clipboard.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct KeyClip {
|
||||
pub layer: LayerId,
|
||||
/// Match-id path relative to the layer (`transform/position`), portable between layers.
|
||||
pub path: String,
|
||||
/// Keys with times relative to the earliest copied key (layer time).
|
||||
pub keys: Vec<effectcraft_keyframe::Keyframe>,
|
||||
}
|
||||
|
||||
/// A selected mask vertex: layer, mask group uid, vertex index.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct VertexRef {
|
||||
pub layer: LayerId,
|
||||
pub mask: Uid,
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
/// Editing state that commands depend on (headless-relevant, serde for agents).
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct EditorState {
|
||||
@@ -108,6 +128,15 @@ pub struct EditorState {
|
||||
/// Layer clipboard (serialized layers) and keyframe clipboard.
|
||||
#[serde(skip)]
|
||||
pub clipboard: Vec<Layer>,
|
||||
/// Copied keyframes (times relative to the earliest copied key).
|
||||
#[serde(skip)]
|
||||
pub key_clipboard: Vec<KeyClip>,
|
||||
/// The last copy was keyframes (Paste pastes keys at the CTI).
|
||||
#[serde(skip)]
|
||||
pub clip_is_keys: bool,
|
||||
/// Selected mask vertices (viewer Selection tool / pen).
|
||||
#[serde(default)]
|
||||
pub selected_vertices: Vec<VertexRef>,
|
||||
pub snapping: bool,
|
||||
/// Last applied effect id (Effect ▸ last effect).
|
||||
pub last_effect: Option<String>,
|
||||
@@ -115,22 +144,15 @@ pub struct EditorState {
|
||||
/// of Interest).
|
||||
#[serde(default)]
|
||||
pub region_of_interest: Option<[f64; 4]>,
|
||||
/// Keyframe clipboard (Edit ▸ Copy with keys selected; Paste / Paste Reversed Keyframes).
|
||||
#[serde(skip)]
|
||||
pub key_clipboard: Vec<KeyClip>,
|
||||
/// Property-link clipboard (Edit ▸ Copy with Property Links / Copy Expression Only).
|
||||
#[serde(skip)]
|
||||
pub link_clipboard: Option<LinkClip>,
|
||||
/// File ▸ Interpret Footage ▸ Remember Interpretation.
|
||||
#[serde(skip)]
|
||||
pub interpretation: Option<effectcraft_project::Footage>,
|
||||
}
|
||||
|
||||
/// Copied keyframes of one property, addressed by its match path (`transform/position`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct KeyClip {
|
||||
pub path: String,
|
||||
pub keys: Vec<effectcraft_keyframe::Keyframe>,
|
||||
/// Viewer 3D view per comp (Active Camera / Front / … / Custom View 3 and edited view cameras).
|
||||
#[serde(default)]
|
||||
pub views3d: std::collections::BTreeMap<ItemId, effectcraft_render::three_d::Views3D>,
|
||||
}
|
||||
|
||||
/// What Copy with Property Links / Copy Expression Only put on the clipboard.
|
||||
@@ -174,10 +196,18 @@ pub struct Session {
|
||||
pub services: Arc<dyn Services>,
|
||||
pub footage: Arc<dyn FootageSource>,
|
||||
pub expr: Option<Arc<dyn ExprHost>>,
|
||||
/// Expression syntax checker (set by the host that links the expression engine).
|
||||
pub expr_check: Option<fn(&str) -> std::result::Result<(), String>>,
|
||||
pub importer: Option<Arc<dyn Importer>>,
|
||||
/// Render Queue encoder (the export layer); `None` = export unavailable.
|
||||
pub exporter: Option<Arc<dyn Exporter>>,
|
||||
/// The running (or finished, not yet polled) render.
|
||||
pub render_job: Option<render_queue::RenderJob>,
|
||||
pub events: Vec<Event>,
|
||||
/// Commands executed: (id, params).
|
||||
pub journal: Vec<(String, Value)>,
|
||||
/// Processed-layer pixels reused across frames and edits (content-keyed, never stale).
|
||||
pub layer_cache: Arc<LayerCache>,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
@@ -192,9 +222,13 @@ impl Default for Session {
|
||||
services: Arc::new(FsServices),
|
||||
footage: Arc::new(NoFootage),
|
||||
expr: None,
|
||||
expr_check: None,
|
||||
importer: None,
|
||||
exporter: None,
|
||||
render_job: None,
|
||||
events: vec![],
|
||||
journal: vec![],
|
||||
layer_cache: Arc::new(LayerCache::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,6 +258,14 @@ impl Session {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// [`Session::execute`] for agents and scripts (MCP, CLI, control channel): unknown top-level
|
||||
/// parameters are rejected with the accepted keys instead of being silently ignored.
|
||||
pub fn execute_checked(&mut self, id: &str, params: Value) -> Result<Value> {
|
||||
let spec = commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
commands::check_params(spec, ¶ms)?;
|
||||
self.execute(id, params)
|
||||
}
|
||||
|
||||
pub fn is_enabled(&self, id: &str) -> bool {
|
||||
commands::find(id).is_some_and(|c| (c.enabled)(self).is_ok())
|
||||
}
|
||||
@@ -286,6 +328,7 @@ impl Session {
|
||||
self.state.selected_layers.retain(|l| ids.contains(l));
|
||||
self.state.selected_props.retain(|(l, _)| ids.contains(l));
|
||||
self.state.selected_keys.retain(|k| ids.contains(&k.layer));
|
||||
self.state.selected_vertices.retain(|v| ids.contains(&v.layer));
|
||||
}
|
||||
self.state.project_selection.retain(|i| p.item(*i).is_some());
|
||||
}
|
||||
@@ -310,7 +353,7 @@ impl Session {
|
||||
if let Some(c) = self.state.active_comp {
|
||||
let comp = self.project.comp(c);
|
||||
let t = match comp {
|
||||
Some(comp) => comp.frame_rate.snap(t.clamp(Tick::ZERO, comp.duration - comp.frame_duration())),
|
||||
Some(comp) => comp.frame_rate.snap_nearest(t.clamp(Tick::ZERO, comp.duration - comp.frame_duration())),
|
||||
None => t,
|
||||
};
|
||||
self.state.times.insert(c, t);
|
||||
@@ -330,6 +373,7 @@ impl Session {
|
||||
self.state.selected_layers.clear();
|
||||
self.state.selected_props.clear();
|
||||
self.state.selected_keys.clear();
|
||||
self.state.selected_vertices.clear();
|
||||
}
|
||||
self.events.push(Event::OpenComp(id));
|
||||
}
|
||||
@@ -342,15 +386,51 @@ impl Session {
|
||||
std::mem::take(&mut self.events)
|
||||
}
|
||||
|
||||
/// The 3D view camera of a comp's viewer (None = the active camera).
|
||||
pub fn view_camera(&self, comp: ItemId) -> Option<effectcraft_render::three_d::CameraState> {
|
||||
let c = self.project.comp(comp)?;
|
||||
if !c.has_3d() {
|
||||
return None;
|
||||
}
|
||||
self.state.views3d.get(&comp)?.override_camera(c.width as f64, c.height as f64)
|
||||
}
|
||||
|
||||
/// Render a comp frame with the session's footage + expression hosts.
|
||||
pub fn render(&self, comp: ItemId, t: Tick, opts: RenderOpts) -> Image {
|
||||
let mut r = Renderer::new(&self.project, self.footage.as_ref(), opts);
|
||||
r.expr = self.expr.as_deref();
|
||||
r.cache = Some(&self.layer_cache);
|
||||
r.comp_frame(comp, t)
|
||||
}
|
||||
|
||||
/// Resolve a comp reference (item id number or name; `None`/null = the active comp).
|
||||
pub fn resolve_comp(&self, comp: Option<&Value>) -> Result<ItemId> {
|
||||
let p = match comp {
|
||||
Some(v) if !v.is_null() => serde_json::json!({ "comp": v }),
|
||||
_ => serde_json::json!({}),
|
||||
};
|
||||
commands::comp_id(self, &p)
|
||||
}
|
||||
|
||||
/// Render a comp frame (comp time `t`) as opaque 8-bit RGBA over the comp background, scaled
|
||||
/// so the longest side is at most `max_side` pixels (0 = full size). Returns (width, height, rgba).
|
||||
pub fn render_rgba8(&self, comp: ItemId, t: Tick, max_side: u32) -> Result<(u32, u32, Vec<u8>)> {
|
||||
let c = self.project.comp(comp).ok_or(EngineError::NoComp)?;
|
||||
let long = c.width.max(c.height).max(1) as f64;
|
||||
let scale = if max_side == 0 { 1.0 } else { (max_side as f64 / long).min(1.0) };
|
||||
let img = self.render(comp, t, RenderOpts { scale, ..Default::default() });
|
||||
Ok((img.width, img.height, img.to_rgba8_over(c.background)))
|
||||
}
|
||||
|
||||
/// Replace the whole project (open/new), resetting history and state.
|
||||
pub fn replace_project(&mut self, mut p: Project, path: Option<String>) {
|
||||
if self.stop_render()
|
||||
&& let Some(mut job) = self.render_job.take()
|
||||
{
|
||||
// Let the worker notice the cancel; its updates refer to the old project.
|
||||
job.wait();
|
||||
}
|
||||
self.render_job = None;
|
||||
p.fix_next_id();
|
||||
self.project = Arc::new(p);
|
||||
self.history = History::default();
|
||||
@@ -365,10 +445,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rq_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_3d;
|
||||
#[cfg(test)]
|
||||
mod tests_menu_cmds;
|
||||
#[cfg(test)]
|
||||
mod tests_timeline;
|
||||
|
||||
/// Font families available to text layers (bundled + scanned system fonts).
|
||||
pub fn text_families() -> Vec<String> {
|
||||
|
||||
+22
-22
@@ -308,7 +308,7 @@ File
|
||||
Placeholder... | file.importPlaceholder
|
||||
Solid... | file.importSolid
|
||||
Export
|
||||
Add to Render Queue | render.addToQueue
|
||||
Add to Render Queue | renderQueue.add
|
||||
---
|
||||
Find | app.find
|
||||
---
|
||||
@@ -443,7 +443,7 @@ Composition
|
||||
Crop Comp to Region of Interest | comp.cropToRegionOfInterest
|
||||
Crop Comp to Selected Layer(s) Bounds | comp.cropToLayerBounds
|
||||
---
|
||||
Add to Render Queue | render.addToQueue
|
||||
Add to Render Queue | renderQueue.add
|
||||
Add Output Module | render.addOutputModule
|
||||
---
|
||||
Preview
|
||||
@@ -515,7 +515,7 @@ Layer
|
||||
Hide Locked Masks | layer.mask.hideLocked
|
||||
Mask and Shape Path
|
||||
RotoBezier | path.rotoBezier
|
||||
Closed | path.closed
|
||||
Closed | mask.setClosed
|
||||
Convert To Bezier Path | path.convertToBezier
|
||||
Group Shapes | path.groupShapes
|
||||
Ungroup Shapes | path.ungroupShapes
|
||||
@@ -563,8 +563,8 @@ Layer
|
||||
---
|
||||
Auto-Orient... | layer.autoOrient
|
||||
Time
|
||||
Enable Time Remapping | layer.timeRemap
|
||||
Time-Reverse Layer | layer.timeStretch {"op":"reverse"} | Cmd+Alt+R
|
||||
Enable Time Remapping | layer.enableTimeRemap
|
||||
Time-Reverse Layer | layer.timeReverse
|
||||
Time Stretch... | layer.timeStretch
|
||||
Freeze Frame | layer.freezeFrame
|
||||
Freeze On Last Frame | layer.freezeOnLastFrame
|
||||
@@ -687,8 +687,8 @@ Layer
|
||||
Link Focus Distance to Point of Interest | camera.linkFocusToPoi
|
||||
Link Focus Distance to Layer | camera.linkFocusToLayer
|
||||
Set Focus Distance to Layer | camera.setFocusToLayer
|
||||
Camera Settings... | camera.settings
|
||||
Reset 3D View | view.reset3dView
|
||||
Camera Settings... | layer.cameraSettings
|
||||
Reset 3D View | view.reset3DView
|
||||
Light
|
||||
Create Lights from 3D Model | light.fromModel
|
||||
Control Light with Camera | light.controlWithCamera
|
||||
@@ -823,8 +823,8 @@ View
|
||||
View Options... | view.options
|
||||
Show Layer Controls | view.layerControls
|
||||
---
|
||||
Camera Settings... | camera.settings
|
||||
Reset 3D View | view.reset3dView
|
||||
Camera Settings... | layer.cameraSettings
|
||||
Reset 3D View | view.reset3DView
|
||||
Create Camera from 3D View | camera.fromView
|
||||
Switch View Layout
|
||||
1 View | view.layout {"views":1}
|
||||
@@ -833,22 +833,22 @@ View
|
||||
---
|
||||
Share View Options | view.shareViewOptions
|
||||
Switch 3D View
|
||||
Active Camera | view.3d {"view":"activeCamera"} | F12
|
||||
Default | view.3d {"view":"default"}
|
||||
Active Camera | view.3d.activeCamera
|
||||
Default | view.3d.default
|
||||
---
|
||||
Front | view.3d {"view":"front"} | F10
|
||||
Left | view.3d {"view":"left"}
|
||||
Top | view.3d {"view":"top"}
|
||||
Back | view.3d {"view":"back"}
|
||||
Right | view.3d {"view":"right"}
|
||||
Bottom | view.3d {"view":"bottom"}
|
||||
Front | view.3d.front
|
||||
Left | view.3d.left
|
||||
Top | view.3d.top
|
||||
Back | view.3d.back
|
||||
Right | view.3d.right
|
||||
Bottom | view.3d.bottom
|
||||
---
|
||||
Custom View 1 | view.3d {"view":"custom1"} | F11
|
||||
Custom View 2 | view.3d {"view":"custom2"}
|
||||
Custom View 3 | view.3d {"view":"custom3"}
|
||||
Custom View 1 | view.3d.custom1
|
||||
Custom View 2 | view.3d.custom2
|
||||
Custom View 3 | view.3d.custom3
|
||||
---
|
||||
Reset 3D View | view.reset3dView
|
||||
Switch to Last 3D View | view.last3dView
|
||||
Reset 3D View | view.reset3DView
|
||||
Switch to Last 3D View | view.3d.last | Escape
|
||||
Look at Selected Layers | view.lookAtSelected
|
||||
Look at All Layers | view.lookAtAll
|
||||
---
|
||||
|
||||
@@ -140,6 +140,15 @@ fn checked_reflects_layer_state() {
|
||||
assert_eq!(checked(&s, "file.save", &serde_json::json!({})), None);
|
||||
}
|
||||
|
||||
/// `cargo test -p effectcraft-engine dump_specs -- --ignored --nocapture`: every command as TSV.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn dump_specs() {
|
||||
for c in crate::command_specs() {
|
||||
eprintln!("SPEC\t{}\t{}\t{}\t{}\t{}", c.id, c.label, c.menu.join(" > "), c.shortcut.unwrap_or(""), c.params);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rejects_bad_trees() {
|
||||
assert!(parse("File\n Empty\n", true).is_err());
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Render Queue runtime: the [`Exporter`] hook (implemented by `effectcraft-export`, wired by
|
||||
//! `effectcraft-host`), output path resolution, and the render job that works through the queued
|
||||
//! items, in the background (desktop UI) or blocking (CLI, agents, tests).
|
||||
//!
|
||||
//! The queue itself (items, Render Settings, Output Modules, status) lives in the project
|
||||
//! (`project.render_queue`) so it is saved with it. A running job owns a snapshot of the project;
|
||||
//! it reports progress through [`JobShared`], and [`Session::poll_render`] copies item status /
|
||||
//! start time / render time back into the project.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_project::render_queue::{OutputFormat, RenderQueueItem, RenderStatus, TemplateVars, expand_template};
|
||||
use effectcraft_project::{ItemId, Project};
|
||||
use effectcraft_render::{ExprHost, FootageSource};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{Event, Session};
|
||||
|
||||
/// One export handed to the [`Exporter`].
|
||||
pub struct ExportJob<'a> {
|
||||
pub project: &'a Project,
|
||||
pub footage: &'a dyn FootageSource,
|
||||
pub expr: Option<&'a dyn ExprHost>,
|
||||
pub item: &'a RenderQueueItem,
|
||||
/// Resolved output path (templates expanded except the `#` frame-number run).
|
||||
pub path: &'a str,
|
||||
}
|
||||
|
||||
/// What an export wrote.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct ExportResult {
|
||||
pub path: String,
|
||||
pub frames: u64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub bytes: u64,
|
||||
pub seconds: f64,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
/// Encodes render queue items (implemented by the export layer).
|
||||
pub trait Exporter: Send + Sync {
|
||||
/// Formats this build can write.
|
||||
fn formats(&self) -> Vec<OutputFormat>;
|
||||
/// Render and write one item (blocking). `progress(done, total)` returns `false` to cancel;
|
||||
/// a cancelled export returns `Err("cancelled")`.
|
||||
fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String>;
|
||||
}
|
||||
|
||||
/// The error string an [`Exporter`] returns when cancelled.
|
||||
pub const CANCELLED: &str = "cancelled";
|
||||
|
||||
/// Live progress of a render job (serde for agents / the control channel).
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
pub struct JobState {
|
||||
/// Item being rendered.
|
||||
pub current: Option<u64>,
|
||||
/// Frames done / total of the current item.
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
/// Seconds since the job started / since the current item started.
|
||||
pub elapsed: f64,
|
||||
pub item_elapsed: f64,
|
||||
/// Estimated seconds left for the current item.
|
||||
pub remaining: Option<f64>,
|
||||
/// Items rendered so far / items in this job.
|
||||
pub items_done: usize,
|
||||
pub items_total: usize,
|
||||
pub finished: bool,
|
||||
}
|
||||
|
||||
/// Per-item status changes from the job thread, applied to the project by `poll_render`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ItemUpdate {
|
||||
Started { id: u64, unix: u64 },
|
||||
Finished { id: u64, status: RenderStatus, seconds: f64, output: Option<String> },
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct JobShared {
|
||||
pub cancel: AtomicBool,
|
||||
pub state: Mutex<JobState>,
|
||||
pub updates: Mutex<Vec<ItemUpdate>>,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
impl JobShared {
|
||||
pub fn snapshot(&self) -> JobState {
|
||||
lock(&self.state).clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A running (or finished, not yet polled) render job.
|
||||
pub struct RenderJob {
|
||||
pub shared: Arc<JobShared>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl RenderJob {
|
||||
pub fn is_finished(&self) -> bool {
|
||||
lock(&self.shared.state).finished
|
||||
}
|
||||
pub fn cancel(&self) {
|
||||
self.shared.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
/// Block until the worker thread ends.
|
||||
pub fn wait(&mut self) {
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the worker needs, detached from the session.
|
||||
struct Work {
|
||||
project: Arc<Project>,
|
||||
footage: Arc<dyn FootageSource>,
|
||||
expr: Option<Arc<dyn ExprHost>>,
|
||||
exporter: Arc<dyn Exporter>,
|
||||
items: Vec<(RenderQueueItem, String)>,
|
||||
}
|
||||
|
||||
fn unix_now() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn run_work(w: Work, shared: &JobShared) {
|
||||
let t0 = std::time::Instant::now();
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.items_total = w.items.len();
|
||||
}
|
||||
for (k, (item, path)) in w.items.iter().enumerate() {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None });
|
||||
continue;
|
||||
}
|
||||
let t1 = std::time::Instant::now();
|
||||
lock(&shared.updates).push(ItemUpdate::Started { id: item.id, unix: unix_now() });
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.current = Some(item.id);
|
||||
s.done = 0;
|
||||
s.total = 0;
|
||||
s.items_done = k;
|
||||
s.remaining = None;
|
||||
}
|
||||
let job = ExportJob { project: &w.project, footage: w.footage.as_ref(), expr: w.expr.as_deref(), item, path };
|
||||
let r = w.exporter.export(&job, &mut |done, total| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = done;
|
||||
s.total = total;
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.item_elapsed = t1.elapsed().as_secs_f64();
|
||||
s.remaining = (done > 0).then(|| s.item_elapsed / done as f64 * total.saturating_sub(done) as f64);
|
||||
!shared.cancel.load(Ordering::Relaxed)
|
||||
});
|
||||
let seconds = t1.elapsed().as_secs_f64();
|
||||
let up = match r {
|
||||
Ok(res) => ItemUpdate::Finished { id: item.id, status: RenderStatus::Done, seconds, output: Some(res.path) },
|
||||
Err(e) if e == CANCELLED => ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds, output: None },
|
||||
Err(e) => {
|
||||
log::warn!("render queue: item {} failed: {e}", item.id);
|
||||
ItemUpdate::Finished { id: item.id, status: RenderStatus::Failed(e), seconds, output: None }
|
||||
}
|
||||
};
|
||||
lock(&shared.updates).push(up);
|
||||
}
|
||||
let mut s = lock(&shared.state);
|
||||
s.items_done = w.items.len();
|
||||
s.current = None;
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.finished = true;
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The project's name for `[projectName]` (file stem, or "Untitled Project").
|
||||
pub fn project_name(&self) -> String {
|
||||
self.path
|
||||
.as_deref()
|
||||
.and_then(|p| std::path::Path::new(p).file_stem())
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "Untitled Project".into())
|
||||
}
|
||||
|
||||
/// The output path of a queue item: template tokens expanded, relative paths resolved against
|
||||
/// the project's folder (or the working directory). `None` when the comp is gone or the
|
||||
/// output is empty ("Needs Output").
|
||||
pub fn resolve_output(&self, item: &RenderQueueItem) -> Option<String> {
|
||||
let comp = self.project.comp(item.comp)?;
|
||||
let name = self.project.item(item.comp).map(|i| i.name.clone()).unwrap_or_default();
|
||||
let tpl = item.output.output.trim();
|
||||
if tpl.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = item.settings.output_size(comp);
|
||||
let (w, h) = item.output.format.coded_size(w, h);
|
||||
let rate = item.settings.rate(comp);
|
||||
let n = item.settings.frame_count(comp) as i64;
|
||||
let f0 = item.settings.first_frame(comp);
|
||||
let pname = self.project_name();
|
||||
let vars =
|
||||
TemplateVars { comp_name: &name, project_name: &pname, width: w, height: h, frame_rate: rate.as_f64(), start_frame: f0, end_frame: f0 + n - 1 };
|
||||
let p = expand_template(tpl, item.output.format, &vars);
|
||||
let path = std::path::Path::new(&p);
|
||||
if path.is_absolute() {
|
||||
return Some(p);
|
||||
}
|
||||
let base = self.path.as_deref().and_then(|s| std::path::Path::new(s).parent().map(|d| d.to_path_buf())).filter(|d| !d.as_os_str().is_empty());
|
||||
let base = base.or_else(|| std::env::current_dir().ok())?;
|
||||
Some(base.join(path).to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Whether a render job is running.
|
||||
pub fn is_rendering(&self) -> bool {
|
||||
self.render_job.as_ref().is_some_and(|j| !j.is_finished())
|
||||
}
|
||||
|
||||
/// Live job progress.
|
||||
pub fn render_progress(&self) -> Option<JobState> {
|
||||
self.render_job.as_ref().map(|j| j.shared.snapshot())
|
||||
}
|
||||
|
||||
/// Start rendering every queued item. `wait`: block until done (otherwise a background thread
|
||||
/// renders; call [`Session::poll_render`] regularly). Returns the ids being rendered.
|
||||
pub fn start_render(&mut self, wait: bool) -> Result<Vec<u64>, String> {
|
||||
if self.is_rendering() {
|
||||
return Err("a render is already in progress".into());
|
||||
}
|
||||
self.poll_render();
|
||||
let exporter = self.exporter.clone().ok_or("export is not available in this build")?;
|
||||
let formats = exporter.formats();
|
||||
let mut items = Vec::new();
|
||||
let mut needs_output = Vec::new();
|
||||
for it in self.project.render_queue.iter().filter(|i| i.is_queued()) {
|
||||
match self.resolve_output(it) {
|
||||
Some(p) if formats.contains(&it.output.format) => items.push((it.clone(), p)),
|
||||
Some(_) => needs_output.push((it.id, RenderStatus::Failed(format!("{} export is not available", it.output.format.label())))),
|
||||
None if self.project.comp(it.comp).is_none() => needs_output.push((it.id, RenderStatus::Failed("composition missing".into()))),
|
||||
None => needs_output.push((it.id, RenderStatus::NeedsOutput)),
|
||||
}
|
||||
}
|
||||
if !needs_output.is_empty() {
|
||||
let p = Arc::make_mut(&mut self.project);
|
||||
for (id, st) in needs_output {
|
||||
if let Some(i) = p.render_queue.iter_mut().find(|i| i.id == id) {
|
||||
i.status = st;
|
||||
}
|
||||
}
|
||||
self.bump();
|
||||
}
|
||||
if items.is_empty() {
|
||||
return Err("nothing is queued: add a composition (Composition ▸ Add to Render Queue) and tick Render".into());
|
||||
}
|
||||
let ids: Vec<u64> = items.iter().map(|(i, _)| i.id).collect();
|
||||
let work = Work { project: self.project.clone(), footage: self.footage.clone(), expr: self.expr.clone(), exporter, items };
|
||||
let shared = Arc::new(JobShared::default());
|
||||
if wait {
|
||||
run_work(work, &shared);
|
||||
self.render_job = Some(RenderJob { shared, thread: None });
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
let thread = std::thread::Builder::new().name("render-queue".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?;
|
||||
self.render_job = Some(RenderJob { shared, thread: Some(thread) });
|
||||
}
|
||||
self.poll_render();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Stop the running render (the current item becomes "User Stopped").
|
||||
pub fn stop_render(&mut self) -> bool {
|
||||
match &self.render_job {
|
||||
Some(j) if !j.is_finished() => {
|
||||
j.cancel();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply job updates to the queue items; drop the job once it finished. Returns whether
|
||||
/// anything changed. Frontends call this every frame while rendering.
|
||||
pub fn poll_render(&mut self) -> bool {
|
||||
let Some(job) = &self.render_job else { return false };
|
||||
let updates = std::mem::take(&mut *lock(&job.shared.updates));
|
||||
let finished = job.is_finished();
|
||||
let changed = !updates.is_empty();
|
||||
if changed {
|
||||
let p = Arc::make_mut(&mut self.project);
|
||||
for u in &updates {
|
||||
match u {
|
||||
ItemUpdate::Started { id, unix } => {
|
||||
if let Some(i) = p.render_queue.iter_mut().find(|i| i.id == *id) {
|
||||
i.status = RenderStatus::Rendering;
|
||||
i.started = Some(*unix);
|
||||
i.render_time = None;
|
||||
}
|
||||
}
|
||||
ItemUpdate::Finished { id, status, seconds, output } => {
|
||||
if let Some(i) = p.render_queue.iter_mut().find(|i| i.id == *id) {
|
||||
i.status = status.clone();
|
||||
i.render_time = Some(*seconds);
|
||||
if output.is_some() {
|
||||
i.last_output = output.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bump();
|
||||
}
|
||||
if finished {
|
||||
let mut job = self.render_job.take().expect("job");
|
||||
if let Some(t) = job.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
let st = job.shared.snapshot();
|
||||
let failed = updates.iter().filter(|u| matches!(u, ItemUpdate::Finished { status: RenderStatus::Failed(_), .. })).count();
|
||||
let stopped = updates.iter().any(|u| matches!(u, ItemUpdate::Finished { status: RenderStatus::UserStopped, .. }));
|
||||
let msg = if failed > 0 {
|
||||
format!("Render finished with {failed} failed item(s)")
|
||||
} else if stopped {
|
||||
"Render stopped".to_string()
|
||||
} else {
|
||||
format!("Rendered {} item(s) in {:.1} s", st.items_total, st.elapsed)
|
||||
};
|
||||
self.events.push(Event::Toast { message: msg, error: failed > 0 });
|
||||
}
|
||||
changed || finished
|
||||
}
|
||||
|
||||
/// The comp to add: `comp` param, the active comp, or the first comp selected in the Project panel.
|
||||
pub(crate) fn comp_for_queue(&self, p: &serde_json::Value) -> Option<ItemId> {
|
||||
if p.get("comp").is_some() {
|
||||
return crate::commands::comp_id(self, p).ok();
|
||||
}
|
||||
let sel = self.state.project_selection.iter().copied().find(|i| self.project.comp(*i).is_some());
|
||||
self.active_comp_id().or(sel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Render Queue commands against mock exporters (real encoding is tested in `effectcraft-export`
|
||||
//! and end to end in `effectcraft-host`).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_project::render_queue::{OutputFormat, RenderQuality, RenderStatus};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::render_queue::CANCELLED;
|
||||
use crate::{Event, ExportJob, ExportResult, Exporter, Session};
|
||||
|
||||
fn demo() -> Session {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Records exports; fails items whose path contains "fail"; honours cancellation.
|
||||
struct MockExporter {
|
||||
log: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Exporter for MockExporter {
|
||||
fn formats(&self) -> Vec<OutputFormat> {
|
||||
OutputFormat::ALL.to_vec()
|
||||
}
|
||||
fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
|
||||
self.log.lock().unwrap().push(job.path.to_string());
|
||||
if job.path.contains("fail") {
|
||||
return Err("boom".into());
|
||||
}
|
||||
let comp = job.project.comp(job.item.comp).ok_or("no comp")?;
|
||||
let n = job.item.settings.frame_count(comp);
|
||||
for k in 0..=n {
|
||||
if !progress(k, n) {
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
}
|
||||
Ok(ExportResult { path: job.path.to_string(), frames: n, ..Default::default() })
|
||||
}
|
||||
}
|
||||
|
||||
fn rq_session() -> (Session, Arc<MockExporter>) {
|
||||
let mut s = demo();
|
||||
let ex = Arc::new(MockExporter { log: Default::default() });
|
||||
s.exporter = Some(ex.clone());
|
||||
(s, ex)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_configure_render() {
|
||||
let (mut s, ex) = rq_session();
|
||||
assert!(s.is_enabled("renderQueue.add"));
|
||||
assert!(!s.is_enabled("renderQueue.render"));
|
||||
let a = s.execute("renderQueue.add", json!({})).unwrap();
|
||||
let name = s.project.item(s.active_comp_id().unwrap()).unwrap().name.clone();
|
||||
assert_eq!(a["index"], 1);
|
||||
assert_eq!(a["statusLabel"], "Queued");
|
||||
assert!(a["outputPath"].as_str().unwrap().ends_with(&format!("{name}.mp4")), "{a}");
|
||||
let id = a["item"].as_u64().unwrap();
|
||||
// Render Settings / Output Module / Output To.
|
||||
let r = s
|
||||
.execute("renderQueue.setRenderSettings", json!({"item": id, "resolution": "half", "timeSpan": "custom", "start": 1.0, "end": 2.0, "frameRate": 10}))
|
||||
.unwrap();
|
||||
assert_eq!(r["frames"], 10);
|
||||
assert_eq!(r["width"], 960);
|
||||
let r = s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "png", "channels": "rgba"})).unwrap();
|
||||
assert!(r["outputPath"].as_str().unwrap().ends_with("_[#####].png"), "{r}");
|
||||
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "jpeg", "channels": "rgba"})).is_err());
|
||||
let r = s.execute("renderQueue.setOutput", json!({"item": id, "path": "/tmp/rq/out.mov"})).unwrap();
|
||||
assert_eq!(r["output"]["format"], "ProRes", "Output To with .mov switches to ProRes");
|
||||
assert_eq!(r["outputPath"], "/tmp/rq/out.mov");
|
||||
// A second item that fails, a third that is unqueued.
|
||||
let b = s.execute("renderQueue.add", json!({"format": "gif", "output": "/tmp/rq/fail.gif"})).unwrap();
|
||||
let c = s.execute("renderQueue.add", json!({"output": "/tmp/rq/skip.mp4"})).unwrap();
|
||||
s.execute("renderQueue.setRender", json!({"item": c["item"], "render": false})).unwrap();
|
||||
assert_eq!(s.project.render_queue[2].status.label(), "Unqueued");
|
||||
let r = s.execute("renderQueue.render", json!({})).unwrap();
|
||||
assert_eq!(r["items"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(*ex.log.lock().unwrap(), vec!["/tmp/rq/out.mov".to_string(), "/tmp/rq/fail.gif".to_string()]);
|
||||
let q = &s.project.render_queue;
|
||||
assert_eq!(q[0].status.label(), "Done");
|
||||
assert!(q[0].started.is_some() && q[0].render_time.is_some());
|
||||
assert_eq!(q[0].last_output.as_deref(), Some("/tmp/rq/out.mov"));
|
||||
assert_eq!(q[1].status, RenderStatus::Failed("boom".into()));
|
||||
assert_eq!(q[2].status.label(), "Unqueued");
|
||||
assert!(s.drain_events().iter().any(|e| matches!(e, Event::Toast { error: true, .. })));
|
||||
// Reorder, duplicate, remove, undo.
|
||||
s.execute("renderQueue.move", json!({"item": b["item"], "to": 1})).unwrap();
|
||||
assert_eq!(s.project.render_queue[0].id, b["item"].as_u64().unwrap());
|
||||
let d = s.execute("renderQueue.duplicate", json!({"index": 2})).unwrap();
|
||||
assert_eq!(s.project.render_queue.len(), 4);
|
||||
assert_eq!(s.project.render_queue[2].id, d["item"].as_u64().unwrap());
|
||||
assert_eq!(s.project.render_queue[2].status.label(), "Queued");
|
||||
s.execute("renderQueue.remove", json!({"index": 3})).unwrap();
|
||||
assert_eq!(s.project.render_queue.len(), 3);
|
||||
s.undo();
|
||||
assert_eq!(s.project.render_queue.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persists_in_project_file() {
|
||||
let (mut s, _) = rq_session();
|
||||
s.execute("renderQueue.add", json!({"format": "tiff", "output": "[compName]/[compName]_[####].tif", "quality": "draft"})).unwrap();
|
||||
let json = s.project.to_json();
|
||||
let p = effectcraft_project::Project::from_json(&json).unwrap();
|
||||
assert_eq!(p.render_queue, s.project.render_queue);
|
||||
assert_eq!(p.render_queue[0].settings.quality, RenderQuality::Draft);
|
||||
// Projects without a queue still load.
|
||||
let old = json.replace("\"render_queue\"", "\"_ignored\"");
|
||||
assert!(effectcraft_project::Project::from_json(&old).unwrap().render_queue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_render_and_stop() {
|
||||
struct Slow;
|
||||
impl Exporter for Slow {
|
||||
fn formats(&self) -> Vec<OutputFormat> {
|
||||
OutputFormat::ALL.to_vec()
|
||||
}
|
||||
fn export(&self, _: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
|
||||
for k in 0..10_000 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
if !progress(k, 10_000) {
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
}
|
||||
Ok(Default::default())
|
||||
}
|
||||
}
|
||||
let mut s = demo();
|
||||
s.exporter = Some(Arc::new(Slow));
|
||||
s.execute("renderQueue.add", json!({"output": "/tmp/a.mp4"})).unwrap();
|
||||
s.execute("renderQueue.add", json!({"output": "/tmp/b.mp4"})).unwrap();
|
||||
s.execute("renderQueue.render", json!({"wait": false})).unwrap();
|
||||
assert!(s.is_rendering());
|
||||
assert!(!s.is_enabled("renderQueue.add"), "queue is locked while rendering");
|
||||
let t0 = std::time::Instant::now();
|
||||
while s.render_progress().is_some_and(|p| p.done < 3) {
|
||||
assert!(t0.elapsed().as_secs() < 20);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
s.poll_render();
|
||||
assert_eq!(s.project.render_queue[0].status.label(), "Rendering");
|
||||
s.execute("renderQueue.stop", json!({})).unwrap();
|
||||
while s.is_rendering() {
|
||||
assert!(t0.elapsed().as_secs() < 20);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
s.poll_render();
|
||||
assert!(s.render_job.is_none());
|
||||
assert_eq!(s.project.render_queue[0].status.label(), "User Stopped");
|
||||
assert_eq!(s.project.render_queue[1].status.label(), "User Stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_exporter() {
|
||||
let mut s = demo();
|
||||
s.execute("renderQueue.add", json!({})).unwrap();
|
||||
assert!(!s.is_enabled("renderQueue.render"));
|
||||
let f = s.execute("renderQueue.formats", json!({})).unwrap();
|
||||
assert_eq!(f["formats"].as_array().unwrap().len(), 7);
|
||||
assert_eq!(f["formats"][0]["available"], false);
|
||||
}
|
||||
@@ -18,6 +18,35 @@ fn demo_opens_and_renders() {
|
||||
assert!(lit > 100_000, "{lit}");
|
||||
}
|
||||
|
||||
/// The session's layer cache never changes pixels: scrubbing the demo (including back and
|
||||
/// forth, and across an edit made through a command) matches cache-less renders exactly.
|
||||
#[test]
|
||||
fn demo_layer_cache_is_transparent() {
|
||||
let mut s = demo();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let opts = effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() };
|
||||
let uncached = |s: &Session, t: f64| {
|
||||
let mut r = effectcraft_render::Renderer::new(&s.project, s.footage.as_ref(), opts);
|
||||
r.expr = s.expr.as_deref();
|
||||
r.comp_frame(cid, effectcraft_time::Tick::from_seconds_f64(t))
|
||||
};
|
||||
let check = |s: &Session, t: f64| {
|
||||
let a = s.render(cid, effectcraft_time::Tick::from_seconds_f64(t), opts);
|
||||
let b = uncached(s, t);
|
||||
assert!(a.data.iter().zip(&b.data).all(|(p, q)| (0..4).all(|c| (p[c] - q[c]).abs() < 1e-6)), "t={t}");
|
||||
};
|
||||
for t in [0.5, 1.0, 3.0, 3.0334, 6.0, 3.0, 0.5] {
|
||||
check(&s, t);
|
||||
}
|
||||
assert!(s.layer_cache.stats().hits > 0);
|
||||
// Edit the title's glow through the command layer, then scrub again.
|
||||
let title = s.project.comp(cid).unwrap().layers.iter().find(|l| l.name == "EFFECTCRAFT").map(|l| l.id.0).unwrap();
|
||||
s.execute("prop.set", json!({"layer": title, "path": "effects/#1/radius", "value": 5.0})).unwrap();
|
||||
for t in [3.0, 0.5] {
|
||||
check(&s, t);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_has_unique_id_and_runs_or_reports() {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -168,4 +197,104 @@ fn set_text_paragraph_fill_and_leading() {
|
||||
assert_eq!((d.leading, d.apply_fill, d.apply_stroke), (Some(50.0), false, true));
|
||||
s.execute("layer.setText", json!({"layer": t, "leading": "auto"})).unwrap();
|
||||
assert_eq!(doc(&s).leading, None);
|
||||
s.execute("layer.setText", json!({"layer": t, "hScale": 120, "vScale": 80, "baselineShift": 4, "smallCaps": true, "strokeOverFill": true})).unwrap();
|
||||
let d = doc(&s);
|
||||
assert_eq!((d.h_scale, d.v_scale, d.baseline_shift, d.small_caps, d.stroke_over_fill), (120.0, 80.0, 4.0, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prop_get_and_render_rgba8() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "T", "width": 320, "height": 180, "duration": 2.0, "frameRate": 30})).unwrap();
|
||||
let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [0, 0]})).unwrap();
|
||||
s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 1.0, "value": [100, 50]})).unwrap();
|
||||
let v = s.execute("prop.get", json!({"layer": l, "path": "transform/position", "time": 1.0})).unwrap();
|
||||
assert_eq!(v["animated"], true);
|
||||
assert_eq!(v["keys"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(v["value"][0].as_f64().unwrap(), 100.0);
|
||||
let cid = s.resolve_comp(Some(&json!("T"))).unwrap();
|
||||
let (w, h, rgba) = s.render_rgba8(cid, effectcraft_time::Tick::ZERO, 160).unwrap();
|
||||
assert_eq!((w, h), (160, 90));
|
||||
assert_eq!(rgba.len(), (w * h * 4) as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_docs_parse() {
|
||||
use crate::commands::accepted_params;
|
||||
let k = |d: &str| accepted_params(d).unwrap();
|
||||
assert_eq!(k("{layers: [id|name|#n], add?, toggle?}"), ["layers", "add", "toggle"]);
|
||||
assert_eq!(k("{time? (s) | frame? | timecode?}"), ["time", "frame", "timecode"]);
|
||||
assert_eq!(k("{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}"), ["interpolation", "in", "out", "autoBezier"]);
|
||||
assert_eq!(k("{keys: [{layer, prop, time}], add?}"), ["keys", "add"]);
|
||||
assert_eq!(k("{label: Red|Yellow|Aqua|…, layers?}"), ["label", "layers"]);
|
||||
assert_eq!(k("{name?, background? [r,g,b]|#hex, open?}"), ["name", "background", "open"]);
|
||||
assert!(k("{}").is_empty());
|
||||
assert!(accepted_params("free text").is_none());
|
||||
// Every registered command documents its params as a parseable key list.
|
||||
for c in crate::command_specs() {
|
||||
assert!(accepted_params(c.params).is_some(), "{}: {}", c.id, c.params);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_checked_rejects_unknown_params() {
|
||||
let mut s = demo();
|
||||
let e = s.execute_checked("layer.select", json!({"index": 2})).unwrap_err().to_string();
|
||||
assert!(e.contains("`index`") && e.contains("layers, add, toggle"), "{e}");
|
||||
s.execute_checked("layer.select", json!({"layers": ["#2"]})).unwrap();
|
||||
assert_eq!(s.state.selected_layers.len(), 1);
|
||||
// Aliases and always-accepted keys.
|
||||
s.execute_checked("layer.select", json!({"layer": "#1", "comp": s.active_comp_id().unwrap().0})).unwrap();
|
||||
s.execute_checked("time.set", json!({"frame": 3})).unwrap();
|
||||
assert!(s.execute_checked("edit.undo", json!({"steps": 2})).is_err());
|
||||
// Non-object params are not validated; the unchecked path stays lenient.
|
||||
s.execute("layer.select", json!({"layers": ["#1"], "index": 2})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_tree_paths_resolve() {
|
||||
let mut s = demo();
|
||||
s.execute("effect.apply", json!({"layer": 1, "effect": "Gaussian Blur"})).unwrap();
|
||||
let comp = s.execute("comp.info", json!({})).unwrap();
|
||||
let mut checked = 0;
|
||||
for l in comp["layers"].as_array().unwrap() {
|
||||
let tree = s.execute("layer.tree", json!({"layer": l["id"]})).unwrap();
|
||||
let mut stack = vec![tree["properties"].clone()];
|
||||
while let Some(n) = stack.pop() {
|
||||
if let Some(ch) = n["children"].as_array() {
|
||||
stack.extend(ch.iter().cloned());
|
||||
continue;
|
||||
}
|
||||
let path = n["path"].as_str().unwrap();
|
||||
let got = s.execute("prop.get", json!({"layer": l["id"], "path": path})).unwrap();
|
||||
assert_eq!(got["uid"], n["uid"], "path {path} on layer {}", l["name"]);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 20, "{checked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comp_settings_anchor_start_timecode_renderer() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "A", "width": 100, "height": 100, "duration": 2.0})).unwrap();
|
||||
let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [10, 20]})).unwrap();
|
||||
let pos = |s: &Session| {
|
||||
let pr = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.prop("transform/position").unwrap().clone();
|
||||
pr.keys[0].value.components()
|
||||
};
|
||||
// Center anchor: grow by 100x50 → shift by half.
|
||||
s.execute("comp.settings", json!({"width": 200, "height": 150})).unwrap();
|
||||
assert_eq!(pos(&s)[..2], [60.0, 45.0]);
|
||||
// Top-left anchor: no shift. Bottom-right: full shift.
|
||||
s.execute("comp.settings", json!({"width": 300, "anchor": 0})).unwrap();
|
||||
assert_eq!(pos(&s)[..2], [60.0, 45.0]);
|
||||
s.execute("comp.settings", json!({"width": 200, "height": 100, "anchor": 8})).unwrap();
|
||||
assert_eq!(pos(&s)[..2], [-40.0, -5.0]);
|
||||
s.execute("comp.settings", json!({"startTimecode": "0:00:01:00", "renderer": "advanced3D"})).unwrap();
|
||||
let c = s.active_comp().unwrap();
|
||||
assert_eq!(c.display_start, c.frame_rate.tick_of(30));
|
||||
assert_eq!(c.renderer, crate::project::Renderer::Advanced3D);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
//! 3D commands: cameras, lights, views, camera tools (with undo/redo), and the 3D demo comp.
|
||||
|
||||
use effectcraft_project::{AutoOrient, LayerSource, LightKind};
|
||||
use effectcraft_render::three_d::View3D;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_orient_command() {
|
||||
let mut s = session();
|
||||
let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.autoOrient", json!({"layer": id, "mode": "towardsCamera"})).unwrap();
|
||||
assert_eq!(s.active_comp().unwrap().layers[0].auto_orient, AutoOrient::TowardsCamera);
|
||||
s.undo();
|
||||
assert_eq!(s.active_comp().unwrap().layers[0].auto_orient, AutoOrient::Off);
|
||||
let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
assert!(s.execute("layer.autoOrient", json!({"layer": cam, "mode": "towardsCamera"})).is_err());
|
||||
s.execute("layer.autoOrient", json!({"layer": cam, "mode": "off"})).unwrap();
|
||||
assert!(!effectcraft_render::three_d::camera::is_two_node(&s.active_comp().unwrap().layers[0]));
|
||||
}
|
||||
|
||||
fn layer_count(s: &Session) -> usize {
|
||||
s.active_comp().unwrap().layers.len()
|
||||
}
|
||||
|
||||
fn prop(s: &Session, layer: u64, path: &str) -> effectcraft_keyframe::Value {
|
||||
let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(layer)).unwrap();
|
||||
l.props.prop(path).unwrap_or_else(|| panic!("no {path}")).value.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_camera_with_preset_undo_redo() {
|
||||
let mut s = session();
|
||||
let r = s.execute("layer.newCamera", json!({"preset": "35mm"})).unwrap();
|
||||
let id = r["layer"].as_u64().unwrap();
|
||||
assert_eq!(layer_count(&s), 1);
|
||||
let zoom = prop(&s, id, "cameraOptions/zoom").as_f64();
|
||||
assert!((zoom - 640.0 * 35.0 / 36.0).abs() < 1e-9);
|
||||
assert_eq!(prop(&s, id, "cameraOptions/focusDistance").as_f64(), zoom);
|
||||
let l = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(l.source, LayerSource::Camera);
|
||||
assert_eq!(l.auto_orient, AutoOrient::TowardsPointOfInterest);
|
||||
assert!(s.undo());
|
||||
assert_eq!(layer_count(&s), 0);
|
||||
assert!(s.redo());
|
||||
assert_eq!(layer_count(&s), 1);
|
||||
assert!(s.execute("layer.newCamera", json!({"preset": "13mm-fisheye"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_settings_one_node_keeps_view() {
|
||||
let mut s = session();
|
||||
let id = s.execute("layer.newCamera", json!({"poi": [100, 50, 0], "position": [320, 180, -400]})).unwrap()["layer"].as_u64().unwrap();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let fwd = |s: &Session| {
|
||||
let c = s.project.comp(cid).unwrap();
|
||||
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, c, s.time());
|
||||
effectcraft_render::three_d::active_camera(&ctx).forward()
|
||||
};
|
||||
let before = fwd(&s);
|
||||
s.execute("layer.cameraSettings", json!({"layer": id, "type": "oneNode", "dof": true, "aperture": 30})).unwrap();
|
||||
let l = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(l.auto_orient, AutoOrient::Off);
|
||||
assert!((fwd(&s) - before).length() < 1e-9, "one-node camera keeps looking the same way");
|
||||
assert!(prop(&s, id, "cameraOptions/dof").as_bool());
|
||||
// Layer Settings (Cmd+Shift+Y) on a camera opens Camera Settings.
|
||||
s.execute("layer.settings", json!({"layer": id, "zoom": 500})).unwrap();
|
||||
assert_eq!(prop(&s, id, "cameraOptions/zoom").as_f64(), 500.0);
|
||||
s.undo();
|
||||
s.undo();
|
||||
let l = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(l.auto_orient, AutoOrient::TowardsPointOfInterest);
|
||||
assert!(!prop(&s, id, "cameraOptions/dof").as_bool());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_light_and_change_type() {
|
||||
let mut s = session();
|
||||
let id = s
|
||||
.execute(
|
||||
"layer.newLight",
|
||||
json!({"kind": "Spot", "intensity": 150, "color": [1, 0.5, 0.25], "coneAngle": 60, "castsShadows": true, "falloff": "Smooth"}),
|
||||
)
|
||||
.unwrap()["layer"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
assert_eq!(prop(&s, id, "lightOptions/intensity").as_f64(), 150.0);
|
||||
assert_eq!(prop(&s, id, "lightOptions/coneAngle").as_f64(), 60.0);
|
||||
assert_eq!(prop(&s, id, "lightOptions/falloff").as_enum(), 1);
|
||||
assert!(prop(&s, id, "lightOptions/castsShadows").as_bool());
|
||||
s.execute("layer.lightSettings", json!({"layer": id, "kind": "Point"})).unwrap();
|
||||
let l = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(l.source, LayerSource::Light { kind: LightKind::Point });
|
||||
assert!(l.props.prop("lightOptions/coneAngle").is_none());
|
||||
assert_eq!(prop(&s, id, "lightOptions/intensity").as_f64(), 150.0, "shared values carry over");
|
||||
s.undo();
|
||||
let l = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(l.source, LayerSource::Light { kind: LightKind::Spot });
|
||||
assert!(s.execute("layer.newLight", json!({"kind": "Laser"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_switch_undo_redo() {
|
||||
let mut s = session();
|
||||
let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap();
|
||||
assert!(s.active_comp().unwrap().layers[0].is_3d());
|
||||
s.undo();
|
||||
assert!(!s.active_comp().unwrap().layers[0].is_3d());
|
||||
s.redo();
|
||||
assert!(s.active_comp().unwrap().layers[0].is_3d());
|
||||
// Turning 3D off discards Z and the 3D-only rotations.
|
||||
s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [10, 20, 300]})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": id, "path": "transform/rotationX", "value": 45})).unwrap();
|
||||
s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": false})).unwrap();
|
||||
assert_eq!(prop(&s, id, "transform/position").as_vec3(), [10.0, 20.0, 0.0]);
|
||||
assert_eq!(prop(&s, id, "transform/rotationX").as_f64(), 0.0);
|
||||
s.undo();
|
||||
assert_eq!(prop(&s, id, "transform/position").as_vec3(), [10.0, 20.0, 300.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_3d_turns_off_lighting() {
|
||||
let mut s = session();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let id = s.execute("layer.newSolid", json!({"width": 640, "height": 360, "color": [1, 1, 1]})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap();
|
||||
s.execute("layer.newLight", json!({"kind": "Point", "intensity": 50, "position": [320, 180, -400]})).unwrap();
|
||||
let px = |s: &Session| s.render(cid, s.time(), effectcraft_render::RenderOpts::default()).get(320, 180)[0];
|
||||
assert!(px(&s) < 0.5);
|
||||
s.execute("comp.setSwitch", json!({"switch": "draft3d", "value": true})).unwrap();
|
||||
assert!((px(&s) - 1.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_switch_and_override_camera() {
|
||||
let mut s = session();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap();
|
||||
assert!(s.view_camera(cid).is_none());
|
||||
s.execute("view.3d.top", json!({})).unwrap();
|
||||
let cam = s.view_camera(cid).unwrap();
|
||||
assert!(cam.ortho);
|
||||
assert!((cam.forward().y - 1.0).abs() < 1e-9);
|
||||
s.execute("view.set3DView", json!({"view": "Custom View 2"})).unwrap();
|
||||
assert!(!s.view_camera(cid).unwrap().ortho);
|
||||
s.execute("view.3d.last", json!({})).unwrap();
|
||||
assert_eq!(s.state.views3d[&cid].current, View3D::Top);
|
||||
// Orbit a custom view: edits the view camera, not the project.
|
||||
s.execute("view.3d.custom1", json!({})).unwrap();
|
||||
let rev = s.revision;
|
||||
let before = s.view_camera(cid).unwrap().eye;
|
||||
s.execute("camera.orbit", json!({"yaw": 20})).unwrap();
|
||||
assert!((s.view_camera(cid).unwrap().eye - before).length() > 1.0);
|
||||
assert_eq!(s.revision, rev);
|
||||
s.execute("view.reset3DView", json!({})).unwrap();
|
||||
assert!((s.view_camera(cid).unwrap().eye - before).length() < 1e-9);
|
||||
s.execute("view.3d.activeCamera", json!({})).unwrap();
|
||||
assert!(s.view_camera(cid).is_none());
|
||||
let q = s.execute("view.get3D", json!({})).unwrap();
|
||||
assert_eq!(q["view"], "activeCamera");
|
||||
assert!(s.execute("view.set3DView", json!({"view": "sideways"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_tools_edit_active_camera_with_undo() {
|
||||
let mut s = session();
|
||||
// No camera layer: the tools explain what is needed.
|
||||
assert!(s.execute("camera.orbit", json!({"yaw": 10})).is_err());
|
||||
let id = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let p0 = prop(&s, id, "transform/position").as_vec3();
|
||||
let poi = prop(&s, id, "transform/poi").as_vec3();
|
||||
let dist = |a: [f64; 3], b: [f64; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt();
|
||||
// A drag = several merged steps → one undo.
|
||||
let undo_len = s.history.undo.len();
|
||||
for _ in 0..5 {
|
||||
s.execute("camera.orbit", json!({"yaw": 6, "pitch": -2, "merge": "drag-1"})).unwrap();
|
||||
}
|
||||
assert_eq!(s.history.undo.len(), undo_len + 1);
|
||||
let p1 = prop(&s, id, "transform/position").as_vec3();
|
||||
assert!((dist(p1, poi) - dist(p0, poi)).abs() < 1e-6, "orbit keeps the distance to the POI");
|
||||
assert!(dist(p1, p0) > 10.0);
|
||||
s.execute("camera.pan", json!({"dx": 50, "dy": 0})).unwrap();
|
||||
let poi2 = prop(&s, id, "transform/poi").as_vec3();
|
||||
assert!(dist(poi2, poi) > 1.0, "pan moves the POI too");
|
||||
s.execute("camera.dolly", json!({"amount": 100})).unwrap();
|
||||
s.undo();
|
||||
s.undo();
|
||||
s.undo();
|
||||
assert_eq!(prop(&s, id, "transform/position").as_vec3(), p0);
|
||||
// One-node cameras orbit by re-orienting.
|
||||
s.execute("layer.cameraSettings", json!({"layer": id, "type": "oneNode"})).unwrap();
|
||||
s.execute("camera.orbit", json!({"yaw": 30})).unwrap();
|
||||
let o = prop(&s, id, "transform/orientation").as_vec3();
|
||||
assert!(o[1].abs() > 1.0, "{o:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demo_has_3d_showcase() {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
let item = s.project.find_by_name(crate::demo::SHOWCASE_3D).unwrap();
|
||||
let cid = item.id;
|
||||
let c = s.project.comp(cid).unwrap();
|
||||
assert!(c.layers.iter().any(|l| l.is_camera()));
|
||||
assert!(c.layers.iter().any(|l| l.is_light()));
|
||||
assert!(c.layers.iter().filter(|l| l.switches.three_d).count() >= 4);
|
||||
let img =
|
||||
s.render(cid, effectcraft_time::Tick::from_seconds_f64(4.0), effectcraft_render::RenderOpts { scale: 0.125, motion_blur: false, ..Default::default() });
|
||||
let lit = img.data.iter().filter(|p| p[3] > 0.99 && p[0] + p[1] + p[2] > 0.3).count();
|
||||
assert!(lit > 2_000, "{lit}");
|
||||
}
|
||||
@@ -185,7 +185,8 @@ fn keyframe_clipboard_paste_and_paste_reversed() {
|
||||
s.execute("time.set", json!({"time": 1.0})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": a, "path": "transform/opacity", "value": 0})).unwrap();
|
||||
s.execute("prop.select", json!({"layer": a, "path": "transform/opacity"})).unwrap();
|
||||
assert_eq!(s.execute("edit.copy", json!({})).unwrap()["keys"], 2);
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
assert_eq!(s.state.key_clipboard.iter().map(|c| c.keys.len()).sum::<usize>(), 2);
|
||||
s.execute("layer.select", json!({"layers": [b]})).unwrap();
|
||||
s.execute("time.set", json!({"time": 2.0})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
@@ -484,7 +485,7 @@ fn frontend_commands_emit_events_and_stubs_are_disabled() {
|
||||
let ev = frontend_events(&mut s);
|
||||
assert_eq!(ev[0].0, "view.zoomIn");
|
||||
assert_eq!(ev[1], ("window.panel".to_string(), json!({"panel": "align"})));
|
||||
for id in ["render.addToQueue", "layer.timeRemap", "camera.fromView", "view.3d", "layer.styles", "prop.separateDimensions"] {
|
||||
for id in ["render.addOutputModule", "path.rotoBezier", "camera.fromView", "view.3d.default", "layer.styles", "track.motion"] {
|
||||
assert!(!s.is_enabled(id), "{id}");
|
||||
assert!(matches!(s.execute(id, json!({})), Err(EngineError::Disabled(..))), "{id}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
//! Timeline depth: keyframe clipboard, easing, velocity/interpolation, roving, nudging, graph
|
||||
//! editor key edits, time remapping/stretch/reverse/freeze, separate dimensions, pick-whips,
|
||||
//! expressions and masks (pen tool). Every command is checked with undo/redo.
|
||||
|
||||
use effectcraft_keyframe::{Interp, Value as KV};
|
||||
use effectcraft_project::Property;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A 4 s, 30 fps comp with one solid; returns (session, layer id).
|
||||
pub(crate) fn setup() -> (Session, u64) {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "T", "width": 400, "height": 300, "frameRate": 30, "duration": 4})).unwrap();
|
||||
let r = s.execute("layer.newSolid", json!({"color": "#ffffff", "width": 100, "height": 100})).unwrap();
|
||||
(s, r["layer"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
pub(crate) fn prop(s: &Session, layer: u64, path: &str) -> Property {
|
||||
s.active_comp().unwrap().layer(effectcraft_project::LayerId(layer)).unwrap().props.prop(path).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Key `path` at the given (time, value) pairs.
|
||||
pub(crate) fn animate(s: &mut Session, layer: u64, path: &str, keys: &[(f64, Value)]) {
|
||||
for (t, v) in keys {
|
||||
s.execute("prop.addKey", json!({"layer": layer, "path": path, "time": t, "value": v})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn select_prop_keys(s: &mut Session, layer: u64, path: &str) {
|
||||
s.execute("prop.select", json!({"layer": layer, "path": path})).unwrap();
|
||||
}
|
||||
|
||||
fn undo_redo_roundtrip(s: &mut Session, check_after: impl Fn(&Session), check_before: impl Fn(&Session)) {
|
||||
check_after(s);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
check_before(s);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
check_after(s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easy_ease_family_sets_influence_and_zero_speed() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/opacity", &[(0.0, json!(0)), (1.0, json!(100)), (2.0, json!(0))]);
|
||||
select_prop_keys(&mut s, l, "transform/opacity");
|
||||
s.execute("keys.easyEase", json!({})).unwrap();
|
||||
undo_redo_roundtrip(
|
||||
&mut s,
|
||||
|s| {
|
||||
let p = prop(s, l, "transform/opacity");
|
||||
assert!(p.keys.iter().all(|k| k.in_interp == Interp::Bezier && k.out_interp == Interp::Bezier));
|
||||
assert!((p.keys[1].in_ease[0].influence - 1.0 / 3.0).abs() < 1e-9 && p.keys[1].in_ease[0].speed == 0.0);
|
||||
},
|
||||
|s| assert!(prop(s, l, "transform/opacity").keys.iter().all(|k| k.in_interp == Interp::Linear)),
|
||||
);
|
||||
// Easy Ease In only touches the incoming side; Out only the outgoing side.
|
||||
s.execute("keys.interpolation", json!({"interpolation": "linear"})).unwrap();
|
||||
s.execute("keys.easyEaseIn", json!({})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
assert!(p.keys.iter().all(|k| k.in_interp == Interp::Bezier && k.out_interp == Interp::Linear));
|
||||
s.execute("keys.interpolation", json!({"interpolation": "linear"})).unwrap();
|
||||
s.execute("keys.easyEaseOut", json!({})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
assert!(p.keys.iter().all(|k| k.in_interp == Interp::Linear && k.out_interp == Interp::Bezier));
|
||||
// Eased motion is slow near the key.
|
||||
s.execute("keys.easyEase", json!({})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
let early = p.value_at(effectcraft_time::Tick::from_seconds_f64(0.1)).as_f64();
|
||||
assert!(early < 5.0, "{early}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframe_copy_paste_keeps_relative_timing_and_crosses_properties() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/rotation", &[(0.5, json!(0)), (1.0, json!(90)), (2.0, json!(45))]);
|
||||
select_prop_keys(&mut s, l, "transform/rotation");
|
||||
s.execute("keys.easyEase", json!({})).unwrap();
|
||||
assert_eq!(s.execute("edit.copy", json!({})).unwrap(), json!(3));
|
||||
assert!(s.state.clip_is_keys);
|
||||
// Paste into the same property at 2.5 s: keys at 2.5, 3.0 and 4.0 (clamped by nothing).
|
||||
s.execute("time.set", json!({"time": 2.5})).unwrap();
|
||||
s.execute("keys.select", json!({"keys": []})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let p = prop(s, l, "transform/rotation");
|
||||
let times: Vec<f64> = p.keys.iter().map(|k| (k.time.seconds() * 30.0).round() / 30.0).collect();
|
||||
assert_eq!(times, vec![0.5, 1.0, 2.0, 2.5, 3.0, 4.0]);
|
||||
assert_eq!(p.keys[4].value, KV::Scalar(90.0));
|
||||
assert_eq!(p.keys[4].in_interp, Interp::Bezier, "interpolation travels with the keys");
|
||||
assert_eq!(s.state.selected_keys.len(), 3, "pasted keys are selected");
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert_eq!(prop(s, l, "transform/rotation").keys.len(), 3));
|
||||
// Cross-property paste of one property's keys into another of the same type (Scalar).
|
||||
let r = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
|
||||
let l2 = r["layer"].as_u64().unwrap();
|
||||
select_prop_keys(&mut s, l, "transform/rotation");
|
||||
s.execute("keys.select", json!({"keys": [{"layer": l, "prop": prop(&s, l, "transform/rotation").uid, "time": 1.0}]})).unwrap();
|
||||
s.execute("keys.copy", json!({})).unwrap();
|
||||
s.execute("time.set", json!({"time": 1.0})).unwrap();
|
||||
s.execute("prop.select", json!({"layer": l2, "path": "transform/opacity", "selectKeys": false})).unwrap();
|
||||
s.execute("keys.paste", json!({"layers": [l2]})).unwrap();
|
||||
let op = prop(&s, l2, "transform/opacity");
|
||||
assert_eq!(op.keys.len(), 1);
|
||||
assert_eq!(op.keys[0].value, KV::Scalar(90.0));
|
||||
// Incompatible target (Vec3 position) is refused when explicitly given.
|
||||
let e = s.execute("keys.paste", json!({"layers": [l2], "path": "transform/position"}));
|
||||
assert!(e.is_err() || prop(&s, l2, "transform/position").keys.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_removes_keys_and_paste_restores_them() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/opacity", &[(0.0, json!(10)), (1.0, json!(20))]);
|
||||
select_prop_keys(&mut s, l, "transform/opacity");
|
||||
s.execute("edit.cut", json!({})).unwrap();
|
||||
assert!(prop(&s, l, "transform/opacity").keys.is_empty());
|
||||
s.execute("time.set", json!({"time": 0.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layers": [l]})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/opacity").keys.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_and_nudge_keys() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/opacity", &[(0.0, json!(10)), (1.0, json!(20))]);
|
||||
animate(&mut s, l, "transform/rotation", &[(0.5, json!(10))]);
|
||||
s.state.selected_props.clear();
|
||||
s.execute("layer.select", json!({"layers": [l]})).unwrap();
|
||||
assert_eq!(s.execute("keys.selectAll", json!({})).unwrap(), json!(3));
|
||||
s.execute("keys.nudgeForward", json!({})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let p = prop(s, l, "transform/opacity");
|
||||
assert!((p.keys[0].time.seconds() - 1.0 / 30.0).abs() < 1e-6);
|
||||
assert_eq!(s.state.selected_keys.len(), 3);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert_eq!(prop(s, l, "transform/opacity").keys[0].time.0, 0));
|
||||
s.execute("keys.nudgeBackward10", json!({})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
assert!((p.keys[0].time.seconds() + 9.0 / 30.0).abs() < 1e-6, "{}", p.keys[0].time.seconds());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn velocity_dialog_values_per_dimension_and_continuous() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/scale", &[(0.0, json!([100, 100])), (1.0, json!([200, 50])), (2.0, json!([100, 100]))]);
|
||||
s.execute("keys.select", json!({"keys": [{"layer": l, "prop": prop(&s, l, "transform/scale").uid, "time": 1.0}]})).unwrap();
|
||||
let info = s.execute("keys.info", json!({})).unwrap();
|
||||
assert_eq!(info[0]["units"], "%/sec");
|
||||
assert_eq!(info[0]["dims"], 2);
|
||||
// Linear sides present the segment slope: +100 %/s in X on the incoming side.
|
||||
assert!((info[0]["inEase"][0]["speed"].as_f64().unwrap() - 100.0).abs() < 1e-6, "{info}");
|
||||
s.execute("keys.velocity", json!({"inSpeed": [10, -20], "inInfluence": 50, "continuous": true})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let k = &prop(s, l, "transform/scale").keys[1];
|
||||
assert_eq!(k.in_ease[0].speed, 10.0);
|
||||
assert_eq!(k.in_ease[1].speed, -20.0);
|
||||
assert_eq!(k.out_ease[1].speed, -20.0, "continuous mirrors incoming");
|
||||
assert!((k.out_ease[0].influence - 0.5).abs() < 1e-9);
|
||||
assert!(k.continuous);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert_eq!(prop(s, l, "transform/scale").keys[1].in_interp, Interp::Linear));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolation_dialog_temporal_spatial_and_roving() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/position", &[(0.0, json!([0, 0])), (0.3, json!([300, 0])), (2.0, json!([400, 0]))]);
|
||||
select_prop_keys(&mut s, l, "transform/position");
|
||||
s.execute("keys.interpolation", json!({"interpolation": "hold"})).unwrap();
|
||||
assert!(prop(&s, l, "transform/position").keys.iter().all(|k| k.out_interp == Interp::Hold));
|
||||
s.execute("keys.interpolation", json!({"interpolation": "autoBezier"})).unwrap();
|
||||
assert!(prop(&s, l, "transform/position").keys.iter().all(|k| k.auto_bezier));
|
||||
s.execute("keys.interpolation", json!({"interpolation": "continuousBezier", "spatial": "linear"})).unwrap();
|
||||
let p = prop(&s, l, "transform/position");
|
||||
assert!(p.keys.iter().all(|k| k.continuous && !k.auto_bezier && !k.spatial_auto && k.spatial_out == [0.0; 3]));
|
||||
// Rove the middle key: its time follows the path length (300 of 400 px → 1.5 s).
|
||||
let uid = p.uid;
|
||||
s.execute("keys.select", json!({"keys": [{"layer": l, "prop": uid, "time": 0.3}]})).unwrap();
|
||||
s.execute("keys.interpolation", json!({"roving": true})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let p = prop(s, l, "transform/position");
|
||||
assert!(p.keys[1].roving);
|
||||
assert!((p.keys[1].time.seconds() - 1.5).abs() < 0.01, "{}", p.keys[1].time.seconds());
|
||||
// The selection follows the roving key.
|
||||
assert!((s.state.selected_keys[0].time.seconds() - 1.5).abs() < 0.01);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert!(!prop(s, l, "transform/position").keys[1].roving));
|
||||
// Moving the last key re-times the roving key.
|
||||
s.execute("keys.set", json!({"layer": l, "path": "transform/position", "time": 2.0, "newTime": 4.0})).unwrap();
|
||||
let p = prop(&s, l, "transform/position");
|
||||
assert!((p.keys[1].time.seconds() - 3.0).abs() < 0.02, "{}", p.keys[1].time.seconds());
|
||||
// Toggle hold on a key and back.
|
||||
s.execute("keys.select", json!({"keys": [{"layer": l, "prop": uid, "time": 0.0}]})).unwrap();
|
||||
s.execute("keys.toggleHold", json!({})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/position").keys[0].out_interp, Interp::Hold);
|
||||
s.execute("keys.toggleHold", json!({})).unwrap();
|
||||
assert_ne!(prop(&s, l, "transform/position").keys[0].out_interp, Interp::Hold);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_editor_key_and_handle_edits() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/opacity", &[(0.0, json!(0)), (2.0, json!(100))]);
|
||||
// Drag a key in the value graph: new time + value, merged into one undo step.
|
||||
s.execute("keys.set", json!({"layer": l, "path": "transform/opacity", "time": 2.0, "newTime": 1.0, "value": 50, "merge": "g1"})).unwrap();
|
||||
s.execute("keys.set", json!({"layer": l, "path": "transform/opacity", "time": 1.0, "newTime": 1.5, "value": 60, "merge": "g1"})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
assert!((p.keys[1].time.seconds() - 1.5).abs() < 1e-6);
|
||||
assert_eq!(p.keys[1].value, KV::Scalar(60.0));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!((prop(&s, l, "transform/opacity").keys[1].time.seconds() - 2.0).abs() < 1e-6);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
// A key can't be dragged past its neighbour.
|
||||
s.execute("keys.set", json!({"layer": l, "path": "transform/opacity", "time": 1.5, "newTime": -1.0})).unwrap();
|
||||
let p = prop(&s, l, "transform/opacity");
|
||||
assert!(p.keys[1].time > p.keys[0].time);
|
||||
// Handle drag: out side of key 0 → speed 200 %/s, 60 % influence.
|
||||
s.execute("keys.setEase", json!({"layer": l, "path": "transform/opacity", "time": 0.0, "side": "out", "speed": 200, "influence": 60})).unwrap();
|
||||
let k = &prop(&s, l, "transform/opacity").keys[0];
|
||||
assert_eq!(k.out_interp, Interp::Bezier);
|
||||
assert_eq!(k.out_ease[0].speed, 200.0);
|
||||
assert!((k.out_ease[0].influence - 0.6).abs() < 1e-9);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/opacity").keys[0].out_interp, Interp::Linear);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_reverse_keyframes() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/opacity", &[(0.0, json!(0)), (1.0, json!(30)), (3.0, json!(100))]);
|
||||
select_prop_keys(&mut s, l, "transform/opacity");
|
||||
s.execute("keys.timeReverse", json!({})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let p = prop(s, l, "transform/opacity");
|
||||
assert_eq!(p.keys[0].value, KV::Scalar(100.0));
|
||||
assert!((p.keys[1].time.seconds() - 2.0).abs() < 1e-6);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert_eq!(prop(s, l, "transform/opacity").keys[0].value, KV::Scalar(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_tool_draws_edits_and_closes_a_mask() {
|
||||
let (mut s, l) = setup();
|
||||
// Click (corner), click, drag (Bezier), click on the first vertex (close).
|
||||
let r = s.execute("mask.new", json!({"layer": l, "vertices": [[10, 10]]})).unwrap();
|
||||
let m = r["mask"].as_u64().unwrap();
|
||||
s.execute("mask.addVertex", json!({"layer": l, "mask": m, "point": [90, 10]})).unwrap();
|
||||
s.execute("mask.addVertex", json!({"layer": l, "mask": m, "point": [90, 90]})).unwrap();
|
||||
s.execute("mask.setVertex", json!({"layer": l, "mask": m, "index": 2, "in": [0, -20], "out": [0, 20], "merge": "pen"})).unwrap();
|
||||
s.execute("mask.addVertex", json!({"layer": l, "mask": m, "point": [10, 90]})).unwrap();
|
||||
s.execute("mask.setClosed", json!({"layer": l, "mask": m, "closed": true})).unwrap();
|
||||
let path = |s: &Session| prop(s, l, "masks/#1/path").value.as_path().unwrap().clone();
|
||||
let p = path(&s);
|
||||
assert_eq!(p.vertices, vec![[10.0, 10.0], [90.0, 10.0], [90.0, 90.0], [10.0, 90.0]]);
|
||||
assert_eq!(p.out_tangents[2], [0.0, 20.0]);
|
||||
assert!(p.closed);
|
||||
assert_eq!(s.state.selected_vertices.last().unwrap().index, 3);
|
||||
// The mask cuts the 100×100 solid (layer centred in the 400×300 comp at 150..250, 100..200).
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let img = s.render(cid, effectcraft_time::Tick::ZERO, effectcraft_render::RenderOpts { scale: 1.0, ..Default::default() });
|
||||
assert!(img.get(200, 150)[3] > 0.99 && img.get(152, 102)[3] < 0.01);
|
||||
// Undo removes the close, redo restores it.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(!path(&s).closed);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
// Select two vertices and drag them; Delete removes them.
|
||||
s.execute("mask.selectVertices", json!({"vertices": [{"layer": l, "mask": m, "index": 0}, {"layer": l, "mask": m, "index": 1}]})).unwrap();
|
||||
s.execute("mask.moveVertices", json!({"delta": [5, -5], "merge": "v1"})).unwrap();
|
||||
s.execute("mask.moveVertices", json!({"delta": [5, -5], "merge": "v1"})).unwrap();
|
||||
assert_eq!(path(&s).vertices[1], [100.0, 0.0]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(path(&s).vertices[1], [90.0, 10.0], "a drag is one undo step");
|
||||
s.execute("edit.clear", json!({})).unwrap();
|
||||
assert_eq!(path(&s).vertices.len(), 2);
|
||||
assert!(!path(&s).closed);
|
||||
// Animated mask paths get a key at the current time.
|
||||
s.execute("prop.toggleAnimation", json!({"layer": l, "path": "masks/#1/path"})).unwrap();
|
||||
s.execute("time.set", json!({"time": 1.0})).unwrap();
|
||||
s.execute("mask.setVertex", json!({"layer": l, "mask": 1, "index": 0, "point": [0, 0]})).unwrap();
|
||||
assert_eq!(prop(&s, l, "masks/#1/path").keys.len(), 2);
|
||||
// Mode / feather / opacity / expansion through the timeline commands.
|
||||
s.execute("layer.setMask", json!({"layer": l, "mask": m, "mode": "Subtract", "inverted": true})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": l, "path": "masks/#1/feather", "value": [4, 4]})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": l, "path": "masks/#1/expansion", "value": 3})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": l, "path": "masks/#1/opacity", "value": 50})).unwrap();
|
||||
assert_eq!(prop(&s, l, "masks/#1/opacity").value, KV::Scalar(50.0));
|
||||
s.execute("mask.removeAll", json!({"layer": l})).unwrap();
|
||||
assert!(s.active_comp().unwrap().layers[0].masks().unwrap().children.is_empty());
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.active_comp().unwrap().layers[0].masks().unwrap().children.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_click_stopwatch_toggles_a_self_reference_expression() {
|
||||
let (mut s, l) = setup();
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/opacity"})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/opacity").expr.unwrap().text, "transform.opacity");
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/opacity", "enabled": false})).unwrap();
|
||||
assert!(!prop(&s, l, "transform/opacity").expr.unwrap().enabled);
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/opacity", "enabled": true})).unwrap();
|
||||
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/opacity"})).unwrap();
|
||||
assert!(prop(&s, l, "transform/opacity").expr.is_none());
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(prop(&s, l, "transform/opacity").expr.unwrap().enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_comp_and_key_times_stay_frame_aligned() {
|
||||
let aligned = |fr: effectcraft_time::FrameRate, t: effectcraft_time::Tick| fr.snap(t) == t;
|
||||
// The demo project: every comp duration, layer in/out/start and key time is on a frame.
|
||||
let mut s = Session::default();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
for (_, c) in s.project.comps() {
|
||||
let fr = c.frame_rate;
|
||||
assert!(aligned(fr, c.duration), "duration {:?}", c.duration);
|
||||
for l in &c.layers {
|
||||
for t in [l.in_point, l.out_point, l.start_time] {
|
||||
assert!(aligned(fr, t), "{} {t:?}", l.name);
|
||||
}
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
for k in &pr.keys {
|
||||
assert!(aligned(fr, l.comp_time(k.time)), "{} {}", l.name, pr.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let lower = s.active_comp().unwrap().layer_by_name("Lower Third").unwrap();
|
||||
let fr = s.active_comp().unwrap().frame_rate;
|
||||
assert_eq!(fr.frame_at(lower.in_point), 150, "5 s at 29.97 is frame 150 (0:00:05:00)");
|
||||
// Commands snap: comp duration, layer timing, key times.
|
||||
s.execute("comp.new", json!({"name": "F", "frameRate": 29.97, "duration": 10.0})).unwrap();
|
||||
let c = s.active_comp().unwrap();
|
||||
assert_eq!(c.frame_rate.frame_at(c.duration), 300);
|
||||
assert!(aligned(c.frame_rate, c.duration));
|
||||
let l = s.execute("layer.newSolid", json!({"color": "#fff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.timing", json!({"layers": [l], "in": 1.01, "out": 3.3333, "delta": 0.02})).unwrap();
|
||||
let ly = s.active_comp().unwrap().layers[0].clone();
|
||||
let fr = s.active_comp().unwrap().frame_rate;
|
||||
for t in [ly.in_point, ly.out_point, ly.start_time] {
|
||||
assert!(aligned(fr, t), "{t:?}");
|
||||
}
|
||||
s.execute("prop.addKey", json!({"layer": l, "path": "transform/opacity", "time": 1.2345, "value": 10})).unwrap();
|
||||
let k = prop(&s, l, "transform/opacity").keys[0].time;
|
||||
assert!(aligned(fr, ly.comp_time(k)));
|
||||
// Layer shifted one frame (delta 0.02 s rounds to 1 frame): 1.2345 s + 1 frame -> frame 38.
|
||||
assert_eq!(fr.frame_at(ly.comp_time(k)), 38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_set_snaps_to_the_nearest_frame_and_ae_timecode() {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "T", "width": 100, "height": 100, "frameRate": 29.97, "duration": 10})).unwrap();
|
||||
let r = s.execute("time.set", json!({"time": 2.5})).unwrap();
|
||||
assert_eq!(r["frame"], 75);
|
||||
let fr = s.active_comp().unwrap().frame_rate;
|
||||
assert_eq!(effectcraft_time::format_timecode_ae(75, fr, false), "0:00:02:15");
|
||||
assert_eq!(effectcraft_time::format_timecode_ae(75, fr, true), "0;00;02;15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_dimensions_split_and_rejoin() {
|
||||
let (mut s, l) = setup();
|
||||
animate(&mut s, l, "transform/position", &[(0.0, json!([0, 100])), (2.0, json!([200, 50]))]);
|
||||
s.execute("prop.separateDimensions", json!({"layer": l})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let x = prop(s, l, "transform/positionX");
|
||||
let y = prop(s, l, "transform/positionY");
|
||||
assert_eq!(x.keys.len(), 2);
|
||||
assert_eq!(y.keys[1].value, KV::Scalar(50.0));
|
||||
// The layer still renders at the same place (render sees the separated values).
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let comp = s.project.comp(cid).unwrap();
|
||||
let layer = &comp.layers[0];
|
||||
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, effectcraft_time::Tick::from_seconds_f64(1.0));
|
||||
let p = ctx.value(layer, layer.transform().unwrap().get("position").unwrap()).as_vec3();
|
||||
assert!((p[0] - 100.0).abs() < 1e-6 && (p[1] - 75.0).abs() < 1e-6, "{p:?}");
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert!(s.active_comp().unwrap().layers[0].transform().unwrap().get("positionX").is_none()));
|
||||
// X and Y animate independently.
|
||||
s.execute("keys.select", json!({"keys": []})).unwrap();
|
||||
s.execute("prop.select", json!({"layer": l, "path": "transform/positionX"})).unwrap();
|
||||
s.execute("keys.easyEase", json!({})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/positionY").keys[0].out_interp, Interp::Linear);
|
||||
// Setting Position (viewer drags) writes X/Y.
|
||||
s.execute("time.set", json!({"time": 3.0})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": l, "path": "transform/position", "value": [7, 8, 0]})).unwrap();
|
||||
assert_eq!(prop(&s, l, "transform/positionX").keys.len(), 3);
|
||||
// Re-join: one Position with keys at the union of times.
|
||||
s.execute("prop.separateDimensions", json!({"layer": l})).unwrap();
|
||||
let p = prop(&s, l, "transform/position");
|
||||
assert_eq!(p.keys.len(), 3);
|
||||
assert_eq!(p.keys[2].value, KV::Vec3([7.0, 8.0, 0.0]));
|
||||
assert!(s.active_comp().unwrap().layers[0].transform().unwrap().get("positionX").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parenting_keeps_the_layer_in_place() {
|
||||
let (mut s, child) = setup();
|
||||
let r = s.execute("layer.newNull", json!({})).unwrap();
|
||||
let par = r["layer"].as_u64().unwrap();
|
||||
s.execute("prop.set", json!({"layer": par, "path": "transform/position", "value": [300, 200]})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": par, "path": "transform/rotation", "value": 90})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": par, "path": "transform/scale", "value": [200, 200]})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": child, "path": "transform/position", "value": [100, 50]})).unwrap();
|
||||
let world = |s: &Session| {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let comp = s.project.comp(cid).unwrap();
|
||||
let l = comp.layer(effectcraft_project::LayerId(child)).unwrap();
|
||||
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, effectcraft_time::Tick::ZERO);
|
||||
let (m, _) = ctx.layer_to_comp(l);
|
||||
let a = m.apply(effectcraft_geom::vec2(50.0, 50.0));
|
||||
let b = m.apply(effectcraft_geom::vec2(100.0, 50.0));
|
||||
(a, (b.y - a.y).atan2(b.x - a.x).to_degrees(), (b.x - a.x).hypot(b.y - a.y))
|
||||
};
|
||||
let before = world(&s);
|
||||
s.execute("layer.setParent", json!({"layers": [child], "parent": par})).unwrap();
|
||||
let after = world(&s);
|
||||
assert!((before.0.x - after.0.x).abs() < 1e-6 && (before.0.y - after.0.y).abs() < 1e-6, "{before:?} {after:?}");
|
||||
assert!((before.1 - after.1).abs() < 1e-6 && (before.2 - after.2).abs() < 1e-6);
|
||||
assert!((prop(&s, child, "transform/rotation").value.as_f64() + 90.0).abs() < 1e-9);
|
||||
// Unparenting restores comp-space values.
|
||||
s.execute("layer.setParent", json!({"layers": [child], "parent": null})).unwrap();
|
||||
let p = prop(&s, child, "transform/position").value.as_vec3();
|
||||
assert!((p[0] - 100.0).abs() < 1e-6 && (p[1] - 50.0).abs() < 1e-6, "{p:?}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.active_comp().unwrap().layer(effectcraft_project::LayerId(child)).unwrap().parent.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_whip_generates_ae_reference_expressions() {
|
||||
let (mut s, l) = setup();
|
||||
let r = s.execute("layer.newSolid", json!({"name": "Other", "color": "#00ff00"})).unwrap();
|
||||
let o = r["layer"].as_u64().unwrap();
|
||||
s.execute("effect.apply", json!({"layer": o, "effect": "Gaussian Blur"})).unwrap();
|
||||
s.execute("layer.addMask", json!({"layer": o})).unwrap();
|
||||
let cases = [
|
||||
("transform/opacity", json!({"layer": o, "path": "transform/opacity"}), "thisComp.layer(\"Other\").transform.opacity"),
|
||||
("transform/rotation", json!({"layer": l, "path": "transform/opacity"}), "transform.opacity"),
|
||||
("transform/rotation", json!({"layer": o, "path": "effects/#1/blurriness"}), "thisComp.layer(\"Other\").effect(\"Gaussian Blur\")(\"Blurriness\")"),
|
||||
("transform/opacity", json!({"layer": o, "path": "masks/#1/feather"}), "thisComp.layer(\"Other\").mask(\"Mask 1\").maskFeather[0]"),
|
||||
("transform/scale", json!({"layer": o, "path": "transform/rotation"}), "temp = thisComp.layer(\"Other\").transform.rotation;\n[temp, temp]"),
|
||||
("transform/position", json!({"layer": o, "path": "transform/position"}), "thisComp.layer(\"Other\").transform.position"),
|
||||
];
|
||||
for (path, target, want) in cases {
|
||||
let got = s.execute("prop.pickWhip", json!({"layer": l, "path": path, "target": target})).unwrap();
|
||||
assert_eq!(got, json!(want));
|
||||
assert_eq!(prop(&s, l, path).expr.unwrap().text, want);
|
||||
}
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_ne!(prop(&s, l, "transform/position").expr.map(|e| e.text), Some("thisComp.layer(\"Other\").transform.position".into()));
|
||||
assert!(s.execute("prop.pickWhip", json!({"layer": l, "path": "transform/opacity", "target": {"layer": l, "path": "transform/opacity"}})).is_err());
|
||||
}
|
||||
|
||||
/// Outer comp (4 s) containing a precomp whose 10×10 white solid moves x = 10 + 20·t (t in s).
|
||||
/// Returns (session, precomp layer id in the outer comp).
|
||||
fn precomp_setup() -> (Session, u64) {
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Inner", "width": 100, "height": 100, "frameRate": 30, "duration": 4})).unwrap();
|
||||
let r = s.execute("layer.newSolid", json!({"color": "#ffffff", "width": 10, "height": 10})).unwrap();
|
||||
let l = r["layer"].as_u64().unwrap();
|
||||
animate(&mut s, l, "transform/position", &[(0.0, json!([10, 50])), (4.0, json!([90, 50]))]);
|
||||
s.execute("comp.new", json!({"name": "Outer", "width": 100, "height": 100, "frameRate": 30, "duration": 4})).unwrap();
|
||||
let r = s.execute("layer.addItem", json!({"item": "Inner"})).unwrap();
|
||||
let pl = r["layer"].as_u64().unwrap();
|
||||
s.execute("layer.select", json!({"layers": [pl]})).unwrap();
|
||||
(s, pl)
|
||||
}
|
||||
|
||||
/// X of the moving square's centre in the outer comp at `t`.
|
||||
fn square_x(s: &Session, t: f64) -> f64 {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let img = s.render(cid, effectcraft_time::Tick::from_seconds_f64(t), effectcraft_render::RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let xs: Vec<usize> = (0..img.width as usize).filter(|x| img.get(*x as i64, 50)[3] > 0.5).collect();
|
||||
assert!(!xs.is_empty(), "nothing drawn at {t}");
|
||||
(xs[0] + xs[xs.len() - 1]) as f64 / 2.0 + 0.5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_remap_enable_freeze_and_disable() {
|
||||
let (mut s, l) = precomp_setup();
|
||||
assert!((square_x(&s, 1.0) - 30.0).abs() < 1.5);
|
||||
s.execute("layer.enableTimeRemap", json!({})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let p = prop(s, l, "timeRemap");
|
||||
assert_eq!(p.keys.len(), 2);
|
||||
assert_eq!(p.keys[1].value, KV::Scalar(4.0));
|
||||
// Remapping at identity shows the same frames.
|
||||
assert!((square_x(s, 1.0) - 30.0).abs() < 1.5);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert!(s.active_comp().unwrap().layers[0].props.get("timeRemap").is_none()));
|
||||
// Remap the first key to show source time 3 s at comp time 0.
|
||||
s.execute("keys.set", json!({"layer": l, "path": "timeRemap", "time": 0.0, "value": 3.0})).unwrap();
|
||||
assert!((square_x(&s, 0.0) - 70.0).abs() < 1.5, "{}", square_x(&s, 0.0));
|
||||
// Freeze Frame at 2 s: one hold key; every frame shows source time 2 s.
|
||||
s.execute("time.set", json!({"time": 2.0})).unwrap();
|
||||
s.execute("keys.set", json!({"layer": l, "path": "timeRemap", "time": 0.0, "value": 0.0})).unwrap();
|
||||
s.execute("layer.freezeFrame", json!({})).unwrap();
|
||||
let p = prop(&s, l, "timeRemap");
|
||||
assert_eq!(p.keys.len(), 1);
|
||||
assert_eq!(p.keys[0].out_interp, Interp::Hold);
|
||||
for t in [0.0, 1.0, 3.5] {
|
||||
assert!((square_x(&s, t) - 50.0).abs() < 1.5, "{t}: {}", square_x(&s, t));
|
||||
}
|
||||
// Ctrl+Alt+T again disables remapping.
|
||||
s.execute("layer.enableTimeRemap", json!({})).unwrap();
|
||||
assert!((square_x(&s, 1.0) - 30.0).abs() < 1.5);
|
||||
// Solids can't be remapped.
|
||||
let r = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
|
||||
assert!(s.execute("layer.enableTimeRemap", json!({"layers": [r["layer"]]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeze_on_last_frame_extends_the_layer() {
|
||||
let (mut s, l) = precomp_setup();
|
||||
s.execute("layer.timing", json!({"layers": [l], "out": 2.0})).unwrap();
|
||||
s.execute("layer.freezeOnLastFrame", json!({})).unwrap();
|
||||
let layer = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(layer.out_point, s.active_comp().unwrap().duration);
|
||||
// Plays normally, then holds the frame before the old out point.
|
||||
assert!((square_x(&s, 1.0) - 30.0).abs() < 1.5);
|
||||
let hold = 10.0 + 20.0 * (2.0 - 1.0 / 30.0);
|
||||
assert!((square_x(&s, 3.5) - hold).abs() < 1.5, "{}", square_x(&s, 3.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_reverse_layer_plays_backwards_and_round_trips() {
|
||||
let (mut s, l) = precomp_setup();
|
||||
let before = s.active_comp().unwrap().layers[0].clone();
|
||||
s.execute("layer.timeReverse", json!({})).unwrap();
|
||||
let after = |s: &Session| {
|
||||
let ly = &s.active_comp().unwrap().layers[0];
|
||||
assert_eq!(ly.stretch, -100.0);
|
||||
assert_eq!((ly.in_point, ly.out_point), (before.in_point, before.out_point));
|
||||
// First frame shows the last source frame; the end shows the start.
|
||||
let last = 10.0 + 20.0 * (4.0 - 1.0 / 30.0);
|
||||
assert!((square_x(s, 0.0) - last).abs() < 1.5, "{}", square_x(s, 0.0));
|
||||
assert!((square_x(s, 4.0 - 1.0 / 30.0) - 10.0).abs() < 1.5);
|
||||
};
|
||||
undo_redo_roundtrip(&mut s, after, |s| assert_eq!(s.active_comp().unwrap().layers[0].stretch, 100.0));
|
||||
// Reversing twice restores normal playback.
|
||||
s.execute("layer.timeReverse", json!({"layers": [l]})).unwrap();
|
||||
let ly = &s.active_comp().unwrap().layers[0];
|
||||
assert_eq!(ly.stretch, 100.0);
|
||||
assert_eq!(ly.start_time, before.start_time);
|
||||
assert!((square_x(&s, 1.0) - 30.0).abs() < 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_stretch_holds_in_current_or_out() {
|
||||
let (mut s, l) = precomp_setup();
|
||||
s.execute("layer.timeStretch", json!({"percent": 50})).unwrap();
|
||||
let ly = s.active_comp().unwrap().layers[0].clone();
|
||||
assert_eq!(ly.stretch, 50.0);
|
||||
assert!((ly.out_point.seconds() - 2.0).abs() < 1e-6);
|
||||
// Twice as fast: comp 1 s shows source 2 s.
|
||||
assert!((square_x(&s, 1.0) - 50.0).abs() < 1.5);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
// Hold the current frame (2 s) in place while doubling the duration.
|
||||
s.execute("time.set", json!({"time": 2.0})).unwrap();
|
||||
s.execute("layer.timeStretch", json!({"layers": [l], "duration": 8.0, "hold": "current"})).unwrap();
|
||||
let ly = s.active_comp().unwrap().layers[0].clone();
|
||||
assert!((ly.stretch - 200.0).abs() < 1e-6);
|
||||
assert!((ly.in_point.seconds() + 2.0).abs() < 1e-6, "{}", ly.in_point.seconds());
|
||||
assert!((square_x(&s, 2.0) - 50.0).abs() < 1.5);
|
||||
// Hold the out point.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("layer.timeStretch", json!({"layers": [l], "percent": 50, "hold": "out"})).unwrap();
|
||||
let ly = s.active_comp().unwrap().layers[0].clone();
|
||||
assert!((ly.out_point.seconds() - 4.0).abs() < 1e-6 && (ly.in_point.seconds() - 2.0).abs() < 1e-6);
|
||||
assert!(s.execute("layer.timeStretch", json!({"layers": [l], "percent": 0})).is_err());
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "effectcraft-export"
|
||||
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC) and ProRes MOV (+PCM) via FilmCraft's pure-Rust encoders, PNG/JPEG/TIFF/EXR sequences, animated GIF"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
effectcraft-time = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
effectcraft-raster = { workspace = true }
|
||||
effectcraft-render = { workspace = true }
|
||||
filmcraft-h264enc = { workspace = true }
|
||||
filmcraft-prores = { workspace = true }
|
||||
filmcraft-aac = { workspace = true }
|
||||
filmcraft-isobmff = { workspace = true }
|
||||
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr"] }
|
||||
gif = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
effectcraft-media = { workspace = true }
|
||||
effectcraft-color = { workspace = true }
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Movie export: FilmCraft H.264 → MP4 (+ AAC) and ProRes → MOV (+ PCM), muxed by
|
||||
//! FilmCraft's ISO BMFF / QuickTime writer.
|
||||
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use effectcraft_project::Comp;
|
||||
use effectcraft_project::render_queue::{Channels, OutputFormat, ProResProfile};
|
||||
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
use filmcraft_isobmff::{Brand, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{ExportError, Job, Report, Result, State, batch_size, render_frame, rgba8, wants_audio};
|
||||
|
||||
fn enc(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Encode(e.to_string())
|
||||
}
|
||||
fn mux_err(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Io(e.to_string())
|
||||
}
|
||||
|
||||
struct Packet {
|
||||
data: Vec<u8>,
|
||||
key: bool,
|
||||
/// pts − dts in the track timescale.
|
||||
cto: i32,
|
||||
}
|
||||
|
||||
trait VideoEncoder {
|
||||
fn sample_entry(&self) -> SampleEntry;
|
||||
fn encode(&mut self, rgba: &[u8], index: u64) -> Result<Vec<Packet>>;
|
||||
fn flush(&mut self) -> Result<Vec<Packet>>;
|
||||
/// Edit-list media start (B-frame delay) in the track timescale.
|
||||
fn media_start(&self) -> Option<i64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- H.264
|
||||
|
||||
struct H264 {
|
||||
enc: filmcraft_h264enc::Encoder,
|
||||
w: u32,
|
||||
h: u32,
|
||||
rate: FrameRate,
|
||||
y: Vec<u8>,
|
||||
u: Vec<u8>,
|
||||
v: Vec<u8>,
|
||||
}
|
||||
|
||||
impl H264 {
|
||||
fn new(w: u32, h: u32, rate: FrameRate, kbps: u32) -> Result<H264> {
|
||||
let mut cfg = filmcraft_h264enc::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
|
||||
cfg.format = filmcraft_h264enc::PacketFormat::LengthPrefixed;
|
||||
cfg.aud = false;
|
||||
cfg.keyint = (rate.as_f64() * 2.0).round().max(1.0) as u32;
|
||||
let kbps = kbps.max(100);
|
||||
cfg.rate = filmcraft_h264enc::RateControl::Vbr { target_kbps: kbps, max_kbps: kbps * 3 / 2 };
|
||||
let enc = filmcraft_h264enc::Encoder::new(cfg).map_err(enc)?;
|
||||
Ok(H264 { enc, w, h, rate, y: vec![], u: vec![], v: vec![] })
|
||||
}
|
||||
fn packets(&self, ps: Vec<filmcraft_h264enc::Packet>) -> Vec<Packet> {
|
||||
ps.into_iter().map(|p| Packet { data: p.data, key: p.keyframe, cto: (p.pts - p.dts) as i32 }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for H264 {
|
||||
fn sample_entry(&self) -> SampleEntry {
|
||||
let cfg = filmcraft_isobmff::AvcConfig::parse(&self.enc.avcc()).unwrap_or_else(|_| {
|
||||
let (sps, pps) = self.enc.sps_pps();
|
||||
filmcraft_isobmff::AvcConfig::new(vec![sps], vec![pps], 4)
|
||||
});
|
||||
SampleEntry::avc(cfg, self.w as u16, self.h as u16)
|
||||
}
|
||||
fn encode(&mut self, rgba: &[u8], index: u64) -> Result<Vec<Packet>> {
|
||||
rgba_to_yuv420(rgba, self.w as usize, self.h as usize, &mut self.y, &mut self.u, &mut self.v);
|
||||
let cw = (self.w as usize).div_ceil(2);
|
||||
let frame = filmcraft_h264enc::YuvFrame { y: &self.y, u: &self.u, v: &self.v, y_stride: self.w as usize, uv_stride: cw };
|
||||
let ps = self.enc.try_encode(&frame, index as i64 * self.rate.den).map_err(enc)?;
|
||||
Ok(self.packets(ps))
|
||||
}
|
||||
fn flush(&mut self) -> Result<Vec<Packet>> {
|
||||
let ps = self.enc.flush();
|
||||
Ok(self.packets(ps))
|
||||
}
|
||||
fn media_start(&self) -> Option<i64> {
|
||||
(self.enc.delay() > 0).then_some(self.rate.den)
|
||||
}
|
||||
}
|
||||
|
||||
/// BT.709 limited-range 8-bit 4:2:0 from RGBA8 (2×2 chroma average; alpha ignored).
|
||||
pub(crate) fn rgba_to_yuv420(rgba: &[u8], w: usize, h: usize, y: &mut Vec<u8>, u: &mut Vec<u8>, v: &mut Vec<u8>) {
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
y.resize(w * h, 0);
|
||||
u.resize(cw * ch, 0);
|
||||
v.resize(cw * ch, 0);
|
||||
y.par_chunks_mut(w * 2).zip(u.par_chunks_mut(cw).zip(v.par_chunks_mut(cw))).enumerate().for_each(|(cy, (yr, (ur, vr)))| {
|
||||
let rows = yr.len() / w;
|
||||
let mut acc = vec![(0f32, 0f32, 0f32); cw];
|
||||
for dy in 0..rows {
|
||||
let src = &rgba[(cy * 2 + dy) * w * 4..][..w * 4];
|
||||
for x in 0..w {
|
||||
let (r, g, b) = (src[x * 4] as f32 / 255.0, src[x * 4 + 1] as f32 / 255.0, src[x * 4 + 2] as f32 / 255.0);
|
||||
let l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
yr[dy * w + x] = (16.0 + 219.0 * l).round().clamp(1.0, 254.0) as u8;
|
||||
let a = &mut acc[x / 2];
|
||||
a.0 += (b - l) / 1.8556;
|
||||
a.1 += (r - l) / 1.5748;
|
||||
a.2 += 1.0;
|
||||
}
|
||||
}
|
||||
for (cx, a) in acc.iter().enumerate() {
|
||||
ur[cx] = (128.0 + 224.0 * a.0 / a.2).round().clamp(1.0, 254.0) as u8;
|
||||
vr[cx] = (128.0 + 224.0 * a.1 / a.2).round().clamp(1.0, 254.0) as u8;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- ProRes
|
||||
|
||||
struct ProRes {
|
||||
enc: filmcraft_prores::Encoder,
|
||||
profile: filmcraft_prores::Profile,
|
||||
w: u32,
|
||||
h: u32,
|
||||
alpha: bool,
|
||||
}
|
||||
|
||||
fn prores_profile(p: ProResProfile) -> filmcraft_prores::Profile {
|
||||
use filmcraft_prores::Profile;
|
||||
match p {
|
||||
ProResProfile::Proxy => Profile::Proxy,
|
||||
ProResProfile::Lt => Profile::Lt,
|
||||
ProResProfile::Standard => Profile::Standard,
|
||||
ProResProfile::Hq => Profile::Hq,
|
||||
ProResProfile::P4444 => Profile::P4444,
|
||||
ProResProfile::P4444Xq => Profile::P4444Xq,
|
||||
}
|
||||
}
|
||||
|
||||
impl ProRes {
|
||||
fn new(w: u32, h: u32, profile: ProResProfile, channels: Channels) -> ProRes {
|
||||
// Alpha needs a 4444 flavour.
|
||||
let profile = if channels == Channels::Rgba && !profile.is_4444() { ProResProfile::P4444 } else { profile };
|
||||
let profile = prores_profile(profile);
|
||||
let alpha = channels == Channels::Rgba;
|
||||
let mut cfg = filmcraft_prores::EncoderConfig::new(profile, w, h);
|
||||
cfg.encode_alpha = alpha;
|
||||
ProRes { enc: filmcraft_prores::Encoder::with_config(cfg), profile, w, h, alpha }
|
||||
}
|
||||
fn is_444(&self) -> bool {
|
||||
matches!(self.profile, filmcraft_prores::Profile::P4444 | filmcraft_prores::Profile::P4444Xq)
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for ProRes {
|
||||
fn sample_entry(&self) -> SampleEntry {
|
||||
SampleEntry::prores(FourCc(self.profile.fourcc()), self.w as u16, self.h as u16)
|
||||
}
|
||||
fn encode(&mut self, rgba: &[u8], _index: u64) -> Result<Vec<Packet>> {
|
||||
let chroma = if self.is_444() { filmcraft_prores::ChromaFormat::Yuv444 } else { filmcraft_prores::ChromaFormat::Yuv422 };
|
||||
let mut fr = filmcraft_prores::Frame::new(self.w, self.h, chroma, 10, self.alpha);
|
||||
rgba_to_yuv_10(rgba, self.w as usize, self.h as usize, self.is_444(), &mut fr.y, &mut fr.cb, &mut fr.cr);
|
||||
if let Some(a) = fr.alpha.as_mut() {
|
||||
for (d, s) in a.iter_mut().zip(rgba.chunks_exact(4)) {
|
||||
*d = ((s[3] as u32 * 1023 + 127) / 255) as u16;
|
||||
}
|
||||
}
|
||||
let data = self.enc.encode(&fr).map_err(enc)?;
|
||||
Ok(vec![Packet { data, key: true, cto: 0 }])
|
||||
}
|
||||
fn flush(&mut self) -> Result<Vec<Packet>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
/// BT.709 limited-range 10-bit 4:2:2 (horizontal chroma average) or 4:4:4 from RGBA8.
|
||||
fn rgba_to_yuv_10(rgba: &[u8], w: usize, h: usize, full_chroma: bool, y: &mut [u16], cb: &mut [u16], cr: &mut [u16]) {
|
||||
let cw = if full_chroma { w } else { w.div_ceil(2) };
|
||||
debug_assert!(y.len() >= w * h && rgba.len() >= w * h * 4);
|
||||
y.par_chunks_mut(w).zip(cb.par_chunks_mut(cw).zip(cr.par_chunks_mut(cw))).enumerate().for_each(|(row, (yr, (cbr, crr)))| {
|
||||
let src = &rgba[row * w * 4..(row + 1) * w * 4];
|
||||
let mut us = vec![0f32; w];
|
||||
let mut vs = vec![0f32; w];
|
||||
for x in 0..w {
|
||||
let (r, g, b) = (src[x * 4] as f32 / 255.0, src[x * 4 + 1] as f32 / 255.0, src[x * 4 + 2] as f32 / 255.0);
|
||||
let l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
yr[x] = (64.0 + 876.0 * l).round().clamp(4.0, 1019.0) as u16;
|
||||
us[x] = (b - l) / 1.8556;
|
||||
vs[x] = (r - l) / 1.5748;
|
||||
}
|
||||
for cx in 0..cw {
|
||||
let (u, v) = if full_chroma {
|
||||
(us[cx], vs[cx])
|
||||
} else {
|
||||
let (a, b2) = (cx * 2, (cx * 2 + 1).min(w - 1));
|
||||
((us[a] + us[b2]) * 0.5, (vs[a] + vs[b2]) * 0.5)
|
||||
};
|
||||
cbr[cx] = (512.0 + 896.0 * u).round().clamp(4.0, 1019.0) as u16;
|
||||
crr[cx] = (512.0 + 896.0 * v).round().clamp(4.0, 1019.0) as u16;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- audio
|
||||
|
||||
enum Audio {
|
||||
Aac(Box<filmcraft_aac::Encoder>),
|
||||
Pcm,
|
||||
}
|
||||
|
||||
const AUDIO_CHANNELS: u32 = 2;
|
||||
|
||||
fn deinterleave(buf: &[f32]) -> [Vec<f32>; 2] {
|
||||
let l = buf.chunks_exact(2).map(|p| p[0]).collect();
|
||||
let r = buf.chunks_exact(2).map(|p| p[1]).collect();
|
||||
[l, r]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the movie
|
||||
|
||||
type Writer = Mp4Writer<BufWriter<std::fs::File>>;
|
||||
|
||||
pub(crate) fn movie(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
let rate = job.settings.rate(comp);
|
||||
let fmt = job.output.format;
|
||||
let channels = if fmt == OutputFormat::ProRes { job.output.channels } else { Channels::Rgb };
|
||||
let mut venc: Box<dyn VideoEncoder> = match fmt {
|
||||
OutputFormat::H264 => Box::new(H264::new(w, h, rate, job.output.bitrate_kbps)?),
|
||||
_ => Box::new(ProRes::new(w, h, job.output.prores_profile, channels)),
|
||||
};
|
||||
let brand = if fmt == OutputFormat::H264 { Brand::Mp4 } else { Brand::Mov };
|
||||
let batch = batch_size();
|
||||
let render = |k: u64| -> Vec<u8> { rgba8(&render_frame(job, comp, k), comp, channels, w, h) };
|
||||
|
||||
// Encode the first batch before creating tracks: encoders finalise their config on frame 1.
|
||||
let first_end = batch.min(st.total);
|
||||
let first: Vec<Vec<u8>> = (0..first_end).into_par_iter().map(render).collect();
|
||||
let mut pending = Vec::new();
|
||||
for (k, px) in first.iter().enumerate() {
|
||||
pending.extend(venc.encode(px, k as u64)?);
|
||||
}
|
||||
drop(first);
|
||||
st.advance(first_end)?;
|
||||
|
||||
let file = std::fs::File::create(job.path).map_err(mux_err)?;
|
||||
let opts = WriterOptions::new(brand);
|
||||
let movie_ts = opts.movie_timescale.max(1) as i128;
|
||||
let mut mux: Writer = Mp4Writer::new(BufWriter::new(file), opts).map_err(mux_err)?;
|
||||
let mut vcfg = TrackConfig::new(venc.sample_entry(), rate.num as u32);
|
||||
if let Some(start) = venc.media_start() {
|
||||
// An explicit edit: the convenience `media_start` edit would subtract the B-frame delay
|
||||
// from the media duration and drop the last frame.
|
||||
let frames_ts = st.total as i128 * rate.den as i128;
|
||||
let seg = (frames_ts * movie_ts + rate.num as i128 / 2) / rate.num as i128;
|
||||
vcfg.edits = vec![filmcraft_isobmff::Edit { segment_duration: seg as u64, media_time: start, media_rate: 0x10000 }];
|
||||
}
|
||||
let vt = mux.add_track(vcfg).map_err(mux_err)?;
|
||||
let sr = job.output.audio_sample_rate.clamp(8_000, 192_000);
|
||||
let with_audio = wants_audio(job);
|
||||
let mut audio = None;
|
||||
if with_audio {
|
||||
let (a, entry, start) = if brand == Brand::Mp4 {
|
||||
let e = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(sr, AUDIO_CHANNELS as usize, 320_000)).map_err(enc)?;
|
||||
let entry = SampleEntry::aac(e.audio_specific_config(), AUDIO_CHANNELS, sr);
|
||||
let priming = e.priming_samples() as i64;
|
||||
(Audio::Aac(Box::new(e)), entry, Some(priming))
|
||||
} else {
|
||||
let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: AUDIO_CHANNELS, sample_rate: sr as f64 };
|
||||
(Audio::Pcm, SampleEntry::pcm(pcm), None)
|
||||
};
|
||||
let mut c = TrackConfig::new(entry, sr);
|
||||
c.media_start = start;
|
||||
let at = mux.add_track(c).map_err(mux_err)?;
|
||||
audio = Some((a, at));
|
||||
}
|
||||
let (span_start, span_end) = job.settings.span(comp);
|
||||
let mut cursor = span_start.to_units_floor(sr as i64);
|
||||
|
||||
let write_video = |mux: &mut Writer, ps: Vec<Packet>| -> Result<()> {
|
||||
for p in ps {
|
||||
mux.write_sample(vt, WriteSample { data: &p.data, duration: rate.den as u32, composition_offset: p.cto, is_sync: p.key }).map_err(mux_err)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let mut write_audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> {
|
||||
let Some((a, at)) = audio.as_mut() else { return Ok(()) };
|
||||
let end = until.to_units_floor(sr as i64);
|
||||
if end <= *cursor {
|
||||
return Ok(());
|
||||
}
|
||||
let n = (end - *cursor) as usize;
|
||||
let start = Tick(((*cursor as i128 * TICKS_PER_SECOND as i128) / sr as i128) as i64);
|
||||
let buf = effectcraft_render::audio::mix_comp(job.project, job.footage, job.expr, job.comp, start, n, sr);
|
||||
*cursor = end;
|
||||
match a {
|
||||
Audio::Aac(e) => {
|
||||
let planar = deinterleave(&buf);
|
||||
let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect();
|
||||
for au in e.encode(&refs) {
|
||||
mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
Audio::Pcm => {
|
||||
let mut pcm = Vec::with_capacity(n * 4);
|
||||
for s in buf {
|
||||
pcm.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
|
||||
}
|
||||
mux.write_sample(*at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let total = st.total;
|
||||
let frame_end_time = |k: u64| -> Tick { if k >= total { span_end } else { job.settings.frame_time(comp, k) } };
|
||||
write_video(&mut mux, pending)?;
|
||||
write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?;
|
||||
let mut i = first_end;
|
||||
while i < total {
|
||||
let end = (i + batch).min(total);
|
||||
let frames: Vec<Vec<u8>> = (i..end).into_par_iter().map(render).collect();
|
||||
for (k, px) in frames.iter().enumerate() {
|
||||
let ps = venc.encode(px, i + k as u64)?;
|
||||
write_video(&mut mux, ps)?;
|
||||
}
|
||||
write_audio_until(&mut mux, frame_end_time(end), &mut cursor)?;
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
write_video(&mut mux, venc.flush()?)?;
|
||||
write_audio_until(&mut mux, span_end, &mut cursor)?;
|
||||
if let Some((Audio::Aac(e), at)) = audio.as_mut() {
|
||||
for au in e.flush() {
|
||||
mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?;
|
||||
}
|
||||
}
|
||||
let mut out = mux.finish().map_err(mux_err)?;
|
||||
out.flush().map_err(mux_err)?;
|
||||
drop(out);
|
||||
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn yuv_of_primaries() {
|
||||
let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255];
|
||||
let (mut y, mut u, mut v) = (vec![], vec![], vec![]);
|
||||
rgba_to_yuv420(&rgba, 2, 2, &mut y, &mut u, &mut v);
|
||||
assert_eq!(y[0], 235);
|
||||
assert_eq!(y[1], 16);
|
||||
assert_eq!((u.len(), v.len()), (1, 1));
|
||||
let (mut y10, mut cb, mut cr) = (vec![0u16; 4], vec![0u16; 4], vec![0u16; 4]);
|
||||
rgba_to_yuv_10(&rgba, 2, 2, true, &mut y10, &mut cb, &mut cr);
|
||||
assert_eq!(y10[0], 940);
|
||||
assert_eq!(y10[1], 64);
|
||||
assert_eq!(cb[0], 512);
|
||||
assert!(cr[2] > 900, "red has high Cr: {}", cr[2]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Render Queue jobs: render a composition's time span and write it through an output module.
|
||||
//!
|
||||
//! | Format | Container / files | Video | Alpha | Audio |
|
||||
//! |---|---|---|---|---|
|
||||
//! | H.264 | MP4 | FilmCraft H.264 High, 8-bit 4:2:0 BT.709 limited, VBR | no | AAC-LC (FilmCraft), stereo |
|
||||
//! | ProRes | QuickTime MOV | FilmCraft ProRes 422 Proxy/LT/422/HQ, 10-bit; 4444/4444 XQ 4:4:4 | 4444 (16-bit alpha coding) | 16-bit PCM, stereo |
|
||||
//! | PNG / JPEG / TIFF sequence | one file per frame | 8-bit | PNG, TIFF | — |
|
||||
//! | OpenEXR sequence | one file per frame | 32-bit float, linear light, premultiplied | yes | — |
|
||||
//! | Animated GIF | GIF89a | 256-colour palette per frame (NeuQuant) | 1-bit | — |
|
||||
//!
|
||||
//! Frames are rendered in parallel batches (rayon; one batch ≈ one frame per core) and handed to
|
||||
//! the encoder in order. Progress is reported after each batch through a callback that can cancel
|
||||
//! the job by returning `false`. Codecs and the MP4/MOV muxer are FilmCraft's pure-Rust crates
|
||||
//! (plan ADR 0001); nothing outside this crate touches them.
|
||||
//!
|
||||
//! H.264 requires even dimensions: odd output sizes are cropped by one pixel (padded when the
|
||||
//! output is a single pixel wide/high).
|
||||
|
||||
mod encode;
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderQuality, RenderSettings, sequence_path};
|
||||
use effectcraft_project::{Comp, ItemId, Project};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{ExprHost, FootageSource, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use effectcraft_project::render_queue;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExportError {
|
||||
#[error("composition not found")]
|
||||
NoComp,
|
||||
#[error("cancelled")]
|
||||
Cancelled,
|
||||
#[error("i/o: {0}")]
|
||||
Io(String),
|
||||
#[error("encode: {0}")]
|
||||
Encode(String),
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, ExportError>;
|
||||
|
||||
fn io(e: impl std::fmt::Display) -> ExportError {
|
||||
ExportError::Io(e.to_string())
|
||||
}
|
||||
|
||||
/// One export: a comp, its Render Settings and Output Module, and the resolved output path.
|
||||
pub struct Job<'a> {
|
||||
pub project: &'a Project,
|
||||
pub footage: &'a dyn FootageSource,
|
||||
pub expr: Option<&'a dyn ExprHost>,
|
||||
pub comp: ItemId,
|
||||
pub settings: &'a RenderSettings,
|
||||
pub output: &'a OutputModule,
|
||||
/// Output file. For image sequences a run of `#` (or `[#####]`) becomes the frame number; a
|
||||
/// path without one gets `_NNNNN` before the extension.
|
||||
pub path: &'a str,
|
||||
}
|
||||
|
||||
/// Progress after a batch of frames.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Progress {
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
pub elapsed: f64,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub fn fraction(&self) -> f64 {
|
||||
if self.total == 0 { 0.0 } else { self.done as f64 / self.total as f64 }
|
||||
}
|
||||
/// Estimated seconds remaining.
|
||||
pub fn remaining(&self) -> Option<f64> {
|
||||
(self.done > 0).then(|| self.elapsed / self.done as f64 * self.total.saturating_sub(self.done) as f64)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an export produced.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Report {
|
||||
/// The movie file, or the first file of a sequence.
|
||||
pub path: String,
|
||||
pub frames: u64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub seconds: f64,
|
||||
pub bytes: u64,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
/// Formats this build can write (all of them; kept as the hook for optional encoders).
|
||||
pub fn available_formats() -> Vec<OutputFormat> {
|
||||
OutputFormat::ALL.to_vec()
|
||||
}
|
||||
|
||||
/// The size of the written frames for a job (H.264 rounds to even).
|
||||
pub fn output_size(comp: &Comp, settings: &RenderSettings, output: &OutputModule) -> (u32, u32) {
|
||||
let (w, h) = settings.output_size(comp);
|
||||
output.format.coded_size(w, h)
|
||||
}
|
||||
|
||||
/// Whether the job writes an audio track.
|
||||
pub fn wants_audio(job: &Job) -> bool {
|
||||
job.output.format.supports_audio()
|
||||
&& match job.output.audio {
|
||||
AudioOutput::On => true,
|
||||
AudioOutput::Off => false,
|
||||
AudioOutput::Auto => effectcraft_render::audio::comp_has_audio(job.project, job.comp),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the export (blocking). `progress` is called after every batch; returning `false` cancels.
|
||||
pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<Report> {
|
||||
let comp = job.project.comp(job.comp).ok_or(ExportError::NoComp)?;
|
||||
let t0 = Instant::now();
|
||||
let total = job.settings.frame_count(comp);
|
||||
let mut st = State { t0, total, done: 0, progress };
|
||||
st.advance(0)?;
|
||||
if let Some(dir) = Path::new(job.path).parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir).map_err(io)?;
|
||||
}
|
||||
let (w, h) = output_size(comp, job.settings, job.output);
|
||||
let mut report = match job.output.format {
|
||||
OutputFormat::H264 | OutputFormat::ProRes => encode::movie(job, comp, w, h, &mut st)?,
|
||||
OutputFormat::Gif => gif_export(job, comp, w, h, &mut st)?,
|
||||
f if f.is_sequence() => sequence(job, comp, w, h, &mut st)?,
|
||||
f => return Err(ExportError::Unsupported(f.label().into())),
|
||||
};
|
||||
report.seconds = t0.elapsed().as_secs_f64();
|
||||
report.frames = total;
|
||||
(report.width, report.height) = (w, h);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub(crate) struct State<'p> {
|
||||
t0: Instant,
|
||||
total: u64,
|
||||
done: u64,
|
||||
progress: &'p mut dyn FnMut(&Progress) -> bool,
|
||||
}
|
||||
|
||||
impl State<'_> {
|
||||
fn snapshot(&self) -> Progress {
|
||||
Progress { done: self.done, total: self.total, elapsed: self.t0.elapsed().as_secs_f64() }
|
||||
}
|
||||
/// Count `n` more frames; `Err(Cancelled)` when the callback says stop.
|
||||
pub(crate) fn advance(&mut self, n: u64) -> Result<()> {
|
||||
self.done += n;
|
||||
let p = self.snapshot();
|
||||
if (self.progress)(&p) { Ok(()) } else { Err(ExportError::Cancelled) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames per parallel batch.
|
||||
pub(crate) fn batch_size() -> u64 {
|
||||
rayon::current_num_threads().clamp(2, 16) as u64
|
||||
}
|
||||
|
||||
/// Render output frame `i` of the job at the settings' resolution.
|
||||
pub(crate) fn render_frame(job: &Job, comp: &Comp, i: u64) -> Image {
|
||||
let t: Tick = job.settings.frame_time(comp, i);
|
||||
let opts = RenderOpts {
|
||||
scale: job.settings.resolution.clamp(0.01, 4.0),
|
||||
motion_blur: job.settings.motion_blur,
|
||||
guides: false,
|
||||
draft: job.settings.quality == RenderQuality::Draft,
|
||||
// Output renders always look through the comp's active camera.
|
||||
view: None,
|
||||
};
|
||||
let mut r = Renderer::new(job.project, job.footage, opts);
|
||||
r.expr = job.expr;
|
||||
r.comp_frame(job.comp, t)
|
||||
}
|
||||
|
||||
/// 8-bit RGBA of the requested channels (RGB: over the comp background, opaque; RGBA: straight),
|
||||
/// cropped/padded to `w`×`h`.
|
||||
pub(crate) fn rgba8(img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32) -> Vec<u8> {
|
||||
let px = match channels {
|
||||
Channels::Rgb => img.to_rgba8_over(comp.background),
|
||||
Channels::Rgba => img.to_rgba8(),
|
||||
};
|
||||
fit(px, img.width, img.height, w, h)
|
||||
}
|
||||
|
||||
fn fit(px: Vec<u8>, iw: u32, ih: u32, w: u32, h: u32) -> Vec<u8> {
|
||||
if iw == w && ih == h {
|
||||
return px;
|
||||
}
|
||||
let mut out = vec![0u8; (w * h * 4) as usize];
|
||||
for y in 0..h.min(ih) as usize {
|
||||
let n = w.min(iw) as usize * 4;
|
||||
out[y * w as usize * 4..y * w as usize * 4 + n].copy_from_slice(&px[y * iw as usize * 4..y * iw as usize * 4 + n]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The comp frame number of output frame 0 (sequence numbering follows comp frames, like AE).
|
||||
fn first_frame_number(job: &Job, comp: &Comp) -> i64 {
|
||||
job.settings.first_frame(comp)
|
||||
}
|
||||
|
||||
fn sequence(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
let f0 = first_frame_number(job, comp);
|
||||
let fmt = job.output.format;
|
||||
let channels = if fmt.supports_alpha() { job.output.channels } else { Channels::Rgb };
|
||||
let batch = batch_size();
|
||||
let mut bytes = 0u64;
|
||||
let mut i = 0;
|
||||
while i < st.total {
|
||||
let end = (i + batch).min(st.total);
|
||||
let written: Vec<Result<u64>> = (i..end)
|
||||
.into_par_iter()
|
||||
.map(|k| {
|
||||
let path = sequence_path(job.path, f0 + k as i64);
|
||||
if job.settings.skip_existing && Path::new(&path).exists() {
|
||||
return Ok(0);
|
||||
}
|
||||
let img = render_frame(job, comp, k);
|
||||
write_still(&path, fmt, &img, comp, channels, w, h, job.output.quality)?;
|
||||
Ok(std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
for r in written {
|
||||
bytes += r?;
|
||||
}
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
Ok(Report { path: sequence_path(job.path, f0), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32, quality: u8) -> Result<()> {
|
||||
use image::{ExtendedColorType, ImageEncoder, ImageFormat};
|
||||
let file = || std::fs::File::create(path).map(std::io::BufWriter::new).map_err(io);
|
||||
match fmt {
|
||||
OutputFormat::ExrSequence => {
|
||||
// Linear light, premultiplied (the EXR convention); RGB keeps alpha = 1 over the background.
|
||||
let lin = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
|
||||
let mut data = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = if x < img.width && y < img.height { img.data[img.idx(x, y)] } else { [0.0; 4] };
|
||||
let (c, a) = match channels {
|
||||
Channels::Rgba => {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let s = |c: f32| if a > 0.0 { lin((c / a).clamp(0.0, 1.0)) * a } else { 0.0 };
|
||||
([s(p[0]), s(p[1]), s(p[2])], a)
|
||||
}
|
||||
Channels::Rgb => {
|
||||
let k = 1.0 - p[3].clamp(0.0, 1.0);
|
||||
let c = |i: usize| lin((p[i] + comp.background[i] * k).clamp(0.0, 1.0));
|
||||
([c(0), c(1), c(2)], 1.0)
|
||||
}
|
||||
};
|
||||
data.extend_from_slice(&[c[0], c[1], c[2], a]);
|
||||
}
|
||||
}
|
||||
let buf = image::Rgba32FImage::from_raw(w, h, data).ok_or_else(|| ExportError::Encode("exr buffer".into()))?;
|
||||
image::DynamicImage::ImageRgba32F(buf).save_with_format(path, ImageFormat::OpenExr).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
OutputFormat::JpegSequence => {
|
||||
let px = rgba8(img, comp, Channels::Rgb, w, h);
|
||||
let rgb: Vec<u8> = px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(file()?, quality.clamp(1, 100))
|
||||
.write_image(&rgb, w, h, ExtendedColorType::Rgb8)
|
||||
.map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
OutputFormat::PngSequence | OutputFormat::TiffSequence => {
|
||||
let px = rgba8(img, comp, channels, w, h);
|
||||
let (data, ct) = match channels {
|
||||
Channels::Rgba => (px, ExtendedColorType::Rgba8),
|
||||
Channels::Rgb => (px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(), ExtendedColorType::Rgb8),
|
||||
};
|
||||
if fmt == OutputFormat::PngSequence {
|
||||
image::codecs::png::PngEncoder::new(file()?).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
} else {
|
||||
// The TIFF encoder needs Seek.
|
||||
let f = std::fs::File::create(path).map_err(io)?;
|
||||
image::codecs::tiff::TiffEncoder::new(std::io::BufWriter::new(f)).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
}
|
||||
f => Err(ExportError::Unsupported(format!("{} is not a still format", f.label()))),
|
||||
}
|
||||
}
|
||||
|
||||
fn gif_export(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {
|
||||
if w > u16::MAX as u32 || h > u16::MAX as u32 {
|
||||
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
|
||||
}
|
||||
let file = std::fs::File::create(job.path).map_err(io)?;
|
||||
let mut enc = gif::Encoder::new(std::io::BufWriter::new(file), w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
let rate = job.settings.rate(comp);
|
||||
// GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing.
|
||||
let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64;
|
||||
let mut clock = 0.0f64;
|
||||
let mut emitted = 0u64;
|
||||
let batch = batch_size();
|
||||
let mut i = 0;
|
||||
while i < st.total {
|
||||
let end = (i + batch).min(st.total);
|
||||
let frames: Vec<gif::Frame<'static>> = (i..end)
|
||||
.into_par_iter()
|
||||
.map(|k| {
|
||||
let img = render_frame(job, comp, k);
|
||||
let mut px = rgba8(&img, comp, job.output.channels, w, h);
|
||||
gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10)
|
||||
})
|
||||
.collect();
|
||||
for mut f in frames {
|
||||
clock += cs_per_frame;
|
||||
let d = (clock.round() as u64).saturating_sub(emitted).max(1);
|
||||
emitted += d;
|
||||
f.delay = d.min(u16::MAX as u64) as u16;
|
||||
if job.output.channels == Channels::Rgba {
|
||||
f.dispose = gif::DisposalMethod::Background;
|
||||
}
|
||||
enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
}
|
||||
st.advance(end - i)?;
|
||||
i = end;
|
||||
}
|
||||
drop(enc);
|
||||
let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);
|
||||
Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fit_crops_and_pads() {
|
||||
let px: Vec<u8> = (0..3 * 3 * 4).map(|v| v as u8).collect();
|
||||
let c = fit(px.clone(), 3, 3, 2, 2);
|
||||
assert_eq!(c.len(), 16);
|
||||
assert_eq!(&c[0..8], &px[0..8]);
|
||||
assert_eq!(&c[8..16], &px[12..20]);
|
||||
let p = fit(px, 3, 3, 4, 4);
|
||||
assert_eq!(p.len(), 64);
|
||||
assert_eq!(&p[12..16], &[0, 0, 0, 0]);
|
||||
assert_eq!(OutputFormat::H264.coded_size(1, 101), (2, 100));
|
||||
assert_eq!(OutputFormat::Gif.coded_size(1, 101), (1, 101));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Encode a short comp to every output format and decode it back: through EffectCraft's own
|
||||
//! media layer (FilmCraft decoders) for MP4/MOV, the `image`/`gif` crates for stills and GIF,
|
||||
//! and — when installed — ffprobe as an external oracle (skipped otherwise).
|
||||
//!
|
||||
//! The comp: 64×48 @ 10 fps, 1.2 s (12 frames), dark-blue background, a red solid of 32×48
|
||||
//! centred, starting at frame 5. So frame < 5 is background everywhere; from frame 5 the centre
|
||||
//! is red and the corners stay background.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_export::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderSettings, TimeSpan, sequence_path};
|
||||
use effectcraft_export::{Job, Progress, export};
|
||||
use effectcraft_media::MediaPool;
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{FootageSource, NoFootage};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
const W: u32 = 64;
|
||||
const H: u32 = 48;
|
||||
const BG: [f32; 3] = [0.1, 0.1, 0.4];
|
||||
const FRAMES: u64 = 12;
|
||||
|
||||
fn out_dir(name: &str) -> PathBuf {
|
||||
let d = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/export").join(name);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).expect("mkdir");
|
||||
d
|
||||
}
|
||||
|
||||
fn project(audio: Option<&Path>) -> (Project, ItemId) {
|
||||
let mut p = Project::default();
|
||||
let mut comp = Comp::new(W, H, FrameRate::new(10, 1), Tick::from_seconds_f64(1.2));
|
||||
comp.background = BG;
|
||||
let sid = p.add_item("Red", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 32, height: H, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(&mut p, &comp, "Red", LayerSource::Solid { item: sid }, (32, H), None);
|
||||
l.in_point = comp.frame_rate.tick_of(5);
|
||||
comp.layers.push(l);
|
||||
if let Some(path) = audio {
|
||||
let f = effectcraft_media::probe(path).expect("probe wav");
|
||||
let fid = p.add_item("tone.wav", Label::SeaFoam, None, ItemKind::Footage(f));
|
||||
let l = build::layer(&mut p, &comp, "tone", LayerSource::Footage { item: fid }, (0, 0), None);
|
||||
comp.layers.push(l);
|
||||
}
|
||||
let cid = p.add_item("Comp 1", Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
(p, cid)
|
||||
}
|
||||
|
||||
fn settings() -> RenderSettings {
|
||||
RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }
|
||||
}
|
||||
|
||||
fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path) -> effectcraft_export::Report {
|
||||
let s = settings();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let job = Job { project: p, footage, expr: None, comp: cid, settings: &s, output: om, path: &path };
|
||||
let mut last = Progress::default();
|
||||
let mut calls = 0;
|
||||
let r = export(&job, &mut |pr| {
|
||||
assert!(pr.done >= last.done, "progress is monotonic");
|
||||
last = *pr;
|
||||
calls += 1;
|
||||
true
|
||||
})
|
||||
.expect("export");
|
||||
assert_eq!(last.done, FRAMES);
|
||||
assert_eq!(last.total, FRAMES);
|
||||
assert!(calls >= 2);
|
||||
assert_eq!(r.frames, FRAMES);
|
||||
r
|
||||
}
|
||||
|
||||
fn px(img: &Image, x: u32, y: u32) -> [f32; 4] {
|
||||
img.data[img.idx(x, y)]
|
||||
}
|
||||
|
||||
fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol)
|
||||
}
|
||||
|
||||
/// Check a decoded (premultiplied, opaque) frame `k`.
|
||||
fn check_frame(img: &Image, k: u64, tol: f32) {
|
||||
let corner = px(img, 2, 2);
|
||||
assert!(near([corner[0], corner[1], corner[2]], BG, tol), "frame {k} corner {corner:?}");
|
||||
let c = px(img, img.width / 2, img.height / 2);
|
||||
let want = if k >= 5 { [1.0, 0.0, 0.0] } else { BG };
|
||||
assert!(near([c[0], c[1], c[2]], want, tol), "frame {k} centre {c:?} want {want:?}");
|
||||
}
|
||||
|
||||
fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Footage {
|
||||
let f = effectcraft_media::probe(path).expect("probe our output");
|
||||
assert_eq!((f.width, f.height), (W, H));
|
||||
assert!(f.has_video);
|
||||
let n = f.frame_rate.frame_at(f.duration - Tick(1)) + 1;
|
||||
assert_eq!(n as u64, frames, "frame count from duration {:?} @ {:?}", f.duration, f.frame_rate);
|
||||
let pool = MediaPool::new();
|
||||
for k in 0..frames {
|
||||
let img = pool.frame_at(&f, f.frame_rate.tick_of(k as i64)).expect("decode");
|
||||
check_frame(&img, k, tol);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
fn ffprobe(path: &Path) -> Option<String> {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,width,height,nb_read_frames,pix_fmt", "-of", "compact=p=0:nk=1"])
|
||||
.arg(path)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
panic!("ffprobe rejected {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
Some(String::from_utf8_lossy(&out.stdout).to_string())
|
||||
}
|
||||
|
||||
/// Frame `k` decoded by ffmpeg (external oracle) as RGBA, or `None` without ffmpeg.
|
||||
fn ffmpeg_frame(path: &Path, k: u64) -> Option<Image> {
|
||||
let png = path.with_extension(format!("ffmpeg-{k}.png"));
|
||||
let st = Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-loglevel", "error", "-y", "-i"])
|
||||
.arg(path)
|
||||
.args(["-vf", &format!("select=eq(n\\,{k})"), "-frames:v", "1", "-pix_fmt", "rgba"])
|
||||
.arg(&png)
|
||||
.status()
|
||||
.ok()?;
|
||||
assert!(st.success(), "ffmpeg failed to decode {}", path.display());
|
||||
let img = image::open(&png).expect("ffmpeg png").to_rgba8();
|
||||
Some(Image::from_rgba8(img.width(), img.height(), img.as_raw()))
|
||||
}
|
||||
|
||||
fn ffmpeg_check(path: &Path, tol: f32) {
|
||||
for k in [0, 4, 5, FRAMES - 1] {
|
||||
match ffmpeg_frame(path, k) {
|
||||
Some(img) => check_frame(&img, k, tol),
|
||||
None => {
|
||||
eprintln!("ffmpeg not found: skipping oracle decode");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_mp4_roundtrip() {
|
||||
let d = out_dir("h264");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule { bitrate_kbps: 4000, ..OutputModule::for_format(OutputFormat::H264) };
|
||||
let path = d.join("comp.mp4");
|
||||
let r = run(&p, cid, &NoFootage, &om, &path);
|
||||
assert!(r.bytes > 100 && !r.audio);
|
||||
decode_movie(&path, FRAMES, 0.08);
|
||||
ffmpeg_check(&path, 0.08);
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.contains("h264|64|48|yuv420p"), "{s}");
|
||||
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_odd_size_is_cropped_even() {
|
||||
let d = out_dir("h264-odd");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule::for_format(OutputFormat::H264);
|
||||
let s = RenderSettings { resolution: 31.0 / 64.0, ..settings() };
|
||||
let comp = p.comp(cid).expect("comp");
|
||||
assert_eq!(s.output_size(comp).0 % 2, 1);
|
||||
let path = d.join("odd.mp4").to_string_lossy().to_string();
|
||||
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path };
|
||||
let r = export(&job, &mut |_| true).expect("export");
|
||||
assert_eq!((r.width % 2, r.height % 2), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prores_mov_roundtrip() {
|
||||
let d = out_dir("prores");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule::for_format(OutputFormat::ProRes);
|
||||
let path = d.join("comp.mov");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
decode_movie(&path, FRAMES, 0.03);
|
||||
ffmpeg_check(&path, 0.03);
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("prores|64|48"), "{s}");
|
||||
assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prores_4444_with_alpha() {
|
||||
let d = out_dir("prores4444");
|
||||
let (p, cid) = project(None);
|
||||
let om = OutputModule { channels: Channels::Rgba, prores_profile: ProResProfile::Hq, ..OutputModule::for_format(OutputFormat::ProRes) };
|
||||
let path = d.join("alpha.mov");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
let f = effectcraft_media::probe(&path).expect("probe");
|
||||
let img = MediaPool::new().frame_at(&f, f.frame_rate.tick_of(7)).expect("decode");
|
||||
assert!(px(&img, 2, 2)[3] < 0.02, "corner transparent: {:?}", px(&img, 2, 2));
|
||||
let c = px(&img, W / 2, H / 2);
|
||||
assert!(c[3] > 0.98 && c[0] > 0.95 && c[1] < 0.05, "centre opaque red: {c:?}");
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("prores|64|48|yuva444"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
fn check_still_dir(dir: &Path, ext: &str, tol: f32, alpha: bool) {
|
||||
for k in 0..FRAMES {
|
||||
let path = sequence_path(&dir.join(format!("f_[#####].{ext}")).to_string_lossy(), k as i64);
|
||||
let img = image::open(&path).unwrap_or_else(|e| panic!("{path}: {e}")).to_rgba8();
|
||||
assert_eq!(img.dimensions(), (W, H));
|
||||
let img = Image::from_rgba8(W, H, img.as_raw());
|
||||
if alpha {
|
||||
let corner = px(&img, 2, 2);
|
||||
assert!(corner[3] < 0.01, "{path}: corner {corner:?}");
|
||||
let c = px(&img, W / 2, H / 2);
|
||||
assert_eq!(c[3] > 0.99, k >= 5, "{path}: centre {c:?}");
|
||||
} else {
|
||||
check_frame(&img, k, tol);
|
||||
}
|
||||
}
|
||||
assert!(!dir.join(format!("f_{:05}.{ext}", FRAMES)).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_sequences_roundtrip() {
|
||||
let (p, cid) = project(None);
|
||||
for (fmt, ext, tol, ch) in [
|
||||
(OutputFormat::PngSequence, "png", 0.01, Channels::Rgb),
|
||||
(OutputFormat::PngSequence, "png", 0.01, Channels::Rgba),
|
||||
(OutputFormat::JpegSequence, "jpg", 0.06, Channels::Rgb),
|
||||
(OutputFormat::TiffSequence, "tif", 0.01, Channels::Rgb),
|
||||
(OutputFormat::TiffSequence, "tif", 0.01, Channels::Rgba),
|
||||
] {
|
||||
let d = out_dir(&format!("seq-{ext}-{ch:?}"));
|
||||
let om = OutputModule { channels: ch, ..OutputModule::for_format(fmt) };
|
||||
let r = run(&p, cid, &NoFootage, &om, &d.join(format!("f_[#####].{ext}")));
|
||||
assert!(r.path.ends_with(&format!("f_00000.{ext}")), "{}", r.path);
|
||||
check_still_dir(&d, ext, tol, ch == Channels::Rgba);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exr_sequence_is_linear() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("seq-exr");
|
||||
let om = OutputModule::for_format(OutputFormat::ExrSequence);
|
||||
run(&p, cid, &NoFootage, &om, &d.join("f_[#####].exr"));
|
||||
let img = image::open(d.join("f_00000.exr")).expect("exr").to_rgba32f();
|
||||
assert_eq!(img.dimensions(), (W, H));
|
||||
let c = img.get_pixel(2, 2).0;
|
||||
// sRGB 0.4 → linear ≈ 0.133
|
||||
assert!((c[2] - 0.1329).abs() < 0.01 && (c[3] - 1.0).abs() < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_roundtrip() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("gif");
|
||||
let om = OutputModule::for_format(OutputFormat::Gif);
|
||||
let path = d.join("anim.gif");
|
||||
run(&p, cid, &NoFootage, &om, &path);
|
||||
let mut opts = gif::DecodeOptions::new();
|
||||
opts.set_color_output(gif::ColorOutput::RGBA);
|
||||
let mut dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header");
|
||||
assert_eq!((dec.width() as u32, dec.height() as u32), (W, H));
|
||||
let mut k = 0;
|
||||
let mut total_delay = 0u32;
|
||||
while let Some(f) = dec.read_next_frame().expect("frame") {
|
||||
assert_eq!((f.width as u32, f.height as u32), (W, H));
|
||||
total_delay += f.delay as u32;
|
||||
let img = Image::from_rgba8(W, H, &f.buffer);
|
||||
check_frame(&img, k, 0.06);
|
||||
k += 1;
|
||||
}
|
||||
assert_eq!(k, FRAMES);
|
||||
assert_eq!(total_delay, 120, "1.2 s in centiseconds");
|
||||
if let Some(s) = ffprobe(&path) {
|
||||
assert!(s.starts_with("gif|64|48"), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_stops_early() {
|
||||
let (p, cid) = project(None);
|
||||
let d = out_dir("cancel");
|
||||
let om = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
let s = settings();
|
||||
let path = d.join("c_[#####].png").to_string_lossy().to_string();
|
||||
let job = Job { project: &p, footage: &NoFootage, expr: None, comp: cid, settings: &s, output: &om, path: &path };
|
||||
let r = export(&job, &mut |_| false);
|
||||
assert!(matches!(r, Err(effectcraft_export::ExportError::Cancelled)));
|
||||
let written = std::fs::read_dir(&d).map(|r| r.count()).unwrap_or(0);
|
||||
assert_eq!(written, 0, "cancelled before the first batch");
|
||||
}
|
||||
|
||||
/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right).
|
||||
fn write_tone(path: &Path, secs: f64) {
|
||||
let sr = 48_000u32;
|
||||
let n = (secs * sr as f64) as usize;
|
||||
let mut data = Vec::with_capacity(n * 4);
|
||||
for i in 0..n {
|
||||
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
|
||||
data.extend_from_slice(&s.to_le_bytes());
|
||||
data.extend_from_slice(&0i16.to_le_bytes());
|
||||
}
|
||||
let mut w = Vec::new();
|
||||
w.extend_from_slice(b"RIFF");
|
||||
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
|
||||
w.extend_from_slice(b"WAVEfmt ");
|
||||
w.extend_from_slice(&16u32.to_le_bytes());
|
||||
w.extend_from_slice(&1u16.to_le_bytes());
|
||||
w.extend_from_slice(&2u16.to_le_bytes());
|
||||
w.extend_from_slice(&sr.to_le_bytes());
|
||||
w.extend_from_slice(&(sr * 4).to_le_bytes());
|
||||
w.extend_from_slice(&4u16.to_le_bytes());
|
||||
w.extend_from_slice(&16u16.to_le_bytes());
|
||||
w.extend_from_slice(b"data");
|
||||
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
w.extend_from_slice(&data);
|
||||
std::fs::write(path, w).expect("write wav");
|
||||
}
|
||||
|
||||
fn rms(v: impl Iterator<Item = f32>) -> f32 {
|
||||
let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1));
|
||||
(s / n.max(1) as f64).sqrt() as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn movies_carry_audio() {
|
||||
let d = out_dir("audio");
|
||||
let wav = d.join("tone.wav");
|
||||
write_tone(&wav, 2.0);
|
||||
let (p, cid) = project(Some(&wav));
|
||||
let pool = MediaPool::new();
|
||||
for (fmt, name) in [(OutputFormat::H264, "a.mp4"), (OutputFormat::ProRes, "a.mov")] {
|
||||
let om = OutputModule { audio: AudioOutput::Auto, ..OutputModule::for_format(fmt) };
|
||||
let path = d.join(name);
|
||||
let r = run(&p, cid, &pool, &om, &path);
|
||||
assert!(r.audio, "{name}: auto audio is on for a comp with a sound layer");
|
||||
let f = effectcraft_media::probe(&path).expect("probe");
|
||||
assert!(f.has_audio, "{name}");
|
||||
let dec = MediaPool::new();
|
||||
let s = dec.audio_samples(&f, Tick::from_seconds_f64(0.3), 24_000, 48_000);
|
||||
let (l, r) = (rms(s.iter().step_by(2).copied()), rms(s.iter().skip(1).step_by(2).copied()));
|
||||
// sine of amplitude 0.5 → RMS ≈ 0.354
|
||||
assert!((l - 0.3536).abs() < 0.03, "{name}: left RMS {l}");
|
||||
assert!(r < 0.01, "{name}: right RMS {r}");
|
||||
if Command::new("ffprobe").arg("-version").output().is_ok() {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=codec_name,channels,sample_rate", "-of", "compact=p=0:nk=1"])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("ffprobe");
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let want = if fmt == OutputFormat::H264 { "aac|48000|2" } else { "pcm_s16le|48000|2" };
|
||||
assert!(s.trim() == want, "{name}: {s}");
|
||||
}
|
||||
// Audio off.
|
||||
let om = OutputModule { audio: AudioOutput::Off, ..om };
|
||||
let path = d.join(format!("silent-{name}"));
|
||||
assert!(!run(&p, cid, &pool, &om, &path).audio);
|
||||
assert!(!effectcraft_media::probe(&path).expect("probe").has_audio);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ function __begin(t, v, c, l, path, uid, idx, fd) {
|
||||
function __finish(r) {
|
||||
r = __v(r);
|
||||
if (r !== null && typeof r === 'object' && r.__isLayer) return r.index;
|
||||
// `[temp, temp]` where temp is a property (pick-whip 1D → 2D): read the values here, while
|
||||
// host requests can still be answered and the script re-run.
|
||||
if (Array.isArray(r)) return r.map(function (x) { return __v(x); });
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ effectcraft-engine = { workspace = true }
|
||||
effectcraft-project = { workspace = true }
|
||||
effectcraft-media = { workspace = true }
|
||||
effectcraft-expr = { workspace = true }
|
||||
effectcraft-export = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
+129
-3
@@ -1,9 +1,11 @@
|
||||
//! A fully wired [`Session`]: footage decoding through `effectcraft-media` (FilmCraft's codecs),
|
||||
//! the media importer and the expression engine. Frontends (desktop, CLI, MCP, web) start here.
|
||||
//! the media importer, the expression engine and Render Queue export through
|
||||
//! `effectcraft-export` (FilmCraft's encoders). Frontends (desktop, CLI, MCP, web) start here.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_engine::{Importer, Session};
|
||||
use effectcraft_engine::project::render_queue::OutputFormat;
|
||||
use effectcraft_engine::{ExportJob, ExportResult, Exporter, Importer, Session};
|
||||
use effectcraft_project::Footage;
|
||||
|
||||
struct MediaImporter;
|
||||
@@ -14,12 +16,39 @@ impl Importer for MediaImporter {
|
||||
}
|
||||
}
|
||||
|
||||
/// A new session with media, import and expressions enabled.
|
||||
/// Render Queue export via `effectcraft-export`.
|
||||
pub struct FileExporter;
|
||||
|
||||
impl Exporter for FileExporter {
|
||||
fn formats(&self) -> Vec<OutputFormat> {
|
||||
effectcraft_export::available_formats()
|
||||
}
|
||||
fn export(&self, job: &ExportJob, progress: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
|
||||
let j = effectcraft_export::Job {
|
||||
project: job.project,
|
||||
footage: job.footage,
|
||||
expr: job.expr,
|
||||
comp: job.item.comp,
|
||||
settings: &job.item.settings,
|
||||
output: &job.item.output,
|
||||
path: job.path,
|
||||
};
|
||||
match effectcraft_export::export(&j, &mut |p| progress(p.done, p.total)) {
|
||||
Ok(r) => Ok(ExportResult { path: r.path, frames: r.frames, width: r.width, height: r.height, bytes: r.bytes, seconds: r.seconds, audio: r.audio }),
|
||||
Err(effectcraft_export::ExportError::Cancelled) => Err(effectcraft_engine::render_queue::CANCELLED.into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A new session with media, import, expressions and export enabled.
|
||||
pub fn session() -> Session {
|
||||
Session {
|
||||
exporter: Some(Arc::new(FileExporter)),
|
||||
footage: Arc::new(effectcraft_media::MediaPool::new()),
|
||||
importer: Some(Arc::new(MediaImporter)),
|
||||
expr: Some(Arc::new(effectcraft_expr::Expressions)),
|
||||
expr_check: Some(effectcraft_expr::check_syntax),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -38,4 +67,101 @@ mod tests {
|
||||
let img = s.render(cid, s.time(), effectcraft_engine::render::RenderOpts { scale: 0.25, ..Default::default() });
|
||||
assert!(img.data.iter().any(|p| p[3] > 0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_queue_exports_demo_comp() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-rq");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = super::session();
|
||||
s.execute("file.openDemoProject", json!({})).unwrap();
|
||||
let out = dir.join("[compName]_[width]x[height].[fileExtension]");
|
||||
let r = s
|
||||
.execute(
|
||||
"renderQueue.add",
|
||||
json!({"format": "h264", "output": out.to_string_lossy(), "resolution": 0.125, "timeSpan": "custom", "start": 0.0, "end": 0.4}),
|
||||
)
|
||||
.unwrap();
|
||||
let path = r["outputPath"].as_str().unwrap().to_string();
|
||||
assert!(path.ends_with("_240x134.mp4"), "{path}");
|
||||
// A second item: PNG sequence, rendered in the background.
|
||||
s.execute("renderQueue.add", json!({"format": "png", "output": dir.join("seq_[###].png").to_string_lossy(), "resolution": 0.0625, "timeSpan": "custom", "start": 0.0, "end": 0.2})).unwrap();
|
||||
let r = s.execute("renderQueue.render", json!({"wait": false})).unwrap();
|
||||
assert_eq!(r["items"].as_array().unwrap().len(), 2);
|
||||
let t0 = std::time::Instant::now();
|
||||
while s.is_rendering() {
|
||||
assert!(t0.elapsed().as_secs() < 300, "render timed out");
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
s.poll_render();
|
||||
}
|
||||
s.poll_render();
|
||||
let list = s.execute("renderQueue.list", json!({})).unwrap();
|
||||
for it in list["items"].as_array().unwrap() {
|
||||
assert_eq!(it["statusLabel"], "Done", "{it}");
|
||||
assert!(it["render_time"].as_f64().is_some());
|
||||
assert!(std::path::Path::new(it["last_output"].as_str().unwrap()).exists(), "{it}");
|
||||
}
|
||||
assert!(std::path::Path::new(&path).metadata().unwrap().len() > 500);
|
||||
assert!(dir.join("seq_000.png").exists() && dir.join("seq_005.png").exists() && !dir.join("seq_006.png").exists());
|
||||
// Rendering again needs a re-queue.
|
||||
assert!(s.execute("renderQueue.render", json!({})).is_err());
|
||||
s.execute("renderQueue.setRender", json!({"index": 1, "render": true})).unwrap();
|
||||
assert_eq!(s.project.render_queue[0].status, effectcraft_engine::project::render_queue::RenderStatus::Queued);
|
||||
}
|
||||
|
||||
/// Value of a property of layer `l` at time 0 (keys + expression).
|
||||
fn value(s: &effectcraft_engine::Session, l: u64, path: &str) -> effectcraft_engine::keyframe::Value {
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let comp = s.project.comp(cid).unwrap();
|
||||
let layer = comp.layer(effectcraft_engine::project::LayerId(l)).unwrap();
|
||||
let ctx = effectcraft_engine::render::EvalCtx { project: &s.project, comp_id: cid, comp, time: Default::default(), expr: s.expr.as_deref() };
|
||||
ctx.value(layer, layer.props.prop(path).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_whip_expressions_evaluate() {
|
||||
let mut s = super::session();
|
||||
s.execute("comp.new", json!({"name": "C", "width": 200, "height": 200, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let a = s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let b = s.execute("layer.newSolid", json!({"name": "Src", "color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("prop.set", json!({"layer": b, "path": "transform/rotation", "value": 33})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": b, "path": "transform/position", "value": [12, 34]})).unwrap();
|
||||
s.execute("effect.apply", json!({"layer": b, "effect": "Gaussian Blur"})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": b, "path": "effects/#1/blurriness", "value": 21})).unwrap();
|
||||
s.execute("layer.addMask", json!({"layer": b})).unwrap();
|
||||
s.execute("prop.set", json!({"layer": b, "path": "masks/#1/feather", "value": [7, 7]})).unwrap();
|
||||
let link = |s: &mut effectcraft_engine::Session, from: &str, to: &str| {
|
||||
s.execute("prop.pickWhip", json!({"layer": a, "path": from, "target": {"layer": b, "path": to}})).unwrap();
|
||||
};
|
||||
link(&mut s, "transform/opacity", "transform/rotation");
|
||||
assert_eq!(value(&s, a, "transform/opacity").as_f64(), 33.0);
|
||||
link(&mut s, "transform/scale", "transform/rotation");
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
let ep = effectcraft_expr::eval_property(&s.project, cid, effectcraft_engine::project::LayerId(a), "transform/scale", 0.0);
|
||||
assert!(ep.is_ok(), "{ep:?}");
|
||||
assert_eq!(value(&s, a, "transform/scale").as_vec2(), [33.0, 33.0]);
|
||||
link(&mut s, "transform/position", "transform/position");
|
||||
assert_eq!(value(&s, a, "transform/position").as_vec2(), [12.0, 34.0]);
|
||||
link(&mut s, "transform/rotation", "effects/#1/blurriness");
|
||||
assert_eq!(value(&s, a, "transform/rotation").as_f64(), 21.0);
|
||||
link(&mut s, "transform/opacity", "masks/#1/feather");
|
||||
assert_eq!(value(&s, a, "transform/opacity").as_f64(), 7.0);
|
||||
// Separated dimensions: X Position reference.
|
||||
s.execute("prop.separateDimensions", json!({"layer": b})).unwrap();
|
||||
link(&mut s, "transform/rotation", "transform/positionX");
|
||||
assert_eq!(value(&s, a, "transform/rotation").as_f64(), 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expression_syntax_errors_disable_the_expression() {
|
||||
let mut s = super::session();
|
||||
s.execute("comp.new", json!({"name": "C", "width": 100, "height": 100, "frameRate": 30, "duration": 2})).unwrap();
|
||||
let a = s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
|
||||
let r = s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "1 +* ("})).unwrap();
|
||||
assert!(r["error"].is_string(), "{r}");
|
||||
let pr = s.active_comp().unwrap().layers[0].props.prop("transform/opacity").unwrap().clone();
|
||||
assert!(!pr.expr.unwrap().enabled);
|
||||
assert_eq!(value(&s, a, "transform/opacity").as_f64(), 100.0);
|
||||
s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "50"})).unwrap();
|
||||
assert_eq!(value(&s, a, "transform/opacity").as_f64(), 50.0);
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,110 @@ fn effective_ease(keys: &[Keyframe], i: usize, d: usize, spatial: bool, out: boo
|
||||
list.get(d).or(list.first()).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The ease a key side presents in the Graph Editor and the Keyframe Velocity dialog: stored
|
||||
/// Bezier eases, auto-Bezier slopes, or the equivalent of a linear side (speed of the straight
|
||||
/// segment, 33.3 % influence). `None` for hold sides and sides without a neighbour.
|
||||
pub fn side_ease(keys: &[Keyframe], i: usize, d: usize, spatial: bool, out: bool) -> Option<Ease> {
|
||||
let k = keys.get(i)?;
|
||||
let j = if out { i + 1 } else { i.checked_sub(1)? };
|
||||
let n = keys.get(j)?;
|
||||
let interp = if out { k.out_interp } else { k.in_interp };
|
||||
if interp == Interp::Hold || (!out && n.out_interp == Interp::Hold) || !k.value.interpolates() {
|
||||
return None;
|
||||
}
|
||||
let is_spatial = spatial && matches!(k.value, Value::Vec2(_) | Value::Vec3(_));
|
||||
if interp == Interp::Linear {
|
||||
let dur = (secs(k.time) - secs(n.time)).abs().max(1e-12);
|
||||
let dv = if is_spatial {
|
||||
let (a, b) = if out { (i, j) } else { (j, i) };
|
||||
spatial_segment_length(keys, a.min(b))
|
||||
} else {
|
||||
let a = k.value.components();
|
||||
let b = n.value.components();
|
||||
let dv = b.get(d).unwrap_or(&0.0) - a.get(d).unwrap_or(&0.0);
|
||||
if out { dv } else { -dv }
|
||||
};
|
||||
return Some(Ease { speed: dv / dur, influence: 1.0 / 3.0 });
|
||||
}
|
||||
Some(effective_ease(keys, i, if is_spatial { 0 } else { d }, is_spatial, out))
|
||||
}
|
||||
|
||||
/// Arc length of the spatial segment `i` → `i + 1` (motion-path length).
|
||||
pub fn spatial_segment_length(keys: &[Keyframe], i: usize) -> f64 {
|
||||
let (Some(a), Some(b)) = (keys.get(i), keys.get(i + 1)) else { return 0.0 };
|
||||
let p0 = v3(&a.value);
|
||||
let p3 = v3(&b.value);
|
||||
let (_, out_t) = spatial_tangents(keys, i);
|
||||
let (in_t, _) = spatial_tangents(keys, i + 1);
|
||||
SpatialSeg::new([p0, [p0[0] + out_t[0], p0[1] + out_t[1], p0[2] + out_t[2]], [p3[0] + in_t[0], p3[1] + in_t[1], p3[2] + in_t[2]], p3]).length()
|
||||
}
|
||||
|
||||
/// Re-time roving keyframes: each run of roving keys between two fixed (non-roving) keys gets
|
||||
/// times proportional to the motion-path length, so the layer moves through them at one
|
||||
/// constant speed (After Effects' "Rove Across Time"). The first and last keys never rove.
|
||||
/// Returns true when any key time changed. Key order is preserved.
|
||||
pub fn retime_roving(keys: &mut [Keyframe], spatial: bool) -> bool {
|
||||
let n = keys.len();
|
||||
if n < 3 {
|
||||
for k in keys.iter_mut() {
|
||||
k.roving = false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
keys[0].roving = false;
|
||||
keys[n - 1].roving = false;
|
||||
if !keys.iter().any(|k| k.roving) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut a = 0;
|
||||
while a < n - 1 {
|
||||
let Some(b) = (a + 1..n).find(|&j| !keys[j].roving) else { break };
|
||||
if b > a + 1 {
|
||||
// Cumulative path length (spatial) or value distance (other) of the run a..=b.
|
||||
let mut acc = vec![0.0];
|
||||
for i in a..b {
|
||||
let len = if spatial && matches!(keys[i].value, Value::Vec2(_) | Value::Vec3(_)) {
|
||||
spatial_segment_length(keys, i)
|
||||
} else {
|
||||
let x = keys[i].value.components();
|
||||
let y = keys[i + 1].value.components();
|
||||
x.iter().zip(&y).map(|(p, q)| (q - p) * (q - p)).sum::<f64>().sqrt()
|
||||
};
|
||||
acc.push(acc.last().unwrap_or(&0.0) + len);
|
||||
}
|
||||
let total = *acc.last().unwrap_or(&0.0);
|
||||
let (t0, t1) = (keys[a].time, keys[b].time);
|
||||
for (o, i) in (a + 1..b).enumerate() {
|
||||
let f = if total > 1e-9 { acc[o + 1] / total } else { (o + 1) as f64 / (b - a) as f64 };
|
||||
let nt = Tick(t0.0 + ((t1.0 - t0.0) as f64 * f).round() as i64);
|
||||
if nt != keys[i].time {
|
||||
keys[i].time = nt;
|
||||
changed = true;
|
||||
}
|
||||
// Roving keys pass speed straight through.
|
||||
keys[i].in_interp = Interp::Linear;
|
||||
keys[i].out_interp = Interp::Linear;
|
||||
}
|
||||
}
|
||||
a = b;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Reverse a run of keys in time within `[first, last]` (Time-Reverse Keyframes): key `i` moves
|
||||
/// to `first + last - t` and in/out sides swap.
|
||||
pub fn time_reverse(keys: &mut [Keyframe]) {
|
||||
let (Some(first), Some(last)) = (keys.first().map(|k| k.time), keys.last().map(|k| k.time)) else { return };
|
||||
for k in keys.iter_mut() {
|
||||
k.time = Tick(first.0 + last.0 - k.time.0);
|
||||
std::mem::swap(&mut k.in_interp, &mut k.out_interp);
|
||||
std::mem::swap(&mut k.in_ease, &mut k.out_ease);
|
||||
std::mem::swap(&mut k.spatial_in, &mut k.spatial_out);
|
||||
}
|
||||
keys.reverse();
|
||||
}
|
||||
|
||||
/// Evaluate a keyframed property at `t`. `spatial` selects motion-path semantics for 2D/3D values.
|
||||
pub fn evaluate(keys: &[Keyframe], t: Tick, spatial: bool) -> Option<Value> {
|
||||
let first = keys.first()?;
|
||||
@@ -524,6 +628,50 @@ mod tests {
|
||||
assert_eq!(v.as_path().unwrap().vertices[0], [-7.5, -7.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roving_keys_get_constant_speed_times() {
|
||||
let mut keys = vec![
|
||||
Keyframe::new(s(0.0), Value::Vec2([0.0, 0.0])),
|
||||
Keyframe::new(s(0.2), Value::Vec2([300.0, 0.0])),
|
||||
Keyframe::new(s(2.0), Value::Vec2([400.0, 0.0])),
|
||||
];
|
||||
for k in &mut keys {
|
||||
k.spatial_auto = false;
|
||||
}
|
||||
keys[1].roving = true;
|
||||
assert!(retime_roving(&mut keys, true));
|
||||
// 300 of 400 px → 75 % of the 2 s span.
|
||||
assert!((keys[1].time.seconds() - 1.5).abs() < 1e-6, "{}", keys[1].time.seconds());
|
||||
let v0 = speed(&keys, s(0.5), true);
|
||||
let v1 = speed(&keys, s(1.8), true);
|
||||
assert!((v0 - 200.0).abs() < 1.0 && (v1 - 200.0).abs() < 1.0, "{v0} {v1}");
|
||||
// First/last keys can't rove.
|
||||
keys[0].roving = true;
|
||||
retime_roving(&mut keys, true);
|
||||
assert!(!keys[0].roving);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_ease_reports_linear_and_eased_sides() {
|
||||
let keys = vec![Keyframe::new(s(0.0), Value::Scalar(0.0)), Keyframe::new(s(2.0), Value::Scalar(100.0)).eased()];
|
||||
let out = side_ease(&keys, 0, 0, false, true).unwrap();
|
||||
assert!((out.speed - 50.0).abs() < 1e-9);
|
||||
let inn = side_ease(&keys, 1, 0, false, false).unwrap();
|
||||
assert_eq!(inn, Ease::EASY);
|
||||
assert!(side_ease(&keys, 0, 0, false, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_reverse_mirrors_keys() {
|
||||
let mut keys =
|
||||
vec![Keyframe::new(s(1.0), Value::Scalar(0.0)).eased(), Keyframe::new(s(2.0), Value::Scalar(5.0)), Keyframe::new(s(4.0), Value::Scalar(10.0))];
|
||||
keys[0].out_interp = Interp::Hold;
|
||||
time_reverse(&mut keys);
|
||||
assert_eq!(keys.iter().map(|k| k.time.seconds().round() as i64).collect::<Vec<_>>(), vec![1, 3, 4]);
|
||||
assert_eq!(keys[0].value, Value::Scalar(10.0));
|
||||
assert_eq!(keys[2].in_interp, Interp::Hold);
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn eased_values_stay_in_range(t in 0.0f64..1.0, i0 in 0.01f64..1.0, i1 in 0.01f64..1.0) {
|
||||
|
||||
@@ -352,6 +352,7 @@ impl Value {
|
||||
}
|
||||
}
|
||||
Value::Layer(_) => Some(Value::Layer(j.as_u64())),
|
||||
Value::Path(_) => serde_json::from_value::<ShapePath>(j.clone()).ok().map(Value::Path).or_else(|| serde_json::from_value::<Value>(j.clone()).ok()),
|
||||
_ => serde_json::from_value::<Value>(j.clone()).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,6 +454,13 @@ impl FootageSource for MediaPool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn audio(&self, _item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {
|
||||
if !footage.has_audio || footage.missing {
|
||||
return None;
|
||||
}
|
||||
Some(self.audio_samples(footage, t, frames, rate))
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
|
||||
@@ -350,12 +350,36 @@ pub fn shape_simple_op(ids: &mut Ids, kind: &str) -> Option<PropGroup> {
|
||||
// ---------------------------------------------------------------- camera / light / 3D
|
||||
|
||||
pub fn camera_options(ids: &mut Ids, zoom: f64) -> PropGroup {
|
||||
camera_options_for(ids, zoom, zoom * 36.0 / 50.0)
|
||||
}
|
||||
|
||||
/// Camera Options for a comp `comp_w` wide (aperture from the 50 mm preset: 25.3 mm at 1920 px).
|
||||
pub fn camera_options_for(ids: &mut Ids, zoom: f64, comp_w: f64) -> PropGroup {
|
||||
let dof = ids.prop("dof", "Depth of Field", Value::Bool(false)).with_ui(ParamUi::Checkbox);
|
||||
ids.group("cameraOptions", "Camera Options")
|
||||
.with(ids.prop("zoom", "Zoom", Value::Scalar(zoom)).with_ui(ParamUi::Pixels))
|
||||
.with(ids.prop("dof", "Depth of Field", Value::Bool(false)).with_ui(ParamUi::Checkbox))
|
||||
.with(dof)
|
||||
.with(ids.prop("focusDistance", "Focus Distance", Value::Scalar(zoom)).with_ui(ParamUi::Pixels))
|
||||
.with(ids.prop("aperture", "Aperture", Value::Scalar(25.3)).with_ui(ParamUi::Pixels))
|
||||
.with(ids.prop("aperture", "Aperture", Value::Scalar(25.3 * comp_w / 1920.0)).with_ui(ParamUi::Pixels))
|
||||
.with(ids.prop("blurLevel", "Blur Level", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
|
||||
.with(ids.prop("irisShape", "Iris Shape", Value::Enum(0)).with_ui(popup(&[
|
||||
"Fast Rectangle",
|
||||
"Triangle",
|
||||
"Square",
|
||||
"Pentagon",
|
||||
"Hexagon",
|
||||
"Heptagon",
|
||||
"Octagon",
|
||||
"Nonagon",
|
||||
"Decagon",
|
||||
])))
|
||||
.with(ids.prop("irisRotation", "Iris Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
|
||||
.with(ids.prop("irisRoundness", "Iris Roundness", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
|
||||
.with(ids.prop("irisAspectRatio", "Iris Aspect Ratio", Value::Scalar(1.0)).with_ui(slider(0.01, 100.0, 0.01, 4.0, 2)))
|
||||
.with(ids.prop("irisDiffractionFringe", "Iris Diffraction Fringe", Value::Scalar(0.0)).with_ui(slider(0.0, 1000.0, 0.0, 100.0, 1)))
|
||||
.with(ids.prop("highlightGain", "Highlight Gain", Value::Scalar(0.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 1)))
|
||||
.with(ids.prop("highlightThreshold", "Highlight Threshold", Value::Scalar(255.0)).with_ui(slider(0.0, 255.0, 0.0, 255.0, 0)))
|
||||
.with(ids.prop("highlightSaturation", "Highlight Saturation", Value::Scalar(0.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 1)))
|
||||
}
|
||||
|
||||
pub fn light_options(ids: &mut Ids, kind: LightKind) -> PropGroup {
|
||||
@@ -457,7 +481,7 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource
|
||||
.with(ids.prop("rotationY", "Y Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
|
||||
.with(ids.prop("rotation", "Z Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle));
|
||||
root.children.push(tr.into());
|
||||
root.children.push(camera_options(&mut ids, zoom).into());
|
||||
root.children.push(camera_options_for(&mut ids, zoom, cw).into());
|
||||
} else if let LayerSource::Light { kind } = source {
|
||||
let mut g = ids.group("transform", "Transform");
|
||||
if matches!(kind, LightKind::Spot | LightKind::Parallel) {
|
||||
@@ -466,6 +490,10 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource
|
||||
if kind != LightKind::Ambient {
|
||||
g.children
|
||||
.push(ids.prop("position", "Position", Value::Vec3([cw / 2.0 - 260.0, ch / 2.0 - 260.0, -440.0])).with_ui(ParamUi::Point3).spatial().into());
|
||||
g.children.push(ids.prop("orientation", "Orientation", Value::Vec3([0.0; 3])).with_ui(ParamUi::Angle).into());
|
||||
g.children.push(ids.prop("rotationX", "X Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle).into());
|
||||
g.children.push(ids.prop("rotationY", "Y Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle).into());
|
||||
g.children.push(ids.prop("rotation", "Z Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle).into());
|
||||
}
|
||||
root.children.push(g.into());
|
||||
root.children.push(light_options(&mut ids, kind).into());
|
||||
@@ -485,6 +513,12 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource
|
||||
root.children.push(audio(&mut ids).into());
|
||||
}
|
||||
let out = duration.map(|d| d.min(comp.duration)).unwrap_or(comp.duration);
|
||||
// Two-node cameras and spot/parallel lights aim at their Point of Interest.
|
||||
let auto_orient = if matches!(source, LayerSource::Camera | LayerSource::Light { kind: LightKind::Spot | LightKind::Parallel }) {
|
||||
crate::AutoOrient::TowardsPointOfInterest
|
||||
} else {
|
||||
crate::AutoOrient::Off
|
||||
};
|
||||
Layer {
|
||||
id,
|
||||
name: comp.unique_layer_name(name),
|
||||
@@ -502,7 +536,7 @@ pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource
|
||||
parent: None,
|
||||
markers: vec![],
|
||||
markers_locked: false,
|
||||
auto_orient: Default::default(),
|
||||
auto_orient,
|
||||
props: root,
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod build;
|
||||
pub mod props;
|
||||
pub mod render_queue;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -600,11 +601,14 @@ pub struct Project {
|
||||
pub settings: ProjectSettings,
|
||||
pub items: BTreeMap<ItemId, Item>,
|
||||
pub next_id: u64,
|
||||
/// The Render Queue (Composition ▸ Add to Render Queue).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub render_queue: Vec<render_queue::RenderQueueItem>,
|
||||
}
|
||||
|
||||
impl Default for Project {
|
||||
fn default() -> Self {
|
||||
Project { schema: SCHEMA_VERSION, settings: ProjectSettings::default(), items: BTreeMap::new(), next_id: 1 }
|
||||
Project { schema: SCHEMA_VERSION, settings: ProjectSettings::default(), items: BTreeMap::new(), next_id: 1, render_queue: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -399,6 +399,38 @@ impl PropGroup {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Match-id path (`transform/position`, `effects/ec.blur.gaussian#2/blurriness`) of the node
|
||||
/// with `uid`: portable between layers with the same structure (keyframe paste, pick-whip).
|
||||
pub fn match_path_of(&self, uid: Uid) -> Option<String> {
|
||||
for (i, c) in self.children.iter().enumerate() {
|
||||
let n = self.children[..i].iter().filter(|o| o.match_id() == c.match_id()).count() + 1;
|
||||
let seg = if n == 1 { c.match_id().to_string() } else { format!("{}#{n}", c.match_id()) };
|
||||
if c.uid() == uid {
|
||||
return Some(seg);
|
||||
}
|
||||
if let Node::Group(g) = c
|
||||
&& let Some(p) = g.match_path_of(uid)
|
||||
{
|
||||
return Some(format!("{seg}/{p}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Chain of nodes from this group's children down to `uid` (inclusive).
|
||||
pub fn node_chain(&self, uid: Uid) -> Option<Vec<&Node>> {
|
||||
for c in &self.children {
|
||||
if c.uid() == uid {
|
||||
return Some(vec![c]);
|
||||
}
|
||||
if let Node::Group(g) = c
|
||||
&& let Some(mut rest) = g.node_chain(uid)
|
||||
{
|
||||
rest.insert(0, c);
|
||||
return Some(rest);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Human path (`Transform/Position`) of the node with `uid`.
|
||||
pub fn name_path_of(&self, uid: Uid) -> Option<String> {
|
||||
for c in &self.children {
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
//! The Render Queue: compositions queued for export, each with Render Settings (what to render:
|
||||
//! quality, resolution, time span, frame rate) and an Output Module (how to write it: format,
|
||||
//! channels, codec options, output path). Saved with the project, like After Effects.
|
||||
//!
|
||||
//! Output paths are templates: `[compName].[fileExtension]` (the default), with the tokens
|
||||
//! `[compName]`, `[projectName]`, `[fileExtension]`, `[width]`, `[height]`, `[frameRate]`,
|
||||
//! `[startFrame]`, `[endFrame]`, `[outputModuleName]` and, for image sequences, a run of `#`
|
||||
//! (`[#####]`) that becomes the zero-padded frame number. A relative result is resolved against the
|
||||
//! project's folder (or the working directory for unsaved projects).
|
||||
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Comp, ItemId};
|
||||
|
||||
/// The default output path template.
|
||||
pub const DEFAULT_TEMPLATE: &str = "[compName].[fileExtension]";
|
||||
/// The default template for image sequences.
|
||||
pub const DEFAULT_SEQUENCE_TEMPLATE: &str = "[compName]_[#####].[fileExtension]";
|
||||
|
||||
/// Render Settings ▸ Quality.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RenderQuality {
|
||||
#[default]
|
||||
Best,
|
||||
Draft,
|
||||
}
|
||||
|
||||
/// Render Settings ▸ Time Span.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum TimeSpan {
|
||||
/// The composition's work area.
|
||||
#[default]
|
||||
WorkArea,
|
||||
/// The whole composition.
|
||||
LengthOfComp,
|
||||
/// An explicit span `[start, end)` in comp time.
|
||||
Custom { start: Tick, end: Tick },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct RenderSettings {
|
||||
pub quality: RenderQuality,
|
||||
/// Output scale (1 = Full, 0.5 = Half, 1/3 = Third, 0.25 = Quarter).
|
||||
pub resolution: f64,
|
||||
pub time_span: TimeSpan,
|
||||
/// `None` = use the comp's frame rate.
|
||||
pub frame_rate: Option<FrameRate>,
|
||||
/// Motion blur for layers with the switch on (and the comp's Enable Motion Blur).
|
||||
pub motion_blur: bool,
|
||||
/// Image sequences: skip frames whose file already exists.
|
||||
pub skip_existing: bool,
|
||||
}
|
||||
|
||||
impl Default for RenderSettings {
|
||||
fn default() -> Self {
|
||||
RenderSettings {
|
||||
quality: RenderQuality::Best,
|
||||
resolution: 1.0,
|
||||
time_span: TimeSpan::WorkArea,
|
||||
frame_rate: None,
|
||||
motion_blur: true,
|
||||
skip_existing: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderSettings {
|
||||
/// The comp-time span `[start, end)` to render.
|
||||
pub fn span(&self, comp: &Comp) -> (Tick, Tick) {
|
||||
let (a, b) = match self.time_span {
|
||||
TimeSpan::WorkArea => comp.work_area,
|
||||
TimeSpan::LengthOfComp => (Tick::ZERO, comp.duration),
|
||||
TimeSpan::Custom { start, end } => (start, end),
|
||||
};
|
||||
let a = a.clamp(Tick::ZERO, comp.duration);
|
||||
let b = b.clamp(a, comp.duration);
|
||||
(a, b)
|
||||
}
|
||||
pub fn rate(&self, comp: &Comp) -> FrameRate {
|
||||
self.frame_rate.unwrap_or(comp.frame_rate)
|
||||
}
|
||||
/// First output-rate frame starting at or after `t`.
|
||||
fn ceil_frame(r: FrameRate, t: Tick) -> i64 {
|
||||
let f = r.frame_at(t);
|
||||
if r.tick_of(f) < t { f + 1 } else { f }
|
||||
}
|
||||
/// Output-rate frame number of output frame 0 (the first frame starting inside the span).
|
||||
pub fn first_frame(&self, comp: &Comp) -> i64 {
|
||||
Self::ceil_frame(self.rate(comp), self.span(comp).0)
|
||||
}
|
||||
/// Number of output frames: those starting in `[start, end)` (at least 1).
|
||||
pub fn frame_count(&self, comp: &Comp) -> u64 {
|
||||
let (_, b) = self.span(comp);
|
||||
let n = Self::ceil_frame(self.rate(comp), b) - self.first_frame(comp);
|
||||
n.max(1) as u64
|
||||
}
|
||||
/// Comp time of output frame `i`.
|
||||
pub fn frame_time(&self, comp: &Comp, i: u64) -> Tick {
|
||||
self.rate(comp).tick_of(self.first_frame(comp) + i as i64)
|
||||
}
|
||||
pub fn output_size(&self, comp: &Comp) -> (u32, u32) {
|
||||
let s = self.resolution.clamp(0.01, 4.0);
|
||||
(((comp.width as f64 * s).round() as u32).max(1), ((comp.height as f64 * s).round() as u32).max(1))
|
||||
}
|
||||
pub fn resolution_label(&self) -> &'static str {
|
||||
match self.resolution {
|
||||
r if (r - 1.0).abs() < 1e-6 => "Full",
|
||||
r if (r - 0.5).abs() < 1e-6 => "Half",
|
||||
r if (r - 1.0 / 3.0).abs() < 1e-3 => "Third",
|
||||
r if (r - 0.25).abs() < 1e-6 => "Quarter",
|
||||
_ => "Custom",
|
||||
}
|
||||
}
|
||||
/// One-line summary shown next to "Render Settings:" (AE shows the template name).
|
||||
pub fn summary(&self) -> String {
|
||||
let q = if self.quality == RenderQuality::Best { "Best Settings" } else { "Draft Settings" };
|
||||
format!("{q} · {}", self.resolution_label())
|
||||
}
|
||||
}
|
||||
|
||||
/// Output Module ▸ Format.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum OutputFormat {
|
||||
/// H.264 video (+ AAC audio) in MP4.
|
||||
#[default]
|
||||
H264,
|
||||
/// Apple ProRes in QuickTime (+ PCM audio). 4444 when channels include alpha.
|
||||
ProRes,
|
||||
PngSequence,
|
||||
JpegSequence,
|
||||
TiffSequence,
|
||||
/// OpenEXR sequence (32-bit float, linear light).
|
||||
ExrSequence,
|
||||
/// Animated GIF.
|
||||
Gif,
|
||||
}
|
||||
|
||||
impl OutputFormat {
|
||||
pub const ALL: [OutputFormat; 7] = [
|
||||
OutputFormat::H264,
|
||||
OutputFormat::ProRes,
|
||||
OutputFormat::PngSequence,
|
||||
OutputFormat::JpegSequence,
|
||||
OutputFormat::TiffSequence,
|
||||
OutputFormat::ExrSequence,
|
||||
OutputFormat::Gif,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::H264 => "H.264",
|
||||
OutputFormat::ProRes => "QuickTime (ProRes)",
|
||||
OutputFormat::PngSequence => "PNG Sequence",
|
||||
OutputFormat::JpegSequence => "JPEG Sequence",
|
||||
OutputFormat::TiffSequence => "TIFF Sequence",
|
||||
OutputFormat::ExrSequence => "OpenEXR Sequence",
|
||||
OutputFormat::Gif => "Animated GIF",
|
||||
}
|
||||
}
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::H264 => "mp4",
|
||||
OutputFormat::ProRes => "mov",
|
||||
OutputFormat::PngSequence => "png",
|
||||
OutputFormat::JpegSequence => "jpg",
|
||||
OutputFormat::TiffSequence => "tif",
|
||||
OutputFormat::ExrSequence => "exr",
|
||||
OutputFormat::Gif => "gif",
|
||||
}
|
||||
}
|
||||
pub fn is_sequence(self) -> bool {
|
||||
matches!(self, OutputFormat::PngSequence | OutputFormat::JpegSequence | OutputFormat::TiffSequence | OutputFormat::ExrSequence)
|
||||
}
|
||||
pub fn is_movie(self) -> bool {
|
||||
matches!(self, OutputFormat::H264 | OutputFormat::ProRes)
|
||||
}
|
||||
pub fn supports_alpha(self) -> bool {
|
||||
!matches!(self, OutputFormat::H264 | OutputFormat::JpegSequence)
|
||||
}
|
||||
pub fn supports_audio(self) -> bool {
|
||||
self.is_movie()
|
||||
}
|
||||
/// The written frame size for a rendered size: H.264 needs even dimensions (rounded down,
|
||||
/// at least 2).
|
||||
pub fn coded_size(self, w: u32, h: u32) -> (u32, u32) {
|
||||
let even = |v: u32| if v < 2 { 2 } else { v & !1 };
|
||||
if self == OutputFormat::H264 { (even(w), even(h)) } else { (w, h) }
|
||||
}
|
||||
/// Parse a format name: `h264`, `mp4`, `prores`, `mov`, `png`, `jpeg`/`jpg`, `tiff`/`tif`,
|
||||
/// `exr`, `gif`, or a label.
|
||||
pub fn from_name(s: &str) -> Option<OutputFormat> {
|
||||
let n = s.trim().to_ascii_lowercase().replace([' ', '.', '-', '_'], "");
|
||||
Some(match n.as_str() {
|
||||
"h264" | "mp4" | "avc" => OutputFormat::H264,
|
||||
"prores" | "mov" | "quicktime" | "quicktimeprores" => OutputFormat::ProRes,
|
||||
"png" | "pngsequence" => OutputFormat::PngSequence,
|
||||
"jpg" | "jpeg" | "jpegsequence" => OutputFormat::JpegSequence,
|
||||
"tif" | "tiff" | "tiffsequence" => OutputFormat::TiffSequence,
|
||||
"exr" | "openexr" | "openexrsequence" => OutputFormat::ExrSequence,
|
||||
"gif" | "animatedgif" => OutputFormat::Gif,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// Guess from a file name's extension.
|
||||
pub fn from_path(path: &str) -> Option<OutputFormat> {
|
||||
let ext = std::path::Path::new(path).extension()?.to_string_lossy().to_ascii_lowercase();
|
||||
OutputFormat::from_name(&ext)
|
||||
}
|
||||
}
|
||||
|
||||
/// Output Module ▸ Channels.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Channels {
|
||||
/// Opaque, composited over the comp background colour.
|
||||
#[default]
|
||||
Rgb,
|
||||
/// With straight (unmatted) alpha.
|
||||
Rgba,
|
||||
}
|
||||
|
||||
/// Output Module ▸ Audio Output.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AudioOutput {
|
||||
/// On when the comp has audible layers.
|
||||
#[default]
|
||||
Auto,
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
|
||||
/// ProRes flavour.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ProResProfile {
|
||||
Proxy,
|
||||
Lt,
|
||||
Standard,
|
||||
#[default]
|
||||
Hq,
|
||||
P4444,
|
||||
P4444Xq,
|
||||
}
|
||||
|
||||
impl ProResProfile {
|
||||
pub const ALL: [ProResProfile; 6] =
|
||||
[ProResProfile::Proxy, ProResProfile::Lt, ProResProfile::Standard, ProResProfile::Hq, ProResProfile::P4444, ProResProfile::P4444Xq];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ProResProfile::Proxy => "Apple ProRes 422 Proxy",
|
||||
ProResProfile::Lt => "Apple ProRes 422 LT",
|
||||
ProResProfile::Standard => "Apple ProRes 422",
|
||||
ProResProfile::Hq => "Apple ProRes 422 HQ",
|
||||
ProResProfile::P4444 => "Apple ProRes 4444",
|
||||
ProResProfile::P4444Xq => "Apple ProRes 4444 XQ",
|
||||
}
|
||||
}
|
||||
pub fn is_4444(self) -> bool {
|
||||
matches!(self, ProResProfile::P4444 | ProResProfile::P4444Xq)
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<ProResProfile> {
|
||||
let n = s.to_ascii_lowercase().replace([' ', '-', '_'], "");
|
||||
ProResProfile::ALL.into_iter().find(|p| {
|
||||
let l = p.label().to_ascii_lowercase().replace(' ', "");
|
||||
l == n || l.trim_start_matches("appleprores") == n.trim_start_matches("appleprores") || format!("{p:?}").to_ascii_lowercase() == n
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct OutputModule {
|
||||
pub format: OutputFormat,
|
||||
pub channels: Channels,
|
||||
/// Output path or template (see the module docs).
|
||||
pub output: String,
|
||||
/// JPEG quality 1–100.
|
||||
pub quality: u8,
|
||||
/// H.264 target bitrate.
|
||||
pub bitrate_kbps: u32,
|
||||
pub prores_profile: ProResProfile,
|
||||
pub audio: AudioOutput,
|
||||
pub audio_sample_rate: u32,
|
||||
/// GIF: loop forever.
|
||||
pub gif_loop: bool,
|
||||
}
|
||||
|
||||
impl Default for OutputModule {
|
||||
fn default() -> Self {
|
||||
OutputModule {
|
||||
format: OutputFormat::H264,
|
||||
channels: Channels::Rgb,
|
||||
output: DEFAULT_TEMPLATE.into(),
|
||||
quality: 90,
|
||||
bitrate_kbps: 10_000,
|
||||
prores_profile: ProResProfile::Hq,
|
||||
audio: AudioOutput::Auto,
|
||||
audio_sample_rate: 48_000,
|
||||
gif_loop: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputModule {
|
||||
pub fn for_format(format: OutputFormat) -> OutputModule {
|
||||
let mut m = OutputModule { format, ..Default::default() };
|
||||
if format.is_sequence() {
|
||||
m.output = DEFAULT_SEQUENCE_TEMPLATE.into();
|
||||
}
|
||||
m
|
||||
}
|
||||
/// Change the format, keeping the output name but fixing its extension / frame-number token.
|
||||
pub fn set_format(&mut self, format: OutputFormat) {
|
||||
let old = self.format;
|
||||
self.format = format;
|
||||
if !format.supports_alpha() {
|
||||
self.channels = Channels::Rgb;
|
||||
}
|
||||
if self.output.contains("[fileExtension]") {
|
||||
if format.is_sequence() && !self.output.contains('#') {
|
||||
self.output = self.output.replace(".[fileExtension]", "_[#####].[fileExtension]");
|
||||
} else if !format.is_sequence() && old.is_sequence() {
|
||||
self.output = self.output.replace("_[#####]", "").replace("[#####]", "");
|
||||
}
|
||||
return;
|
||||
}
|
||||
let p = std::path::Path::new(&self.output);
|
||||
let mut stem = p.with_extension("").to_string_lossy().to_string();
|
||||
if format.is_sequence() && !stem.contains('#') {
|
||||
stem.push_str("_[#####]");
|
||||
} else if !format.is_sequence() {
|
||||
stem = stem.replace("_[#####]", "").replace("[#####]", "");
|
||||
}
|
||||
self.output = format!("{stem}.{}", format.extension());
|
||||
}
|
||||
/// One-line summary shown next to "Output Module:".
|
||||
pub fn summary(&self) -> String {
|
||||
let ch = match self.channels {
|
||||
Channels::Rgb => "RGB",
|
||||
Channels::Rgba => "RGB + Alpha",
|
||||
};
|
||||
match self.format {
|
||||
OutputFormat::H264 => format!("H.264 · {} kbps", self.bitrate_kbps),
|
||||
OutputFormat::ProRes => format!(
|
||||
"{} · {ch}",
|
||||
if self.channels == Channels::Rgba && !self.prores_profile.is_4444() { "Apple ProRes 4444" } else { self.prores_profile.label() }
|
||||
),
|
||||
f => format!("{} · {ch}", f.label()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render Queue item status (the Status column).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub enum RenderStatus {
|
||||
/// Render checkbox off.
|
||||
Unqueued,
|
||||
#[default]
|
||||
Queued,
|
||||
NeedsOutput,
|
||||
Rendering,
|
||||
Done,
|
||||
UserStopped,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl RenderStatus {
|
||||
pub fn label(&self) -> &str {
|
||||
match self {
|
||||
RenderStatus::Unqueued => "Unqueued",
|
||||
RenderStatus::Queued => "Queued",
|
||||
RenderStatus::NeedsOutput => "Needs Output",
|
||||
RenderStatus::Rendering => "Rendering",
|
||||
RenderStatus::Done => "Done",
|
||||
RenderStatus::UserStopped => "User Stopped",
|
||||
RenderStatus::Failed(_) => "Failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RenderQueueItem {
|
||||
/// Stable id (unique within the queue).
|
||||
pub id: u64,
|
||||
pub comp: ItemId,
|
||||
/// The Render checkbox.
|
||||
pub render: bool,
|
||||
#[serde(default)]
|
||||
pub status: RenderStatus,
|
||||
#[serde(default)]
|
||||
pub settings: RenderSettings,
|
||||
#[serde(default)]
|
||||
pub output: OutputModule,
|
||||
/// Unix seconds when the last render of this item started.
|
||||
#[serde(default)]
|
||||
pub started: Option<u64>,
|
||||
/// Seconds the last render took.
|
||||
#[serde(default)]
|
||||
pub render_time: Option<f64>,
|
||||
/// Resolved path of the last render (first file for sequences).
|
||||
#[serde(default)]
|
||||
pub last_output: Option<String>,
|
||||
}
|
||||
|
||||
impl RenderQueueItem {
|
||||
pub fn new(id: u64, comp: ItemId) -> RenderQueueItem {
|
||||
RenderQueueItem {
|
||||
id,
|
||||
comp,
|
||||
render: true,
|
||||
status: RenderStatus::Queued,
|
||||
settings: RenderSettings::default(),
|
||||
output: OutputModule::default(),
|
||||
started: None,
|
||||
render_time: None,
|
||||
last_output: None,
|
||||
}
|
||||
}
|
||||
/// Will be rendered by the next Render.
|
||||
pub fn is_queued(&self) -> bool {
|
||||
self.render && matches!(self.status, RenderStatus::Queued)
|
||||
}
|
||||
}
|
||||
|
||||
/// Values for template tokens.
|
||||
pub struct TemplateVars<'a> {
|
||||
pub comp_name: &'a str,
|
||||
pub project_name: &'a str,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub frame_rate: f64,
|
||||
pub start_frame: i64,
|
||||
pub end_frame: i64,
|
||||
}
|
||||
|
||||
/// Expand template tokens (all but the `#` frame-number run).
|
||||
pub fn expand_template(template: &str, format: OutputFormat, v: &TemplateVars) -> String {
|
||||
let fps = if (v.frame_rate - v.frame_rate.round()).abs() < 1e-6 { format!("{}", v.frame_rate.round() as i64) } else { format!("{:.2}", v.frame_rate) };
|
||||
template
|
||||
.replace("[compName]", &sanitize(v.comp_name))
|
||||
.replace("[projectName]", &sanitize(v.project_name))
|
||||
.replace("[fileExtension]", format.extension())
|
||||
.replace("[width]", &v.width.to_string())
|
||||
.replace("[height]", &v.height.to_string())
|
||||
.replace("[frameRate]", &fps)
|
||||
.replace("[startFrame]", &v.start_frame.to_string())
|
||||
.replace("[endFrame]", &v.end_frame.to_string())
|
||||
.replace("[outputModuleName]", format.label())
|
||||
}
|
||||
|
||||
/// Replace the first run of `#` (optionally in brackets, `[####]`) with the zero-padded frame
|
||||
/// number. Paths without a run get `_NNNNN` before the extension.
|
||||
pub fn sequence_path(path: &str, frame: i64) -> String {
|
||||
if let Some(start) = path.find('#') {
|
||||
let len = path[start..].chars().take_while(|c| *c == '#').count();
|
||||
let (mut a, mut b) = (start, start + len);
|
||||
if a > 0 && path.as_bytes()[a - 1] == b'[' && path.as_bytes().get(b) == Some(&b']') {
|
||||
a -= 1;
|
||||
b += 1;
|
||||
}
|
||||
return format!("{}{:0width$}{}", &path[..a], frame, &path[b..], width = len);
|
||||
}
|
||||
let p = std::path::Path::new(path);
|
||||
match p.extension() {
|
||||
Some(ext) => format!("{}_{frame:05}.{}", p.with_extension("").to_string_lossy(), ext.to_string_lossy()),
|
||||
None => format!("{path}_{frame:05}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a name safe as a file name component.
|
||||
pub fn sanitize(name: &str) -> String {
|
||||
name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn templates_and_sequences() {
|
||||
let v = TemplateVars { comp_name: "Main/Title", project_name: "P", width: 1920, height: 1080, frame_rate: 29.97, start_frame: 0, end_frame: 9 };
|
||||
assert_eq!(expand_template(DEFAULT_TEMPLATE, OutputFormat::H264, &v), "Main_Title.mp4");
|
||||
assert_eq!(expand_template("[compName]_[width]x[height]@[frameRate].[fileExtension]", OutputFormat::Gif, &v), "Main_Title_1920x1080@29.97.gif");
|
||||
assert_eq!(sequence_path("out/a_[#####].png", 42), "out/a_00042.png");
|
||||
assert_eq!(sequence_path("a###.tif", 7), "a007.tif");
|
||||
assert_eq!(sequence_path("a.png", 3), "a_00003.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_format_fixes_names() {
|
||||
let mut m = OutputModule::default();
|
||||
m.set_format(OutputFormat::PngSequence);
|
||||
assert_eq!(m.output, "[compName]_[#####].[fileExtension]");
|
||||
m.set_format(OutputFormat::ProRes);
|
||||
assert_eq!(m.output, DEFAULT_TEMPLATE);
|
||||
m.output = "/tmp/x.mov".into();
|
||||
m.set_format(OutputFormat::JpegSequence);
|
||||
assert_eq!(m.output, "/tmp/x_[#####].jpg");
|
||||
assert_eq!(OutputFormat::from_name("TIFF"), Some(OutputFormat::TiffSequence));
|
||||
assert_eq!(ProResProfile::from_name("4444"), Some(ProResProfile::P4444));
|
||||
assert_eq!(ProResProfile::from_name("hq"), Some(ProResProfile::Hq));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spans() {
|
||||
let mut c = Comp::new(100, 50, FrameRate::new(25, 1), Tick::from_seconds_f64(4.0));
|
||||
c.work_area = (Tick::from_seconds_f64(1.0), Tick::from_seconds_f64(2.0));
|
||||
let mut s = RenderSettings::default();
|
||||
assert_eq!(s.frame_count(&c), 25);
|
||||
assert_eq!(s.frame_time(&c, 0), Tick::from_seconds_f64(1.0));
|
||||
s.time_span = TimeSpan::LengthOfComp;
|
||||
assert_eq!(s.frame_count(&c), 100);
|
||||
s.frame_rate = Some(FrameRate::new(10, 1));
|
||||
assert_eq!(s.frame_count(&c), 40);
|
||||
s.resolution = 0.5;
|
||||
assert_eq!(s.output_size(&c), (50, 25));
|
||||
// NTSC: 1 s – 2 s holds the 30 frames that start inside it.
|
||||
let c = Comp::new(100, 50, FrameRate::new(30000, 1001), Tick::from_seconds_f64(4.0));
|
||||
let s = RenderSettings { time_span: TimeSpan::Custom { start: Tick::from_seconds_f64(1.0), end: Tick::from_seconds_f64(2.0) }, ..Default::default() };
|
||||
assert_eq!(s.frame_count(&c), 30);
|
||||
assert_eq!(s.first_frame(&c), 30);
|
||||
assert!(s.frame_time(&c, 0) >= Tick::from_seconds_f64(1.0));
|
||||
}
|
||||
}
|
||||
+142
-41
@@ -1,20 +1,23 @@
|
||||
//! Blurs: separable box passes (exact running sums) approximating Gaussians, plus directional
|
||||
//! and radial (spin/zoom) blurs.
|
||||
//!
|
||||
//! Box passes run straight on row-major pixels: horizontal passes per row, vertical passes over
|
||||
//! blocks of rows with a per-column running sum (no transposes), ping-ponging between two
|
||||
//! buffers so a Gaussian allocates two images regardless of the number of passes.
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Image, Px};
|
||||
|
||||
/// One horizontal box pass of radius `r` (window 2r+1) over each row; `repeat` = edge pixels
|
||||
/// extend, otherwise transparent.
|
||||
fn box_h(img: &Image, r: usize, repeat: bool) -> Image {
|
||||
/// One horizontal box pass of radius `r` (window 2r+1) over each row of `src` (width `w`) into
|
||||
/// `out`; `repeat` = edge pixels extend, otherwise transparent.
|
||||
fn box_h_into(src: &[Px], out: &mut [Px], w: usize, r: usize, repeat: bool) {
|
||||
if r == 0 {
|
||||
return img.clone();
|
||||
out.copy_from_slice(src);
|
||||
return;
|
||||
}
|
||||
let w = img.width as usize;
|
||||
let mut out = Image::new(img.width, img.height);
|
||||
let norm = 1.0 / (2 * r + 1) as f32;
|
||||
out.data.par_chunks_mut(w).zip(img.data.par_chunks(w)).for_each(|(o, row)| {
|
||||
out.par_chunks_mut(w).zip(src.par_chunks(w)).for_each(|(o, row)| {
|
||||
let get = |i: isize| -> Px {
|
||||
if i < 0 {
|
||||
if repeat { row[0] } else { [0.0; 4] }
|
||||
@@ -40,18 +43,89 @@ fn box_h(img: &Image, r: usize, repeat: bool) -> Image {
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn transpose(img: &Image) -> Image {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let mut out = Image::new(img.height, img.width);
|
||||
out.data.par_chunks_mut(h.max(1)).enumerate().for_each(|(x, col)| {
|
||||
for y in 0..h {
|
||||
col[y] = img.data[y * w + x];
|
||||
/// One vertical box pass (same semantics as [`box_h_into`] along columns).
|
||||
fn box_v_into(src: &[Px], out: &mut [Px], w: usize, h: usize, r: usize, repeat: bool) {
|
||||
if r == 0 {
|
||||
out.copy_from_slice(src);
|
||||
return;
|
||||
}
|
||||
let norm = 1.0 / (2 * r + 1) as f32;
|
||||
let block = (4 * r).clamp(32, 256);
|
||||
let row = |i: isize| -> Option<&[Px]> {
|
||||
if i < 0 {
|
||||
repeat.then(|| &src[0..w])
|
||||
} else if i as usize >= h {
|
||||
repeat.then(|| &src[(h - 1) * w..h * w])
|
||||
} else {
|
||||
Some(&src[i as usize * w..(i as usize + 1) * w])
|
||||
}
|
||||
};
|
||||
out.par_chunks_mut(w * block).enumerate().for_each(|(bi, chunk)| {
|
||||
let ya = (bi * block) as isize;
|
||||
let mut acc = vec![[0.0f32; 4]; w];
|
||||
for i in ya - r as isize..=ya + r as isize {
|
||||
if let Some(rw) = row(i) {
|
||||
for (a, p) in acc.iter_mut().zip(rw) {
|
||||
for c in 0..4 {
|
||||
a[c] += p[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (yy, o) in chunk.chunks_mut(w).enumerate() {
|
||||
let y = ya + yy as isize;
|
||||
for (o, a) in o.iter_mut().zip(&acc) {
|
||||
*o = a.map(|v| v * norm);
|
||||
}
|
||||
match (row(y + r as isize + 1), row(y - r as isize)) {
|
||||
(Some(add), Some(sub)) => {
|
||||
for ((a, p), q) in acc.iter_mut().zip(add).zip(sub) {
|
||||
for c in 0..4 {
|
||||
a[c] += p[c] - q[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(add), None) => {
|
||||
for (a, p) in acc.iter_mut().zip(add) {
|
||||
for c in 0..4 {
|
||||
a[c] += p[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
(None, Some(sub)) => {
|
||||
for (a, q) in acc.iter_mut().zip(sub) {
|
||||
for c in 0..4 {
|
||||
a[c] -= q[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Run horizontal passes with radii `rx` then vertical passes with radii `ry`.
|
||||
fn box_passes(img: &Image, rx: &[usize], ry: &[usize], repeat: bool) -> Image {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let passes: Vec<(bool, usize)> = rx.iter().map(|&r| (false, r)).chain(ry.iter().map(|&r| (true, r))).filter(|p| p.1 > 0).collect();
|
||||
if passes.is_empty() || w == 0 || h == 0 {
|
||||
return img.clone();
|
||||
}
|
||||
let mut a = Image::new(img.width, img.height);
|
||||
let mut b = Image::new(img.width, img.height);
|
||||
for (i, &(vertical, r)) in passes.iter().enumerate() {
|
||||
let src: &[Px] = if i == 0 { &img.data } else { &a.data };
|
||||
if vertical {
|
||||
box_v_into(src, &mut b.data, w, h, r, repeat);
|
||||
} else {
|
||||
box_h_into(src, &mut b.data, w, r, repeat);
|
||||
}
|
||||
std::mem::swap(&mut a, &mut b);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Box radii for `n` passes approximating a Gaussian of `sigma` (Kovesi / "boxes for Gauss").
|
||||
@@ -72,36 +146,15 @@ fn box_radii(sigma: f64, n: usize) -> Vec<usize> {
|
||||
|
||||
/// Separable box blur with given radii, `iterations` passes.
|
||||
pub fn box_blur(img: &Image, rx: usize, ry: usize, iterations: usize, repeat: bool) -> Image {
|
||||
let mut cur = img.clone();
|
||||
for _ in 0..iterations.max(1) {
|
||||
cur = box_h(&cur, rx, repeat);
|
||||
}
|
||||
if ry > 0 {
|
||||
let mut t = transpose(&cur);
|
||||
for _ in 0..iterations.max(1) {
|
||||
t = box_h(&t, ry, repeat);
|
||||
}
|
||||
cur = transpose(&t);
|
||||
}
|
||||
cur
|
||||
let n = iterations.max(1);
|
||||
box_passes(img, &vec![rx; n], &vec![ry; n], repeat)
|
||||
}
|
||||
|
||||
/// Gaussian blur with standard deviations in pixels (3 box passes per axis).
|
||||
pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> Image {
|
||||
let mut cur = img.clone();
|
||||
if sigma_x > 0.05 {
|
||||
for r in box_radii(sigma_x, 3) {
|
||||
cur = box_h(&cur, r, repeat);
|
||||
}
|
||||
}
|
||||
if sigma_y > 0.05 {
|
||||
let mut t = transpose(&cur);
|
||||
for r in box_radii(sigma_y, 3) {
|
||||
t = box_h(&t, r, repeat);
|
||||
}
|
||||
cur = transpose(&t);
|
||||
}
|
||||
cur
|
||||
let rx = if sigma_x > 0.05 { box_radii(sigma_x, 3) } else { vec![] };
|
||||
let ry = if sigma_y > 0.05 { box_radii(sigma_y, 3) } else { vec![] };
|
||||
box_passes(img, &rx, &ry, repeat)
|
||||
}
|
||||
|
||||
/// Motion blur along `angle_deg` (0 = vertical in AE's Directional Blur, measured clockwise from
|
||||
@@ -182,6 +235,54 @@ mod tests {
|
||||
assert!(b.data.iter().all(|p| (p[0] - 0.5).abs() < 1e-5));
|
||||
}
|
||||
|
||||
/// Direct (windowed sum) box filter along x or y: the definition the passes must match.
|
||||
fn box_ref(img: &Image, r: usize, vertical: bool, repeat: bool) -> Image {
|
||||
let mut out = Image::new(img.width, img.height);
|
||||
let (w, h) = (img.width as i64, img.height as i64);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut acc = [0.0f64; 4];
|
||||
for k in -(r as i64)..=(r as i64) {
|
||||
let (sx, sy) = if vertical { (x, y + k) } else { (x + k, y) };
|
||||
let p = if repeat { img.get_clamped(sx, sy) } else { img.get(sx, sy) };
|
||||
for c in 0..4 {
|
||||
acc[c] += p[c] as f64;
|
||||
}
|
||||
}
|
||||
out.set(x as u32, y as u32, acc.map(|v| (v / (2 * r + 1) as f64) as f32));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_match_direct_box_filter() {
|
||||
let mut img = Image::new(53, 301);
|
||||
for y in 0..301 {
|
||||
for x in 0..53 {
|
||||
let v = crate::hash_noise(x, y, 3);
|
||||
img.set(x, y, [v * 0.5, v * 0.25, v, v]);
|
||||
}
|
||||
}
|
||||
for repeat in [false, true] {
|
||||
for (rx, ry) in [(0, 3), (2, 0), (5, 9), (40, 70), (1, 200)] {
|
||||
let fast = box_passes(&img, &[rx, rx + 1], &[ry, ry / 2], repeat);
|
||||
let mut slow = img.clone();
|
||||
for r in [rx, rx + 1] {
|
||||
slow = box_ref(&slow, r, false, repeat);
|
||||
}
|
||||
for r in [ry, ry / 2] {
|
||||
slow = box_ref(&slow, r, true, repeat);
|
||||
}
|
||||
for (i, (p, q)) in fast.data.iter().zip(&slow.data).enumerate() {
|
||||
for c in 0..4 {
|
||||
assert!((p[c] - q[c]).abs() < 1e-4, "r {rx},{ry} repeat {repeat} px {i}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radii_sane() {
|
||||
let r = box_radii(10.0, 3);
|
||||
|
||||
@@ -10,7 +10,7 @@ use effectcraft_color::{BlendMode, blend_pixel};
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use blur::{box_blur, directional_blur, gaussian_blur, radial_blur};
|
||||
pub use warp::{Sampling, WarpOpts, composite_warp, resample};
|
||||
pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_reference, resample};
|
||||
|
||||
pub type Px = [f32; 4];
|
||||
|
||||
|
||||
+249
-1
@@ -4,7 +4,7 @@ use effectcraft_color::{BlendMode, blend_pixel};
|
||||
use effectcraft_geom::{Mat3, Rect, vec2};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Image, hash_noise};
|
||||
use crate::{Image, Px, hash_noise};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Sampling {
|
||||
@@ -52,7 +52,163 @@ fn half(src: &Image) -> Image {
|
||||
}
|
||||
|
||||
/// Draw `src` transformed by `m` (src pixel space → dst pixel space) onto `dst` with blending.
|
||||
///
|
||||
/// Affine transforms with non-stencil modes take a fast path (per-row span clipping, interior
|
||||
/// bilinear without bounds checks, integer-translation copies, inlined Normal blending); it
|
||||
/// matches [`composite_warp_reference`] to float rounding.
|
||||
pub fn composite_warp(dst: &mut Image, src: &Image, m: &Mat3, opts: &WarpOpts) {
|
||||
composite_warp_impl(dst, src, m, opts, true, None);
|
||||
}
|
||||
|
||||
/// `dst += warp(src) · weight` (plain sum, no blending): motion-blur sub-samples accumulate
|
||||
/// straight into one buffer instead of one full-size image per sample.
|
||||
pub fn accumulate_warp(dst: &mut Image, src: &Image, m: &Mat3, sampling: Sampling, weight: f32) {
|
||||
let opts = WarpOpts { sampling, ..Default::default() };
|
||||
if m.is_affine() && m.inverse().is_some_and(|i| i.is_affine()) {
|
||||
composite_warp_impl(dst, src, m, &opts, true, Some(weight));
|
||||
return;
|
||||
}
|
||||
let mut tmp = Image::new(dst.width, dst.height);
|
||||
composite_warp(&mut tmp, src, m, &opts);
|
||||
dst.data.par_iter_mut().zip(tmp.data.par_iter()).for_each(|(d, s)| {
|
||||
for c in 0..4 {
|
||||
d[c] += s[c] * weight;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The straightforward per-pixel implementation (reference for the fast path's tests).
|
||||
pub fn composite_warp_reference(dst: &mut Image, src: &Image, m: &Mat3, opts: &WarpOpts) {
|
||||
composite_warp_impl(dst, src, m, opts, false, None);
|
||||
}
|
||||
|
||||
/// Bilinear blend of four taps (same operation order as [`Image::sample_bilinear`]).
|
||||
#[inline(always)]
|
||||
fn bilerp(a: Px, b: Px, c: Px, d: Px, tx: f32, ty: f32) -> Px {
|
||||
let mut o = [0.0; 4];
|
||||
for i in 0..4 {
|
||||
let top = a[i] + (b[i] - a[i]) * tx;
|
||||
let bot = c[i] + (d[i] - c[i]) * tx;
|
||||
o[i] = top + (bot - top) * ty;
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Bilinear sample with an unchecked interior fast path.
|
||||
#[inline(always)]
|
||||
fn sample_bilinear_fast(img: &Image, x: f64, y: f64) -> Px {
|
||||
let fx = x - 0.5;
|
||||
let fy = y - 0.5;
|
||||
let x0 = fx.floor();
|
||||
let y0 = fy.floor();
|
||||
let (xi, yi) = (x0 as i64, y0 as i64);
|
||||
let (w, h) = (img.width as i64, img.height as i64);
|
||||
if xi >= 0 && yi >= 0 && xi + 1 < w && yi + 1 < h {
|
||||
let tx = (fx - x0) as f32;
|
||||
let ty = (fy - y0) as f32;
|
||||
let i = yi as usize * w as usize + xi as usize;
|
||||
let row0 = &img.data[i..i + 2];
|
||||
let row1 = &img.data[i + w as usize..i + w as usize + 2];
|
||||
return bilerp(row0[0], row0[1], row1[0], row1[1], tx, ty);
|
||||
}
|
||||
img.sample_bilinear(x, y)
|
||||
}
|
||||
|
||||
/// Index range `[lo, hi)` of `i` in `0..n` for which `p0 + i·s` may lie in `[min, max]`
|
||||
/// (conservative by one step on each side; callers still check per pixel).
|
||||
fn span(p0: f64, s: f64, min: f64, max: f64, n: usize) -> (usize, usize) {
|
||||
if s.abs() < 1e-12 {
|
||||
return if p0 >= min - 1e-9 && p0 <= max + 1e-9 { (0, n) } else { (0, 0) };
|
||||
}
|
||||
let (a, b) = ((min - p0) / s, (max - p0) / s);
|
||||
let (a, b) = if a < b { (a, b) } else { (b, a) };
|
||||
let lo = (a.floor() - 1.0).max(0.0);
|
||||
let hi = (b.ceil() + 2.0).min(n as f64);
|
||||
if hi <= lo { (0, 0) } else { (lo as usize, hi as usize) }
|
||||
}
|
||||
|
||||
/// Fast affine rows: `blend(dst, src, x, y)` is only called for visible source pixels.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn affine_rows(
|
||||
dst: &mut Image,
|
||||
img: &Image,
|
||||
inv: &Mat3,
|
||||
sampling: Sampling,
|
||||
op: f32,
|
||||
x0: usize,
|
||||
x1: usize,
|
||||
y0: usize,
|
||||
y1: usize,
|
||||
blend: impl Fn(Px, Px, u32, u32) -> Px + Sync,
|
||||
) {
|
||||
let w = dst.width as usize;
|
||||
let m = inv.0;
|
||||
let (iw, ih) = (img.width as f64, img.height as f64);
|
||||
let step = vec2(m[0][0], m[1][0]);
|
||||
// Pure integer translation: every sample lands on a pixel centre, so all filters return the
|
||||
// source pixel itself (bicubic still clamps negatives, as in the reference).
|
||||
let int_tx = m[0][0] == 1.0 && m[1][1] == 1.0 && m[0][1] == 0.0 && m[1][0] == 0.0 && m[0][2].fract() == 0.0 && m[1][2].fract() == 0.0;
|
||||
dst.data.par_chunks_mut(w).enumerate().skip(y0).take(y1 - y0).for_each(|(y, row)| {
|
||||
let fy = y as f64 + 0.5;
|
||||
let p0 = vec2(m[0][0] * (x0 as f64 + 0.5) + m[0][1] * fy + m[0][2], m[1][0] * (x0 as f64 + 0.5) + m[1][1] * fy + m[1][2]);
|
||||
let n = x1 - x0;
|
||||
let (ax, bx) = span(p0.x, step.x, -1.0, iw + 1.0, n);
|
||||
let (ay, by) = span(p0.y, step.y, -1.0, ih + 1.0, n);
|
||||
let (lo, hi) = (ax.max(ay), bx.min(by));
|
||||
if lo >= hi {
|
||||
return;
|
||||
}
|
||||
if int_tx {
|
||||
let sy = y as i64 + m[1][2] as i64;
|
||||
if sy < 0 || sy >= img.height as i64 {
|
||||
return;
|
||||
}
|
||||
let dx = m[0][2] as i64;
|
||||
let srow = &img.data[sy as usize * img.width as usize..(sy as usize + 1) * img.width as usize];
|
||||
let xa = (x0 as i64 + lo as i64).max(-dx).max(0) as usize;
|
||||
let xb = ((x0 + hi) as i64).min(img.width as i64 - dx).max(0) as usize;
|
||||
for x in xa..xb.max(xa) {
|
||||
let mut s = srow[(x as i64 + dx) as usize];
|
||||
if sampling == Sampling::Bicubic {
|
||||
s = [s[0].max(0.0), s[1].max(0.0), s[2].max(0.0), s[3].max(0.0)];
|
||||
}
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if op < 1.0 {
|
||||
for c in s.iter_mut() {
|
||||
*c *= op;
|
||||
}
|
||||
}
|
||||
row[x] = blend(row[x], s, x as u32, y as u32);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for i in lo..hi {
|
||||
let x = x0 + i;
|
||||
let p = vec2(p0.x + step.x * i as f64, p0.y + step.y * i as f64);
|
||||
if p.x < -1.0 || p.y < -1.0 || p.x > iw + 1.0 || p.y > ih + 1.0 {
|
||||
continue;
|
||||
}
|
||||
let mut s = match sampling {
|
||||
Sampling::Nearest => img.get(p.x.floor() as i64, p.y.floor() as i64),
|
||||
Sampling::Bilinear => sample_bilinear_fast(img, p.x, p.y),
|
||||
Sampling::Bicubic => img.sample_bicubic(p.x, p.y),
|
||||
};
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if op < 1.0 {
|
||||
for c in s.iter_mut() {
|
||||
*c *= op;
|
||||
}
|
||||
}
|
||||
row[x] = blend(row[x], s, x as u32, y as u32);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn composite_warp_impl(dst: &mut Image, src: &Image, m: &Mat3, opts: &WarpOpts, allow_fast: bool, accumulate: Option<f32>) {
|
||||
if src.is_empty() || dst.is_empty() || opts.opacity <= 0.0 {
|
||||
return;
|
||||
}
|
||||
@@ -91,6 +247,26 @@ pub fn composite_warp(dst: &mut Image, src: &Image, m: &Mat3, opts: &WarpOpts) {
|
||||
let affine = inv.is_affine();
|
||||
let mode = opts.mode;
|
||||
let op = opts.opacity;
|
||||
if let Some(k) = accumulate
|
||||
&& affine
|
||||
{
|
||||
affine_rows(dst, img, &inv, opts.sampling, 1.0, x0, x1, y0, y1, |d, s, _, _| [d[0] + s[0] * k, d[1] + s[1] * k, d[2] + s[2] * k, d[3] + s[3] * k]);
|
||||
return;
|
||||
}
|
||||
if allow_fast && affine && !mode.is_stencil() {
|
||||
match mode {
|
||||
BlendMode::Normal => affine_rows(dst, img, &inv, opts.sampling, op, x0, x1, y0, y1, |d, s, _, _| {
|
||||
let k = 1.0 - s[3];
|
||||
[s[0] + d[0] * k, s[1] + d[1] * k, s[2] + d[2] * k, s[3] + d[3] * k]
|
||||
}),
|
||||
BlendMode::Dissolve | BlendMode::DancingDissolve => {
|
||||
let seed = opts.seed;
|
||||
affine_rows(dst, img, &inv, opts.sampling, op, x0, x1, y0, y1, |d, s, x, y| blend_pixel(mode, d, s, hash_noise(x, y, seed)))
|
||||
}
|
||||
_ => affine_rows(dst, img, &inv, opts.sampling, op, x0, x1, y0, y1, |d, s, _, _| blend_pixel(mode, d, s, 0.5)),
|
||||
}
|
||||
return;
|
||||
}
|
||||
dst.data.par_chunks_mut(w).enumerate().skip(y0).take(y1 - y0).for_each(|(y, row)| {
|
||||
let fy = y as f64 + 0.5;
|
||||
let mut sp = inv.apply(vec2(x0 as f64 + 0.5, fy));
|
||||
@@ -172,6 +348,78 @@ mod tests {
|
||||
assert_eq!(dst.get(3, 2), [1.0; 4]);
|
||||
}
|
||||
|
||||
fn test_image(w: u32, h: u32, seed: u32) -> Image {
|
||||
let mut img = Image::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let a = if (x + y) % 7 == 0 { 0.0 } else { hash_noise(x, y, seed) };
|
||||
img.set(x, y, [hash_noise(x, y, seed + 1) * a, hash_noise(x, y, seed + 2) * a, hash_noise(x, y, seed + 3) * a, a]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// The fast affine path equals the reference per-pixel path (modes, filters, transforms).
|
||||
#[test]
|
||||
fn fast_path_matches_reference() {
|
||||
let src = test_image(37, 23, 5);
|
||||
let mats = [
|
||||
Mat3::IDENTITY,
|
||||
Mat3::translate(vec2(5.0, -3.0)),
|
||||
Mat3::translate(vec2(-40.0, 2.0)),
|
||||
Mat3::translate(vec2(3.25, 7.5)),
|
||||
Mat3::translate(vec2(20.0, 10.0)) * Mat3::rotate_deg(23.0) * Mat3::scale(vec2(1.3, 0.8)),
|
||||
Mat3::translate(vec2(30.0, 5.0)) * Mat3::rotate_deg(-120.0) * Mat3::scale(vec2(0.7, 0.7)),
|
||||
Mat3::translate(vec2(10.0, 10.0)) * Mat3::scale(vec2(-1.0, 1.0)),
|
||||
Mat3::scale(vec2(0.3, 0.3)),
|
||||
];
|
||||
let modes = [BlendMode::Normal, BlendMode::Add, BlendMode::Multiply, BlendMode::Screen, BlendMode::Dissolve, BlendMode::Overlay];
|
||||
for (mi, m) in mats.iter().enumerate() {
|
||||
for mode in modes {
|
||||
for sampling in [Sampling::Nearest, Sampling::Bilinear, Sampling::Bicubic] {
|
||||
for opacity in [1.0, 0.6] {
|
||||
let opts = WarpOpts { sampling, opacity, mode, seed: 9, clip: None };
|
||||
let mut a = test_image(48, 40, 77);
|
||||
let mut b = a.clone();
|
||||
composite_warp(&mut a, &src, m, &opts);
|
||||
composite_warp_reference(&mut b, &src, m, &opts);
|
||||
for (i, (p, q)) in a.data.iter().zip(&b.data).enumerate() {
|
||||
for c in 0..4 {
|
||||
assert!((p[c] - q[c]).abs() < 1e-4, "mat {mi} {mode:?} {sampling:?} op {opacity} px {i}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulating sub-samples equals warping each into its own image and summing.
|
||||
#[test]
|
||||
fn accumulate_matches_per_sample_images() {
|
||||
let src = test_image(30, 20, 11);
|
||||
let persp = Mat3::square_to_quad([vec2(5.0, 4.0), vec2(40.0, 2.0), vec2(44.0, 30.0), vec2(2.0, 35.0)]) * Mat3::scale(vec2(1.0 / 30.0, 1.0 / 20.0));
|
||||
let mats = [Mat3::translate(vec2(3.0, 4.0)), Mat3::translate(vec2(5.5, 4.25)) * Mat3::rotate_deg(12.0), persp];
|
||||
let k = 1.0 / mats.len() as f32;
|
||||
let mut fast = Image::new(48, 40);
|
||||
let mut slow = Image::new(48, 40);
|
||||
for m in &mats {
|
||||
accumulate_warp(&mut fast, &src, m, Sampling::Bilinear, k);
|
||||
let mut img = Image::new(48, 40);
|
||||
composite_warp_reference(&mut img, &src, m, &WarpOpts::default());
|
||||
for (a, b) in slow.data.iter_mut().zip(&img.data) {
|
||||
for c in 0..4 {
|
||||
a[c] += b[c] * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (p, q) in fast.data.iter().zip(&slow.data) {
|
||||
for c in 0..4 {
|
||||
assert!((p[c] - q[c]).abs() < 1e-4, "{p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downscale_preserves_average() {
|
||||
let src = Image::filled(64, 64, [0.25, 0.5, 0.75, 1.0]);
|
||||
|
||||
@@ -21,4 +21,5 @@ effectcraft-text = { workspace = true }
|
||||
effectcraft-effects = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Audio mixdown of a composition: every audible footage layer (and, recursively, precomp layer)
|
||||
//! summed with its Audio Levels (dB, per channel), respecting in/out points, the Audio switch and
|
||||
//! solo. Levels are evaluated once per call (callers mix in short blocks, e.g. one video frame).
|
||||
//! Time-stretched layers are resampled nearest-sample; reversed (negative stretch) layers are
|
||||
//! silent for now.
|
||||
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project};
|
||||
use effectcraft_time::{TICKS_PER_SECOND, Tick};
|
||||
|
||||
use crate::{EvalCtx, ExprHost, FootageSource};
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// `frames` stereo sample frames of `comp`'s mix from comp time `start` at `rate` Hz,
|
||||
/// interleaved (L R L R …).
|
||||
pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dyn ExprHost>, comp: ItemId, start: Tick, frames: usize, rate: u32) -> Vec<f32> {
|
||||
let mut out = vec![0.0f32; frames * 2];
|
||||
mix_into(project, footage, expr, comp, start, rate, &mut out, 1.0, 1.0, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the comp has anything audible (footage with audio, or a precomp that has).
|
||||
pub fn comp_has_audio(project: &Project, comp: ItemId) -> bool {
|
||||
fn walk(project: &Project, comp: ItemId, depth: usize) -> bool {
|
||||
let Some(c) = project.comp(comp) else { return false };
|
||||
depth < MAX_DEPTH
|
||||
&& c.layers.iter().any(|l| {
|
||||
l.switches.audio
|
||||
&& match &l.source {
|
||||
LayerSource::Footage { item } => {
|
||||
matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing)
|
||||
}
|
||||
LayerSource::Comp { item } => walk(project, *item, depth + 1),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
walk(project, comp, 0)
|
||||
}
|
||||
|
||||
fn audible(project: &Project, l: &Layer) -> bool {
|
||||
l.switches.audio
|
||||
&& match &l.source {
|
||||
LayerSource::Footage { item } => matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio),
|
||||
LayerSource::Comp { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn db_to_gain(db: f64) -> f32 {
|
||||
if db <= -96.0 { 0.0 } else { 10f64.powf(db / 20.0) as f32 }
|
||||
}
|
||||
|
||||
fn units_ceil(t: Tick, rate: u32) -> i64 {
|
||||
let n = t.0 as i128 * rate as i128;
|
||||
let d = TICKS_PER_SECOND as i128;
|
||||
(n.div_euclid(d) + i128::from(n.rem_euclid(d) != 0)) as i64
|
||||
}
|
||||
|
||||
fn sample_tick(i: i64, rate: u32) -> Tick {
|
||||
Tick(((i as i128 * TICKS_PER_SECOND as i128) / rate as i128) as i64)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn mix_into(
|
||||
project: &Project,
|
||||
footage: &dyn FootageSource,
|
||||
expr: Option<&dyn ExprHost>,
|
||||
comp_id: ItemId,
|
||||
start: Tick,
|
||||
rate: u32,
|
||||
out: &mut [f32],
|
||||
gl: f32,
|
||||
gr: f32,
|
||||
depth: usize,
|
||||
) {
|
||||
let Some(comp) = project.comp(comp_id) else { return };
|
||||
if depth >= MAX_DEPTH || rate == 0 {
|
||||
return;
|
||||
}
|
||||
let frames = out.len() / 2;
|
||||
let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l));
|
||||
let s0 = start.to_units_floor(rate as i64);
|
||||
for l in &comp.layers {
|
||||
if !audible(project, l) || (any_solo && !l.switches.solo) || l.stretch <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Sample range of the block that falls inside the layer's [in, out).
|
||||
let a = (units_ceil(l.in_point, rate) - s0).clamp(0, frames as i64) as usize;
|
||||
let b = (units_ceil(l.out_point, rate) - s0).clamp(0, frames as i64) as usize;
|
||||
if a >= b {
|
||||
continue;
|
||||
}
|
||||
let t_a = sample_tick(s0 + a as i64, rate);
|
||||
let (ll, lr) = levels(project, comp_id, comp, l, t_a, expr);
|
||||
let (ll, lr) = (ll * gl, lr * gr);
|
||||
if ll == 0.0 && lr == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let n = b - a;
|
||||
let speed = 100.0 / l.stretch;
|
||||
let src_n = ((n as f64 * speed).ceil() as usize).max(1);
|
||||
let lt = l.layer_time(t_a);
|
||||
let buf = match &l.source {
|
||||
LayerSource::Footage { item } => match project.item(*item).map(|i| &i.kind) {
|
||||
Some(ItemKind::Footage(f)) => footage.audio(*item, f, lt, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]),
|
||||
_ => continue,
|
||||
},
|
||||
LayerSource::Comp { item } => {
|
||||
if project.comp_contains(*item, comp_id) {
|
||||
continue;
|
||||
}
|
||||
let mut sub = vec![0.0f32; src_n * 2];
|
||||
mix_into(project, footage, expr, *item, lt, rate, &mut sub, 1.0, 1.0, depth + 1);
|
||||
sub
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let same = (speed - 1.0).abs() < 1e-9;
|
||||
for i in 0..n {
|
||||
let j = if same { i } else { ((i as f64 * speed) as usize).min(src_n - 1) };
|
||||
if j * 2 + 1 >= buf.len() {
|
||||
break;
|
||||
}
|
||||
out[(a + i) * 2] += buf[j * 2] * ll;
|
||||
out[(a + i) * 2 + 1] += buf[j * 2 + 1] * lr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn levels(project: &Project, comp_id: ItemId, comp: &Comp, l: &Layer, t: Tick, expr: Option<&dyn ExprHost>) -> (f32, f32) {
|
||||
let Some(g) = l.props.sub("audio") else { return (1.0, 1.0) };
|
||||
let mut ctx = EvalCtx::new(project, comp_id, comp, t);
|
||||
ctx.expr = expr;
|
||||
let [a, b] = ctx.v2(l, g, "levels", [0.0, 0.0]);
|
||||
(db_to_gain(a), db_to_gain(b))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_project::{Footage, FootageKind, build};
|
||||
use effectcraft_time::FrameRate;
|
||||
|
||||
use super::*;
|
||||
use crate::Image;
|
||||
|
||||
/// A 1 kHz-ish constant "tone": every sample is 0.25 (left) / -0.25 (right).
|
||||
struct Dc;
|
||||
impl FootageSource for Dc {
|
||||
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
|
||||
None
|
||||
}
|
||||
fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, _: u32) -> Option<Vec<f32>> {
|
||||
Some((0..frames).flat_map(|_| if start >= Tick::ZERO { [0.25, -0.25] } else { [0.0, 0.0] }).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixes_layers_with_levels_and_in_out() {
|
||||
let mut p = Project::default();
|
||||
let f = Footage {
|
||||
path: "x.wav".into(),
|
||||
kind: FootageKind::Audio,
|
||||
width: 0,
|
||||
height: 0,
|
||||
pixel_aspect: 1.0,
|
||||
frame_rate: FrameRate::new(25, 1),
|
||||
native_rate: None,
|
||||
duration: Tick::from_seconds_f64(10.0),
|
||||
has_video: false,
|
||||
has_audio: true,
|
||||
alpha: Default::default(),
|
||||
premul_color: [0.0; 3],
|
||||
loop_count: 1,
|
||||
codec: String::new(),
|
||||
missing: false,
|
||||
sequence: vec![],
|
||||
};
|
||||
let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(f));
|
||||
let comp = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0));
|
||||
let mut l1 = build::layer(&mut p, &comp, "a", LayerSource::Footage { item: fid }, (0, 0), None);
|
||||
l1.in_point = Tick::from_seconds_f64(1.0);
|
||||
let mut l2 = build::layer(&mut p, &comp, "b", LayerSource::Footage { item: fid }, (0, 0), None);
|
||||
if let Some(g) = l2.props.sub_mut("audio")
|
||||
&& let Some(pr) = g.get_mut("levels")
|
||||
{
|
||||
pr.value = effectcraft_project::Value::Vec2([-6.0206, -96.0]);
|
||||
}
|
||||
let mut comp = comp;
|
||||
comp.layers = vec![l1, l2];
|
||||
let cid = p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
assert!(comp_has_audio(&p, cid));
|
||||
let rate = 1000;
|
||||
let m = mix_comp(&p, &Dc, None, cid, Tick::from_seconds_f64(0.5), 1000, rate);
|
||||
// first half: only layer b (half gain left, muted right)
|
||||
assert!((m[0] - 0.125).abs() < 1e-3 && m[1].abs() < 1e-6, "{} {}", m[0], m[1]);
|
||||
// second half (≥ 1 s): a + b
|
||||
let i = 700 * 2;
|
||||
assert!((m[i] - 0.375).abs() < 1e-3 && (m[i + 1] + 0.25).abs() < 1e-3, "{} {}", m[i], m[i + 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Layer render cache.
|
||||
//!
|
||||
//! The processed pixels of a layer (source → masks → effects, in layer space) depend only on the
|
||||
//! layer's own non-transform properties, its source item and the render options — not on its
|
||||
//! transform, opacity, blend mode or anything below it. [`LayerCache`] keeps those buffers keyed
|
||||
//! by a content hash of exactly those inputs, *evaluated at the frame time*, so:
|
||||
//!
|
||||
//! * a static layer (or one whose only animation is in Transform) renders once and is reused on
|
||||
//! every frame while scrubbing or playing;
|
||||
//! * editing one layer re-renders only that layer — every other layer's cached pixels stay valid
|
||||
//! because their keys do not change;
|
||||
//! * any change to a property value, keyframe, expression result, effect, mask, switch or source
|
||||
//! item changes the key, so stale pixels are never returned.
|
||||
//!
|
||||
//! Layers whose pixels depend on time in ways the property values do not capture (time-based
|
||||
//! effects such as Noise or Wave Warp, Wiggle Paths, footage, precomps) either fold the layer
|
||||
//! time into the key or are not cached.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_effects::Buf;
|
||||
use effectcraft_project::{ItemKind, Layer, LayerSource, Node, PropGroup};
|
||||
|
||||
use crate::eval::EvalCtx;
|
||||
|
||||
/// Thread-safe, memory-budgeted cache of processed layer buffers.
|
||||
pub struct LayerCache {
|
||||
inner: Mutex<Inner>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
buf: Arc<Buf>,
|
||||
bytes: usize,
|
||||
last_use: u64,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
map: HashMap<u64, Entry>,
|
||||
bytes: usize,
|
||||
budget: usize,
|
||||
clock: u64,
|
||||
hits: u64,
|
||||
misses: u64,
|
||||
}
|
||||
|
||||
/// Hit/miss counters and memory use (for perf readouts and tests).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CacheStats {
|
||||
pub entries: usize,
|
||||
pub bytes: usize,
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
}
|
||||
|
||||
impl Default for LayerCache {
|
||||
fn default() -> Self {
|
||||
LayerCache::new(1 << 30)
|
||||
}
|
||||
}
|
||||
|
||||
impl LayerCache {
|
||||
/// A cache holding at most `budget` bytes of pixels.
|
||||
pub fn new(budget: usize) -> LayerCache {
|
||||
LayerCache { inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0 }) }
|
||||
}
|
||||
|
||||
pub fn get(&self, key: u64) -> Option<Arc<Buf>> {
|
||||
let mut g = self.inner.lock().ok()?;
|
||||
g.clock += 1;
|
||||
let now = g.clock;
|
||||
match g.map.get_mut(&key) {
|
||||
Some(e) => {
|
||||
e.last_use = now;
|
||||
let b = e.buf.clone();
|
||||
g.hits += 1;
|
||||
Some(b)
|
||||
}
|
||||
None => {
|
||||
g.misses += 1;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&self, key: u64, buf: Arc<Buf>) {
|
||||
let bytes = buf.img.data.len() * std::mem::size_of::<effectcraft_raster::Px>();
|
||||
let Ok(mut g) = self.inner.lock() else { return };
|
||||
if bytes > g.budget / 4 {
|
||||
return;
|
||||
}
|
||||
g.clock += 1;
|
||||
let now = g.clock;
|
||||
if let Some(old) = g.map.insert(key, Entry { buf, bytes, last_use: now }) {
|
||||
g.bytes -= old.bytes;
|
||||
}
|
||||
g.bytes += bytes;
|
||||
if g.bytes > g.budget {
|
||||
// Evict least-recently used entries down to 3/4 of the budget.
|
||||
let target = g.budget / 4 * 3;
|
||||
let mut by_age: Vec<(u64, u64)> = g.map.iter().map(|(k, e)| (e.last_use, *k)).collect();
|
||||
by_age.sort_unstable();
|
||||
for (_, k) in by_age {
|
||||
if g.bytes <= target {
|
||||
break;
|
||||
}
|
||||
if let Some(e) = g.map.remove(&k) {
|
||||
g.bytes -= e.bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
if let Ok(mut g) = self.inner.lock() {
|
||||
g.map.clear();
|
||||
g.bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> CacheStats {
|
||||
self.inner.lock().map(|g| CacheStats { entries: g.map.len(), bytes: g.bytes, hits: g.hits, misses: g.misses }).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a style 64-bit hasher fed by `Debug` output (exact float formatting) and raw values.
|
||||
struct KeyHasher(u64);
|
||||
|
||||
impl Hasher for KeyHasher {
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for &b in bytes {
|
||||
self.0 ^= b as u64;
|
||||
self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Write for KeyHasher {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
Hasher::write(self, s.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_debug(h: &mut KeyHasher, v: &impl std::fmt::Debug) {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(h, "{v:?}");
|
||||
Hasher::write_u8(h, 0xff);
|
||||
}
|
||||
|
||||
/// Time-based layer content: does any part of the source/effects read the clock directly
|
||||
/// (rather than through property values)?
|
||||
fn time_dependent(layer: &Layer) -> bool {
|
||||
if layer.switches.effects
|
||||
&& let Some(fx) = layer.effects()
|
||||
{
|
||||
for g in fx.groups() {
|
||||
if let effectcraft_project::GroupKind::Effect { effect } = &g.kind
|
||||
&& g.enabled
|
||||
&& effectcraft_effects::is_time_dependent(effect)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(layer.source, LayerSource::Shape)
|
||||
&& let Some(c) = layer.props.sub("contents")
|
||||
{
|
||||
return group_has(c, "wiggle");
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn group_has(g: &PropGroup, match_id: &str) -> bool {
|
||||
g.children.iter().any(|c| match c {
|
||||
Node::Group(sub) => sub.match_id == match_id || group_has(sub, match_id),
|
||||
Node::Prop(_) => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Feed every property of `g` that can change over time (keyframes or expression) as its value
|
||||
/// at the context time. The static structure is hashed separately.
|
||||
fn hash_values(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer, g: &PropGroup) {
|
||||
for c in &g.children {
|
||||
match c {
|
||||
Node::Prop(p) => {
|
||||
if !p.keys.is_empty() || p.has_expression() {
|
||||
p.uid.hash(h);
|
||||
hash_debug(h, &ctx.value(layer, p));
|
||||
}
|
||||
}
|
||||
Node::Group(sub) => hash_values(h, ctx, layer, sub),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache key for the processed (source → masks → effects) buffer of `layer` at the context
|
||||
/// time, or `None` when the layer must not be cached (footage, precomps, cameras, adjustment
|
||||
/// layers…).
|
||||
pub fn layer_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool) -> Option<u64> {
|
||||
if layer.switches.adjustment {
|
||||
return None;
|
||||
}
|
||||
let mut h = KeyHasher(0xcbf2_9ce4_8422_2325);
|
||||
match &layer.source {
|
||||
LayerSource::Solid { item } => {
|
||||
let it = ctx.project.item(*item)?;
|
||||
let ItemKind::Solid(s) = &it.kind else { return None };
|
||||
hash_debug(&mut h, s);
|
||||
}
|
||||
LayerSource::Text | LayerSource::Shape => {}
|
||||
_ => return None,
|
||||
}
|
||||
ctx.comp_id.hash(&mut h);
|
||||
ctx.comp.width.hash(&mut h);
|
||||
ctx.comp.height.hash(&mut h);
|
||||
scale.to_bits().hash(&mut h);
|
||||
draft.hash(&mut h);
|
||||
layer.id.hash(&mut h);
|
||||
hash_debug(&mut h, &layer.source);
|
||||
hash_debug(&mut h, &layer.switches);
|
||||
for c in &layer.props.children {
|
||||
if let Node::Group(g) = c
|
||||
&& g.match_id == "transform"
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Static structure: values, keyframes, expressions, enabled flags, effect ids, modes.
|
||||
hash_debug(&mut h, c);
|
||||
if let Node::Group(g) = c {
|
||||
hash_values(&mut h, ctx, layer, g);
|
||||
}
|
||||
}
|
||||
if time_dependent(layer) {
|
||||
layer.layer_time(ctx.time).0.hash(&mut h);
|
||||
// Effects also see the layer's time mapping.
|
||||
layer.start_time.0.hash(&mut h);
|
||||
layer.stretch.to_bits().hash(&mut h);
|
||||
}
|
||||
Some(h.finish())
|
||||
}
|
||||
+44
-38
@@ -3,7 +3,7 @@
|
||||
//! Keyframe times are stored in **layer time** (they move with the layer), so evaluating a
|
||||
//! property at comp time `t` first maps `t` through the layer's start time and stretch.
|
||||
|
||||
use effectcraft_geom::{Mat3, Mat4, Vec3, look_at, vec3};
|
||||
use effectcraft_geom::{Mat3, Mat4, Vec3, vec3};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Comp, ItemId, Layer, LayerId, LayerSource, Project, PropGroup, Property};
|
||||
use effectcraft_time::Tick;
|
||||
@@ -33,6 +33,16 @@ impl<'a> EvalCtx<'a> {
|
||||
}
|
||||
/// Value of a property at the context time (keyframes, then expression).
|
||||
pub fn value(&self, layer: &Layer, prop: &Property) -> Value {
|
||||
// Separated Position reads as the combination of X/Y/Z Position.
|
||||
if prop.match_id == "position"
|
||||
&& let Some(tr) = layer.transform()
|
||||
&& let Some(px) = tr.get("positionX")
|
||||
&& tr.get("position").is_some_and(|p| p.uid == prop.uid)
|
||||
{
|
||||
let z = tr.get("positionZ").map(|p| self.value(layer, p).as_f64()).unwrap_or(0.0);
|
||||
let y = tr.get("positionY").map(|p| self.value(layer, p).as_f64()).unwrap_or(0.0);
|
||||
return Value::Vec3([self.value(layer, px).as_f64(), y, z]);
|
||||
}
|
||||
let lt = layer.layer_time(self.time);
|
||||
let v = prop.value_at(lt);
|
||||
if prop.has_expression()
|
||||
@@ -63,6 +73,21 @@ impl<'a> EvalCtx<'a> {
|
||||
pub fn b(&self, layer: &Layer, g: &PropGroup, m: &str) -> bool {
|
||||
self.group_value(layer, g, m).map(|v| v.as_bool()).unwrap_or(false)
|
||||
}
|
||||
/// Layer Position, honouring Separate Dimensions (X/Y/Z Position properties).
|
||||
pub fn position(&self, layer: &Layer, tr: &PropGroup) -> [f64; 3] {
|
||||
match tr.get("positionX") {
|
||||
Some(px) => [self.value(layer, px).as_f64(), self.f(layer, tr, "positionY", 0.0), self.f(layer, tr, "positionZ", 0.0)],
|
||||
None => self.v3(layer, tr, "position", [0.0; 3]),
|
||||
}
|
||||
}
|
||||
/// Source time of a layer at the context time: Time Remap's value when enabled, else the
|
||||
/// (stretch-aware) layer time.
|
||||
pub fn source_time(&self, layer: &Layer) -> Tick {
|
||||
if let Some(tr) = layer.props.get("timeRemap") {
|
||||
return Tick::from_seconds_f64(self.value(layer, tr).as_f64());
|
||||
}
|
||||
layer.layer_time(self.time)
|
||||
}
|
||||
pub fn layer(&self, id: LayerId) -> Option<&'a Layer> {
|
||||
self.comp.layer(id)
|
||||
}
|
||||
@@ -71,10 +96,11 @@ impl<'a> EvalCtx<'a> {
|
||||
pub fn local_matrix(&self, layer: &Layer) -> Mat4 {
|
||||
let Some(tr) = layer.transform() else { return Mat4::IDENTITY };
|
||||
let three = layer.is_3d();
|
||||
let pos = self.v3(layer, tr, "position", [0.0; 3]);
|
||||
let pos = self.position(layer, tr);
|
||||
let rz = self.f(layer, tr, "rotation", 0.0);
|
||||
if layer.is_camera() || layer.is_light() {
|
||||
return Mat4::translate(Vec3::from(pos)) * Mat4::rotate_z(rz);
|
||||
// Children of cameras/lights follow their position and full rotation.
|
||||
return Mat4::translate(Vec3::from(pos)) * crate::three_d::camera::rig_rotation(self, layer);
|
||||
}
|
||||
let anchor = self.v3(layer, tr, "anchor", [0.0; 3]);
|
||||
let mut scale = self.v3(layer, tr, "scale", [100.0; 3]);
|
||||
@@ -82,12 +108,22 @@ impl<'a> EvalCtx<'a> {
|
||||
scale[2] = 100.0;
|
||||
let a = Vec3::from([anchor[0], anchor[1], 0.0]);
|
||||
let p = Vec3::from([pos[0], pos[1], 0.0]);
|
||||
let rz = rz + crate::three_d::camera::auto_orient_2d(self, layer);
|
||||
return Mat4::layer_3d(a, p, Vec3::from(scale), Vec3::ZERO, vec3(0.0, 0.0, rz));
|
||||
}
|
||||
let o = self.v3(layer, tr, "orientation", [0.0; 3]);
|
||||
let rx = self.f(layer, tr, "rotationX", 0.0);
|
||||
let ry = self.f(layer, tr, "rotationY", 0.0);
|
||||
Mat4::layer_3d(Vec3::from(anchor), Vec3::from(pos), Vec3::from(scale), Vec3::from(o), vec3(rx, ry, rz))
|
||||
let p = Vec3::from(pos);
|
||||
// Auto-orient (along path / towards camera) replaces Orientation.
|
||||
let orient = crate::three_d::camera::auto_orient_3d(self, layer, p)
|
||||
.unwrap_or_else(|| Mat4::orientation(Vec3::from(self.v3(layer, tr, "orientation", [0.0; 3]))));
|
||||
Mat4::translate(p)
|
||||
* orient
|
||||
* Mat4::rotate_z(rz)
|
||||
* Mat4::rotate_y(ry)
|
||||
* Mat4::rotate_x(rx)
|
||||
* Mat4::scale(Vec3::from(scale) / 100.0)
|
||||
* Mat4::translate(-Vec3::from(anchor))
|
||||
}
|
||||
|
||||
/// Layer space → comp (world) space, including parents.
|
||||
@@ -111,40 +147,10 @@ impl<'a> EvalCtx<'a> {
|
||||
layer.transform().map(|tr| self.f(layer, tr, "opacity", 100.0)).unwrap_or(100.0) / 100.0
|
||||
}
|
||||
|
||||
/// The comp's camera at this time: (view-projection to comp pixels, eye position).
|
||||
/// The comp's active camera at this time: (view-projection to comp pixels, eye, zoom).
|
||||
pub fn camera(&self) -> (Mat4, Vec3, f64) {
|
||||
let (w, h) = (self.comp.width as f64, self.comp.height as f64);
|
||||
if let Some(cam) = self.comp.active_camera(self.time)
|
||||
&& let Some(tr) = cam.transform()
|
||||
{
|
||||
let pos = Vec3::from(self.v3(cam, tr, "position", [w / 2.0, h / 2.0, -1000.0]));
|
||||
let zoom = cam.props.sub("cameraOptions").map(|g| self.f(cam, g, "zoom", 1000.0)).unwrap_or(1000.0);
|
||||
let o = self.v3(cam, tr, "orientation", [0.0; 3]);
|
||||
let rx = self.f(cam, tr, "rotationX", 0.0);
|
||||
let ry = self.f(cam, tr, "rotationY", 0.0);
|
||||
let rz = self.f(cam, tr, "rotation", 0.0);
|
||||
// Extra camera rotation is applied in camera space (inverse, because it rotates the eye).
|
||||
let extra = (Mat4::orientation(Vec3::from(o)) * Mat4::rotate_z(rz) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx)).transpose();
|
||||
let view = if let Some(poi) = tr.get("poi").map(|p| self.value(cam, p).as_vec3()) {
|
||||
look_at(pos, Vec3::from(poi), extra)
|
||||
} else {
|
||||
look_at(pos, pos + vec3(0.0, 0.0, 1.0), extra)
|
||||
};
|
||||
let mut view = view;
|
||||
// Parented cameras: apply the parent's world matrix inverse.
|
||||
if let Some(pid) = cam.parent
|
||||
&& let Some(p) = self.comp.layer(pid)
|
||||
&& let Some(inv) = self.world_matrix(p).inverse()
|
||||
{
|
||||
view = view * inv;
|
||||
let _ = pos;
|
||||
}
|
||||
return (effectcraft_geom::camera_matrix(w, h, pos, view, zoom), pos, zoom);
|
||||
}
|
||||
let zoom = effectcraft_geom::default_camera_zoom(w);
|
||||
let pos = vec3(w / 2.0, h / 2.0, -zoom);
|
||||
let view = look_at(pos, vec3(w / 2.0, h / 2.0, 0.0), Mat4::IDENTITY);
|
||||
(effectcraft_geom::camera_matrix(w, h, pos, view, zoom), pos, zoom)
|
||||
let c = crate::three_d::active_camera(self);
|
||||
(c.projection(self.comp.width as f64, self.comp.height as f64), c.eye, c.zoom)
|
||||
}
|
||||
|
||||
/// Layer space → comp pixel space as a 2D projective matrix, plus camera-space depth of the
|
||||
|
||||
+132
-35
@@ -6,15 +6,19 @@
|
||||
//! with motion blur sub-samples) → **track matte** → **blend** with the layer's mode and opacity.
|
||||
//! Adjustment layers run their effects on everything below, limited by their own bounds/masks.
|
||||
|
||||
pub mod audio;
|
||||
pub mod cache;
|
||||
pub mod eval;
|
||||
pub mod masks;
|
||||
pub mod shapes;
|
||||
pub mod text;
|
||||
pub mod three_d;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use cache::{CacheStats, LayerCache};
|
||||
use effectcraft_color::BlendMode;
|
||||
use effectcraft_effects::{Buf, EffectCtx, Params};
|
||||
use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
|
||||
use effectcraft_geom::{Mat3, vec2};
|
||||
use effectcraft_project::{Comp, Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, MatteKind, Node, Project, Quality, Sampling};
|
||||
pub use effectcraft_raster::Image;
|
||||
@@ -27,6 +31,44 @@ use rayon::prelude::*;
|
||||
pub trait FootageSource: Send + Sync {
|
||||
/// The frame of `item` at source time `t`, straight from the file (any size).
|
||||
fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<Image>>;
|
||||
/// `frames` interleaved stereo sample frames of `item`'s audio from source time `t` at
|
||||
/// `rate` Hz (`None` when unavailable).
|
||||
fn audio(&self, _item: ItemId, _footage: &Footage, _t: Tick, _frames: usize, _rate: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer parameters and audio for effects (see [`effectcraft_effects::EffectHost`]).
|
||||
struct FxHost<'r, 'a, 'c> {
|
||||
r: &'r Renderer<'a>,
|
||||
ctx: &'c EvalCtx<'a>,
|
||||
layer: &'c Layer,
|
||||
}
|
||||
|
||||
impl EffectHost for FxHost<'_, '_, '_> {
|
||||
fn layer(&self, id: u64, masks_and_effects: bool) -> Option<LayerPixels> {
|
||||
let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
|
||||
if other.id == self.layer.id || self.r.depth > 8 {
|
||||
return None;
|
||||
}
|
||||
let sub = Renderer { depth: self.r.depth + 1, ..*self.r };
|
||||
// The cached layer buffer is shared; effects get their own copy.
|
||||
let buf = if masks_and_effects { (*sub.layer_buf(self.ctx, other)?).clone() } else { sub.source(self.ctx, other)? };
|
||||
let size = source_size(self.r.project, other);
|
||||
let size = if size.0 == 0 { [self.ctx.comp.width as f64, self.ctx.comp.height as f64] } else { [size.0 as f64, size.1 as f64] };
|
||||
Some(LayerPixels { buf, size })
|
||||
}
|
||||
|
||||
fn audio(&self, id: u64, start: f64, frames: usize, rate: u32) -> Option<Vec<f32>> {
|
||||
let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
|
||||
let LayerSource::Footage { item } = &other.source else { return None };
|
||||
let ItemKind::Footage(f) = &self.r.project.item(*item)?.kind else { return None };
|
||||
if !f.has_audio {
|
||||
return None;
|
||||
}
|
||||
let st = other.layer_time(Tick::from_seconds_f64(start));
|
||||
self.r.footage.audio(*item, f, st, frames, rate)
|
||||
}
|
||||
}
|
||||
|
||||
/// No footage available (renders footage layers as transparent).
|
||||
@@ -46,11 +88,13 @@ pub struct RenderOpts {
|
||||
pub guides: bool,
|
||||
/// Draft quality: fewer motion-blur samples, bilinear only.
|
||||
pub draft: bool,
|
||||
/// 3D view camera override (viewer Front/Top/Custom views); None = the comp's active camera.
|
||||
pub view: Option<three_d::CameraState>,
|
||||
}
|
||||
|
||||
impl Default for RenderOpts {
|
||||
fn default() -> Self {
|
||||
RenderOpts { scale: 1.0, motion_blur: true, guides: false, draft: false }
|
||||
RenderOpts { scale: 1.0, motion_blur: true, guides: false, draft: false, view: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,13 +103,32 @@ pub struct Renderer<'a> {
|
||||
pub footage: &'a dyn FootageSource,
|
||||
pub expr: Option<&'a dyn ExprHost>,
|
||||
pub opts: RenderOpts,
|
||||
/// Processed-layer cache shared across frames (see [`cache`]). `None` renders everything.
|
||||
pub cache: Option<&'a LayerCache>,
|
||||
/// Optional per-layer timing sink (`frame --bench` / perf readouts).
|
||||
pub profile: Option<&'a std::sync::Mutex<Vec<LayerTiming>>>,
|
||||
/// Current nesting depth (precomp recursion guard).
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// Time spent on one layer of one frame (milliseconds).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LayerTiming {
|
||||
pub depth: usize,
|
||||
pub layer: String,
|
||||
/// Source + masks + effects (cache lookup only, on a hit).
|
||||
pub process_ms: f64,
|
||||
/// Per effect: (effect id, ms). Empty on a cache hit.
|
||||
pub effects: Vec<(String, f64)>,
|
||||
/// Transform + matte + blend.
|
||||
pub composite_ms: f64,
|
||||
/// The processed buffer came from the layer cache.
|
||||
pub cached: bool,
|
||||
}
|
||||
|
||||
impl<'a> Renderer<'a> {
|
||||
pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> {
|
||||
Renderer { project, footage, expr: None, opts, depth: 0 }
|
||||
Renderer { project, footage, expr: None, opts, cache: None, profile: None, depth: 0 }
|
||||
}
|
||||
|
||||
fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {
|
||||
@@ -98,11 +161,7 @@ impl<'a> Renderer<'a> {
|
||||
while j < visible.len() && visible[j].is_3d() {
|
||||
j += 1;
|
||||
}
|
||||
let mut run: Vec<(&Layer, f64)> = visible[i..j].iter().map(|l| (*l, ctx.layer_to_comp(l).1)).collect();
|
||||
run.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
for (l, _) in run {
|
||||
self.draw_layer(&ctx, l, &mut canvas);
|
||||
}
|
||||
three_d::compose::draw_run(self, &ctx, &visible[i..j], &mut canvas);
|
||||
i = j;
|
||||
} else {
|
||||
self.draw_layer(&ctx, visible[i], &mut canvas);
|
||||
@@ -126,7 +185,11 @@ impl<'a> Renderer<'a> {
|
||||
p
|
||||
}
|
||||
|
||||
fn apply_effects(&self, ctx: &EvalCtx, layer: &Layer, mut buf: Buf, adjustment: bool) -> Buf {
|
||||
fn apply_effects(&self, ctx: &EvalCtx, layer: &Layer, buf: Buf, adjustment: bool) -> Buf {
|
||||
self.apply_effects_timed(ctx, layer, buf, adjustment, None)
|
||||
}
|
||||
|
||||
fn apply_effects_timed(&self, ctx: &EvalCtx, layer: &Layer, mut buf: Buf, adjustment: bool, mut timing: Option<&mut Vec<(String, f64)>>) -> Buf {
|
||||
if !layer.switches.effects {
|
||||
return buf;
|
||||
}
|
||||
@@ -134,6 +197,9 @@ impl<'a> Renderer<'a> {
|
||||
let lt = layer.layer_time(ctx.time);
|
||||
let size = source_size(self.project, layer);
|
||||
let layer_size = if size.0 == 0 { [ctx.comp.width as f64, ctx.comp.height as f64] } else { [size.0 as f64, size.1 as f64] };
|
||||
let mask_shapes = masks::shapes(ctx, layer);
|
||||
let host = FxHost { r: self, ctx, layer };
|
||||
let env = EffectEnv { masks: &mask_shapes, host: Some(&host), comp_time: ctx.time.seconds(), frame_rate: ctx.comp.frame_rate.as_f64() };
|
||||
for g in fx.groups() {
|
||||
if !g.enabled {
|
||||
continue;
|
||||
@@ -141,8 +207,12 @@ impl<'a> Renderer<'a> {
|
||||
let GroupKind::Effect { effect } = &g.kind else { continue };
|
||||
let Some(spec) = effectcraft_effects::find(effect) else { continue };
|
||||
let params = self.effect_params(ctx, layer, g);
|
||||
let ectx = EffectCtx { params: ¶ms, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment };
|
||||
let ectx = EffectCtx { params: ¶ms, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment, env };
|
||||
let t0 = std::time::Instant::now();
|
||||
buf = effectcraft_effects::apply(spec, &ectx, buf);
|
||||
if let Some(v) = timing.as_deref_mut() {
|
||||
v.push((spec.id.to_string(), t0.elapsed().as_secs_f64() * 1e3));
|
||||
}
|
||||
}
|
||||
buf
|
||||
}
|
||||
@@ -165,8 +235,8 @@ impl<'a> Renderer<'a> {
|
||||
if self.project.comp_contains(*item, ctx.comp_id) {
|
||||
return None;
|
||||
}
|
||||
let sub = Renderer { project: self.project, footage: self.footage, expr: self.expr, opts: self.opts, depth: self.depth + 1 };
|
||||
let lt = layer.layer_time(ctx.time);
|
||||
let sub = Renderer { depth: self.depth + 1, ..*self };
|
||||
let lt = ctx.source_time(layer);
|
||||
Some(Buf { img: sub.comp_frame(*item, lt), offset: [0.0; 2], scale: s })
|
||||
}
|
||||
LayerSource::Footage { item } => {
|
||||
@@ -175,7 +245,7 @@ impl<'a> Renderer<'a> {
|
||||
if !f.has_video {
|
||||
return None;
|
||||
}
|
||||
let lt = layer.layer_time(ctx.time);
|
||||
let lt = ctx.source_time(layer);
|
||||
let img = self.footage.frame(*item, f, lt)?;
|
||||
let k = if img.width > 0 { f.width.max(1) as f64 / img.width as f64 } else { 1.0 };
|
||||
// Keep native pixels when downsampling is small; resample otherwise.
|
||||
@@ -193,10 +263,28 @@ impl<'a> Renderer<'a> {
|
||||
}
|
||||
|
||||
/// Fully processed layer buffer (source → masks → effects).
|
||||
pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
|
||||
/// Served from the layer cache when the layer's content key matches.
|
||||
pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
|
||||
self.layer_buf_timed(ctx, layer, None)
|
||||
}
|
||||
|
||||
fn layer_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<Arc<Buf>> {
|
||||
let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.opts.scale, self.opts.draft));
|
||||
if let (Some(c), Some(k)) = (self.cache, key)
|
||||
&& let Some(b) = c.get(k)
|
||||
{
|
||||
if let Some(t) = timing.as_deref_mut() {
|
||||
t.cached = true;
|
||||
}
|
||||
return Some(b);
|
||||
}
|
||||
let mut buf = self.source(ctx, layer)?;
|
||||
masks::apply(ctx, layer, &mut buf);
|
||||
Some(self.apply_effects(ctx, layer, buf, false))
|
||||
let buf = Arc::new(self.apply_effects_timed(ctx, layer, buf, false, timing.map(|t| &mut t.effects)));
|
||||
if let (Some(c), Some(k)) = (self.cache, key) {
|
||||
c.insert(k, buf.clone());
|
||||
}
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
fn sampling(&self, layer: &Layer) -> effectcraft_raster::Sampling {
|
||||
@@ -232,25 +320,14 @@ impl<'a> Renderer<'a> {
|
||||
let fd = ctx.comp.frame_duration().seconds();
|
||||
let angle = ctx.comp.shutter_angle / 360.0;
|
||||
let phase = ctx.comp.shutter_phase / 360.0;
|
||||
// Sub-samples sum straight into one buffer (each warp is row-parallel).
|
||||
let mut acc = Image::new(target.width, target.height);
|
||||
let accum: Vec<Image> = (0..samples)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let f = phase + angle * i as f64 / (samples - 1) as f64;
|
||||
let sub = ctx.at(ctx.time + Tick::from_seconds_f64(f * fd));
|
||||
let m = self.buf_matrix(&sub, layer, buf);
|
||||
let mut img = Image::new(target.width, target.height);
|
||||
composite_warp(&mut img, &buf.img, &m, &WarpOpts { mode: BlendMode::Normal, opacity: 1.0, ..opts });
|
||||
img
|
||||
})
|
||||
.collect();
|
||||
let k = 1.0 / samples as f32;
|
||||
for img in &accum {
|
||||
acc.data.par_iter_mut().zip(img.data.par_iter()).for_each(|(a, b)| {
|
||||
for c in 0..4 {
|
||||
a[c] += b[c] * k;
|
||||
}
|
||||
});
|
||||
for i in 0..samples {
|
||||
let f = phase + angle * i as f64 / (samples - 1) as f64;
|
||||
let sub = ctx.at(ctx.time + Tick::from_seconds_f64(f * fd));
|
||||
let m = self.buf_matrix(&sub, layer, buf);
|
||||
effectcraft_raster::accumulate_warp(&mut acc, &buf.img, &m, opts.sampling, k);
|
||||
}
|
||||
target.blend_from(&acc, mode, opacity, layer.id.0 as u32);
|
||||
}
|
||||
@@ -264,16 +341,34 @@ impl<'a> Renderer<'a> {
|
||||
self.draw_adjustment(ctx, layer, canvas, opacity);
|
||||
return;
|
||||
}
|
||||
let Some(buf) = self.layer_buf(ctx, layer) else { return };
|
||||
let Some(prof) = self.profile else {
|
||||
if let Some(buf) = self.layer_buf(ctx, layer) {
|
||||
self.composite_layer(ctx, layer, &buf, canvas, opacity);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let mut timing = LayerTiming { depth: self.depth, layer: layer.name.clone(), ..Default::default() };
|
||||
let t0 = std::time::Instant::now();
|
||||
let Some(buf) = self.layer_buf_timed(ctx, layer, Some(&mut timing)) else { return };
|
||||
let t1 = std::time::Instant::now();
|
||||
self.composite_layer(ctx, layer, &buf, canvas, opacity);
|
||||
timing.process_ms = (t1 - t0).as_secs_f64() * 1e3;
|
||||
timing.composite_ms = t1.elapsed().as_secs_f64() * 1e3;
|
||||
if let Ok(mut v) = prof.lock() {
|
||||
v.push(timing);
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_layer(&self, ctx: &EvalCtx, layer: &Layer, buf: &Buf, canvas: &mut Image, opacity: f32) {
|
||||
let matte = layer.track_matte.and_then(|tm| ctx.comp.layer(tm.layer).filter(|m| m.id != layer.id).map(|m| (m, tm.kind)));
|
||||
let preserve = layer.preserve_transparency;
|
||||
if matte.is_none() && !preserve {
|
||||
self.place(ctx, layer, &buf, canvas, layer.blend_mode, opacity);
|
||||
self.place(ctx, layer, buf, canvas, layer.blend_mode, opacity);
|
||||
return;
|
||||
}
|
||||
// Render in isolation, then matte / preserve transparency, then blend.
|
||||
let mut iso = Image::new(canvas.width, canvas.height);
|
||||
self.place(ctx, layer, &buf, &mut iso, BlendMode::Normal, 1.0);
|
||||
self.place(ctx, layer, buf, &mut iso, BlendMode::Normal, 1.0);
|
||||
if let Some((m, kind)) = matte {
|
||||
let mut mimg = Image::new(canvas.width, canvas.height);
|
||||
if m.is_active_at(ctx.time)
|
||||
@@ -332,6 +427,8 @@ pub fn render_frame(project: &Project, comp: ItemId, t: Tick, scale: f64) -> Ima
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_remap;
|
||||
|
||||
/// Layer-space bounds `[x0, y0, x1, y1]` of a layer's content at the context time (source size
|
||||
/// for solids/footage/precomps, glyph bounds for text, painted bounds for shapes). Used for viewer
|
||||
|
||||
@@ -39,6 +39,34 @@ fn coverage(ctx: &EvalCtx, layer: &Layer, g: &effectcraft_project::PropGroup, bu
|
||||
Some(cov)
|
||||
}
|
||||
|
||||
/// The layer's enabled masks at the context time, flattened to polylines in layer space (for
|
||||
/// effects that use masks as paths: Stroke, Scribble, Inner/Outer Key, Reshape…).
|
||||
pub fn shapes(ctx: &EvalCtx, layer: &Layer) -> Vec<effectcraft_effects::MaskShape> {
|
||||
let Some(masks) = layer.masks() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for g in masks.groups().filter(|g| g.enabled) {
|
||||
let GroupKind::Mask { inverted, .. } = g.kind else { continue };
|
||||
let Some(Value::Path(sp)) = ctx.group_value(layer, g, "path") else { continue };
|
||||
let path = effectcraft_path::to_kurbo(&sp);
|
||||
let mut pts: Vec<[f64; 2]> = Vec::new();
|
||||
let mut closed = false;
|
||||
kurbo::flatten(path.iter(), 0.25, |el| match el {
|
||||
effectcraft_path::PathEl::MoveTo(p) | effectcraft_path::PathEl::LineTo(p) => {
|
||||
if pts.last() != Some(&[p.x, p.y]) {
|
||||
pts.push([p.x, p.y]);
|
||||
}
|
||||
}
|
||||
effectcraft_path::PathEl::ClosePath => closed = true,
|
||||
_ => {}
|
||||
});
|
||||
if closed && pts.len() > 1 && pts.first() == pts.last() {
|
||||
pts.pop();
|
||||
}
|
||||
out.push(effectcraft_effects::MaskShape { name: g.name.clone(), points: pts, closed: closed || sp.closed, inverted });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply the layer's masks to its buffer.
|
||||
pub fn apply(ctx: &EvalCtx, layer: &Layer, buf: &mut Buf) {
|
||||
let Some(masks) = layer.masks() else { return };
|
||||
|
||||
@@ -160,3 +160,211 @@ fn effects_run_in_pipeline() {
|
||||
let c = img.get(100, 50);
|
||||
assert!(c[1] > 0.99 && c[0] < 0.01, "{c:?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------ layer cache
|
||||
|
||||
fn render_cached(p: &Project, cid: ItemId, t: Tick, cache: Option<&crate::LayerCache>) -> crate::Image {
|
||||
let mut r = crate::Renderer::new(p, &crate::NoFootage, crate::RenderOpts::default());
|
||||
r.cache = cache;
|
||||
r.comp_frame(cid, t)
|
||||
}
|
||||
|
||||
/// [`add_effect`] for a 200×100 layer.
|
||||
fn add_effect_200(p: &mut Project, l: &mut effectcraft_project::Layer, id: &str, vals: &[(&str, Value)]) {
|
||||
add_effect(p, l, id, [200.0, 100.0], vals);
|
||||
}
|
||||
|
||||
fn add_effect(p: &mut Project, l: &mut effectcraft_project::Layer, id: &str, size: [f64; 2], vals: &[(&str, Value)]) {
|
||||
let spec = effectcraft_effects::find(id).unwrap();
|
||||
let mut next = p.next_id;
|
||||
let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, size);
|
||||
p.next_id = next;
|
||||
for (k, v) in vals {
|
||||
g.prop_mut(k).unwrap().value = v.clone();
|
||||
}
|
||||
l.props.sub_mut("effects").unwrap().children.push(g.into());
|
||||
}
|
||||
|
||||
/// A comp with a static effected solid, an animated-trim shape, a moving text layer with a blur.
|
||||
fn cache_scene() -> (Project, ItemId) {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut bg = solid(&mut p, &comp, [0.2, 0.3, 0.4], 200, 100);
|
||||
add_effect_200(&mut p, &mut bg, "ec.color.tint", &[("white", Value::Color([1.0, 0.5, 0.0, 1.0]))]);
|
||||
let mut shape = build::layer(&mut p, &comp, "Shape", LayerSource::Shape, (200, 100), None);
|
||||
let mut next = p.next_id;
|
||||
{
|
||||
let mut ids = Ids(&mut next);
|
||||
let e = build::shape_ellipse(&mut ids, [60.0, 60.0], [0.0, 0.0]);
|
||||
let tr = build::shape_trim(&mut ids, 0.0, 0.0, 0.0);
|
||||
let s = build::shape_stroke(&mut ids, [1.0, 1.0, 1.0, 1.0], 4.0);
|
||||
let g = build::shape_group(&mut ids, "Ring", vec![e, tr, s]);
|
||||
shape.props.sub_mut("contents").unwrap().children.push(g.into());
|
||||
}
|
||||
p.next_id = next;
|
||||
shape.props.prop_mut("contents/group#1/contents/trim/end").unwrap().keys =
|
||||
vec![Keyframe::new(Tick::ZERO, Value::Scalar(10.0)), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Scalar(100.0))];
|
||||
let mut text = build::layer(&mut p, &comp, "Text", LayerSource::Text, (200, 100), None);
|
||||
text.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "AB".into(), size: 40.0, ..Default::default() }));
|
||||
text.props.prop_mut("transform/position").unwrap().keys =
|
||||
vec![Keyframe::new(Tick::ZERO, Value::Vec3([20.0, 70.0, 0.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec3([120.0, 70.0, 0.0]))];
|
||||
add_effect_200(&mut p, &mut text, "ec.blur.gaussian", &[("blurriness", Value::Scalar(6.0))]);
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
c.layers = vec![text, shape, bg];
|
||||
(p, cid)
|
||||
}
|
||||
|
||||
fn assert_same(a: &crate::Image, b: &crate::Image, what: &str) {
|
||||
assert_eq!((a.width, a.height), (b.width, b.height), "{what}");
|
||||
for (i, (p, q)) in a.data.iter().zip(&b.data).enumerate() {
|
||||
for c in 0..4 {
|
||||
assert!((p[c] - q[c]).abs() < 1e-6, "{what}: pixel {i}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_frames_match_uncached() {
|
||||
let (p, cid) = cache_scene();
|
||||
let cache = crate::LayerCache::default();
|
||||
for f in [0.0, 0.25, 0.5, 0.5, 1.2, 1.5, 0.25] {
|
||||
let t = Tick::from_seconds_f64(f);
|
||||
assert_same(&render_cached(&p, cid, t, Some(&cache)), &render_cached(&p, cid, t, None), &format!("t={f}"));
|
||||
}
|
||||
// bg is static, text only moves (transform), the shape is static after 1 s: lots of reuse.
|
||||
let st = cache.stats();
|
||||
assert!(st.hits >= 10, "{st:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_and_transform_only_layers_are_reused() {
|
||||
let (p, cid) = cache_scene();
|
||||
let cache = crate::LayerCache::default();
|
||||
render_cached(&p, cid, Tick::from_seconds_f64(0.2), Some(&cache));
|
||||
let before = cache.stats();
|
||||
render_cached(&p, cid, Tick::from_seconds_f64(0.4), Some(&cache));
|
||||
let after = cache.stats();
|
||||
// bg (static) + text (only its position animates) hit; the shape's trim animates: miss.
|
||||
assert_eq!(after.hits - before.hits, 2, "{before:?} {after:?}");
|
||||
assert_eq!(after.misses - before.misses, 1, "{before:?} {after:?}");
|
||||
}
|
||||
|
||||
type Edit = Box<dyn Fn(&mut Project, ItemId)>;
|
||||
|
||||
/// Every kind of edit re-renders the affected layer: the cached render of the edited project
|
||||
/// equals a fresh uncached render, and differs from the unedited frame.
|
||||
#[test]
|
||||
fn edits_invalidate_cached_layers() {
|
||||
let (p, cid) = cache_scene();
|
||||
let t = Tick::from_seconds_f64(0.5);
|
||||
let edits: Vec<(&str, Edit)> = vec![
|
||||
(
|
||||
"effect param value",
|
||||
Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[2].props.prop_mut("effects/#1/white").unwrap().value = Value::Color([0.0, 1.0, 0.0, 1.0])),
|
||||
),
|
||||
(
|
||||
"effect param keyframes",
|
||||
Box::new(|p, cid| {
|
||||
p.comp_mut(cid).unwrap().layers[0].props.prop_mut("effects/#1/blurriness").unwrap().keys =
|
||||
vec![Keyframe::new(Tick::ZERO, Value::Scalar(0.0)), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Scalar(30.0))]
|
||||
}),
|
||||
),
|
||||
("effect disabled", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[2].props.group_mut("effects/#1").unwrap().enabled = false)),
|
||||
("effects switch off", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[0].switches.effects = false)),
|
||||
(
|
||||
"effect added",
|
||||
Box::new(|p, cid| {
|
||||
let mut l = p.comp_mut(cid).unwrap().layers[2].clone();
|
||||
add_effect_200(p, &mut l, "ec.channel.invert", &[]);
|
||||
p.comp_mut(cid).unwrap().layers[2] = l;
|
||||
}),
|
||||
),
|
||||
(
|
||||
"shape keyframe moved",
|
||||
Box::new(|p, cid| {
|
||||
p.comp_mut(cid).unwrap().layers[1].props.prop_mut("contents/group#1/contents/trim/end").unwrap().keys[1].time = Tick::from_seconds_f64(2.0)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"text changed",
|
||||
Box::new(|p, cid| {
|
||||
p.comp_mut(cid).unwrap().layers[0].props.prop_mut("text/sourceText").unwrap().value =
|
||||
Value::Text(Box::new(TextDoc { text: "XYZ".into(), size: 40.0, ..Default::default() }))
|
||||
}),
|
||||
),
|
||||
(
|
||||
"solid colour",
|
||||
Box::new(|p, cid| {
|
||||
let LayerSource::Solid { item } = p.comp(cid).unwrap().layers[2].source else { unreachable!() };
|
||||
if let ItemKind::Solid(s) = &mut p.item_mut(item).unwrap().kind {
|
||||
s.color = [0.9, 0.1, 0.1];
|
||||
}
|
||||
p.comp_mut(cid).unwrap().layers[2].props.group_mut("effects/#1").unwrap().enabled = false;
|
||||
}),
|
||||
),
|
||||
(
|
||||
"mask added",
|
||||
Box::new(|p, cid| {
|
||||
let mut next = p.next_id;
|
||||
let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]);
|
||||
p.next_id = next;
|
||||
p.comp_mut(cid).unwrap().layers[2].props.sub_mut("masks").unwrap().children.push(m.into());
|
||||
}),
|
||||
),
|
||||
("layer time shifted", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[1].start_time = Tick::from_seconds_f64(0.3))),
|
||||
];
|
||||
for (what, edit) in edits {
|
||||
let cache = crate::LayerCache::default();
|
||||
let orig = render_cached(&p, cid, t, Some(&cache));
|
||||
let mut q = p.clone();
|
||||
edit(&mut q, cid);
|
||||
let cached = render_cached(&q, cid, t, Some(&cache));
|
||||
let fresh = render_cached(&q, cid, t, None);
|
||||
assert_same(&cached, &fresh, what);
|
||||
assert!(orig.data.iter().zip(&fresh.data).any(|(a, b)| (a[0] - b[0]).abs() + (a[3] - b[3]).abs() > 1e-3), "{what}: edit had no visible effect");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_dependent_effects_rerender_every_frame() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut l = solid(&mut p, &comp, [0.5, 0.5, 0.5], 200, 100);
|
||||
add_effect_200(&mut p, &mut l, "ec.noise.noise", &[("amount", Value::Scalar(50.0))]);
|
||||
p.comp_mut(cid).unwrap().layers.push(l);
|
||||
let cache = crate::LayerCache::default();
|
||||
let a = render_cached(&p, cid, Tick::from_seconds_f64(0.1), Some(&cache));
|
||||
let b = render_cached(&p, cid, Tick::from_seconds_f64(0.2), Some(&cache));
|
||||
assert_same(&b, &render_cached(&p, cid, Tick::from_seconds_f64(0.2), None), "noise at 0.2");
|
||||
assert!(a != b, "noise must animate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_see_layer_masks() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut l = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100);
|
||||
let mut next = p.next_id;
|
||||
let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::None, [255, 255, 0]);
|
||||
p.next_id = next;
|
||||
l.props.sub_mut("masks").unwrap().children.push(m.into());
|
||||
add_effect(&mut p, &mut l, "ec.generate.stroke", [200.0, 100.0], &[("brushSize", Value::Scalar(6.0))]);
|
||||
p.comp_mut(cid).unwrap().layers.push(l);
|
||||
let img = render_frame(&p, cid, Tick::ZERO, 1.0);
|
||||
assert!(img.get(30, 50)[0] > 0.5, "stroke on the mask edge: {:?}", img.get(30, 50));
|
||||
assert!(img.get(50, 50)[0] < 0.01, "inside untouched");
|
||||
assert!(img.get(150, 50)[3] > 0.99, "mode None mask does not cut the layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_read_layer_params() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut src = solid(&mut p, &comp, [0.0, 0.0, 1.0], 200, 100);
|
||||
src.switches.video = false;
|
||||
let src_id = src.id.0;
|
||||
let mut top = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100);
|
||||
add_effect(&mut p, &mut top, "ec.channel.blend", [200.0, 100.0], &[("blendWithLayer", Value::Layer(Some(src_id)))]);
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
c.layers.push(top);
|
||||
c.layers.push(src);
|
||||
let img = render_frame(&p, cid, Tick::ZERO, 1.0);
|
||||
let px = img.get(100, 50);
|
||||
assert!(px[2] > 0.99 && px[0] < 0.01, "{px:?}");
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Time remapping and separated Position dimensions.
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_keyframe::{Keyframe, Value};
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{Comp, ItemKind, LayerSource, Node, Project, Solid};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
use crate::render_frame;
|
||||
|
||||
fn s(x: f64) -> Tick {
|
||||
Tick::from_seconds_f64(x)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separated_position_drives_the_transform() {
|
||||
let mut p = Project::default();
|
||||
let comp = Comp::new(200, 100, FrameRate::FPS_30, s(2.0));
|
||||
let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into()));
|
||||
let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: 20, height: 20, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(&mut p, &comp, "S", LayerSource::Solid { item: sid }, (20, 20), None);
|
||||
let mut next = p.next_id;
|
||||
let mut ids = Ids(&mut next);
|
||||
let mut px = ids.prop("positionX", "X Position", Value::Scalar(20.0));
|
||||
px.keys = vec![Keyframe::new(Tick::ZERO, Value::Scalar(20.0)), Keyframe::new(s(1.0), Value::Scalar(180.0))];
|
||||
let py = ids.prop("positionY", "Y Position", Value::Scalar(50.0));
|
||||
let pz = ids.prop("positionZ", "Z Position", Value::Scalar(0.0));
|
||||
p.next_id = next;
|
||||
let tr = l.props.sub_mut("transform").unwrap();
|
||||
// The combined property is ignored while separated.
|
||||
tr.get_mut("position").unwrap().value = Value::Vec3([100.0, 10.0, 0.0]);
|
||||
tr.children.extend([Node::Prop(px), Node::Prop(py), Node::Prop(pz)]);
|
||||
p.comp_mut(cid).unwrap().layers.push(l);
|
||||
let a = render_frame(&p, cid, Tick::ZERO, 1.0);
|
||||
assert!(a.get(20, 50)[3] > 0.99 && a.get(100, 10)[3] < 0.01);
|
||||
let b = render_frame(&p, cid, s(0.5), 1.0);
|
||||
assert!(b.get(100, 50)[3] > 0.99 && b.get(20, 50)[3] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_remap_picks_the_source_frame() {
|
||||
let mut p = Project::default();
|
||||
let outer = Comp::new(100, 100, FrameRate::FPS_30, s(4.0));
|
||||
let mut inner = Comp::new(100, 100, FrameRate::FPS_30, s(4.0));
|
||||
// Inner comp: a solid that moves from x=10 (t=0) to x=90 (t=2).
|
||||
let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: 10, height: 10, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(&mut p, &inner, "S", LayerSource::Solid { item: sid }, (10, 10), None);
|
||||
l.props.prop_mut("transform/position").unwrap().keys =
|
||||
vec![Keyframe::new(Tick::ZERO, Value::Vec3([10.0, 50.0, 0.0])), Keyframe::new(s(2.0), Value::Vec3([90.0, 50.0, 0.0]))];
|
||||
inner.layers.push(l);
|
||||
let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
|
||||
let cid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.clone().into()));
|
||||
let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: iid }, (100, 100), None);
|
||||
let mut next = p.next_id;
|
||||
// Freeze on source time 2 s.
|
||||
let tr = Ids(&mut next).prop("timeRemap", "Time Remap", Value::Scalar(2.0));
|
||||
p.next_id = next;
|
||||
let mut tr = tr;
|
||||
tr.keys = vec![Keyframe::new(Tick::ZERO, Value::Scalar(2.0)).hold()];
|
||||
pre.props.children.push(Node::Prop(tr));
|
||||
p.comp_mut(cid).unwrap().layers.push(pre);
|
||||
let img = render_frame(&p, cid, Tick::ZERO, 1.0);
|
||||
assert!(img.get(90, 50)[3] > 0.99, "frozen at the end position");
|
||||
assert!(img.get(10, 50)[3] < 0.01);
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
//! Cameras: the comp's active camera (camera layers or the default 50 mm comp camera), the 3D
|
||||
//! views of the viewer (Front/Left/Top/Back/Right/Bottom orthographic views and three custom
|
||||
//! perspective views) and the camera-tool math (orbit, pan, dolly) shared by the engine commands.
|
||||
//!
|
||||
//! Conventions: world space is comp space (x right, y down, z into the screen). Camera space has
|
||||
//! x right, y down and z forward (depth). The perspective projection maps camera space to comp
|
||||
//! pixels as `x' = zoom·x/z + w/2`; orthographic views use `x' = zoom·x + w/2`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use effectcraft_geom::{Mat4, Vec2, Vec3, vec2, vec3};
|
||||
use effectcraft_project::{AutoOrient, Layer};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::EvalCtx;
|
||||
|
||||
/// Closest a perspective camera renders (camera-space z, pixels).
|
||||
pub const NEAR: f64 = 1.0;
|
||||
|
||||
/// Depth of field settings of a camera.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Dof {
|
||||
/// Distance from the eye to the plane in focus (pixels).
|
||||
pub focus: f64,
|
||||
/// Aperture diameter (pixels).
|
||||
pub aperture: f64,
|
||||
/// Blur Level (1.0 = 100%).
|
||||
pub blur_level: f64,
|
||||
}
|
||||
|
||||
impl Dof {
|
||||
/// Circle-of-confusion diameter (comp pixels) for a point at camera depth `z`.
|
||||
pub fn coc(&self, z: f64) -> f64 {
|
||||
if z <= NEAR || self.focus <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
self.aperture * (z - self.focus).abs() / z * self.blur_level
|
||||
}
|
||||
}
|
||||
|
||||
/// An evaluated camera.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CameraState {
|
||||
/// World → camera space (rigid).
|
||||
pub view: Mat4,
|
||||
/// Eye position in world space.
|
||||
pub eye: Vec3,
|
||||
/// Perspective: distance from the eye to the image plane (pixels). Orthographic: pixels per
|
||||
/// world unit.
|
||||
pub zoom: f64,
|
||||
pub ortho: bool,
|
||||
pub dof: Option<Dof>,
|
||||
}
|
||||
|
||||
impl CameraState {
|
||||
/// World → comp pixels (homogeneous: divide by `w` for perspective cameras).
|
||||
pub fn projection(&self, comp_w: f64, comp_h: f64) -> Mat4 {
|
||||
if self.ortho {
|
||||
let z = self.zoom;
|
||||
Mat4([[z, 0.0, 0.0, comp_w * 0.5], [0.0, z, 0.0, comp_h * 0.5], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) * self.view
|
||||
} else {
|
||||
effectcraft_geom::camera_matrix(comp_w, comp_h, self.eye, self.view, self.zoom)
|
||||
}
|
||||
}
|
||||
/// Camera-space depth of a world point.
|
||||
pub fn depth(&self, p: Vec3) -> f64 {
|
||||
self.view.apply(p).z
|
||||
}
|
||||
/// Unit view direction (world).
|
||||
pub fn forward(&self) -> Vec3 {
|
||||
let m = &self.view.0;
|
||||
vec3(m[2][0], m[2][1], m[2][2])
|
||||
}
|
||||
pub fn right(&self) -> Vec3 {
|
||||
let m = &self.view.0;
|
||||
vec3(m[0][0], m[0][1], m[0][2])
|
||||
}
|
||||
pub fn down(&self) -> Vec3 {
|
||||
let m = &self.view.0;
|
||||
vec3(m[1][0], m[1][1], m[1][2])
|
||||
}
|
||||
/// Project a world point to comp pixels; None when behind a perspective camera.
|
||||
pub fn project(&self, comp_w: f64, comp_h: f64, p: Vec3) -> Option<Vec2> {
|
||||
let c = self.view.apply(p);
|
||||
if self.ortho {
|
||||
return Some(vec2(self.zoom * c.x + comp_w * 0.5, self.zoom * c.y + comp_h * 0.5));
|
||||
}
|
||||
if c.z < NEAR {
|
||||
return None;
|
||||
}
|
||||
Some(vec2(self.zoom * c.x / c.z + comp_w * 0.5, self.zoom * c.y / c.z + comp_h * 0.5))
|
||||
}
|
||||
/// Direction from a shaded point towards the viewer.
|
||||
pub fn to_viewer(&self, p: Vec3) -> Vec3 {
|
||||
if self.ortho { -self.forward() } else { (self.eye - p).normalize() }
|
||||
}
|
||||
}
|
||||
|
||||
/// View matrix from an eye, a forward direction and a screen-down hint.
|
||||
pub fn basis_view(eye: Vec3, forward: Vec3, down_hint: Vec3) -> Mat4 {
|
||||
let f = forward.normalize();
|
||||
let f = if f.length() == 0.0 { vec3(0.0, 0.0, 1.0) } else { f };
|
||||
let mut d = down_hint - f * down_hint.dot(f);
|
||||
if d.length() < 1e-9 {
|
||||
d = if f.y.abs() < 0.99 { vec3(0.0, 1.0, 0.0) } else { vec3(0.0, 0.0, -1.0) };
|
||||
d = d - f * d.dot(f);
|
||||
}
|
||||
let d = d.normalize();
|
||||
let r = d.cross(f).normalize();
|
||||
Mat4([[r.x, r.y, r.z, 0.0], [d.x, d.y, d.z, 0.0], [f.x, f.y, f.z, 0.0], [0.0, 0.0, 0.0, 1.0]]) * Mat4::translate(-eye)
|
||||
}
|
||||
|
||||
/// Orientation angles (degrees, AE order X→Y→Z with Z = 0) that point +z along `dir`.
|
||||
pub fn orientation_for(dir: Vec3) -> [f64; 3] {
|
||||
let d = dir.normalize();
|
||||
let x = (-d.y).clamp(-1.0, 1.0).asin().to_degrees();
|
||||
let y = d.x.atan2(d.z).to_degrees();
|
||||
[norm360(x), norm360(y), 0.0]
|
||||
}
|
||||
|
||||
fn norm360(a: f64) -> f64 {
|
||||
let r = a.rem_euclid(360.0);
|
||||
if (r - 360.0).abs() < 1e-9 { 0.0 } else { r }
|
||||
}
|
||||
|
||||
/// AE's camera presets (35 mm film width 36 mm): (name, focal length mm).
|
||||
pub const PRESETS: [(&str, f64); 9] =
|
||||
[("15mm", 15.0), ("20mm", 20.0), ("24mm", 24.0), ("28mm", 28.0), ("35mm", 35.0), ("50mm", 50.0), ("80mm", 80.0), ("135mm", 135.0), ("200mm", 200.0)];
|
||||
|
||||
/// Film width the presets assume (mm, measured horizontally).
|
||||
pub const FILM_SIZE_MM: f64 = 36.0;
|
||||
|
||||
/// Zoom (pixels) for a focal length on a comp `comp_w` pixels wide.
|
||||
pub fn zoom_for_focal(comp_w: f64, focal_mm: f64) -> f64 {
|
||||
comp_w * focal_mm / FILM_SIZE_MM
|
||||
}
|
||||
|
||||
/// Focal length (mm) of a zoom value.
|
||||
pub fn focal_for_zoom(comp_w: f64, zoom: f64) -> f64 {
|
||||
zoom * FILM_SIZE_MM / comp_w.max(1.0)
|
||||
}
|
||||
|
||||
/// Horizontal angle of view (degrees) of a zoom value.
|
||||
pub fn angle_of_view(comp_w: f64, zoom: f64) -> f64 {
|
||||
2.0 * (comp_w * 0.5 / zoom.max(1e-9)).atan().to_degrees()
|
||||
}
|
||||
|
||||
/// Default aperture (pixels) of the presets: 25.3 mm at a 1920-pixel-wide comp, proportional.
|
||||
pub fn default_aperture(comp_w: f64) -> f64 {
|
||||
25.3 * comp_w / 1920.0
|
||||
}
|
||||
|
||||
/// The comp camera used when there is no camera layer: the 50 mm preset at (w/2, h/2, −zoom)
|
||||
/// looking at the comp centre, which shows the z = 0 plane at 100%.
|
||||
pub fn default_camera(comp_w: f64, comp_h: f64) -> CameraState {
|
||||
let zoom = effectcraft_geom::default_camera_zoom(comp_w);
|
||||
let eye = vec3(comp_w / 2.0, comp_h / 2.0, -zoom);
|
||||
CameraState { view: basis_view(eye, vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)), eye, zoom, ortho: false, dof: None }
|
||||
}
|
||||
|
||||
/// Whether a camera layer is two-node (auto-orients towards its Point of Interest).
|
||||
pub fn is_two_node(layer: &Layer) -> bool {
|
||||
layer.auto_orient == AutoOrient::TowardsPointOfInterest && layer.transform().is_some_and(|t| t.get("poi").is_some())
|
||||
}
|
||||
|
||||
/// Rotation of a camera/light layer from its Orientation and X/Y/Z Rotation (layer → parent).
|
||||
pub fn layer_rotation(ctx: &EvalCtx, layer: &Layer) -> Mat4 {
|
||||
let Some(tr) = layer.transform() else { return Mat4::IDENTITY };
|
||||
let o = ctx.v3(layer, tr, "orientation", [0.0; 3]);
|
||||
let rx = ctx.f(layer, tr, "rotationX", 0.0);
|
||||
let ry = ctx.f(layer, tr, "rotationY", 0.0);
|
||||
let rz = ctx.f(layer, tr, "rotation", 0.0);
|
||||
Mat4::orientation(Vec3::from(o)) * Mat4::rotate_z(rz) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx)
|
||||
}
|
||||
|
||||
/// World matrix of a layer's parent chain (identity when unparented).
|
||||
pub fn parent_world(ctx: &EvalCtx, layer: &Layer) -> Mat4 {
|
||||
match layer.parent.and_then(|p| ctx.comp.layer(p)) {
|
||||
Some(p) => ctx.world_matrix(p),
|
||||
None => Mat4::IDENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotation (local → parent) of a frame whose +z is `fwd` and whose +y is as close to
|
||||
/// `down_hint` as possible.
|
||||
pub fn basis_rotation(fwd: Vec3, down_hint: Vec3) -> Mat4 {
|
||||
let m = basis_view(Vec3::ZERO, fwd, down_hint).0;
|
||||
Mat4([[m[0][0], m[1][0], m[2][0], 0.0], [m[0][1], m[1][1], m[2][1], 0.0], [m[0][2], m[1][2], m[2][2], 0.0], [0.0, 0.0, 0.0, 1.0]])
|
||||
}
|
||||
|
||||
/// Local rotation (layer → parent) of a camera or light: auto-orient towards the Point of
|
||||
/// Interest (two-node), then Orientation and X/Y/Z Rotation.
|
||||
pub fn rig_rotation(ctx: &EvalCtx, layer: &Layer) -> Mat4 {
|
||||
let rot = layer_rotation(ctx, layer);
|
||||
match layer.transform().filter(|_| is_two_node(layer)) {
|
||||
Some(tr) => {
|
||||
let (w, h) = (ctx.comp.width as f64, ctx.comp.height as f64);
|
||||
let pos = Vec3::from(ctx.v3(layer, tr, "position", [w / 2.0, h / 2.0, -1000.0]));
|
||||
let poi = Vec3::from(ctx.v3(layer, tr, "poi", [w / 2.0, h / 2.0, 0.0]));
|
||||
basis_rotation(poi - pos, vec3(0.0, 1.0, 0.0)) * rot
|
||||
}
|
||||
None => rot,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- auto-orient
|
||||
|
||||
/// Direction of travel of a layer's position (parent space) at the context time.
|
||||
fn path_tangent(ctx: &EvalCtx, layer: &Layer) -> Option<Vec3> {
|
||||
let tr = layer.transform()?;
|
||||
// Position (or its separated X/Y/Z dimensions) must be animated.
|
||||
let moving = ["position", "positionX", "positionY", "positionZ"].iter().any(|m| tr.get(m).is_some_and(|p| p.keys.len() > 1 || p.has_expression()));
|
||||
if !moving {
|
||||
return None;
|
||||
}
|
||||
let dt = effectcraft_time::Tick::from_seconds_f64(0.005);
|
||||
let a = Vec3::from(ctx.at(ctx.time - dt).v3(layer, tr, "position", [0.0; 3]));
|
||||
let b = Vec3::from(ctx.at(ctx.time + dt).v3(layer, tr, "position", [0.0; 3]));
|
||||
let d = b - a;
|
||||
(d.length() > 1e-9).then(|| d.normalize())
|
||||
}
|
||||
|
||||
/// Auto-Orient ▸ Orient Along Path for 2D layers: extra Z rotation in degrees.
|
||||
pub fn auto_orient_2d(ctx: &EvalCtx, layer: &Layer) -> f64 {
|
||||
if layer.auto_orient != AutoOrient::AlongPath {
|
||||
return 0.0;
|
||||
}
|
||||
path_tangent(ctx, layer).map(|t| t.y.atan2(t.x).to_degrees()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Whether `id` is `layer` or one of its parents.
|
||||
fn in_parent_chain(ctx: &EvalCtx, layer: &Layer, id: effectcraft_project::LayerId) -> bool {
|
||||
let mut cur = Some(layer);
|
||||
let mut guard = 0;
|
||||
while let Some(l) = cur {
|
||||
if l.id == id || guard > 64 {
|
||||
return true;
|
||||
}
|
||||
guard += 1;
|
||||
cur = l.parent.and_then(|p| ctx.comp.layer(p));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Auto-orient for 3D layers: the rotation that replaces Orientation (Along Path: the layer's x
|
||||
/// axis follows the motion path; Towards Camera: the layer faces the active camera).
|
||||
pub fn auto_orient_3d(ctx: &EvalCtx, layer: &Layer, pos: Vec3) -> Option<Mat4> {
|
||||
match layer.auto_orient {
|
||||
AutoOrient::AlongPath => {
|
||||
let t = path_tangent(ctx, layer)?;
|
||||
// x = tangent, y ≈ down, z = x × y.
|
||||
let mut y = vec3(0.0, 1.0, 0.0) - t * t.y;
|
||||
if y.length() < 1e-9 {
|
||||
y = vec3(0.0, 0.0, 1.0) - t * t.z;
|
||||
}
|
||||
let y = y.normalize();
|
||||
let z = t.cross(y);
|
||||
Some(Mat4([[t.x, y.x, z.x, 0.0], [t.y, y.y, z.y, 0.0], [t.z, y.z, z.z, 0.0], [0.0, 0.0, 0.0, 1.0]]))
|
||||
}
|
||||
AutoOrient::TowardsCamera => {
|
||||
// A camera parented (through any chain) to this layer would recurse.
|
||||
if ctx.comp.active_camera(ctx.time).is_some_and(|c| in_parent_chain(ctx, c, layer.id)) {
|
||||
return None;
|
||||
}
|
||||
let eye = active_camera(ctx).eye;
|
||||
let e = parent_world(ctx, layer).inverse().unwrap_or(Mat4::IDENTITY).apply(eye);
|
||||
let d = pos - e;
|
||||
(d.length() > 1e-9).then(|| basis_rotation(d, vec3(0.0, 1.0, 0.0)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// (eye, forward, down) in world space of a camera or light layer.
|
||||
pub fn layer_frame(ctx: &EvalCtx, layer: &Layer) -> (Vec3, Vec3, Vec3) {
|
||||
let (w, h) = (ctx.comp.width as f64, ctx.comp.height as f64);
|
||||
let Some(tr) = layer.transform() else { return (vec3(w / 2.0, h / 2.0, -1000.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)) };
|
||||
let parent = parent_world(ctx, layer);
|
||||
let pos = Vec3::from(ctx.v3(layer, tr, "position", [w / 2.0, h / 2.0, -1000.0]));
|
||||
let local = rig_rotation(ctx, layer);
|
||||
let eye = parent.apply(pos);
|
||||
let fwd = parent.apply_vec(local.apply_vec(vec3(0.0, 0.0, 1.0))).normalize();
|
||||
let down = parent.apply_vec(local.apply_vec(vec3(0.0, 1.0, 0.0))).normalize();
|
||||
(eye, fwd, down)
|
||||
}
|
||||
|
||||
/// Evaluate a camera layer.
|
||||
pub fn layer_camera(ctx: &EvalCtx, cam: &Layer) -> CameraState {
|
||||
let w = ctx.comp.width as f64;
|
||||
let (eye, fwd, down) = layer_frame(ctx, cam);
|
||||
let opts = cam.props.sub("cameraOptions");
|
||||
let zoom = opts.map(|g| ctx.f(cam, g, "zoom", 1000.0)).unwrap_or(1000.0).max(1e-3);
|
||||
let dof = opts.filter(|g| ctx.b(cam, g, "dof")).map(|g| Dof {
|
||||
focus: ctx.f(cam, g, "focusDistance", zoom),
|
||||
aperture: ctx.f(cam, g, "aperture", default_aperture(w)).max(0.0),
|
||||
blur_level: ctx.f(cam, g, "blurLevel", 100.0).max(0.0) / 100.0,
|
||||
});
|
||||
CameraState { view: basis_view(eye, fwd, down), eye, zoom, ortho: false, dof }
|
||||
}
|
||||
|
||||
/// The comp's active camera at the context time (topmost active camera layer, else the default).
|
||||
pub fn active_camera(ctx: &EvalCtx) -> CameraState {
|
||||
match ctx.comp.active_camera(ctx.time) {
|
||||
Some(cam) => layer_camera(ctx, cam),
|
||||
None => default_camera(ctx.comp.width as f64, ctx.comp.height as f64),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3D views
|
||||
|
||||
/// The viewer's 3D views (View ▸ Switch 3D View).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum View3D {
|
||||
#[default]
|
||||
ActiveCamera,
|
||||
Front,
|
||||
Left,
|
||||
Top,
|
||||
Back,
|
||||
Right,
|
||||
Bottom,
|
||||
Custom1,
|
||||
Custom2,
|
||||
Custom3,
|
||||
}
|
||||
|
||||
impl View3D {
|
||||
pub const ALL: [View3D; 10] = [
|
||||
View3D::ActiveCamera,
|
||||
View3D::Front,
|
||||
View3D::Left,
|
||||
View3D::Top,
|
||||
View3D::Back,
|
||||
View3D::Right,
|
||||
View3D::Bottom,
|
||||
View3D::Custom1,
|
||||
View3D::Custom2,
|
||||
View3D::Custom3,
|
||||
];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
View3D::ActiveCamera => "Active Camera",
|
||||
View3D::Front => "Front",
|
||||
View3D::Left => "Left",
|
||||
View3D::Top => "Top",
|
||||
View3D::Back => "Back",
|
||||
View3D::Right => "Right",
|
||||
View3D::Bottom => "Bottom",
|
||||
View3D::Custom1 => "Custom View 1",
|
||||
View3D::Custom2 => "Custom View 2",
|
||||
View3D::Custom3 => "Custom View 3",
|
||||
}
|
||||
}
|
||||
/// Stable id used by commands (`activeCamera`, `front`, `custom1`…).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
View3D::ActiveCamera => "activeCamera",
|
||||
View3D::Front => "front",
|
||||
View3D::Left => "left",
|
||||
View3D::Top => "top",
|
||||
View3D::Back => "back",
|
||||
View3D::Right => "right",
|
||||
View3D::Bottom => "bottom",
|
||||
View3D::Custom1 => "custom1",
|
||||
View3D::Custom2 => "custom2",
|
||||
View3D::Custom3 => "custom3",
|
||||
}
|
||||
}
|
||||
pub fn from_id(s: &str) -> Option<View3D> {
|
||||
let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
|
||||
View3D::ALL.into_iter().find(|v| v.id().eq_ignore_ascii_case(&k) || v.label().replace(' ', "").eq_ignore_ascii_case(&k))
|
||||
}
|
||||
pub fn is_ortho(self) -> bool {
|
||||
matches!(self, View3D::Front | View3D::Left | View3D::Top | View3D::Back | View3D::Right | View3D::Bottom)
|
||||
}
|
||||
}
|
||||
|
||||
/// A view camera: eye, point of interest, screen-down hint, zoom (perspective) or scale (ortho).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ViewCam {
|
||||
pub eye: [f64; 3],
|
||||
pub poi: [f64; 3],
|
||||
pub down: [f64; 3],
|
||||
pub zoom: f64,
|
||||
pub ortho: bool,
|
||||
}
|
||||
|
||||
impl ViewCam {
|
||||
pub fn state(&self) -> CameraState {
|
||||
let eye = Vec3::from(self.eye);
|
||||
let poi = Vec3::from(self.poi);
|
||||
CameraState { view: basis_view(eye, poi - eye, Vec3::from(self.down)), eye, zoom: self.zoom, ortho: self.ortho, dof: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Default camera of a view for a `w`×`h` comp.
|
||||
pub fn default_view_cam(v: View3D, w: f64, h: f64) -> ViewCam {
|
||||
let c = vec3(w / 2.0, h / 2.0, 0.0);
|
||||
let zoom = effectcraft_geom::default_camera_zoom(w);
|
||||
let far = 10_000.0;
|
||||
let ortho = |fwd: Vec3, down: Vec3| ViewCam { eye: arr(c - fwd * far), poi: arr(c), down: arr(down), zoom: 0.5, ortho: true };
|
||||
let custom = |yaw: f64, pitch: f64| {
|
||||
// Orbit the default camera around the comp centre (yaw about y, then pitch).
|
||||
let off = Mat4::rotate_y(yaw).apply_vec(Mat4::rotate_x(pitch).apply_vec(vec3(0.0, 0.0, -zoom * 1.6)));
|
||||
ViewCam { eye: arr(c + off), poi: arr(c), down: [0.0, 1.0, 0.0], zoom, ortho: false }
|
||||
};
|
||||
match v {
|
||||
View3D::ActiveCamera | View3D::Front => ortho(vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)),
|
||||
View3D::Back => ortho(vec3(0.0, 0.0, -1.0), vec3(0.0, 1.0, 0.0)),
|
||||
View3D::Left => ortho(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)),
|
||||
View3D::Right => ortho(vec3(-1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)),
|
||||
View3D::Top => ortho(vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, -1.0)),
|
||||
View3D::Bottom => ortho(vec3(0.0, -1.0, 0.0), vec3(0.0, 0.0, 1.0)),
|
||||
// Custom views look down at the comp from above-left, above and above-right.
|
||||
View3D::Custom1 => custom(30.0, -20.0),
|
||||
View3D::Custom2 => custom(0.0, -35.0),
|
||||
View3D::Custom3 => custom(-30.0, -20.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn arr(v: Vec3) -> [f64; 3] {
|
||||
[v.x, v.y, v.z]
|
||||
}
|
||||
|
||||
/// Per-comp 3D view state of the viewer (current view + edited view cameras).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Views3D {
|
||||
pub current: View3D,
|
||||
/// The view before the last switch (View ▸ Switch to Last 3D View).
|
||||
#[serde(default)]
|
||||
pub last: View3D,
|
||||
/// Edited view cameras (views not present use their defaults).
|
||||
#[serde(default)]
|
||||
pub cams: BTreeMap<View3D, ViewCam>,
|
||||
}
|
||||
|
||||
impl Views3D {
|
||||
pub fn cam(&self, v: View3D, w: f64, h: f64) -> ViewCam {
|
||||
self.cams.get(&v).copied().unwrap_or_else(|| default_view_cam(v, w, h))
|
||||
}
|
||||
/// Camera override for rendering: None for the active camera view.
|
||||
pub fn override_camera(&self, w: f64, h: f64) -> Option<CameraState> {
|
||||
(self.current != View3D::ActiveCamera).then(|| self.cam(self.current, w, h).state())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- camera tools
|
||||
|
||||
/// A camera as edited by the tools: position, point of interest, zoom (two-node form).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Rig {
|
||||
pub eye: Vec3,
|
||||
pub poi: Vec3,
|
||||
pub zoom: f64,
|
||||
pub ortho: bool,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
pub fn from_view(v: &ViewCam) -> Rig {
|
||||
Rig { eye: Vec3::from(v.eye), poi: Vec3::from(v.poi), zoom: v.zoom, ortho: v.ortho }
|
||||
}
|
||||
fn frame(&self) -> (Vec3, Vec3, Vec3) {
|
||||
let s =
|
||||
CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None };
|
||||
(s.forward(), s.right(), s.down())
|
||||
}
|
||||
/// Orbit the eye around the point of interest: `yaw` about world Y, `pitch` about the
|
||||
/// camera's right axis (degrees). Pitch is limited short of straight up/down.
|
||||
pub fn orbit(&mut self, yaw: f64, pitch: f64) {
|
||||
if self.ortho {
|
||||
return;
|
||||
}
|
||||
let off = self.eye - self.poi;
|
||||
let dist = off.length().max(1e-6);
|
||||
let cur_pitch = (off.y / dist).clamp(-1.0, 1.0).asin().to_degrees();
|
||||
let new_pitch = (cur_pitch + pitch).clamp(-89.0, 89.0);
|
||||
let horiz = vec3(off.x, 0.0, off.z);
|
||||
let hl = horiz.length();
|
||||
let az = if hl > 1e-9 { off.x.atan2(-off.z).to_degrees() } else { 0.0 } + yaw;
|
||||
let (sp, cp) = new_pitch.to_radians().sin_cos();
|
||||
let (sa, ca) = az.to_radians().sin_cos();
|
||||
self.eye = self.poi + vec3(sa * cp, sp, -ca * cp) * dist;
|
||||
}
|
||||
/// Pan in the image plane by (`dx`, `dy`) comp pixels (as seen at the point of interest).
|
||||
pub fn pan(&mut self, dx: f64, dy: f64) {
|
||||
let (_, r, d) = self.frame();
|
||||
let k = if self.ortho { 1.0 / self.zoom.max(1e-9) } else { (self.poi - self.eye).length() / self.zoom.max(1e-9) };
|
||||
let delta = r * (-dx * k) + d * (-dy * k);
|
||||
self.eye += delta;
|
||||
self.poi += delta;
|
||||
}
|
||||
/// Dolly along the view direction by `amount` pixels (positive = towards the POI). With
|
||||
/// `with_poi` the point of interest travels too (camera layers: Track Z); otherwise the
|
||||
/// eye stops short of the POI. Orthographic views scale instead.
|
||||
pub fn dolly(&mut self, amount: f64, with_poi: bool) {
|
||||
if self.ortho {
|
||||
self.zoom = (self.zoom * (amount / 500.0).exp()).clamp(0.01, 100.0);
|
||||
return;
|
||||
}
|
||||
let (f, _, _) = self.frame();
|
||||
if with_poi {
|
||||
self.eye += f * amount;
|
||||
self.poi += f * amount;
|
||||
} else {
|
||||
let dist = (self.poi - self.eye).length();
|
||||
let d = amount.min(dist - 1.0);
|
||||
self.eye += f * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
//! The Classic 3D compositor for a run of consecutive 3D layers.
|
||||
//!
|
||||
//! Each layer is a textured plane: its processed buffer (source → masks → effects, DOF-blurred)
|
||||
//! mapped through `projection · world`. Rendering is per output pixel (rows in parallel): every
|
||||
//! plane covering the pixel is inverse-mapped through its homography (exact perspective-correct
|
||||
//! texture coordinates, bilinear/bicubic sampling), its camera depth taken from the plane
|
||||
//! equation, and the fragment shaded by the comp's lights. The pixel's fragments are then sorted
|
||||
//! far→near (coplanar fragments keep layer-stack order) and blended with each layer's mode and
|
||||
//! opacity. Sorting per pixel handles intersecting layers exactly, and blend modes and partial
|
||||
//! transparency still compose in depth order, as in AE's Classic 3D renderer.
|
||||
//!
|
||||
//! Shadows are ray-cast against the shadow-casting planes (exact for planar layers, including
|
||||
//! alpha-shaped and coloured shadows through Light Transmission); Shadow Diffusion softens them
|
||||
//! with a penumbra that grows with the distance between caster and receiver.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_color::{BlendMode, blend_pixel};
|
||||
use effectcraft_effects::Buf;
|
||||
use effectcraft_geom::{Mat3, Mat4, Vec3, vec3};
|
||||
use effectcraft_project::{Layer, LightKind, MatteKind};
|
||||
use effectcraft_raster::{Image, Px, hash_noise};
|
||||
use effectcraft_time::Tick;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use super::camera::{CameraState, NEAR, active_camera};
|
||||
use super::light::{LightState, Material, lights_at, shade};
|
||||
use crate::{EvalCtx, Renderer};
|
||||
|
||||
/// One position of a plane (several with motion blur).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Geo {
|
||||
/// Output pixel → homogeneous layer coordinates.
|
||||
hinv: Mat3,
|
||||
/// Camera-space depth as a function of layer (u, v): `d0·u + d1·v + d2`.
|
||||
depth: [f64; 3],
|
||||
world: Mat4,
|
||||
normal: Vec3,
|
||||
/// Output pixel bounds [x0, y0, x1, y1) covered by the plane.
|
||||
bbox: [i64; 4],
|
||||
cam: CameraState,
|
||||
}
|
||||
|
||||
/// A prepared 3D layer.
|
||||
pub(crate) struct Item<'a> {
|
||||
pub layer: &'a Layer,
|
||||
/// Position in the layer stack (higher = above).
|
||||
order: usize,
|
||||
buf: Arc<Buf>,
|
||||
bicubic: bool,
|
||||
geos: Vec<Geo>,
|
||||
mat: Material,
|
||||
opacity: f32,
|
||||
/// Drawn (false for "Casts Shadows: Only" and shadow-only casters outside the run).
|
||||
draw: bool,
|
||||
/// Screen-space track matte factor (output size).
|
||||
matte: Option<Vec<f32>>,
|
||||
preserve: bool,
|
||||
/// World → layer (for shadow rays) and the buffer's layer-space bounds.
|
||||
winv: Mat4,
|
||||
bounds: [f64; 4],
|
||||
bbox: [i64; 4],
|
||||
}
|
||||
|
||||
impl Item<'_> {
|
||||
#[inline]
|
||||
fn texel(&self, u: f64, v: f64) -> Px {
|
||||
let x = u * self.buf.scale + self.buf.offset[0];
|
||||
let y = v * self.buf.scale + self.buf.offset[1];
|
||||
if self.bicubic { self.buf.img.sample_bicubic(x, y) } else { self.buf.img.sample_bilinear(x, y) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the plane geometry of a layer for a camera.
|
||||
fn geo(cam: &CameraState, world: Mat4, buf: &Buf, comp: (f64, f64), scale: f64, out: (u32, u32)) -> Option<Geo> {
|
||||
let proj = Mat4::scale(vec3(scale, scale, 1.0)) * cam.projection(comp.0, comp.1);
|
||||
let full = proj * world;
|
||||
let h = full.plane_to_mat3();
|
||||
let hinv = h.inverse()?;
|
||||
let cv = cam.view * world;
|
||||
let depth = [cv.0[2][0], cv.0[2][1], cv.0[2][3]];
|
||||
let normal = world.apply_vec(vec3(1.0, 0.0, 0.0)).cross(world.apply_vec(vec3(0.0, 1.0, 0.0)));
|
||||
if normal.length() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let normal = normal.normalize();
|
||||
let b = buf_bounds(buf);
|
||||
let corners = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])];
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
let mut behind = 0;
|
||||
let mut full_frame = false;
|
||||
for (u, v) in corners {
|
||||
let z = depth[0] * u + depth[1] * v + depth[2];
|
||||
if !cam.ortho && z < NEAR {
|
||||
behind += 1;
|
||||
full_frame = true;
|
||||
continue;
|
||||
}
|
||||
let p = full.apply(vec3(u, v, 0.0));
|
||||
x0 = x0.min(p.x);
|
||||
y0 = y0.min(p.y);
|
||||
x1 = x1.max(p.x);
|
||||
y1 = y1.max(p.y);
|
||||
}
|
||||
if behind == 4 {
|
||||
return None;
|
||||
}
|
||||
let (ow, oh) = (out.0 as i64, out.1 as i64);
|
||||
let bbox = if full_frame {
|
||||
[0, 0, ow, oh]
|
||||
} else {
|
||||
[((x0.floor() as i64) - 2).max(0), ((y0.floor() as i64) - 2).max(0), ((x1.ceil() as i64) + 2).min(ow), ((y1.ceil() as i64) + 2).min(oh)]
|
||||
};
|
||||
if bbox[0] >= bbox[2] || bbox[1] >= bbox[3] {
|
||||
return None;
|
||||
}
|
||||
Some(Geo { hinv, depth, world, normal, bbox, cam: *cam })
|
||||
}
|
||||
|
||||
/// Layer-space rectangle covered by a buffer.
|
||||
fn buf_bounds(buf: &Buf) -> [f64; 4] {
|
||||
let s = buf.scale.max(1e-9);
|
||||
[-buf.offset[0] / s, -buf.offset[1] / s, (buf.img.width as f64 - buf.offset[0]) / s, (buf.img.height as f64 - buf.offset[1]) / s]
|
||||
}
|
||||
|
||||
/// Inverse-map an output pixel centre onto a plane: (u, v, camera depth).
|
||||
#[inline]
|
||||
fn unproject(g: &Geo, sx: f64, sy: f64) -> Option<(f64, f64, f64)> {
|
||||
let h = &g.hinv.0;
|
||||
let qz = h[2][0] * sx + h[2][1] * sy + h[2][2];
|
||||
if !g.cam.ortho && qz <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if qz.abs() < 1e-300 {
|
||||
return None;
|
||||
}
|
||||
let u = (h[0][0] * sx + h[0][1] * sy + h[0][2]) / qz;
|
||||
let v = (h[1][0] * sx + h[1][1] * sy + h[1][2]) / qz;
|
||||
let z = g.depth[0] * u + g.depth[1] * v + g.depth[2];
|
||||
if !g.cam.ortho && z < NEAR {
|
||||
return None;
|
||||
}
|
||||
Some((u, v, z))
|
||||
}
|
||||
|
||||
/// The camera a renderer uses at a context time (view override only for the top-level comp).
|
||||
pub(crate) fn camera_for(r: &Renderer, ctx: &EvalCtx) -> CameraState {
|
||||
match r.opts.view {
|
||||
Some(v) if r.depth == 0 => v,
|
||||
_ => active_camera(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of motion-blur sub-samples for a layer.
|
||||
fn mb_samples(r: &Renderer, ctx: &EvalCtx, layer: &Layer) -> usize {
|
||||
if r.opts.motion_blur && ctx.comp.enable_motion_blur && layer.switches.motion_blur {
|
||||
if r.opts.draft { 4 } else { ctx.comp.motion_blur_samples.clamp(2, 64) as usize }
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare a layer (buffer, geometry, material). `None` when it shows nothing.
|
||||
pub(crate) fn prepare<'a>(r: &Renderer, ctx: &EvalCtx<'a>, layer: &'a Layer, order: usize, out: (u32, u32), in_run: bool) -> Option<Item<'a>> {
|
||||
let mut buf = r.layer_buf(ctx, layer)?;
|
||||
if buf.img.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let comp = (ctx.comp.width as f64, ctx.comp.height as f64);
|
||||
let s = r.opts.scale;
|
||||
let cam = camera_for(r, ctx);
|
||||
let world = ctx.world_matrix(layer);
|
||||
// Depth of field: blur the layer by its circle of confusion at its centre.
|
||||
if let Some(dof) = cam.dof.filter(|_| !ctx.comp.draft_3d && !r.opts.draft) {
|
||||
let b = buf_bounds(&buf);
|
||||
let centre = world.apply(vec3((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5, 0.0));
|
||||
let z = cam.depth(centre);
|
||||
let coc = dof.coc(z);
|
||||
// Comp pixels on screen per layer pixel at that depth.
|
||||
let k = cam.zoom / z.max(NEAR) * world.apply_vec(vec3(1.0, 0.0, 0.0)).length().max(1e-9);
|
||||
let radius = coc * 0.5 / k * buf.scale;
|
||||
if radius > 0.3 {
|
||||
let sigma = radius / 1.5;
|
||||
let pad = (sigma * 3.0).ceil() as u32 + 1;
|
||||
let padded = buf.img.padded(pad);
|
||||
// The (cached, shared) layer buffer stays untouched; the blurred copy is per frame.
|
||||
buf = Arc::new(Buf {
|
||||
img: effectcraft_raster::gaussian_blur(&padded, sigma, sigma, false),
|
||||
offset: [buf.offset[0] + pad as f64, buf.offset[1] + pad as f64],
|
||||
scale: buf.scale,
|
||||
});
|
||||
}
|
||||
}
|
||||
let n = if in_run { mb_samples(r, ctx, layer) } else { 1 };
|
||||
let geos: Vec<Geo> = if n <= 1 {
|
||||
geo(&cam, world, &buf, comp, s, out).into_iter().collect()
|
||||
} else {
|
||||
let fd = ctx.comp.frame_duration().seconds();
|
||||
let angle = ctx.comp.shutter_angle / 360.0;
|
||||
let phase = ctx.comp.shutter_phase / 360.0;
|
||||
(0..n)
|
||||
.filter_map(|i| {
|
||||
let f = phase + angle * i as f64 / (n - 1) as f64;
|
||||
let sub = ctx.at(ctx.time + Tick::from_seconds_f64(f * fd));
|
||||
let c = camera_for(r, &sub);
|
||||
geo(&c, sub.world_matrix(layer), &buf, comp, s, out)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if geos.is_empty() && in_run {
|
||||
return None;
|
||||
}
|
||||
let mut bbox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];
|
||||
for g in &geos {
|
||||
bbox = [bbox[0].min(g.bbox[0]), bbox[1].min(g.bbox[1]), bbox[2].max(g.bbox[2]), bbox[3].max(g.bbox[3])];
|
||||
}
|
||||
let mat = Material::of(ctx, layer);
|
||||
let bounds = buf_bounds(&buf);
|
||||
Some(Item {
|
||||
layer,
|
||||
order,
|
||||
bicubic: matches!(r.sampling(layer), effectcraft_raster::Sampling::Bicubic),
|
||||
buf,
|
||||
geos,
|
||||
opacity: ctx.opacity(layer) as f32,
|
||||
draw: in_run && mat.casts_shadows != 2,
|
||||
mat,
|
||||
matte: None,
|
||||
preserve: layer.preserve_transparency,
|
||||
winv: world.inverse().unwrap_or(Mat4::IDENTITY),
|
||||
bounds,
|
||||
bbox,
|
||||
})
|
||||
}
|
||||
|
||||
/// Screen-space track matte factor for a layer, or None.
|
||||
fn matte_for(r: &Renderer, ctx: &EvalCtx, layer: &Layer, out: (u32, u32)) -> Option<Vec<f32>> {
|
||||
let tm = layer.track_matte?;
|
||||
let m = ctx.comp.layer(tm.layer).filter(|m| m.id != layer.id)?;
|
||||
let mut img = Image::new(out.0, out.1);
|
||||
if m.is_active_at(ctx.time) {
|
||||
if m.is_3d() {
|
||||
// Render the matte plane alone (its own matte is ignored).
|
||||
let mut solo = m.clone();
|
||||
solo.track_matte = None;
|
||||
solo.preserve_transparency = false;
|
||||
solo.blend_mode = BlendMode::Normal;
|
||||
if let Some(it) = prepare(r, ctx, &solo, 0, out, true) {
|
||||
let lights = scene_lights(ctx);
|
||||
composite(&mut img, &[it], &lights, &[], m.id.0 as u32);
|
||||
}
|
||||
} else if let Some(mb) = r.layer_buf(ctx, m) {
|
||||
r.place(ctx, m, &mb, &mut img, BlendMode::Normal, ctx.opacity(m) as f32);
|
||||
}
|
||||
}
|
||||
Some(
|
||||
img.data
|
||||
.par_iter()
|
||||
.map(|q| {
|
||||
match tm.kind {
|
||||
MatteKind::Alpha => q[3],
|
||||
MatteKind::AlphaInverted => 1.0 - q[3],
|
||||
MatteKind::Luma => effectcraft_color::luminance(q[0], q[1], q[2]),
|
||||
MatteKind::LumaInverted => 1.0 - effectcraft_color::luminance(q[0], q[1], q[2]),
|
||||
}
|
||||
.clamp(0.0, 1.0)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Lights used for shading: none in Draft 3D (which also turns off shadows and depth of field).
|
||||
fn scene_lights(ctx: &EvalCtx) -> Vec<LightState> {
|
||||
if ctx.comp.draft_3d { vec![] } else { lights_at(ctx) }
|
||||
}
|
||||
|
||||
/// Draw a run of consecutive 3D layers (bottom-to-top order) into `canvas`.
|
||||
pub(crate) fn draw_run(r: &Renderer, ctx: &EvalCtx, run: &[&Layer], canvas: &mut Image) {
|
||||
// 3D adjustment layers act on everything below them in the stack (like 2D ones): split.
|
||||
if let Some(k) = run.iter().position(|l| l.switches.adjustment) {
|
||||
draw_run(r, ctx, &run[..k], canvas);
|
||||
r.draw_layer(ctx, run[k], canvas);
|
||||
draw_run(r, ctx, &run[k + 1..], canvas);
|
||||
return;
|
||||
}
|
||||
if run.is_empty() {
|
||||
return;
|
||||
}
|
||||
let out = (canvas.width, canvas.height);
|
||||
let lights = scene_lights(ctx);
|
||||
let mut items: Vec<Item> = run
|
||||
.par_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, l)| ctx.opacity(l) > 0.0)
|
||||
.filter_map(|(i, l)| {
|
||||
let mut it = prepare(r, ctx, l, i, out, true)?;
|
||||
it.matte = matte_for(r, ctx, l, out);
|
||||
Some(it)
|
||||
})
|
||||
.collect();
|
||||
// Shadow casters outside this run (other 3D layers of the comp).
|
||||
let mut extra: Vec<Item> = vec![];
|
||||
if lights.iter().any(|l| l.casts_shadows && l.kind != LightKind::Ambient) {
|
||||
let in_run: Vec<_> = run.iter().map(|l| l.id).collect();
|
||||
extra = ctx
|
||||
.comp
|
||||
.layers
|
||||
.par_iter()
|
||||
.filter(|l| l.switches.three_d && l.has_video() && l.is_active_at(ctx.time) && !in_run.contains(&l.id) && !l.switches.adjustment)
|
||||
.filter(|l| Material::of(ctx, l).casts_shadows != 0)
|
||||
.filter_map(|l| prepare(r, ctx, l, 0, out, false))
|
||||
.collect();
|
||||
}
|
||||
items.sort_by_key(|i| i.order);
|
||||
let casters: Vec<&Item> = items.iter().chain(extra.iter()).filter(|i| i.mat.casts_shadows != 0 && !i.geos.is_empty()).collect();
|
||||
composite(canvas, &items, &lights, &casters, run[0].id.0 as u32);
|
||||
}
|
||||
|
||||
/// Per-pixel depth-sorted compositing of prepared planes.
|
||||
fn composite(canvas: &mut Image, items: &[Item], lights: &[LightState], casters: &[&Item], seed: u32) {
|
||||
let w = canvas.width as usize;
|
||||
canvas.rows_mut().for_each(|(y, row)| {
|
||||
let yi = y as i64;
|
||||
let active: Vec<&Item> = items.iter().filter(|it| it.draw && yi >= it.bbox[1] && yi < it.bbox[3]).collect();
|
||||
if active.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut frags: Vec<(f64, usize, Px, usize)> = Vec::with_capacity(active.len());
|
||||
for x in 0..w {
|
||||
let xi = x as i64;
|
||||
frags.clear();
|
||||
for (k, it) in active.iter().enumerate() {
|
||||
if xi < it.bbox[0] || xi >= it.bbox[2] {
|
||||
continue;
|
||||
}
|
||||
if let Some((z, px)) = fragment(it, x as f64 + 0.5, y as f64 + 0.5, lights, casters) {
|
||||
let px = match &it.matte {
|
||||
Some(m) => {
|
||||
let f = m[y * w + x];
|
||||
[px[0] * f, px[1] * f, px[2] * f, px[3] * f]
|
||||
}
|
||||
None => px,
|
||||
};
|
||||
if px[3] > 0.0 || px[0] != 0.0 || px[1] != 0.0 || px[2] != 0.0 {
|
||||
frags.push((z, it.order, px, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
if frags.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Far → near; (near-)coplanar fragments in stack order (lower layer first).
|
||||
for i in 1..frags.len() {
|
||||
let mut j = i;
|
||||
while j > 0 && before(&frags[j], &frags[j - 1]) {
|
||||
frags.swap(j, j - 1);
|
||||
j -= 1;
|
||||
}
|
||||
}
|
||||
let mut d = row[x];
|
||||
for (_, _, px, k) in &frags {
|
||||
let it = active[*k];
|
||||
let mut s = *px;
|
||||
let op = it.opacity * if it.preserve { d[3] } else { 1.0 };
|
||||
for c in s.iter_mut() {
|
||||
*c *= op;
|
||||
}
|
||||
let mode = it.layer.blend_mode;
|
||||
let n = if matches!(mode, BlendMode::Dissolve | BlendMode::DancingDissolve) {
|
||||
hash_noise(x as u32, y as u32, seed ^ it.layer.id.0 as u32)
|
||||
} else {
|
||||
0.5
|
||||
};
|
||||
d = blend_pixel(mode, d, s, n);
|
||||
}
|
||||
row[x] = d;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn before(a: &(f64, usize, Px, usize), b: &(f64, usize, Px, usize)) -> bool {
|
||||
let tol = 1e-6 * a.0.abs().max(b.0.abs()).max(1.0);
|
||||
if (a.0 - b.0).abs() <= tol { a.1 < b.1 } else { a.0 > b.0 }
|
||||
}
|
||||
|
||||
/// Shaded premultiplied fragment of a plane at an output pixel centre, with its depth.
|
||||
fn fragment(it: &Item, sx: f64, sy: f64, lights: &[LightState], casters: &[&Item]) -> Option<(f64, Px)> {
|
||||
let n = it.geos.len();
|
||||
let mut acc = [0.0f32; 4];
|
||||
let mut depth = None;
|
||||
for g in &it.geos {
|
||||
let Some((u, v, z)) = unproject(g, sx, sy) else { continue };
|
||||
let t = it.texel(u, v);
|
||||
if t[3] <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
depth.get_or_insert(z);
|
||||
let px = shade_texel(it, g, u, v, t, lights, casters);
|
||||
for c in 0..4 {
|
||||
acc[c] += px[c];
|
||||
}
|
||||
}
|
||||
let depth = depth?;
|
||||
if n > 1 {
|
||||
let k = 1.0 / n as f32;
|
||||
for c in acc.iter_mut() {
|
||||
*c *= k;
|
||||
}
|
||||
}
|
||||
Some((depth, acc))
|
||||
}
|
||||
|
||||
fn shade_texel(it: &Item, g: &Geo, u: f64, v: f64, t: Px, lights: &[LightState], casters: &[&Item]) -> Px {
|
||||
if lights.is_empty() || !it.mat.accepts_lights {
|
||||
if it.mat.accepts_shadows == 2 {
|
||||
return [0.0; 4];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
let a = t[3];
|
||||
let rgb = [t[0] / a, t[1] / a, t[2] / a];
|
||||
let p = g.world.apply(vec3(u, v, 0.0));
|
||||
let shadow = |li: usize, p: Vec3| -> [f32; 3] {
|
||||
let l = &lights[li];
|
||||
let mut tr = [1.0f32; 3];
|
||||
for c in casters {
|
||||
if std::ptr::eq(*c, it) || c.layer.id == it.layer.id {
|
||||
continue;
|
||||
}
|
||||
let o = occlusion(c, p, l);
|
||||
for k in 0..3 {
|
||||
tr[k] *= o[k];
|
||||
}
|
||||
}
|
||||
tr
|
||||
};
|
||||
let (lit, shadow_amt) = shade(rgb, p, g.normal, g.cam.to_viewer(p), &it.mat, lights, &shadow);
|
||||
if it.mat.accepts_shadows == 2 {
|
||||
return [0.0, 0.0, 0.0, a * shadow_amt];
|
||||
}
|
||||
[lit[0] * a, lit[1] * a, lit[2] * a, a]
|
||||
}
|
||||
|
||||
/// RGB transmittance of light `l` reaching `p` past caster `c` (1 = unoccluded).
|
||||
fn occlusion(c: &Item, p: Vec3, l: &LightState) -> [f32; 3] {
|
||||
const FAR: f64 = 1.0e6;
|
||||
let a = c.winv.apply(p);
|
||||
let target = if l.kind == LightKind::Parallel { p - l.dir * FAR } else { l.pos };
|
||||
let b = c.winv.apply(target);
|
||||
if a.z == b.z || a.z.signum() == b.z.signum() {
|
||||
return [1.0; 3];
|
||||
}
|
||||
let t = a.z / (a.z - b.z);
|
||||
if t <= 1e-6 || t >= 1.0 - 1e-9 {
|
||||
return [1.0; 3];
|
||||
}
|
||||
let hit = a + (b - a) * t;
|
||||
// Penumbra radius (layer pixels) from Shadow Diffusion: grows with receiver–caster distance.
|
||||
let seg = (target - p).length();
|
||||
let d_pc = seg * t;
|
||||
let d_cl = if l.kind == LightKind::Parallel { 1000.0 } else { (seg * (1.0 - t)).max(1.0) };
|
||||
let r = l.shadow_diffusion * (d_pc / d_cl).min(4.0);
|
||||
let bd = &c.bounds;
|
||||
if hit.x < bd[0] - r || hit.y < bd[1] - r || hit.x > bd[2] + r || hit.y > bd[3] + r {
|
||||
return [1.0; 3];
|
||||
}
|
||||
let mut px = [0.0f32; 4];
|
||||
if r * c.buf.scale < 0.5 {
|
||||
px = c.texel(hit.x, hit.y);
|
||||
} else {
|
||||
for j in -1..=1 {
|
||||
for i in -1..=1 {
|
||||
let q = c.texel(hit.x + i as f64 * r * 0.66, hit.y + j as f64 * r * 0.66);
|
||||
for k in 0..4 {
|
||||
px[k] += q[k] / 9.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let alpha = (px[3] * c.opacity).clamp(0.0, 1.0);
|
||||
if alpha <= 0.0 {
|
||||
return [1.0; 3];
|
||||
}
|
||||
let tr = c.mat.light_transmission;
|
||||
let dark = l.shadow_darkness as f32;
|
||||
let mut out = [1.0f32; 3];
|
||||
for k in 0..3 {
|
||||
let straight = if px[3] > 0.0 { (px[k] / px[3]).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let pass = (1.0 - alpha) + alpha * tr * straight;
|
||||
out[k] = 1.0 - dark * (1.0 - pass);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Lights and Classic 3D shading.
|
||||
//!
|
||||
//! Shading model (per light, Blinn-Phong on the layer plane, lit from both sides):
|
||||
//! `colour = texture · (ambient_mat · Σ ambient + diffuse_mat · Σ diffuse) + specular`, where a
|
||||
//! light's diffuse term is `colour · intensity · max(N·L, 0) · falloff · cone · shadow`, light from
|
||||
//! behind the layer passes through by Light Transmission, and the specular highlight
|
||||
//! `(N·H)^shininess` takes the light's colour mixed towards the layer's colour by Metal.
|
||||
//! A comp without lights shows 3D layers unlit.
|
||||
|
||||
use effectcraft_geom::{Vec3, vec3};
|
||||
use effectcraft_project::{Layer, LightKind};
|
||||
|
||||
use super::camera::layer_frame;
|
||||
use crate::EvalCtx;
|
||||
|
||||
/// An evaluated light.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct LightState {
|
||||
pub kind: LightKind,
|
||||
/// World position (point/spot; parallel lights use it only for the shadow source).
|
||||
pub pos: Vec3,
|
||||
/// Unit direction the light travels (parallel/spot).
|
||||
pub dir: Vec3,
|
||||
/// Linear colour × intensity (1.0 = 100%).
|
||||
pub color: [f32; 3],
|
||||
/// Spot cone half-angle (radians) and feather (0..1).
|
||||
pub cone_half: f64,
|
||||
pub feather: f64,
|
||||
/// Falloff: 0 None, 1 Smooth, 2 Inverse Square Clamped.
|
||||
pub falloff: u32,
|
||||
pub radius: f64,
|
||||
pub falloff_distance: f64,
|
||||
pub casts_shadows: bool,
|
||||
/// 0..1.
|
||||
pub shadow_darkness: f64,
|
||||
/// Pixels.
|
||||
pub shadow_diffusion: f64,
|
||||
}
|
||||
|
||||
impl LightState {
|
||||
/// Evaluate a light layer.
|
||||
pub fn from_layer(ctx: &EvalCtx, layer: &Layer) -> Option<LightState> {
|
||||
let effectcraft_project::LayerSource::Light { kind } = layer.source else { return None };
|
||||
let g = layer.props.sub("lightOptions")?;
|
||||
let intensity = ctx.f(layer, g, "intensity", 100.0) / 100.0;
|
||||
let c = ctx.color(layer, g, "color");
|
||||
let color = [(c[0] as f64 * intensity) as f32, (c[1] as f64 * intensity) as f32, (c[2] as f64 * intensity) as f32];
|
||||
let (pos, fwd, _) = layer_frame(ctx, layer);
|
||||
// Spot/parallel lights aim at their point of interest (auto-orient), then rotate.
|
||||
let dir = fwd;
|
||||
Some(LightState {
|
||||
kind,
|
||||
pos,
|
||||
dir,
|
||||
color,
|
||||
cone_half: (ctx.f(layer, g, "coneAngle", 90.0).clamp(0.0, 180.0) / 2.0).to_radians(),
|
||||
feather: ctx.f(layer, g, "coneFeather", 50.0).clamp(0.0, 100.0) / 100.0,
|
||||
falloff: ctx.e(layer, g, "falloff"),
|
||||
radius: ctx.f(layer, g, "radius", 500.0).max(0.0),
|
||||
falloff_distance: ctx.f(layer, g, "falloffDistance", 500.0).max(0.0),
|
||||
casts_shadows: ctx.b(layer, g, "castsShadows"),
|
||||
shadow_darkness: ctx.f(layer, g, "shadowDarkness", 100.0).clamp(0.0, 100.0) / 100.0,
|
||||
shadow_diffusion: ctx.f(layer, g, "shadowDiffusion", 0.0).max(0.0),
|
||||
})
|
||||
}
|
||||
|
||||
/// Unit vector from a point towards the light, and the distance (∞ for parallel lights).
|
||||
pub fn to_light(&self, p: Vec3) -> (Vec3, f64) {
|
||||
match self.kind {
|
||||
LightKind::Parallel => (-self.dir, f64::INFINITY),
|
||||
_ => {
|
||||
let d = self.pos - p;
|
||||
let len = d.length();
|
||||
if len < 1e-9 { (vec3(0.0, 0.0, -1.0), 0.0) } else { (d / len, len) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Distance attenuation × spot cone factor at `p` (0..1).
|
||||
pub fn attenuation(&self, p: Vec3) -> f64 {
|
||||
let (l, dist) = self.to_light(p);
|
||||
let mut k = match self.falloff {
|
||||
1 if dist.is_finite() => {
|
||||
// Smooth: full within Radius, smooth to zero over Falloff Distance.
|
||||
if dist <= self.radius {
|
||||
1.0
|
||||
} else if self.falloff_distance <= 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
let t = ((dist - self.radius) / self.falloff_distance).clamp(0.0, 1.0);
|
||||
1.0 - t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
}
|
||||
2 if dist.is_finite() => {
|
||||
// Inverse square, clamped to 1 inside Radius.
|
||||
if dist <= self.radius || self.radius <= 0.0 && dist <= 1.0 { 1.0 } else { (self.radius.max(1.0) / dist).powi(2) }
|
||||
}
|
||||
_ => 1.0,
|
||||
};
|
||||
if self.kind == LightKind::Spot {
|
||||
let cos_a = (-l).dot(self.dir).clamp(-1.0, 1.0);
|
||||
let a = cos_a.acos();
|
||||
let outer = self.cone_half;
|
||||
let inner = outer * (1.0 - self.feather);
|
||||
k *= if a <= inner {
|
||||
1.0
|
||||
} else if a >= outer {
|
||||
0.0
|
||||
} else {
|
||||
let t = (a - inner) / (outer - inner).max(1e-9);
|
||||
1.0 - t * t * (3.0 - 2.0 * t)
|
||||
};
|
||||
}
|
||||
k
|
||||
}
|
||||
}
|
||||
|
||||
/// All lights switched on and active at the context time.
|
||||
pub fn lights_at(ctx: &EvalCtx) -> Vec<LightState> {
|
||||
ctx.comp.layers.iter().filter(|l| l.is_light() && l.switches.video && l.is_active_at(ctx.time)).filter_map(|l| LightState::from_layer(ctx, l)).collect()
|
||||
}
|
||||
|
||||
/// Material Options of a 3D layer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Material {
|
||||
/// 0 Off, 1 On, 2 Only.
|
||||
pub casts_shadows: u32,
|
||||
/// 0..1.
|
||||
pub light_transmission: f32,
|
||||
/// 0 Off, 1 On, 2 Only.
|
||||
pub accepts_shadows: u32,
|
||||
pub accepts_lights: bool,
|
||||
pub ambient: f32,
|
||||
pub diffuse: f32,
|
||||
pub specular: f32,
|
||||
/// 0..1.
|
||||
pub shininess: f32,
|
||||
pub metal: f32,
|
||||
}
|
||||
|
||||
impl Default for Material {
|
||||
fn default() -> Self {
|
||||
Material {
|
||||
casts_shadows: 0,
|
||||
light_transmission: 0.0,
|
||||
accepts_shadows: 1,
|
||||
accepts_lights: true,
|
||||
ambient: 1.0,
|
||||
diffuse: 0.5,
|
||||
specular: 0.5,
|
||||
shininess: 0.05,
|
||||
metal: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Material {
|
||||
pub fn of(ctx: &EvalCtx, layer: &Layer) -> Material {
|
||||
let Some(g) = layer.props.sub("materialOptions") else { return Material::default() };
|
||||
let d = Material::default();
|
||||
let pct = |m: &str, def: f32| (ctx.f(layer, g, m, def as f64 * 100.0) / 100.0) as f32;
|
||||
Material {
|
||||
casts_shadows: g.get("castsShadows").map(|p| ctx.value(layer, p).as_enum()).unwrap_or(d.casts_shadows),
|
||||
light_transmission: pct("lightTransmission", d.light_transmission).clamp(0.0, 1.0),
|
||||
accepts_shadows: g.get("acceptsShadows").map(|p| ctx.value(layer, p).as_enum()).unwrap_or(d.accepts_shadows),
|
||||
accepts_lights: g.get("acceptsLights").map(|p| ctx.value(layer, p).as_bool()).unwrap_or(true),
|
||||
ambient: pct("ambient", d.ambient),
|
||||
diffuse: pct("diffuse", d.diffuse),
|
||||
specular: pct("specularIntensity", d.specular),
|
||||
shininess: pct("specularShininess", d.shininess).clamp(0.0, 1.0),
|
||||
metal: pct("metal", d.metal).clamp(0.0, 1.0),
|
||||
}
|
||||
}
|
||||
/// Blinn-Phong exponent for Specular Shininess (0% → 1, 100% → 256).
|
||||
pub fn exponent(&self) -> f64 {
|
||||
256f64.powf(self.shininess as f64).max(1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shade one straight-alpha texel at world point `p` with unit normal `n`.
|
||||
///
|
||||
/// `to_viewer` is the unit direction towards the viewer; `shadow(light_index, p)` returns the
|
||||
/// RGB light transmittance (1 = unshadowed). Returns the lit straight RGB colour and the summed
|
||||
/// shadow amount (0..1, used by "Accepts Shadows: Only").
|
||||
pub fn shade(
|
||||
rgb: [f32; 3],
|
||||
p: Vec3,
|
||||
n: Vec3,
|
||||
to_viewer: Vec3,
|
||||
mat: &Material,
|
||||
lights: &[LightState],
|
||||
shadow: &dyn Fn(usize, Vec3) -> [f32; 3],
|
||||
) -> ([f32; 3], f32) {
|
||||
if lights.is_empty() || !mat.accepts_lights {
|
||||
return (rgb, 0.0);
|
||||
}
|
||||
let n = if n.dot(to_viewer) < 0.0 { -n } else { n };
|
||||
let mut amb = [0.0f32; 3];
|
||||
let mut diff = [0.0f32; 3];
|
||||
let mut spec = [0.0f32; 3];
|
||||
let mut shadow_amt = 0.0f32;
|
||||
let exp = mat.exponent();
|
||||
for (i, l) in lights.iter().enumerate() {
|
||||
if l.kind == LightKind::Ambient {
|
||||
for c in 0..3 {
|
||||
amb[c] += l.color[c];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let k = l.attenuation(p);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (lv, _) = l.to_light(p);
|
||||
let ndl = n.dot(lv);
|
||||
let front = ndl > 0.0;
|
||||
let lambert = if front { ndl } else { -ndl * mat.light_transmission as f64 };
|
||||
if lambert <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let sh = if l.casts_shadows && mat.accepts_shadows != 0 { shadow(i, p) } else { [1.0; 3] };
|
||||
shadow_amt = shadow_amt.max(1.0 - (sh[0] + sh[1] + sh[2]) / 3.0);
|
||||
let kd = (lambert * k) as f32;
|
||||
for c in 0..3 {
|
||||
diff[c] += l.color[c] * kd * sh[c];
|
||||
}
|
||||
if front && mat.specular > 0.0 {
|
||||
let h = (lv + to_viewer).normalize();
|
||||
let s = (n.dot(h).max(0.0).powf(exp) * k) as f32;
|
||||
for c in 0..3 {
|
||||
// Metal: highlight colour from the light (0%) to the layer colour (100%).
|
||||
let tint = 1.0 + (rgb[c] - 1.0) * mat.metal;
|
||||
spec[c] += l.color[c] * s * sh[c] * tint;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = [0.0f32; 3];
|
||||
for c in 0..3 {
|
||||
out[c] = rgb[c] * (mat.ambient * amb[c] + mat.diffuse * diff[c]) + mat.specular * spec[c];
|
||||
}
|
||||
(out, shadow_amt)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Classic 3D: cameras, 3D views, lights, materials and the depth-sorted, lit, shadowed
|
||||
//! compositor for runs of 3D layers.
|
||||
//!
|
||||
//! The 2D compositor (`Renderer::comp_frame`) walks the layer stack bottom-to-top; each run of
|
||||
//! consecutive 3D layers is handed to [`compose::draw_run`] as a group (2D layers break 3D
|
||||
//! groups, as in After Effects).
|
||||
|
||||
pub mod camera;
|
||||
pub(crate) mod compose;
|
||||
pub mod light;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_orient;
|
||||
|
||||
pub use camera::{CameraState, Dof, Rig, View3D, ViewCam, Views3D, active_camera, default_camera, default_view_cam};
|
||||
pub use light::{LightState, Material, lights_at};
|
||||
|
||||
use effectcraft_geom::Mat3;
|
||||
use effectcraft_project::Layer;
|
||||
|
||||
use crate::EvalCtx;
|
||||
|
||||
/// Layer space → comp pixels through `cam` (2D projective), for viewer overlays and picking in
|
||||
/// any 3D view. 2D layers ignore the camera.
|
||||
pub fn layer_to_view(ctx: &EvalCtx, layer: &Layer, cam: &CameraState) -> Mat3 {
|
||||
if !layer.is_3d() {
|
||||
return ctx.layer_to_comp(layer).0;
|
||||
}
|
||||
let (w, h) = (ctx.comp.width as f64, ctx.comp.height as f64);
|
||||
(cam.projection(w, h) * ctx.world_matrix(layer)).plane_to_mat3()
|
||||
}
|
||||
|
||||
/// Project a world point into comp pixels through `cam` (None behind a perspective camera).
|
||||
pub fn project_point(ctx: &EvalCtx, cam: &CameraState, p: [f64; 3]) -> Option<[f64; 2]> {
|
||||
cam.project(ctx.comp.width as f64, ctx.comp.height as f64, p.into()).map(|v| [v.x, v.y])
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_geom::{Vec3, vec3};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build;
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, LightKind, Project, Solid};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
use super::camera::{Rig, View3D, default_view_cam, orientation_for};
|
||||
use super::*;
|
||||
use crate::{NoFootage, RenderOpts, Renderer, render_frame};
|
||||
|
||||
const W: u32 = 200;
|
||||
const H: u32 = 100;
|
||||
|
||||
fn setup() -> (Project, ItemId, Comp) {
|
||||
let mut p = Project::default();
|
||||
let comp = Comp::new(W, H, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
|
||||
let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into()));
|
||||
(p, cid, comp)
|
||||
}
|
||||
|
||||
/// A 3D solid of `w`×`h` centred at `pos`.
|
||||
fn solid3(p: &mut Project, comp: &Comp, color: [f32; 3], w: u32, h: u32, pos: [f64; 3]) -> Layer {
|
||||
let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(p, comp, "Solid", LayerSource::Solid { item: sid }, (w, h), None);
|
||||
l.switches.three_d = true;
|
||||
set(&mut l, "transform/position", Value::Vec3(pos));
|
||||
l
|
||||
}
|
||||
|
||||
fn set(l: &mut Layer, path: &str, v: Value) {
|
||||
l.props.prop_mut(path).unwrap_or_else(|| panic!("no {path}")).value = v;
|
||||
}
|
||||
|
||||
fn push(p: &mut Project, cid: ItemId, l: Layer) {
|
||||
// Appended = lowest in the stack.
|
||||
p.comp_mut(cid).unwrap().layers.push(l);
|
||||
}
|
||||
|
||||
fn render(p: &Project, cid: ItemId) -> effectcraft_raster::Image {
|
||||
render_frame(p, cid, Tick::ZERO, 1.0)
|
||||
}
|
||||
|
||||
fn close(a: f32, b: f32, eps: f32) -> bool {
|
||||
(a - b).abs() <= eps
|
||||
}
|
||||
|
||||
fn zoom() -> f64 {
|
||||
W as f64 * 50.0 / 36.0
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- projection
|
||||
|
||||
#[test]
|
||||
fn z0_plane_matches_2d() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let l = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 40, 20, [50.0, 30.0, 0.0]);
|
||||
push(&mut p, cid, l);
|
||||
let img = render(&p, cid);
|
||||
// Covers x 30..70, y 20..40.
|
||||
assert_eq!(img.get(31, 21), [1.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(img.get(68, 38), [1.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(img.get(29, 30)[3], 0.0);
|
||||
assert_eq!(img.get(71, 30)[3], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn farther_layers_project_smaller() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
// At z = zoom the plane is twice as far from the eye: half size around the comp centre.
|
||||
let l = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 80, 40, [100.0, 50.0, zoom()]);
|
||||
push(&mut p, cid, l);
|
||||
let img = render(&p, cid);
|
||||
// 40×20 centred on (100, 50): x 80..120, y 40..60.
|
||||
assert!(img.get(82, 42)[3] > 0.99);
|
||||
assert!(img.get(117, 57)[3] > 0.99);
|
||||
assert!(img.get(77, 50)[3] < 0.01, "{:?}", img.get(77, 50));
|
||||
assert!(img.get(100, 37)[3] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_math_matches_camera_state() {
|
||||
let cam = default_camera(1920.0, 1080.0);
|
||||
let pr = cam.projection(1920.0, 1080.0);
|
||||
let p = pr.apply(vec3(100.0, 200.0, 0.0));
|
||||
assert!((p.x - 100.0).abs() < 1e-6 && (p.y - 200.0).abs() < 1e-6);
|
||||
// A point at depth 2·zoom maps halfway to the centre.
|
||||
let q = cam.project(1920.0, 1080.0, vec3(0.0, 0.0, cam.zoom)).unwrap();
|
||||
assert!((q.x - 480.0).abs() < 1e-6 && (q.y - 270.0).abs() < 1e-6, "{q:?}");
|
||||
assert!(cam.project(1920.0, 1080.0, vec3(960.0, 540.0, -cam.zoom - 10.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn y_rotation_foreshortens_with_correct_perspective() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut l = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 100, 60, [100.0, 50.0, 0.0]);
|
||||
set(&mut l, "transform/rotationY", Value::Scalar(60.0));
|
||||
push(&mut p, cid, l);
|
||||
let img = render(&p, cid);
|
||||
// cos 60° = 0.5: roughly half as wide; the near edge (right, z<0) is taller than the far edge.
|
||||
assert!(img.get(100, 50)[3] > 0.99);
|
||||
assert!(img.get(140, 50)[3] < 0.01);
|
||||
let col_h = |x: u32| (0..H).filter(|&y| img.get(x as i64, y as i64)[3] > 0.5).count();
|
||||
assert!(col_h(122) > col_h(78), "near edge {} vs far edge {}", col_h(122), col_h(78));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_behind_camera_is_clipped() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let l = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100, [100.0, 50.0, -zoom() - 50.0]);
|
||||
push(&mut p, cid, l);
|
||||
let img = render(&p, cid);
|
||||
assert!(img.data.iter().all(|px| px[3] == 0.0));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- depth ordering
|
||||
|
||||
#[test]
|
||||
fn nearer_layer_wins_regardless_of_stack_order() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let far = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 600, 300, [100.0, 50.0, 200.0]);
|
||||
let near = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 40, 40, [100.0, 50.0, 0.0]);
|
||||
// Far layer is on top of the stack.
|
||||
push(&mut p, cid, far);
|
||||
push(&mut p, cid, near);
|
||||
let img = render(&p, cid);
|
||||
assert_eq!(img.get(100, 50), [0.0, 1.0, 0.0, 1.0]);
|
||||
assert_eq!(img.get(5, 50)[0], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coplanar_layers_keep_stack_order() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let top = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 40, 40, [100.0, 50.0, 30.0]);
|
||||
let bottom = solid3(&mut p, &comp, [0.0, 0.0, 1.0], 80, 80, [100.0, 50.0, 30.0]);
|
||||
push(&mut p, cid, top);
|
||||
push(&mut p, cid, bottom);
|
||||
let img = render(&p, cid);
|
||||
assert_eq!(img.get(100, 50), [1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersecting_planes_split_per_pixel() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let flat = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 160, 80, [100.0, 50.0, 0.0]);
|
||||
let mut tilted = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 160, 80, [100.0, 50.0, 0.0]);
|
||||
// Rotated about Y: its right half comes towards the camera, its left half goes behind.
|
||||
set(&mut tilted, "transform/rotationY", Value::Scalar(40.0));
|
||||
push(&mut p, cid, tilted);
|
||||
push(&mut p, cid, flat);
|
||||
let img = render(&p, cid);
|
||||
assert_eq!(img.get(125, 50), [0.0, 1.0, 0.0, 1.0], "right: tilted plane in front");
|
||||
assert_eq!(img.get(75, 50), [1.0, 0.0, 0.0, 1.0], "left: flat plane in front");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_d_layer_breaks_3d_group() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let far_top = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 60, 60, [100.0, 50.0, 300.0]);
|
||||
let sid = p.add_item("S2", Label::Red, None, ItemKind::Solid(Solid { color: [0.0, 0.0, 1.0], width: 20, height: 100, pixel_aspect: 1.0 }));
|
||||
let mut two_d = build::layer(&mut p, &comp, "2D", LayerSource::Solid { item: sid }, (20, 100), None);
|
||||
set(&mut two_d, "transform/position", Value::Vec3([100.0, 50.0, 0.0]));
|
||||
let near_bottom = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 200, 100, [100.0, 50.0, 0.0]);
|
||||
// Stack: far 3D (top), 2D, near 3D (bottom). The far layer is a separate group above the
|
||||
// 2D layer, so it draws over everything even though it is farther away.
|
||||
push(&mut p, cid, far_top);
|
||||
push(&mut p, cid, two_d);
|
||||
push(&mut p, cid, near_bottom);
|
||||
let img = render(&p, cid);
|
||||
assert_eq!(img.get(100, 50), [1.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(img.get(5, 5), [0.0, 1.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lighting
|
||||
|
||||
fn light(p: &mut Project, comp: &Comp, kind: LightKind, pos: [f64; 3]) -> Layer {
|
||||
let mut l = build::layer(p, comp, "Light", LayerSource::Light { kind }, (W, H), None);
|
||||
if kind != LightKind::Ambient {
|
||||
set(&mut l, "transform/position", Value::Vec3(pos));
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn no_specular(l: &mut Layer) {
|
||||
set(l, "materialOptions/specularIntensity", Value::Scalar(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_on_point_light_scales_by_diffuse() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut s = solid3(&mut p, &comp, [1.0, 0.8, 0.6], 200, 100, [100.0, 50.0, 0.0]);
|
||||
no_specular(&mut s);
|
||||
let l = light(&mut p, &comp, LightKind::Point, [100.0, 50.0, -500.0]);
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s);
|
||||
let img = render(&p, cid);
|
||||
let c = img.get(100, 50);
|
||||
// Diffuse 50% · N·L = 1 · intensity 100%.
|
||||
assert!(close(c[0], 0.5, 1e-3) && close(c[1], 0.4, 1e-3) && close(c[2], 0.3, 1e-3), "{c:?}");
|
||||
// Off-axis pixels are lit at a grazing angle → darker.
|
||||
assert!(img.get(2, 2)[0] < c[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambient_light_uses_ambient_coefficient() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut s = solid3(&mut p, &comp, [0.8, 0.8, 0.8], 200, 100, [100.0, 50.0, 0.0]);
|
||||
set(&mut s, "materialOptions/ambient", Value::Scalar(50.0));
|
||||
let mut l = light(&mut p, &comp, LightKind::Ambient, [0.0; 3]);
|
||||
set(&mut l, "lightOptions/intensity", Value::Scalar(50.0));
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s);
|
||||
let c = render(&p, cid).get(10, 10);
|
||||
assert!(close(c[0], 0.8 * 0.5 * 0.5, 1e-4), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lights_off_or_not_accepting_lights_render_unlit() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut s = solid3(&mut p, &comp, [0.3, 0.6, 0.9], 200, 100, [100.0, 50.0, 0.0]);
|
||||
set(&mut s, "materialOptions/acceptsLights", Value::Bool(false));
|
||||
let l = light(&mut p, &comp, LightKind::Point, [100.0, 50.0, -500.0]);
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s);
|
||||
let c = render(&p, cid).get(100, 50);
|
||||
assert!(close(c[0], 0.3, 1e-5) && close(c[2], 0.9, 1e-5), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_behind_layer_needs_transmission() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100, [100.0, 50.0, 0.0]);
|
||||
no_specular(&mut s);
|
||||
let l = light(&mut p, &comp, LightKind::Point, [100.0, 50.0, 500.0]);
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s.clone());
|
||||
assert!(render(&p, cid).get(100, 50)[0] < 1e-4);
|
||||
// 100% transmission passes the light through the layer.
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
set(&mut c.layers[1], "materialOptions/lightTransmission", Value::Scalar(100.0));
|
||||
let v = render(&p, cid).get(100, 50)[0];
|
||||
assert!(close(v, 0.5, 1e-3), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specular_highlight_adds_light() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let s = solid3(&mut p, &comp, [0.5, 0.5, 0.5], 200, 100, [100.0, 50.0, 0.0]);
|
||||
let l = light(&mut p, &comp, LightKind::Point, [100.0, 50.0, -zoom()]);
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s);
|
||||
let c = render(&p, cid).get(100, 50);
|
||||
// 0.5·0.5 diffuse + 0.5 specular (N·H = 1) tinted by the layer colour (Metal 100%) = 0.5.
|
||||
assert!(close(c[0], 0.25 + 0.25, 2e-3), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_cone_limits_light() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100, [100.0, 50.0, 0.0]);
|
||||
no_specular(&mut s);
|
||||
let mut l = light(&mut p, &comp, LightKind::Spot, [100.0, 50.0, -200.0]);
|
||||
set(&mut l, "transform/poi", Value::Vec3([100.0, 50.0, 0.0]));
|
||||
set(&mut l, "lightOptions/coneAngle", Value::Scalar(20.0));
|
||||
set(&mut l, "lightOptions/coneFeather", Value::Scalar(0.0));
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, s);
|
||||
let img = render(&p, cid);
|
||||
assert!(img.get(100, 50)[0] > 0.45);
|
||||
// tan(10°)·200 ≈ 35 px radius.
|
||||
assert!(img.get(160, 50)[0] < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falloff_inverse_square_clamped() {
|
||||
let mut ls = LightState::from_layer(&crate::EvalCtx::new(&Project::default(), ItemId(0), &Comp::new(W, H, FrameRate::FPS_30, Tick::ZERO), Tick::ZERO), &{
|
||||
let (mut p, _, comp) = setup();
|
||||
light(&mut p, &comp, LightKind::Point, [0.0, 0.0, 0.0])
|
||||
})
|
||||
.unwrap();
|
||||
ls.falloff = 2;
|
||||
ls.radius = 100.0;
|
||||
assert!((ls.attenuation(vec3(50.0, 0.0, 0.0)) - 1.0).abs() < 1e-12);
|
||||
assert!((ls.attenuation(vec3(200.0, 0.0, 0.0)) - 0.25).abs() < 1e-12);
|
||||
ls.falloff = 1;
|
||||
ls.falloff_distance = 100.0;
|
||||
assert!((ls.attenuation(vec3(150.0, 0.0, 0.0)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(ls.attenuation(vec3(250.0, 0.0, 0.0)), 0.0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shadows
|
||||
|
||||
#[test]
|
||||
fn caster_shadows_receiver() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut recv = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100, [100.0, 50.0, 100.0]);
|
||||
no_specular(&mut recv);
|
||||
let mut caster = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 20, 20, [60.0, 50.0, 0.0]);
|
||||
no_specular(&mut caster);
|
||||
set(&mut caster, "materialOptions/castsShadows", Value::Enum(1));
|
||||
// Parallel light straight along +z: the shadow lands right behind the caster.
|
||||
let mut l = light(&mut p, &comp, LightKind::Parallel, [100.0, 50.0, -500.0]);
|
||||
set(&mut l, "transform/poi", Value::Vec3([100.0, 50.0, 0.0]));
|
||||
set(&mut l, "lightOptions/castsShadows", Value::Bool(true));
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, caster);
|
||||
push(&mut p, cid, recv);
|
||||
let img = render(&p, cid);
|
||||
// Lit receiver away from the shadow: 0.5.
|
||||
assert!(close(img.get(150, 50)[0], 0.5, 1e-3));
|
||||
// Light from the left (direction (300, 0, 500)): the shadow shifts +60 px at the receiver's
|
||||
// depth, to world x 110..130 → screen ≈ 107..122.
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
set(&mut c.layers[0], "transform/position", Value::Vec3([100.0 - 300.0, 50.0, -500.0]));
|
||||
let img = render(&p, cid);
|
||||
let lit = img.get(150, 50)[0];
|
||||
let expect = 0.5 * (500.0 / (300.0f64 * 300.0 + 500.0 * 500.0).sqrt()) as f32;
|
||||
assert!(close(lit, expect, 1e-3), "lit {lit} vs {expect}");
|
||||
assert!(img.get(115, 50)[0] < 1e-3, "shadowed {:?}", img.get(115, 50));
|
||||
assert!(close(img.get(60, 50)[0], expect, 1e-3), "caster itself is lit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_darkness_and_accepts_off() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut recv = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 400, 200, [100.0, 50.0, 100.0]);
|
||||
no_specular(&mut recv);
|
||||
let mut caster = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 400, 200, [100.0, 50.0, 0.0]);
|
||||
set(&mut caster, "materialOptions/castsShadows", Value::Enum(2)); // Only: invisible caster
|
||||
let mut l = light(&mut p, &comp, LightKind::Parallel, [100.0, 50.0, -500.0]);
|
||||
set(&mut l, "transform/poi", Value::Vec3([100.0, 50.0, 0.0]));
|
||||
set(&mut l, "lightOptions/castsShadows", Value::Bool(true));
|
||||
set(&mut l, "lightOptions/shadowDarkness", Value::Scalar(50.0));
|
||||
push(&mut p, cid, l);
|
||||
push(&mut p, cid, caster);
|
||||
push(&mut p, cid, recv);
|
||||
let v = render(&p, cid).get(100, 50)[0];
|
||||
assert!(close(v, 0.25, 1e-3), "half-dark shadow: {v}");
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
set(&mut c.layers[2], "materialOptions/acceptsShadows", Value::Enum(0));
|
||||
let v = render(&p, cid).get(100, 50)[0];
|
||||
assert!(close(v, 0.5, 1e-3), "no shadow accepted: {v}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- cameras
|
||||
|
||||
fn camera(p: &mut Project, comp: &Comp) -> Layer {
|
||||
build::layer(p, comp, "Camera", LayerSource::Camera, (W, H), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_camera_layer_matches_comp_camera() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let cam = camera(&mut p, &comp);
|
||||
assert_eq!(cam.props.prop("cameraOptions/zoom").unwrap().value.as_f64(), zoom());
|
||||
let s = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 40, 20, [50.0, 30.0, 0.0]);
|
||||
push(&mut p, cid, s.clone());
|
||||
let a = render(&p, cid);
|
||||
p.comp_mut(cid).unwrap().layers.insert(0, cam);
|
||||
let b = render(&p, cid);
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_node_camera_looks_at_poi() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut cam = camera(&mut p, &comp);
|
||||
// Look at a layer far to the right: it lands in the middle of the frame.
|
||||
set(&mut cam, "transform/poi", Value::Vec3([600.0, 50.0, 0.0]));
|
||||
set(&mut cam, "transform/position", Value::Vec3([600.0, 50.0, -zoom()]));
|
||||
let s = solid3(&mut p, &comp, [0.0, 0.0, 1.0], 20, 20, [600.0, 50.0, 0.0]);
|
||||
push(&mut p, cid, cam);
|
||||
push(&mut p, cid, s);
|
||||
let img = render(&p, cid);
|
||||
assert!(img.get(100, 50)[2] > 0.99);
|
||||
assert!(img.get(80, 50)[3] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_node_camera_uses_orientation() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut cam = camera(&mut p, &comp);
|
||||
cam.auto_orient = effectcraft_project::AutoOrient::Off;
|
||||
set(&mut cam, "transform/position", Value::Vec3([100.0, 50.0, 0.0]));
|
||||
// Turn to look along +x.
|
||||
set(&mut cam, "transform/orientation", Value::Vec3(orientation_for(vec3(1.0, 0.0, 0.0))));
|
||||
let mut s = solid3(&mut p, &comp, [1.0, 1.0, 0.0], 40, 40, [400.0, 50.0, 0.0]);
|
||||
set(&mut s, "transform/rotationY", Value::Scalar(90.0));
|
||||
push(&mut p, cid, cam);
|
||||
push(&mut p, cid, s);
|
||||
let img = render(&p, cid);
|
||||
assert!(img.get(100, 50)[3] > 0.99, "{:?}", img.get(100, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orientation_for_round_trips() {
|
||||
for d in [vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), vec3(-0.3, 0.4, 0.8), vec3(0.2, -0.9, -0.1)] {
|
||||
let o = orientation_for(d);
|
||||
let f = effectcraft_geom::Mat4::orientation(Vec3::from(o)).apply_vec(vec3(0.0, 0.0, 1.0));
|
||||
assert!((f - d.normalize()).length() < 1e-9, "{d:?} → {o:?} → {f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_of_field_blurs_out_of_focus_layers() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut cam = camera(&mut p, &comp);
|
||||
set(&mut cam, "cameraOptions/dof", Value::Bool(true));
|
||||
set(&mut cam, "cameraOptions/aperture", Value::Scalar(60.0));
|
||||
let s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 60, 60, [100.0, 50.0, 0.0]);
|
||||
push(&mut p, cid, cam);
|
||||
push(&mut p, cid, s);
|
||||
// In focus (focus distance = zoom = distance to z=0): hard edge at x = 70.
|
||||
let a = render(&p, cid);
|
||||
assert!(a.get(71, 50)[3] > 0.99 && a.get(69, 50)[3] < 0.01);
|
||||
let c = p.comp_mut(cid).unwrap();
|
||||
set(&mut c.layers[0], "cameraOptions/focusDistance", Value::Scalar(zoom() * 0.5));
|
||||
let b = render(&p, cid);
|
||||
let e = b.get(70, 50)[3];
|
||||
assert!(e > 0.1 && e < 0.9, "soft edge {e}");
|
||||
assert!(b.get(66, 50)[3] > 0.01);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- views
|
||||
|
||||
#[test]
|
||||
fn view_ids_round_trip() {
|
||||
for v in View3D::ALL {
|
||||
assert_eq!(View3D::from_id(v.id()), Some(v));
|
||||
assert_eq!(View3D::from_id(v.label()), Some(v));
|
||||
}
|
||||
assert_eq!(View3D::from_id("Custom View 2"), Some(View3D::Custom2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn front_view_is_orthographic() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
// In an orthographic view depth doesn't change size.
|
||||
let a = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 40, 40, [60.0, 50.0, 0.0]);
|
||||
let b = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 40, 40, [140.0, 50.0, 1000.0]);
|
||||
push(&mut p, cid, a);
|
||||
push(&mut p, cid, b);
|
||||
let mut vc = default_view_cam(View3D::Front, W as f64, H as f64);
|
||||
vc.zoom = 1.0;
|
||||
let opts = RenderOpts { view: Some(vc.state()), ..Default::default() };
|
||||
let img = Renderer::new(&p, &NoFootage, opts).comp_frame(cid, Tick::ZERO);
|
||||
assert!(img.get(41, 50)[0] > 0.99 && img.get(39, 50)[3] < 0.01);
|
||||
assert!(img.get(121, 50)[1] > 0.99 && img.get(159, 50)[1] > 0.99 && img.get(161, 50)[3] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_view_sees_planes_edge_on() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
let a = solid3(&mut p, &comp, [1.0, 0.0, 0.0], 100, 100, [100.0, 50.0, 0.0]);
|
||||
let mut b = solid3(&mut p, &comp, [0.0, 1.0, 0.0], 100, 100, [100.0, 50.0, 0.0]);
|
||||
set(&mut b, "transform/rotationX", Value::Scalar(90.0));
|
||||
push(&mut p, cid, a);
|
||||
push(&mut p, cid, b);
|
||||
let mut vc = default_view_cam(View3D::Top, W as f64, H as f64);
|
||||
vc.zoom = 1.0;
|
||||
let opts = RenderOpts { view: Some(vc.state()), ..Default::default() };
|
||||
let img = Renderer::new(&p, &NoFootage, opts).comp_frame(cid, Tick::ZERO);
|
||||
// From the top, the X-rotated plane is a 100×100 square; the upright one is a line.
|
||||
assert!(img.get(100, 30)[1] > 0.99 && img.get(100, 70)[1] > 0.99);
|
||||
assert!(img.get(100, 30)[0] < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rig_orbit_keeps_distance_and_pan_moves_both() {
|
||||
let vc = default_view_cam(View3D::Custom1, 1920.0, 1080.0);
|
||||
let mut r = Rig::from_view(&vc);
|
||||
let d0 = (r.eye - r.poi).length();
|
||||
r.orbit(37.0, -15.0);
|
||||
assert!(((r.eye - r.poi).length() - d0).abs() < 1e-6);
|
||||
let (e, p) = (r.eye, r.poi);
|
||||
r.pan(10.0, 0.0);
|
||||
assert!(((r.eye - e) - (r.poi - p)).length() < 1e-9);
|
||||
r.dolly(100.0, false);
|
||||
assert!(((r.eye - r.poi).length() - (d0 - 100.0)).abs() < 1e-6);
|
||||
// Pitch is clamped short of the poles.
|
||||
r.orbit(0.0, 500.0);
|
||||
let off = r.eye - r.poi;
|
||||
assert!(off.y.abs() / off.length() < 0.9999);
|
||||
}
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user