PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Blend modes: Fill below 100% works inside the blend for Photoshop's special eight (#2552)
MrCloudy24760f75b4dc1
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex ebecc60c1..7bf3be25b 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -1218,12 +1218,12 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer*p = psblend::composite(BlendMode::Normal, *p, *s, 1.0);p[3] *= mask_k(&mask, i);}- blend_into(backdrop, &content, layer.blend, opacity);+ blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0);return;}let Some(mut content) = render_content(layer, rect, cx) else { return };advanced::composite_clipped(clipped, &mut content, cx);- blend_into_g(backdrop, &content, layer.blend, opacity, text_gamma(layer));+ blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer));}/// A layer with effects (and its clipping group) onto `backdrop`.@@ -1590,6 +1590,19 @@ fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32blend_into_g(backdrop, src, mode, opacity, 1.0);}+/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for+/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise.+fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) {+ if fill >= 1.0 || !psblend::fill_is_special(mode) {+ return blend_into_g(backdrop, src, mode, opacity * fill, gamma);+ }+ for (b, s) in backdrop.px.iter_mut().zip(&src.px) {+ if s[3] > 0.0 {+ *b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma);+ }+ }+}+/// [`blend_into`] mixing coverage in a `gamma` space (type layers).fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {let rect = backdrop.rect;diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rsindex 84566086e..afd841234 100644--- a/crates/compose/src/psblend.rs+++ b/crates/compose/src/psblend.rs@@ -121,6 +121,76 @@ pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {}}+/// Photoshop's "special eight": the modes for which a layer's Fill isn't just less coverage.+/// Below 100% Fill, Photoshop blends at full strength a source pulled toward the mode's neutral+/// colour, the one that leaves the backdrop unchanged (Hard Mix has its own formula); Opacity+/// still mixes the result in. Measured on Photoshop 27.11 (Fill 50%, eight modes, ±1 level).+pub fn fill_is_special(mode: BlendMode) -> bool {+ matches!(+ mode,+ BlendMode::ColorBurn+ | BlendMode::LinearBurn+ | BlendMode::ColorDodge+ | BlendMode::LinearDodge+ | BlendMode::VividLight+ | BlendMode::LinearLight+ | BlendMode::HardMix+ | BlendMode::Difference+ )+}++/// [`blend_rgb`] for a layer at `fill` (0..1): the special eight ([`fill_is_special`]) change+/// their blend below 100%; every other mode, or `fill >= 1`, is plain [`blend_rgb`].+pub fn blend_rgb_fill(mode: BlendMode, cb: [f32; 3], cs: [f32; 3], fill: f32) -> [f32; 3] {+ let f = fill.clamp(0.0, 1.0);+ if f >= 1.0 || !fill_is_special(mode) {+ return blend_rgb(mode, cb, cs);+ }+ let toward = |neutral: f32| -> [f32; 3] { std::array::from_fn(|i| neutral + (cs[i] - neutral) * f) };+ match mode {+ // Hard Mix at Fill f: (cb − f·(1 − cs)) / (1 − f), clamped. At f = 1 it is the hard+ // threshold (cb + cs ≥ 1), at f = 0 the backdrop.+ BlendMode::HardMix => std::array::from_fn(|i| ((cb[i] - f * (1.0 - cs[i])) / (1.0 - f)).clamp(0.0, 1.0)),+ BlendMode::ColorBurn | BlendMode::LinearBurn => blend_rgb(mode, cb, toward(1.0)),+ BlendMode::VividLight | BlendMode::LinearLight => blend_rgb(mode, cb, toward(0.5)),+ _ => blend_rgb(mode, cb, toward(0.0)),+ }+}++/// [`composite_gamma`] for a layer with separate `opacity` and `fill`. Normal modes take both+/// as coverage, as before. For the special eight below 100% Fill, coverage over the backdrop is+/// `opacity` and the blend is [`blend_rgb_fill`]; over transparency, Fill stays coverage, so a+/// layer over nothing looks as it did.+pub fn composite_fill(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: f32, fill: f32, gamma: f32) -> [f32; 4] {+ if fill >= 1.0 || !fill_is_special(mode) {+ return composite_gamma(mode, backdrop, source, opacity * fill.clamp(0.0, 1.0), gamma);+ }+ let ab = backdrop[3];+ let over = source[3] * opacity;+ let alone = over * fill.clamp(0.0, 1.0);+ if over <= 0.0 {+ return backdrop;+ }+ let ao = ab + (1.0 - ab) * alone;+ if ao <= 0.0 {+ return [0.0; 4];+ }+ let cb = [backdrop[0], backdrop[1], backdrop[2]];+ let cs = [source[0], source[1], source[2]];+ let b = blend_rgb_fill(mode, cb, cs, fill);+ let (wb, wbs, ws) = (ab * (1.0 - over) / ao, ab * over / ao, (1.0 - ab) * alone / ao);+ let mut out = [0.0f32; 4];+ for i in 0..3 {+ out[i] = if gamma == 1.0 {+ wb * cb[i] + wbs * b[i] + ws * cs[i]+ } else {+ text_decode(wb * text_encode(cb[i], gamma) + wbs * text_encode(b[i], gamma) + ws * text_encode(cs[i], gamma), gamma)+ };+ }+ out[3] = ao;+ out+}+/// Straight-alpha source over straight-alpha backdrop (W3C/PDF general/// formula) using [`blend_rgb`].pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] {@@ -251,6 +321,67 @@ mod tests {use super::*;+ /// Photoshop 27.11, measured: Background #c89664, a layer #64b4dc at Fill 50% (128/255),+ /// Opacity 100%, in each of the special eight. Values are the composite at 8 bits.+ #[test]+ fn special_eight_fill_matches_photoshop() {+ let measured: [(BlendMode, [u8; 3]); 8] = [+ (BlendMode::ColorBurn, [176, 132, 88]),+ (BlendMode::LinearBurn, [122, 112, 82]),+ (BlendMode::ColorDodge, [249, 232, 176]),+ (BlendMode::LinearDodge, [250, 240, 210]),+ (BlendMode::VividLight, [193, 188, 157]),+ (BlendMode::LinearLight, [171, 202, 192]),+ (BlendMode::HardMix, [245, 225, 165]),+ (BlendMode::Difference, [150, 60, 10]),+ ];+ let px = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0];+ let (b, t) = (px([200, 150, 100]), px([100, 180, 220]));+ for (mode, want) in measured {+ let got = composite_fill(mode, b, t, 1.0, 128.0 / 255.0, 1.0);+ for i in 0..3 {+ assert!((got[i] * 255.0 - f32::from(want[i])).abs() <= 1.5, "{mode:?} channel {i}: {} vs Photoshop {}", got[i] * 255.0, want[i]);+ }+ // At 100% Fill it is the plain blend; at 0% the backdrop.+ assert_eq!(composite_fill(mode, b, t, 1.0, 1.0, 1.0), composite(mode, b, t, 1.0), "{mode:?}");+ let none = composite_fill(mode, b, t, 1.0, 0.0, 1.0);+ assert!((0..3).all(|i| (none[i] - b[i]).abs() < 1e-5), "{mode:?} at Fill 0: {none:?}");+ }+ // A second measurement: Background #3c78b4, layer #d25a1e at Fill 25% (64/255) and 75%+ // (191/255). Hard Mix at 75% is 3 levels off in red: dividing by 1 − f = 0.25 magnifies+ // Photoshop's 8-bit rounding.+ let confirm: [(BlendMode, [u8; 3], [u8; 3]); 8] = [+ (BlendMode::ColorBurn, [51, 94, 159], [30, 0, 33]),+ (BlendMode::LinearBurn, [49, 79, 124], [26, 0, 11]),+ (BlendMode::ColorDodge, [76, 132, 186], [156, 163, 197]),+ (BlendMode::LinearDodge, [113, 143, 188], [217, 187, 202]),+ (BlendMode::VividLight, [71, 109, 162], [117, 81, 80]),+ (BlendMode::LinearLight, [100, 100, 130], [183, 63, 33]),+ (BlendMode::HardMix, [65, 105, 166], [102, 0, 47]),+ (BlendMode::Difference, [7, 97, 172], [97, 53, 158]),+ ];+ let (b2, t2) = (px([60, 120, 180]), px([210, 90, 30]));+ for (mode, q, tq) in confirm {+ for (fill, want) in [(64.0 / 255.0, q), (191.0 / 255.0, tq)] {+ let got = composite_fill(mode, b2, t2, 1.0, fill, 1.0);+ let tol = if mode == BlendMode::HardMix { 3.5 } else { 1.5 };+ for i in 0..3 {+ assert!(+ (got[i] * 255.0 - f32::from(want[i])).abs() <= tol,+ "{mode:?} fill {fill} channel {i}: {} vs Photoshop {}",+ got[i] * 255.0,+ want[i]+ );+ }+ }+ }+ // Other modes keep Fill as coverage, like Opacity.+ assert_eq!(composite_fill(BlendMode::Multiply, b, t, 0.8, 0.5, 1.0), composite(BlendMode::Multiply, b, t, 0.4));+ // Over transparency Fill is still coverage for the special eight.+ let r = composite_fill(BlendMode::LinearDodge, [0.0; 4], t, 1.0, 0.5, 1.0);+ assert!((r[3] - 0.5).abs() < 1e-6 && (r[0] - t[0]).abs() < 1e-6, "{r:?}");+ }+#[test]fn vivid_light_source_extremes_win() {assert_eq!(vivid_light_ps(0.0, 1.0), 1.0);diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgslindex 884cb0f96..48fb3bae7 100644--- a/crates/gpu/src/compose.wgsl+++ b/crates/gpu/src/compose.wgsl@@ -18,7 +18,7 @@ struct Op {opacity: f32,mask_density: f32,mask_default: f32,- _pad1: f32,+ fill: f32, // layer Fill for fs_blend (psblend::composite_fill); 1 elsewheretex_origin: vec2<i32>,tex_size: vec2<i32>,mask_origin: vec2<i32>,@@ -299,6 +299,46 @@ fn composite_g(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32, gamma_on: boreturn vec4(text_dec(pw / ao, g), ao);}+// psblend::fill_is_special: Color Burn, Linear Burn, Color Dodge, Linear Dodge, Vivid Light,+// Linear Light, Hard Mix, Difference (mode_index 5, 6, 10, 11, 16, 17, 19, 20).+fn fill_is_special(mode: i32) -> bool {+ return mode == 5 || mode == 6 || mode == 10 || mode == 11 || mode == 16 || mode == 17 || mode == 19 || mode == 20;+}++// psblend::composite_fill, with a single blend_rgb call (fs_blend's only composite: every+// inlined blend_rgb copy grows the shader, and WARP compiles it slowly). Normal modes take Fill+// as coverage; below 100% Fill the special eight blend a source pulled toward the mode's neutral+// colour (Hard Mix: (cb - f(1 - cs)) / (1 - f)) at `opacity`, Fill staying coverage over+// transparency. Lab documents mix Normal in CIELAB; type layers mix in the text gamma space.+fn composite_fill(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32, fill: f32, gamma_on: bool) -> vec4<f32> {+ let f = clamp(fill, 0.0, 1.0);+ let special = f < 1.0 && fill_is_special(mode);+ let ab = b.a;+ var over = s.a * opacity;+ var alone = over * f;+ if (!special) { over = alone; }+ if (over <= 0.0) { return b; }+ let ao = ab + (1.0 - ab) * alone;+ if (ao <= 0.0) { return vec4(0.0); }+ if (!special && !gamma_on && (op.flags & F_LAB) != 0u && mode == M_NORMAL && ab > 0.0) {+ let m = srgb_to_lab(b.rgb) * (ab * (1.0 - over) / ao) + srgb_to_lab(s.rgb) * (over / ao);+ return vec4(lab_to_srgb(m), ao);+ }+ var neutral = 0.0;+ if (mode == 5 || mode == 6) { neutral = 1.0; }+ if (mode == 16 || mode == 17) { neutral = 0.5; }+ var cs = s.rgb;+ if (special) { cs = vec3(neutral) + (s.rgb - vec3(neutral)) * f; }+ var bl = blend_rgb(mode, b.rgb, cs);+ if (special && mode == 19) { bl = clamp((b.rgb - f * (vec3(1.0) - s.rgb)) / (1.0 - f), vec3(0.0), vec3(1.0)); }+ let wb = ab * (1.0 - over) / ao;+ let wbs = ab * over / ao;+ let ws = (1.0 - ab) * alone / ao;+ if (!gamma_on) { return vec4(wb * b.rgb + wbs * bl + ws * s.rgb, ao); }+ let g = op.p4.w;+ return vec4(text_dec(wb * text_enc(b.rgb, g) + wbs * text_enc(bl, g) + ws * text_enc(s.rgb, g), g), ao);+}+// photocraft_color::convert::{srgb_to_lab, lab_to_srgb} (D50, Bradford to sRGB).const D50: vec3<f32> = vec3(0.96422, 1.0, 0.82521);fn lab_f(t: f32) -> f32 {@@ -750,10 +790,10 @@ fn fs_blend(in: VOut) -> @location(0) vec4<f32> {var s = textureLoad(tex_b, p, 0);if (s.a <= 0.0) { return b; }if (op.mode == M_DISSOLVE) {- s.a = select(0.0, 1.0, dissolve_noise(doc_px(p)) < s.a * op.opacity);+ s.a = select(0.0, 1.0, dissolve_noise(doc_px(p)) < s.a * op.opacity * op.fill);return composite(M_NORMAL, b, s, 1.0);}- return composite_g(op.mode, b, s, op.opacity, (op.flags & F_TEXT_GAMMA) != 0u);+ return composite_fill(op.mode, b, s, op.opacity, op.fill, (op.flags & F_TEXT_GAMMA) != 0u);}// composite_atop(base = A, src = B): blend as if the base were opaque, keep its alpha.diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsindex 4a6480c95..a19e1b404 100644--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@ -1660,7 +1660,7 @@ fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, mF(p.opacity),F(density),F(mdefault),- F(0.0),+ F(p.fill),I(to[0]),I(to[1]),I(ts[0]),diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex 205ac06aa..9a2d0a63b 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -171,6 +171,9 @@ pub struct Pass<'a> {pub d: Option<Slot>,pub mode: BlendMode,pub opacity: f32,+ /// The layer's Fill where it isn't folded into `opacity`: the final blend of a plain layer+ /// (`Kernel::Blend`), so the special eight can apply it inside the blend. 1 elsewhere.+ pub fill: f32,/// Layer pixels (raster / text / shape / smart cache / fill cache).pub tex: Option<TexUse<'a>>,/// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect@@ -232,6 +235,7 @@ impl<'a> Pass<'a> {d: None,mode: BlendMode::Normal,opacity: 1.0,+ fill: 1.0,tex: None,color: [0.0; 4],mask: None,@@ -671,7 +675,8 @@ impl<'a> Planner<'a> {p.a = Some(backdrop);p.b = Some(content);p.mode = layer.blend;- p.opacity = opacity;+ p.opacity = layer.opacity;+ p.fill = layer.fill_opacity;return Ok(self.emit(p));}@@ -704,7 +709,8 @@ impl<'a> Planner<'a> {p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop });p.b = Some(content);p.mode = layer.blend;- p.opacity = opacity;+ p.opacity = layer.opacity;+ p.fill = layer.fill_opacity;p.flags = gamma_flag(layer);p.extra[3] = photocraft_compose::text_gamma(layer);p.clip = clip;diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex 9dccc008f..530bc8b5b 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -170,6 +170,37 @@ fn blend_modes() {}}+/// Photoshop's special eight apply Fill inside the blend (psblend::composite_fill): the GPU's+/// blend pass takes Fill separately and must match the CPU at low and middle Fill, with Opacity,+/// over transparency and over an opaque backdrop.+#[test]+fn special_eight_fill_matches_cpu() {+ let Some(mut g) = gpu() else { return };+ let special = [+ BlendMode::ColorBurn,+ BlendMode::LinearBurn,+ BlendMode::ColorDodge,+ BlendMode::LinearDodge,+ BlendMode::VividLight,+ BlendMode::LinearLight,+ BlendMode::HardMix,+ BlendMode::Difference,+ ];+ for mode in special {+ for fill in [0.3, 0.6] {+ let mut d = base_doc(64, 48);+ let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 2, 0.0);+ l.blend = mode;+ l.opacity = 0.7;+ l.fill_opacity = fill;+ d.layers.push(l);+ check(&mut g, &d, &format!("{mode:?} fill {fill}"));+ d.layers[0] = noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 5, 1.0);+ check(&mut g, &d, &format!("{mode:?} fill {fill} opaque"));+ }+ }+}+#[test]fn xor_rounding_on_half_float_targets() {let Some((_adapter, device, queue, _lock)) = any_device() else { return };