mirror of
https://github.com/storytold/effectcraft.git
synced 2026-12-04 16:01:18 -05:00
* #4368: Add / Match / Remove Grain gain After Effects' missing controls Shared grain groups (crates/effects/src/grain_shared.rs), all functional: - Application > Channel Balance (9 per-channel shadow/midtone/highlight multipliers) - Sampling > Source Frame, Noise Sample Points 1-10 (used by Sampling Process "Manual"), Match Grain's per-point Intensity 1-10 - Blend with Original: Amount, Combine Match and Mask Using, Blur Matte, Color Matching (RGB / Hue / Chroma, tolerance, softness, invert) and Masking Layer (layer, mode, size fit) Remove Grain: Channel Noise Reduction (R/G/B), Chroma Suppression, Noise Size Bias, Clean Solid Areas. New instances follow After Effects' Effect Controls order; saved instances keep their stored order and get the new controls with defaults that render unchanged (Source Frame -1 = the frame being rendered for projects saved before it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * #4368: grain sampling review fixes - Manual Noise Sample Points skip boxes whose surround reaches transparent pixels (the automatic rule), and each kept box keeps its own point's Intensity. - Remove Grain measures a fixed Source Frame that is the current frame before Temporal Filtering, as other frames are measured; Source Frame -1 keeps the old measurement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * #4368: Match Grain's historical Masks choice no longer samples the unmasked Source Historical mask reads aren't available, so layer_sample_frame returns None for the Masks choice and the caller falls back to the current-frame layer_masks read. Source and Effects & Masks historical reads are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * #4368: Masks at a historical Source Frame; legacy Roto Brush keys with grain above Match Grain's Masks choice at a historical Source Frame now samples the layer with its masks as they are at that frame: EffectHost gains layer_masks_at (default None, the current-frame fallback), and the renderer's FxHost implements it like layer_masks at another time. Roto Brush Input Keys saved by 0.24 hash the effects above the brush. Opening an old project adds the grain effects' 89 new controls and Manual to Sampling Process, so the legacy text now leaves the added controls out while they hold the value an old project gets (Source Frame -1 via legacy_default) and restores Sampling Process's 0.24 options. The ADDED_SINCE_0_24 mechanism is taken as-is from #4374 (with an Added::Legacy variant and a POPUPS_0_24 table added). Tests: grain_shared historical Masks test, render layer_masks_at_reads_the_masks_of_that_time, legacy.rs unit tests and an analysis_signature test on an old project with grain above a frozen brush (fixture grain-0.24.json written by the pre-#4368 code). That last test is #[ignore]d: its 0.24 key derivation did not reproduce the base fixture's key in a local run. Not compiled locally after the final edits; CI is the check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * #4368: un-ignore the grain legacy Roto Brush key test The test reproduced 0.24's Roto Brush Input Key from the fixture as opened, but the fixture's 3D Camera Tracker (above the brush) holds a stand-in Solve that 0.24 didn't have when it made the key: the first edit clears it (camera_track::invalidate), and only then does the legacy text give ROTO_INPUT_0_24. The derivation now adds a render queue item first, as the fixture's own test does, and the test runs again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: FredApps <FredApps@users.noreply.github.com>
This commit is contained in:
@@ -82,9 +82,31 @@ const CPU_ONLY_CONTROLS: &[(&str, &[&str])] = &[
|
||||
"sourceCrops/edgeColourAlpha",
|
||||
],
|
||||
),
|
||||
("ec.noise.addgrain", &["viewingMode", "preset", "color/redBalance", "color/greenBalance", "color/blueBalance", "previewRegion/"]),
|
||||
(
|
||||
"ec.noise.addgrain",
|
||||
&[
|
||||
"viewingMode",
|
||||
"preset",
|
||||
"color/redBalance",
|
||||
"color/greenBalance",
|
||||
"color/blueBalance",
|
||||
"previewRegion/",
|
||||
"application/channelBalance/",
|
||||
"blendWithOriginal/",
|
||||
],
|
||||
),
|
||||
("ec.blur.cameralens", &["irisProperties/diffractionFringe", "blurMap/blurMapLayer"]),
|
||||
("ec.noise.removegrain", &["temporalFiltering/enabled"]),
|
||||
(
|
||||
"ec.noise.removegrain",
|
||||
&[
|
||||
"temporalFiltering/enabled",
|
||||
"noiseReductionSettings/channelNoiseReduction/",
|
||||
"fineTuning/chromaSuppression",
|
||||
"fineTuning/noiseSizeBias",
|
||||
"fineTuning/cleanSolidAreas",
|
||||
"blendWithOriginal/",
|
||||
],
|
||||
),
|
||||
("ec.distort.liquify", &["viewFreezeAreaMask", "viewMesh"]),
|
||||
("ec.distort.ccpowerpin", &["unstretch"]),
|
||||
// #4368: Two-Point Bend's Distort = Preserve Length.
|
||||
|
||||
@@ -0,0 +1,936 @@
|
||||
//! Controls the grain effects (Add Grain, Match Grain, Remove Grain) share beyond their look
|
||||
//! (`noise::GrainLook`): Application ▸ Channel Balance, the Sampling group (Source Frame, the
|
||||
//! manual Noise Sample Points and Match Grain's per-point Intensity) and the Blend with
|
||||
//! Original group (Amount, the colour-matching and mask-layer matte that says where the
|
||||
//! original comes back).
|
||||
|
||||
use effectcraft_color::{luminance, rgb_to_hsl};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::util::{Plane, fit_buffer, fit_layer, gauss_plane, lerp4, smoothstep, unpremul};
|
||||
use crate::{Buf, EffectCtx, ParamSpec, num, p, popup, slider};
|
||||
|
||||
fn pct() -> ParamUi {
|
||||
slider(0.0, 100.0, 0.0, 100.0, 1)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Channel Balance
|
||||
|
||||
/// Application ▸ Channel Balance: per channel (red, green, blue) multipliers of the Shadows,
|
||||
/// Midtones and Highlights grain weights, `[channel][tone]`.
|
||||
pub(crate) const CHANNEL_BALANCE_IDS: [[&str; 3]; 3] = [
|
||||
["application/channelBalance/redShadows", "application/channelBalance/redMidtones", "application/channelBalance/redHighlights"],
|
||||
["application/channelBalance/greenShadows", "application/channelBalance/greenMidtones", "application/channelBalance/greenHighlights"],
|
||||
["application/channelBalance/blueShadows", "application/channelBalance/blueMidtones", "application/channelBalance/blueHighlights"],
|
||||
];
|
||||
const CHANNEL_BALANCE_NAMES: [[&str; 3]; 3] = [
|
||||
["Red Shadows", "Red Midtones", "Red Highlights"],
|
||||
["Green Shadows", "Green Midtones", "Green Highlights"],
|
||||
["Blue Shadows", "Blue Midtones", "Blue Highlights"],
|
||||
];
|
||||
|
||||
pub(crate) fn channel_balance_params() -> Vec<ParamSpec> {
|
||||
CHANNEL_BALANCE_IDS
|
||||
.iter()
|
||||
.zip(CHANNEL_BALANCE_NAMES.iter())
|
||||
.flat_map(|(ids, names)| ids.iter().zip(names.iter()).map(|(id, name)| p(id, name, num(1.0), slider(0.0, 10.0, 0.0, 2.0, 2))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Channel Balance multipliers of an instance (1 for projects saved before they existed).
|
||||
pub(crate) fn channel_balance(ctx: &EffectCtx) -> [[f32; 3]; 3] {
|
||||
CHANNEL_BALANCE_IDS.map(|ids| ids.map(|id| ctx.params.get(id).map(Value::as_f64).unwrap_or(1.0).max(0.0) as f32))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Sampling
|
||||
|
||||
const POINT_IDS: [&str; 10] = [
|
||||
"sampling/noiseSamplePoints/point1",
|
||||
"sampling/noiseSamplePoints/point2",
|
||||
"sampling/noiseSamplePoints/point3",
|
||||
"sampling/noiseSamplePoints/point4",
|
||||
"sampling/noiseSamplePoints/point5",
|
||||
"sampling/noiseSamplePoints/point6",
|
||||
"sampling/noiseSamplePoints/point7",
|
||||
"sampling/noiseSamplePoints/point8",
|
||||
"sampling/noiseSamplePoints/point9",
|
||||
"sampling/noiseSamplePoints/point10",
|
||||
];
|
||||
const INTENSITY_IDS: [&str; 10] = [
|
||||
"sampling/intensity/intensity1",
|
||||
"sampling/intensity/intensity2",
|
||||
"sampling/intensity/intensity3",
|
||||
"sampling/intensity/intensity4",
|
||||
"sampling/intensity/intensity5",
|
||||
"sampling/intensity/intensity6",
|
||||
"sampling/intensity/intensity7",
|
||||
"sampling/intensity/intensity8",
|
||||
"sampling/intensity/intensity9",
|
||||
"sampling/intensity/intensity10",
|
||||
];
|
||||
const NUMBERS: [&str; 10] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
|
||||
|
||||
/// Sample Selection (`sampling/samplingProcess`) options: the flattest boxes found
|
||||
/// automatically, or boxes centred on the Noise Sample Points.
|
||||
pub(crate) const SAMPLE_SELECTION: [&str; 2] = ["Automatic", "Manual"];
|
||||
const MANUAL: u32 = 1;
|
||||
|
||||
/// The Sampling group of Match Grain (`intensity`: with its per-point Intensity) and Remove
|
||||
/// Grain, in Effect Controls order.
|
||||
pub(crate) fn sampling_params(intensity: bool) -> Vec<ParamSpec> {
|
||||
let mut v = vec![
|
||||
// −1 (projects saved before Source Frame existed) samples the frame being rendered.
|
||||
p("sampling/sourceFrame", "Source Frame", num(0.0), slider(-1.0, 100000.0, 0.0, 300.0, 0)),
|
||||
p("sampling/numberOfSamples", "Number of Samples", num(80.0), slider(1.0, 500.0, 1.0, 200.0, 0)),
|
||||
p("sampling/sampleSize", "Sample Size", num(9.0), slider(3.0, 64.0, 3.0, 32.0, 0)),
|
||||
p("sampling/sampleBoxColor", "Sample Box Color", crate::col(1.0, 1.0, 0.0), ParamUi::Color),
|
||||
p("sampling/samplingProcess", "Sampling Process", Value::Enum(0), popup(&SAMPLE_SELECTION)),
|
||||
];
|
||||
// Ten points spread over the layer (two rows of five).
|
||||
for (k, (id, name)) in POINT_IDS.iter().zip(NUMBERS.iter()).enumerate() {
|
||||
let (col, row) = ((k % 5) as f64, (k / 5) as f64);
|
||||
v.push(p(id, name, Value::Vec2([0.15 + col * 0.175, 0.3 + row * 0.4]), ParamUi::Point));
|
||||
}
|
||||
if intensity {
|
||||
for (id, name) in INTENSITY_IDS.iter().zip(NUMBERS.iter()) {
|
||||
v.push(p(id, name, num(1.0), slider(0.0, 10.0, 0.0, 2.0, 2)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Sample box size in buffer pixels.
|
||||
fn sample_size(ctx: &EffectCtx, scale: f64) -> usize {
|
||||
let s = ctx.params.get("sampling/sampleSize").map(Value::as_f64).unwrap_or(9.0) * scale;
|
||||
if s.is_finite() { s.round().clamp(3.0, 4096.0) as usize } else { 9 }
|
||||
}
|
||||
|
||||
fn number_of_samples(ctx: &EffectCtx) -> usize {
|
||||
let n = ctx.params.get("sampling/numberOfSamples").map(Value::as_f64).unwrap_or(80.0);
|
||||
if n.is_finite() { n.clamp(1.0, 500.0) as usize } else { 80 }
|
||||
}
|
||||
|
||||
fn manual(ctx: &EffectCtx) -> bool {
|
||||
ctx.params.get("sampling/samplingProcess").map(Value::as_enum) == Some(MANUAL)
|
||||
}
|
||||
|
||||
/// The sample boxes (x, y, size in buffer px) of the effect's Sampling settings in `img`, a
|
||||
/// buffer at `scale` and `offset`: see [`sampling`].
|
||||
pub(crate) fn sampling_boxes(ctx: &EffectCtx, img: &Image, scale: f64, offset: [f64; 2]) -> Vec<(usize, usize, usize)> {
|
||||
sampling(ctx, img, scale, offset).into_iter().map(|(b, _)| b).collect()
|
||||
}
|
||||
|
||||
/// Whether box `(x, y, s)` and the `SAMPLE_REACH` px around it are opaque in `img` (the rule
|
||||
/// automatic sampling applies: a transparent pixel there is black once unpremultiplied, and
|
||||
/// the grain statistics' high-pass would measure that edge as grain).
|
||||
fn opaque_surround(img: &Image, (x, y, s): (usize, usize, usize)) -> bool {
|
||||
let reach = crate::noise::SAMPLE_REACH;
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let (x1, y1) = (x.saturating_add(s).saturating_add(reach).min(w), y.saturating_add(s).saturating_add(reach).min(h));
|
||||
(y.saturating_sub(reach)..y1).all(|yy| (x.saturating_sub(reach)..x1).all(|xx| img.data.get(yy * w + xx).is_some_and(|p| p[3] > 0.5)))
|
||||
}
|
||||
|
||||
/// The sample boxes with the index of the Noise Sample Point each came from: the flattest boxes
|
||||
/// (Automatic; indexed in order), or boxes centred on the first Number of Samples (at most 10)
|
||||
/// Noise Sample Points, kept inside the image, without those whose surround reaches transparent
|
||||
/// pixels (Manual).
|
||||
pub(crate) fn sampling(ctx: &EffectCtx, img: &Image, scale: f64, offset: [f64; 2]) -> Vec<((usize, usize, usize), usize)> {
|
||||
let s = sample_size(ctx, scale);
|
||||
if !manual(ctx) {
|
||||
return crate::noise::sample_boxes(img, number_of_samples(ctx), s).into_iter().enumerate().map(|(i, b)| (b, i)).collect();
|
||||
}
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let s = s.min(w).min(h);
|
||||
if s < 3 {
|
||||
return vec![];
|
||||
}
|
||||
POINT_IDS
|
||||
.iter()
|
||||
.take(number_of_samples(ctx).min(POINT_IDS.len()))
|
||||
.enumerate()
|
||||
.map(|(i, id)| {
|
||||
let pt = ctx.params.get(id).map(Value::as_vec2).unwrap_or([0.0, 0.0]);
|
||||
let c = [pt[0] * scale + offset[0], pt[1] * scale + offset[1]];
|
||||
let corner = |v: f64, n: usize| {
|
||||
let v = v - s as f64 * 0.5;
|
||||
if v.is_finite() { v.round().clamp(0.0, n.saturating_sub(s) as f64) as usize } else { 0 }
|
||||
};
|
||||
((corner(c[0], w), corner(c[1], h), s), i)
|
||||
})
|
||||
.filter(|(b, _)| opaque_surround(img, *b))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Match Grain's per-point Intensity weights of manual sample boxes from Noise Sample Points
|
||||
/// `points` (`None` in Automatic sampling or without the controls).
|
||||
pub(crate) fn sample_intensities(ctx: &EffectCtx, points: &[usize]) -> Option<Vec<f32>> {
|
||||
if !manual(ctx) || ctx.params.get(INTENSITY_IDS[0]).is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(points.iter().map(|&i| INTENSITY_IDS.get(i).and_then(|id| ctx.params.get(id)).map(Value::as_f64).unwrap_or(1.0).max(0.0) as f32).collect())
|
||||
}
|
||||
|
||||
/// The layer uses a fixed Source Frame (not −1, "the frame being rendered").
|
||||
pub(crate) fn fixed_source_frame(ctx: &EffectCtx) -> bool {
|
||||
ctx.params.get("sampling/sourceFrame").is_some_and(|v| v.as_f64() >= 0.0)
|
||||
}
|
||||
|
||||
/// The layer time of Sampling ▸ Source Frame (frames at the comp rate from the layer's start),
|
||||
/// or `None` when it is the frame being rendered (or −1, "the current frame").
|
||||
pub(crate) fn source_frame_time(ctx: &EffectCtx) -> Option<f64> {
|
||||
let f = ctx.params.get("sampling/sourceFrame")?.as_f64();
|
||||
if !f.is_finite() || f < 0.0 {
|
||||
return None;
|
||||
}
|
||||
let fps = ctx.fps();
|
||||
let t = f.round() / fps;
|
||||
((t - ctx.time).abs() >= 0.5 / fps).then_some(t)
|
||||
}
|
||||
|
||||
/// The effect's own input at the Source Frame, in `b`'s pixel grid (`None` when that is the
|
||||
/// current frame or the host can't render it: then the current input is sampled).
|
||||
pub(crate) fn own_sample_frame(ctx: &EffectCtx, b: &Buf) -> Option<Image> {
|
||||
let t = source_frame_time(ctx)?;
|
||||
let other = ctx.env.host?.self_at(t, ctx.env.effect_index)?;
|
||||
Some(fit_buffer(&other, b.img.width, b.img.height, b.offset, b.scale))
|
||||
}
|
||||
|
||||
/// Layer parameter `id` (with its source companion) at the Source Frame, fitted to `b`
|
||||
/// (`None` when that is the current frame, no layer is chosen or the host can't render it).
|
||||
pub(crate) fn layer_sample_frame(ctx: &EffectCtx, b: &Buf, id: &str) -> Option<Image> {
|
||||
let t = source_frame_time(ctx)?;
|
||||
let lid = ctx.params.get(id)?.as_layer()?;
|
||||
let comp_t = ctx.env.comp_time + (t - ctx.time);
|
||||
let host = ctx.env.host?;
|
||||
// Source / Masks / Effects & Masks, at the Source Frame.
|
||||
let other = match ctx.params.get(&crate::layer_source_id(id)).map(Value::as_enum) {
|
||||
Some(1) => host.layer_masks_at(lid, comp_t)?,
|
||||
Some(e) => host.layer_at(lid, comp_t, e >= 2)?,
|
||||
None => host.layer_at(lid, comp_t, false)?,
|
||||
};
|
||||
Some(fit_layer(ctx, b, &other, false))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Blend with Original
|
||||
|
||||
/// Combine Match and Mask Using options.
|
||||
pub(crate) const COMBINE: [&str; 2] = ["Add", "Multiply"];
|
||||
/// Match Color Using options.
|
||||
pub(crate) const MATCH_COLOR_USING: [&str; 3] = ["RGB", "Hue", "Chroma"];
|
||||
/// Masking Mode options (which channel of the Mask Layer brings the original back).
|
||||
pub(crate) const MASKING_MODES: [&str; 4] = ["Luminance", "Inverted Luminance", "Alpha", "Inverted Alpha"];
|
||||
/// If Mask Size Differs options.
|
||||
pub(crate) const MASK_SIZE: [&str; 2] = ["Center", "Stretch to Fit"];
|
||||
|
||||
const MASK_LAYER: &str = "blendWithOriginal/maskingLayer/maskLayer";
|
||||
|
||||
/// The Blend with Original group, in Effect Controls order.
|
||||
pub(crate) fn blend_params() -> Vec<ParamSpec> {
|
||||
vec![
|
||||
p("blendWithOriginal/amount", "Amount", num(0.0), pct()),
|
||||
p("blendWithOriginal/combineMatchAndMaskUsing", "Combine Match and Mask Using", Value::Enum(0), popup(&COMBINE)),
|
||||
p("blendWithOriginal/blurMatte", "Blur Matte", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
|
||||
p("blendWithOriginal/colorMatching/matchColorUsing", "Match Color Using", Value::Enum(0), popup(&MATCH_COLOR_USING)),
|
||||
p("blendWithOriginal/colorMatching/matchingColor", "Matching Color", crate::col(1.0, 1.0, 1.0), ParamUi::Color),
|
||||
p("blendWithOriginal/colorMatching/matchingTolerance", "Matching Tolerance", num(0.0), pct()),
|
||||
p("blendWithOriginal/colorMatching/matchingSoftness", "Matching Softness", num(0.0), pct()),
|
||||
p("blendWithOriginal/colorMatching/invertMatch", "Invert Match", Value::Bool(false), ParamUi::Checkbox),
|
||||
p(MASK_LAYER, "Mask Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("blendWithOriginal/maskingLayer/maskingMode", "Masking Mode", Value::Enum(0), popup(&MASKING_MODES)),
|
||||
p("blendWithOriginal/maskingLayer/ifMaskSizeDiffers", "If Mask Size Differs", Value::Enum(0), popup(&MASK_SIZE)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Distance 0..1 between straight colours `c` and `m` in Match Color Using's space.
|
||||
fn color_distance(using: u32, c: [f32; 3], m: [f32; 3]) -> f32 {
|
||||
match using {
|
||||
// Hue: around the colour wheel.
|
||||
1 => {
|
||||
let (h1, _, _) = rgb_to_hsl(c[0], c[1], c[2]);
|
||||
let (h2, _, _) = rgb_to_hsl(m[0], m[1], m[2]);
|
||||
let d = (h1 - h2).abs().rem_euclid(1.0);
|
||||
d.min(1.0 - d) * 2.0
|
||||
}
|
||||
// Chroma: the colour difference planes, ignoring lightness.
|
||||
2 => {
|
||||
let (y1, y2) = (luminance(c[0], c[1], c[2]), luminance(m[0], m[1], m[2]));
|
||||
let (b, r) = ((c[2] - y1) - (m[2] - y2), (c[0] - y1) - (m[0] - y2));
|
||||
(b * b + r * r).sqrt()
|
||||
}
|
||||
_ => {
|
||||
let d = [0, 1, 2].map(|k| c[k] - m[k]);
|
||||
((d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) / 3.0).sqrt()
|
||||
}
|
||||
}
|
||||
.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// How much of the original each pixel of `b` takes back (Amount × the matte, 0..1), or
|
||||
/// `None` when Amount is 0. The matte is the Color Matching selection of `orig`'s colours
|
||||
/// (active once Matching Tolerance or Softness is above 0, or Invert Match is on) and the Mask
|
||||
/// Layer (when one is chosen), combined by Combine Match and Mask Using and blurred by Blur
|
||||
/// Matte; with neither, the original is blended uniformly.
|
||||
pub(crate) fn original_weight(ctx: &EffectCtx, b: &Buf, orig: &Image) -> Option<Plane> {
|
||||
let pr = ctx.params;
|
||||
let val = |id: &str, d: f64| pr.get(id).map(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(d);
|
||||
let amount = (val("blendWithOriginal/amount", 0.0) / 100.0).clamp(0.0, 1.0) as f32;
|
||||
if amount <= 0.0 || orig.data.len() != b.img.data.len() {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let tol = (val("blendWithOriginal/colorMatching/matchingTolerance", 0.0) / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let soft = (val("blendWithOriginal/colorMatching/matchingSoftness", 0.0) / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let invert = pr.get("blendWithOriginal/colorMatching/invertMatch").is_some_and(Value::as_bool);
|
||||
let color = (tol > 0.0 || soft > 0.0 || invert).then(|| {
|
||||
let using = pr.get("blendWithOriginal/colorMatching/matchColorUsing").map(Value::as_enum).unwrap_or(0);
|
||||
let m = pr.get("blendWithOriginal/colorMatching/matchingColor").map(Value::as_color).unwrap_or([1.0; 4]);
|
||||
let m = [m[0], m[1], m[2]];
|
||||
Plane::from_image(orig, |px| {
|
||||
let (c, _) = unpremul(px);
|
||||
let d = color_distance(using, c, m);
|
||||
let hit = if soft > 0.0 {
|
||||
1.0 - smoothstep(tol, tol + soft, d)
|
||||
} else if d <= tol {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if invert { 1.0 - hit } else { hit }
|
||||
})
|
||||
});
|
||||
let mask = ctx.layer_param(MASK_LAYER, true).map(|o| {
|
||||
let stretch = pr.get("blendWithOriginal/maskingLayer/ifMaskSizeDiffers").map(Value::as_enum) == Some(1);
|
||||
let img = fit_layer(ctx, b, &o, stretch);
|
||||
let mode = pr.get("blendWithOriginal/maskingLayer/maskingMode").map(Value::as_enum).unwrap_or(0);
|
||||
Plane::from_image(&img, move |px| {
|
||||
// Premultiplied luminance: transparent mask pixels are black.
|
||||
let v = match mode {
|
||||
0 | 1 => luminance(px[0], px[1], px[2]),
|
||||
_ => px[3],
|
||||
}
|
||||
.clamp(0.0, 1.0);
|
||||
if mode % 2 == 1 { 1.0 - v } else { v }
|
||||
})
|
||||
});
|
||||
let matte = match (color, mask) {
|
||||
(Some(c), Some(m)) => {
|
||||
let multiply = pr.get("blendWithOriginal/combineMatchAndMaskUsing").map(Value::as_enum) == Some(1);
|
||||
Some(c.zip_map(&m, |a, b| if multiply { a * b } else { (a + b).min(1.0) }))
|
||||
}
|
||||
(c, m) => c.or(m),
|
||||
};
|
||||
let Some(mut matte) = matte else {
|
||||
return Some(Plane { w, h, data: vec![amount; w * h] });
|
||||
};
|
||||
let blur = val("blendWithOriginal/blurMatte", 0.0).max(0.0) * b.scale;
|
||||
if blur > 0.05 {
|
||||
matte = gauss_plane(&matte, blur, blur);
|
||||
}
|
||||
Some(matte.map(|v| v.clamp(0.0, 1.0) * amount))
|
||||
}
|
||||
|
||||
/// Blend `orig` back into `b` by the [`original_weight`] `k` (nothing when `None`).
|
||||
pub(crate) fn blend_back(b: &mut Buf, orig: &Image, k: Option<&Plane>) {
|
||||
let Some(k) = k else { return };
|
||||
if orig.data.len() != b.img.data.len() || k.data.len() != b.img.data.len() {
|
||||
return;
|
||||
}
|
||||
b.img.data.par_iter_mut().zip(orig.data.par_iter()).zip(k.data.par_iter()).for_each(|((px, o), &t)| {
|
||||
*px = if t >= 1.0 { *o } else { lerp4(*px, *o, t) };
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::migrate::upgrade_instance;
|
||||
use crate::{EffectEnv, EffectHost, LayerPixels, Params, find, flatten_params, instantiate};
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{Node, PropGroup};
|
||||
|
||||
/// Effect Controls outline of an instance: shown properties and groups (`name/`), two spaces
|
||||
/// per nesting level.
|
||||
fn outline(g: &PropGroup) -> Vec<String> {
|
||||
fn walk(g: &PropGroup, depth: usize, out: &mut Vec<String>) {
|
||||
for c in &g.children {
|
||||
match c {
|
||||
Node::Prop(p) if !matches!(p.ui, ParamUi::Hidden) => out.push(format!("{}{}", " ".repeat(depth), p.name)),
|
||||
Node::Prop(_) => {}
|
||||
Node::Group(sg) => {
|
||||
out.push(format!("{}{}/", " ".repeat(depth), sg.name));
|
||||
walk(sg, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(g, 0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Expected outline lines: `>` per nesting level, a trailing `/` for a group.
|
||||
fn expect(lines: &[&str]) -> Vec<String> {
|
||||
lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let depth = l.chars().take_while(|c| *c == '>').count();
|
||||
format!("{}{}", " ".repeat(depth), &l[depth..])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn new_instance(id: &str) -> (&'static crate::EffectSpec, PropGroup) {
|
||||
let spec = find(id).unwrap();
|
||||
let mut next = 1;
|
||||
(spec, instantiate(spec, &mut Ids(&mut next), spec.name, [64.0, 48.0]))
|
||||
}
|
||||
|
||||
const PREVIEW: &[&str] = &["Preview Region/", ">Center", ">Width", ">Height", ">Show Box", ">Box Color"];
|
||||
const LOOK: &[&str] = &[
|
||||
"Tweaking/",
|
||||
">Intensity",
|
||||
">Size",
|
||||
">Softness",
|
||||
">Aspect Ratio",
|
||||
">Channel Intensities/",
|
||||
">>Red Intensity",
|
||||
">>Green Intensity",
|
||||
">>Blue Intensity",
|
||||
">Channel Size/",
|
||||
">>Red Size",
|
||||
">>Green Size",
|
||||
">>Blue Size",
|
||||
"Color/",
|
||||
">Monochromatic",
|
||||
">Saturation",
|
||||
">Tint Amount",
|
||||
">Tint Color",
|
||||
// (ours: per-channel grain multipliers After Effects doesn't show)
|
||||
">Red Balance",
|
||||
">Green Balance",
|
||||
">Blue Balance",
|
||||
"Application/",
|
||||
">Blending Mode",
|
||||
">Shadows",
|
||||
">Midtones",
|
||||
">Highlights",
|
||||
">Midpoint",
|
||||
">Channel Balance/",
|
||||
">>Red Shadows",
|
||||
">>Red Midtones",
|
||||
">>Red Highlights",
|
||||
">>Green Shadows",
|
||||
">>Green Midtones",
|
||||
">>Green Highlights",
|
||||
">>Blue Shadows",
|
||||
">>Blue Midtones",
|
||||
">>Blue Highlights",
|
||||
];
|
||||
const ANIMATION: &[&str] = &["Animation/", ">Animation Speed", ">Animate Smoothly", ">Random Seed"];
|
||||
const SAMPLING: &[&str] = &[
|
||||
"Sampling/",
|
||||
">Source Frame",
|
||||
">Number of Samples",
|
||||
">Sample Size",
|
||||
">Sample Box Color",
|
||||
">Sampling Process",
|
||||
">Noise Sample Points/",
|
||||
">>1",
|
||||
">>2",
|
||||
">>3",
|
||||
">>4",
|
||||
">>5",
|
||||
">>6",
|
||||
">>7",
|
||||
">>8",
|
||||
">>9",
|
||||
">>10",
|
||||
];
|
||||
const SAMPLE_INTENSITY: &[&str] = &[">Intensity/", ">>1", ">>2", ">>3", ">>4", ">>5", ">>6", ">>7", ">>8", ">>9", ">>10"];
|
||||
const BLEND: &[&str] = &[
|
||||
"Blend with Original/",
|
||||
">Amount",
|
||||
">Combine Match and Mask Using",
|
||||
">Blur Matte",
|
||||
">Color Matching/",
|
||||
">>Match Color Using",
|
||||
">>Matching Color",
|
||||
">>Matching Tolerance",
|
||||
">>Matching Softness",
|
||||
">>Invert Match",
|
||||
">Masking Layer/",
|
||||
">>Mask Layer",
|
||||
">>Masking Mode",
|
||||
">>If Mask Size Differs",
|
||||
];
|
||||
|
||||
/// #4368: the grain effects' controls, in After Effects' Effect Controls order.
|
||||
#[test]
|
||||
fn grain_effects_have_after_effects_controls_in_order() {
|
||||
let add = [&["Viewing Mode", "Preset"][..], PREVIEW, LOOK, ANIMATION, BLEND].concat();
|
||||
assert_eq!(outline(&new_instance("ec.noise.addgrain").1), expect(&add));
|
||||
let matching =
|
||||
[&["Viewing Mode", "Noise Source Layer"][..], PREVIEW, &["Compensate for Existing Noise"], LOOK, SAMPLING, SAMPLE_INTENSITY, ANIMATION, BLEND]
|
||||
.concat();
|
||||
assert_eq!(outline(&new_instance("ec.noise.matchgrain").1), expect(&matching));
|
||||
let remove = [
|
||||
&["Viewing Mode"][..],
|
||||
PREVIEW,
|
||||
&[
|
||||
"Noise Reduction Settings/",
|
||||
">Noise Reduction",
|
||||
">Passes",
|
||||
">Mode",
|
||||
">Channel Noise Reduction/",
|
||||
">>Red Noise Reduction",
|
||||
">>Green Noise Reduction",
|
||||
">>Blue Noise Reduction",
|
||||
"Fine Tuning/",
|
||||
">Chroma Suppression",
|
||||
">Texture",
|
||||
">Noise Size Bias",
|
||||
">Clean Solid Areas",
|
||||
"Temporal Filtering/",
|
||||
">Enabled",
|
||||
">Amount",
|
||||
">Motion Sensitivity",
|
||||
"Unsharp Mask/",
|
||||
">Amount",
|
||||
">Radius",
|
||||
">Threshold",
|
||||
],
|
||||
SAMPLING,
|
||||
BLEND,
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(outline(&new_instance("ec.noise.removegrain").1), expect(&remove));
|
||||
}
|
||||
|
||||
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;
|
||||
let m = (crate::util::hash1(x, y, seed ^ 0x55) - 0.5) * 2.0 * amp;
|
||||
img.set(x, y, [0.5 + n, 0.5 + m, 0.5 - n, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn var(img: &Image, k: usize) -> f32 {
|
||||
let n = img.data.len() as f32;
|
||||
let mean = img.data.iter().map(|p| p[k]).sum::<f32>() / n;
|
||||
img.data.iter().map(|p| (p[k] - mean).powi(2)).sum::<f32>() / n
|
||||
}
|
||||
|
||||
fn max_diff(a: &Image, b: &Image) -> f32 {
|
||||
a.data.iter().zip(&b.data).flat_map(|(p, q)| (0..4).map(move |k| (p[k] - q[k]).abs())).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
fn diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 {
|
||||
a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |k| (p[k] - q[k]).abs())).fold(0.0f32, f32::max)
|
||||
}
|
||||
|
||||
fn run(id: &str, vals: &[(&str, Value)], img: Image, time: f64, env: EffectEnv) -> Image {
|
||||
crate::run_fx(id, vals, img, time, env).img
|
||||
}
|
||||
|
||||
/// A host with layer 7 (`layer`), the layer's own input at other times (`own`) and layer 7
|
||||
/// at other times (`other`).
|
||||
struct Host {
|
||||
layer: Image,
|
||||
own: Option<Image>,
|
||||
other: Option<Image>,
|
||||
}
|
||||
impl EffectHost for Host {
|
||||
fn layer(&self, id: u64, _: bool) -> Option<LayerPixels> {
|
||||
(id == 7).then(|| LayerPixels {
|
||||
buf: Buf { img: self.layer.clone(), offset: [0.0; 2], scale: 1.0 },
|
||||
size: [self.layer.width as f64, self.layer.height as f64],
|
||||
})
|
||||
}
|
||||
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
fn self_at(&self, _: f64, _: usize) -> Option<Buf> {
|
||||
self.own.clone().map(|img| Buf { img, offset: [0.0; 2], scale: 1.0 })
|
||||
}
|
||||
fn layer_at(&self, id: u64, _: f64, _: bool) -> Option<LayerPixels> {
|
||||
let img = self.other.clone().filter(|_| id == 7)?;
|
||||
Some(LayerPixels { size: [img.width as f64, img.height as f64], buf: Buf { img, offset: [0.0; 2], scale: 1.0 } })
|
||||
}
|
||||
}
|
||||
|
||||
fn host(layer: Image) -> Host {
|
||||
Host { layer, own: None, other: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_balance_scales_each_channels_tones() {
|
||||
let base = Image::filled(48, 48, [0.4, 0.4, 0.4, 1.0]);
|
||||
let grain = ("tweaking/intensity", num(3.0));
|
||||
let env = EffectEnv::default();
|
||||
let plain = run("ec.noise.addgrain", std::slice::from_ref(&grain), base.clone(), 0.0, env);
|
||||
// Balance 1 everywhere renders as before.
|
||||
let ones: Vec<(&str, Value)> = CHANNEL_BALANCE_IDS.iter().flatten().map(|id| (*id, num(1.0))).chain([grain.clone()]).collect();
|
||||
assert_eq!(run("ec.noise.addgrain", &ones, base.clone(), 0.0, env).data, plain.data);
|
||||
// No red grain in any tone leaves red alone; green keeps its grain.
|
||||
let nored: Vec<(&str, Value)> = CHANNEL_BALANCE_IDS[0].iter().map(|id| (*id, num(0.0))).chain([grain.clone()]).collect();
|
||||
let out = run("ec.noise.addgrain", &nored, base.clone(), 0.0, env);
|
||||
assert!(out.data.iter().all(|p| (p[0] - 0.4).abs() < 1e-6));
|
||||
assert!(out.data.iter().any(|p| (p[1] - 0.4).abs() > 1e-3));
|
||||
// Only the tone the pixel is in matters: a dark image ignores Red Highlights.
|
||||
let dark = Image::filled(48, 48, [0.02, 0.02, 0.02, 1.0]);
|
||||
let a = run("ec.noise.addgrain", std::slice::from_ref(&grain), dark.clone(), 0.0, env);
|
||||
let b = run("ec.noise.addgrain", &[grain.clone(), (CHANNEL_BALANCE_IDS[0][2], num(0.0))], dark.clone(), 0.0, env);
|
||||
assert!(max_diff(&a, &b) < 1e-3);
|
||||
let c = run("ec.noise.addgrain", &[grain, (CHANNEL_BALANCE_IDS[0][0], num(0.0))], dark, 0.0, env);
|
||||
assert!(max_diff(&a, &c) > 1e-3);
|
||||
// Match Grain reads the same controls.
|
||||
let h = host(noisy(48, 48, 0.1, 3));
|
||||
let env = EffectEnv { host: Some(&h), ..Default::default() };
|
||||
let src = ("noiseSourceLayer", Value::Layer(Some(7)));
|
||||
let m = run("ec.noise.matchgrain", std::slice::from_ref(&src), base.clone(), 0.0, env);
|
||||
let mut nored: Vec<(&str, Value)> = CHANNEL_BALANCE_IDS[0].iter().map(|id| (*id, num(0.0))).collect();
|
||||
nored.push(src);
|
||||
let m0 = run("ec.noise.matchgrain", &nored, base, 0.0, env);
|
||||
assert!(m0.data.iter().all(|p| (p[0] - 0.4).abs() < 1e-6));
|
||||
assert!(max_diff(&m, &m0) > 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_with_original_amount_color_matching_and_mask_layer() {
|
||||
// Left half red, right half blue.
|
||||
let mut base = Image::new(48, 32);
|
||||
for y in 0..32 {
|
||||
for x in 0..48 {
|
||||
base.set(x, y, if x < 24 { [0.8, 0.1, 0.1, 1.0] } else { [0.1, 0.1, 0.8, 1.0] });
|
||||
}
|
||||
}
|
||||
let grain = ("tweaking/intensity", num(4.0));
|
||||
let env = EffectEnv::default();
|
||||
let full = run("ec.noise.addgrain", std::slice::from_ref(&grain), base.clone(), 0.0, env);
|
||||
assert!(max_diff(&full, &base) > 0.01);
|
||||
let amount = |v: f64| ("blendWithOriginal/amount", num(v));
|
||||
// Amount 100 with no matte: the original.
|
||||
assert!(max_diff(&run("ec.noise.addgrain", &[grain.clone(), amount(100.0)], base.clone(), 0.0, env), &base) < 1e-6);
|
||||
// Amount 50: halfway.
|
||||
let half = run("ec.noise.addgrain", &[grain.clone(), amount(50.0)], base.clone(), 0.0, env);
|
||||
for ((h, f), o) in half.data.iter().zip(&full.data).zip(&base.data) {
|
||||
assert!((h[2] - (f[2] + o[2]) * 0.5).abs() < 1e-5);
|
||||
}
|
||||
// Color matching on red: the red half gets the original back, the blue half keeps the grain.
|
||||
let red = ("blendWithOriginal/colorMatching/matchingColor", crate::col(0.8, 0.1, 0.1));
|
||||
let tol = ("blendWithOriginal/colorMatching/matchingTolerance", num(10.0));
|
||||
let matched = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), red.clone(), tol.clone()], base.clone(), 0.0, env);
|
||||
let side = |img: &Image, left: bool| {
|
||||
let w = img.width as usize;
|
||||
img.data.iter().enumerate().filter(|(i, _)| (i % w < 24) == left).map(|(_, p)| *p).collect::<Vec<_>>()
|
||||
};
|
||||
assert!(diff(&side(&matched, true), &side(&base, true)) < 1e-6);
|
||||
assert!(diff(&side(&matched, false), &side(&full, false)) < 1e-6);
|
||||
// Invert Match swaps the sides.
|
||||
let invert = ("blendWithOriginal/colorMatching/invertMatch", Value::Bool(true));
|
||||
let inverted = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), red.clone(), tol.clone(), invert], base.clone(), 0.0, env);
|
||||
assert!(diff(&side(&inverted, false), &side(&base, false)) < 1e-6);
|
||||
assert!(diff(&side(&inverted, true), &side(&full, true)) < 1e-6);
|
||||
// Hue matching ignores lightness: a darker red still matches.
|
||||
let dark_red = ("blendWithOriginal/colorMatching/matchingColor", crate::col(0.4, 0.05, 0.05));
|
||||
let by_hue = ("blendWithOriginal/colorMatching/matchColorUsing", Value::Enum(1));
|
||||
let hue = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), dark_red, tol.clone(), by_hue], base.clone(), 0.0, env);
|
||||
assert!(diff(&side(&hue, true), &side(&base, true)) < 1e-6);
|
||||
// Mask layer: white over the top half brings the original back there.
|
||||
let mut mask = Image::new(48, 32);
|
||||
for y in 0..16 {
|
||||
for x in 0..48 {
|
||||
mask.set(x, y, [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
}
|
||||
let h = host(mask);
|
||||
let env = EffectEnv { host: Some(&h), ..Default::default() };
|
||||
let layer = (MASK_LAYER, Value::Layer(Some(7)));
|
||||
let masked = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), layer.clone()], base.clone(), 0.0, env);
|
||||
let top = |img: &Image| img.data[..48 * 16].to_vec();
|
||||
let bottom = |img: &Image| img.data[48 * 16..].to_vec();
|
||||
assert!(diff(&top(&masked), &top(&base)) < 1e-6);
|
||||
assert!(diff(&bottom(&masked), &bottom(&full)) < 1e-6);
|
||||
// Inverted Luminance swaps them.
|
||||
let inv_mode = ("blendWithOriginal/maskingLayer/maskingMode", Value::Enum(1));
|
||||
let inv = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), layer.clone(), inv_mode], base.clone(), 0.0, env);
|
||||
assert!(diff(&bottom(&inv), &bottom(&base)) < 1e-6);
|
||||
// Mask and colour match combined: Multiply keeps only the top-left quarter original,
|
||||
// Add the union.
|
||||
let both = |combine: u32| {
|
||||
let using = ("blendWithOriginal/combineMatchAndMaskUsing", Value::Enum(combine));
|
||||
run("ec.noise.addgrain", &[grain.clone(), amount(100.0), layer.clone(), red.clone(), tol.clone(), using], base.clone(), 0.0, env)
|
||||
};
|
||||
let (add, mul) = (both(0), both(1));
|
||||
let px = |img: &Image, x: i64, y: i64| img.get(x, y);
|
||||
assert_eq!(px(&mul, 5, 5), px(&base, 5, 5));
|
||||
assert_ne!(px(&mul, 40, 5), px(&base, 40, 5));
|
||||
assert_eq!(px(&add, 40, 5), px(&base, 40, 5));
|
||||
assert_eq!(px(&add, 5, 28), px(&base, 5, 28));
|
||||
assert_ne!(px(&add, 40, 28), px(&base, 40, 28));
|
||||
// Blur Matte softens the mask edge.
|
||||
let blurred = run("ec.noise.addgrain", &[grain.clone(), amount(100.0), layer, ("blendWithOriginal/blurMatte", num(4.0))], base.clone(), 0.0, env);
|
||||
assert_ne!(px(&blurred, 40, 15), px(&base, 40, 15));
|
||||
// The Blending Matte view shows where the grain still applies.
|
||||
let matte = run("ec.noise.addgrain", &[grain, amount(50.0), ("viewingMode", Value::Enum(1))], base.clone(), 0.0, EffectEnv::default());
|
||||
assert!(matte.data.iter().all(|p| (p[0] - 0.5).abs() < 1e-5 && p[3] == 1.0));
|
||||
// Remove Grain and Match Grain blend too.
|
||||
let noise = noisy(32, 32, 0.15, 5);
|
||||
let rg = run("ec.noise.removegrain", &[("noiseReductionSettings/noiseReduction", num(3.0)), amount(100.0)], noise.clone(), 0.0, EffectEnv::default());
|
||||
assert!(max_diff(&rg, &noise) < 1e-6);
|
||||
let rg_matte = run("ec.noise.removegrain", &[amount(25.0), ("viewingMode", Value::Enum(2))], noise.clone(), 0.0, EffectEnv::default());
|
||||
assert!(rg_matte.data.iter().all(|p| (p[0] - 0.75).abs() < 1e-5));
|
||||
let h = host(noisy(32, 32, 0.1, 3));
|
||||
let env = EffectEnv { host: Some(&h), ..Default::default() };
|
||||
let flat = Image::filled(32, 32, [0.5, 0.5, 0.5, 1.0]);
|
||||
let mg = run("ec.noise.matchgrain", &[("noiseSourceLayer", Value::Layer(Some(7))), amount(100.0)], flat.clone(), 0.0, env);
|
||||
assert!(max_diff(&mg, &flat) < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_grain_channel_and_fine_tuning_controls() {
|
||||
let img = noisy(48, 48, 0.12, 11);
|
||||
let env = EffectEnv::default();
|
||||
let nr = ("noiseReductionSettings/noiseReduction", num(3.0));
|
||||
let base = run("ec.noise.removegrain", std::slice::from_ref(&nr), img.clone(), 0.0, env);
|
||||
// No red noise reduction leaves red as it was; green is still smoothed.
|
||||
let red_off = ("noiseReductionSettings/channelNoiseReduction/redNoiseReduction", num(0.0));
|
||||
let red_off = run("ec.noise.removegrain", &[nr.clone(), red_off], img.clone(), 0.0, env);
|
||||
assert!(red_off.data.iter().zip(&img.data).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6));
|
||||
assert!(var(&red_off, 1) < var(&img, 1) * 0.5);
|
||||
// More green reduction smooths green further.
|
||||
let green_more = ("noiseReductionSettings/channelNoiseReduction/greenNoiseReduction", num(3.0));
|
||||
let green_more = run("ec.noise.removegrain", &[nr.clone(), green_more], img.clone(), 0.0, env);
|
||||
assert!(var(&green_more, 1) < var(&base, 1));
|
||||
// Chroma Suppression takes colour noise out but keeps the luminance.
|
||||
let chroma = run("ec.noise.removegrain", &[nr.clone(), ("fineTuning/chromaSuppression", num(1.0))], img.clone(), 0.0, env);
|
||||
let chroma_var = |im: &Image| {
|
||||
let n = im.data.len() as f32;
|
||||
im.data.iter().map(|p| (p[0] - effectcraft_color::luminance(p[0], p[1], p[2])).powi(2)).sum::<f32>() / n
|
||||
};
|
||||
assert!(chroma_var(&chroma) < chroma_var(&base) * 0.8, "{} vs {}", chroma_var(&chroma), chroma_var(&base));
|
||||
// Noise Size Bias widens (or narrows) the filter.
|
||||
let wide = run("ec.noise.removegrain", &[nr.clone(), ("fineTuning/noiseSizeBias", num(1.0))], img.clone(), 0.0, env);
|
||||
let narrow = run("ec.noise.removegrain", &[nr.clone(), ("fineTuning/noiseSizeBias", num(-1.0))], img.clone(), 0.0, env);
|
||||
assert!(var(&wide, 1) < var(&base, 1) && var(&base, 1) < var(&narrow, 1));
|
||||
// Clean Solid Areas flattens the (flat, noisy) picture further.
|
||||
let clean = run("ec.noise.removegrain", &[nr, ("fineTuning/cleanSolidAreas", num(1.0))], img.clone(), 0.0, env);
|
||||
assert!(var(&clean, 1) < var(&base, 1));
|
||||
for out in [&red_off, &green_more, &chroma, &wide, &narrow, &clean] {
|
||||
assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()) && p[3] == 1.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_sampling_uses_the_noise_sample_points() {
|
||||
let img = noisy(64, 48, 0.1, 2);
|
||||
let mut params = Params { values: sampling_params(true).iter().map(|p| (p.id.to_string(), crate::default_value(p, [64.0, 48.0]))).collect() };
|
||||
params.values.insert("sampling/samplingProcess".into(), Value::Enum(1));
|
||||
params.values.insert("sampling/numberOfSamples".into(), num(3.0));
|
||||
params.values.insert(POINT_IDS[0].into(), Value::Vec2([10.0, 10.0]));
|
||||
// A point near the corner keeps its box inside the image.
|
||||
params.values.insert(POINT_IDS[2].into(), Value::Vec2([63.0, 47.0]));
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [64.0, 48.0], seed: 0, adjustment: false, env: Default::default() };
|
||||
let boxes = sampling_boxes(&ctx, &img, 1.0, [0.0, 0.0]);
|
||||
assert_eq!(boxes.len(), 3);
|
||||
assert_eq!(boxes[0], (6, 6, 9));
|
||||
assert_eq!(boxes[2], (55, 39, 9));
|
||||
// The buffer offset and scale place them in buffer pixels.
|
||||
assert_eq!(sampling_boxes(&ctx, &Image::filled(160, 120, [0.5, 0.5, 0.5, 1.0]), 2.0, [10.0, 4.0])[0], (21, 15, 18));
|
||||
// Transparent everywhere: no clean sample.
|
||||
assert!(sampling_boxes(&ctx, &Image::new(160, 120), 2.0, [10.0, 4.0]).is_empty());
|
||||
assert_eq!(sample_intensities(&ctx, &[0, 1, 2]), Some(vec![1.0; 3]));
|
||||
// A box whose surround reaches transparent pixels is left out; the others keep their
|
||||
// points (and so their Intensity).
|
||||
let mut holed = img.clone();
|
||||
holed.set(12, 3, [0.0; 4]);
|
||||
let kept: Vec<usize> = sampling(&ctx, &holed, 1.0, [0.0, 0.0]).into_iter().map(|(_, i)| i).collect();
|
||||
assert_eq!(kept, [1, 2]);
|
||||
// Automatic sampling ignores them.
|
||||
params.values.insert("sampling/samplingProcess".into(), Value::Enum(0));
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [64.0, 48.0], seed: 0, adjustment: false, env: Default::default() };
|
||||
assert_eq!(sampling_boxes(&ctx, &img, 1.0, [0.0, 0.0]), crate::noise::sample_boxes(&img, 3, 9));
|
||||
assert_eq!(sample_intensities(&ctx, &[0, 1, 2]), None);
|
||||
// Match Grain's per-point Intensity scales each sample's grain: all 0, no grain.
|
||||
let h = host(noisy(64, 48, 0.1, 3));
|
||||
let env = EffectEnv { host: Some(&h), ..Default::default() };
|
||||
let flat = Image::filled(64, 48, [0.5, 0.5, 0.5, 1.0]);
|
||||
let manual = [("noiseSourceLayer", Value::Layer(Some(7))), ("sampling/samplingProcess", Value::Enum(1))];
|
||||
let on = run("ec.noise.matchgrain", &manual, flat.clone(), 0.0, env);
|
||||
assert!(max_diff(&on, &flat) > 0.01);
|
||||
let zeros: Vec<(&str, Value)> = INTENSITY_IDS.iter().map(|id| (*id, num(0.0))).chain(manual.iter().cloned()).collect();
|
||||
assert!(max_diff(&run("ec.noise.matchgrain", &zeros, flat.clone(), 0.0, env), &flat) < 1e-6);
|
||||
let doubled: Vec<(&str, Value)> = INTENSITY_IDS.iter().map(|id| (*id, num(2.0))).chain(manual.iter().cloned()).collect();
|
||||
assert!(var(&run("ec.noise.matchgrain", &doubled, flat.clone(), 0.0, env), 0) > var(&on, 0) * 2.0);
|
||||
// Remove Grain's Noise Samples view shows where it samples.
|
||||
let rg = |process: u32| {
|
||||
let vals = [("sampling/samplingProcess", Value::Enum(process)), ("viewingMode", Value::Enum(1))];
|
||||
run("ec.noise.removegrain", &vals, flat.clone(), 0.0, EffectEnv::default())
|
||||
};
|
||||
assert_ne!(rg(1).data, rg(0).data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_frame_samples_another_frame() {
|
||||
let flat = Image::filled(48, 48, [0.5, 0.5, 0.5, 1.0]);
|
||||
let grainy = noisy(48, 48, 0.1, 4);
|
||||
// Match Grain on a source flat now and grainy at frame 0: sampling frame 0 at 1 s adds
|
||||
// grain; Source Frame −1 (the current frame) doesn't.
|
||||
let h = Host { layer: flat.clone(), own: None, other: Some(grainy.clone()) };
|
||||
let env = EffectEnv { host: Some(&h), frame_rate: 24.0, comp_time: 1.0, ..Default::default() };
|
||||
let src = ("noiseSourceLayer", Value::Layer(Some(7)));
|
||||
let at0 = run("ec.noise.matchgrain", std::slice::from_ref(&src), flat.clone(), 1.0, env);
|
||||
assert!(max_diff(&at0, &flat) > 0.01);
|
||||
let now = run("ec.noise.matchgrain", &[src.clone(), ("sampling/sourceFrame", num(-1.0))], flat.clone(), 1.0, env);
|
||||
assert!(max_diff(&now, &flat) < 1e-6);
|
||||
// At frame 0 itself, Source Frame 0 is the current frame.
|
||||
let same = run("ec.noise.matchgrain", &[src], flat.clone(), 0.0, env);
|
||||
assert!(max_diff(&same, &flat) < 1e-6);
|
||||
// Remove Grain measures the grain level of its own input at the Source Frame.
|
||||
let h = Host { layer: flat.clone(), own: Some(grainy), other: None };
|
||||
let level = |sf: f64| {
|
||||
let s = find("ec.noise.removegrain").unwrap();
|
||||
let mut params = Params { values: s.params.iter().map(|p| (p.id.to_string(), crate::default_value(p, [48.0, 48.0]))).collect() };
|
||||
params.values.insert("sampling/sourceFrame".into(), num(sf));
|
||||
let env = EffectEnv { host: Some(&h), frame_rate: 24.0, ..Default::default() };
|
||||
let ctx = EffectCtx { params: ¶ms, time: 1.0, layer_size: [48.0, 48.0], seed: 0, adjustment: false, env };
|
||||
crate::noise::remove_grain_level(&ctx, &Buf { img: flat.clone(), offset: [0.0; 2], scale: 1.0 })
|
||||
};
|
||||
assert!(level(0.0) > level(-1.0), "{} vs {}", level(0.0), level(-1.0));
|
||||
assert_eq!(level(24.0), level(-1.0), "frame 24 at 1 s is the current frame");
|
||||
}
|
||||
|
||||
/// Layer 7's Source is grainy at every time. Its masks hide all of it except at frame 0
|
||||
/// (comp time 0), where they reveal it: only when `masks_at` is set, else the host can't
|
||||
/// read masks at another time.
|
||||
struct MaskedHost {
|
||||
grainy: Image,
|
||||
hidden: Image,
|
||||
masks_at: bool,
|
||||
}
|
||||
impl MaskedHost {
|
||||
fn px(&self, img: &Image) -> LayerPixels {
|
||||
LayerPixels { buf: Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }, size: [48.0, 48.0] }
|
||||
}
|
||||
}
|
||||
impl EffectHost for MaskedHost {
|
||||
fn layer(&self, id: u64, _: bool) -> Option<LayerPixels> {
|
||||
(id == 7).then(|| self.px(&self.grainy))
|
||||
}
|
||||
fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
fn layer_masks(&self, id: u64) -> Option<LayerPixels> {
|
||||
(id == 7).then(|| self.px(&self.hidden))
|
||||
}
|
||||
fn layer_at(&self, id: u64, _: f64, _: bool) -> Option<LayerPixels> {
|
||||
self.layer(id, false)
|
||||
}
|
||||
fn layer_masks_at(&self, id: u64, comp_time: f64) -> Option<LayerPixels> {
|
||||
(self.masks_at && id == 7).then(|| self.px(if comp_time.abs() < 1e-9 { &self.grainy } else { &self.hidden }))
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Masks choice, a historical Source Frame reads the layer with its masks at that
|
||||
/// frame: grain the masks reveal only at frame 0 is matched when sampling frame 0, and
|
||||
/// neither the unmasked Source nor the current frame's masks are read instead.
|
||||
#[test]
|
||||
fn historical_masks_choice_samples_the_masked_layer_at_the_source_frame() {
|
||||
let flat = Image::filled(48, 48, [0.5, 0.5, 0.5, 1.0]);
|
||||
let src = ("noiseSourceLayer", Value::Layer(Some(7)));
|
||||
let run_at = |h: &MaskedHost, t: f64, choice: u32, frame: f64| {
|
||||
let env = EffectEnv { host: Some(h), frame_rate: 24.0, comp_time: t, ..Default::default() };
|
||||
let vals = [src.clone(), ("noiseSourceLayerSource", Value::Enum(choice)), ("sampling/sourceFrame", num(frame))];
|
||||
run("ec.noise.matchgrain", &vals, flat.clone(), t, env)
|
||||
};
|
||||
let h = MaskedHost { grainy: noisy(48, 48, 0.1, 4), hidden: Image::new(48, 48), masks_at: true };
|
||||
for t in [1.0, 1.5, 2.0] {
|
||||
// Frame 0's masks reveal the grain: it is matched.
|
||||
assert!(max_diff(&run_at(&h, t, 1, 0.0), &flat) > 0.01, "Masks at frame 0 from {t}s");
|
||||
// Frame 12's masks (comp time 0.5) hide it all: no grain, though the Source is grainy.
|
||||
assert!(max_diff(&run_at(&h, t, 1, 12.0), &flat) < 1e-6, "Masks at frame 12 from {t}s");
|
||||
// The current frame (−1) reads today's masks, which hide it.
|
||||
assert!(max_diff(&run_at(&h, t, 1, -1.0), &flat) < 1e-6, "Masks now at {t}s");
|
||||
// Source still reads the historical frame without masks.
|
||||
assert!(max_diff(&run_at(&h, t, 0, 12.0), &flat) > 0.01, "Source at {t}s");
|
||||
}
|
||||
// A host that can't render the masked layer at another time: the current frame's
|
||||
// masked read, as for every choice the host can't render.
|
||||
let h = MaskedHost { masks_at: false, ..h };
|
||||
assert!(max_diff(&run_at(&h, 1.0, 1, 0.0), &flat) < 1e-6);
|
||||
}
|
||||
|
||||
fn strip_new_controls(g: &mut PropGroup) {
|
||||
const GROUPS: [&str; 5] = ["blendWithOriginal", "channelBalance", "noiseSamplePoints", "intensity", "channelNoiseReduction"];
|
||||
const PROPS: [&str; 4] = ["sourceFrame", "chromaSuppression", "noiseSizeBias", "cleanSolidAreas"];
|
||||
g.children.retain(|c| match c {
|
||||
Node::Group(sg) => !GROUPS.contains(&sg.match_id.as_str()),
|
||||
Node::Prop(p) => !PROPS.contains(&p.match_id.as_str()),
|
||||
});
|
||||
for c in &mut g.children {
|
||||
if let Node::Group(sg) = c {
|
||||
strip_new_controls(sg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_leaf(g: &mut PropGroup, leaf: &str, v: &Value) {
|
||||
for c in &mut g.children {
|
||||
match c {
|
||||
Node::Prop(p) if p.match_id == leaf => p.value = v.clone(),
|
||||
Node::Group(sg) => set_leaf(sg, leaf, v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Old projects: an instance saved before #4368's controls gets them with defaults that
|
||||
/// render exactly as it did (Source Frame −1: the frame being rendered), and keeps its
|
||||
/// controls where they were.
|
||||
#[test]
|
||||
fn instances_saved_before_the_new_controls_render_unchanged() {
|
||||
let flat = Image::filled(40, 40, [0.45, 0.5, 0.55, 1.0]);
|
||||
let grainy = noisy(40, 40, 0.1, 6);
|
||||
// Layer 7 and the layer itself look different at other times: a Source Frame that
|
||||
// defaulted to 0 would change the render.
|
||||
let h = Host { layer: noisy(40, 40, 0.05, 8), own: Some(flat.clone()), other: Some(flat.clone()) };
|
||||
let env = EffectEnv { host: Some(&h), frame_rate: 24.0, comp_time: 1.0, ..Default::default() };
|
||||
for (id, leaf, v, img) in [
|
||||
("ec.noise.addgrain", "intensity", num(2.0), flat.clone()),
|
||||
("ec.noise.matchgrain", "noiseSourceLayer", Value::Layer(Some(7)), flat.clone()),
|
||||
("ec.noise.removegrain", "noiseReduction", num(3.0), grainy.clone()),
|
||||
] {
|
||||
let (spec, mut old) = new_instance(id);
|
||||
strip_new_controls(&mut old);
|
||||
set_leaf(&mut old, leaf, &v);
|
||||
let before = outline(&old);
|
||||
let mut upgraded = old.clone();
|
||||
let mut next = 10_000;
|
||||
assert!(upgrade_instance(spec, &mut upgraded, &mut Ids(&mut next), [40.0, 40.0]), "{id}");
|
||||
// Every control is there now, the old ones in their old order.
|
||||
let have = outline(&upgraded);
|
||||
assert_eq!(have.len(), outline(&new_instance(id).1).len(), "{id}");
|
||||
let mut rest = have.iter();
|
||||
assert!(before.iter().all(|l| rest.any(|h| h == l)), "{id}: old controls moved");
|
||||
let render = |g: &PropGroup| {
|
||||
let params = flatten_params(g, &mut |p| p.value.clone());
|
||||
let ctx = EffectCtx { params: ¶ms, time: 1.0, layer_size: [40.0, 40.0], seed: 1, adjustment: false, env };
|
||||
crate::apply(spec, &ctx, Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }).img
|
||||
};
|
||||
let (a, b) = (render(&old), render(&upgraded));
|
||||
assert!(max_diff(&a, &img) > 1e-3, "{id} did something");
|
||||
assert_eq!(a.data, b.data, "{id}");
|
||||
if spec.params.iter().any(|p| p.id == "sampling/sourceFrame") {
|
||||
let params = flatten_params(&upgraded, &mut |p| p.value.clone());
|
||||
assert_eq!(params.get("sampling/sourceFrame"), Some(&num(-1.0)), "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ pub mod fidelity;
|
||||
mod generate;
|
||||
mod generate2;
|
||||
mod generate3;
|
||||
mod grain_shared;
|
||||
mod keying;
|
||||
mod keying2;
|
||||
pub mod keylight;
|
||||
@@ -550,6 +551,11 @@ pub trait EffectHost: Sync {
|
||||
fn layer_at(&self, _id: u64, _comp_time: f64, _masks_and_effects: bool) -> Option<LayerPixels> {
|
||||
None
|
||||
}
|
||||
/// Layer `id` with its masks but none of its effects at comp time `comp_time` (seconds):
|
||||
/// [`EffectHost::layer_masks`] at another time. `None` when unavailable.
|
||||
fn layer_masks_at(&self, _id: u64, _comp_time: f64) -> Option<LayerPixels> {
|
||||
None
|
||||
}
|
||||
/// Auxiliary 3D channels (depth, object / material IDs, normals, Cryptomatte, any named
|
||||
/// EXR channel) of the effect's own layer source at the current time, in layer space (see
|
||||
/// [`AuxChannels`]). `None` when the source has none (the 3D Channel effects then pass the
|
||||
@@ -1025,6 +1031,14 @@ pub const PARAM_GROUPS: &[(&str, &str)] = &[
|
||||
("previewRegion", "Preview Region"),
|
||||
("sampling", "Sampling"),
|
||||
("temporalFiltering", "Temporal Filtering"),
|
||||
// Add / Match / Remove Grain (`grain_shared`).
|
||||
("channelBalance", "Channel Balance"),
|
||||
("noiseSamplePoints", "Noise Sample Points"),
|
||||
("intensity", "Intensity"),
|
||||
("channelNoiseReduction", "Channel Noise Reduction"),
|
||||
("blendWithOriginal", "Blend with Original"),
|
||||
("colorMatching", "Color Matching"),
|
||||
("maskingLayer", "Masking Layer"),
|
||||
// Time: Timewarp.
|
||||
("tuning", "Tuning"),
|
||||
("motionBlur", "Motion Blur"),
|
||||
|
||||
@@ -160,6 +160,8 @@ pub fn legacy_default(effect: &str, param: &str) -> Option<Value> {
|
||||
("ec.noise.turbulent", "evolutionOptions/turbulenceFactor") => Value::Scalar(0.0),
|
||||
("ec.noise.addgrain", "application/blendingMode") => Value::Enum(2),
|
||||
("ec.noise.removegrain", "noiseReductionSettings/mode") => Value::Enum(1),
|
||||
// Match / Remove Grain sampled the frame being rendered (Source Frame −1).
|
||||
("ec.noise.matchgrain" | "ec.noise.removegrain", "sampling/sourceFrame") => Value::Scalar(-1.0),
|
||||
// Audio: the Compressor's release was always manual.
|
||||
("ec.audio.compressor", "autoRelease") => Value::Bool(false),
|
||||
// Keying: Advanced Spill Suppressor's Ultra mode had no hue tolerance.
|
||||
|
||||
+137
-56
@@ -7,6 +7,7 @@ use effectcraft_raster::{Image, Px};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::generate::value_noise;
|
||||
use crate::grain_shared::sampling_boxes;
|
||||
use crate::util::{Plane, gauss_plane, guided_filter, hash1, join, lerp, premul, smoothstep, split, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
@@ -61,6 +62,9 @@ pub struct GrainLook {
|
||||
pub seed: u32,
|
||||
/// Color ▸ Red / Green / Blue Balance.
|
||||
pub balance: [f32; 3],
|
||||
/// Application ▸ Channel Balance: `[channel][shadows, midtones, highlights]` multipliers of
|
||||
/// the tonal weights.
|
||||
pub channel_balance: [[f32; 3]; 3],
|
||||
}
|
||||
|
||||
impl GrainLook {
|
||||
@@ -87,6 +91,7 @@ impl GrainLook {
|
||||
frame: if smooth && ft.fract() != 0.0 { ft as f32 } else { ft.floor() as f32 },
|
||||
seed: (pr.f("animation/randomSeed") as i64 as u32) ^ ctx.seed.wrapping_mul(0x9e37),
|
||||
balance: ch("color/", "redBalance", "greenBalance", "blueBalance"),
|
||||
channel_balance: crate::grain_shared::channel_balance(ctx),
|
||||
}
|
||||
.with_preset(pr.e("preset"))
|
||||
}
|
||||
@@ -133,13 +138,14 @@ impl GrainLook {
|
||||
planes
|
||||
}
|
||||
|
||||
/// Tonal weight of the grain at straight colour `c` (Shadows / Midtones / Highlights around
|
||||
/// the Midpoint).
|
||||
pub(crate) fn weight(&self, c: [f32; 3]) -> f32 {
|
||||
/// Tonal weight of the grain per channel at straight colour `c`: Shadows / Midtones /
|
||||
/// Highlights around the Midpoint, each scaled by the channel's Application ▸ Channel
|
||||
/// Balance (the same weight in every channel at the default balance of 1).
|
||||
pub(crate) fn weights(&self, c: [f32; 3]) -> [f32; 3] {
|
||||
let l = luminance(c[0], c[1], c[2]).clamp(0.0, 1.0);
|
||||
let s = 1.0 - smoothstep(0.0, self.midpoint, l);
|
||||
let hi = smoothstep(self.midpoint, 1.0, l);
|
||||
self.tones[0] * s + self.tones[1] * (1.0 - s - hi) + self.tones[2] * hi
|
||||
self.channel_balance.map(|cb| (self.tones[0] * cb[0]) * s + (self.tones[1] * cb[1]) * (1.0 - s - hi) + (self.tones[2] * cb[2]) * hi)
|
||||
}
|
||||
|
||||
/// Per-channel grain from the raw plane values `g` (Saturation, Tint).
|
||||
@@ -174,20 +180,21 @@ impl GrainLook {
|
||||
}
|
||||
|
||||
/// Grain control parameters shared by Add Grain and Match Grain, in Effect Controls order:
|
||||
/// (Tweaking, Color, Application, Animation).
|
||||
/// (Tweaking, Color, Application with its Channel Balance, Animation). Saved instances keep
|
||||
/// the order they were created with (properties are addressed by path, not position).
|
||||
pub(crate) fn grain_params() -> (Vec<crate::ParamSpec>, Vec<crate::ParamSpec>, Vec<crate::ParamSpec>, Vec<crate::ParamSpec>) {
|
||||
let mult = || slider(0.0, 10.0, 0.0, 2.0, 2);
|
||||
let tweaking = vec![
|
||||
p("tweaking/intensity", "Intensity", num(1.0), slider(0.0, 100.0, 0.0, 10.0, 2)),
|
||||
p("tweaking/size", "Size", num(1.0), slider(0.05, 100.0, 0.1, 10.0, 2)),
|
||||
p("tweaking/softness", "Softness", num(0.0), slider(0.0, 100.0, 0.0, 5.0, 2)),
|
||||
p("tweaking/aspectRatio", "Aspect Ratio", num(1.0), slider(0.05, 20.0, 0.25, 4.0, 2)),
|
||||
p("tweaking/channelIntensities/redIntensity", "Red Intensity", num(1.0), mult()),
|
||||
p("tweaking/channelIntensities/greenIntensity", "Green Intensity", num(1.0), mult()),
|
||||
p("tweaking/channelIntensities/blueIntensity", "Blue Intensity", num(1.0), mult()),
|
||||
p("tweaking/size", "Size", num(1.0), slider(0.05, 100.0, 0.1, 10.0, 2)),
|
||||
p("tweaking/channelSize/redSize", "Red Size", num(1.0), mult()),
|
||||
p("tweaking/channelSize/greenSize", "Green Size", num(1.0), mult()),
|
||||
p("tweaking/channelSize/blueSize", "Blue Size", num(1.0), mult()),
|
||||
p("tweaking/softness", "Softness", num(0.0), slider(0.0, 100.0, 0.0, 5.0, 2)),
|
||||
p("tweaking/aspectRatio", "Aspect Ratio", num(1.0), slider(0.05, 20.0, 0.25, 4.0, 2)),
|
||||
];
|
||||
let color = vec![
|
||||
p("color/monochromatic", "Monochromatic", Value::Bool(false), ParamUi::Checkbox),
|
||||
@@ -198,13 +205,14 @@ pub(crate) fn grain_params() -> (Vec<crate::ParamSpec>, Vec<crate::ParamSpec>, V
|
||||
p("color/greenBalance", "Green Balance", num(1.0), mult()),
|
||||
p("color/blueBalance", "Blue Balance", num(1.0), mult()),
|
||||
];
|
||||
let application = vec![
|
||||
let mut application = vec![
|
||||
p("application/blendingMode", "Blending Mode", Value::Enum(0), popup(&GRAIN_BLEND_MODES)),
|
||||
p("application/shadows", "Shadows", num(1.0), mult()),
|
||||
p("application/midtones", "Midtones", num(1.0), mult()),
|
||||
p("application/highlights", "Highlights", num(1.0), mult()),
|
||||
p("application/midpoint", "Midpoint", num(0.5), slider(0.0, 1.0, 0.0, 1.0, 2)),
|
||||
];
|
||||
application.extend(crate::grain_shared::channel_balance_params());
|
||||
let animation = vec![
|
||||
p("animation/animationSpeed", "Animation Speed", num(1.0), slider(0.0, 100.0, 0.0, 5.0, 2)),
|
||||
p("animation/animateSmoothly", "Animate Smoothly", Value::Bool(true), ParamUi::Checkbox),
|
||||
@@ -256,7 +264,7 @@ pub(crate) fn preview_compose(ctx: &EffectCtx, b: &mut Buf, orig: &Image) {
|
||||
|
||||
/// How far the grain statistics read around a sample box: their high-pass subtracts a Gaussian
|
||||
/// of sigma 1.5, three box passes of radius 1 (`noise2::grain_stats_boxes`).
|
||||
const SAMPLE_REACH: usize = 3;
|
||||
pub(crate) const SAMPLE_REACH: usize = 3;
|
||||
|
||||
/// Boxes (x, y, size in buffer px) where grain is sampled: the flattest of a grid of
|
||||
/// candidate boxes (real grain shows best where the picture has no detail). A box and the
|
||||
@@ -338,23 +346,30 @@ fn add_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let (w, h) = (b.img.width as usize, b.img.height as usize);
|
||||
let planes = look.planes(w, h, look.size * b.scale as f32, b.scale, 101);
|
||||
let amp = look.intensity * 0.25;
|
||||
// Blend with Original: how much of the original each pixel takes back.
|
||||
let back = crate::grain_shared::original_weight(ctx, &b, &orig);
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(*px);
|
||||
let weight = look.weight(c);
|
||||
let weight = look.weights(c);
|
||||
if view == 1 {
|
||||
// Blending Matte: where (and how strongly) the grain applies.
|
||||
let v = weight.clamp(0.0, 1.0);
|
||||
*px = [v, v, v, 1.0];
|
||||
// Blending Matte: where (and how strongly, per channel) the grain applies.
|
||||
let keep = 1.0 - back.as_ref().and_then(|k| k.data.get(i)).copied().unwrap_or(0.0);
|
||||
let v = weight.map(|w| w.clamp(0.0, 1.0) * keep);
|
||||
*px = [v[0], v[1], v[2], 1.0];
|
||||
return;
|
||||
}
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let raw = if look.mono { [planes[0].data[i]; 3] } else { [planes[0].data[i], planes[1].data[i], planes[2].data[i]] };
|
||||
let at = |k: usize| planes.get(k).and_then(|pl| pl.data.get(i)).copied().unwrap_or(0.0);
|
||||
let raw = if look.mono { [at(0); 3] } else { [at(0), at(1), at(2)] };
|
||||
let g = look.color(raw);
|
||||
let o = [0, 1, 2].map(|k| look.blend(c[k], g[k] * amp * look.channel_intensity[k] * weight));
|
||||
let o = [0, 1, 2].map(|k| look.blend(c[k], g[k] * amp * look.channel_intensity[k] * weight[k]));
|
||||
*px = premul(o, a);
|
||||
});
|
||||
if view != 1 {
|
||||
crate::grain_shared::blend_back(&mut b, &orig, back.as_ref());
|
||||
}
|
||||
if view == 0 {
|
||||
preview_compose(ctx, &mut b, &orig);
|
||||
}
|
||||
@@ -493,24 +508,6 @@ fn dust_scratches(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
/// Remove Grain's Viewing Mode options.
|
||||
pub(crate) const REMOVE_GRAIN_VIEWS: [&str; 4] = ["Preview", "Noise Samples", "Blending Matte", "Final Output"];
|
||||
|
||||
/// Grain sampling controls (Match Grain, Remove Grain): how many flat boxes of what size the
|
||||
/// grain is measured in.
|
||||
pub(crate) fn sampling_params() -> Vec<crate::ParamSpec> {
|
||||
vec![
|
||||
p("sampling/samplingProcess", "Sampling Process", Value::Enum(0), popup(&["Automatic"])),
|
||||
p("sampling/numberOfSamples", "Number of Samples", num(80.0), slider(1.0, 500.0, 1.0, 200.0, 0)),
|
||||
p("sampling/sampleSize", "Sample Size", num(9.0), slider(3.0, 64.0, 3.0, 32.0, 0)),
|
||||
p("sampling/sampleBoxColor", "Sample Box Color", crate::col(1.0, 1.0, 0.0), ParamUi::Color),
|
||||
]
|
||||
}
|
||||
|
||||
/// The sample boxes for the effect's Sampling settings.
|
||||
pub(crate) fn sampling_boxes(ctx: &EffectCtx, img: &Image, scale: f64) -> Vec<(usize, usize, usize)> {
|
||||
let n = ctx.params.get("sampling/numberOfSamples").map(Value::as_f64).unwrap_or(80.0).clamp(1.0, 500.0) as usize;
|
||||
let s = (ctx.params.get("sampling/sampleSize").map(Value::as_f64).unwrap_or(9.0) * scale).round().max(3.0) as usize;
|
||||
sample_boxes(img, n, s)
|
||||
}
|
||||
|
||||
/// The grain level (0.5..2) measured in the sample boxes of `img`.
|
||||
fn grain_level(img: &Image, boxes: &[(usize, usize, usize)]) -> f32 {
|
||||
let st = crate::noise2::grain_stats_boxes(img, boxes);
|
||||
@@ -519,9 +516,52 @@ fn grain_level(img: &Image, boxes: &[(usize, usize, usize)]) -> f32 {
|
||||
}
|
||||
|
||||
/// Remove Grain's measured grain level for buffer `b` without Temporal Filtering (the GPU
|
||||
/// kernels' spatial pass, effectcraft-gpu `fx_noise`).
|
||||
/// kernels' spatial pass, effectcraft-gpu `fx_noise`), sampled at Sampling ▸ Source Frame.
|
||||
pub fn remove_grain_level(ctx: &EffectCtx, b: &Buf) -> f32 {
|
||||
grain_level(&b.img, &sampling_boxes(ctx, &b.img, b.scale))
|
||||
let other = crate::grain_shared::own_sample_frame(ctx, b);
|
||||
let img = other.as_ref().unwrap_or(&b.img);
|
||||
grain_level(img, &sampling_boxes(ctx, img, b.scale, b.offset))
|
||||
}
|
||||
|
||||
/// Remove Grain's Channel Noise Reduction multipliers (1 for projects saved before them).
|
||||
const CHANNEL_NOISE_REDUCTION: [&str; 3] = [
|
||||
"noiseReductionSettings/channelNoiseReduction/redNoiseReduction",
|
||||
"noiseReductionSettings/channelNoiseReduction/greenNoiseReduction",
|
||||
"noiseReductionSettings/channelNoiseReduction/blueNoiseReduction",
|
||||
];
|
||||
|
||||
/// Fine Tuning ▸ Chroma Suppression: smooth the colour-difference planes (each channel minus
|
||||
/// the luminance) of `ch` by `amount` (0..5; above 1 the blur widens), luminance kept.
|
||||
fn suppress_chroma(ch: &mut [Plane; 4], amount: f32, r: usize) {
|
||||
if amount <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let y = ch[0].zip_map(&ch[1], |r, g| r * 0.2126 + g * 0.7152).zip_map(&ch[2], |rg, b| rg + b * 0.0722);
|
||||
let sigma = r as f64 * (1.0 + amount.max(1.0) as f64);
|
||||
let t = amount.min(1.0);
|
||||
for c in ch.iter_mut().take(3) {
|
||||
let diff = c.zip_map(&y, |v, l| v - l);
|
||||
let smooth = gauss_plane(&diff, sigma, sigma);
|
||||
let mixed = diff.zip_map(&smooth, |d, s| d + (s - d) * t);
|
||||
*c = y.zip_map(&mixed, |l, d| l + d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fine Tuning ▸ Clean Solid Areas: pull flat regions (little local deviation from a wide
|
||||
/// blur) further towards that blur, by `amount` (0..1).
|
||||
fn clean_solid_areas(ch: &mut [Plane; 4], amount: f32, r: usize) {
|
||||
if amount <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let sigma = (3 * r) as f64;
|
||||
let t = amount.min(1.0);
|
||||
for c in ch.iter_mut().take(3) {
|
||||
let wide = gauss_plane(c, sigma, sigma);
|
||||
let dev = gauss_plane(&c.zip_map(&wide, |v, l| (v - l).abs()), sigma, sigma);
|
||||
let pulled = c.zip_map(&wide, |v, l| l - v);
|
||||
let flat = dev.zip_map(&pulled, |d, toward| toward * (1.0 - smoothstep(0.0, 0.03, d)) * t);
|
||||
*c = c.zip_map(&flat, |v, k| v + k);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
@@ -529,14 +569,25 @@ fn remove_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let amt = pr.f("noiseReductionSettings/noiseReduction") as f32;
|
||||
let um_amount = pr.f("unsharpMask/amount") as f32 / 100.0;
|
||||
let view = pr.get("viewingMode").map(|v| v.as_enum()).unwrap_or(3);
|
||||
let boxes = sampling_boxes(ctx, &b.img, b.scale);
|
||||
// Sampling ▸ Source Frame: the frame the grain is measured in (`None`: this one).
|
||||
let sample = crate::grain_shared::own_sample_frame(ctx, &b);
|
||||
let boxes = sampling_boxes(ctx, sample.as_ref().unwrap_or(&b.img), b.scale, b.offset);
|
||||
if view == 1 {
|
||||
let c = pr.get("sampling/sampleBoxColor").map(|v| v.as_color()).unwrap_or([1.0, 1.0, 0.0, 1.0]);
|
||||
if let Some(img) = sample {
|
||||
b.img = img;
|
||||
}
|
||||
draw_boxes(&mut b.img, &boxes, c);
|
||||
return b;
|
||||
}
|
||||
if view == 2 {
|
||||
b.img.data.iter_mut().for_each(|p| *p = [1.0, 1.0, 1.0, 1.0]);
|
||||
// Blending Matte: where the noise reduction applies (white), less where Blend with
|
||||
// Original brings the original back.
|
||||
let back = crate::grain_shared::original_weight(ctx, &b, &b.img);
|
||||
b.img.data.iter_mut().enumerate().for_each(|(i, p)| {
|
||||
let v = 1.0 - back.as_ref().and_then(|k| k.data.get(i)).copied().unwrap_or(0.0);
|
||||
*p = [v, v, v, 1.0];
|
||||
});
|
||||
return b;
|
||||
}
|
||||
let temporal = pr.b("temporalFiltering/enabled");
|
||||
@@ -575,19 +626,24 @@ fn remove_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
});
|
||||
}
|
||||
if amt <= 0.0 && um_amount <= 0.0 {
|
||||
if view == 0 {
|
||||
preview_compose(ctx, &mut b, &before);
|
||||
}
|
||||
finish_remove_grain(ctx, &mut b, &before, view);
|
||||
return b;
|
||||
}
|
||||
}
|
||||
// The grain level measured in the sample boxes scales the smoothing.
|
||||
let level = grain_level(&b.img, &boxes);
|
||||
// The grain level measured in the sample boxes scales the smoothing. A fixed Source Frame
|
||||
// that is this frame is measured before Temporal Filtering, as it is from other frames
|
||||
// (`self_at` gives the effect's input); Source Frame −1 (older projects) after it.
|
||||
let fixed_now = crate::grain_shared::fixed_source_frame(ctx).then_some(&before);
|
||||
let level = grain_level(sample.as_ref().or(fixed_now).unwrap_or(&b.img), &boxes);
|
||||
let passes = pr.f("noiseReductionSettings/passes").round().clamp(1.0, 8.0) as usize;
|
||||
let multichannel = pr.e("noiseReductionSettings/mode") == 0;
|
||||
let texture = (pr.f("fineTuning/texture") as f32).clamp(0.0, 1.0);
|
||||
let r = (2.0 * b.scale).round().max(1.0) as usize;
|
||||
let eps = (0.02 * amt * level).powi(2);
|
||||
let fine = |id: &str, d: f64| pr.get(id).map(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(d);
|
||||
// Fine Tuning ▸ Noise Size Bias: −1..1 halves..doubles the filter radius.
|
||||
let bias = fine("fineTuning/noiseSizeBias", 0.0).clamp(-1.0, 1.0);
|
||||
let r = (2.0 * b.scale * bias.exp2()).round().clamp(1.0, 4096.0) as usize;
|
||||
// Channel Noise Reduction scales each channel's smoothing.
|
||||
let eps = CHANNEL_NOISE_REDUCTION.map(|id| (0.02 * amt * level * fine(id, 1.0).max(0.0) as f32).powi(2));
|
||||
let orig = split(&b.img);
|
||||
let mut ch = orig.clone();
|
||||
if amt > 0.0 {
|
||||
@@ -598,13 +654,19 @@ fn remove_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let (w, h) = (ch[0].w, ch[0].h);
|
||||
Plane { w, h, data: (0..w * h).map(|i| luminance(ch[0].data[i], ch[1].data[i], ch[2].data[i])).collect() }
|
||||
});
|
||||
for c in ch.iter_mut().take(3) {
|
||||
for (c, &e) in ch.iter_mut().take(3).zip(eps.iter()) {
|
||||
// A channel with no noise reduction is left as it is.
|
||||
if e <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
*c = match &guide {
|
||||
Some(g) => guided_filter(g, c, r, eps),
|
||||
None => guided_filter(c, c, r, eps),
|
||||
Some(g) => guided_filter(g, c, r, e),
|
||||
None => guided_filter(c, c, r, e),
|
||||
};
|
||||
}
|
||||
}
|
||||
suppress_chroma(&mut ch, fine("fineTuning/chromaSuppression", 0.0).max(0.0) as f32, r);
|
||||
clean_solid_areas(&mut ch, fine("fineTuning/cleanSolidAreas", 0.0).max(0.0) as f32, r);
|
||||
// Texture: let some of the removed fine detail back through.
|
||||
if texture > 0.0 {
|
||||
for k in 0..3 {
|
||||
@@ -630,12 +692,19 @@ fn remove_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
p[3] = a;
|
||||
});
|
||||
b.img = out;
|
||||
if view == 0 {
|
||||
preview_compose(ctx, &mut b, &before);
|
||||
}
|
||||
finish_remove_grain(ctx, &mut b, &before, view);
|
||||
b
|
||||
}
|
||||
|
||||
/// Remove Grain's last steps: Blend with Original, then the Preview Region (Preview mode).
|
||||
fn finish_remove_grain(ctx: &EffectCtx, b: &mut Buf, before: &Image, view: u32) {
|
||||
let back = crate::grain_shared::original_weight(ctx, b, before);
|
||||
crate::grain_shared::blend_back(b, before, back.as_ref());
|
||||
if view == 0 {
|
||||
preview_compose(ctx, b, before);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Noise Alpha / Noise HLS ----
|
||||
|
||||
/// Per-pixel noise in 0..1 that changes smoothly with `phase` (whole units = new pattern).
|
||||
@@ -783,7 +852,12 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
let (tweaking, color, application, animation) = grain_params();
|
||||
let head =
|
||||
vec![p("viewingMode", "Viewing Mode", Value::Enum(2), popup(&ADD_GRAIN_VIEWS)), p("preset", "Preset", Value::Enum(0), popup(&GRAIN_PRESETS))];
|
||||
spec("ec.noise.addgrain", "Add Grain", [head, preview_params(), tweaking, color, application, animation].into_iter().flatten().collect(), add_grain)
|
||||
spec(
|
||||
"ec.noise.addgrain",
|
||||
"Add Grain",
|
||||
[head, preview_params(), tweaking, color, application, animation, crate::grain_shared::blend_params()].into_iter().flatten().collect(),
|
||||
add_grain,
|
||||
)
|
||||
},
|
||||
spec(
|
||||
"ec.noise.median",
|
||||
@@ -814,15 +888,22 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("noiseReductionSettings/noiseReduction", "Noise Reduction", num(1.0), slider(0.0, 5.0, 0.0, 5.0, 2)),
|
||||
p("noiseReductionSettings/passes", "Passes", num(1.0), slider(1.0, 8.0, 1.0, 4.0, 0)),
|
||||
p("noiseReductionSettings/mode", "Mode", Value::Enum(0), popup(&["Multichannel", "Single Channel"])),
|
||||
p(CHANNEL_NOISE_REDUCTION[0], "Red Noise Reduction", num(1.0), slider(0.0, 5.0, 0.0, 2.0, 2)),
|
||||
p(CHANNEL_NOISE_REDUCTION[1], "Green Noise Reduction", num(1.0), slider(0.0, 5.0, 0.0, 2.0, 2)),
|
||||
p(CHANNEL_NOISE_REDUCTION[2], "Blue Noise Reduction", num(1.0), slider(0.0, 5.0, 0.0, 2.0, 2)),
|
||||
p("fineTuning/chromaSuppression", "Chroma Suppression", num(0.0), slider(0.0, 5.0, 0.0, 2.0, 2)),
|
||||
p("fineTuning/texture", "Texture", num(0.0), slider(0.0, 1.0, 0.0, 1.0, 2)),
|
||||
p("unsharpMask/amount", "Amount", num(0.0), slider(0.0, 500.0, 0.0, 200.0, 1)),
|
||||
p("unsharpMask/radius", "Radius", num(1.0), slider(0.1, 100.0, 0.1, 10.0, 1)),
|
||||
p("unsharpMask/threshold", "Threshold", num(0.0), slider(0.0, 255.0, 0.0, 255.0, 0)),
|
||||
p("fineTuning/noiseSizeBias", "Noise Size Bias", num(0.0), slider(-1.0, 1.0, -1.0, 1.0, 2)),
|
||||
p("fineTuning/cleanSolidAreas", "Clean Solid Areas", num(0.0), slider(0.0, 1.0, 0.0, 1.0, 2)),
|
||||
p("temporalFiltering/enabled", "Enabled", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("temporalFiltering/amount", "Amount", num(100.0), pct()),
|
||||
p("temporalFiltering/motionSensitivity", "Motion Sensitivity", num(0.5), slider(0.0, 1.0, 0.0, 1.0, 2)),
|
||||
p("unsharpMask/amount", "Amount", num(0.0), slider(0.0, 500.0, 0.0, 200.0, 1)),
|
||||
p("unsharpMask/radius", "Radius", num(1.0), slider(0.1, 100.0, 0.1, 10.0, 1)),
|
||||
p("unsharpMask/threshold", "Threshold", num(0.0), slider(0.0, 255.0, 0.0, 255.0, 0)),
|
||||
],
|
||||
sampling_params(),
|
||||
crate::grain_shared::sampling_params(false),
|
||||
crate::grain_shared::blend_params(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
|
||||
@@ -7,7 +7,10 @@ use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::noise::{GrainLook, draw_boxes, fbm, grain_params, median_image, preview_params, sampling_boxes, sampling_params};
|
||||
use crate::grain_shared::{
|
||||
blend_back, blend_params, layer_sample_frame, original_weight, own_sample_frame, sample_intensities, sampling, sampling_boxes, sampling_params,
|
||||
};
|
||||
use crate::noise::{GrainLook, draw_boxes, fbm, grain_params, median_image, preview_params};
|
||||
use crate::util::{Plane, gauss_plane, layer_or_self, premul, unpremul};
|
||||
use crate::{Buf, EffectCtx, EffectSpec, num, p, popup, slider};
|
||||
|
||||
@@ -180,12 +183,21 @@ fn match_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
}
|
||||
// MATCH_GRAIN_VIEWS order.
|
||||
let view = ctx.params.e("viewingMode");
|
||||
let source = layer_or_self(ctx, &b, "noiseSourceLayer", false, false);
|
||||
let src_boxes = sampling_boxes(ctx, &source, b.scale);
|
||||
// Sampling ▸ Source Frame: the source (and, for the compensation, this layer) is sampled
|
||||
// at that frame; the current one when it is this frame or can't be rendered.
|
||||
let source = layer_sample_frame(ctx, &b, "noiseSourceLayer").unwrap_or_else(|| layer_or_self(ctx, &b, "noiseSourceLayer", false, false));
|
||||
let (src_boxes, src_points): (Vec<_>, Vec<_>) = sampling(ctx, &source, b.scale, b.offset).into_iter().unzip();
|
||||
let box_col = ctx.params.get("sampling/sampleBoxColor").map(|v| v.as_color()).unwrap_or([1.0, 1.0, 0.0, 1.0]);
|
||||
let own_img = || own_sample_frame(ctx, &b).unwrap_or_else(|| b.img.clone());
|
||||
if view == 1 || view == 2 {
|
||||
// Noise Samples (on the source) / Compensation Samples (on this layer).
|
||||
let (mut img, boxes) = if view == 1 { (source, src_boxes) } else { (b.img.clone(), sampling_boxes(ctx, &b.img, b.scale)) };
|
||||
let (mut img, boxes) = if view == 1 {
|
||||
(source, src_boxes)
|
||||
} else {
|
||||
let img = own_img();
|
||||
let boxes = sampling_boxes(ctx, &img, b.scale, b.offset);
|
||||
(img, boxes)
|
||||
};
|
||||
draw_boxes(&mut img, &boxes, box_col);
|
||||
b.img = img;
|
||||
return b;
|
||||
@@ -193,12 +205,26 @@ fn match_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
// No box with an opaque surround (a small layer inside transparent pixels) means no clean
|
||||
// sample: no grain to match, as After Effects applies none when its samples hold transparent
|
||||
// areas. The whole-image fallback of `grain_stats_boxes` would measure the edge again.
|
||||
let clean_stats = |img: &Image, boxes: &[(usize, usize, usize)]| if boxes.is_empty() { GrainStats::default() } else { grain_stats_boxes(img, boxes) };
|
||||
let src_stats = clean_stats(&source, &src_boxes);
|
||||
let clean_stats = |img: &Image, boxes: &[(usize, usize, usize)], points: &[usize]| {
|
||||
if boxes.is_empty() {
|
||||
return GrainStats::default();
|
||||
}
|
||||
match sample_intensities(ctx, points) {
|
||||
Some(weights) => weighted_stats(img, boxes, &weights),
|
||||
None => grain_stats_boxes(img, boxes),
|
||||
}
|
||||
};
|
||||
let src_stats = clean_stats(&source, &src_boxes, &src_points);
|
||||
let comp = (ctx.params.f("compensateForExistingNoise") / 100.0) as f32;
|
||||
// The own-layer boxes only matter for the compensation term; skip them when it is off.
|
||||
let own = if comp > 0.0 { clean_stats(&b.img, &sampling_boxes(ctx, &b.img, b.scale)) } else { GrainStats::default() };
|
||||
let orig = (view == 0).then(|| b.img.clone());
|
||||
let own = if comp > 0.0 {
|
||||
let img = own_img();
|
||||
let (boxes, points): (Vec<_>, Vec<_>) = sampling(ctx, &img, b.scale, b.offset).into_iter().unzip();
|
||||
clean_stats(&img, &boxes, &points)
|
||||
} else {
|
||||
GrainStats::default()
|
||||
};
|
||||
let orig = b.img.clone();
|
||||
let look = GrainLook::from_params(ctx);
|
||||
let amp: [f32; 3] = [0, 1, 2].map(|k| {
|
||||
let s = src_stats.std[k];
|
||||
@@ -216,28 +242,59 @@ fn match_grain(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let k = if var > 1e-12 { 1.0 / var.sqrt() } else { 0.0 };
|
||||
*pl = pl.map(|v| ((v as f64 - mean) * k) as f32);
|
||||
}
|
||||
// Blend with Original: how much of the original each pixel takes back.
|
||||
let back = original_weight(ctx, &b, &orig);
|
||||
b.img.data.par_iter_mut().enumerate().for_each(|(i, px)| {
|
||||
let (c, a) = unpremul(*px);
|
||||
let raw = if look.mono { [planes[0].data[i]; 3] } else { [planes[0].data[i], planes[1].data[i], planes[2].data[i]] };
|
||||
let at = |k: usize| planes.get(k).and_then(|pl| pl.data.get(i)).copied().unwrap_or(0.0);
|
||||
let raw = if look.mono { [at(0); 3] } else { [at(0), at(1), at(2)] };
|
||||
let g = look.color(raw);
|
||||
let weight = look.weight(c);
|
||||
let weight = look.weights(c);
|
||||
match view {
|
||||
3 => *px = [weight.clamp(0.0, 1.0), weight.clamp(0.0, 1.0), weight.clamp(0.0, 1.0), 1.0],
|
||||
3 => {
|
||||
let keep = 1.0 - back.as_ref().and_then(|k| k.data.get(i)).copied().unwrap_or(0.0);
|
||||
let v = weight.map(|w| w.clamp(0.0, 1.0) * keep);
|
||||
*px = [v[0], v[1], v[2], 1.0];
|
||||
}
|
||||
_ => {
|
||||
if a <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let o = [0, 1, 2].map(|k| look.blend(c[k], g[k] * amp[k] * weight));
|
||||
let o = [0, 1, 2].map(|k| look.blend(c[k], g[k] * amp[k] * weight[k]));
|
||||
*px = premul(o, a);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(orig) = &orig {
|
||||
crate::noise::preview_compose(ctx, &mut b, orig);
|
||||
if view != 3 {
|
||||
blend_back(&mut b, &orig, back.as_ref());
|
||||
}
|
||||
if view == 0 {
|
||||
crate::noise::preview_compose(ctx, &mut b, &orig);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Grain statistics of manually placed sample boxes, each box's grain strength scaled by its
|
||||
/// Sampling ▸ Intensity (`weights`, one per box): the RMS of the scaled per-box deviations,
|
||||
/// and the intensity-weighted mean grain size.
|
||||
fn weighted_stats(img: &Image, boxes: &[(usize, usize, usize)], weights: &[f32]) -> GrainStats {
|
||||
let mut sq = [0.0f32; 3];
|
||||
let (mut size, mut wsum, mut n) = (0.0f32, 0.0f32, 0.0f32);
|
||||
for (bx, &wt) in boxes.iter().zip(weights.iter()) {
|
||||
let st = grain_stats_boxes(img, std::slice::from_ref(bx));
|
||||
for k in 0..3 {
|
||||
sq[k] += (st.std[k] * wt).powi(2);
|
||||
}
|
||||
size += st.size * wt;
|
||||
wsum += wt;
|
||||
n += 1.0;
|
||||
}
|
||||
if n <= 0.0 {
|
||||
return GrainStats::default();
|
||||
}
|
||||
GrainStats { std: sq.map(|v| (v / n).sqrt()), size: if wsum > 0.0 { size / wsum } else { 0.6 } }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Median (Legacy)
|
||||
|
||||
fn median_legacy(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
@@ -338,10 +395,11 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p("viewingMode", "Viewing Mode", Value::Enum(4), popup(&MATCH_GRAIN_VIEWS)),
|
||||
p("noiseSourceLayer", "Noise Source Layer", Value::Layer(None), ParamUi::Layer),
|
||||
p("noiseSourceLayerSource", "Noise Source Layer Source", Value::Enum(0), ParamUi::Hidden),
|
||||
p("compensateForExistingNoise", "Compensate for Existing Noise", num(0.0), pct()),
|
||||
]
|
||||
.into_iter()
|
||||
.chain([preview_params(), sampling_params(), tweaking, color, application, animation].into_iter().flatten())
|
||||
.chain(preview_params())
|
||||
.chain([p("compensateForExistingNoise", "Compensate for Existing Noise", num(0.0), pct())])
|
||||
.chain([tweaking, color, application, sampling_params(true), animation, blend_params()].into_iter().flatten())
|
||||
.collect(),
|
||||
match_grain,
|
||||
),
|
||||
|
||||
@@ -60,6 +60,16 @@ const SLIDERS_0_24: &[(&str, &str, [f64; 4], u8)] = &[
|
||||
("ec.blur.gaussian", "blurriness", [0.0, 3000.0, 0.0, 50.0], 1),
|
||||
];
|
||||
|
||||
/// Popup options as 0.22–0.24 gave them, for popups that have gained options since, as (effect,
|
||||
/// parameter path, options). Like [`SLIDERS_0_24`]: opening a project replaces an instance's
|
||||
/// options with the current ones, so [`effect_text`] puts these back.
|
||||
#[rustfmt::skip]
|
||||
const POPUPS_0_24: &[(&str, &str, &[&str])] = &[
|
||||
// #4368: Sampling Process gained Manual.
|
||||
("ec.noise.matchgrain", "sampling/samplingProcess", &["Automatic"]),
|
||||
("ec.noise.removegrain", "sampling/samplingProcess", &["Automatic"]),
|
||||
];
|
||||
|
||||
/// Parameters effects gained after 0.24.1, as (effect, parameter path, the value the parameter
|
||||
/// takes in a project those releases saved). Those releases hashed each effect without them, and
|
||||
/// opening such a project adds them, so [`effect_text`] leaves one out while it still holds that
|
||||
@@ -139,6 +149,97 @@ const ADDED_SINCE_0_24: &[(&str, &str, Added)] = &[
|
||||
("ec.transition.cardwipe", "positionJitter/zJitterSpeed", Added::SameAs("positionJitter/jitterSpeed")),
|
||||
("ec.transition.cardwipe", "rotationJitter/yRotJitterSpeed", Added::SameAs("rotationJitter/rotJitterSpeed")),
|
||||
("ec.transition.cardwipe", "rotationJitter/zRotJitterSpeed", Added::SameAs("rotationJitter/rotJitterSpeed")),
|
||||
// #4368: Add / Match / Remove Grain's missing controls. Source Frame was the frame being
|
||||
// rendered (−1).
|
||||
("ec.noise.addgrain", "application/channelBalance/redShadows", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/redMidtones", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/redHighlights", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/greenShadows", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/greenMidtones", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/greenHighlights", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/blueShadows", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/blueMidtones", Added::Default),
|
||||
("ec.noise.addgrain", "application/channelBalance/blueHighlights", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/amount", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/combineMatchAndMaskUsing", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/blurMatte", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/colorMatching/matchColorUsing", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/colorMatching/matchingColor", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/colorMatching/matchingTolerance", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/colorMatching/matchingSoftness", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/colorMatching/invertMatch", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/maskingLayer/maskLayer", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/maskingLayer/maskingMode", Added::Default),
|
||||
("ec.noise.addgrain", "blendWithOriginal/maskingLayer/ifMaskSizeDiffers", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/sourceFrame", Added::Legacy),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point1", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point2", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point3", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point4", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point5", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point6", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point7", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point8", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point9", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/noiseSamplePoints/point10", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity1", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity2", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity3", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity4", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity5", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity6", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity7", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity8", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity9", Added::Default),
|
||||
("ec.noise.matchgrain", "sampling/intensity/intensity10", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/redShadows", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/redMidtones", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/redHighlights", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/greenShadows", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/greenMidtones", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/greenHighlights", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/blueShadows", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/blueMidtones", Added::Default),
|
||||
("ec.noise.matchgrain", "application/channelBalance/blueHighlights", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/amount", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/combineMatchAndMaskUsing", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/blurMatte", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/colorMatching/matchColorUsing", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/colorMatching/matchingColor", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/colorMatching/matchingTolerance", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/colorMatching/matchingSoftness", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/colorMatching/invertMatch", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/maskingLayer/maskLayer", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/maskingLayer/maskingMode", Added::Default),
|
||||
("ec.noise.matchgrain", "blendWithOriginal/maskingLayer/ifMaskSizeDiffers", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/sourceFrame", Added::Legacy),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point1", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point2", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point3", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point4", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point5", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point6", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point7", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point8", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point9", Added::Default),
|
||||
("ec.noise.removegrain", "sampling/noiseSamplePoints/point10", Added::Default),
|
||||
("ec.noise.removegrain", "noiseReductionSettings/channelNoiseReduction/redNoiseReduction", Added::Default),
|
||||
("ec.noise.removegrain", "noiseReductionSettings/channelNoiseReduction/greenNoiseReduction", Added::Default),
|
||||
("ec.noise.removegrain", "noiseReductionSettings/channelNoiseReduction/blueNoiseReduction", Added::Default),
|
||||
("ec.noise.removegrain", "fineTuning/chromaSuppression", Added::Default),
|
||||
("ec.noise.removegrain", "fineTuning/noiseSizeBias", Added::Default),
|
||||
("ec.noise.removegrain", "fineTuning/cleanSolidAreas", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/amount", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/combineMatchAndMaskUsing", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/blurMatte", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/colorMatching/matchColorUsing", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/colorMatching/matchingColor", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/colorMatching/matchingTolerance", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/colorMatching/matchingSoftness", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/colorMatching/invertMatch", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/maskingLayer/maskLayer", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/maskingLayer/maskingMode", Added::Default),
|
||||
("ec.noise.removegrain", "blendWithOriginal/maskingLayer/ifMaskSizeDiffers", Added::Default),
|
||||
];
|
||||
|
||||
/// The value an [`ADDED_SINCE_0_24`] parameter takes in a project saved before it existed.
|
||||
@@ -146,6 +247,9 @@ const ADDED_SINCE_0_24: &[(&str, &str, Added)] = &[
|
||||
enum Added {
|
||||
/// The parameter's default.
|
||||
Default,
|
||||
/// The value opening an old project gives it in place of the default
|
||||
/// ([`effectcraft_effects::migrate::legacy_default`]).
|
||||
Legacy,
|
||||
/// A copy of the parameter at this path (the one it was split from): its value, keyframes
|
||||
/// and expression.
|
||||
SameAs(&'static str),
|
||||
@@ -159,7 +263,8 @@ pub(crate) fn effect_text(g: &PropGroup, layer_size: [f64; 2]) -> String {
|
||||
let GroupKind::Effect { effect } = &g.kind else { return format!("{g:?}") };
|
||||
let mut rows = SLIDERS_0_24.iter().filter(|r| r.0 == effect).peekable();
|
||||
let mut added = ADDED_SINCE_0_24.iter().filter(|r| r.0 == effect).peekable();
|
||||
if rows.peek().is_none() && added.peek().is_none() {
|
||||
let mut popups = POPUPS_0_24.iter().filter(|r| r.0 == effect).peekable();
|
||||
if rows.peek().is_none() && added.peek().is_none() && popups.peek().is_none() {
|
||||
return format!("{g:?}");
|
||||
}
|
||||
let mut g = g.clone();
|
||||
@@ -168,6 +273,11 @@ pub(crate) fn effect_text(g: &PropGroup, layer_size: [f64; 2]) -> String {
|
||||
p.ui = ParamUi::Slider { min, max, slider_min, slider_max, decimals };
|
||||
}
|
||||
}
|
||||
for &(_, path, options) in popups {
|
||||
if let Some(p) = g.prop_mut(path).filter(|p| matches!(p.ui, ParamUi::Popup { .. })) {
|
||||
p.ui = ParamUi::Popup { options: options.iter().map(|o| o.to_string()).collect() };
|
||||
}
|
||||
}
|
||||
let spec = effectcraft_effects::find(effect);
|
||||
let mut left_out = false;
|
||||
for &(_, path, was) in added {
|
||||
@@ -178,6 +288,10 @@ pub(crate) fn effect_text(g: &PropGroup, layer_size: [f64; 2]) -> String {
|
||||
};
|
||||
g.prop(path).is_some_and(|p| unanimated(p) && same_value(&p.value, &old))
|
||||
}
|
||||
Added::Legacy => {
|
||||
let Some(old) = effectcraft_effects::migrate::legacy_default(effect, path) else { continue };
|
||||
g.prop(path).is_some_and(|p| unanimated(p) && same_value(&p.value, &old))
|
||||
}
|
||||
// Copied from the parameter it was split from, keyframes and expression included.
|
||||
Added::SameAs(from) => match (g.prop(path), g.prop(from)) {
|
||||
(Some(p), Some(f)) => p.value == f.value && p.keys == f.keys && p.expr == f.expr,
|
||||
@@ -355,6 +469,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every popup row names a popup its effect has.
|
||||
#[test]
|
||||
fn popups_0_24_rows_name_real_popups() {
|
||||
for &(effect, path, _) in POPUPS_0_24 {
|
||||
let spec = effectcraft_effects::find(effect).unwrap_or_else(|| panic!("{effect}"));
|
||||
assert!(spec.params.iter().any(|ps| ps.id == path && matches!(ps.ui, ParamUi::Popup { .. })), "{effect}: {path}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The grain effects with every added parameter at the value an old project gets (Source
|
||||
/// Frame −1): the legacy text leaves them all out, the twirl-downs of only new parameters
|
||||
/// and the Mask Layer's source choice included, and gives Sampling Process its 0.24 options.
|
||||
#[test]
|
||||
fn grain_added_parameters_at_their_old_value_are_left_out() {
|
||||
let size = [320.0, 180.0];
|
||||
for effect in ["ec.noise.addgrain", "ec.noise.matchgrain", "ec.noise.removegrain"] {
|
||||
let mut g = instance(effect, size);
|
||||
if let Some(p) = g.prop_mut("sampling/sourceFrame") {
|
||||
p.value = Value::Scalar(-1.0);
|
||||
}
|
||||
let text = effect_text(&g, size);
|
||||
let spec = effectcraft_effects::find(effect).unwrap();
|
||||
let leaf = |path: &'static str| path.rsplit('/').next().unwrap_or(path);
|
||||
for &(_, path, _) in ADDED_SINCE_0_24.iter().filter(|r| r.0 == effect) {
|
||||
// Not a leaf an older parameter shares (Remove Grain's Unsharp Mask ▸ Amount).
|
||||
if spec.params.iter().any(|ps| ps.id != path && leaf(ps.id) == leaf(path)) {
|
||||
continue;
|
||||
}
|
||||
assert!(!text.contains(&format!("match_id: {:?}", leaf(path))), "{effect}: {path} kept");
|
||||
}
|
||||
// (Sampling ▸ Intensity shares its match id with Add Grain's Tweaking ▸ Intensity.)
|
||||
for group in ["blendWithOriginal", "channelBalance", "noiseSamplePoints", "channelNoiseReduction"] {
|
||||
assert!(!text.contains(&format!("match_id: {group:?}")), "{effect}: {group} kept");
|
||||
}
|
||||
assert!(!text.contains("maskLayerSource"), "{effect}: the Mask Layer's source choice is left out too");
|
||||
assert!(!text.contains("\"Manual\""), "{effect}: Sampling Process has its 0.24 options");
|
||||
}
|
||||
}
|
||||
|
||||
/// A new instance holds every added parameter at the value an old project gets, so the legacy
|
||||
/// text leaves them all out, groups of only new parameters (Paint Beads' Light) included.
|
||||
#[test]
|
||||
@@ -401,5 +554,25 @@ mod tests {
|
||||
assert!(!effect_text(&wipe, size).contains("yJitterSpeed"));
|
||||
wipe.prop_mut("positionJitter/yJitterSpeed").unwrap().keys.clear();
|
||||
assert!(effect_text(&wipe, size).contains("yJitterSpeed"), "a different animation is kept");
|
||||
let old = |effect: &str| {
|
||||
let mut g = instance(effect, size);
|
||||
if let Some(p) = g.prop_mut("sampling/sourceFrame") {
|
||||
p.value = Value::Scalar(-1.0);
|
||||
}
|
||||
g
|
||||
};
|
||||
// Source Frame 0 (a new instance's default) samples another frame than −1 did.
|
||||
let mut g = old("ec.noise.matchgrain");
|
||||
g.prop_mut("sampling/sourceFrame").unwrap().value = Value::Scalar(0.0);
|
||||
assert!(effect_text(&g, size).contains("sourceFrame"));
|
||||
let mut g = old("ec.noise.addgrain");
|
||||
g.prop_mut("application/channelBalance/redShadows").unwrap().value = Value::Scalar(2.0);
|
||||
let text = effect_text(&g, size);
|
||||
assert!(text.contains("redShadows") && !text.contains("greenShadows"), "{text}");
|
||||
let mut g = old("ec.noise.removegrain");
|
||||
g.prop_mut("sampling/noiseSamplePoints/point3").unwrap().value = Value::Vec2([1.0, 2.0]);
|
||||
g.prop_mut("blendWithOriginal/amount").unwrap().keys = vec![effectcraft_project::Keyframe::new(Default::default(), Value::Scalar(0.0))];
|
||||
let text = effect_text(&g, size);
|
||||
assert!(text.contains("point3") && text.contains("blendWithOriginal") && !text.contains("point4"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
|
||||
use effectcraft_effects::roto::{FROZEN, INPUT_KEY};
|
||||
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{GroupKind, ItemId, LayerId, ParamUi, Project};
|
||||
use effectcraft_project::{GroupKind, ItemId, LayerId, Node, ParamUi, Project, PropGroup};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
@@ -106,6 +106,116 @@ fn legacy_roto_keys_hash_the_0_24_blurriness_range() {
|
||||
assert_eq!(crate::analysis::frames_key::legacy::effect_text(blur, [0.0; 2]), format!("{as_0_24:?}"));
|
||||
}
|
||||
|
||||
/// Add Grain, Match Grain and Remove Grain as EffectCraft wrote them before #4368 gave them
|
||||
/// After Effects' missing controls (their shape is unchanged since 0.24.1).
|
||||
const GRAIN_0_24: &str = include_str!("fixtures/grain-0.24.json");
|
||||
|
||||
/// [`ANALYSED_0_24`] with the three grain effects of [`GRAIN_0_24`] above its Roto Brush, and
|
||||
/// the Roto Brush Input Key 0.24 computed for that stack: its hash of the frames' signature, the
|
||||
/// masks and the `Debug` text of each effect above, as the grain effects were before they
|
||||
/// gained their controls.
|
||||
fn grain_above_the_brush_0_24() -> String {
|
||||
use crate::analysis::frames_key::legacy;
|
||||
let mut v: serde_json::Value = serde_json::from_str(ANALYSED_0_24).unwrap();
|
||||
let grain: Vec<serde_json::Value> = serde_json::from_str(GRAIN_0_24).unwrap();
|
||||
let max_uid = |g: &serde_json::Value| {
|
||||
g.to_string().split("\"uid\":").skip(1).filter_map(|s| s.split(|c: char| !c.is_ascii_digit()).next()?.parse::<u64>().ok()).max()
|
||||
};
|
||||
let next = grain.iter().filter_map(max_uid).max().unwrap() + 1;
|
||||
let layer = &mut v["items"]["2"]["kind"]["layers"][0];
|
||||
let effects = layer["props"]["children"].as_array_mut().unwrap().iter_mut().find(|c| c["match"] == "effects").unwrap();
|
||||
let list = effects["children"].as_array_mut().unwrap();
|
||||
let at = list.iter().position(|g| g["uid"] == ROTO).unwrap();
|
||||
for (i, g) in grain.into_iter().enumerate() {
|
||||
list.insert(at + i, g);
|
||||
}
|
||||
v["next_id"] = next.into();
|
||||
// The grain effects as saved, not yet brought up to date (that happens when it is opened).
|
||||
let saved = Project::from_json(&v.to_string()).unwrap();
|
||||
let saved_layer = saved.comp(COMP).unwrap().layer(CLIP).unwrap();
|
||||
let is_grain = |g: &&PropGroup| matches!(&g.kind, GroupKind::Effect { effect } if effect.starts_with("ec.noise.") && effect.ends_with("grain"));
|
||||
let grain: Vec<PropGroup> = saved_layer.effects().unwrap().groups().filter(is_grain).cloned().collect();
|
||||
assert_eq!(grain.len(), 3);
|
||||
// The rest of the stack as 0.24 hashed it: the opened fixture, whose key the legacy text
|
||||
// reproduces (see `analyses_saved_by_0_24_survive_edits_that_keep_their_frames`), with the
|
||||
// signature that gives that key. The fixture's 3D Camera Tracker holds a stand-in Solve that
|
||||
// 0.24 didn't have when it made the key; the first edit clears it (the solve is checked
|
||||
// with the tracks), so the key is reproduced from the project as an edit leaves it.
|
||||
let mut s = open(ANALYSED_0_24);
|
||||
add_to_render_queue(&mut s);
|
||||
let c = s.project.comp(COMP).unwrap();
|
||||
let layer = c.layer(CLIP).unwrap();
|
||||
let size = crate::roto::layer_size(&s.project, c, layer);
|
||||
let sigs = legacy::signatures(&s.project, COMP, layer);
|
||||
let sig = sigs.into_iter().find(|sig| legacy::input_key_of(sig.clone(), layer, ROTO, size) == ROTO_INPUT_0_24).expect("0.24's key is reproduced");
|
||||
// 0.24 hashed the grain effects' plain `Debug`: the legacy text of an instance as it was
|
||||
// then has nothing to put back.
|
||||
for g in &grain {
|
||||
assert_eq!(legacy::effect_text(g, size), format!("{g:?}"), "{}", g.name);
|
||||
}
|
||||
let mut stack = layer.clone();
|
||||
let effects = stack.props.sub_mut("effects").unwrap();
|
||||
let at = effects.children.iter().position(|n| matches!(n, Node::Group(g) if g.uid == ROTO)).unwrap();
|
||||
for (i, g) in grain.into_iter().enumerate() {
|
||||
effects.children.insert(at + i, Node::Group(g));
|
||||
}
|
||||
let key = legacy::input_key_of(sig, &stack, ROTO, size);
|
||||
assert_ne!(key, ROTO_INPUT_0_24);
|
||||
let fx = &mut v["items"]["2"]["kind"]["layers"][0]["props"]["children"];
|
||||
let roto = fx.as_array_mut().unwrap().iter_mut().find(|c| c["match"] == "effects").unwrap()["children"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.iter_mut()
|
||||
.find(|g| g["uid"] == ROTO)
|
||||
.unwrap();
|
||||
let input = roto["children"].as_array_mut().unwrap().iter_mut().find(|c| c["match"] == INPUT_KEY).unwrap();
|
||||
input["value"]["v"] = key.into();
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// #4368 gave the grain effects new controls. Opening an old project adds them (at values that
|
||||
/// render as before) and refreshes Sampling Process's options, so the instance's `Debug` text
|
||||
/// changes: the Roto Brush's analysis below them is kept all the same, through save and reopen,
|
||||
/// and a changed control above it still clears it.
|
||||
#[test]
|
||||
fn legacy_roto_keys_survive_the_grain_controls_added_above_them() {
|
||||
let old = grain_above_the_brush_0_24();
|
||||
let mut s = open(&old);
|
||||
let before = saved(&s);
|
||||
assert_eq!(before[2].0, "saved frozen");
|
||||
// Opening it changed the grain effects' text: the plain 0.24 hash wouldn't match any more.
|
||||
let unopened = Project::from_json(&old).unwrap();
|
||||
let grain = |p: &Project| -> Vec<String> {
|
||||
let fx = p.comp(COMP).unwrap().layer(CLIP).unwrap().effects().unwrap();
|
||||
fx.groups().filter(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect.contains("grain"))).map(|g| format!("{g:?}")).collect()
|
||||
};
|
||||
assert_eq!(grain(&unopened).len(), 3);
|
||||
assert!(grain(&unopened).iter().zip(grain(&s.project)).all(|(a, b)| *a != b));
|
||||
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before);
|
||||
let mut s = open(&s.project.to_json());
|
||||
add_to_render_queue(&mut s);
|
||||
assert_eq!(saved(&s), before, "saved and reopened");
|
||||
|
||||
// A changed control above the brush, old or new, clears its analysis; undo brings it back.
|
||||
for (path, value) in [
|
||||
("effects/#4/tweaking/intensity", json!(2.0)),
|
||||
("effects/#4/application/channelBalance/redShadows", json!(2.0)),
|
||||
("effects/#5/sampling/sourceFrame", json!(0)),
|
||||
("effects/#5/blendWithOriginal/amount", json!(50)),
|
||||
("effects/#6/fineTuning/chromaSuppression", json!(1.0)),
|
||||
("effects/#6/sampling/samplingProcess", json!(1)),
|
||||
] {
|
||||
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": path, "value": value})).unwrap();
|
||||
let after = saved(&s);
|
||||
assert_eq!(after[2].0, "", "{path}");
|
||||
assert_ne!(after[2].1, before[2].1, "{path}");
|
||||
s.execute_checked("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before, "{path} undone");
|
||||
}
|
||||
}
|
||||
|
||||
/// The text keys are made from today, written field by field (#3536). It changes only when this
|
||||
/// test is changed with it: a new field of a type it writes doesn't compile until it is decided
|
||||
/// in `analysis::frames_key`, and renaming a field or variant doesn't change it.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
asset: grain-0.24.json
|
||||
title: Add Grain, Match Grain and Remove Grain instances as EffectCraft wrote them before #4368
|
||||
author: barchukmov
|
||||
source: original work
|
||||
license: MIT OR Apache-2.0
|
||||
license-file: ../../../../../LICENSE-MIT
|
||||
added: 2026-12-03 by barchukmov
|
||||
notes: Written by effectcraft_effects::instantiate at commit a11548f9 (the grain effects' parameters are unchanged there since 0.24.1) for a 160x120 layer, uids from 1000, as compact JSON effect nodes. Used to check that Roto Brush keys saved with grain above the brush survive the controls #4368 adds.
|
||||
@@ -168,6 +168,17 @@ impl EffectHost for FxHost<'_, '_, '_> {
|
||||
self.pixels(other, (*sub.layer_input(&ctx, other, 0)?).clone(), false)
|
||||
})
|
||||
}
|
||||
|
||||
fn layer_masks_at(&self, id: u64, comp_time: f64) -> Option<LayerPixels> {
|
||||
let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
|
||||
if !comp_time.is_finite() || self.r.depth > MAX_FX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let ctx = self.ctx.at(Tick::from_seconds_f64(comp_time));
|
||||
let sub = self.r.nested();
|
||||
// Source and masks without effects, as `layer_masks`: a self-reference can't recurse.
|
||||
Some(self.pixels(other, (*sub.layer_input(&ctx, other, 0)?).clone(), false))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameter `id` (a flattened id: match ids joined by `/`) of effect `effect_index` in
|
||||
|
||||
@@ -1514,6 +1514,39 @@ fn timed_source_reads_preserve_other_layer_masks() {
|
||||
assert_eq!(timed.buf.img.get(150, 50)[3], 0.0);
|
||||
}
|
||||
|
||||
/// A layer parameter's Masks choice at another time (Match Grain's Source Frame): the layer
|
||||
/// with its masks as they are at that time, without its effects.
|
||||
#[test]
|
||||
fn layer_masks_at_reads_the_masks_of_that_time() {
|
||||
use effectcraft_effects::EffectHost;
|
||||
let (mut p, cid, comp) = setup();
|
||||
let mut owner = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100);
|
||||
let mut other = solid(&mut p, &comp, [0.0, 1.0, 0.0], 200, 100);
|
||||
add_effect_200(&mut p, &mut other, "ec.channel.invert", &[]);
|
||||
let mut next = p.next_id;
|
||||
let mut mask = build::mask(&mut Ids(&mut next), "Left", ShapePath::rect([50.0, 50.0], 80.0, 80.0), MaskMode::Add, [255, 255, 0]);
|
||||
p.next_id = next;
|
||||
// Fully open at 0 s, closed at 1 s.
|
||||
let key = |t: f64, v: f64| Keyframe::new(Tick::from_seconds_f64(t), Value::Scalar(v));
|
||||
mask.get_mut("opacity").unwrap().keys = vec![key(0.0, 100.0), key(1.0, 0.0)];
|
||||
other.props.sub_mut("masks").unwrap().children.push(mask.clone().into());
|
||||
owner.props.sub_mut("masks").unwrap().children.push(mask.into());
|
||||
p.comp_mut(cid).unwrap().layers = vec![owner.clone(), other.clone()].into();
|
||||
let ctx = crate::EvalCtx::new(&p, cid, p.comp(cid).unwrap(), Tick::from_seconds_f64(0.5));
|
||||
let renderer = crate::Renderer::new(&p, &crate::NoFootage, crate::RenderOpts::default());
|
||||
let host = crate::FxHost { r: &renderer, ctx: &ctx, layer: &owner, origin: [0.0; 2], index: Default::default(), original: None };
|
||||
for id in [other.id.0, owner.id.0] {
|
||||
let open = host.layer_masks_at(id, 0.0).unwrap().buf.img;
|
||||
assert_eq!(open.get(50, 50)[3], 1.0, "inside the mask at 0 s");
|
||||
assert_eq!(open.get(150, 50)[3], 0.0, "outside the mask");
|
||||
assert_eq!(host.layer_masks_at(id, 1.0).unwrap().buf.img.get(50, 50)[3], 0.0, "closed at 1 s");
|
||||
assert!(host.layer_masks_at(id, f64::NAN).is_none());
|
||||
}
|
||||
// No effects: the other layer's Invert isn't applied.
|
||||
assert_eq!(host.layer_masks_at(other.id.0, 0.0).unwrap().buf.img.get(50, 50), [0.0, 1.0, 0.0, 1.0]);
|
||||
assert!(host.layer_masks_at(999, 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_dependencies_remain_cacheable_and_invalidate_only_related_edits() {
|
||||
let (mut p, cid, comp) = setup();
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@
|
||||
<!-- Generated from the effect registry (crates/effects/src/catalog.rs); do not edit by hand.
|
||||
Regenerate: UPDATE_DOCS=1 cargo test -p effectcraft-effects --lib effects_doc_is_current -->
|
||||
|
||||
EffectCraft ships 308 effects with 3124 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
|
||||
EffectCraft ships 308 effects with 3213 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
|
||||
|
||||
- **GPU**: 280 effects also run on the GPU compositor with identical results.
|
||||
- **32**: 308 effects process 32-bit float (HDR, overbright) pixels without clamping.
|
||||
@@ -266,18 +266,18 @@ Effects are addressed by id (`ec.<category>.<name>`) or display name in commands
|
||||
|
||||
| Effect | Id | Params | GPU | 32 | Status |
|
||||
|---|---|---:|:-:|:-:|---|
|
||||
| Add Grain | `ec.noise.addgrain` | 32 | GPU | 32 | Implemented |
|
||||
| Add Grain | `ec.noise.addgrain` | 52 | GPU | 32 | Implemented |
|
||||
| Curl Noise | `ec.noise.curlnoise` | 10 | GPU | 32 | Implemented |
|
||||
| Dust & Scratches | `ec.noise.dustscratches` | 3 | GPU | 32 | Implemented |
|
||||
| Fractal Noise | `ec.noise.fractal` | 26 | GPU | 32 | Implemented |
|
||||
| Match Grain | `ec.noise.matchgrain` | 37 | | 32 | Implemented |
|
||||
| Match Grain | `ec.noise.matchgrain` | 78 | | 32 | Implemented |
|
||||
| Median | `ec.noise.median` | 2 | GPU | 32 | Implemented |
|
||||
| Median (Legacy) | `ec.noise.medianlegacy` | 2 | GPU | 32 | Implemented |
|
||||
| Noise | `ec.noise.noise` | 3 | GPU | 32 | Implemented |
|
||||
| Noise Alpha | `ec.noise.noisealpha` | 8 | GPU | 32 | Implemented |
|
||||
| Noise HLS | `ec.noise.noisehls` | 6 | GPU | 32 | Implemented |
|
||||
| Noise HLS Auto | `ec.noise.noisehlsauto` | 6 | GPU | 32 | Implemented |
|
||||
| Remove Grain | `ec.noise.removegrain` | 20 | GPU | 32 | Implemented |
|
||||
| Remove Grain | `ec.noise.removegrain` | 48 | GPU | 32 | Implemented |
|
||||
| Turbulent Noise | `ec.noise.turbulent` | 22 | GPU | 32 | Implemented |
|
||||
|
||||
## Obsolete
|
||||
|
||||
Reference in New Issue
Block a user