New node: 'Blend If' (#5065)

Add Blend If, hiding content by its own tones and those beneath it
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-03 04:03:46 -08:00
1 parent c8e8fbf8d1
commit e30bf2e987
31 files changed
+4121 -233

No files matched your search

@@ -551,6 +551,7 @@ tagged_value! {
WarpStyle(graphic_types::WarpStyle),
WaveType(graphic_types::WaveType),
DisplaceMode(graphic_types::DisplaceMode),
BlendIfChannel(graphic_types::BlendIfChannel),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -29,7 +29,7 @@ use graphene_std::vector::misc::{
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
use node_registry_macros::async_node;
use std::collections::HashMap;
@@ -303,6 +303,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
WarpStyle,
WaveType,
DisplaceMode,
BlendIfChannel,
Stroke,
ScaleType,
ReferencePoint,
@@ -0,0 +1,361 @@
//! Blend If, shaped for PSD interop as its blending ranges: the content shows only where its own colors, and the colors of what lies beneath it, fall within a range of each channel's levels.
//! The content's own range fades it like its fill does, leaving the shadows and glows cast from it as they are, and the range beneath fades everything the content draws like its opacity does.
use crate::effect_layers::is_pixel_filter;
use crate::effects::EffectOperation;
use crate::parameters::ParameterVisitor;
use core_types::graphene_hash::CacheHash;
use dyn_any::DynAny;
/// For PSD interop, the gray channel weighs the levels of the gamma-encoded red, green, and blue channels by these percentages.
pub const GRAY_PERCENTAGES: [usize; 3] = [30, 59, 11];
/// How many levels each renderer reads a channel at before weighing it, the 8 bits browsers filter with, so every renderer cuts off the same pixels.
pub const CHANNEL_LEVELS: usize = 256;
/// How near a cutoff a channel may lie, as a fraction of its full scale, and still count as reaching it: a quarter of a level, so a cutoff given in percent lands on the level it names.
const CUTOFF_TOLERANCE: f64 = 1. / 1024.;
/// Which channel of the colors a Blend If range reads.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum BlendIfChannel {
/// The lightness of the colors, weighing red, green, and blue by 30%, 59%, and 11%.
#[default]
Gray,
Red,
Green,
Blue,
}
/// A range of one channel's levels, in percent, which shows the content fully from its range start to its end and fades it out linearly to nothing at its falloff start and end.
/// A falloff that meets its end of the range is a sharp cutoff, which shows the content at the level it lies on.
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub struct BlendRange {
pub falloff_start: f64,
pub range_start: f64,
pub range_end: f64,
pub falloff_end: f64,
}
impl Default for BlendRange {
fn default() -> Self {
Self {
falloff_start: 0.,
range_start: 0.,
range_end: 100.,
falloff_end: 100.,
}
}
}
impl BlendRange {
/// How strongly the content shows where the channel is `value`, from 0 to 1.
pub fn weight(&self, value: f64) -> f64 {
let value = value * 100.;
let tolerance = CUTOFF_TOLERANCE * 100.;
// Each side rises (or falls) across its falloff, with its ends taken in either order
let side = |falloff: f64, range: f64, rising: bool| {
let (low, high) = (falloff.min(range), falloff.max(range));
match (high - low > tolerance, rising) {
(true, true) => ((value - low) / (high - low)).clamp(0., 1.),
(true, false) => ((high - value) / (high - low)).clamp(0., 1.),
(false, true) => f64::from(value >= low - tolerance),
(false, false) => f64::from(value <= high + tolerance),
}
};
side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false)
}
/// Whether the range shows every level fully, so it changes nothing.
pub fn shows_everything(&self) -> bool {
// Rising then falling, it's full everywhere once it's full at both ends
self.weight(0.) >= 1. && self.weight(1.) >= 1.
}
/// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white.
pub fn level_weights(&self) -> Vec<f64> {
(0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect()
}
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
let key = |parameter: &str| format!("{group}_{parameter}");
visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.);
visitor.parameter(&key("range_start"), &mut self.range_start, 0.);
visitor.parameter(&key("range_end"), &mut self.range_end, 100.);
visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.);
}
}
/// The ranges each channel's levels must fall within for the content to show, which multiply.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct ChannelRanges {
pub gray: BlendRange,
pub red: BlendRange,
pub green: BlendRange,
pub blue: BlendRange,
}
impl ChannelRanges {
/// Each channel with its range, in the order the GPU takes them.
pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] {
[
(BlendIfChannel::Gray, &self.gray),
(BlendIfChannel::Red, &self.red),
(BlendIfChannel::Green, &self.green),
(BlendIfChannel::Blue, &self.blue),
]
}
/// The channels with ranges that hide some levels.
pub fn limiting(&self) -> impl Iterator<Item = (BlendIfChannel, &BlendRange)> {
self.channels().into_iter().filter(|(_, range)| !range.shows_everything())
}
/// Whether every channel's range shows every level fully, so they change nothing.
pub fn show_everything(&self) -> bool {
self.limiting().next().is_none()
}
/// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level.
pub fn weight(&self, color: [f64; 3]) -> f64 {
self.channel_weights(color).into_iter().product()
}
/// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`].
pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] {
let levels = color.map(channel_level);
let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64;
let [red, green, blue] = levels.map(value);
[self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)]
}
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) {
self.gray.visit_parameters(visitor, side);
self.red.visit_parameters(visitor, &format!("red_{side}"));
self.green.visit_parameters(visitor, &format!("green_{side}"));
self.blue.visit_parameters(visitor, &format!("blue_{side}"));
}
}
/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them.
pub fn channel_level(value: f64) -> usize {
((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1)
}
/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer.
pub fn gray_level(levels: [usize; 3]) -> usize {
let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum();
(weighed + 50) / 100
}
/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct BlendIfRanges {
pub content: ChannelRanges,
pub underlying: ChannelRanges,
}
impl BlendIfRanges {
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
self.content.visit_parameters(visitor, "content");
self.underlying.visit_parameters(visitor, "underlying");
}
}
/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges.
/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent.
pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 {
1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color))
}
/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter.
/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows.
pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> {
let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous]));
if !follows_pixel_filter {
return Vec::new();
}
(rows[index..].iter())
.take_while(|operation| !processes_pixels(operation))
.filter_map(|operation| match operation {
EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()),
_ => None,
})
.collect()
}
/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects.
/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints.
pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool {
let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1);
let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next);
!fades_content(&rows[start..end])
}
/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does.
pub fn fades_content(operations: &[EffectOperation]) -> bool {
operations
.iter()
.any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything()))
}
/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of.
fn processes_pixels(operation: &EffectOperation) -> bool {
is_pixel_filter(operation) && !operation.changes_nothing()
}
/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply.
pub fn underlying_ranges<'a>(operations: impl IntoIterator<Item = &'a EffectOperation>) -> Vec<ChannelRanges> {
(operations.into_iter())
.filter_map(|operation| match operation {
EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying),
_ => None,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange {
BlendRange {
falloff_start,
range_start,
range_end,
falloff_end,
}
}
/// A level from 0 to 255 as a channel value.
fn level(level: f64) -> f64 {
level / 255.
}
#[test]
fn ranges_fade_linearly_across_their_falloffs() {
let percent = |level: f64| level / 255. * 100.;
let soft = range(percent(64.), percent(128.), percent(192.), percent(224.));
assert_eq!(soft.weight(level(32.)), 0.);
assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12);
assert_eq!(soft.weight(level(160.)), 1.);
assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12);
assert_eq!(soft.weight(level(240.)), 0.);
}
#[test]
fn unsplit_cutoffs_keep_the_level_they_lie_on() {
// For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported
let percent = |level: f64| level / 255. * 100.;
let hard = range(percent(64.), percent(64.), percent(192.), percent(192.));
assert_eq!(hard.weight(level(63.)), 0.);
assert_eq!(hard.weight(level(64.)), 1.);
assert_eq!(hard.weight(level(192.)), 1.);
assert_eq!(hard.weight(level(193.)), 0.);
}
#[test]
fn the_default_range_shows_everything() {
assert!(BlendRange::default().shows_everything());
assert!(ChannelRanges::default().show_everything());
assert!(!range(0., 10., 100., 100.).shows_everything());
assert!(!range(0., 0., 100., 99.).shows_everything());
}
#[test]
fn channels_multiply_with_gray_weighing_the_color() {
let ranges = ChannelRanges {
gray: range(0., 50., 100., 100.),
red: range(0., 0., 50., 100.),
..Default::default()
};
// The gray of a light pink shows fully, but its red at full strength fades it to nothing
assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.);
// A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range
let red = level(77.);
let gray = gray_level([77, 0, 0]) as f64 / 255.;
let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.);
assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12);
}
#[test]
fn nothing_beneath_hides_nothing() {
let underlying = ChannelRanges {
gray: range(50., 50., 100., 100.),
..Default::default()
};
assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.);
assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.);
assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12);
}
#[test]
fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() {
let blend_if = EffectOperation::BlendIf(Box::default());
let blur = EffectOperation::Blur {
radius_mask: Default::default(),
radius: 2.,
box_blur: false,
gamma: false,
};
let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow);
let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if];
// The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them
let acting: Vec<usize> = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect();
assert_eq!(acting, [1, 0, 0, 1, 0]);
// A blur of no radius changes nothing, so it starts no stretch of its own
let no_blur = EffectOperation::Blur {
radius_mask: Default::default(),
radius: 0.,
box_blur: false,
gamma: false,
};
let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())];
assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1);
}
#[test]
fn grays_between_two_levels_round_up() {
// Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39
assert_eq!(gray_level([0, 0, 250]), 28);
assert_eq!(gray_level([0, 0, 249]), 27);
assert_eq!(gray_level([5, 0, 0]), 2);
assert_eq!(gray_level([255, 255, 255]), 255);
}
#[test]
fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() {
let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay {
color: core_types::Color::RED,
blend_mode: core_types::blending::BlendMode::Normal,
opacity: 100.,
});
let mut ranges = BlendIfRanges::default();
ranges.content.gray.range_start = 40.;
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
let blur = EffectOperation::Blur {
radius_mask: Default::default(),
radius: 2.,
box_blur: false,
gamma: false,
};
assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0));
assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0));
assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2));
assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0));
}
}
@@ -65,8 +65,11 @@ pub struct EffectLayers {
/// How many of the effects, from the first, are carried out within the content's image.
pub flattened: usize,
pub layers: Vec<EffectLayer>,
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
/// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity.
/// Empty where those masks flatten what's before them instead.
pub trailing_masks: Range<usize>,
/// Whether a Blend If fades every layer by the colors of what lies beneath.
pub fades_by_underlying: bool,
}
impl EffectLayers {
@@ -76,9 +79,10 @@ impl EffectLayers {
let operations: Vec<EffectOperation> = effects.operations().collect();
let blend_mode = if blend_mode.to_svg_style_name().is_some() { 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
// 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.
let shares_content = blend_mode == BlendMode::Normal;
let blends_into_content = shares_content && fill >= 1.;
let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations);
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
let no_rows = operations.len()..operations.len();
@@ -174,8 +178,10 @@ impl EffectLayers {
layers.splice(content_layer..content_layer, through);
}
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it blurs what lies beneath
if blends_into_content && backdrop.is_empty() && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
let fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty();
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it reads what lies beneath
if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
let content = EffectLayer {
blend_mode: BlendMode::Normal,
parts: vec![LayerPart::Content],
@@ -184,6 +190,7 @@ impl EffectLayers {
flattened: operations.len(),
layers: vec![content],
trailing_masks: no_rows,
fades_by_underlying,
};
}
@@ -192,7 +199,12 @@ impl EffectLayers {
content_layer.parts.splice(0..0, backdrop);
}
Self { flattened, layers, trailing_masks }
Self {
flattened,
layers,
trailing_masks,
fades_by_underlying,
}
}
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
@@ -214,8 +226,13 @@ impl EffectLayers {
planned
}
/// Whether a layered piece reads what lies beneath the content.
/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content.
pub fn reads_backdrop(&self) -> bool {
self.fades_by_underlying || self.reads_around_backdrop()
}
/// 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.
pub fn reads_around_backdrop(&self) -> bool {
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
}
@@ -283,9 +300,11 @@ impl EffectLayers {
/// Whether any of the effects reads what lies beneath the content, like a background blur.
pub fn effects_read_backdrop(effects: &Effects) -> bool {
effects
.operations()
.any(|operation| matches!(operation, EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing())
effects.operations().any(|operation| match &operation {
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
_ => false,
})
}
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
@@ -335,31 +354,39 @@ fn merged_into_content(operations: &[EffectOperation]) -> usize {
.map_or(0, |index| index + 1)
}
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath.
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
let operations: Vec<EffectOperation> = effects.operations().collect();
let trailing_masks = trailing_masks(&operations);
let merged = merged_into_content(&operations[..trailing_masks.start]);
if merged == trailing_masks.start {
// A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold)
let kept: Vec<usize> = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect();
if kept.len() == operations.len() {
return Cow::Borrowed(effects);
}
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect()))
}
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect.
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
let no_rows = operations.len()..operations.len();
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation);
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
return no_rows;
};
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows };
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation));
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
}
/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing).
fn reads_only_beneath(operation: &EffectOperation) -> bool {
matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything())
}
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
// Only a drop shadow can show through the content
@@ -442,6 +469,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
| EffectOperation::HighPass { .. }
| EffectOperation::AddNoise { .. }
| EffectOperation::Dissolve { .. }
| EffectOperation::BlendIf(_)
| EffectOperation::Adjustment(_) => Vec::new(),
};
pieces.into_iter().flatten().collect()
@@ -815,6 +843,71 @@ mod tests {
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
}
#[test]
fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() {
let mut ranges = crate::blend_if::BlendIfRanges::default();
ranges.content.gray.range_start = 50.;
let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true);
assert_eq!(layers.layers.len(), 1);
assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only));
ranges.underlying.blue.falloff_end = 50.;
let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true);
assert_eq!(layers.layers[0].parts, [LayerPart::Content]);
assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath));
// Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill
let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]);
let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true);
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
assert!(layers.reads_through_share());
}
#[test]
fn blend_ifs_after_trailing_masks_leave_them_trailing() {
let mut ranges = crate::blend_if::BlendIfRanges::default();
ranges.underlying.gray.range_start = 50.;
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
let kinds = |effects: &Effects| -> Vec<EffectKind> { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() };
// After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone
for operations in [
[drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()],
[drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()],
] {
let effects = Effects::from_operations(operations);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::<Vec<_>>());
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
assert!(layers.fades_layers());
assert_eq!(kinds(&effects), [EffectKind::Mask]);
}
// With nothing else to trail, a clipping base still takes the mask alone in either order
assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]);
assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]);
}
#[test]
fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() {
let mut ranges = crate::blend_if::BlendIfRanges::default();
ranges.content.gray.range_start = 50.;
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
// The mask merges the shadow flattened before it into the content's image, which the Blend If then reads
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
assert_eq!(layers.flattened, 2);
assert!(!layers.fades_layers());
// A clipping base takes the mask alone, with the Blend If before it or after it
assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]);
assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]);
}
#[test]
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
@@ -4,6 +4,7 @@
use crate::Graphic;
use crate::adjustment::Adjustment;
use crate::blend_if::BlendIfRanges;
use crate::filters::{Convolution, NoiseDistribution};
use crate::masks::{MaskMode, mask_feather_sigma};
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
@@ -93,6 +94,8 @@ pub enum EffectKind {
ColorHalftone,
/// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass.
BackgroundBlur,
/// Shows the content only where its own colors, and those of what lies beneath it, fall within ranges of their channels.
BlendIf,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
@@ -151,6 +154,7 @@ impl std::fmt::Display for EffectKind {
Self::Pixelate => "Pixelate",
Self::ColorHalftone => "Color Halftone",
Self::BackgroundBlur => "Background Blur",
Self::BlendIf => "Blend If",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
@@ -1240,6 +1244,8 @@ pub enum EffectOperation {
/// Whether to blend the colors with their gamma encoding rather than in linear light.
gamma: bool,
},
/// Fades the content by how its own colors fall within ranges, as its fill does, and everything it draws by how the colors beneath fall within others, as its opacity does.
BlendIf(Box<BlendIfRanges>),
Adjustment(Adjustment),
}
@@ -1298,6 +1304,7 @@ impl EffectOperation {
Self::Pixelate { .. } => EffectKind::Pixelate,
Self::ColorHalftone { .. } => EffectKind::ColorHalftone,
Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur,
Self::BlendIf(_) => EffectKind::BlendIf,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
@@ -1380,6 +1387,7 @@ impl EffectOperation {
// The four neighbors lie a fixed distance away, so only the blur needs a radius
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
}
}
@@ -1415,7 +1423,7 @@ impl EffectOperation {
| Self::Outline { .. }
| Self::BevelAndEmboss { .. }
| Self::Feather { .. } => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
}
}
@@ -1483,7 +1491,7 @@ impl EffectOperation {
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
}
}
@@ -1618,7 +1626,7 @@ impl EffectOperation {
offset,
phase,
} => [radius, red_angle, green_angle, blue_angle, &mut offset.x, &mut offset.y, phase].into_iter().for_each(finite),
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::BlendIf(_) | Self::Adjustment(_) => {}
}
self
}
@@ -1830,6 +1838,7 @@ impl EffectOperation {
box_blur: false,
gamma: false,
},
EffectKind::BlendIf => Self::BlendIf(Box::default()),
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
@@ -2217,6 +2226,7 @@ impl EffectOperation {
visitor.parameter("offset", offset, DVec2::ZERO);
visitor.parameter("phase", phase, 0.);
}
Self::BlendIf(ranges) => ranges.visit_parameters(visitor),
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
}
}
@@ -2487,10 +2497,16 @@ mod tests {
offset: DVec2::new(-4., 6.),
phase: 25.,
},
EffectOperation::BlendIf(Box::new({
let mut ranges = BlendIfRanges::default();
ranges.content.gray.range_start = 25.;
ranges.underlying.red.falloff_end = 80.;
ranges
})),
];
for operation in operations {
assert_eq!(Effect::new(&operation).operation(), operation);
for operation in &operations {
assert_eq!(Effect::new(operation).operation(), *operation);
}
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
@@ -2512,6 +2528,13 @@ mod tests {
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
// Blend If's ranges ride attributes named like its node's inputs
let blend_if = operations.iter().find(|operation| operation.kind() == EffectKind::BlendIf).unwrap();
let row = Effect::new(blend_if);
assert_eq!(row.0.attribute::<f64>("content_range_start"), Some(&25.));
assert_eq!(row.0.attribute::<f64>("red_underlying_falloff_end"), Some(&80.));
assert_eq!(row.0.attributes().iter_any().count(), 2);
}
#[test]
@@ -1,6 +1,7 @@
pub mod adjustment;
pub mod appearance;
pub mod artboard;
pub mod blend_if;
pub mod effect_layers;
pub mod effects;
pub mod filters;
@@ -20,6 +21,7 @@ pub use vector_types;
pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use blend_if::BlendIfChannel;
pub use effects::{
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
stamp_effect, stamped_transform,
@@ -1746,6 +1746,7 @@ impl EffectOperation {
| Self::AddNoise { .. }
| Self::Dissolve { .. }
| Self::BackgroundBlur { .. }
| Self::BlendIf(_)
| Self::Adjustment(_) => false,
}
}
@@ -8,7 +8,7 @@ use crate::generators::pattern_sampler;
use crate::layer_blending::blend_layer;
use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur};
use crate::resample_kernels::{MotionBlurShear, displaced, frame_warped, halftoned, motion_blurred, pixelated, radial_blurred};
use crate::value_effects::{adjusted_gradient, adjustments, evaluate_gradient_effects, filled_color};
use crate::value_effects::{adjusted_gradient_with_blend_ifs, adjustments, content_blend_ifs, evaluate_gradient_effects, filled_color_with_blend_ifs};
use crate::warp_kernels::WarpRasterizer;
use core_types::FallibleVec2Operations;
use core_types::blending::BlendMode;
@@ -19,6 +19,7 @@ use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFOR
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Graphic;
use graphic_types::adjustment::Adjustment;
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, paint_overlay_folds};
use graphic_types::effect_layers::{EffectLayers, LayerPart, PiecePlace};
use graphic_types::effects::{
BevelDirection, BevelStyle, BevelTechnique, EffectCapture, EffectOperation, Effects, GlowFill, GlowSource, GlowTechnique, OutlineFill, bevel_light, contour_gradient_span, effect_space,
@@ -31,6 +32,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
use raster_types::parallel_rows::fill_rows;
use raster_types::{CPU, Image, Raster};
use std::collections::HashMap;
use std::ops::Range;
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
mod styles;
@@ -118,9 +120,22 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
})
.collect();
// Each row's run and its place in it, which Blend Ifs act within as the renderers' runs do
let operations: Vec<EffectOperation> = rows.iter().map(|(operation, ..)| operation.clone()).collect();
let runs: Vec<Range<usize>> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
let in_run = |index: usize| match runs.iter().find(|rows| rows.contains(&index)) {
Some(rows) => (&operations[rows.clone()], index - rows.start),
None => (&operations[..], index),
};
// Unless a fill fades them first, leading adjustments flattened into the image change its own colors, keeping even transparent pixels' colors
let layers = EffectLayers::plan_runs(effects, BlendMode::Normal, fill, true);
let leading_adjustments = rows.iter().take(layers.flattened).take_while(|_| fill == 1.).map_while(|(operation, ..)| match operation {
let overlay_folds = |index: usize| {
let (run, row) = in_run(index);
paint_overlay_folds(run, row)
};
let leading_adjustments = (rows.iter().enumerate().take(layers.flattened).take_while(|_| fill == 1.)).map_while(|(index, (operation, ..))| match operation {
EffectOperation::Adjustment(Adjustment::ColorOverlay { .. }) if !overlay_folds(index) => None,
EffectOperation::Adjustment(adjustment) => Some(adjustment),
_ => None,
});
@@ -181,9 +196,13 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
let mut pieces: HashMap<EffectCapture, Plane<[f32; 4]>> = HashMap::new();
// How much the trailing masks together show of each finished layer
let mut layer_fade: Option<Plane<f32>> = None;
// How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it
let mut blend_if_weight: Option<Plane<f32>> = None;
// Each run after the first takes the result of those before it as its content at full strength, like the renderers' nested runs
let mut run_fill = fill;
// The leading adjustments carried out on the image's colors still start stretches that Blend Ifs act at the start of
let mut rows_reached = 0;
for (index, &(ref operation, effect_to_pixels, starts_later_run)) in rows.iter().enumerate().skip(leading) {
if starts_later_run {
full = match (filled.take(), beneath.take()) {
@@ -192,7 +211,23 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
(None, None) => full,
};
run_fill = 1.;
blend_if_weight = None;
}
let acting_blend_ifs = (rows_reached..=index).flat_map(|row| {
let (run, row) = in_run(row);
blend_ifs_acting_before(run, row)
});
for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) {
let weight = blend_if_weights(&full, &ranges.content);
filled = Some(filled.as_ref().unwrap_or(&full).zip(&weight, |pixel, weight| pixel.map(|channel| channel * weight)));
blend_if_weight = Some(match blend_if_weight {
Some(previous) => previous.zip(&weight, |previous, weight| previous * weight),
None => weight,
});
}
rows_reached = index + 1;
if operation.changes_nothing() {
continue;
}
@@ -210,6 +245,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
let layered = index >= layers.flattened;
let piece = |plane: usize| layered.then_some(EffectCapture { index, plane });
let knockout_fill = if layered { 1. } else { run_fill };
let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered);
match *operation {
EffectOperation::Blur { radius, box_blur, gamma, .. } if !operation.varies_blur_radius() => {
@@ -273,7 +309,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
let silhouette = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y);
let strength = cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, pixels_per_length);
let shadow = tinted(&strength, color);
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill) } else { shadow };
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill, knockout_weight) } else { shadow };
place_beneath(&mut pieces, piece(0), &mut beneath, shadow);
}
EffectOperation::OuterGlow {
@@ -293,7 +329,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
let strength = shaped(raw.clone(), range, contour);
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect);
let fades = matches!(paint, GlowFill::Gradient { .. }) || noise > 0.;
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill);
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill, knockout_weight);
place_beneath(&mut pieces, piece(0), &mut beneath, glow);
}
EffectOperation::InnerShadow {
@@ -411,7 +447,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
// The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow
if let Some(band) = &bands.outside {
let band = knocked_out(painted(band), &full, knockout_fill);
let band = knocked_out(painted(band), &full, knockout_fill, knockout_weight);
place_beneath(&mut pieces, piece(0), &mut beneath, band);
}
if let Some(band) = &bands.inside {
@@ -492,7 +528,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
place_within(&mut pieces, piece(plane), &mut full, &mut filled, tinted(&amount, color), blend_mode);
}
for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() {
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill);
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill, knockout_weight);
place_beneath(&mut pieces, piece(plane + 2), &mut beneath, slope);
}
}
@@ -511,8 +547,8 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
};
place_within(&mut pieces, piece(0), &mut full, &mut filled, painted, blend_mode);
}
// An image of its own has nothing beneath it to blur
EffectOperation::BackgroundBlur { .. } => {}
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
// A solid paint overlay paints within the content alone, like any other paint overlay
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
@@ -672,7 +708,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
let Some(frame) = &frame else { continue };
let Some(screens) = HalftoneScreen::of(operation, frame) else { continue };
// Each pixel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots
// Each pixel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots
merge_beneath(&mut full, &mut filled, &mut beneath);
let shares = filled.as_ref().map(|filled| crate::filter_kernels::fill_shares(&full, filled));
let unfaded = filled.map(|filled| crate::filter_kernels::at_full_coverage(&filled, &full));
@@ -881,19 +917,31 @@ fn tinted(coverage: &Plane<f32>, color: Color) -> Plane<[f32; 4]> {
coverage.map(|coverage| color.map(|channel| channel * coverage))
}
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`.
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> {
if fill >= 1. {
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`, times the Blend If weight if any fades it.
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32, blend_if_weight: Option<&Plane<f32>>) -> Plane<[f32; 4]> {
if fill >= 1. && blend_if_weight.is_none() {
return tinted;
}
// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this
tinted.zip(full_content, |tinted, content| {
let shown = (1. - content[3]) / (1. - fill * content[3]).max(f32::EPSILON);
let covering = match blend_if_weight {
Some(weight) => full_content.zip(weight, |content, weight| [content[3], weight * fill, 0., 0.]),
None => full_content.map(|content| [content[3], fill, 0., 0.]),
};
tinted.zip(&covering, |tinted, [alpha, fill, ..]| {
let shown = (1. - alpha) / (1. - fill * alpha).max(f32::EPSILON);
tinted.map(|channel| channel * shown)
})
}
/// How strongly Blend If's `ranges` show each pixel of a premultiplied gamma-encoded `image`, by its straight color.
fn blend_if_weights(image: &Plane<[f32; 4]>, ranges: &ChannelRanges) -> Plane<f32> {
image.map(|[red, green, blue, alpha]| {
let straight = if alpha > 0. { [red, green, blue].map(|channel| (channel / alpha) as f64) } else { [0.; 3] };
ranges.weight(straight) as f32
})
}
/// Places a tinted image beneath the content: as the layered `piece` if it names one, or else stacked over what lies `beneath` the content so far.
fn place_beneath(pieces: &mut HashMap<EffectCapture, Plane<[f32; 4]>>, piece: Option<EffectCapture>, beneath: &mut Option<Plane<[f32; 4]>>, tinted: Plane<[f32; 4]>) {
match piece {
@@ -1192,8 +1240,9 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
// The fill fades the color beneath its paint overlays, which paint over it at full strength, as the renderers fill an endless color
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments).unwrap_or_default();
let color = filled_color(*item.element(), &adjustments, fill);
let effects = item.attribute::<Effects>(ATTR_EFFECTS);
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
let color = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
Some(Box::new(move |_| faded(color, opacity)))
}
Graphic::RasterCPU(item) => {
@@ -1344,12 +1393,13 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
Some(Box::new(move |point| sample_gamma(&image, to_pixels.transform_point2(point)).map(|channel| channel * opacity)))
}
Graphic::Gradient(item) => {
// The GPU fades a gradient by its fill in the layer of its opacity, unless adjustments act on the ramp the fill fades
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
// The GPU fades a gradient by its fill in the layer of its opacity, unless effects act on the ramp the fill fades
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
let settings = GradientSettings::from_item_attributes(item);
let (gradient, settings, opacity) = match adjusted_gradient(item.element(), settings, &adjustments, fill) {
let (gradient, settings, opacity) = match adjusted_gradient_with_blend_ifs(item.element(), settings, &adjustments, &blend_ifs, fill) {
Some((adjusted, adjusted_settings)) => (std::borrow::Cow::Owned(adjusted), adjusted_settings, opacity),
None => (std::borrow::Cow::Borrowed(item.element()), settings, opacity * fill),
};
@@ -1363,12 +1413,16 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
}))
}
Graphic::Color(item) => {
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless adjustments act on the faded color
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless effects act on the faded color
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
let (color, opacity) = match adjustments.is_empty() {
let (color, opacity) = match adjustments.is_empty() && blend_ifs.is_empty() {
true => (*item.element(), paint_opacity(item)),
false => (filled_color(*item.element(), &adjustments, fill), item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32),
false => (
filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill),
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32,
),
};
let (color, opacity) = (core_types::color::SRGBA8::from(color), layer_opacity(opacity));
@@ -2449,6 +2503,60 @@ mod tests {
}
}
#[test]
fn halftones_keep_the_fade_of_blend_ifs_before_them() {
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
// A Blend If hiding the white content stays hiding it once a halftone prints it, which white leaves as white
let mut ranges = BlendIfRanges::default();
ranges.content.gray = BlendRange {
falloff_start: 0.,
range_start: 0.,
range_end: 50.,
falloff_end: 50.,
};
let halftone = EffectOperation::ColorHalftone {
radius: 4.,
red_angle: 45.,
green_angle: 45.,
blue_angle: 45.,
offset: DVec2::ZERO,
phase: 0.,
};
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(24, 24, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(24.)));
[EffectOperation::BlendIf(Box::new(ranges)), halftone]
.iter()
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
let evaluated = evaluate_raster_effects(item);
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
}
#[test]
fn blend_ifs_still_act_after_leading_adjustments_that_change_nothing() {
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
// A Blend If hiding the white content hides it before the invert, though the image's own colors take the Make Opaque of no strength ahead of it
let mut ranges = BlendIfRanges::default();
ranges.content.gray = BlendRange {
falloff_start: 0.,
range_start: 0.,
range_end: 50.,
falloff_end: 50.,
};
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
[
EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
EffectOperation::BlendIf(Box::new(ranges)),
EffectOperation::Adjustment(Adjustment::Invert),
]
.iter()
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
let evaluated = evaluate_raster_effects(item);
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
}
#[test]
fn halftones_too_fine_to_print_show_their_tone() {
// Dots a fraction of a pixel apart print the tone they average to, which for opaque content is the content
@@ -7,6 +7,7 @@ use core_types::Color;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
use graphic_types::adjustment::Adjustment;
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
use graphic_types::effects::{EffectOperation, Effects};
use std::hash::{DefaultHasher, Hasher};
use std::sync::{Mutex, PoisonError};
@@ -29,6 +30,47 @@ pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
.collect()
}
/// A step a value's Blend Ifs take among its adjustments (see [`content_blend_ifs`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BlendIfStep {
/// A Blend If reads the value's colors and fades the value by these content ranges, as a fill does.
Fade(ChannelRanges),
/// An effect run after the first starts (see [`Effects::runs`]), taking the value as the runs before it leave it as its content at full strength.
NextRun,
}
/// Where each Blend If among the effects that fades a value by its own colors reads it, after how many of the [`adjustments`], with where each effect run after the first starts.
/// Empty if no Blend If fades the value.
pub fn content_blend_ifs(effects: &Effects) -> Vec<(usize, BlendIfStep)> {
let operations: Vec<EffectOperation> = effects.operations().collect();
if !fades_content(&operations) {
return Vec::new();
}
// Each run's Blend Ifs act from its own start, as the renderers draw each run's effects on the result of those before it
let mut adjustments_before = 0;
let mut steps = Vec::new();
for (run_index, (_, rows)) in effects.runs().into_iter().enumerate() {
if run_index > 0 {
steps.push((adjustments_before, BlendIfStep::NextRun));
}
let run = &operations[rows];
for (row, operation) in run.iter().enumerate() {
let acting = blend_ifs_acting_before(run, row).into_iter().filter(|ranges| !ranges.content.show_everything());
steps.extend(acting.map(|ranges| (adjustments_before, BlendIfStep::Fade(ranges.content))));
adjustments_before += usize::from(matches!(operation, EffectOperation::Adjustment(_)));
}
}
steps
}
/// Whether a Blend If fades a value with effects in more than one run, so later runs read and paint within the result of those before them.
pub fn blend_ifs_span_runs(effects: &Effects) -> bool {
content_blend_ifs(effects).iter().any(|(_, step)| *step == BlendIfStep::NextRun)
}
/// The color with `adjustments` carried out on it in order.
pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
@@ -37,19 +79,60 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
/// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it.
/// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque.
pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color {
if fill >= 1. {
return adjusted_color(color, adjustments);
}
fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color))
filled_color_with_blend_ifs(color, adjustments, &[], fill)
}
/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color {
/// Like [`filled_color`], with the steps of the `blend_ifs` (see [`content_blend_ifs`]) also fading the paint by each one's content ranges where it reads the paint's colors.
pub fn filled_color_with_blend_ifs(color: Color, adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Color {
if fill >= 1. && blend_ifs.is_empty() {
return adjusted_color(color, adjustments);
}
fill_through(color, adjustments, blend_ifs, fill, |index, color| adjust_color(&adjustments[index], color), ChannelRanges::weight)
}
/// Carries out `adjustments` over a paint faded by `fill` and the `blend_ifs` as [`filled_color_with_blend_ifs`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
/// `weigh` gives how strongly a Blend If's ranges show the gamma-encoded channels it reads.
fn fill_through(
color: Color,
adjustments: &[Adjustment],
blend_ifs: &[(usize, BlendIfStep)],
fill: f32,
adjust: impl Fn(usize, Color) -> Color,
mut weigh: impl FnMut(&ChannelRanges, [f64; 3]) -> f64,
) -> Color {
// Each Blend If fades the faded color by how strongly it shows the full-strength one, which each later run resets to the faded color
let mut steps = blend_ifs.iter().peekable();
let mut take_steps = |full: &mut Color, filled: &mut Color, adjusted_count: usize| {
let mut weight = 1.;
let mut faded = false;
while let Some((_, step)) = steps.next_if(|(before, _)| *before <= adjusted_count) {
match step {
BlendIfStep::Fade(ranges) => {
let [red, green, blue, _] = full.to_gamma_srgb_channels();
weight *= weigh(ranges, [red, green, blue].map(f64::from));
faded = true;
}
BlendIfStep::NextRun => {
*filled = filled.with_alpha(filled.a() * std::mem::replace(&mut weight, 1.) as f32);
*full = *filled;
}
}
}
*filled = filled.with_alpha(filled.a() * weight as f32);
faded
};
// The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength
let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill));
// Once a Blend If fades them, adjustments keep the colors empty where they're empty, as the renderers keep empty pixels
let mut faded = false;
for (index, adjustment) in adjustments.iter().enumerate() {
faded |= take_steps(&mut full, &mut filled, index);
let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else {
(full, filled) = (adjust(index, full), adjust(index, filled));
let adjusted = |color: Color| if !faded || color.a() > 0. { adjust(index, color) } else { color };
(full, filled) = (adjusted(full), adjusted(filled));
continue;
};
@@ -64,18 +147,39 @@ fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: imp
filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha);
full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32);
}
take_steps(&mut full, &mut filled, adjustments.len());
filled
}
/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once.
fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color> {
/// Carries out `adjustments` in order on any number of colors with the `fill` and the `blend_ifs` fading them, with each one's kernel prepared once.
fn prepared(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Box<dyn Fn(Color) -> Color> {
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
if fill >= 1. {
if fill >= 1. && blend_ifs.is_empty() {
return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color)));
}
let adjustments = adjustments.to_vec();
Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color)))
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
Box::new(move |color| fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), ChannelRanges::weight))
}
/// Tells apart the colors each channel's range of each of the `blend_ifs` shows fully, partly, or not at all, as it reads them where [`fill_through`] fades by it.
fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> impl Fn(Color) -> u64 {
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
// Each channel's state (hidden, partly shown, or shown) is a digit in base 3, so up to ten Blend Ifs stay apart exactly
move |color| {
let mut region = 0_u64;
let weigh = |ranges: &ChannelRanges, channels: [f64; 3]| {
for weight in ranges.channel_weights(channels) {
let state = u64::from(weight > 0.) + u64::from(weight >= 1.);
region = region.wrapping_mul(3).wrapping_add(state);
}
ranges.weight(channels)
};
fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), weigh);
region
}
}
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
@@ -83,17 +187,28 @@ fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> {
if adjustments.is_empty() {
adjusted_gradient_with_blend_ifs(gradient, settings, adjustments, &[], fill)
}
/// Like [`adjusted_gradient`], with the `blend_ifs` also fading the ramp as [`filled_color_with_blend_ifs`] fades a color, or `None` if there are neither adjustments nor Blend Ifs.
pub fn adjusted_gradient_with_blend_ifs(
gradient: &Gradient,
settings: GradientSettings,
adjustments: &[Adjustment],
blend_ifs: &[(usize, BlendIfStep)],
fill: f32,
) -> Option<(Gradient, GradientSettings)> {
if adjustments.is_empty() && blend_ifs.is_empty() {
return None;
}
// A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black
if gradient.is_empty() {
return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings));
return Some((Gradient::from(vec![prepared(adjustments, blend_ifs, fill)(Color::BLACK)]), settings));
}
if settings.interpolation == GradientInterpolation::Stepped {
let adjust = prepared(adjustments, fill);
let adjust = prepared(adjustments, blend_ifs, fill);
return Some((gradient.map_colors(|color| adjust(*color)), settings));
}
@@ -102,6 +217,16 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
gradient.cache_hash(&mut hasher);
settings.cache_hash(&mut hasher);
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
for (before, step) in blend_ifs {
hasher.write_usize(*before);
match step {
BlendIfStep::Fade(ranges) => {
hasher.write_u8(0);
ranges.cache_hash(&mut hasher);
}
BlendIfStep::NextRun => hasher.write_u8(1),
}
}
hasher.write_u32(fill.to_bits());
let key = hasher.finish();
@@ -114,7 +239,11 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
return Some(result);
}
let resampled = gradient.map_ramp(settings, prepared(adjustments, fill));
// A Blend If cuts the ramp off wherever the colors it reads cross its ranges, which may lie between the resampling's probes
let resampled = match blend_ifs.is_empty() {
true => gradient.map_ramp(settings, prepared(adjustments, blend_ifs, fill)),
false => gradient.map_ramp_by_regions(settings, prepared(adjustments, blend_ifs, fill), blend_if_regions(adjustments, blend_ifs, fill)),
};
let resampled_settings = GradientSettings {
space: GradientSpace::RgbGamma,
interpolation: GradientInterpolation::Linear,
@@ -129,29 +258,43 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
Some((resampled, resampled_settings))
}
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> Color> {
prepared(&adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
/// A color without the effects attribute is returned as it is.
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
return item;
};
let mut item = item;
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
*item.element_mut() = color;
item.remove_attribute::<Effects>(ATTR_EFFECTS);
item
}
/// The gradient with the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors.
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
/// A gradient without the effects attribute is returned as it is.
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
return item;
};
let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) else { return item };
let settings = GradientSettings::from_item_attributes(&item);
let adjusted = gradient_after_effects(item.element(), settings, effects);
let mut item = item;
let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) {
let settings = match adjusted {
Some((gradient, adjusted_settings)) => {
*item.element_mut() = gradient;
adjusted_settings
@@ -180,6 +323,16 @@ mod tests {
actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4)
}
/// The `element` with each row stamped on it while it's placed by the row's scale, so a row stamped at a new scale starts a run of its own.
fn stamped<T>(element: T, rows: &[(EffectOperation, f64)]) -> Item<T> {
let mut item = Item::new_from_element(element);
for (operation, scale) in rows {
item.set_attribute(core_types::ATTR_TRANSFORM, glam::DAffine2::from_scale(glam::DVec2::splat(*scale)));
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation));
}
item
}
#[test]
fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() {
let half_white = [Adjustment::ColorOverlay {
@@ -198,6 +351,162 @@ mod tests {
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
}
#[test]
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
use graphic_types::blend_if::BlendIfRanges;
// Shown only where the gray is at least half
let mut hides_darks = BlendIfRanges::default();
hides_darks.content.gray.falloff_start = 50.;
hides_darks.content.gray.range_start = 50.;
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
let invert = EffectOperation::Adjustment(Adjustment::Invert);
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let black_through = |operations: Vec<EffectOperation>| evaluate_color_effects(Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations)));
// Black is hidden, whether inverted after the Blend If reads it or not, but shows once inverted before
assert_eq!(black_through(vec![blend_if.clone()]).element().a(), 0.);
assert_eq!(black_through(vec![blend_if.clone(), invert.clone()]).element().a(), 0.);
assert!(close(gamma(*black_through(vec![invert, blend_if.clone()]).element()), [1.; 4]));
// An overlay after it paints over the hidden color at full strength, as over a fill of none, and the effects are consumed
let overlaid = black_through(vec![blend_if.clone(), red]);
assert!(close(gamma(*overlaid.element()), [1., 0., 0., 1.]));
assert!(overlaid.attribute::<Effects>(ATTR_EFFECTS).is_none());
// A gradient's dark start is hidden and its light end shown
let gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_EFFECTS, Effects::from_operations([blend_if]));
let evaluated = evaluate_gradient_effects(gradient);
let settings = GradientSettings::from_item_attributes(&evaluated);
assert!(evaluated.element().evaluate(0., settings).a() < 1e-6);
assert!(close(gamma(evaluated.element().evaluate(1., settings)), [1.; 4]));
}
#[test]
fn consumed_values_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_it() {
use graphic_types::blend_if::BlendIfRanges;
// Shown only where the gray is at least half
let mut hides_darks = BlendIfRanges::default();
hides_darks.content.gray.falloff_start = 50.;
hides_darks.content.gray.range_start = 50.;
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
let overlay = |color: Color| {
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color,
blend_mode: BlendMode::Normal,
opacity: 100.,
})
};
// White painted blue is read as blue by a Blend If after a scale, which hides it, but in the same run the Blend If reads the white beneath the overlay
let color_through = |color: Color, rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(color, rows)).element();
assert_eq!(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 2.)]).a(), 0.);
assert!(close(gamma(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 1.)])), [0., 0., 1., 1.]));
// Black hidden before a scale leaves nothing for an overlay after it to paint within
assert_eq!(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 2.)]).a(), 0.);
assert!(close(gamma(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 1.)])), [1., 0., 0., 1.]));
// A ramp painted blue is hidden all along by a Blend If after a scale
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(overlay(Color::BLUE), 1.), (blend_if, 2.)]);
let evaluated = evaluate_gradient_effects(ramp);
let settings = GradientSettings::from_item_attributes(&evaluated);
for t in [0., 0.25, 0.75, 1.] {
let shown = evaluated.element().evaluate(t, settings);
assert!(shown.a() < 1e-6, "hidden at {t}: {:?}", gamma(shown));
}
}
#[test]
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels};
use graphic_types::EffectKind;
use graphic_types::blend_if::BlendIfRanges;
use raster_types::{Image, Raster};
// Shown only where the gray is at least half
let mut hides_darks = BlendIfRanges::default();
hides_darks.content.gray.falloff_start = 50.;
hides_darks.content.gray.range_start = 50.;
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
let make_opaque = EffectOperation::default_for(EffectKind::MakeOpaque);
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 100.,
});
// Black consumed as a color, which agrees with a raster's pixel of it
let black_through = |name: &str, rows: &[(EffectOperation, f64)]| {
let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows));
let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT);
let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel));
assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}");
color
};
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
let hidden = [
("made opaque", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 1.)]),
("made opaque in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.)]),
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]),
];
for (name, rows) in hidden {
assert_eq!(black_through(name, &rows).a(), 0., "black {name}");
}
// In its own run, an overlay still paints within the full-strength black
let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
for scale in [1., 2.] {
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(blend_if.clone(), 1.), (make_opaque.clone(), scale)]);
let evaluated = evaluate_gradient_effects(ramp);
let settings = GradientSettings::from_item_attributes(&evaluated);
for (t, alpha) in [(0., 0.), (0.25, 0.), (0.75, 1.), (1., 1.)] {
let shown = evaluated.element().evaluate(t, settings).a();
assert!((shown - alpha).abs() < 1e-6, "the alpha at {t} with the scale {scale} is {shown}");
}
}
}
#[test]
fn a_ramp_keeps_the_band_a_blend_if_shows_between_where_resampling_probes_it() {
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
// Shown only where the gray lies from 30% to 40%, which neither end of the ramp nor any of its quarter points lands within
let mut band = BlendIfRanges::default();
band.content.gray = BlendRange {
falloff_start: 30.,
range_start: 30.,
range_end: 40.,
falloff_end: 40.,
};
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(band))]);
let gamma_settings = GradientSettings {
space: GradientSpace::RgbGamma,
interpolation: GradientInterpolation::Linear,
..Default::default()
};
let (resampled, settings) = gradient_after_effects(&Gradient::from(vec![Color::BLACK, Color::WHITE]), gamma_settings, &effects).expect("the Blend If fades the ramp");
// The band shows its own grays from level 77 to 102, which lie from 30% to just past 40% along the ramp, with sharp edges
for t in [0.301, 0.35, 0.4] {
let shown = resampled.evaluate(t, settings);
assert!(close(gamma(shown), [t as f32, t as f32, t as f32, 1.]), "the band shows at {t}: {:?}", gamma(shown));
}
for t in [0., 0.25, 0.299, 0.403, 0.5, 0.75, 1.] {
assert!(resampled.evaluate(t, settings).a() < 1e-6, "hidden at {t}");
}
}
#[test]
fn a_gradient_without_stops_adjusts_the_black_it_reads_as() {
let empty = Gradient::from(Vec::<Color>::new());
@@ -3,7 +3,7 @@
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
use core_types::Color;
use core_types::blending::BlendMode;
@@ -202,6 +202,8 @@ pub struct DeferredImage {
pub margin: f64,
pub opacity: f32,
pub blend_mode: BlendMode,
/// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any.
pub mask: Option<String>,
}
/// What the GPU renders an image of for an SVG.
@@ -276,6 +278,7 @@ pub struct DeferredImagePlacement {
pub user_to_document: DAffine2,
pub opacity: f32,
pub blend_mode: BlendMode,
pub mask: Option<String>,
/// Whether the image is drawn to a canvas rather than embedded in the SVG.
pub to_canvas: bool,
/// Screen pixels per document unit, which sizes an image drawn to a canvas.
@@ -289,14 +292,22 @@ pub struct DeferredImageLayout {
pub size: UVec2,
}
/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow.
pub(crate) const DEFERRED_IMAGE_OPENING: &str = "<!--deferred-image-";
pub(crate) const DEFERRED_IMAGE_CLOSING: &str = "<!--/deferred-image-";
/// The starts of the markers around a copy of that markup in a Blend If mask, which can't draw the canvas of its image, followed by its ID, a hyphen and the key color's hex (for the opening), and `-->`.
pub(crate) const DEFERRED_COVER_OPENING: &str = "<!--deferred-cover-";
pub(crate) const DEFERRED_COVER_CLOSING: &str = "<!--/deferred-cover-";
/// The markers that open and close the markup standing in for the item of deferred content `id` names.
pub(crate) fn image_markers(id: u64) -> (String, String) {
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{id}-->"))
(format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->"))
}
/// Whether the `markup` holds markers of markup standing in for an item of deferred content.
pub(crate) fn holds_image_markers(markup: &str) -> bool {
markup.contains("<!--deferred-image-")
markup.contains(DEFERRED_IMAGE_OPENING)
}
impl DeferredImage {
@@ -311,6 +322,7 @@ impl DeferredImage {
user_to_document: self.user_to_document,
opacity: self.opacity,
blend_mode: self.blend_mode,
mask: self.mask.clone(),
to_canvas: self.render_params.to_canvas(),
canvas_image_scale: self.render_params.canvas_image_scale,
},
@@ -358,11 +370,41 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
canvas_image_scale: placement.canvas_image_scale,
..Default::default()
};
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
let opacity = if placement.opacity < 1. { format!(r#" opacity="{}""#, placement.opacity) } else { String::new() };
let style = if placement.blend_mode != BlendMode::Normal {
format!(r#" style="{}""#, placement.blend_mode.render())
} else {
String::new()
};
let markup = render.svg.to_svg_string();
// A mask goes on a group taking the image's opacity and blend mode, which still blends with what lies beneath
let markup = match &placement.mask {
Some(mask) => {
render_raster_cpu_image_svg(image, placement.transform, 1., BlendMode::Normal, &mut render, &render_params);
format!(r#"<g mask="{mask}"{opacity}{style}>{}</g>"#, render.svg.to_svg_string())
}
None => {
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
render.svg.to_svg_string()
}
};
while let Some(span) = marked_span(svg, &opening, &closing) {
svg.replace_range(span, &markup);
}
image_data.extend(render.image_data);
// A Blend If mask can't draw the canvas in its copy of what lies beneath, so a rectangle of the color its ranges show in full covers the image there
if placement.to_canvas {
let (opening, closing) = (format!("{DEFERRED_COVER_OPENING}{}-", placement.id), format!("{DEFERRED_COVER_CLOSING}{}-->", placement.id));
let transform = format_transform_matrix(placement.transform);
while let Some(start) = svg.find(&opening) {
let key_start = start + opening.len();
let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break };
let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else {
break;
};
let cover = format!(r##"<rect width="1" height="1" transform="{transform}" fill="#{}"{opacity}{style} />"##, &svg[key_start..key_end]);
svg.replace_range(start..end, &cover);
}
}
}
@@ -3,6 +3,7 @@ pub mod deferred_image;
pub mod render_ext;
mod renderer;
mod svg_backdrop;
mod svg_blend_if;
pub mod to_peniko;
pub mod vello_scene_builder;
File diff suppressed because it is too large. Load diff
@@ -134,7 +134,8 @@ impl SvgRender {
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64) -> Option<String> {
/// The image is embedded `for_mask`, which draws no canvas.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
return None;
}
@@ -151,8 +152,11 @@ impl SvgRender {
let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
// A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers
let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params));
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
let image_clip = match holds_backdrop && self.images_replace_markup(render_params) {
let image_clip = match images && self.images_replace_markup(render_params) {
true => match &clip {
Some((reference, _)) => self.clip_outline(reference).map(Some),
None => Some(None),
@@ -161,9 +165,16 @@ impl SvgRender {
};
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
let copies = match (holds_backdrop, image_clip) {
let image = images && image_clip.is_some();
let copies = match (images, image_clip) {
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false),
(true, Some(clip)) => self.backdrop_image(root, copies_to_document, clip, region, read_reach, render_params),
(true, Some(clip)) => {
let image_params = RenderParams {
embeds_images: render_params.embeds_images || for_mask,
..render_params.clone()
};
self.backdrop_image(root, copies_to_document, clip, region, read_reach, &image_params)
}
(true, None) => self.backdrop_markup_copies(root, copies_to_document, true, true),
}?;
@@ -172,11 +183,22 @@ impl SvgRender {
group.holds_backdrop = true;
}
let Some((clip_path, root_to_document)) = clip else { return Some(copies) };
let markup = match clip {
Some((clip_path, root_to_document)) => {
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#)
}
None => copies,
};
Some(BackdropCopy { markup, image })
}
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
Some(format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#))
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root).
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
let start = self.open_groups.groups[root].content_start;
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas)
}
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
@@ -240,6 +262,7 @@ impl SvgRender {
margin: self.ancestors_reach + read_reach,
opacity: 1.,
blend_mode: BlendMode::Normal,
mask: None,
});
let (opening, closing) = deferred_image::image_markers(id);
@@ -247,6 +270,13 @@ impl SvgRender {
}
}
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
pub(crate) struct BackdropCopy {
pub markup: String,
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
pub image: bool,
}
/// The outline of the union of the `shapes`, each filled by the nonzero rule, as one path filled by that rule, or `None` if their coordinates aren't finite or a sweep fails.
/// Each shape's winding is resolved alone first, so the final sweep counts one winding rather than one per shape at every edge.
fn united_outline(shapes: &[BezPath]) -> Option<BezPath> {
@@ -336,7 +366,7 @@ pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds:
let space_to_user = space.unwrap_or_default();
let read_region = (space_to_user * Quad::from_box([min, max])).bounding_box();
let read_reach = reach * spans_along_axes((render.transform * space_to_user).matrix2).max_element();
let copy = render.backdrop_copy(render_params, read_region, read_reach)?;
let copy = render.backdrop_copy(render_params, read_region, read_reach, false)?.markup;
let copy = match space.map(|space| format_transform_matrix(space.inverse())) {
Some(matrix) if !matrix.is_empty() => format!(r#"<g transform="{matrix}">{copy}</g>"#),
_ => copy,
@@ -0,0 +1,228 @@
//! Blend If in SVG, all native: filter primitives weigh each pixel by its channels' levels through tables of the ranges' weights, fading the content within its effects filter,
//! and a mask holding a copy of what lies beneath, filtered into its weights, fades every layer the content draws.
use crate::deferred_image::{DEFERRED_COVER_CLOSING, DEFERRED_COVER_OPENING, DEFERRED_IMAGE_CLOSING, DEFERRED_IMAGE_OPENING};
use crate::renderer::{RenderParams, SvgRender};
use core_types::uuid::generate_uuid;
use glam::DVec2;
use graphic_types::BlendIfChannel;
use graphic_types::blend_if::{BlendRange, ChannelRanges, GRAY_PERCENTAGES};
use graphic_types::effects::spans_along_axes;
use std::fmt::Write;
/// Pushes the primitives weighing how strongly the `ranges` show each pixel of the `image` result by its straight color, given `push` (a primitive's tag, attributes, and children, returning its result's name).
/// Returns the name of the result holding the weight in its alpha, or `None` if the ranges show everything.
pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &str, ranges: &ChannelRanges) -> Option<String> {
let mut weight: Option<String> = None;
for (channel, range) in ranges.limiting() {
// A gray exactly between two levels gains a sliver of a level, so it rounds up as `gray_level` rounds it
let [red, green, blue] = GRAY_PERCENTAGES.map(|percentage| percentage as f64 / 100.);
let alpha_row = match channel {
BlendIfChannel::Gray => format!("{red} {green} {blue} 0 {}", 0.005 / 255.),
BlendIfChannel::Red => "1 0 0 0 0".to_string(),
BlendIfChannel::Green => "0 1 0 0 0".to_string(),
BlendIfChannel::Blue => "0 0 1 0 0".to_string(),
};
// The channel's level moved into alpha, then looked up in the table of the range's weight at each level, which the browser's 8-bit filters index exactly
let level = push(
"feColorMatrix",
&format!(r#"in="{image}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {alpha_row}" color-interpolation-filters="sRGB""#),
"",
);
let table: Vec<String> = range.level_weights().iter().map(|weight| format_table_value(*weight)).collect();
let shown = push(
"feComponentTransfer",
&format!(r#"in="{level}" color-interpolation-filters="sRGB""#),
&format!(r#"<feFuncA type="table" tableValues="{}" />"#, table.join(" ")),
);
weight = Some(match weight {
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
None => shown,
});
}
weight
}
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
fn with_unreadable_covered(markup: &str, key: &str) -> String {
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
}
/// The `markup` with the canvases standing in for images covered with the `key` color, at their own placement, size, opacity, and blend mode, so a translucent image hides less of what lies beneath it.
fn with_canvases_covered(markup: &str, key: &str) -> String {
const OPENING: &str = "<foreignObject";
const CLOSING: &str = "</foreignObject>";
let mut covered = String::with_capacity(markup.len());
let mut rest = markup;
while let Some(start) = rest.find(OPENING) {
let Some(end) = rest[start..].find(CLOSING).map(|offset| start + offset + CLOSING.len()) else {
break;
};
covered.push_str(&rest[..start]);
// A canvas's cover takes its opening tag's attributes
let element = &rest[start..end];
match (element.contains("data-canvas-placeholder"), element.find('>')) {
(true, Some(tag_end)) => write!(covered, r#"<rect{} fill="{key}" />"#, &element[OPENING.len()..tag_end]).unwrap(),
(true, None) => {}
(false, _) => covered.push_str(element),
}
rest = &rest[end..];
}
covered.push_str(rest);
covered
}
/// The `markup` with the markup standing in for each image the GPU renders marked for a rectangle of the `key` color to cover once the image arrives (see [`crate::deferred_image::substitute_deferred_image`]).
/// Without a GPU the markup is what's drawn, which the mask reads as it is.
fn with_deferred_images_marked_for_covers(markup: &str, key: &str) -> String {
let markup = markup.replace(DEFERRED_IMAGE_CLOSING, DEFERRED_COVER_CLOSING);
let mut parts = markup.split(DEFERRED_IMAGE_OPENING);
let mut marked = parts.next().unwrap_or_default().to_string();
for part in parts {
// Each opening marker's ID is followed by the end of the comment, before which the key goes
match part.split_once("-->") {
Some((id, rest)) => write!(marked, "{DEFERRED_COVER_OPENING}{id}-{}-->{rest}", key.trim_start_matches('#')).unwrap(),
None => write!(marked, "{DEFERRED_IMAGE_OPENING}{part}").unwrap(),
}
}
marked
}
/// A color the `underlying` ranges, which multiply, show most strongly (in full if any color is shown in full), as a hex color.
/// Each channel shows its levels in full in one span, and the gray rises with each channel, so the colors from every channel's lowest such level to every one's highest pass through each gray between them.
fn key_color(underlying: &[ChannelRanges]) -> String {
// The span of levels each channel shows most strongly, by itself
let span = |range: fn(&ChannelRanges) -> &BlendRange| {
let shown = |level: usize| underlying.iter().map(|ranges| range(ranges).weight(level as f64 / 255.)).product::<f64>();
let most = (0..256).map(shown).fold(0., f64::max);
let levels: Vec<usize> = (0..256).filter(|&level| shown(level) >= most).collect();
[levels.first().copied().unwrap_or(0), levels.last().copied().unwrap_or(255)].map(|level| level as f64)
};
let spans = [span(|ranges| &ranges.red), span(|ranges| &ranges.green), span(|ranges| &ranges.blue)];
// O(256 × ranges): the colors along the way from the lowest ends to the highest, which the gray's ranges show most strongly somewhere
let weight = |color: [f64; 3]| underlying.iter().map(|ranges| ranges.weight(color)).product::<f64>();
let color_at = |step: usize| spans.map(|[low, high]| (low + (high - low) * step as f64 / 255.).round() / 255.);
let best = (0..256).map(color_at).fold(color_at(0), |best, color| if weight(color) > weight(best) { color } else { best });
let [red, green, blue] = best.map(|channel| (channel * 255.).round() as u8);
format!("#{red:02x}{green:02x}{blue:02x}")
}
/// A weight for a table, with no more digits than it needs.
fn format_table_value(weight: f64) -> String {
let rounded = format!("{weight:.4}");
rounded.trim_end_matches('0').trim_end_matches('.').to_string()
}
/// Writes a mask into the render's defs that fades what's drawn in the current user space by how strongly the `underlying` ranges, which multiply, show what lies beneath, returning its reference, or `None` with nothing beneath to read.
/// `bounds` is the content's extent in this user space and `reach` how far its effects reach past it along each axis there.
pub(crate) fn underlying_mask(render: &mut SvgRender, underlying: &[ChannelRanges], bounds: [DVec2; 2], reach: DVec2, render_params: &RenderParams) -> Option<String> {
let mut markup = String::new();
let mut count = 0;
let mut push = |tag: &str, attributes: &str, children: &str| {
count += 1;
let result = format!("blend-if-{count}");
match children.is_empty() {
true => write!(markup, r#"<{tag} {attributes} result="{result}" />"#),
false => write!(markup, r#"<{tag} {attributes} result="{result}">{children}</{tag}>"#),
}
.unwrap();
result
};
// Each side's channels multiply, and so do the sides
let mut weight: Option<String> = None;
for ranges in underlying {
let Some(shown) = self::weight(&mut push, "SourceGraphic", ranges) else { continue };
weight = Some(match weight {
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
None => shown,
});
}
let weight = weight?;
// Where nothing lies beneath, nothing is hidden: the weight is 1 - alpha × (1 - weight)
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
let hidden = push("feComponentTransfer", &format!(r#"in="{weight}""#), invert);
let hidden_beneath = push("feComposite", &format!(r#"in="{hidden}" in2="SourceAlpha" operator="in""#), "");
push("feComponentTransfer", &format!(r#"in="{hidden_beneath}""#), invert);
// The mask covers how far the effects reach past the content, and a document pixel more for the pixels its edges cut through
let reach = reach + spans_along_axes(render.transform.matrix2.inverse());
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
// Each pixel reads only what lies beneath it, so an image of that reads nothing past the view
let copy = render.backdrop_copy(render_params, [min, max], 0., true)?;
// Where canvases and the GPU's images stand in for what lies beneath in a copy of its markup, it can't be read, so nothing there is hidden
let copy = match copy.image {
true => copy.markup,
false => with_unreadable_covered(&copy.markup, &key_color(underlying)),
};
let (filter_id, mask_id) = (format!("blend-if-{}", generate_uuid()), format!("blend-if-mask-{}", generate_uuid()));
write!(
render.svg_defs,
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region} color-interpolation-filters="sRGB">{markup}</filter><mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}><g filter="url(#{filter_id})">{copy}</g></mask>"#
)
.unwrap();
Some(format!("url(#{mask_id})"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_are_colors_the_ranges_show_in_full_where_no_gray_is() {
// Red from 60% up and blue up to 40%, which no gray passes both of
let mut ranges = ChannelRanges::default();
(ranges.red.falloff_start, ranges.red.range_start) = (60., 60.);
(ranges.blue.range_end, ranges.blue.falloff_end) = (40., 40.);
let key = key_color(&[ranges]);
let channel = |index: usize| u8::from_str_radix(&key[1 + 2 * index..3 + 2 * index], 16).unwrap() as f64 / 255.;
assert_eq!(ranges.weight([channel(0), channel(1), channel(2)]), 1., "{key}");
}
#[test]
fn copies_where_no_image_stands_in_cover_canvases_and_the_gpus_images_with_the_key_color() {
use crate::deferred_image::{DeferredImagePlacement, substitute_deferred_image};
use core_types::Color;
use core_types::blending::BlendMode;
use glam::DAffine2;
use graphic_types::raster_types::{Image, Raster};
let canvas = r#"<foreignObject x="1" y="2" width="3" height="4"><div data-canvas-placeholder="image-7"></div></foreignObject>"#;
let stand_in = r#"<!--deferred-image-9--><path d="M0,0" /><!--/deferred-image-9-->"#;
let covered = with_unreadable_covered(&format!("{canvas}{stand_in}"), "#000000");
// A canvas becomes a rectangle of the key color at its own placement, and the stand-in for the GPU's image is marked for one
assert!(covered.starts_with(r##"<rect x="1" y="2" width="3" height="4" fill="#000000" />"##), "{covered}");
assert!(covered.contains(r#"<!--deferred-cover-9-000000--><path d="M0,0" /><!--/deferred-cover-9-->"#), "{covered}");
// Once the GPU's image arrives in a canvas in place of the original stand-in, the rectangle replaces the copy's
let placement = DeferredImagePlacement {
id: 9,
transform: DAffine2::IDENTITY,
user_to_document: DAffine2::IDENTITY,
opacity: 1.,
blend_mode: BlendMode::Normal,
mask: None,
to_canvas: true,
canvas_image_scale: 1.,
};
let mut svg = format!("{covered}{stand_in}");
substitute_deferred_image(&mut svg, &mut Vec::new(), &placement, &Raster::new_cpu(Image::new(1, 1, Color::BLACK)));
assert!(svg.contains(r##"<rect width="1" height="1" transform="" fill="#000000" />"##) && !svg.contains("deferred-"), "{svg}");
}
}
@@ -613,7 +613,7 @@ impl<'a> VelloSceneBuilder<'a> {
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable();
if reads_backdrop {
if reads_backdrop && layers.reads_around_backdrop() {
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
let linear = effect_to_device.matrix2;
@@ -1437,8 +1437,20 @@ impl Gradient {
/// of it, since a map that isn't linear in the gradient's own space bends the ramp between the stops. Read the result with
/// [`GradientSpace::RgbGamma`] and [`GradientInterpolation::Linear`] in place of the space and interpolation in `settings`.
pub fn map_ramp(&self, settings: GradientSettings, map: impl Fn(Color) -> Color) -> Self {
self.map_ramp_anchored(settings, map, None::<fn(Color)>)
}
/// Like [`Gradient::map_ramp`], for a map that jumps wherever the `region` of the ramp's colors changes, as a cutoff on their levels does.
/// Scanning for each change at the finest spacing the resampling reaches keeps a region lying between its probes, and the colors on both sides anchor the change at one position.
pub fn map_ramp_by_regions<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: impl Fn(Color) -> R) -> Self {
self.map_ramp_anchored(settings, map, Some(region))
}
fn map_ramp_anchored<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: Option<impl Fn(Color) -> R>) -> Self {
/// Deeper than this, an interval is under 1/4096 of the ramp, too short to see a step in the mapped colors smear.
const MAX_DEPTH: u32 = 12;
/// How many times a change of region is narrowed down from the step of the scan it lies in, far closer than any renderer resolves.
const REGION_BISECTIONS: u32 = 32;
fn subdivide(ramp: &impl Fn(f64) -> Color, left: f64, right: f64, color_left: Color, color_right: Color, result: &mut Vec<GradientStop>, depth: u32) {
// Probe the quarter points as well as the center, since a map with a steep toe peaks its deviation off-center
@@ -1466,14 +1478,55 @@ impl Gradient {
let ramp = |position: f64| map(evaluator.evaluate(position));
// Each stop anchors its own color, keeping the jump between coincident stops, and a cyclic ramp's seam anchors at both ends
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, map(stop.color))).collect();
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, stop.color)).collect();
if settings.cyclic && anchors.first().is_some_and(|&(position, _)| position > 0.) {
anchors.insert(0, (0., ramp(0.)));
anchors.insert(0, (0., evaluator.evaluate(0.)));
}
if settings.cyclic && anchors.last().is_some_and(|&(position, _)| position < 1.) {
anchors.push((1., ramp(0.)));
anchors.push((1., evaluator.evaluate(0.)));
}
// Scanned for in steps of a 4096th of the ramp, each change of region anchors the colors on both its sides at one position
if let Some(region) = region {
let extent = anchors.first().zip(anchors.last()).map_or(0., |(&(first, _), &(last, _))| last - first);
let mut anchored = Vec::with_capacity(anchors.len());
for (index, &(left, color_left)) in anchors.iter().enumerate() {
anchored.push((left, color_left));
let Some(&(right, color_right)) = anchors.get(index + 1).filter(|&&(right, _)| right > left) else {
continue;
};
let steps = ((right - left) / extent * f64::from(1_u32 << MAX_DEPTH)).ceil().max(1.) as usize;
let (mut previous_position, mut previous_color, mut previous_region) = (left, color_left, region(color_left));
for step in 1..=steps {
let position = if step == steps { right } else { left + (right - left) * step as f64 / steps as f64 };
let color = if step == steps { color_right } else { evaluator.evaluate(position) };
let current_region = region(color);
if current_region != previous_region {
let (mut low, mut color_low, mut high, mut color_high) = (previous_position, previous_color, position, color);
for _ in 0..REGION_BISECTIONS {
let middle = (low + high) / 2.;
let color_middle = evaluator.evaluate(middle);
if region(color_middle) == previous_region {
(low, color_low) = (middle, color_middle);
} else {
(high, color_high) = (middle, color_middle);
}
}
anchored.extend([(high, color_low), (high, color_high)]);
}
(previous_position, previous_color, previous_region) = (position, color, current_region);
}
}
anchors = anchored;
}
let anchors: Vec<(f64, Color)> = anchors.into_iter().map(|(position, color)| (position, map(color))).collect();
let mut result = Vec::new();
for (index, &(position, color)) in anchors.iter().enumerate() {
result.push(GradientStop { position, midpoint: 0.5, color });
@@ -0,0 +1,72 @@
// Blend If's passes, appended to the effect passes: ranges of each channel's levels that a pixel shows within, matching `graphic_types::blend_if`
// How near a cutoff a channel may lie and still count as reaching it, matching `CUTOFF_TOLERANCE`
const BLEND_IF_CUTOFF_TOLERANCE: f32 = 1. / 1024.;
// Each channel's nearest of 256 levels, with halves rounding up, matching `channel_level`
fn blend_if_levels(color: vec3<f32>) -> vec3<u32> {
return vec3<u32>(floor(clamp(color, vec3<f32>(0.), vec3<f32>(1.)) * 255. + 0.5));
}
// One side of a range, rising across the span between its falloff and range ends (or falling, if not `rising`), or cutting off sharply where they meet
fn blend_if_side(value: f32, falloff: f32, range: f32, rising: bool) -> f32 {
let low = min(falloff, range);
let high = max(falloff, range);
if high - low > BLEND_IF_CUTOFF_TOLERANCE {
return clamp(select(high - value, value - low, rising) / (high - low), 0., 1.);
}
return select(f32(value <= high + BLEND_IF_CUTOFF_TOLERANCE), f32(value >= low - BLEND_IF_CUTOFF_TOLERANCE), rising);
}
// How strongly a range of (falloff start, range start, range end, falloff end) shows a channel's value
fn blend_if_range(value: f32, edges: vec4<f32>) -> f32 {
return blend_if_side(value, edges.x, edges.y, true) * blend_if_side(value, edges.w, edges.z, false);
}
// How strongly the ranges in the first four taps (gray, red, green, and blue) show a premultiplied pixel, by its straight color
fn blend_if_weight(pixel: vec4<f32>) -> f32 {
var color = vec3<f32>(0.);
if pixel.a > 0. {
color = pixel.rgb / pixel.a;
}
// The gray in whole numbers, rounding halves up, matching `gray_level`
let levels = blend_if_levels(color);
let channels = vec3<f32>(levels) / 255.;
let gray = f32((30u * levels.r + 59u * levels.g + 11u * levels.b + 50u) / 100u) / 255.;
let gray_weight = blend_if_range(gray, parameters.taps[0]);
let red_weight = blend_if_range(channels.r, parameters.taps[1]);
let green_weight = blend_if_range(channels.g, parameters.taps[2]);
let blue_weight = blend_if_range(channels.b, parameters.taps[3]);
return gray_weight * red_weight * green_weight * blue_weight;
}
// How strongly the ranges in the taps show each pixel of the content (`source`), by its own colors
@fragment
fn blend_if_content_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(blend_if_weight(textureLoad(source, vec2<i32>(position.xy), 0)));
}
// How strongly the ranges in the taps show each pixel by what lies beneath it, sampled from the scene's backdrop (`source`) where it lands as `sample_backdrop` places it.
// With `values.z` 1 it multiplies the weight so far in `secondary`, and with `values.w` 1 it eases to full where nothing lies beneath, matching `underlying_weight`.
@fragment
fn blend_if_underlying_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let point = backdrop_point(position.xy);
let backdrop = textureSampleLevel(source, linear_sampler, point / vec2<f32>(textureDimensions(source)), 0.);
var weight = blend_if_weight(backdrop);
if parameters.values.z > 0.5 {
weight *= textureLoad(secondary, vec2<i32>(position.xy), 0).r;
}
if parameters.values.w > 0.5 {
weight = 1. - backdrop.a * (1. - weight);
}
return vec4<f32>(weight);
}
// An image (`source`) faded by the weight in `secondary`
@fragment
fn blend_if_fade(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let pixel = vec2<i32>(position.xy);
return textureLoad(source, pixel, 0) * textureLoad(secondary, pixel, 0).r;
}
@@ -6,6 +6,7 @@ use core_types::Color;
use core_types::blending::BlendMode;
use core_types::transfer_curve::TransferCurve;
use glam::{DAffine2, DVec2, UVec2};
use graphic_types::blend_if::{blend_ifs_acting_before, fades_content, underlying_ranges};
use graphic_types::effect_layers::{EffectLayers, EffectPiece, LayerPart, PiecePlace, is_pixel_filter};
use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GRADIENT_TABLE_SIZE, GlowFill, OutlineFill, bevel_light, contour_gradient_span, grow_and_tent, outline_extents, shadow_offset};
use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels};
@@ -18,6 +19,7 @@ use std::sync::{Mutex, PoisonError};
use vello_gpu::kurbo::Affine;
use wgpu::util::DeviceExt;
mod blend_if;
mod filters;
mod masks;
mod resample;
@@ -165,7 +167,7 @@ impl EffectPasses {
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
}
// The filters', resampling, styles', and masks' passes live in files of their own, sharing this one's bindings and helpers
// The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("vello_effects.wgsl"),
source: wgpu::ShaderSource::Wgsl(
@@ -176,7 +178,8 @@ impl EffectPasses {
include_str!("vello_resample.wgsl"),
include_str!("vello_warp.wgsl"),
include_str!("vello_styles.wgsl"),
include_str!("vello_masks.wgsl")
include_str!("vello_masks.wgsl"),
include_str!("vello_blend_if.wgsl")
)
.into(),
),
@@ -304,30 +307,43 @@ impl EffectPasses {
let mut pieces: HashMap<EffectCapture, wgpu::Texture> = HashMap::new();
// How much the trailing masks together show of each finished layer
let mut layer_fade: Option<wgpu::Texture> = None;
// How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it
let mut blend_if_weight: Option<wgpu::Texture> = None;
// How strongly all the masks together show the content, which they show what lies beneath it by too
let mut masks_strength: Option<wgpu::Texture> = None;
// A captured coverage ends the passes in place of the effects' result, once the content's layer is finished if its knockout or share depends on that
let mut captured: Option<wgpu::Texture> = None;
let captured_piece = capture.and_then(|capture| layers.piece(capture)).map(|(_, piece)| piece);
// At a full fill, the content's own layer has exactly the full-strength content's alpha, so knocking out a piece within it again changes nothing
let knocks_out_by_layer = |piece: &EffectPiece| piece.knocks_out && (fill < 1. || layers.knockout_cover(piece.capture, opacity) < 1. || layers.masks_fade_knockout_cover(piece.capture));
let every_operation: Vec<EffectOperation> = effects.operations().collect();
// Unless a fill or a Blend If fades the content, its own layer has exactly the full-strength content's alpha, so knocking out a piece within it again changes nothing
let content_faded = fill < 1. || fades_content(&every_operation);
let knocks_out_by_layer = |piece: &EffectPiece| piece.knocks_out && (content_faded || layers.knockout_cover(piece.capture, opacity) < 1. || layers.masks_fade_knockout_cover(piece.capture));
let capture_needs_content_layer = capture == Some(EffectCapture::THROUGH_MASK) || captured_piece.as_ref().is_some_and(knocks_out_by_layer);
// Each operation with its index, for a capture to name, leaving out those that change nothing so they don't split the runs of adjustments around them.
// A blur whose result is captured runs however slight, so its map still holds the content.
let captured_blur =
|index: usize, operation: &EffectOperation| matches!(operation, EffectOperation::Blur { .. }) && !operation.changes_nothing() && capture.is_some_and(|capture| capture.index == index);
let operations: Vec<(usize, EffectOperation)> = (effects.operations().enumerate())
let operations: Vec<(usize, EffectOperation)> = (every_operation.iter().cloned().enumerate())
.filter(|(index, operation)| captured_blur(*index, operation) || !changes_nothing(operation, length_scale))
.collect();
let mut paints = paints.iter();
// The rows left out still start stretches that Blend Ifs act at the start of
let mut rows_reached = 0;
for (position, (index, operation)) in operations.iter().enumerate() {
let index = *index;
let acting_blend_ifs = (rows_reached..=index).flat_map(|row| blend_ifs_acting_before(&every_operation, row));
for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) {
blend_if_weight = Some(recorder.blend_if_content(&ranges.content, full.as_ref().unwrap_or(content), &mut filled, blend_if_weight.take()));
}
rows_reached = index + 1;
// A layered effect's coverages become pieces, which the content knocks out once its layer is finished, and a flattened one is knocked out by the faded content now
let layered = index >= layers.flattened;
let piece = |plane: usize| EffectCapture { index, plane };
let knockout_fill = if layered { 1. } else { fill };
let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered);
// A coverage is captured in black, and an already tinted image as it is
let mut capture_plane = |recorder: &mut PassRecorder, plane: usize, coverage: &wgpu::Texture, tinted: bool| {
@@ -393,26 +409,21 @@ impl EffectPasses {
}
}
// The full-strength content is read by a later operation, as the unfaded result, or as a box blur's map, and capturing one plane ends the passes
// SVG takes a box's results as maps of planes 0 and 1, having no box of each pixel's own width, and a Gaussian's after a Blend If as 1 and 2 (see `masked_radius_blur_takes_maps`)
let (full_plane, filled_plane) = if box_blur { (0, 1) } else { (1, 2) };
// The full-strength content is read by a later operation, as the unfaded result, or as a map, and capturing one plane ends the passes
let captures_only = |plane: usize| capture == Some(piece(plane)) && !capture_needs_content_layer;
let full_is_read = !captures_only(1) && (filled.is_none() || position + 1 < operations.len() || (box_blur && capture == Some(piece(0))));
let full_is_read = !captures_only(filled_plane) && (filled.is_none() || position + 1 < operations.len() || capture == Some(piece(full_plane)));
if captures_only(full_plane)
&& let Some(filled) = filled.take()
{
recorder.textures.release(filled);
}
match box_blur {
true => {
if captures_only(0)
&& let Some(filled) = filled.take()
{
recorder.textures.release(filled);
}
let radius = DVec2::splat(radius * length_scale);
recorder.masked_box_blur(content, &mut full, &mut filled, &luminance, radius, !gamma, full_is_read);
// SVG has no box of each pixel's own width, so it takes the results as maps
if let Some(full) = &full {
capture_plane(&mut recorder, 0, full, true);
}
if let Some(filled) = &filled {
capture_plane(&mut recorder, 1, filled, true);
}
}
false => {
let levels: Vec<f64> = masked_radius_blur_levels(radius, length_scale).into_iter().map(|level| level * length_scale).collect();
@@ -420,6 +431,13 @@ impl EffectPasses {
}
}
recorder.textures.release(luminance);
if let Some(full) = &full {
capture_plane(&mut recorder, full_plane, full, true);
}
if let Some(filled) = &filled {
capture_plane(&mut recorder, filled_plane, filled, true);
}
}
EffectOperation::DropShadow {
color,
@@ -435,7 +453,7 @@ impl EffectPasses {
let silhouette = recorder.silhouette(full_content, lengths_to_pixels * shadow_offset(angle, distance), false);
let mut strength = recorder.cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, length_scale);
if knockout {
strength = recorder.knock_out(strength, full_content, knockout_fill);
strength = recorder.knock_out(strength, full_content, knockout_fill, knockout_weight);
}
capture_plane(&mut recorder, 0, &strength, false);
recorder.place_beneath(layered.then_some((&mut pieces, piece(0))), &mut beneath, strength, Some(color));
@@ -474,7 +492,7 @@ impl EffectPasses {
};
[Some(raw), shaped].into_iter().flatten().for_each(|texture| recorder.textures.release(texture));
let coverage = recorder.knock_out(coverage, full_content, knockout_fill);
let coverage = recorder.knock_out(coverage, full_content, knockout_fill, knockout_weight);
capture_plane(&mut recorder, 0, &coverage, color.is_none());
recorder.place_beneath(layered.then_some((&mut pieces, piece(0))), &mut beneath, coverage, color);
}
@@ -614,7 +632,7 @@ impl EffectPasses {
// The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow
if let Some(band) = bands.outside {
let band = recorder.knock_out(band, full.as_ref().unwrap_or(content), knockout_fill);
let band = recorder.knock_out(band, full.as_ref().unwrap_or(content), knockout_fill, knockout_weight);
capture_plane(&mut recorder, 0, &band, false);
let band = painted(&mut recorder, band);
@@ -728,12 +746,14 @@ impl EffectPasses {
};
brighter.into_iter().for_each(|brighter| recorder.textures.release(brighter));
for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() {
let amount = recorder.knock_out(amount, full.as_ref().unwrap_or(content), knockout_fill);
let amount = recorder.knock_out(amount, full.as_ref().unwrap_or(content), knockout_fill, knockout_weight);
capture_plane(&mut recorder, plane + 2, &amount, false);
recorder.place_beneath(layered.then_some((&mut pieces, piece(plane + 2))), &mut beneath, amount, Some(color));
}
recorder.textures.release(height);
}
// Blend If fades the content where it acts, and the layers once they're drawn
EffectOperation::BlendIf(_) => {}
// What lies beneath, blurred, is always a piece at the bottom of the content's own layer
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => {
let Some((backdrop, placement)) = backdrop else { continue };
@@ -924,7 +944,7 @@ impl EffectPasses {
let Some(frame) = &frame else { continue };
let Some(screens) = HalftoneScreen::of(operation, frame) else { continue };
// Each texel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots
// Each texel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
let shares = (filled.as_ref()).map(|filled| {
recorder.run(
@@ -1007,7 +1027,7 @@ impl EffectPasses {
}
}
if let Some(captured) = captured.take_if(|_| !capture_needs_content_layer) {
let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values());
let textures = [full, filled, beneath, layer_fade, blend_if_weight, masks_strength].into_iter().flatten().chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
return vec![(captured, BlendMode::Normal)];
@@ -1016,7 +1036,7 @@ impl EffectPasses {
// A coverage the passes never reached, like that of a band too thin to draw at this resolution, covers nothing
if capture.is_some_and(|capture| capture != EffectCapture::THROUGH_MASK) && captured.is_none() {
let empty = recorder.scale(full.as_ref().unwrap_or(content), 0.);
let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values());
let textures = [full, filled, beneath, layer_fade, blend_if_weight, masks_strength].into_iter().flatten().chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
return vec![(empty, BlendMode::Normal)];
@@ -1085,7 +1105,7 @@ impl EffectPasses {
// A coverage too small to draw, like an outline's band at a far zoom, covers nothing
_ => recorder.run("flood", WORKING_FORMAT, recorder.size, full_content, None, None, Parameters::default()),
};
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade, masks_strength]
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade, blend_if_weight, masks_strength]
.into_iter()
.flatten()
.chain(pieces.into_values());
@@ -1182,7 +1202,13 @@ impl EffectPasses {
results.push((result, layer.blend_mode));
}
let textures = [full, content_image, beneath, content_with_fade, layer_fade, masks_strength]
// Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them
let underlying = underlying_ranges(&every_operation);
if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) {
recorder.blend_if_underlying(&underlying, backdrop, &mut results);
}
let textures = [full, content_image, beneath, content_with_fade, layer_fade, blend_if_weight, masks_strength]
.into_iter()
.flatten()
.chain(pieces.into_values());
@@ -1666,13 +1692,17 @@ impl PassRecorder<'_> {
texture
}
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 fades the content that shows over it.
fn knock_out(&mut self, coverage: wgpu::Texture, full_content: &wgpu::Texture, fill: f32) -> wgpu::Texture {
if fill >= 1. {
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
fn knock_out(&mut self, coverage: wgpu::Texture, full_content: &wgpu::Texture, fill: f32, blend_if_weight: Option<&wgpu::Texture>) -> wgpu::Texture {
if fill >= 1. && blend_if_weight.is_none() {
return coverage;
}
let parameters = Parameters { amount: fill, ..Default::default() };
let knocked_out = self.run("knock_out", coverage.format(), self.size, &coverage, None, Some(full_content), parameters);
let parameters = Parameters {
amount: fill,
values: [if blend_if_weight.is_some() { 1. } else { 0. }, 0., 0., 0.],
..Default::default()
};
let knocked_out = self.run("knock_out", coverage.format(), self.size, &coverage, blend_if_weight, Some(full_content), parameters);
self.textures.release(coverage);
knocked_out
}
@@ -306,13 +306,17 @@ fn tint(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return parameters.color * textureLoad(source, vec2<i32>(position.xy), 0).r;
}
// Hides the coverage of what lies beneath behind the `content` at full strength, where the fill `amount` fades the content showing over it.
// Hides the coverage of what lies beneath behind the `content` at full strength, where the fill `amount` (times the Blend If weight in `secondary`, with `values.x` 1) fades the content showing over it.
// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this.
@fragment
fn knock_out(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let pixel = vec2<i32>(position.xy);
let alpha = textureLoad(content, pixel, 0).a;
let shown = (1. - alpha) / max(1. - parameters.amount * alpha, 1e-6);
var fill = parameters.amount;
if parameters.values.x > 0.5 {
fill *= textureLoad(secondary, pixel, 0).r;
}
let shown = (1. - alpha) / max(1. - fill * alpha, 1e-6);
return textureLoad(source, pixel, 0) * shown;
}
@@ -0,0 +1,63 @@
//! Blend If's GPU passes, which fade the content by its own colors and every layer by the colors of what lies beneath, matching the CPU's and the SVG filters' weights.
use super::{COVERAGE_FORMAT, PARAMETER_TAPS, Parameters, PassRecorder, WORKING_FORMAT};
use core_types::blending::BlendMode;
use graphic_types::blend_if::ChannelRanges;
use vello_gpu::kurbo::Affine;
/// The ranges in the shader's first four taps, gray, red, green, and blue, each its falloff start, range start, range end, and falloff end from 0 to 1.
fn range_taps(ranges: &ChannelRanges) -> [[f32; 4]; PARAMETER_TAPS] {
let mut taps = [[0.; 4]; PARAMETER_TAPS];
for (tap, (_, range)) in taps.iter_mut().zip(ranges.channels()) {
*tap = [range.falloff_start, range.range_start, range.range_end, range.falloff_end].map(|percent| (percent / 100.) as f32);
}
taps
}
impl PassRecorder<'_> {
/// Fades the content's image (`filled`, or a copy of `full` if the fill fades nothing) by how strongly the `ranges` show the colors of `full`.
/// Returns that weight times the `weight` so far, which the knockouts hide what's beneath behind.
pub(super) fn blend_if_content(&mut self, ranges: &ChannelRanges, full: &wgpu::Texture, filled: &mut Option<wgpu::Texture>, weight: Option<wgpu::Texture>) -> wgpu::Texture {
let parameters = Parameters {
taps: range_taps(ranges),
..Default::default()
};
let shown = self.run("blend_if_content_weight", COVERAGE_FORMAT, self.size, full, None, None, parameters);
let faded = self.run("blend_if_fade", WORKING_FORMAT, self.size, filled.as_ref().unwrap_or(full), Some(&shown), None, Parameters::default());
self.replace_or_fill(filled, faded);
let Some(weight) = weight else { return shown };
let combined = self.run("blend_if_fade", COVERAGE_FORMAT, self.size, &weight, Some(&shown), None, Parameters::default());
self.textures.release(weight);
self.textures.release(shown);
combined
}
/// Fades each layer's image in `results` by how strongly the `underlying` ranges, which multiply, show what lies beneath each pixel in the scene's `backdrop`.
/// The backdrop's placement maps the layers' pixels into it.
pub(super) fn blend_if_underlying(&mut self, underlying: &[ChannelRanges], (backdrop, placement): (&wgpu::Texture, Affine), results: &mut [(wgpu::Texture, BlendMode)]) {
let placed = Parameters::placed_in_backdrop(placement);
let [x, y, ..] = placed.values;
// Each range multiplies the weight before it, and the last eases it to full where nothing lies beneath
let mut weight: Option<wgpu::Texture> = None;
for (index, ranges) in underlying.iter().enumerate() {
let flag = |set: bool| if set { 1. } else { 0. };
let parameters = Parameters {
values: [x, y, flag(weight.is_some()), flag(index + 1 == underlying.len())],
taps: range_taps(ranges),
..placed
};
let next = self.run("blend_if_underlying_weight", COVERAGE_FORMAT, self.size, backdrop, weight.as_ref(), None, parameters);
self.replace_or_fill(&mut weight, next);
}
let Some(weight) = weight else { return };
for (image, _) in results {
let faded = self.run("blend_if_fade", WORKING_FORMAT, self.size, image, Some(&weight), None, Parameters::default());
self.replace(image, faded);
}
self.textures.release(weight);
}
}
File diff suppressed because it is too large. Load diff
+259
View File
@@ -0,0 +1,259 @@
use core_types::list::Item;
use core_types::{Color, Ctx};
use graphic_types::blend_if::{BlendIfRanges, BlendRange, ChannelRanges};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{BlendIfChannel, Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
use vector_types::Gradient;
/// Shows the content only where the levels of its own colors, and those of what lies beneath it, fall within ranges, fading it out across each range's falloffs.
/// The content's own ranges fade it like its fill does, leaving the shadows and glows cast from it, while the ranges beneath fade everything it draws like its opacity does. The gray, red, green, and blue channels' ranges all apply together.
#[node_macro::node(category("Graphic"), inspector("blend_if_inspector"))]
fn blend_if<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// Hides the content where its gray level falls below this, fading it in from here to the range start.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
content_falloff_start: Item<f64>,
/// Shows the content fully where its gray level is at least this, up to the range end.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
content_range_start: Item<f64>,
/// Shows the content fully where its gray level is at most this, down to the range start.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
content_range_end: Item<f64>,
/// Hides the content where its gray level rises above this, fading it in from here to the range end.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
content_falloff_end: Item<f64>,
/// Hides the content and its effects where the gray level of what lies beneath it falls below this, fading it in from here to the range start.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
underlying_falloff_start: Item<f64>,
/// Shows the content and its effects fully where the gray level of what lies beneath it is at least this, up to the range end.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
underlying_range_start: Item<f64>,
/// Shows the content and its effects fully where the gray level of what lies beneath it is at most this, down to the range start.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
underlying_range_end: Item<f64>,
/// Hides the content and its effects where the gray level of what lies beneath it rises above this, fading it in from here to the range end.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
underlying_falloff_end: Item<f64>,
/// Hides the content where its red level falls below this, fading it in from here to the range start.
#[name("(Red) Content Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
red_content_falloff_start: Item<f64>,
/// Shows the content fully where its red level is at least this, up to the range end.
#[name("(Red) Content Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
red_content_range_start: Item<f64>,
/// Shows the content fully where its red level is at most this, down to the range start.
#[name("(Red) Content Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
red_content_range_end: Item<f64>,
/// Hides the content where its red level rises above this, fading it in from here to the range end.
#[name("(Red) Content Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
red_content_falloff_end: Item<f64>,
/// Hides the content and its effects where the red level of what lies beneath it falls below this, fading it in from here to the range start.
#[name("(Red) Underlying Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
red_underlying_falloff_start: Item<f64>,
/// Shows the content and its effects fully where the red level of what lies beneath it is at least this, up to the range end.
#[name("(Red) Underlying Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
red_underlying_range_start: Item<f64>,
/// Shows the content and its effects fully where the red level of what lies beneath it is at most this, down to the range start.
#[name("(Red) Underlying Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
red_underlying_range_end: Item<f64>,
/// Hides the content and its effects where the red level of what lies beneath it rises above this, fading it in from here to the range end.
#[name("(Red) Underlying Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
red_underlying_falloff_end: Item<f64>,
/// Hides the content where its green level falls below this, fading it in from here to the range start.
#[name("(Green) Content Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
green_content_falloff_start: Item<f64>,
/// Shows the content fully where its green level is at least this, up to the range end.
#[name("(Green) Content Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
green_content_range_start: Item<f64>,
/// Shows the content fully where its green level is at most this, down to the range start.
#[name("(Green) Content Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
green_content_range_end: Item<f64>,
/// Hides the content where its green level rises above this, fading it in from here to the range end.
#[name("(Green) Content Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
green_content_falloff_end: Item<f64>,
/// Hides the content and its effects where the green level of what lies beneath it falls below this, fading it in from here to the range start.
#[name("(Green) Underlying Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
green_underlying_falloff_start: Item<f64>,
/// Shows the content and its effects fully where the green level of what lies beneath it is at least this, up to the range end.
#[name("(Green) Underlying Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
green_underlying_range_start: Item<f64>,
/// Shows the content and its effects fully where the green level of what lies beneath it is at most this, down to the range start.
#[name("(Green) Underlying Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
green_underlying_range_end: Item<f64>,
/// Hides the content and its effects where the green level of what lies beneath it rises above this, fading it in from here to the range end.
#[name("(Green) Underlying Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
green_underlying_falloff_end: Item<f64>,
/// Hides the content where its blue level falls below this, fading it in from here to the range start.
#[name("(Blue) Content Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
blue_content_falloff_start: Item<f64>,
/// Shows the content fully where its blue level is at least this, up to the range end.
#[name("(Blue) Content Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
blue_content_range_start: Item<f64>,
/// Shows the content fully where its blue level is at most this, down to the range start.
#[name("(Blue) Content Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
blue_content_range_end: Item<f64>,
/// Hides the content where its blue level rises above this, fading it in from here to the range end.
#[name("(Blue) Content Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
blue_content_falloff_end: Item<f64>,
/// Hides the content and its effects where the blue level of what lies beneath it falls below this, fading it in from here to the range start.
#[name("(Blue) Underlying Falloff Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
blue_underlying_falloff_start: Item<f64>,
/// Shows the content and its effects fully where the blue level of what lies beneath it is at least this, up to the range end.
#[name("(Blue) Underlying Range Start")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(0.)]
blue_underlying_range_start: Item<f64>,
/// Shows the content and its effects fully where the blue level of what lies beneath it is at most this, down to the range start.
#[name("(Blue) Underlying Range End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
blue_underlying_range_end: Item<f64>,
/// Hides the content and its effects where the blue level of what lies beneath it rises above this, fading it in from here to the range end.
#[name("(Blue) Underlying Falloff End")]
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
blue_underlying_falloff_end: Item<f64>,
/// Which channel's ranges are shown for editing.
_channel: Item<BlendIfChannel>,
) -> Item<T> {
let range = |falloff_start: Item<f64>, range_start: Item<f64>, range_end: Item<f64>, falloff_end: Item<f64>| BlendRange {
falloff_start: falloff_start.into_element(),
range_start: range_start.into_element(),
range_end: range_end.into_element(),
falloff_end: falloff_end.into_element(),
};
let ranges = BlendIfRanges {
content: ChannelRanges {
gray: range(content_falloff_start, content_range_start, content_range_end, content_falloff_end),
red: range(red_content_falloff_start, red_content_range_start, red_content_range_end, red_content_falloff_end),
green: range(green_content_falloff_start, green_content_range_start, green_content_range_end, green_content_falloff_end),
blue: range(blue_content_falloff_start, blue_content_range_start, blue_content_range_end, blue_content_falloff_end),
},
underlying: ChannelRanges {
gray: range(underlying_falloff_start, underlying_range_start, underlying_range_end, underlying_falloff_end),
red: range(red_underlying_falloff_start, red_underlying_range_start, red_underlying_range_end, red_underlying_falloff_end),
green: range(green_underlying_falloff_start, green_underlying_range_start, green_underlying_range_end, green_underlying_falloff_end),
blue: range(blue_underlying_falloff_start, blue_underlying_range_start, blue_underlying_range_end, blue_underlying_falloff_end),
},
};
let mut content = content;
stamp_effect(&mut content, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
content
}
+26
View File
@@ -971,4 +971,30 @@ mod test {
}
}
}
#[test]
fn paint_overlay_fades_a_color_paint_by_its_own_blend_ifs() {
use graphic_types::blend_if::BlendIfRanges;
use graphic_types::{Effect, EffectOperation, stamp_effect};
// A black paint shown only where its gray is at least half, so it paints nothing
let mut hides_darks = BlendIfRanges::default();
hides_darks.content.gray.falloff_start = 50.;
hides_darks.content.gray.range_start = 50.;
let mut paint = Item::new_from_element(Color::BLACK);
stamp_effect(&mut paint, Effect::new(&EffectOperation::BlendIf(Box::new(hides_darks))));
let result = super::paint_overlay(
(),
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
Item::new_from_element(Graphic::from(paint)),
BlendMode::Normal.into(),
100_f64.into(),
false.into(),
DAffine2::IDENTITY.into(),
);
let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0];
assert!(color.r() > 0.99, "the hidden black paint leaves {color:?}");
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod backdrop;
pub mod blend_if;
pub mod distortions;
pub mod effects;
pub mod filters;
+27 -6
View File
@@ -9,7 +9,6 @@ use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Effects, Generator, Vector};
use rand::SeedableRng;
use rand::seq::SliceRandom;
use raster_kernels::adjustments::PreparedAdjustment;
use raster_kernels::value_effects;
use raster_types::{CPU, GPU, Raster};
use std::cmp::Ordering;
@@ -1168,13 +1167,14 @@ fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
#[node_macro::node(category("Gradient"), icon("NodeGradientToColors"), name("Gradient to Colors"))]
fn gradient_to_colors(_: impl Ctx, gradient: Item<Gradient>) -> List<Color> {
// The adjustments the gradient carries change each stop's color
let adjustments = gradient.attribute::<Effects>(ATTR_EFFECTS).map(value_effects::adjustments).unwrap_or_default();
let adjustments: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
// The effects the gradient carries, like adjustments and Blend Ifs, change each stop's color
let after_effects = gradient.attribute::<Effects>(ATTR_EFFECTS).map(value_effects::prepared_color_after_effects);
let mut colors = gradient.into_element().into_color_list();
for color in colors.iter_element_values_mut() {
*color = adjustments.iter().fold(*color, |color, adjustment| adjustment.adjust(color));
if let Some(after_effects) = after_effects {
for color in colors.iter_element_values_mut() {
*color = after_effects(*color);
}
}
colors
}
@@ -1421,4 +1421,25 @@ mod test {
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone()))));
assert_eq!(restored.element(), &gradient, "a default ramp should round trip without gaining attributes it never had");
}
#[test]
fn gradient_to_colors_fades_each_stop_by_the_blend_ifs_the_gradient_carries() {
use graphic_types::EffectOperation;
use graphic_types::blend_if::BlendIfRanges;
// Shown only where the gray is at least half
let mut hides_darks = BlendIfRanges::default();
hides_darks.content.gray.falloff_start = 50.;
hides_darks.content.gray.range_start = 50.;
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(hides_darks))]);
let mut gradient = Gradient::from(vec![Color::BLACK, Color::WHITE]);
gradient.set_positions(&[0.25, 0.75]);
let colors = gradient_to_colors((), Item::new_from_element(gradient).with_attribute(ATTR_EFFECTS, effects));
assert_eq!(elements(&colors), [Color::BLACK.with_alpha(0.), Color::WHITE], "the dark stop should be hidden and the light one shown");
let mut expected = Gradient::from(vec![Color::BLACK.with_alpha(0.), Color::WHITE]);
expected.set_positions(&[0.25, 0.75]);
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
}
}
+2 -2
View File
@@ -14,8 +14,8 @@ pub use graphene_core;
pub use graphene_core::debug;
pub use graphic_nodes;
pub use graphic_types::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, Graphic, MaskMode,
MinimumMaximumMode, NoiseDistribution, Vector, stamp_coverage,
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique,
Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector, stamp_coverage,
};
pub use graphic_types::{DisplaceMode, RadialBlurMethod, WarpStyle, WaveType};
pub use math_nodes;