Merge main into M13.28 worktree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-04 02:57:55 -04:00
co-authored by Claude Opus 5.5
32 changed files with 2536 additions and 430 deletions
+2 -26
View File
@@ -91,36 +91,12 @@ const CPU_ONLY_CONTROLS: &[(&str, &[&str])] = &[
];
/// Whether the GPU kernel of effect `id` covers the instance's current settings (see
/// [`CPU_ONLY_CONTROLS`]; plus Cell Pattern's HQ variants, Turbulent Displace's locked
/// pinning, Warp's strong Fisheye / Twist and Timewarp with a Matte Layer).
/// [`CPU_ONLY_CONTROLS`]; plus Cell Pattern's HQ variants and Turbulent Displace's locked
/// pinning).
pub fn gpu_supported(id: &str, ctx: &crate::EffectCtx) -> bool {
match id {
"ec.generate.cellpattern" if (6..=10).contains(&ctx.params.e("cellPattern")) => return false,
"ec.distort.turbulentdisplace" if ctx.params.e("pinning") >= 8 => return false,
// Shatter's wireframe views; Foam's User Defined texture, Environment Map and flow-map
// preview (the GPU draws the rendered pieces and the sprite bubbles only).
"ec.sim.shatter" if ctx.params.e("view") != 0 => return false,
"ec.sim.foam" => {
let set = |id: &str| matches!(ctx.params.get(id), Some(effectcraft_keyframe::Value::Layer(Some(_))));
let view = ctx.params.e("view");
if (view == 2 && ctx.params.e("rendering/bubbleTexture") == 5)
|| (view == 2 && ctx.params.f("rendering/reflectionStrength") > 0.0 && set("rendering/environmentMap"))
|| (view == 1 && set("flowMap/flowMap"))
{
return false;
}
}
// Timewarp's Matte Layer (foreground and background on their own vectors).
"ec.time.timewarp" if ctx.params.get("matteLayer").and_then(effectcraft_keyframe::Value::as_layer).is_some() => return false,
// Fisheye / Twist (a crease at the unit circle) bent past 50 % or with Horizontal /
// Vertical Distortion: Newton's inverse wanders chaotically before converging near the
// fold, so f32 lands on other pixels than the CPU's f64.
"ec.distort.warp"
if matches!(ctx.params.e("warpStyle"), 11 | 14)
&& (ctx.params.f("bend").abs() > 50.0 || ctx.params.f("horizontalDistortion") != 0.0 || ctx.params.f("verticalDistortion") != 0.0) =>
{
return false;
}
_ => {}
}
let Some((_, controls)) = CPU_ONLY_CONTROLS.iter().find(|(e, _)| *e == id) else { return true };
+27 -5
View File
@@ -663,13 +663,24 @@ fn warp(ctx: &EffectCtx, mut b: Buf) -> Buf {
if k == 0.0 && hd == 0.0 && vd == 0.0 {
return b;
}
let style = ctx.params.e("warpStyle");
let vertical = ctx.params.e("warpAxis") == 1;
let (hx, hy) = (ctx.layer_size[0] * b.scale * 0.5, ctx.layer_size[1] * b.scale * 0.5);
if !ctx.adjustment {
let pad = ((k.abs() + hd.abs() + vd.abs()) * 0.6 * hx.max(hy)).ceil().min(4096.0);
b.pad(pad as u32 + 1);
}
b.img = remap(&b.img, false, warp_inverse(ctx, &b));
b
}
/// Warp's inverse map for buffer geometry `b` (padded): the source point of an output point
/// (buffer px), by Newton iterations on the forward warp; `None` = transparent.
fn warp_inverse(ctx: &EffectCtx, b: &Buf) -> impl Fn(f64, f64) -> Option<(f64, f64)> + Sync + use<> {
let k = ctx.params.f("bend") / 100.0;
let hd = ctx.params.f("horizontalDistortion") / 100.0;
let vd = ctx.params.f("verticalDistortion") / 100.0;
let style = ctx.params.e("warpStyle");
let vertical = ctx.params.e("warpAxis") == 1;
let (hx, hy) = (ctx.layer_size[0] * b.scale * 0.5, ctx.layer_size[1] * b.scale * 0.5);
let c = b.to_px([ctx.layer_size[0] * 0.5, ctx.layer_size[1] * 0.5]);
let (hx, hy) = (hx.max(1e-6), hy.max(1e-6));
let fwd = move |x: f64, y: f64| -> (f64, f64) {
@@ -682,7 +693,7 @@ fn warp(ctx: &EffectCtx, mut b: Buf) -> Buf {
x1 *= 1.0 + 0.5 * vd * y1;
(c.0 + x1 * hx, c.1 + y1 * hy)
};
b.img = remap(&b.img, false, |x, y| {
move |x, y| {
let (mut sx, mut sy) = (x, y);
for _ in 0..12 {
let (fx, fy) = fwd(sx, sy);
@@ -706,8 +717,19 @@ fn warp(ctx: &EffectCtx, mut b: Buf) -> Buf {
return None;
}
Some((sx, sy))
});
b
}
}
/// Warp's inverse map over a `w` × `h` buffer with geometry `b` (its pixels are not read), as
/// an image of (source x, source y, 1, 0) per pixel centre, transparent where the warp leaves
/// the pixel empty: the plan of the GPU compositor's Warp where the Newton iterations must run
/// in f64 to land on the CPU's pixels (strong Fisheye / Twist bends).
pub fn warp_inverse_map(ctx: &EffectCtx, b: &Buf, w: u32, h: u32) -> Image {
let f = warp_inverse(ctx, b);
crate::util::gen_image(w, h, |x, y| match f(x as f64 + 0.5, y as f64 + 0.5) {
Some((sx, sy)) => [sx as f32, sy as f32, 1.0, 0.0],
None => [0.0; 4],
})
}
// ---------------------------------------------------------------- Detail-preserving Upscale
+14 -3
View File
@@ -75,7 +75,7 @@ pub use color2::{Curve, auto_correct_settings, color_link_mode, color_link_sampl
pub use color3::OffsetCurve;
pub use distort::transform_shutter;
pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh};
pub use distort3::{RESHAPE_POINTS, ReshapeSetup, SmearSetup, reshape_setup, smear_setup};
pub use distort3::{RESHAPE_POINTS, ReshapeSetup, SmearSetup, reshape_setup, smear_setup, warp_inverse_map};
pub use distort4::liquify_mesh;
use effectcraft_keyframe::Value;
use effectcraft_project::build::Ids;
@@ -83,7 +83,7 @@ use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
pub use effectcraft_raster::{AuxChannels, Image};
pub use misc::{INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation};
pub use sim::particle_state;
pub use sim3::playground_state;
pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state};
pub use stylize2::strobe_on;
// CPU helpers the GPU kernels share (effectcraft-gpu).
pub use blur2::{camera_lens_plain, camera_lens_spans};
@@ -109,7 +109,10 @@ pub use ocio::color_stabilizer_maps;
pub use channel3d::{CRYPTO_LAYERS, id_color, selection_hashes};
pub use ocio::{ColorOp, Straight, Tf, color_program};
pub use sim::{Acc, Blob, Bubble, Post, Shape, Sprite, SpritePlan, Tint, bubble_list, drizzle_drops, mercury_blobs, sprite_plan};
pub use sim2::{CausticsSetup, Piece, PiecePlan, PieceTex, WavePlan, Waves, caustics_setup, piece_plan, wave_world_plan};
pub use sim2::{
CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan,
wave_world_plan,
};
pub use utility::{Lut, load_lut};
pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation};
@@ -990,6 +993,14 @@ pub const GPU_EFFECTS: &[&str] = &[
"ec.sim.shatter",
"ec.sim.carddance",
"ec.transition.cardwipe",
// effectcraft-gpu fx_particles (particle render passes)
"ec.sim.ccparticleworld",
"ec.sim.ccparticlesystems2",
"ec.sim.particleplayground",
"ec.sim.ccballaction",
"ec.sim.ccpixelpolly",
"ec.sim.ccscatterize",
"ec.noise.curlnoise",
// effectcraft-gpu fx_light (the CC light family)
"ec.generate.cclightrays",
"ec.generate.cclightburst",
+106 -15
View File
@@ -888,6 +888,88 @@ pub enum ColorOp {
/// A LUT (0 nearest, 1 trilinear, 2 tetrahedral) with an optional per-channel shaper, forward
/// or inverse (as [`FileXform::apply`]).
Lut { lut: Arc<Lut>, shaper: Option<Arc<[Vec<(f32, f32)>; 3]>>, interp: u32, inverse: bool },
/// `m × (c + pre) + post` (a custom config's MatrixTransform and RangeTransform).
Affine { m: [[f32; 3]; 3], pre: [f32; 3], post: [f32; 3] },
/// `max(c, 0) ^ p` per channel (ExponentTransform).
Pow([f32; 3]),
/// LogTransform / LogAffineTransform, forward or inverse (as `ocio_config::Xf::apply`).
LogAffine { base: f32, log_slope: [f32; 3], log_offset: [f32; 3], lin_slope: [f32; 3], lin_offset: [f32; 3], inverse: bool },
}
/// The ops of a LUT / CDL file transform (as [`FileXform::apply`]).
fn file_ops(x: &FileXform, interp: u32, inverse: bool, ccc_id: &str, ops: &mut Vec<ColorOp>) {
match x {
FileXform::Cdl(list) => {
let cdl = list.iter().find(|(i, _)| !ccc_id.is_empty() && i == ccc_id).or(list.first()).map(|(_, c)| *c).unwrap_or_default();
ops.push(ColorOp::Cdl { cdl, clamp: true, inverse });
}
FileXform::Lut { lut, shaper } => {
ops.push(ColorOp::Lut { lut: Arc::new(lut.clone()), shaper: shaper.clone().map(Arc::new), interp, inverse });
}
}
}
/// The ops of a custom config's transform `x` (as `Xf::apply`).
fn config_xf_ops(x: &crate::ocio_config::Xf, inverse: bool, ops: &mut Vec<ColorOp>) {
use crate::ocio_config::Xf;
let f3 = |v: &[f64; 3]| v.map(|x| x as f32);
match x {
Xf::Inverse(x) => config_xf_ops(x, !inverse, ops),
Xf::Matrix { m, offset } => {
if !inverse {
let m = [0, 1, 2].map(|r| [m[r * 4] as f32, m[r * 4 + 1] as f32, m[r * 4 + 2] as f32]);
ops.push(ColorOp::Affine { m, pre: [0.0; 3], post: [offset[0] as f32, offset[1] as f32, offset[2] as f32] });
} else if let Some(inv) = crate::ocio_config::mat3_inverse(m) {
let m = inv.map(|r| r.map(|v| v as f32));
ops.push(ColorOp::Affine { m, pre: [-offset[0] as f32, -offset[1] as f32, -offset[2] as f32], post: [0.0; 3] });
}
}
Xf::File { xf: Some(x), interp, ccc, .. } => file_ops(x, *interp, inverse, ccc, ops),
Xf::File { xf: None, .. } | Xf::Unsupported(_) => {}
Xf::Exponent(e) => ops.push(ColorOp::Pow([0, 1, 2].map(|k| (if inverse { 1.0 / e[k].max(1e-9) } else { e[k] }) as f32))),
Xf::Log { base } => {
ops.push(ColorOp::LogAffine { base: *base as f32, log_slope: [1.0; 3], log_offset: [0.0; 3], lin_slope: [1.0; 3], lin_offset: [0.0; 3], inverse })
}
Xf::LogAffine { base, log_slope, log_offset, lin_slope, lin_offset } => ops.push(ColorOp::LogAffine {
base: *base as f32,
log_slope: f3(log_slope),
log_offset: f3(log_offset),
lin_slope: f3(lin_slope),
lin_offset: f3(lin_offset),
inverse,
}),
Xf::Cdl(cdl) => ops.push(ColorOp::Cdl { cdl: *cdl, clamp: true, inverse }),
Xf::Range { min_in, max_in, min_out, max_out } => {
let (a0, a1, b0, b1) = if inverse { (*min_out, *max_out, *min_in, *max_in) } else { (*min_in, *max_in, *min_out, *max_out) };
let k = if (a1 - a0).abs() > 1e-12 { (b1 - b0) / (a1 - a0) } else { 0.0 };
let k = k as f32;
ops.push(ColorOp::Affine { m: [[k, 0.0, 0.0], [0.0, k, 0.0], [0.0, 0.0, k]], pre: [-a0 as f32; 3], post: [b0 as f32; 3] });
}
Xf::Group(list) => {
if inverse {
list.iter().rev().for_each(|x| config_xf_ops(x, true, ops));
} else {
list.iter().for_each(|x| config_xf_ops(x, false, ops));
}
}
}
}
/// The ops of a custom config's conversion from space `a` to space `z` (as `Config::convert`).
fn config_ops(a: &crate::ocio_config::ConfigSpace, z: &crate::ocio_config::ConfigSpace, ops: &mut Vec<ColorOp>) {
if a.is_data || z.is_data || a.name == z.name {
return;
}
match (&a.to_ref, &a.from_ref) {
(Some(x), _) => config_xf_ops(x, false, ops),
(None, Some(x)) => config_xf_ops(x, true, ops),
_ => {}
}
match (&z.from_ref, &z.to_ref) {
(Some(x), _) => config_xf_ops(x, false, ops),
(None, Some(x)) => config_xf_ops(x, true, ops),
_ => {}
}
}
/// How a colour program meets premultiplied pixels.
@@ -912,8 +994,8 @@ fn xform_ops(x: &Xform, ops: &mut Vec<ColorOp>) {
}
/// Effect `id`'s per-pixel transform as a list of [`ColorOp`]s that reproduces the CPU effect
/// (empty = the layer passes through). `None` when it has no such form (a custom OCIO config,
/// another effect).
/// (empty = the layer passes through; custom OCIO configs compile their transforms too). `None`
/// for another effect.
pub fn color_program(id: &str, ctx: &EffectCtx) -> Option<(Vec<ColorOp>, Straight)> {
let pr = ctx.params;
let mut ops = vec![];
@@ -926,7 +1008,16 @@ pub fn color_program(id: &str, ctx: &EffectCtx) -> Option<(Vec<ColorOp>, Straigh
}
"ec.color.ociocolorspace" => {
if pr.e("config") == 1 {
return custom_config(ctx).is_none().then_some((ops, Straight::Unpremul));
// A custom config (one that can't be read, or names unknown spaces: the pixels
// pass through).
if let Some(cfg) = custom_config(ctx)
&& let (Some(a), Some(z)) =
(custom_space(&cfg, pr.s("sourceName"), pr.e("source")), custom_space(&cfg, pr.s("destinationName"), pr.e("destination")))
{
let (a, z) = if pr.e("direction") == 1 { (z, a) } else { (a, z) };
config_ops(a, z, &mut ops);
}
return Some((ops, Straight::Unpremul));
}
let (a, z) = (space_at(pr.e("source")), space_at(pr.e("destination")));
let (a, z) = if pr.e("direction") == 1 { (z, a) } else { (a, z) };
@@ -942,7 +1033,17 @@ pub fn color_program(id: &str, ctx: &EffectCtx) -> Option<(Vec<ColorOp>, Straigh
}
"ec.color.ociodisplay" => {
if pr.e("config") == 1 {
return custom_config(ctx).is_none().then_some((ops, Straight::Unpremul));
if let Some(cfg) = custom_config(ctx) {
let display = DISPLAYS.get(pr.e("display") as usize).map_or("", |d| d.0);
let view = VIEWS.get(pr.e("view") as usize).copied().unwrap_or("");
let dn = if pr.s("displayName").is_empty() { display } else { pr.s("displayName") };
let vn = if pr.s("viewName").is_empty() { view } else { pr.s("viewName") };
if let (Some(a), Some(z)) = (custom_space(&cfg, pr.s("sourceName"), pr.e("source")), cfg.view_space(dn, vn)) {
let (a, z) = if pr.e("direction") == 1 { (z, a) } else { (a, z) };
config_ops(a, z, &mut ops);
}
}
return Some((ops, Straight::Unpremul));
}
let input = space_at(pr.e("source"));
let (display, view, inverse) = (pr.e("display") as usize, pr.e("view") as usize, pr.e("direction") == 1);
@@ -974,17 +1075,7 @@ pub fn color_program(id: &str, ctx: &EffectCtx) -> Option<(Vec<ColorOp>, Straigh
1 => 1,
_ => 2,
};
let inverse = pr.e("direction") == 1;
match &*x {
FileXform::Cdl(list) => {
let id = pr.s("cccId");
let cdl = list.iter().find(|(i, _)| !id.is_empty() && i == id).or(list.first()).map(|(_, c)| *c).unwrap_or_default();
ops.push(ColorOp::Cdl { cdl, clamp: true, inverse });
}
FileXform::Lut { lut, shaper } => {
ops.push(ColorOp::Lut { lut: Arc::new(lut.clone()), shaper: shaper.clone().map(Arc::new), interp, inverse });
}
}
file_ops(&x, interp, pr.e("direction") == 1, pr.s("cccId"), &mut ops);
}
}
"ec.color.ociolook" => {
+1 -1
View File
@@ -439,7 +439,7 @@ fn mat_apply(m: &[f64; 16], off: &[f64; 4], c: [f64; 3]) -> [f64; 3] {
[0, 1, 2].map(|r| m[r * 4] * c[0] + m[r * 4 + 1] * c[1] + m[r * 4 + 2] * c[2] + off[r])
}
fn mat3_inverse(m: &[f64; 16]) -> Option<[[f64; 3]; 3]> {
pub(crate) fn mat3_inverse(m: &[f64; 16]) -> Option<[[f64; 3]; 3]> {
let a = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
let det = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
+32 -26
View File
@@ -268,6 +268,8 @@ pub fn sprite_plan(id: &str, ctx: &EffectCtx, b: &Buf) -> Option<SpritePlan> {
crate::sim2::WavePlan::Height { .. } => None,
}),
"ec.sim.foam" => crate::sim2::foam_plan(ctx, b),
"ec.sim.ccparticleworld" => particle_world_plan(ctx, b),
"ec.sim.ccparticlesystems2" => Some(particle_systems2_plan(ctx, b)),
_ => None,
}
}
@@ -1059,12 +1061,20 @@ fn pw_phys(ctx: &EffectCtx) -> Phys {
}
}
fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn particle_world(ctx: &EffectCtx, b: Buf) -> Buf {
match particle_world_plan(ctx, &b) {
Some(plan) => plan.finish(b),
None => b,
}
}
/// CC Particle World's sprites (far to near), `None` before anything is born.
fn particle_world_plan(ctx: &EffectCtx, b: &Buf) -> Option<SpritePlan> {
let pr = ctx.params;
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
let phys = pw_phys(ctx);
if phys.rate <= 0.0 && ctx.time <= 0.0 {
return b;
return None;
}
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1);
let st = accelerated(ctx, key, &phys).unwrap_or_else(|| simulate(&PW_CACHE, key, ctx.time, &phys));
@@ -1097,20 +1107,24 @@ fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
.collect();
list.sort_by(|a, b| b.0.total_cmp(&a.0));
let sprites: Vec<Sprite> = list.into_iter().map(|(_, s)| s).collect();
let mode = pr.e("particle/transferMode");
let fx = splat(b.img.width, b.img.height, &sprites, if mode == 2 { Acc::Add } else { Acc::Over });
b.img = combine(
&b.img,
&fx,
match mode {
Some(particle_sprites(sprites, pr.e("particle/transferMode")))
}
/// The CC particle systems' sprites with their Transfer Mode (Composite, Screen, Add, Black
/// Background).
fn particle_sprites(sprites: Vec<Sprite>, mode: u32) -> SpritePlan {
SpritePlan {
sprites,
tints: vec![],
acc: if mode == 2 { Acc::Add } else { Acc::Over },
post: Post::Combine(match mode {
0 => 0,
1 => 1,
2 => 2,
3 => 5,
_ => 0,
},
);
b
}),
}
}
// ------------------------------------------------------------------ CC Particle Systems II
@@ -1143,7 +1157,12 @@ fn ps2_phys(ctx: &EffectCtx) -> Phys {
}
}
fn particle_systems2(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn particle_systems2(ctx: &EffectCtx, b: Buf) -> Buf {
particle_systems2_plan(ctx, &b).finish(b)
}
/// CC Particle Systems II's sprites.
fn particle_systems2_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let pr = ctx.params;
let lh = ctx.layer_size[1] as f32;
let unit = lh.max(1.0);
@@ -1167,20 +1186,7 @@ fn particle_systems2(ctx: &EffectCtx, mut b: Buf) -> Buf {
type_sprite(kind, bx as f32, by as f32, r, c, q.v[0] * unit * s, q.v[1] * unit * s, (q.id % 628) as f32 * 0.01 + q.age * 2.0)
})
.collect();
let mode = pr.e("particle/transferMode");
let fx = splat(b.img.width, b.img.height, &sprites, if mode == 2 { Acc::Add } else { Acc::Over });
b.img = combine(
&b.img,
&fx,
match mode {
0 => 0,
1 => 1,
2 => 2,
3 => 5,
_ => 0,
},
);
b
particle_sprites(sprites, pr.e("particle/transferMode"))
}
// ------------------------------------------------------------------ CC Mr. Mercury
+176 -90
View File
@@ -12,7 +12,7 @@ use rayon::prelude::*;
use crate::card3d::{Lighting, Proj};
use crate::generate::value_noise;
use crate::sim::{Acc, Shape, Sprite, h, hs, pct, pt, raster, spec, splat};
use crate::sim::{Acc, Post, Shape, Sprite, SpritePlan, h, hs, pct, pt, raster, spec, splat};
use crate::util::{Plane, SimCache, gauss_plane, layer_or_self, params_key, unpremul};
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
@@ -146,7 +146,10 @@ impl PiecePlan {
pub fn piece_plan(id: &str, ctx: &EffectCtx, b: &Buf) -> Option<PiecePlan> {
match id {
"ec.sim.carddance" => Some(card_dance_plan(ctx, b)),
"ec.sim.shatter" if ctx.params.e("view") == 0 => shatter_impl(ctx, b, true).err(),
"ec.sim.shatter" if ctx.params.e("view") == 0 => match shatter_impl(ctx, b) {
ShatterPlan::Pieces(plan) => Some(plan),
ShatterPlan::Wire(_) => None,
},
"ec.transition.cardwipe" => crate::transition::card_wipe_plan(ctx, b),
_ => None,
}
@@ -290,7 +293,12 @@ pub(crate) fn sort_far_first(pieces: &mut [Piece]) {
// ------------------------------------------------------------------ CC Ball Action
fn ball_action(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn ball_action(ctx: &EffectCtx, b: Buf) -> Buf {
ball_action_plan(ctx, &b).finish(b)
}
/// CC Ball Action's balls (far to near), coloured by the layer's pixels.
fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let pr = ctx.params;
let scatter = pr.f("scatter") as f32;
let axis = pr.e("rotationAxis");
@@ -307,7 +315,7 @@ fn ball_action(ctx: &EffectCtx, mut b: Buf) -> Buf {
let ny = (lh / spacing).ceil().max(1.0) as u32;
let d = 2.0 * lw.max(lh) as f64;
let (cx, cy) = (lw as f64 * 0.5, lh as f64 * 0.5);
let src = b.img.clone();
let src = &b.img;
let ax: [f64; 3] = match axis {
0 => [1.0, 0.0, 0.0],
1 => [0.0, 1.0, 0.0],
@@ -353,17 +361,24 @@ fn ball_action(ctx: &EffectCtx, mut b: Buf) -> Buf {
.collect();
balls.sort_by(|a, b| b.0.total_cmp(&a.0));
let sprites: Vec<Sprite> = balls.into_iter().map(|(_, s)| s).collect();
b.img = splat(src.width, src.height, &sprites, Acc::Over);
b
SpritePlan { sprites, tints: vec![], acc: Acc::Over, post: Post::Replace }
}
// ------------------------------------------------------------------ CC Pixel Polly
fn pixel_polly(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn pixel_polly(ctx: &EffectCtx, b: Buf) -> Buf {
match pixel_polly_plan(ctx, &b) {
Some(plan) => plan.finish(b),
None => b,
}
}
/// CC Pixel Polly's pieces, `None` before Start Time (the layer as is).
fn pixel_polly_plan(ctx: &EffectCtx, b: &Buf) -> Option<PiecePlan> {
let pr = ctx.params;
let t = ctx.time - pr.f("startTime");
if t <= 0.0 {
return b;
return None;
}
let force = pr.f("force");
let gravity = pr.f("gravity");
@@ -383,7 +398,7 @@ fn pixel_polly(ctx: &EffectCtx, mut b: Buf) -> Buf {
let tri = object <= 1;
let textured = object == 1 || object == 3;
let maxd = lw.max(lh);
let src = b.img.clone();
let src = &b.img;
let per = if tri { 2 } else { 1 };
let mut pieces: Vec<Piece> = (0..nx * ny * per)
.into_par_iter()
@@ -425,21 +440,26 @@ fn pixel_polly(ctx: &EffectCtx, mut b: Buf) -> Buf {
if depth_sort {
sort_far_first(&mut pieces);
}
let mut out = Image::new(src.width, src.height);
draw_pieces(&mut out, &pieces, &src, None);
b.img = out;
b
Some(PiecePlan { pieces, front: PieceTex::Layer, back: None })
}
// ------------------------------------------------------------------ CC Scatterize
fn scatterize(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn scatterize(ctx: &EffectCtx, b: Buf) -> Buf {
match scatterize_plan(ctx, &b) {
Some(plan) => plan.finish(b),
None => b,
}
}
/// CC Scatterize's pixel dots, `None` when nothing moves (the layer as is).
fn scatterize_plan(ctx: &EffectCtx, b: &Buf) -> Option<SpritePlan> {
let pr = ctx.params;
let scatter = pr.f("scatter") as f32;
let right = pr.f("rightTwist").to_radians();
let left = pr.f("leftTwist").to_radians();
if scatter == 0.0 && right == 0.0 && left == 0.0 {
return b;
return None;
}
let add = pr.e("transferMode") == 1;
let seed = ctx.seed.wrapping_mul(0x7feb352d);
@@ -471,8 +491,29 @@ fn scatterize(ctx: &EffectCtx, mut b: Buf) -> Buf {
Some(Sprite::new(sx as f32, sy as f32, 0.6 * persp as f32, [c[0], c[1], c[2], a], Shape::Disc))
})
.collect();
b.img = splat(w, hh, &sprites, if add { Acc::Add } else { Acc::Over });
b
Some(SpritePlan { sprites, tints: vec![], acc: if add { Acc::Add } else { Acc::Over }, post: Post::Replace })
}
/// What a particle effect that reads the layer's pixels draws this frame (CC Ball Action, CC
/// Pixel Polly, CC Scatterize, Shatter's wireframe views), for layer `b`; `None` for other
/// effects or a frame showing the layer as is.
pub enum PixelPlan {
Sprites(SpritePlan),
Pieces(PiecePlan),
}
/// The [`PixelPlan`] of effect `id` for layer `b` (its pixels are read).
pub fn pixel_plan(id: &str, ctx: &EffectCtx, b: &Buf) -> Option<PixelPlan> {
match id {
"ec.sim.ccballaction" => Some(PixelPlan::Sprites(ball_action_plan(ctx, b))),
"ec.sim.ccpixelpolly" => pixel_polly_plan(ctx, b).map(PixelPlan::Pieces),
"ec.sim.ccscatterize" => scatterize_plan(ctx, b).map(PixelPlan::Sprites),
"ec.sim.shatter" => Some(match shatter_impl(ctx, b) {
ShatterPlan::Pieces(plan) => PixelPlan::Pieces(plan),
ShatterPlan::Wire(plan) => PixelPlan::Sprites(plan),
}),
_ => None,
}
}
// ------------------------------------------------------------------ Card Dance
@@ -686,14 +727,19 @@ fn map_key(c: [f32; 4]) -> u32 {
}
fn shatter(ctx: &EffectCtx, b: Buf) -> Buf {
match shatter_impl(ctx, &b, false) {
Ok(img) => Buf { img, ..b },
Err(plan) => plan.finish(b),
match shatter_impl(ctx, &b) {
ShatterPlan::Pieces(plan) => plan.finish(b),
ShatterPlan::Wire(plan) => plan.finish(b),
}
}
/// Shatter: the frame (`Ok`), or with `plan_only` in the Rendered view its pieces (`Err`).
fn shatter_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, PiecePlan> {
/// What Shatter draws: the pieces (Rendered view) or the wireframe lines.
enum ShatterPlan {
Pieces(PiecePlan),
Wire(SpritePlan),
}
fn shatter_impl(ctx: &EffectCtx, b: &Buf) -> ShatterPlan {
let pr = ctx.params;
let view = pr.e("view");
let render = pr.e("render");
@@ -770,7 +816,6 @@ fn shatter_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, Piec
e.1 += 1.0;
}
let g3 = [gdir.sin() * ginc.cos() * gravity * unit, -gdir.cos() * ginc.cos() * gravity * unit, ginc.sin() * gravity * unit];
let src = b.img.clone();
let mut pieces: Vec<Piece> = polys
.par_iter()
.zip(keys.par_iter())
@@ -902,13 +947,8 @@ fn shatter_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, Piec
let tex = |i: &Option<Image>| i.clone().map(PieceTex::Image);
let front_t = tex(&front.img).unwrap_or(PieceTex::Layer);
let back_t = tex(&backf.img).unwrap_or_else(|| front_t.clone());
let plan = PiecePlan { pieces, front: front_t, back: Some(back_t) };
if plan_only {
return Err(plan);
}
return Ok(plan.finish(Buf { img: src, offset: b.offset, scale: b.scale }).img);
return ShatterPlan::Pieces(PiecePlan { pieces, front: front_t, back: Some(back_t) });
}
let out;
{
// Wireframes: piece outlines (front view: at rest; otherwise animated), plus forces.
let animated = view == 2 || view == 4;
@@ -948,9 +988,8 @@ fn shatter_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, Piec
}
}
}
out = splat(src.width, src.height, &lines, Acc::Over);
ShatterPlan::Wire(SpritePlan { sprites: lines, tints: vec![], acc: Acc::Over, post: Post::Replace })
}
Ok(out)
}
// ------------------------------------------------------------------ Caustics
@@ -1516,22 +1555,97 @@ fn foam_pop_age(id: u32, lifespan: f32, frailty: f32, seed: u32) -> f32 {
/// neighbours away at Pop Velocity. Rendered bubbles use a built-in texture or the Bubble
/// Texture Layer, oriented by Bubble Orientation, and reflect the Environment Map.
fn foam(ctx: &EffectCtx, b: Buf) -> Buf {
match foam_impl(ctx, &b, false) {
Ok(img) => Buf { img, ..b },
Err(plan) => plan.finish(b),
}
foam_full_plan(ctx, &b).finish(b)
}
/// Foam's bubbles as sprites, `None` when it draws more than sprites (a User Defined bubble
/// texture, an Environment Map reflection or the Draft + Flow Map view's flow map).
pub(crate) fn foam_plan(ctx: &EffectCtx, b: &Buf) -> Option<crate::sim::SpritePlan> {
if !crate::catalog::gpu_supported("ec.sim.foam", ctx) {
return None;
}
foam_impl(ctx, b, true).err()
let plan = foam_full_plan(ctx, b);
(plan.user.is_none() && plan.env.is_none() && plan.flow.is_none()).then_some(plan.sprites)
}
fn foam_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, crate::sim::SpritePlan> {
/// A bubble disc filled by Foam's User Defined texture (buffer px; `rot` radians).
#[derive(Clone, Copy, Debug)]
pub struct FoamDisc {
pub x: f64,
pub y: f64,
pub r: f32,
pub rot: f32,
pub fade: f32,
}
/// Foam's Environment Map reflection: the map fitted to the buffer, Reflection Convergence and
/// Strength, and the bubble discs reflecting it (`rot` and `fade` unused).
pub struct FoamEnv {
pub img: Image,
pub conv: f64,
pub strength: f32,
pub discs: Vec<FoamDisc>,
}
/// What Foam draws this frame over a transparent frame of the layer's size: the bubble sprites,
/// then the User Defined texture's discs, the Environment Map's reflections and (Draft + Flow
/// Map) the flow map under it all, each [`foam_disc`]-composited in bubble order.
pub struct FoamPlan {
pub sprites: crate::sim::SpritePlan,
pub user: Option<(crate::LayerPixels, Vec<FoamDisc>)>,
pub env: Option<FoamEnv>,
/// The flow map fitted to the buffer.
pub flow: Option<Image>,
}
impl FoamPlan {
pub fn finish(&self, b: Buf) -> Buf {
let mut out = splat(b.img.width, b.img.height, &self.sprites.sprites, self.sprites.acc);
// User Defined: the texture layer fills each bubble's disc.
if let Some((tex, discs)) = &self.user {
for d in discs {
let (rot, fade) = (d.rot, d.fade);
foam_disc(&mut out, d.x, d.y, d.r as f64, |u, v| {
// u, v in −1..1 across the bubble, rotated into the texture.
let (sr, cr) = rot.sin_cos();
let (tu, tv) = (u as f32 * cr + v as f32 * sr, -u as f32 * sr + v as f32 * cr);
let (x, y) = ((tu as f64 * 0.5 + 0.5) * tex.size[0], (tv as f64 * 0.5 + 0.5) * tex.size[1]);
let px = tex.buf.img.sample_bilinear(x * tex.buf.scale + tex.buf.offset[0], y * tex.buf.scale + tex.buf.offset[1]);
px.map(|c| c * fade)
});
}
}
// Environment Map: each bubble reflects the map along its sphere normal (Reflection
// Convergence pulls the reflection towards the bubble's own spot of the map).
if let Some(env) = &self.env {
let (conv, strength) = (env.conv, env.strength);
let (w, h) = (b.img.width as f64, b.img.height as f64);
for d in &env.discs {
let (bx, by) = (d.x, d.y);
foam_disc(&mut out, bx, by, d.r as f64, |u, v| {
// Sphere normal; the reflection looks across the whole map, or (convergence 1)
// just behind the bubble.
let (ex, ey) =
if conv >= 1.0 { (bx, by) } else { (bx * conv + (u * 0.5 + 0.5) * w * (1.0 - conv), by * conv + (v * 0.5 + 0.5) * h * (1.0 - conv)) };
let e = env.img.sample_bilinear(ex, ey);
let rim = ((u * u + v * v) as f32).min(1.0);
let k = strength * (0.3 + 0.7 * rim);
[e[0] * k, e[1] * k, e[2] * k, 0.0]
});
}
}
// Draft + Flow Map shows the flow map under the bubbles.
if let Some(fm) = &self.flow {
out.data.par_iter_mut().zip(fm.data.par_iter()).for_each(|(o, f)| {
let k = 1.0 - o[3];
for c in 0..4 {
o[c] += f[c] * 0.5 * k;
}
});
}
Buf { img: out, ..b }
}
}
/// Foam's [`FoamPlan`] for layer geometry `b` (its size; its pixels are not read).
pub fn foam_full_plan(ctx: &EffectCtx, b: &Buf) -> FoamPlan {
let pr = ctx.params;
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
let unit = lw * 0.01;
@@ -1754,62 +1868,34 @@ fn foam_impl(ctx: &EffectCtx, b: &Buf, plan_only: bool) -> Result<Image, crate::
})
.collect();
let acc = if blend == 0 && view == 2 { Acc::Add } else { Acc::Over };
if plan_only {
return Err(crate::sim::SpritePlan { sprites, tints: vec![], acc, post: crate::sim::Post::Replace });
}
let mut out = splat(b.img.width, b.img.height, &sprites, acc);
// User Defined: the texture layer fills each bubble's disc.
if let Some(tex) = &user_tex {
for q in &order {
let (bx, by, r, rot) = place(q);
let fade = ((foam_pop_age(q.id, lifespan, frailty, seed) - q.age) / 5.0).clamp(0.0, 1.0);
foam_disc(&mut out, bx, by, r as f64, |u, v| {
// u, v in −1..1 across the bubble, rotated into the texture.
let (sr, cr) = rot.sin_cos();
let (tu, tv) = (u as f32 * cr + v as f32 * sr, -u as f32 * sr + v as f32 * cr);
let (x, y) = ((tu as f64 * 0.5 + 0.5) * tex.size[0], (tv as f64 * 0.5 + 0.5) * tex.size[1]);
let px = tex.buf.img.sample_bilinear(x * tex.buf.scale + tex.buf.offset[0], y * tex.buf.scale + tex.buf.offset[1]);
px.map(|c| c * fade)
});
}
}
// Environment Map: each bubble reflects the map along its sphere normal (Reflection
// Convergence pulls the reflection towards the bubble's own spot of the map).
let disc = |q: &&FoamBubble| {
let (x, y, r, rot) = place(q);
let fade = ((foam_pop_age(q.id, lifespan, frailty, seed) - q.age) / 5.0).clamp(0.0, 1.0);
FoamDisc { x, y, r, rot, fade }
};
let user = user_tex.map(|tex| (tex, order.iter().map(disc).collect()));
let strength = pr.f("rendering/reflectionStrength").clamp(0.0, 1.0) as f32;
if view == 2
let env = if view == 2
&& strength > 0.0
&& let Some(env) = ctx.layer_param("rendering/environmentMap", true)
{
let env_img = crate::util::fit_layer(ctx, b, &env, true);
let conv = pr.f("rendering/reflectionConvergence").clamp(0.0, 1.0);
let (w, h) = (b.img.width as f64, b.img.height as f64);
for q in &order {
let (bx, by, r, _) = place(q);
foam_disc(&mut out, bx, by, r as f64, |u, v| {
// Sphere normal; the reflection looks across the whole map, or (convergence 1)
// just behind the bubble.
let (ex, ey) =
if conv >= 1.0 { (bx, by) } else { (bx * conv + (u * 0.5 + 0.5) * w * (1.0 - conv), by * conv + (v * 0.5 + 0.5) * h * (1.0 - conv)) };
let e = env_img.sample_bilinear(ex, ey);
let rim = ((u * u + v * v) as f32).min(1.0);
let k = strength * (0.3 + 0.7 * rim);
[e[0] * k, e[1] * k, e[2] * k, 0.0]
});
}
}
// Draft + Flow Map shows the flow map under the bubbles.
if view == 1
Some(FoamEnv {
img: crate::util::fit_layer(ctx, b, &env, true),
conv: pr.f("rendering/reflectionConvergence").clamp(0.0, 1.0),
strength,
discs: order.iter().map(disc).collect(),
})
} else {
None
};
let flow = if view == 1
&& let Some(lp) = &flow
{
let fm = crate::util::fit_layer(ctx, b, lp, true);
out.data.par_iter_mut().zip(fm.data.par_iter()).for_each(|(o, f)| {
let k = 1.0 - o[3];
for c in 0..4 {
o[c] += f[c] * 0.5 * k;
}
});
}
Ok(out)
Some(crate::util::fit_layer(ctx, b, lp, true))
} else {
None
};
FoamPlan { sprites: crate::sim::SpritePlan { sprites, tints: vec![], acc, post: crate::sim::Post::Replace }, user, env, flow }
}
/// Add `f(u, v)` (premultiplied; u, v ∈ −1..1 across the disc) over the disc of radius `r` at
+55 -17
View File
@@ -716,7 +716,12 @@ pub fn playground_state(ctx: &EffectCtx) -> Option<Vec<crate::psim::SimParticle>
)
}
fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
fn particle_playground(ctx: &EffectCtx, b: Buf) -> Buf {
playground_plan(ctx, &b).finish(b)
}
/// Particle Playground's [`PgPlan`] for buffer geometry `b` (its pixels are not read).
pub fn playground_plan(ctx: &EffectCtx, b: &Buf) -> PgPlan {
let pr = ctx.params;
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
let pg = pg_of(ctx);
@@ -825,7 +830,6 @@ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
let offset_type = pr.e("layerMap/timeOffsetType");
let offset = pr.f("layerMap/timeOffset");
let fps = ctx.fps();
let mut frames: std::collections::HashMap<i64, Option<crate::LayerPixels>> = std::collections::HashMap::new();
let mut sprites: Vec<Sprite> = vec![];
let mut blits: Vec<(PgParticle, i64)> = vec![];
for q in &parts {
@@ -869,30 +873,64 @@ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
None => sprites.push(Sprite::new(x as f32, y as f32, q.r * sc * s, q.c, Shape::Disc)),
}
}
let mut fx = splat(b.img.width, b.img.height, &sprites, Acc::Over);
let mut plan = PgPlan { sprites: SpritePlan { sprites, tints: vec![], acc: Acc::Over, post: Post::Combine(5) }, blits: vec![], frames: vec![] };
if let (Some(id), Some(host)) = (map_id, ctx.env.host) {
let me = pr.get(&crate::layer_source_id("layerMap/layerMapLayer")).is_none_or(|v| v.as_enum() != 0);
// Fetched frames by frame number: their index in `plan.frames` (`None` = unavailable).
let mut frames: std::collections::HashMap<i64, Option<usize>> = std::collections::HashMap::new();
for (q, frame) in &blits {
if !frames.contains_key(frame) && frames.len() >= 32 {
let at = if !frames.contains_key(frame) && frames.len() >= 32 {
// Too many distinct times: reuse the nearest fetched frame.
if let Some(k) = frames.keys().min_by_key(|k| (*k - frame).abs()).copied()
&& let Some(Some(lp)) = frames.get(&k)
{
let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
blit_layer(&mut fx, lp, x, y, q.angle as f64, [q.scale[0] as f64, q.scale[1] as f64], b.scale, q.c[3]);
match frames.keys().min_by_key(|k| (*k - frame).abs()).copied() {
Some(k) => frames.get(&k).copied().flatten(),
None => None,
}
continue;
}
let lp = frames.entry(*frame).or_insert_with(|| host.layer_at(id, *frame as f64 / fps, me));
if let Some(lp) = lp {
} else {
*frames.entry(*frame).or_insert_with(|| {
let lp = host.layer_at(id, *frame as f64 / fps, me)?;
plan.frames.push(lp);
Some(plan.frames.len() - 1)
})
};
if let Some(i) = at {
let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
blit_layer(&mut fx, lp, x, y, q.angle as f64, [q.scale[0] as f64, q.scale[1] as f64], b.scale, q.c[3]);
plan.blits.push(PgBlit { frame: i, x, y, angle: q.angle as f64, scale: [q.scale[0] as f64, q.scale[1] as f64], alpha: q.c[3] });
}
}
}
// Particles replace the layer's own pixels.
b.img = combine(&b.img, &fx, 5);
b
plan
}
/// A Layer Map particle: frame `frame` of [`PgPlan::frames`] centred on (`x`, `y`) buffer px,
/// rotated `angle` degrees, scaled and faded to `alpha`.
#[derive(Clone, Copy, Debug)]
pub struct PgBlit {
pub frame: usize,
pub x: f64,
pub y: f64,
pub angle: f64,
pub scale: [f64; 2],
pub alpha: f32,
}
/// What Particle Playground draws this frame: the dot and text particles as sprites, then the
/// Layer Map particles over them in order; the result replaces the layer's own pixels.
pub struct PgPlan {
pub sprites: SpritePlan,
pub blits: Vec<PgBlit>,
pub frames: Vec<crate::LayerPixels>,
}
impl PgPlan {
pub fn finish(&self, mut b: Buf) -> Buf {
let mut fx = splat(b.img.width, b.img.height, &self.sprites.sprites, self.sprites.acc);
for q in &self.blits {
blit_layer(&mut fx, &self.frames[q.frame], q.x, q.y, q.angle, q.scale, b.scale, q.alpha);
}
// Particles replace the layer's own pixels.
b.img = combine(&b.img, &fx, 5);
b
}
}
// ---------------------------------------------------------------- CC Hair
+102 -117
View File
@@ -680,18 +680,22 @@ fn fetch_layer(ctx: &EffectCtx, id: &str, times: &[f64], grid: &Buf) -> Option<V
)
}
/// One output instant of a Timewarp without a Matte Layer: a fetched frame, a cross-fade of two,
/// or the in-between frame built along a motion field ([`TimewarpPlan::flows`]).
/// One output instant of a Timewarp: a frame, a cross-fade of two, or the in-between frame
/// built along a motion field ([`TimewarpPlan::flows`]); with a Matte Layer's Pixel Motion, the
/// foreground and background pairs (`[frame a, frame b, flow]`) each built on their own vectors
/// and shown as Show asks.
#[derive(Clone, Copy, Debug)]
pub enum TwStep {
Whole(usize),
Mix(usize, usize, f32),
Motion { a: usize, b: usize, w: f32, flow: usize },
Layered { fg: [usize; 3], bg: [usize; 3], w: f32, show: u32 },
}
/// Timewarp without a Matte Layer, prepared for the GPU compositor (effectcraft-gpu `fx_time`):
/// the fetched frames on one grid, the instants across the shutter (with their weights) and the
/// motion fields (block matching on the CPU). [`TimewarpPlan::render_cpu`] is the CPU effect.
/// Timewarp prepared for the GPU compositor (effectcraft-gpu `fx_time`): the fetched frames on
/// one grid (plus the matte-masked ones a Matte Layer needs), the instants across the shutter
/// (with their weights) and the motion fields (block matching on the CPU).
/// [`TimewarpPlan::render_cpu`] is the CPU effect.
pub struct TimewarpPlan {
pub grid: Buf,
pub frames: Vec<Image>,
@@ -710,6 +714,11 @@ impl TimewarpPlan {
TwStep::Whole(i) => f[i].clone(),
TwStep::Mix(i, j, w) => effectcraft_raster::flow::mix(&f[i], &f[j], w),
TwStep::Motion { a, b, w, flow } => timewarp_interpolate(&f[a], &f[b], w, &self.flows[flow], &self.pm),
TwStep::Layered { fg, bg, w, show } => {
let fgi = timewarp_interpolate(&f[fg[0]], &f[fg[1]], w, &self.flows[fg[2]], &self.pm);
let bgi = timewarp_interpolate(&f[bg[0]], &f[bg[1]], w, &self.flows[bg[2]], &self.pm);
layered(fgi, bgi, show)
}
})
.collect();
let weights: Vec<f32> = self.steps.iter().map(|(_, w)| *w).collect();
@@ -758,48 +767,102 @@ fn tw_split(s: f64, fps: f64) -> (f64, f32) {
(f0, ((f - f0) as f32).max(0.0))
}
/// [`TimewarpPlan`] of a Timewarp instance without a Matte Layer. `None` without the effect host
/// (the layer passes through) or with a Matte Layer.
/// [`TimewarpPlan`] of a Timewarp instance. `None` without the effect host or source frames (the
/// layer passes through). With a Matte Layer the frames the instants need (masked by the matte,
/// or the matte itself for Show Matte) are prepared here and join [`TimewarpPlan::frames`].
pub fn timewarp_plan(ctx: &EffectCtx) -> Option<TimewarpPlan> {
ctx.env.host?;
if ctx.params.get("matteLayer").and_then(Value::as_layer).is_some() {
return None;
}
// Instants of source time (with weights) across the shutter; each needs the frame at or
// before it and the next one.
let (instants, times, fps) = timewarp_instants(ctx);
let method = ctx.params.e("method");
let one = method > 0 && ctx.params.b("tuning/buildFromOneImage");
let fr = fetch(ctx, &times)?;
let pm = PixelMotion::from(ctx, fr.grid.scale);
let mattes = fetch_layer(ctx, "matteLayer", &times, &fr.grid);
let warps = fetch_layer(ctx, "warpLayer", &times, &fr.grid);
let matte_ch = ctx.params.e("matteChannel");
let show = ctx.params.e("show");
let idx = |t: f64| times.iter().position(|q| (q - t).abs() < 1e-9).unwrap_or(0);
let mut flows: Vec<(i64, Flow)> = vec![];
let mut frames = fr.imgs;
let add = |frames: &mut Vec<Image>, img: Image| {
frames.push(img);
frames.len() - 1
};
// Motion fields: per source frame pair (keyed), or per masked pair (unkeyed).
let mut flows: Vec<(Option<i64>, Flow)> = vec![];
let mut steps = vec![];
for &(s, wgt) in &instants {
let (f0, frac) = tw_split(s, fps);
let (i0, i1) = (idx(f0 / fps), idx((f0 + 1.0) / fps));
let ma = mattes.as_ref().map(|m| matte_of(&m[i0], matte_ch));
let mb = mattes.as_ref().map(|m| matte_of(&m[i1], matte_ch));
let step = if method == 0 || frac < 1e-4 || (one && method == 1) {
// Whole frames (Build From One Image with Frame Mix: the nearest frame).
let pick = if method == 0 || frac < 1e-4 { 0.0 } else { frac.round() };
TwStep::Whole(if pick < 0.5 { i0 } else { i1 })
let i = if pick < 0.5 { i0 } else { i1 };
let base = &frames[i];
let derived = match (show, &ma, &mb) {
(1, Some(m), _) if pick < 0.5 => Some(times_mask(base, m, false)),
(2, Some(m), _) if pick < 0.5 => Some(times_mask(base, m, true)),
(1, _, Some(m)) => Some(times_mask(base, m, false)),
(2, _, Some(m)) => Some(times_mask(base, m, true)),
(3, Some(m), _) => Some(matte_image(if pick < 0.5 { m } else { mb.as_ref().unwrap_or(m) }, base)),
_ => None,
};
TwStep::Whole(match derived {
Some(img) => add(&mut frames, img),
None => i,
})
} else if method == 1 {
TwStep::Mix(i0, i1, frac)
match (&ma, &mb, show) {
(Some(m0), Some(m1), 3) => {
let (a, b) = (matte_image(m0, &frames[i0]), matte_image(m1, &frames[i1]));
TwStep::Mix(add(&mut frames, a), add(&mut frames, b), frac)
}
(Some(m0), Some(m1), 1 | 2) => {
let (a, b) = (times_mask(&frames[i0], m0, show == 2), times_mask(&frames[i1], m1, show == 2));
TwStep::Mix(add(&mut frames, a), add(&mut frames, b), frac)
}
_ => TwStep::Mix(i0, i1, frac),
}
} else {
// Pixel Motion: vectors from the warp layer if any, else from the layer.
let key = f0 as i64;
let flow = match flows.iter().position(|(k, _)| *k == key) {
let flow = match flows.iter().position(|(k, _)| *k == Some(key)) {
Some(k) => k,
None => {
let f = match &warps {
Some(w) => timewarp_flow(&w[i0], &w[i1], &pm),
None => timewarp_flow(&fr.imgs[i0], &fr.imgs[i1], &pm),
None => timewarp_flow(&frames[i0], &frames[i1], &pm),
};
flows.push((key, f));
flows.push((Some(key), f));
flows.len() - 1
}
};
TwStep::Motion { a: i0, b: i1, w: frac, flow }
match (&ma, &mb) {
(Some(m0), Some(m1)) => {
// Foreground and background each move on their own vectors.
let (fa, fb) = (times_mask(&frames[i0], m0, false), times_mask(&frames[i1], m1, false));
let (ga, gb) = (times_mask(&frames[i0], m0, true), times_mask(&frames[i1], m1, true));
let mut own = |a: &Image, b: &Image| {
if warps.is_some() {
return flow;
}
flows.push((None, timewarp_flow(a, b, &pm)));
flows.len() - 1
};
let (fg_flow, bg_flow) = (own(&fa, &fb), own(&ga, &gb));
let fg = [add(&mut frames, fa), add(&mut frames, fb), fg_flow];
let bg = [add(&mut frames, ga), add(&mut frames, gb), bg_flow];
TwStep::Layered { fg, bg, w: frac, show }
}
_ => TwStep::Motion { a: i0, b: i1, w: frac, flow },
}
};
steps.push((step, wgt));
}
Some(TimewarpPlan { grid: fr.grid, frames: fr.imgs, steps, flows: flows.into_iter().map(|(_, f)| f).collect(), pm })
Some(TimewarpPlan { grid: fr.grid, frames, steps, flows: flows.into_iter().map(|(_, f)| f).collect(), pm })
}
/// Timewarp. Whole Frames shows the nearest source frame, Frame Mix cross-fades the two
@@ -809,108 +872,30 @@ pub fn timewarp_plan(ctx: &EffectCtx) -> Option<TimewarpPlan> {
/// Warp Layer supplies the motion instead of the layer itself. Motion Blur averages Shutter
/// Samples instants across the shutter.
fn timewarp(ctx: &EffectCtx, b: Buf) -> Buf {
if ctx.env.host.is_none() {
return b;
match timewarp_plan(ctx) {
Some(plan) => plan.render_cpu(),
None => b,
}
if ctx.params.get("matteLayer").and_then(Value::as_layer).is_none() {
return match timewarp_plan(ctx) {
Some(plan) => plan.render_cpu(),
None => b,
};
}
// Instants of source time (with weights) across the shutter; each needs the frame at or
// before it and the next one.
let (instants, times, fps) = timewarp_instants(ctx);
let split = |s: f64| tw_split(s, fps);
let method = ctx.params.e("method");
let one = method > 0 && ctx.params.b("tuning/buildFromOneImage");
let Some(fr) = fetch(ctx, &times) else { return b };
let grid = fr.grid.clone();
let frame = |t: f64| -> &Image {
let k = times.iter().position(|q| (q - t).abs() < 1e-9).unwrap_or(0);
&fr.imgs[k]
};
let pm = PixelMotion::from(ctx, grid.scale);
let mattes = fetch_layer(ctx, "matteLayer", &times, &grid);
let warps = fetch_layer(ctx, "warpLayer", &times, &grid);
let matte_ch = ctx.params.e("matteChannel");
let show = ctx.params.e("show");
let mut flows: Vec<((i64, bool), Flow)> = vec![];
let mut out_frames = vec![];
for &(s, wgt) in &instants {
let (f0, frac) = split(s);
let (t0, t1) = (f0 / fps, (f0 + 1.0) / fps);
let (a, bb) = (frame(t0), frame(t1));
let idx = |t: f64| times.iter().position(|q| (q - t).abs() < 1e-9).unwrap_or(0);
let ma = mattes.as_ref().map(|m| matte_of(&m[idx(t0)], matte_ch));
let mb = mattes.as_ref().map(|m| matte_of(&m[idx(t1)], matte_ch));
let img = if method == 0 || frac < 1e-4 || (one && method == 1) {
// Whole frames (Build From One Image with Frame Mix: the nearest frame).
let pick = if method == 0 || frac < 1e-4 { 0.0 } else { frac.round() };
let base = if pick < 0.5 { a } else { bb };
match (show, &ma, &mb) {
(1, Some(m), _) if pick < 0.5 => times_mask(base, m, false),
(2, Some(m), _) if pick < 0.5 => times_mask(base, m, true),
(1, _, Some(m)) => times_mask(base, m, false),
(2, _, Some(m)) => times_mask(base, m, true),
(3, Some(m), _) => matte_image(if pick < 0.5 { m } else { mb.as_ref().unwrap_or(m) }, base),
_ => base.clone(),
}
} else if method == 1 {
match (&ma, &mb, show) {
(Some(m0), Some(m1), 3) => effectcraft_raster::flow::mix(&matte_image(m0, a), &matte_image(m1, bb), frac),
(Some(m0), Some(m1), 1 | 2) => effectcraft_raster::flow::mix(&times_mask(a, m0, show == 2), &times_mask(bb, m1, show == 2), frac),
_ => effectcraft_raster::flow::mix(a, bb, frac),
}
} else {
// Pixel Motion: vectors from the warp layer if any, else from the layer.
let key = ((f0 as i64), false);
let flow_ab = |fa: &Image, fb: &Image| -> Flow { timewarp_flow(fa, fb, &pm) };
let flow = match flows.iter().find(|(k, _)| *k == key) {
Some((_, f)) => f.clone(),
None => {
let f = match &warps {
Some(w) => flow_ab(&w[idx(t0)], &w[idx(t1)]),
None => flow_ab(a, bb),
};
flows.push((key, f.clone()));
f
}
/// Pixel Motion with a Matte Layer: the foreground and background frames built on their own
/// vectors, shown as Show asks (0 Normal: foreground over background).
fn layered(fg: Image, bg: Image, show: u32) -> Image {
match show {
1 => fg,
2 => bg,
3 => matte_image(&fg.data.iter().map(|p| p[3]).collect::<Vec<_>>(), &fg),
_ => {
let mut o = bg;
o.data.par_iter_mut().zip(fg.data.par_iter()).for_each(|(p, q)| {
let k = 1.0 - q[3];
for c in 0..4 {
p[c] = q[c] + p[c] * k;
}
};
match (&ma, &mb) {
(Some(m0), Some(m1)) => {
// Foreground and background each move on their own vectors.
let (fa, fb) = (times_mask(a, m0, false), times_mask(bb, m1, false));
let (ga, gb) = (times_mask(a, m0, true), times_mask(bb, m1, true));
let fg_flow = if warps.is_some() { flow.clone() } else { flow_ab(&fa, &fb) };
let bg_flow = if warps.is_some() { flow.clone() } else { flow_ab(&ga, &gb) };
let fg = timewarp_interpolate(&fa, &fb, frac, &fg_flow, &pm);
let bg = timewarp_interpolate(&ga, &gb, frac, &bg_flow, &pm);
match show {
1 => fg,
2 => bg,
3 => matte_image(&fg.data.iter().map(|p| p[3]).collect::<Vec<_>>(), &fg),
_ => {
let mut o = bg;
o.data.par_iter_mut().zip(fg.data.par_iter()).for_each(|(p, q)| {
let k = 1.0 - q[3];
for c in 0..4 {
p[c] = q[c] + p[c] * k;
}
});
o
}
}
}
_ => timewarp_interpolate(a, bb, frac, &flow, &pm),
}
};
out_frames.push((img, wgt));
});
o
}
}
let imgs: Vec<Image> = out_frames.iter().map(|(i, _)| i.clone()).collect();
let weights: Vec<f32> = out_frames.iter().map(|(_, w)| *w).collect();
let img = if imgs.len() == 1 { imgs.into_iter().next().unwrap_or_default() } else { average(&imgs, &weights) };
with_img(grid, img)
}
/// A matte shown as opaque grey.