Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4138,7 +4138,7 @@ impl DocumentMessageHandler {
})
.unwrap_or((None, None, None));

let blend_mode_menu_entries = BlendMode::list_svg_subset()
let blend_mode_menu_entries = BlendMode::list()
.iter()
.map(|modes| {
modes
Expand All @@ -4155,7 +4155,7 @@ impl DocumentMessageHandler {

let widgets = vec![
DropdownInput::new(blend_mode_menu_entries)
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
.disabled(disabled)
.draw_icon(false)
.sizing(WidgetSizing::default().grow(false))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1337,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
return LayoutGroup::row(vec![]);
};
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
let entries = BlendMode::list_svg_subset()
let entries = BlendMode::list()
.iter()
.map(|category| {
category
Expand All @@ -1354,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout

widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries)
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
]);
}
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
Expand Down
99 changes: 77 additions & 22 deletions node-graph/libraries/core-types/src/blending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,31 +72,32 @@ impl BlendMode {
]
}

/// The subset of [`BlendMode::list()`] that is supported by SVG.
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
pub fn index_in_list(&self) -> Option<usize> {
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
}

/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
/// The alpha-only utility modes, hidden from the list, draw layers normally.
pub fn reads_backdrop(&self) -> bool {
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
}

/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
pub fn strength_moves_toward_neutral(&self) -> bool {
use BlendMode::*;
[
// Normal group
&[Normal],
// Darken group
&[Darken, Multiply, ColorBurn],
// Lighten group
&[Lighten, Screen, ColorDodge],
// Contrast group
&[Overlay, SoftLight, HardLight],
// Inversion group
&[Difference, Exclusion],
// Component group
&[Hue, Saturation, Color, Luminosity],
]
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
}

pub fn index_in_list(&self) -> Option<usize> {
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
self.strength_moves_toward_neutral()
}

pub fn index_in_list_svg_subset(&self) -> Option<usize> {
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
}

/// Convert the enum to the CSS string for the blend mode.
Expand Down Expand Up @@ -130,11 +131,14 @@ impl BlendMode {
}

/// Renders the blend mode CSS style declaration.
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
pub fn render(&self) -> String {
format!(
r#" mix-blend-mode: {};"#,
self.to_svg_style_name().unwrap_or_else(|| {
log::warn!("Unsupported blend mode {self:?}");
if !self.reads_backdrop() {
log::warn!("Unsupported blend mode {self:?}");
}
"normal"
})
)
Expand All @@ -156,7 +160,7 @@ impl Display for BlendMode {
BlendMode::Lighten => write!(f, "Lighten"),
BlendMode::Screen => write!(f, "Screen"),
BlendMode::ColorDodge => write!(f, "Color Dodge"),
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
BlendMode::LighterColor => write!(f, "Lighter Color"),
// Contrast group
BlendMode::Overlay => write!(f, "Overlay"),
Expand Down Expand Up @@ -247,6 +251,30 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
}
}

/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
}

/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
let toward = |neutral: f32| {
let moved = |channel: f32| neutral + strength * (channel - neutral);
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
};

match blend_mode {
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
_ => apply_blend_mode(foreground, background, blend_mode),
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -375,6 +403,33 @@ mod tests {
}
}

#[test]
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();

// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));

// The modes whose strength fades their blend take the paint as it is
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());

// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
assert_eq!(reading.len(), 10);
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
assert!(!BlendMode::Erase.reads_backdrop());

// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
}
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
}

#[test]
fn source_over_weights_straight_colors_by_alpha() {
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
Expand Down
89 changes: 61 additions & 28 deletions node-graph/libraries/graphic-types/src/effect_layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,14 @@ pub struct EffectLayers {

impl EffectLayers {
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
let operations: Vec<EffectOperation> = effects.operations().collect();
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
blend_mode
} else {
BlendMode::Normal
};

// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
Expand Down Expand Up @@ -226,9 +230,20 @@ impl EffectLayers {
planned
}

/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content.
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
pub fn reads_backdrop(&self) -> bool {
self.fades_by_underlying || self.reads_around_backdrop()
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
}

/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
let Some(content_layer) = self.content_layer() else { return false };
let blend_mode = self.layers[content_layer].blend_mode;

let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
}

/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
Expand Down Expand Up @@ -298,20 +313,30 @@ impl EffectLayers {
}
}

/// Whether any of the effects reads what lies beneath the content, like a background blur.
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
pub fn effects_read_backdrop(effects: &Effects) -> bool {
effects.operations().any(|operation| match &operation {
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
_ => false,
_ => {
!operation.changes_nothing()
&& pieces(0, &operation)
.iter()
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
}
})
}

/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
_ if blend_mode.to_svg_style_name().is_some() => true,
PiecePlace::Beneath => blend_mode.reads_backdrop(),
PiecePlace::Within => blend_into_content,
_ => false,
};
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
}

Expand Down Expand Up @@ -562,9 +587,11 @@ mod tests {
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);

// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
Expand Down Expand Up @@ -647,14 +674,11 @@ mod tests {
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);

// One flattened for a mode CSS lacks covers it too
let mut flattened_shadow = with_knockout(false);
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
*blend_mode = BlendMode::LinearBurn;
}
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 1);
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
// One flattened before an interior piece in a mode CSS lacks covers it too
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2);
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
}

#[test]
Expand Down Expand Up @@ -761,9 +785,14 @@ mod tests {
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
let unmerged = Effects::from_operations([
drop_shadow(RED, BlendMode::Multiply),
inner_shadow(RED, BlendMode::LinearBurn),
drop_shadow(RED, BlendMode::Multiply),
mask(),
]);
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
}

#[test]
Expand All @@ -780,19 +809,23 @@ mod tests {
assert_eq!(layers.flattened, 2);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);

let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2);
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
assert!(layers.reads_backdrop());

// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
assert_eq!(layers.flattened, 2);
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 3);
assert_eq!(modes(&layers), [BlendMode::Normal]);

// Clipped content flattens everything
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
assert_eq!(layers.flattened, 2);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
assert_eq!(layers.flattened, 3);
assert_eq!(parts(&layers), [[None]]);
}

Expand Down
Loading
Loading