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

@@ -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