diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index d0a160216bc..e7a50048ab6 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -32,6 +32,7 @@ pub mod native_lab; pub mod pattern; pub mod proxy; pub mod psblend; +pub mod scripted_pattern; pub mod shape_split; pub mod smart_mix; mod uniform; diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs new file mode 100644 index 00000000000..9def7a74936 --- /dev/null +++ b/crates/compose/src/scripted_pattern.rs @@ -0,0 +1,230 @@ +//! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a +//! plain repeat. Brick Fill is the first script; the others extend [`SCRIPTS`] and [`controls`] with their own layout. +//! +//! Every script shares the per-tile Color and Brightness randomness ([`Jitter`]): at 0 a tile keeps the pattern's +//! exact colours, above 0 each placed tile drifts by its own random amount. Areas no tile covers stay transparent. + +use photocraft_geom::Rect; + +use crate::pattern::{Placement, Tile}; + +/// The scripts in the Script list's order: (parameter value, name). The name is also the script dialog's title. +pub const SCRIPTS: [(&str, &str); 6] = [ + ("brickFill", "Brick Fill"), + ("crossWeave", "Cross Weave"), + ("placeAlongPath", "Place Along Path"), + ("randomFill", "Random Fill"), + ("spiral", "Spiral"), + ("symmetryFill", "Symmetry Fill"), +]; + +/// The scripts that paint today; the rest are listed but answer "not supported yet". +pub const SUPPORTED: [&str; 1] = ["brickFill"]; + +/// The parameter value of a script name, matched without regard to case. +pub fn script_key(name: &str) -> Option<&'static str> { + SCRIPTS.iter().map(|(k, _)| *k).find(|k| k.eq_ignore_ascii_case(name)) +} + +/// One value of a script dialog: its parameter key, factory value and range. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Control { + pub key: &'static str, + pub default: f64, + pub min: f64, + pub max: f64, + /// The most digits shown after the decimal mark. + pub decimals: u32, +} + +impl Control { + const fn new(key: &'static str, default: f64, min: f64, max: f64, decimals: u32) -> Control { + Control { key, default, min, max, decimals } + } + + /// `v` inside the range; a non-finite value takes the factory value. + pub fn clamp(&self, v: f64) -> f64 { + if v.is_finite() { v.clamp(self.min, self.max) } else { self.default } + } +} + +/// The Spacing range for a `width` x `height` pattern tile, in pixels: up to three tile widths apart, and overlapping +/// by up to the shorter side less 2 px (the measured -28 to 120 for a 40 x 30 tile). It does not change with the scale. +pub fn spacing_range(width: u32, height: u32) -> (f64, f64) { + let min = -f64::from(width.min(height).saturating_sub(2)); + (min, 3.0 * f64::from(width)) +} + +/// The values of `script` in its dialog's order, for a `width` x `height` pattern; `None` for an unknown script or one +/// that does not paint yet. +pub fn controls(script: &str, width: u32, height: u32) -> Option> { + match script { + "brickFill" => { + let (lo, hi) = spacing_range(width, height); + Some(vec![ + Control::new("patternScale", 1.0, 0.1, 1.25, 2), + Control::new("spacing", 0.0, lo, hi, 0), + Control::new("offsetBetweenRows", 50.0, -100.0, 100.0, 0), + Control::new("colorRandomness", 0.05, 0.0, 1.0, 2), + Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), + Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0), + ]) + } + _ => None, + } +} + +/// Per-tile colour and brightness drift, both 0..1, repeatable for one `seed`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Jitter { + pub color: f32, + pub brightness: f32, + pub seed: u64, +} + +/// How far each channel moves at randomness 1: a quarter of the range, so the default 0.05 / 0.1 shift a channel by a +/// few levels (one measured tile: blue 245 instead of 255). +const JITTER_REACH: f32 = 0.25; + +impl Jitter { + /// The change added to each channel of tile `(row, col)`: its own colour offsets plus one shared brightness offset. + fn offsets(&self, row: i64, col: i64) -> [f32; 3] { + if self.color <= 0.0 && self.brightness <= 0.0 { + return [0.0; 3]; + } + let mut state = self.seed ^ (row as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (col as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F); + let mut next = || { + // splitmix64: a well-mixed value per call, in -1..1. + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + ((z >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 + }; + let light = next() * self.brightness * JITTER_REACH; + let mut out = [0.0; 3]; + for o in &mut out { + *o = next() * self.color * JITTER_REACH + light; + } + out + } +} + +/// Brick Fill: rows of whole tiles from the canvas origin, every second row shifted by a share of the tile width. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BrickFill { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels between neighbouring tiles, across and down; negative overlaps them. + pub spacing: f64, + /// Shift of every second row to the left, in percent of the tile width (negative shifts right). + pub offset: f64, + /// Rotation of each tile about its centre, degrees counter-clockwise. + pub angle: f64, + pub jitter: Jitter, +} + +/// Most tiles composited into one pixel, front to back: bounds the work of extreme overlaps. Only a pixel whose +/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. +const MAX_LAYERS: usize = 1024; + +/// The x range where the convex polygon `corners` (in order) meets the line at height `y`, if it does. +fn span(corners: &[(f64, f64); 4], y: f64) -> Option<(f64, f64)> { + let mut range: Option<(f64, f64)> = None; + for i in 0..4 { + let (a, b) = (corners[i], corners[(i + 1) % 4]); + if (a.1 - y) * (b.1 - y) > 0.0 { + continue; + } + let x = if a.1 == b.1 { [a.0, b.0] } else { [a.0 + (b.0 - a.0) * (y - a.1) / (b.1 - a.1); 2] }; + for x in x { + range = Some(range.map_or((x, x), |(lo, hi)| (lo.min(x), hi.max(x)))); + } + } + range +} + +impl BrickFill { + /// The tiles of a `width` x `height` pattern laid out over `rect` (row-major straight RGBA, transparent where no + /// tile lies). Later tiles (down, then right) lie over earlier ones where they overlap. + pub fn render(&self, tile: &Tile, width: u32, height: u32, rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + // At the f32 precision the placement maps with, so the tile bounds here are the ones it samples. + let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 }; + let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale); + if len == 0 || tw <= 0.0 || th <= 0.0 { + return out; + } + let spacing = if self.spacing.is_finite() { self.spacing } else { 0.0 }; + // At least a pixel between tile origins, so every layout ends. + let (pitch_x, pitch_y) = ((tw + spacing).max(1.0), (th + spacing).max(1.0)); + let shift = if self.offset.is_finite() { self.offset / 100.0 * tw } else { 0.0 }; + let angle = if self.angle.is_finite() { self.angle } else { 0.0 }; + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + // The tile centres that put a pixel inside their tile form the turned tile rectangle around the pixel: its + // corners, relative to the pixel, and how far it reaches down. + let (a, b) = (tw / 2.0, th / 2.0); + let corners = [(a, b), (a, -b), (-a, -b), (-a, b)].map(|(hx, hy)| (hx * c + hy * s, -hx * s + hy * c)); + let reach_y = s.abs() * a + c.abs() * b; + let placement = |row: i64, col: i64| { + let x0 = col as f64 * pitch_x - if row.rem_euclid(2) == 1 { shift } else { 0.0 }; + let y0 = row as f64 * pitch_y; + let (cx, cy) = (x0 + tw / 2.0, y0 + th / 2.0); + // The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise). + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (cx + hx * c + hy * s, cy - hx * s + hy * c); + Placement::anchored(origin, true, (0.0, 0.0), scale as f32, angle as f32) + }; + let mut i = 0; + for y in rect.y0..rect.y1 { + let py = f64::from(y) + 0.5; + // Rows whose tiles can reach this line, the last drawn (topmost) first. + let top_row = ((py + reach_y - th / 2.0) / pitch_y).floor() as i64; + let low_row = ((py - reach_y - th / 2.0) / pitch_y).ceil() as i64; + for x in rect.x0..rect.x1 { + let px = f64::from(x) + 0.5; + let mut acc = [0.0f32; 4]; + let mut layers = 0; + 'rows: for row in (low_row..=top_row).rev() { + // Only the tiles of this row whose centre lies in the turned rectangle around the pixel cover it. + let Some((lo, hi)) = span(&corners, row as f64 * pitch_y + th / 2.0 - py) else { continue }; + let row_shift = if row.rem_euclid(2) == 1 { shift } else { 0.0 }; + let right = ((px + hi + row_shift - tw / 2.0) / pitch_x).floor() as i64; + let left = ((px + lo + row_shift - tw / 2.0) / pitch_x).ceil() as i64; + for col in (left..=right).rev() { + if layers >= MAX_LAYERS || acc[3] >= 1.0 { + break 'rows; + } + let place = placement(row, col); + let (u, v) = place.map(px, py); + if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { + continue; + } + layers += 1; + let mut q = tile.sample_area(&place, px, py); + let d = self.jitter.offsets(row, col); + // Without a drift a tile keeps its exact colour, also a float one past 1. + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + // Front to back: what is already in front covers this tile. + let k = q[3] * (1.0 - acc[3]); + for ch in 0..3 { + acc[ch] += q[ch] * k; + } + acc[3] += k; + } + } + if acc[3] > 0.0 { + out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)]; + } + i += 1; + } + } + out + } +} diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 2de505d99cb..bd5228cd88e 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -135,10 +135,16 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { // Edit › Fill (#14975). let space = photocraft_compose::pattern::PatternSpace::of_pixels(&st.doc); let tile = photocraft_compose::pattern::Tile::new_in(&pat, space).ok_or_else(|| bad("the pattern is empty or too large to paint"))?; - // Photoshop's Fill uses the canvas origin. - let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle); out["pattern"] = json!(pat.id); - Source::Pixels(area, photocraft_compose::pattern::render(&tile, &place, area)) + // With a script the pattern is laid out tile by tile instead of repeated. + if let Some(script) = script(p)? { + out["script"] = json!(script); + Source::Pixels(area, scripted(p, script, &tile, &pat, area)?) + } else { + // Photoshop's Fill uses the canvas origin. + let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle); + Source::Pixels(area, photocraft_compose::pattern::render(&tile, &place, area)) + } } "history" => { // A History panel row `state` or a `snapshot`, else the History Brush's source. @@ -190,6 +196,43 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The `script` param of a pattern fill: a [`SCRIPTS`](photocraft_compose::scripted_pattern::SCRIPTS) key, or none. +fn script(p: &Value) -> Result> { + use photocraft_compose::scripted_pattern::{SCRIPTS, script_key}; + match p.get("script") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(name)) => { + let names = SCRIPTS.iter().map(|(k, _)| *k).collect::>().join("|"); + script_key(name).map(Some).ok_or_else(|| bad(format!("unknown script `{name}` ({names})"))) + } + Some(v) => Err(bad(format!("`script` must be a script name, not {v}"))), + } +} + +/// The scripted pattern `script` laid out over `area`, with its values from `p` (each clamped to its range, the factory +/// value when missing) and an optional whole-number `seed` for the per-tile randomness. +fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, pat: &photocraft_doc::pattern::Pattern, area: Rect) -> Result> { + use photocraft_compose::scripted_pattern::{BrickFill, Jitter, controls}; + let controls = + controls(script, pat.width, pat.height).ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill paints today")))?; + let mut values = std::collections::HashMap::new(); + for c in &controls { + let v = match p.get(c.key) { + None | Some(Value::Null) => c.default, + Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(format!("`{}` must be a number {}..{}, not {v}", c.key, c.min, c.max)))?, + }; + values.insert(c.key, c.clamp(v)); + } + let seed = match p.get("seed") { + None | Some(Value::Null) => 1, + Some(v) => v.as_u64().ok_or_else(|| bad(format!("`seed` must be a whole number, not {v}")))?, + }; + let get = |k: &str| values.get(k).copied().unwrap_or_default(); + let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed }; + let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter }; + Ok(brick.render(tile, pat.width, pat.height, area)) +} + /// The reference application refuses Fill on the Quick Mask with a colour-only blend mode, Preserve Transparency or /// History contents, and leaves the channel as it was (#17489). fn check_quick_mask(contents: &str, mode: BlendMode, preserve: bool) -> Result<()> { diff --git a/crates/engine-paint/src/fill_script_brick_tests.rs b/crates/engine-paint/src/fill_script_brick_tests.rs new file mode 100644 index 00000000000..a5411907105 --- /dev/null +++ b/crates/engine-paint/src/fill_script_brick_tests.rs @@ -0,0 +1,227 @@ +//! #17428: Edit › Fill › Pattern with Script on lays the pattern out tile by tile. `edit.fill` takes `script` and the +//! script's values; Brick Fill paints rows of whole tiles from the canvas origin with every second row shifted left by +//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the five +//! listed scripts without a layout yet answer "not supported". + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const GREEN: [u8; 3] = [0, 255, 0]; + +/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green, so a shift, a turn +/// and a mirror all show. Defined as "probe" from a `mode` / `depth` document. +fn define_probe(s: &mut Session, mode: &str, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] { + s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap(); +} + +/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined. +fn session_in(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + define_probe(&mut s, mode, depth); + s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn session() -> Session { + session_in("rgb", 8) +} + +/// Brick Fill with both randomness values at 0 and `extra` values on top. +fn brick(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "brickFill", "colorRandomness": 0, "brightnessRandomness": 0}); + for (k, v) in extra.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p +} + +fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn rgb8(px: [f32; 4]) -> [u8; 3] { + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +/// The colour runs along row `y` from x 0 to 79 (two tile widths). +fn runs(s: &Session, y: i32) -> Vec<(i32, [u8; 3])> { + let mut out: Vec<(i32, [u8; 3])> = Vec::new(); + for x in 0..80 { + let c = rgb8(pixel(s, x, y)); + if out.last().is_none_or(|(_, last)| *last != c) { + out.push((x, c)); + } + } + out +} + +fn undo_label(s: &Session) -> Option { + s.active().unwrap().history.undo_label().map(str::to_string) +} + +#[test] +fn brick_fill_shifts_every_second_row_by_half_a_tile() { + let mut s = session(); + let r = s.execute("edit.fill", brick(json!({}))).unwrap(); + assert_eq!(r["script"], "brickFill"); + // Row 0 starts with the tile's left edge at x 0; row 1 (y 30-59) starts 20 px further left. + assert_eq!(runs(&s, 3), vec![(0, RED), (20, BLUE), (40, RED), (60, BLUE)]); + assert_eq!(runs(&s, 33), vec![(0, BLUE), (20, RED), (40, BLUE), (60, RED)]); + // The bottom quarter shows the shift too, and row 2 lines up with row 0 again. + assert_eq!(rgb8(pixel(&s, 5, 50)), GREEN); + assert_eq!(runs(&s, 63), runs(&s, 3)); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn brick_fill_differs_from_the_plain_pattern_fill() { + let mut plain = session(); + plain.execute("edit.fill", json!({"contents": "pattern", "pattern": "probe"})).unwrap(); + let mut scripted = session(); + scripted.execute("edit.fill", brick(json!({}))).unwrap(); + assert_eq!(runs(&plain, 3), runs(&scripted, 3), "row 0 is the plain repeat"); + assert_ne!(runs(&plain, 33), runs(&scripted, 33), "row 1 is shifted only with the script"); +} + +#[test] +fn row_offset_spacing_and_scale_move_the_tiles() { + // No offset: every row lines up like the plain repeat. + let mut s = session(); + s.execute("edit.fill", brick(json!({"offsetBetweenRows": 0}))).unwrap(); + assert_eq!(runs(&s, 33), runs(&s, 3)); + // Spacing leaves transparent gaps between tiles, across and down. + let mut s = session(); + s.execute("edit.fill", brick(json!({"spacing": 10, "offsetBetweenRows": 0}))).unwrap(); + assert_eq!(pixel(&s, 45, 3)[3], 0.0, "gap after the first tile"); + assert!(pixel(&s, 55, 3)[3] > 0.99, "the second tile starts after the gap"); + assert_eq!(pixel(&s, 5, 35)[3], 0.0, "gap under the first row"); + // Half the scale halves the tile. + let mut s = session(); + s.execute("edit.fill", brick(json!({"patternScale": 0.5, "offsetBetweenRows": 0}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 25, 3)), RED, "the second, half-size tile starts at x 20"); +} + +#[test] +fn a_turned_tile_is_no_longer_upright() { + let mut s = session(); + s.execute("edit.fill", brick(json!({"patternRotateAngle": 180}))).unwrap(); + // Turned half way, the tile's blue half comes first. + assert_eq!(rgb8(pixel(&s, 5, 20)), BLUE); +} + +#[test] +fn randomness_varies_tiles_only_above_zero() { + let mut exact = session(); + exact.execute("edit.fill", brick(json!({}))).unwrap(); + let mut drift = session(); + drift.execute("edit.fill", brick(json!({"colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap(); + // At 0 every tile keeps the pattern's colours. + for x in (5..600).step_by(40) { + assert_eq!(rgb8(pixel(&exact, x, 3)), RED, "x {x}"); + } + // Above 0 the tiles drift, each its own way, while one tile stays one colour. + let tiles: Vec<[u8; 3]> = (5..600).step_by(40).map(|x| rgb8(pixel(&drift, x, 3))).collect(); + assert!(tiles.iter().any(|c| *c != RED), "{tiles:?}"); + assert!(tiles.windows(2).any(|w| w[0] != w[1]), "tiles differ from each other: {tiles:?}"); + assert_eq!(rgb8(pixel(&drift, 5, 3)), rgb8(pixel(&drift, 15, 10)), "one tile drifts as a whole"); + // The factory values drift a little. + let mut default = session(); + let mut p = brick(json!({})); + p.as_object_mut().unwrap().retain(|k, _| !k.ends_with("Randomness")); + default.execute("edit.fill", p).unwrap(); + let tiles: Vec<[u8; 3]> = (5..600).step_by(40).map(|x| rgb8(pixel(&default, x, 3))).collect(); + assert!(tiles.iter().any(|c| *c != RED), "{tiles:?}"); +} + +#[test] +fn the_fill_stays_in_the_selection_with_mode_and_opacity() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + s.execute("edit.fill", brick(json!({"opacity": 50}))).unwrap(); + let inside = pixel(&s, 5, 3); + assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}"); + assert_eq!(pixel(&s, 150, 3)[3], 0.0, "outside the selection"); + assert_eq!(pixel(&s, 5, 80)[3], 0.0, "below the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 5, 3)[3], 0.0, "one history state"); +} + +#[test] +fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() { + let mut s = session(); + let before = undo_label(&s); + let err = s.execute("edit.fill", brick(json!({"script": "noSuchScript"}))).unwrap_err().to_string(); + assert!(err.contains("unknown script"), "{err}"); + for script in ["crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"] { + let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string(); + assert!(err.contains("not supported"), "{script}: {err}"); + } + assert_eq!(undo_label(&s), before, "nothing was filled"); + assert_eq!(pixel(&s, 5, 3)[3], 0.0); +} + +#[test] +fn bad_values_are_errors_and_out_of_range_ones_are_clamped() { + let mut s = session(); + for bad in [json!({"script": 3}), json!({"patternScale": "big"}), json!({"spacing": [1]}), json!({"seed": -1}), json!({"offsetBetweenRows": true})] { + assert!(s.execute("edit.fill", brick(bad.clone())).is_err(), "{bad}"); + } + // A huge scale paints at the 1.25 limit; a huge negative spacing at the overlap limit, without hanging. + let mut huge = session(); + huge.execute("edit.fill", brick(json!({"patternScale": 1e9, "offsetBetweenRows": 0}))).unwrap(); + let mut limit = session(); + limit.execute("edit.fill", brick(json!({"patternScale": 1.25, "offsetBetweenRows": 0}))).unwrap(); + assert_eq!(runs(&huge, 3), runs(&limit, 3)); + let mut s = session(); + s.execute("edit.fill", brick(json!({"spacing": -1e12, "patternRotateAngle": 45}))).unwrap(); +} + +#[test] +fn brick_fill_runs_in_every_mode_and_depth() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] { + let mut s = session_in(mode, depth); + s.execute("edit.fill", brick(json!({}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + // Row 1's first pixel shows the tile's right half, row 0's its left half. + let (row0, row1) = (pixel(&s, 5, 3), pixel(&s, 5, 33)); + assert!(row0[3] > 0.99 && row1[3] > 0.99, "{mode}/{depth}: painted"); + assert_ne!(rgb8(row0), rgb8(row1), "{mode}/{depth}: row 1 is shifted"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}"); + } +} + +#[test] +fn a_long_turned_tile_still_covers_pixels_far_from_its_centre() { + // A 4000 x 4 tile overlapping its neighbours by the most (2 px between rows) and turned 45°: about 2000 rows of + // tiles lie near each pixel, and the one that covers (1000, 200) has its centre 1000 px above it. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap(); + s.execute("file.new", json!({"width": 1200, "height": 400, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 995, "y": 195, "width": 10, "height": 10})).unwrap(); + let p = json!({"pattern": "bar", "spacing": -2, "offsetBetweenRows": 0, "patternRotateAngle": 45}); + s.execute("edit.fill", brick(p)).unwrap(); + let px = pixel(&s, 1000, 200); + assert!(px[3] > 0.99 && rgb8(px) == RED, "{px:?}"); +} + +#[test] +fn a_pixel_on_the_edge_of_a_scaled_tile_is_painted() { + // At scale 1.01249999 the tile is 40.5 px wide (at the placement's f32 precision a hair wider), so the centre of + // pixel 40 lies inside the first tile and must be painted, not left in the 1 px gap. + let mut s = session(); + s.execute("edit.fill", brick(json!({"patternScale": 1.012_499_99, "spacing": 1, "offsetBetweenRows": 0}))).unwrap(); + assert!(pixel(&s, 40, 5)[3] > 0.0, "{:?}", pixel(&s, 40, 5)); +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index 7c3836b8591..21025b6ed9b 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -46,6 +46,8 @@ mod eraser_gray_background_tests; #[cfg(test)] mod fill_quick_mask_refusals_tests; #[cfg(test)] +mod fill_script_brick_tests; +#[cfg(test)] mod mixer_indexed_bitmap_tests; #[cfg(test)] mod mixer_toggle_commands_tests; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 057910f752b..ed0d8058f9f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -40,8 +40,8 @@ pub(crate) mod params { use super::{ PhotocraftApp, alerts, brush_preset_dialog, canvas_input, channel_options_ui, color_picker_ui, color_table_ui, contact_sheet_ui, count_group_name_ui, - duplicate_layer_ui, equalize_ui, file_forms, fill_ui, filter_dialog, history_options_ui, image_processor_ui, merge_channels_ui, new_group_ui, - new_layer_ui, paragraph_text_size, smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui, + duplicate_layer_ui, equalize_ui, file_forms, fill_script_ui, fill_ui, filter_dialog, history_options_ui, image_processor_ui, merge_channels_ui, + new_group_ui, new_layer_ui, paragraph_text_size, smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui, }; use crate::canvas::document_display::CanvasHost; @@ -95,6 +95,7 @@ pub(crate) mod params { /// Every family of parameter dialogs, first match wins; the generic filter family owns what is left. pub(crate) const PARAM_FAMILIES: &[ParamFamily] = &[ ParamFamily { check: Some(fill_ui::check), ..ParamFamily::new(fill_ui::owns, fill_ui::run) }, + ParamFamily { check: Some(fill_ui::check), footer: Some(fill_script_ui::footer), ..ParamFamily::new(fill_script_ui::owns, fill_script_ui::run) }, ParamFamily { check: Some(stroke_ui::check), ..ParamFamily::new(stroke_ui::owns, stroke_ui::run) }, ParamFamily { check: Some(smart_filter_dialog::check), @@ -511,6 +512,7 @@ pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[ file_ui::take, format_prompts::take, pattern_fill_ui::take, + fill_script_ui::take, crate::workspace_ui::take, crate::kys_import::take, crate::prefs_ui::take_presets, @@ -834,6 +836,7 @@ pub mod export_dialog; pub(crate) mod fade_modes; pub mod file_forms; pub mod file_ui; +pub mod fill_script_ui; pub mod fill_ui; pub mod filter_dialog; pub(super) mod filter_preview_ui; diff --git a/crates/ui-egui/src/dialogs/fill_script_ui.rs b/crates/ui-egui/src/dialogs/fill_script_ui.rs new file mode 100644 index 00000000000..4d042d0effa --- /dev/null +++ b/crates/ui-egui/src/dialogs/fill_script_ui.rs @@ -0,0 +1,275 @@ +//! The script dialog of Edit › Fill › Pattern with Script on (#17428): OK in Fill opens the chosen script's own dialog, +//! titled with the script's name. Every script shares one layout: a live preview of the current values with the chosen +//! pattern, a Preset row (Default, Load / Save / Delete greyed, Custom), a field and slider per value, and OK, Reset and +//! Cancel. Reset restores the values the dialog opened with; Preset › Default sets the factory values, and changing a +//! value turns Preset back to Custom. The values are remembered per script after OK. Cancel fills nothing. + +use craft::ui::contract::Bind; +use craft::ui::dialog::{DialogId, StackDialog}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult, PreviewState}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::memory::{MemoryStage, SaveKey}; +use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::value_drag::SliderScale; +use photocraft_compose::scripted_pattern::{BrickFill, Control, Jitter, SCRIPTS, controls}; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::dialogs::params::{captured, memory_scope, open_param}; + +/// The dialog key of a script is this prefix and the script's parameter value (`edit.fill.script.brickFill`). +const PREFIX: &str = "edit.fill.script."; + +/// The side of the preview's sample area, in pattern pixels. +const PREVIEW: u32 = 256; + +/// The Preset entries: (value, label). Load, Save and Delete are listed greyed until presets can be filed. +const PRESETS: [(&str, &str); 5] = + [("default", "Default"), ("load", "Load Preset..."), ("save", "Save Preset..."), ("delete", "Delete Preset..."), ("custom", "Custom")]; + +/// The dialog key of `script`. +pub(crate) fn key(script: &str) -> String { + format!("{PREFIX}{script}") +} + +/// Whether the dialog `key` is a script dialog. +pub(crate) fn owns(key: &str) -> bool { + key.starts_with(PREFIX) +} + +fn script_of(key: &str) -> &str { + key.strip_prefix(PREFIX).unwrap_or_default() +} + +/// The label of a script value. +fn label(key: &str) -> Label { + Label::from(match key { + "patternScale" => tl!("Pattern Scale"), + "spacing" => tl!("Spacing"), + "offsetBetweenRows" => tl!("Offset between rows"), + "colorRandomness" => tl!("Color randomness"), + "brightnessRandomness" => tl!("Brightness randomness"), + "patternRotateAngle" => tl!("Pattern rotate angle"), + _ => tl!("Value"), + }) +} + +/// The unit shown after a value's field, if any. +fn unit(key: &str) -> Option