diff --git a/crates/engine-core/src/pixel_fill.rs b/crates/engine-core/src/pixel_fill.rs index 533280fbf30..95ab72b6472 100644 --- a/crates/engine-core/src/pixel_fill.rs +++ b/crates/engine-core/src/pixel_fill.rs @@ -198,6 +198,69 @@ pub fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<& Ok(()) } +/// Snap every pixel of `area` that `sel` covers (all of them without one) to black below 50 % grey and to white from +/// it, on the first sample: a Bitmap document's 1-bit pixels after a fill (#17475). Alpha is left as it is. +pub fn snap_black_white(surf: &mut Surface, area: Rect, sel: Option<&Surface>) -> Result<()> { + let fmt = surf.format(); + let n = fmt.channels(); + let bpp = fmt.bytes_per_pixel(); + let snapped = |pb: &[u8]| { + let v = photocraft_color::read_sample(pb, fmt.sample, 0); + if v >= 0.5 { 1.0 } else { 0.0 } + }; + let selected = |mask: Option<&Mask>, x: i32, y: i32| mask.is_none_or(|m| m.at(x, y) > 0.0); + let tiles = surf + .try_take_tiles(area) + .map_err(|e| EngineError::Other(format!("not enough memory while preparing pixel tiles ({e}); the document was not changed")))?; + let mut done = crate::allocation::capacity(tiles.len(), "snapping pixels to black or white")?; + for (tc, tile) in tiles { + let tr = tc.rect().intersect(&area); + let mask = sel.map(|m| Mask::of(m, tc)); + let at = |x: i32, y: i32| ((y - tc.rect().y0) as usize * TILE_SIZE as usize + (x - tc.rect().x0) as usize) * bpp; + // Tiles already black and white (a solid black or white fill, untouched pixels) stay shared. + let grey = { + let bytes = tile.bytes(); + (tr.y0..tr.y1).any(|y| { + (tr.x0..tr.x1).any(|x| { + selected(mask.as_ref(), x, y) + && bytes.get(at(x, y)..at(x, y) + bpp).is_some_and(|pb| photocraft_color::read_sample(pb, fmt.sample, 0) != snapped(pb)) + }) + }) + }; + if !grey { + done.push((tc, tile)); + continue; + } + let mut tile = match std::sync::Arc::try_unwrap(tile) { + Ok(tile) => tile, + Err(tile) => tile + .try_clone() + .map_err(|e| EngineError::Other(format!("not enough memory while snapping a pixel tile ({e}); the document was not changed")))?, + }; + { + let mut bytes = tile.bytes_mut(); + let mut px = [0.0f32; 8]; + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + if !selected(mask.as_ref(), x, y) { + continue; + } + let i = at(x, y); + let Some(pb) = bytes.get_mut(i..i + bpp) else { continue }; + for (c, v) in px.iter_mut().enumerate().take(n) { + *v = photocraft_color::read_sample(pb, fmt.sample, c); + } + px[0] = snapped(pb); + photocraft_raster::encode_pixel(&fmt, &px[..n.min(8)], pb); + } + } + } + done.push((tc, std::sync::Arc::new(tile))); + } + surf.put_tiles(done); + Ok(()) +} + /// The selection's coverage over one tile (its channel 0). pub struct Mask<'a> { bytes: Option>, diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 7968d1cc76d..1c6edb58d0b 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -6,7 +6,7 @@ //! Every parameter is validated: a bad one is an error, never a panic. use photocraft_algo::content_aware::FillOptions; -use photocraft_color::BlendMode; +use photocraft_color::{BlendMode, ColorMode}; use photocraft_geom::Rect; #[cfg(test)] use photocraft_geom::TILE_SIZE; @@ -17,7 +17,7 @@ use serde_json::{Value, json}; use crate::commands::{cmyk_param, color_param, layer_param, parse_blend}; use crate::content_sampling::{content_aware, content_aware_options}; pub use crate::pixel_fill::greyed_modes; -use crate::pixel_fill::{Blend, Source, blend_into, check_mode_available, read_rgba}; +use crate::pixel_fill::{Blend, Source, blend_into, check_mode_available, read_rgba, snap_black_white}; use crate::{EngineError, Result, Session}; const CMD: &str = "edit.fill"; @@ -79,6 +79,10 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { let id = if channel { None } else { Some(layer_param(s, p)?) }; let st = s.active().ok_or(EngineError::NoDocument)?; check_mode_available(CMD, &st.doc, mode)?; + // A Bitmap document holds black or white only: opacity is an on/off threshold at 50 % (Dissolve keeps its odds), + // and the filled pixels snap to black or white below (#17475). + let bitmap = st.doc.mode == ColorMode::Bitmap; + let opacity = if bitmap && mode != BlendMode::Dissolve { if opacity >= 0.5 { 1.0 } else { 0.0 } } else { opacity }; let doc_bounds = st.doc.bounds(); let sel = st.doc.selection.clone(); let area = sel.as_ref().map_or(doc_bounds, |m| m.content_bounds().intersect(&doc_bounds)); @@ -152,6 +156,9 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { let sel = doc.selection.clone(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore })?; + if bitmap { + snap_black_white(surf, area, sel.as_ref())?; + } Ok(()) }) })?; @@ -172,6 +179,9 @@ mod tests; #[cfg(test)] mod mode_by_document_tests; +#[cfg(test)] +mod bitmap_threshold_tests; + #[cfg(test)] #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; diff --git a/crates/engine-paint/src/cmd/fill_cmds/bitmap_threshold_tests.rs b/crates/engine-paint/src/cmd/fill_cmds/bitmap_threshold_tests.rs new file mode 100644 index 00000000000..acf6a079f16 --- /dev/null +++ b/crates/engine-paint/src/cmd/fill_cmds/bitmap_threshold_tests.rs @@ -0,0 +1,97 @@ +//! #17475: Edit › Fill in a Bitmap document writes black or white only, and its opacity is an on/off threshold at +//! 50 %. Dissolve keeps its random mix; fills in other colour modes still blend greys. + +use super::*; +use serde_json::json; + +const BLACK_SIDE: (i32, i32) = (75, 50); +const WHITE_SIDE: (i32, i32) = (125, 50); + +/// A 200×100 document of `mode`, its left half black, with the selection 50,25-150,75 over both halves. +fn half_black(mode: &str) -> Session { + let mut s = crate::session(); + let depth = if mode == "bitmap" { 1 } else { 8 }; + s.execute("file.new", json!({"width": 200, "height": 100, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute(CMD, json!({"contents": "black"})).unwrap(); + s.execute("select.rect", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap(); + s +} + +/// The grey sample at (`x`, `y`) of the active layer, 0..1. +fn grey(s: &Session, (x, y): (i32, i32)) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(x, y, x + 1, y + 1))[0] +} + +/// Every grey sample of the selected area that is neither black nor white. +fn greys_in_selection(s: &Session) -> Vec { + let st = s.active().unwrap(); + let px = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(50, 25, 150, 75)); + px.as_chunks::<2>().0.iter().map(|p| p[0]).filter(|v| *v != 0.0 && *v != 1.0).collect() +} + +/// Fills with `params` and returns the grey over the black half and over the white half; asserts that no grey value +/// is left in the selection. +fn fill(params: Value) -> (f32, f32) { + let mut s = half_black("bitmap"); + s.tools.foreground = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + s.execute(CMD, params.clone()).unwrap(); + assert_eq!(greys_in_selection(&s), Vec::::new(), "{params}: only black or white in a Bitmap document"); + (grey(&s, BLACK_SIDE), grey(&s, WHITE_SIDE)) +} + +#[test] +fn colours_become_black_or_white() { + let cases = [ + (json!({"contents": "foreground"}), 0.0), + (json!({"contents": "color", "color": [100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0]}), 0.0), + (json!({"contents": "color", "color": [140.0 / 255.0, 140.0 / 255.0, 140.0 / 255.0]}), 1.0), + (json!({"contents": "black"}), 0.0), + (json!({"contents": "white"}), 1.0), + ]; + for (params, want) in cases { + assert_eq!(fill(params.clone()), (want, want), "{params}"); + } + // 50% Gray was not measured: it only has to land on one side. + let (b, w) = fill(json!({"contents": "gray"})); + assert_eq!(b, w); +} + +#[test] +fn opacity_is_a_threshold_at_half() { + // White over black: below 50 % nothing changes, from 50 % it is white. + assert_eq!(fill(json!({"contents": "white", "opacity": 49})), (0.0, 1.0)); + assert_eq!(fill(json!({"contents": "white", "opacity": 50})), (1.0, 1.0)); + // Black over white, the other way round. + assert_eq!(fill(json!({"contents": "black", "opacity": 49})), (0.0, 1.0)); + assert_eq!(fill(json!({"contents": "black", "opacity": 50})), (0.0, 0.0)); +} + +#[test] +fn dissolve_keeps_a_random_mix() { + let mut s = half_black("bitmap"); + s.execute(CMD, json!({"contents": "white", "mode": "dissolve", "opacity": 50})).unwrap(); + assert_eq!(greys_in_selection(&s), Vec::::new()); + let st = s.active().unwrap(); + let px = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(50, 25, 100, 75)); + let white = px.as_chunks::<2>().0.iter().filter(|p| p[0] == 1.0).count(); + let all = px.len() / 2; + assert!(white > 0 && white < all, "a mix over the black half: {white} of {all} white"); +} + +#[test] +fn darken_and_lighten_keep_their_results() { + assert_eq!(fill(json!({"contents": "white", "mode": "darken"})), (0.0, 1.0)); + assert_eq!(fill(json!({"contents": "white", "mode": "lighten"})), (1.0, 1.0)); + assert_eq!(fill(json!({"contents": "black", "mode": "darken"})), (0.0, 0.0)); + assert_eq!(fill(json!({"contents": "black", "mode": "lighten"})), (0.0, 1.0)); +} + +#[test] +fn other_colour_modes_still_blend_greys() { + let mut s = half_black("grayscale"); + s.execute(CMD, json!({"contents": "white", "opacity": 49})).unwrap(); + let g = grey(&s, BLACK_SIDE); + assert!(g > 0.0 && g < 1.0, "a grey between black and white: {g}"); +}