Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(compose): don't clip Add and Divide at 1 in 32-bit documents (#1722)

eric60018dea692f
diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs
index 8c6a6b48e..02fdadef1 100644
--- a/crates/color/src/blend.rs
+++ b/crates/color/src/blend.rs
@@ -151,6 +151,20 @@ impl BlendMode {
/// Separable per-channel blend function `B(cb, cs)`.
#[inline]
pub fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
+ channel(mode, cb, cs, 1.0)
+}
+
+/// [`blend_channel`] for 32-bit float documents, whose values may exceed 1: Linear Dodge (Add)
+/// and Divide don't clip at 1 there (Photoshop's 32-bit Add is how light is added in HDR), only
+/// at `f32::MAX`, so they stay finite. Every other mode is [`blend_channel`].
+#[inline]
+pub fn blend_channel_hdr(mode: BlendMode, cb: f32, cs: f32) -> f32 {
+ channel(mode, cb, cs, f32::MAX)
+}
+
+/// `B(cb, cs)` with Linear Dodge and Divide clipped at `hi` (1 at integer depths).
+#[inline]
+fn channel(mode: BlendMode, cb: f32, cs: f32, hi: f32) -> f32 {
match mode {
BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough => cs,
BlendMode::Darken => cb.min(cs),
@@ -160,7 +174,7 @@ pub fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
BlendMode::Lighten => cb.max(cs),
BlendMode::Screen => cb + cs - cb * cs,
BlendMode::ColorDodge => color_dodge(cb, cs),
- BlendMode::LinearDodge => (cb + cs).min(1.0),
+ BlendMode::LinearDodge => (cb + cs).min(hi),
BlendMode::Overlay => hard_light(cs, cb),
BlendMode::SoftLight => soft_light_ps(cb, cs),
BlendMode::HardLight => hard_light(cb, cs),
@@ -195,7 +209,7 @@ pub fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
if cs <= 0.0 {
if cb <= 0.0 { 0.0 } else { 1.0 }
} else {
- (cb / cs).min(1.0)
+ (cb / cs).min(hi)
}
}
// Non-separable modes are handled by `blend_rgb`; fall back to source.
@@ -337,6 +351,11 @@ pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
}
}
+/// [`blend_rgb`] for 32-bit float documents: separable modes use [`blend_channel_hdr`].
+pub fn blend_rgb_hdr(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
+ if mode.is_separable() { std::array::from_fn(|i| blend_channel_hdr(mode, cb[i], cs[i])) } else { blend_rgb(mode, cb, cs) }
+}
+
/// Composite a straight-alpha source over a straight-alpha backdrop with blend mode and opacity.
///
/// Uses the W3C/PDF general formula:
@@ -476,6 +495,38 @@ mod tests {
}
}
+ #[test]
+ fn add_and_divide_clip_at_integer_depths_but_not_in_float() {
+ // Integer depths: Photoshop clips Linear Dodge (Add) and Divide at 1.
+ assert_eq!(blend_channel(BlendMode::LinearDodge, 2.0, 0.5), 1.0);
+ assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.5), 1.0);
+ assert_eq!(blend_channel(BlendMode::Divide, 2.0, 0.5), 1.0);
+ assert_eq!(blend_channel(BlendMode::Divide, 0.5, 0.25), 1.0);
+ // 32-bit float: light adds up past 1 (adding light never darkens).
+ assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 2.0, 0.5), 2.5));
+ assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.5), 1.25));
+ assert!(close(blend_channel_hdr(BlendMode::Divide, 2.0, 0.5), 4.0));
+ assert!(close(blend_channel_hdr(BlendMode::Divide, 0.5, 0.25), 2.0));
+ assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [2.5, 0.75, 4.5]);
+ assert_eq!(blend_rgb_hdr(BlendMode::Divide, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [4.0, 2.0, 8.0]);
+ // Divide by zero keeps its guard; overflow stays finite.
+ assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.0, 0.0), 0.0);
+ assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, 0.0), 1.0);
+ assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0);
+ assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX);
+ assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX);
+ assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite());
+ // Every other mode is unchanged, and the in-range results agree.
+ for m in BlendMode::LAYER_MODES.into_iter().filter(|m| !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) {
+ for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] {
+ assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}");
+ }
+ }
+ let (cb, cs) = ([0.2, 0.3, 0.1], [0.3, 0.4, 0.4]);
+ assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, cb, cs), blend_rgb(BlendMode::LinearDodge, cb, cs));
+ assert_eq!(blend_rgb_hdr(BlendMode::Divide, cb, cs), blend_rgb(BlendMode::Divide, cb, cs));
+ }
+
#[test]
fn luminosity_and_color_swap_components() {
let cb = [0.8, 0.2, 0.2];
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 31817c83d..4ab50d378 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -96,8 +96,10 @@ pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer {
let tile = tile.max(1);
- // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX).
+ // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit
+ // documents don't clip Add / Divide at 1 (psblend::HDR).
let lab = doc.mode == photocraft_color::ColorMode::Lab;
+ let hdr = doc.depth == photocraft_color::SampleType::F32;
// CMYK layers are read through the document's own CMYK profile (thread-local scope).
let cmyk = cmyk_space(doc);
let cmyk = cmyk.as_ref();
@@ -107,26 +109,18 @@ fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer
if rect.width() as i32 <= tile && rect.height() as i32 <= tile {
return photocraft_color::convert::with_cmyk_space(cmyk, || {
let mut buf = multichannel::backdrop(doc, rect);
- psblend::LAB_MIX.with(|l| l.set(lab));
- composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT);
- psblend::LAB_MIX.with(|l| l.set(false));
+ in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT));
buf
});
}
// Effect maps are built once, here, before any tile needs them (#276).
prepare_effects(&doc.layers, rect, cx, |f| {
- photocraft_color::convert::with_cmyk_space(cmyk, || {
- psblend::LAB_MIX.with(|l| l.set(lab));
- f();
- psblend::LAB_MIX.with(|l| l.set(false));
- });
+ photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f));
});
let run = |t: Rect| {
photocraft_color::convert::with_cmyk_space(cmyk, || {
let mut b = multichannel::backdrop(doc, t);
- psblend::LAB_MIX.with(|l| l.set(lab));
- composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT);
- psblend::LAB_MIX.with(|l| l.set(false));
+ in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT));
b
})
};
@@ -186,6 +180,17 @@ fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer
out
}
+/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]),
+/// clearing them afterwards.
+fn in_blend_space<R>(lab: bool, hdr: bool, f: impl FnOnce() -> R) -> R {
+ psblend::LAB_MIX.with(|l| l.set(lab));
+ psblend::HDR.with(|h| h.set(hdr));
+ let r = f();
+ psblend::LAB_MIX.with(|l| l.set(false));
+ psblend::HDR.with(|h| h.set(false));
+ r
+}
+
/// The document's own CMYK profile for reading its CMYK pixels (`None`: not a CMYK document,
/// untagged, or the built-in coated CMYK). Enter it with `photocraft_color::convert::with_cmyk_space`
/// around code that converts the document's CMYK pixels or colours to RGB.
diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rs
index c3698bb4b..5d83068c9 100644
--- a/crates/compose/src/psblend.rs
+++ b/crates/compose/src/psblend.rs
@@ -76,6 +76,9 @@ thread_local! {
/// (Photoshop composites Lab documents in Lab; an anti-aliased edge between two colours
/// differs by up to 14 / 255 from an sRGB mix: psd-tools stroke-color-descriptors-lab).
pub static LAB_MIX: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+ /// Set while rendering a 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1
+ /// ([`generic::blend_rgb_hdr`]), as in Photoshop's 32-bit mode; integer depths clip.
+ pub static HDR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// `B(Cb, Cs)` with Photoshop's variants.
@@ -85,6 +88,7 @@ pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
BlendMode::HardMix => std::array::from_fn(|i| hard_mix_ps(cb[i], cs[i])),
BlendMode::ColorBurn => std::array::from_fn(|i| color_burn(cb[i], cs[i])),
BlendMode::ColorDodge => std::array::from_fn(|i| color_dodge(cb[i], cs[i])),
+ m if HDR.with(|h| h.get()) => generic::blend_rgb_hdr(m, cb, cs),
m => generic::blend_rgb(m, cb, cs),
}
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 259805aec..902202b6c 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -76,7 +76,10 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() {
top.blend = mode;
d.layers = vec![bottom, top];
let got = px(&d, 0, 0);
+ // A 32-bit document: Add / Divide don't clip at 1 (Divide gives 0.6 / 0.2 = 3 in red).
+ psblend::HDR.with(|h| h.set(true));
let want = blend::blend_rgb(mode, [0.6, 0.3, 0.2], [0.2, 0.7, 0.5]);
+ psblend::HDR.with(|h| h.set(false));
for i in 0..3 {
assert!((got[i] - want[i]).abs() < 1e-5, "{mode:?}: {got:?} vs {want:?}");
}
@@ -373,6 +376,50 @@ fn sixteen_bit_and_float_layers_composite() {
}
}
+/// `top` blended with `mode` over an opaque `bg`, both solid, in a 4×4 RGB document of `depth`.
+fn two_solid_layers(depth: SampleType, mode: BlendMode, bg: [f32; 3], top: [f32; 3]) -> Document {
+ let mut d = Document::new("hdr", Size::new(4, 4), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ let mut b = Layer::raster("bg", fmt);
+ b.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &photocraft_raster::from_rgba(&fmt, [bg[0], bg[1], bg[2], 1.0]));
+ let mut t = Layer::raster("top", fmt);
+ t.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &photocraft_raster::from_rgba(&fmt, [top[0], top[1], top[2], 1.0]));
+ t.blend = mode;
+ d.layers.push(b);
+ d.layers.push(t);
+ d
+}
+
+#[test]
+fn float_documents_add_and_divide_past_white() {
+ // 32-bit: Linear Dodge (Add) and Divide keep HDR values (adding light never darkens).
+ let (bg, top) = ([2.0, 0.5, 4.0], [0.5, 0.25, 0.5]);
+ for (mode, want) in [(BlendMode::LinearDodge, [2.5, 0.75, 4.5]), (BlendMode::Divide, [4.0, 2.0, 8.0]), (BlendMode::Multiply, [1.0, 0.125, 2.0])] {
+ let d = two_solid_layers(SampleType::F32, mode, bg, top);
+ for buf in [flatten(&d), render_tiled(&d, d.bounds(), 2)] {
+ for p in &buf.px {
+ assert!(close4(*p, [want[0], want[1], want[2], 1.0]), "{mode:?}: {p:?}");
+ }
+ }
+ }
+ // The flag doesn't leak into later renders on this thread.
+ let d = two_solid_layers(SampleType::U16, BlendMode::LinearDodge, [0.8, 0.5, 0.6], top);
+ assert!(close4(flatten(&d).px[0], [1.0, 0.75, 1.0, 1.0]));
+}
+
+#[test]
+fn integer_documents_clip_add_and_divide_at_white() {
+ let (bg, top) = ([0.8, 0.5, 0.6], [0.5, 0.25, 0.5]);
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let f32_doc = depth == SampleType::F32;
+ for (mode, clipped, hdr) in [(BlendMode::LinearDodge, [1.0, 0.75, 1.0], [1.3, 0.75, 1.1]), (BlendMode::Divide, [1.0, 1.0, 1.0], [1.6, 2.0, 1.2])] {
+ let want = if f32_doc { hdr } else { clipped };
+ let p = flatten(&two_solid_layers(depth, mode, bg, top)).px[5];
+ assert!(close4(p, [want[0], want[1], want[2], 1.0]), "{mode:?} {depth:?}: {p:?}");
+ }
+ }
+}
+
#[test]
fn thumbnail_dimensions() {
let d = doc_white(400, 200);
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index a71e53ec0..1d6c019b7 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -48,6 +48,7 @@ const F_STROKE_OUT: u32 = 1024u; // effect paint: outside stroke band
const F_FIRST: u32 = 2048u; // outside strokes: nothing accumulated yet
const F_CHANNELS: u32 = 4096u; // lerp: per-channel weights in p0 (channel restrictions)
const F_LAB: u32 = 65536u; // Lab document: Normal mixes in CIELAB
+const F_HDR: u32 = 262144u; // 32-bit float document: Add / Divide don't clip at 1
const F_QUANT: u32 = 32768u; // lerp: A rounded to p0.x steps (adjustment results, integer docs)
const F_ADD_DIFF: u32 = 16384u; // lerp: A + (B - C) premultiplied (clips on pass-through groups)
const F_TEXT_GAMMA: u32 = 8192u; // blend / atop / fx merge: type layer, mix coverage at gamma p4.w
@@ -152,7 +153,11 @@ fn vivid_light_generic(cb: f32, cs: f32) -> f32 {
return min(cb / (2.0 * (1.0 - cs)), 1.0);
}
+const F32_MAX: f32 = 3.40282347e38;
+
fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {
+ // Linear Dodge / Divide clip at 1 at integer depths, at f32::MAX in 32-bit documents.
+ let hi = select(1.0, F32_MAX, (op.flags & F_HDR) != 0u);
switch mode {
case 3: { return min(cb, cs); } // Darken
case 4: { return cb * cs; } // Multiply
@@ -161,7 +166,7 @@ fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {
case 8: { return max(cb, cs); } // Lighten
case 9: { return cb + cs - cb * cs; } // Screen
case 10: { return color_dodge(cb, cs); } // ColorDodge
- case 11: { return min(cb + cs, 1.0); } // LinearDodge
+ case 11: { return min(cb + cs, hi); } // LinearDodge
case 13: { return hard_light(cs, cb); } // Overlay
case 14: { return soft_light_ps(cb, cs); } // SoftLight
case 15: { return hard_light(cb, cs); } // HardLight
@@ -179,7 +184,7 @@ fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {
case 22: { return max(cb - cs, 0.0); } // Subtract
case 23: { // Divide
if (cs <= 0.0) { return select(1.0, 0.0, cb <= 0.0); }
- return min(cb / cs, 1.0);
+ return min(cb / cs, hi);
}
default: { return cs; } // Normal, Dissolve, PassThrough
}
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index b320ea938..30dc06a76 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -362,6 +362,8 @@ pub const F_FIRST: u32 = 2048;
pub const F_CHANNELS: u32 = 4096;
/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`).
pub const F_LAB: u32 = 65536;
+/// 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1 (`psblend::HDR`).
+pub const F_HDR: u32 = 262144;
/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents).
pub const F_QUANT: u32 = 32768;
/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups).
@@ -427,6 +429,9 @@ impl<'a> Planner<'a> {
if self.cx.mode == photocraft_color::ColorMode::Lab {
pass.flags |= F_LAB;
}
+ if self.cx.depth == photocraft_color::SampleType::F32 {
+ pass.flags |= F_HDR;
+ }
let (a, b, c, d) = (pass.a, pass.b, pass.c, pass.d);
self.passes.push(pass);
for s in [a, b, c, d].into_iter().flatten() {
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 05d13a666..2329ece14 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -1244,6 +1244,42 @@ fn blend_mode_extremes() {
}
}
+#[test]
+fn float_documents_blend_past_white() {
+ // 32-bit documents hold values above 1; Linear Dodge (Add) and Divide don't clip them there
+ // (integer depths do, see `blend_mode_extremes`). Values and alphas are exact in half floats.
+ // Separable modes only: the non-separable ones' ClipColor is ill-conditioned past white (a
+ // grey above 1 has max − lum ≈ 0), so CPU and GPU rounding diverge there.
+ let Some(mut g) = gpu() else { return };
+ let vals = [0.0f32, 0.25, 0.5, 1.0, 2.0, 4.0];
+ let alphas = [1.0f32, 0.5, 0.25];
+ for mode in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable()) {
+ let n = vals.len() as u32;
+ let mut d = Document::new("hdr", Size::new(n * 3, n), ColorMode::Rgb, SampleType::F32);
+ let fmt = d.pixel_format();
+ let mut bg = Layer::raster("bg", fmt);
+ let mut top = Layer::raster("top", fmt);
+ for (i, &b) in vals.iter().enumerate() {
+ for (j, &s) in vals.iter().enumerate() {
+ for (k, &a) in alphas.iter().enumerate() {
+ let r = Rect::from_xywh((i * 3 + k) as i32, j as i32, 1, 1);
+ bg.surface_mut().unwrap().fill_rect(r, &[b, b * 0.5, b, 1.0]);
+ top.surface_mut().unwrap().fill_rect(r, &[s, s, s * 0.5, a]);
+ }
+ }
+ }
+ top.blend = mode;
+ d.layers.push(bg);
+ d.layers.push(top);
+ check(&mut g, &d, &format!("hdr {mode:?}"));
+ if mode == BlendMode::LinearDodge {
+ // 4 + 0.25 at full opacity (column 5 × 3, row 1): unclipped on the GPU too.
+ let px = render_to_vec(&mut g.comp, &g.device, &g.queue, &d, Rect::from_xywh(15, 1, 1, 1)).unwrap();
+ assert!((px[0][0] - 4.25).abs() < 1e-3, "{:?}", px[0]);
+ }
+ }
+}
+
#[test]
fn stroked_shapes_with_clipped_layers() {
let Some(mut g) = gpu() else { return };