PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Keep CMYK ink values when flattening and merging (#3855)
Fabio Lussi25c0ec78d574
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 01087f493..c059d9c8b 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -24,6 +24,7 @@ pub mod fill_layout;pub mod gradient_fill;pub mod masks;pub mod multichannel;+pub mod native;pub mod pattern;pub mod proxy;pub mod psblend;@@ -232,20 +233,38 @@ pub fn band_rows_for(width: u32, requested: i32) -> i32 {/// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model/// and depth), optionally flattened over an opaque `background`; rendered and written in bands,/// so no full-size float composite is held. Tiles equal to the default pixel are pruned.+/// A CMYK document of plain Normal layers is composited in its ink values instead+/// ([`native::flatten_cmyk`]), so flattening doesn't round-trip its pixels through RGB (#3778).pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface {+ composite_to_surface(doc, doc.bounds(), fmt, background)+}++/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty).+pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface {+ let paper = background.is_some_and(|bg| bg == [1.0; 3]);+ if (background.is_none() || paper)+ && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper)+ {+ return s;+ }let mut s = Surface::new(fmt);let n = fmt.channels();let mut data = Vec::new();- let _ = render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {+ // The composite separates back to CMYK through the document's own profile, the one its+ // pixels were read through.+ let cmyk = cmyk_space(doc);+ let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> {let band = match background {Some(bg) => band.over_background(bg),None => band,};data.clear();data.resize(band.px.len() * n, 0.0);- for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) {- photocraft_raster::from_rgba_into(&fmt, *p, out);- }+ photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || {+ for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) {+ photocraft_raster::from_rgba_into(&fmt, *p, out);+ }+ });s.write_region(band.rect, &data);Ok(())});diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rsnew file mode 100644index 000000000..9eafd18cc--- /dev/null+++ b/crates/compose/src/native.rs@@ -0,0 +1,101 @@+//! Mode-native flattening of plain CMYK layer stacks (#3778).+//!+//! The compositor works in display RGB, so flattening a CMYK document through it reads every ink+//! value through the profile and separates it again: even a lone Background comes back with+//! different ink. When every visible layer is a plain raster layer in Normal mode (no masks,+//! effects, clipping or advanced blending), the composite needs no colour conversion at all:+//! Normal mixes ink values linearly, as Photoshop does in CMYK, so it is worked out on the stored+//! values and an opaque layer keeps them exactly.++use photocraft_color::blend::BlendMode;+use photocraft_color::{ColorMode, PixelFormat};+use photocraft_doc::{Document, Layer, LayerContent};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++/// Process channels of a CMYK pixel.+const INKS: usize = 4;++/// A layer the native path can composite: a visible raster layer the compositor would only blend+/// Normally at its opacity.+fn plain(layer: &Layer) -> Option<&Surface> {+ let LayerContent::Raster(s) = &layer.content else { return None };+ let simple = layer.blend == BlendMode::Normal+ && !layer.clipped+ && layer.mask.as_ref().is_none_or(|m| !m.enabled)+ && layer.vector_mask.as_ref().is_none_or(|v| !v.enabled)+ && !crate::effects::has_effects(layer)+ && layer.excluded_channels == 0+ && layer.blend_if.is_default()+ && layer.advanced.is_default()+ && layer.video.is_none()+ && s.format().mode == ColorMode::Cmyk;+ simple.then_some(s)+}++/// The composite of `doc` over `rect` in `fmt`, worked out in ink values, or `None` when the+/// document isn't CMYK or a visible layer needs the full compositor (see the module docs).+/// `paper` flattens onto white paper (no ink) and makes the result opaque.+pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) -> Option<Surface> {+ if doc.mode != ColorMode::Cmyk || fmt.mode != ColorMode::Cmyk || doc.layers.iter().any(|l| l.clipped) {+ return None;+ }+ let mut stack = Vec::new();+ for layer in doc.layers.iter().filter(|l| l.visible) {+ let alpha = (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0);+ stack.push((plain(layer)?, alpha));+ }+ let mut out = Surface::new(fmt);+ if rect.is_empty() {+ return Some(out);+ }+ let n = fmt.channels();+ let w = rect.width() as usize;+ let rows = crate::band_rows_for(rect.width(), 0);+ let (mut acc, mut src, mut data) = (Vec::new(), Vec::new(), Vec::new());+ let mut y = rect.y0;+ while y < rect.y1 {+ let band = Rect::new(rect.x0, y, rect.x1, y.saturating_add(rows).min(rect.y1));+ // Straight C, M, Y, K, alpha per pixel, starting transparent.+ acc.clear();+ acc.resize(w * band.height() as usize, [0.0f32; INKS + 1]);+ for &(surf, opacity) in &stack {+ if opacity <= 0.0 || (surf.content_bounds().intersect(&band).is_empty() && surf.default_pixel().iter().all(|v| *v == 0.0)) {+ continue;+ }+ let sf = surf.format();+ let sn = sf.channels();+ surf.read_region_into(band, &mut src);+ for (d, s) in acc.iter_mut().zip(src.chunks_exact(sn)) {+ let sa = if sf.alpha { s[INKS] } else { 1.0 } * opacity;+ if sa <= 0.0 {+ continue;+ }+ let oa = sa + d[INKS] * (1.0 - sa);+ let keep = d[INKS] * (1.0 - sa);+ for c in 0..INKS {+ // An opaque pixel replaces what is below exactly (no rounding through the mix).+ d[c] = if sa >= 1.0 { s[c] } else { (s[c] * sa + d[c] * keep) / oa };+ }+ d[INKS] = oa;+ }+ }+ data.clear();+ data.resize(acc.len() * n, 0.0);+ for (p, o) in acc.iter().zip(data.chunks_exact_mut(n)) {+ // White paper carries no ink, so flattening onto it scales the ink by coverage.+ let a = p[INKS];+ let k = if paper && a < 1.0 { a } else { 1.0 };+ for c in 0..INKS {+ o[c] = p[c] * k;+ }+ if fmt.alpha {+ o[INKS] = if paper { 1.0 } else { a };+ }+ }+ out.write_region(band, &data);+ y = band.y1;+ }+ out.prune();+ Some(out)+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 48caf85b2..a47bde9ff 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -774,7 +774,7 @@ fn build() -> Vec<CommandSpec> {below.push(idx - 1);let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone();let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone();- let merged = pixels::merge_down(doc.bounds(), &lower, &upper, doc.pixel_format());+ let merged = pixels::merge_down(doc, &lower, &upper);doc.remove(id);*doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged;*active = Some(lower.id);diff --git a/crates/engine/src/flatten_cmyk_tests.rs b/crates/engine/src/flatten_cmyk_tests.rsnew file mode 100644index 000000000..4fd187cee--- /dev/null+++ b/crates/engine/src/flatten_cmyk_tests.rs@@ -0,0 +1,169 @@+//! #3778: Flatten Image, Merge Visible and Merge Down keep a CMYK document's ink values instead+//! of round-tripping them through RGB.++use photocraft_cms::synth::{CmykParams, cmyk_profile};+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Document, Layer, LayerContent, Size};+use photocraft_geom::Rect;+use photocraft_raster::Surface;+use serde_json::json;++use crate::Session;++const W: i32 = 16;+const H: i32 = 8;++fn canvas() -> Rect {+ Rect::new(0, 0, W, H)+}++/// Ink values that vary per pixel and per channel, away from the 8-bit grid.+fn ink(x: i32, y: i32) -> [f32; 4] {+ let f = |k: i32| ((x * 7 + y * 13 + k * 29) % 97) as f32 / 96.0 * 0.9 + 0.0371;+ [f(0), f(1), f(2), f(3)]+}++/// A 16-bit CMYK document tagged with a synthetic profile (not the built-in coated CMYK), holding+/// just an opaque Background of varied ink.+fn cmyk_doc() -> Document {+ let mut d = Document::new("cmyk", Size::new(W as u32, H as u32), ColorMode::Cmyk, SampleType::U16);+ let profile =+ cmyk_profile(&CmykParams { description: "Flatten Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() });+ d.icc_profile = Some(profile.to_bytes());+ let mut bg = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, false));+ for y in 0..H {+ for x in 0..W {+ bg.write_pixel(x, y, &ink(x, y));+ }+ }+ let mut layer = Layer::new("Background", LayerContent::Raster(bg));+ layer.locks.transparency = true;+ layer.locks.position = true;+ d.layers.push(layer);+ d+}++/// A layer above the Background: solid ink on the left half, half-transparent ink on a strip,+/// nothing on the rest.+fn upper_layer() -> Layer {+ let mut s = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true));+ s.fill_rect(Rect::new(0, 0, W / 2, H), &[0.8123, 0.1234, 0.4567, 0.0789, 1.0]);+ s.fill_rect(Rect::new(W / 2, 0, W / 2 + 2, H), &[0.25, 0.5, 0.75, 0.1, 0.5]);+ Layer::new("Layer 1", LayerContent::Raster(s))+}++fn session(doc: Document) -> Session {+ let mut s = Session::new();+ s.add_document(doc, None);+ s+}++/// The bottom layer's ink values (C, M, Y, K per pixel, without any alpha channel).+fn pixels(s: &Session) -> Vec<f32> {+ let surf = s.active().unwrap().doc.layers[0].surface().unwrap();+ let n = surf.channels();+ surf.read_region(canvas()).chunks_exact(n).flat_map(|p| p[..4].to_vec()).collect()+}++fn bottom_format(s: &Session) -> PixelFormat {+ s.active().unwrap().doc.layers[0].surface().unwrap().format()+}++#[test]+fn flattening_a_lone_cmyk_background_keeps_its_pixels() {+ let doc = cmyk_doc();+ let before = doc.layers[0].surface().unwrap().read_region(canvas());+ let mut s = session(doc);+ s.execute("layer.flattenImage", json!({})).unwrap();+ let fmt = bottom_format(&s);+ assert_eq!((fmt.mode, fmt.sample), (ColorMode::Cmyk, SampleType::U16), "16-bit CMYK stays 16-bit CMYK");+ let moved = pixels(&s).iter().zip(&before).filter(|(a, b)| a != b).count();+ assert_eq!(moved, 0, "a single Background must flatten to the same ink values");+}++/// What a Normal 100 % layer over the Background gives, worked out in ink values: the solid part+/// replaces the ink, the half-transparent strip mixes half and half, the rest shows the Background.+fn expected_two_layers() -> Vec<f32> {+ let mut out = Vec::new();+ for y in 0..H {+ for x in 0..W {+ let below = ink(x, y);+ let px = if x < W / 2 {+ [0.8123, 0.1234, 0.4567, 0.0789]+ } else if x < W / 2 + 2 {+ let top = [0.25, 0.5, 0.75, 0.1];+ [0, 1, 2, 3].map(|c| top[c] * 0.5 + below[c] * 0.5)+ } else {+ below+ };+ out.extend_from_slice(&px);+ }+ }+ out+}++fn assert_close(got: &[f32], want: &[f32], what: &str) {+ assert_eq!(got.len(), want.len(), "{what}: pixel count");+ // One 16-bit code (the stored value is quantised to 1/65535).+ let worst = got.iter().zip(want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);+ assert!(worst <= 1.0 / 65535.0 + 1e-6, "{what}: ink values moved by up to {worst}");+}++#[test]+fn flattening_normal_cmyk_layers_composites_in_ink_values() {+ let mut doc = cmyk_doc();+ doc.layers.push(upper_layer());+ let mut s = session(doc);+ s.execute("layer.flattenImage", json!({})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.len(), 1);+ assert_eq!(bottom_format(&s).sample, SampleType::U16);+ assert_close(&pixels(&s), &expected_two_layers(), "Flatten Image");+}++#[test]+fn merge_visible_and_merge_down_keep_cmyk_ink_values() {+ for cmd in ["layer.mergeVisible", "layer.mergeDown"] {+ let mut doc = cmyk_doc();+ let upper = upper_layer();+ let id = upper.id;+ doc.layers.push(upper);+ let mut s = session(doc);+ s.execute(cmd, json!({"layer": id.0})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.len(), 1, "{cmd}");+ assert_eq!(bottom_format(&s).sample, SampleType::U16, "{cmd}");+ assert_close(&pixels(&s), &expected_two_layers(), cmd);+ }+}++/// A stack the ink-value path can't take (a Multiply layer) still goes through the compositor,+/// but separates back through the document's profile, the one it read the ink through, so the+/// round trip lands near the original ink instead of on the built-in profile's separation.+#[test]+fn compositor_flatten_separates_through_the_documents_profile() {+ let mut doc = cmyk_doc();+ // Light inks, inside the printable gamut, so a separation can give them back.+ let bg = doc.layers[0].surface_mut().unwrap();+ for y in 0..H {+ for x in 0..W {+ bg.write_pixel(x, y, &ink(x, y).map(|v| v * 0.4));+ }+ }+ let before = doc.layers[0].surface().unwrap().read_region(canvas());+ let mut empty = Layer::new("Layer 1", LayerContent::Raster(Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true))));+ empty.blend = photocraft_color::blend::BlendMode::Multiply;+ doc.layers.push(empty);+ let mut s = session(doc);+ s.execute("layer.flattenImage", json!({})).unwrap();+ // Compare what the inks print as (a CMYK colour has many separations): RGB through the profile.+ let d = &s.active().unwrap().doc;+ let space = photocraft_compose::cmyk_space(d);+ let shown = |v: &[f32]| -> Vec<[f32; 3]> {+ photocraft_color::convert::with_cmyk_space(space.as_ref(), || v.as_chunks::<4>().0.iter().map(|p| photocraft_color::convert::cmyk_to_rgb(*p)).collect())+ };+ let (a, b) = (shown(&pixels(&s)), shown(&before));+ let diffs: Vec<f32> = a.iter().zip(&b).flat_map(|(p, q)| (0..3).map(move |c| (p[c] - q[c]).abs())).collect();+ let mean = diffs.iter().sum::<f32>() / diffs.len() as f32;+ // The synthetic profile's small tables don't round-trip exactly; the built-in profile's+ // separation lands about 0.08 off on average.+ assert!(mean < 0.03, "flattening shifted the printed colour by {mean} on average");+}diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rsindex 2ba5b5dcf..b19a1b270 100644--- a/crates/engine/src/pixels.rs+++ b/crates/engine/src/pixels.rs@@ -21,32 +21,11 @@ pub fn composite_layers(solo: &Document, format: photocraft_color::PixelFormat,.reduce(|a, b| a.union(&b)).unwrap_or(Rect::EMPTY).intersect(&canvas);- let mut surface = Surface::new(format);if area.is_empty() {- return surface;+ return Surface::new(format);}-- let channels = format.channels();- let mut data = Vec::new();- let _ = photocraft_compose::render_bands(solo, area, 0, |mut band| -> Result<(), ()> {- if let Some(color) = background {- for pixel in &mut band.px {- let alpha = pixel[3];- for channel in 0..3 {- pixel[channel] = pixel[channel] * alpha + color[channel] * (1.0 - alpha);- }- pixel[3] = 1.0;- }- }- data.resize(band.px.len() * channels, 0.0);- for (pixel, encoded) in band.px.iter().zip(data.chunks_exact_mut(channels)) {- photocraft_raster::from_rgba_into(&format, *pixel, encoded);- }- surface.write_region(band.rect, &data);- Ok(())- });- surface.prune();- surface+ // Also keeps a plain CMYK stack in its ink values (#3778).+ photocraft_compose::composite_to_surface(solo, area, format, background)}/// Apply an adjustment destructively to a surface, weighted by an optional selection.@@ -77,6 +56,9 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surfs.put_tiles(done);}+#[cfg(test)]+#[path = "flatten_cmyk_tests.rs"]+mod flatten_cmyk_tests;#[cfg(test)]#[path = "pixels_tests.rs"]mod tests;@@ -296,9 +278,12 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa}/// Merge `upper` onto `lower` producing a raster layer (Layer → Merge Down).-pub fn merge_down(doc_bounds: Rect, lower: &Layer, upper: &Layer, format: photocraft_color::PixelFormat) -> Layer {+pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer {+ let format = doc.pixel_format();let stack = vec![lower.clone(), upper.clone()];- let mut tmp = Document::new("merge", doc_bounds.size(), format.mode, format.sample);+ let mut tmp = Document::new("merge", doc.size, format.mode, format.sample);+ // The pair is read (and a CMYK one separated again) through the document's own profile.+ tmp.icc_profile = doc.icc_profile.clone();tmp.layers = stack;let s = composite_layers(&tmp, format, None);let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s));