Fix how Darker Color, Lighter Color, Hard Mix, and Color Dodge blend (#5066)

This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-03 14:48:39 -08:00
1 parent e30bf2e987
commit 7c37cc504b
7 files changed
+101 -35

No files matched your search

@@ -261,9 +261,13 @@ mod tests {
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
}
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
// Divide also turns any other white under a black source.
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
}
for source in [1., 1. - 1e-7, 1. + 2e-7] {
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
}
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
@@ -339,6 +343,38 @@ mod tests {
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
}
#[test]
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
// Where the lumas tie, the backdrop stays, with the paint's alpha
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
}
#[test]
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
// At full strength, white past a sum of 1 and black short of it, even a level away
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
let half = hard_mix(backdrop, source, 128. / 255.);
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
}
}
#[test]
fn source_over_weights_straight_colors_by_alpha() {
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
@@ -633,14 +633,20 @@ impl Color {
c_b + c_s - 1.
}
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
#[inline(always)]
pub fn blend_darker_color(&self, other: Color) -> Color {
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
darker.with_alpha(other.alpha)
}
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
#[inline(always)]
fn blend_luma(&self) -> f32 {
luma_rec_601_rounded(self.red, self.green, self.blue)
}
/// Per-channel "Screen" blend.
#[inline(always)]
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
@@ -653,10 +659,16 @@ impl Color {
c_s.max(c_b)
}
/// Per-channel "Color Dodge" blend.
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
#[inline(always)]
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
0.
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
1.
} else {
(c_b / (1. - c_s)).min(1.)
}
}
/// Per-channel "Linear Dodge" (Add) blend.
@@ -665,10 +677,10 @@ impl Color {
c_b + c_s
}
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
#[inline(always)]
pub fn blend_lighter_color(&self, other: Color) -> Color {
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
lighter.with_alpha(other.alpha)
}
@@ -724,9 +736,15 @@ impl Color {
}
}
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
}
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
(c_b - steepness * (1. - c_s)) / (1. - steepness)
}
/// Per-channel "Difference" blend.
@@ -3,6 +3,7 @@
use crate::effect_kernels::Plane;
use core_types::blending::BlendMode;
use core_types::color::BLEND_EDGE_TOLERANCE;
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
@@ -56,8 +57,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
BlendMode::Overlay => hard_light(source, backdrop),
BlendMode::Darken => backdrop.min(source),
BlendMode::Lighten => backdrop.max(source),
BlendMode::ColorDodge if backdrop <= 0. => 0.,
BlendMode::ColorDodge if source >= 1. => 1.,
BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
BlendMode::ColorBurn if backdrop >= 1. => 1.,
BlendMode::ColorBurn if source <= 0. => 0.,
+10 -13
View File
@@ -1619,18 +1619,18 @@ impl SvgFilterPrimitives {
let doubled = |primitives: &mut Self| transfer(primitives, &source, r#"type="linear" slope="2""#);
let doubled_less_one = |primitives: &mut Self| transfer(primitives, &source, r#"type="linear" slope="2" intercept="-1""#);
// Whichever of the backdrop or source has the lower mean channel, or the higher if `lighter`
let pick_by_mean = |primitives: &mut Self, lighter: bool| {
let mean = |primitives: &mut Self, input: &str| {
// Whichever of the backdrop or source has the lower luma, or the higher if `lighter`
let pick_by_luma = |primitives: &mut Self, lighter: bool| {
let luma = |primitives: &mut Self, input: &str| {
primitives.push(
"feColorMatrix",
&format!(r#"in="{input}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3333 0.3333 0.3334 0 0" {space}"#),
&format!(r#"in="{input}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0" {space}"#),
"",
)
};
let (backdrop_mean, source_mean) = (mean(primitives, &backdrop), mean(primitives, &source));
let (backdrop_luma, source_luma) = (luma(primitives, &backdrop), luma(primitives, &source));
// Half the difference past a middle, in alpha, which a step turns into where the backdrop wins
let difference = arithmetic(primitives, &backdrop_mean, &source_mean, [0., 0.5, -0.5, 0.5]);
let difference = arithmetic(primitives, &backdrop_luma, &source_luma, [0., 0.5, -0.5, 0.5]);
let steps = if lighter { "0 1" } else { "1 0" };
let backdrop_wins = primitives.push(
"feComponentTransfer",
@@ -1657,11 +1657,8 @@ impl SvgFilterPrimitives {
let darkened = blend(self, &doubled, &backdrop, "darken");
blend(self, &doubled_less_one, &darkened, "lighten")
}
// Linear Light thresholded at a half, which a third of the backdrop plus two thirds of the source reaches at the same point
BlendMode::HardMix => {
let mean = arithmetic(self, &source, &backdrop, [0., 2. / 3., 1. / 3., 0.]);
transfer(self, &mean, r#"type="discrete" tableValues="0 1""#)
}
// A ramp a 256th wide around where the channels sum to 1
BlendMode::HardMix => arithmetic(self, &source, &backdrop, [0., 255., 256., -255.]),
// Color Burn by twice the source where it's dark, and Color Dodge by twice it less one where it's light
BlendMode::VividLight => {
let (doubled, doubled_less_one) = (doubled(self), doubled_less_one(self));
@@ -1673,8 +1670,8 @@ impl SvgFilterPrimitives {
let dodged = arithmetic(self, &dodged, &light, [1., 0., 0., 0.]);
arithmetic(self, &burned, &dodged, [0., 1., 1., 0.])
}
BlendMode::DarkerColor => pick_by_mean(self, false),
BlendMode::LighterColor => pick_by_mean(self, true),
BlendMode::DarkerColor => pick_by_luma(self, false),
BlendMode::LighterColor => pick_by_luma(self, true),
// Dividing by the paint is Color Dodge by its inverse, which keeps black backdrops black just as Divide does
Divide => {
let inverted = transfer(self, &source, r#"type="table" tableValues="1 0""#);
@@ -1630,7 +1630,11 @@ fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
return max(c_s, c_b);
}
// A black backdrop stays black, and any other turns white under a white source, as the W3C formula orders them
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if abs(c_b) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.;
}
@@ -1726,7 +1730,8 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
return blend_pin_light(c_b, c_s);
}
case BLEND_HARD_MIX: {
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5);
// A ramp a 256th wide around where the channels sum to 1, matching `blend_hard_mix`
return (c_b - 255. / 256. * (1. - c_s)) * 256.;
}
case BLEND_DIFFERENCE: {
return abs(c_b - c_s);
@@ -1751,11 +1756,11 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> {
switch mode {
case BLEND_DARKER_COLOR: {
let background_is_darker = (background.r + background.g + background.b) / 3. <= (foreground.r + foreground.g + foreground.b) / 3.;
let background_is_darker = luma_rec_601_rounded(background.rgb) <= luma_rec_601_rounded(foreground.rgb);
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a);
}
case BLEND_LIGHTER_COLOR: {
let background_is_lighter = (background.r + background.g + background.b) / 3. >= (foreground.r + foreground.g + foreground.b) / 3.;
let background_is_lighter = luma_rec_601_rounded(background.rgb) >= luma_rec_601_rounded(foreground.rgb);
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a);
}
case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: {
@@ -431,14 +431,13 @@ fn composite_beneath(@builtin(position) position: vec4<f32>) -> @location(0) vec
// The paint mixed with the backdrop by a blend mode besides the component ones, numbered in the order `BlendMode` declares them
fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
let average = vec3<f32>(1. / 3.);
switch mode {
// Darker Color and Lighter Color keep whichever whole color has the lower or higher mean
// Darker Color and Lighter Color keep whichever whole color has the lower or higher luma, the backdrop where they tie
case 5u: {
return select(paint, backdrop, dot(backdrop, average) <= dot(paint, average));
return select(paint, backdrop, luma(backdrop) <= luma(paint));
}
case 10u: {
return select(paint, backdrop, dot(backdrop, average) >= dot(paint, average));
return select(paint, backdrop, luma(backdrop) >= luma(paint));
}
default: {
return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode));
@@ -504,7 +503,7 @@ fn blend_channel(backdrop: f32, paint: f32, mode: u32) -> f32 {
result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5);
}
case 17u: {
result = select(1., 0., linear_light(backdrop, paint) < 0.5);
result = hard_mix(backdrop, paint, 1.);
}
// Difference, Exclusion, Subtract, Divide
case 18u: {
@@ -545,7 +544,11 @@ fn color_burn(backdrop: f32, paint: f32) -> f32 {
return 1. - min((1. - backdrop) / paint, 1.);
}
// A black backdrop stays black, and any other turns white under white paint, as the W3C formula orders them
fn color_dodge(backdrop: f32, paint: f32) -> f32 {
if abs(backdrop) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(paint - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.;
}
@@ -568,6 +571,12 @@ fn linear_light(backdrop: f32, paint: f32) -> f32 {
return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5);
}
// Hard Mix of a paint at `strength`, unclamped, whose ramp steepens to a 256th wide at full strength, matching the CPU's `blend_hard_mix_at_strength`
fn hard_mix(backdrop: f32, paint: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
return (backdrop - steepness * (1. - paint)) / (1. - steepness);
}
// Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them
fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
switch mode {
@@ -4681,10 +4681,10 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
];
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
// Every blend mode, overlaying an opaque color and a translucent one, each with channels summing to what no test color's do, which Darker Color and Lighter Color compare
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
for (color, opacity) in [
(Color::from_gamma_srgb_channels(0.9, 0.453, 0.2, 1.), 70.),
(Color::from_gamma_srgb_channels(0.9, 0.462, 0.239, 1.), 70.),
(Color::from_gamma_srgb_channels(0.1, 0.6, 0.853, 0.4), 100.),
] {
let overlay = Adjustment::ColorOverlay {