diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index b8a183e2d9..3be7ed0112 100644 --- a/crates/compose/src/scripted_pattern.rs +++ b/crates/compose/src/scripted_pattern.rs @@ -1,6 +1,6 @@ //! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a -//! plain repeat. Brick Fill, Cross Weave, Random Fill and Spiral paint today; the others extend [`SCRIPTS`], [`controls`] -//! and [`render`] with their own layout. +//! plain repeat. Brick Fill, Cross Weave, Place Along Path, Random Fill and Spiral paint today; the others extend +//! [`SCRIPTS`], [`controls`] and [`render`] 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. @@ -25,11 +25,16 @@ pub const SCRIPTS: [(&str, &str); 6] = [ ]; /// The scripts that paint today; the rest are listed but answer "not supported yet". -pub const SUPPORTED: [&str; 4] = ["brickFill", "crossWeave", "randomFill", "spiral"]; +pub const SUPPORTED: [&str; 5] = ["brickFill", "crossWeave", "placeAlongPath", "randomFill", "spiral"]; /// Whether `script` keeps its tiles near the selected path when there is one. pub fn uses_path(script: &str) -> bool { - script == "randomFill" + matches!(script, "placeAlongPath" | "randomFill") +} + +/// Whether `script` lays its tiles along the selected path only, and so needs one. +pub fn needs_path(script: &str) -> bool { + script == "placeAlongPath" } /// The parameter value of a script name, matched without regard to case. @@ -55,6 +60,7 @@ impl Control { Control { key, default, min, max, decimals, toggle: false } } + /// A check box, ticked by default when `on`. const fn check(key: &'static str, on: bool) -> Control { Control { key, default: if on { 1.0 } else { 0.0 }, min: 0.0, max: 1.0, decimals: 0, toggle: true } } @@ -122,6 +128,28 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option> { Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), ]) } + "placeAlongPath" => Some(vec![ + Control::new("patternScale", 1.0, 0.1, 1.25, 2), + Control::new("spacing", 0.0, -50.0, 150.0, 0), + Control::check("adjustSpacingToFit", false), + Control::new("angleFromPath", 0.0, -90.0, 90.0, 0), + Control::new("distanceFromPath", 0.0, 0.0, 200.0, 0), + Control::check("alternatePatterns", true), + Control::new("scaleProgression", 100.0, 90.0, 110.0, 0), + Control::check("skipSymbolRotation", false), + Control::new("colorRandomness", 0.05, 0.0, 1.0, 2), + Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), + ]), + _ => None, + } +} + +/// The value that greys `key` while it is ticked, in a script's dialog: Adjust spacing to fit sets the spacing itself and +/// Skip symbol rotation keeps tiles upright, so neither Spacing nor Angle from path applies. +pub fn greyed_by(script: &str, key: &str) -> Option<&'static str> { + match (script, key) { + ("placeAlongPath", "spacing") => Some("adjustSpacingToFit"), + ("placeAlongPath", "angleFromPath") => Some("skipSymbolRotation"), _ => None, } } @@ -446,13 +474,29 @@ pub fn render(script: &str, value: &dyn Fn(&str) -> f64, seed: u64, tile: &Tile, }; Some(spiral.render(tile, width, height, rect)) } + "placeAlongPath" => { + let on = |k: &str| value(k) >= 0.5; + let layout = PlaceAlongPath { + scale: value("patternScale"), + spacing: value("spacing"), + fit: on("adjustSpacingToFit"), + angle: value("angleFromPath"), + distance: value("distanceFromPath"), + alternate: on("alternatePatterns"), + progression: value("scaleProgression"), + upright: on("skipSymbolRotation"), + jitter, + }; + Some(layout.render(tile, width, height, path.unwrap_or_default(), rect)) + } _ => None, } } -/// The polylines of `path` that a script lays its tiles along. +/// The polylines of `path` that a script lays its tiles along, flattened finely enough for Place Along Path's tile +/// positions. pub fn path_lines(path: &Path) -> Vec { - flatten_path(path, 0.25) + flatten_path(path, 0.1) } /// The built-in curve the dialog previews a path script on: one wave across a `side` x `side` sample area. @@ -806,3 +850,149 @@ impl Spiral { out } } + +/// Place Along Path: tiles one after another along each subpath of the selected path, the first centred on the start +/// point and each turned with the path; a tile is placed only while it ends before the path does. Later tiles lie over +/// earlier ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PlaceAlongPath { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels added to the step between tile centres (the tile's shorter side); negative packs them closer. + pub spacing: f64, + /// Stretch the steps so the last tile ends exactly at the path's end; Spacing does not apply. + pub fit: bool, + /// Turn of each tile against the path direction, degrees counter-clockwise. + pub angle: f64, + /// How far the tiles sit off the path, in pixels, to the left of its direction. + pub distance: f64, + /// Every other tile mirrored top to bottom, starting with the first (measured with one pattern). + pub alternate: bool, + /// Each tile's size against the one before, in percent. + pub progression: f64, + /// Tiles stay upright instead of following the path direction; Angle from path does not apply. + pub upright: bool, + pub jitter: Jitter, +} + +/// Most tiles one fill lays along its paths: bounds the work of a huge path at the tightest step. +const MAX_PATH_TILES: usize = 100_000; + +/// One tile on the path: its centre on the path, the path's unit direction there, its scale, and (subpath, index). +#[derive(Clone, Copy, Debug)] +struct OnPath { + point: (f64, f64), + dir: (f64, f64), + scale: f64, + id: (i64, i64), +} + +impl PlaceAlongPath { + /// The tiles along a path `len` long, for a `w` x `h` pattern at `scale`: (arc length of the centre, tile scale), + /// at most `budget` of them (taken from it). + fn positions(&self, len: f64, (w, h): (f64, f64), scale: f64, budget: &mut usize) -> Vec<(f64, f64)> { + let progression = if self.progression.is_finite() && self.progression > 0.0 { self.progression / 100.0 } else { 1.0 }; + let spacing = if self.fit || !self.spacing.is_finite() { 0.0 } else { self.spacing }; + let mut out: Vec<(f64, f64)> = Vec::new(); + let (mut at, mut k) = (0.0, scale); + while *budget > 0 && k.is_finite() && k >= crate::pattern::MIN_PLACEMENT_SCALE { + // The first tile always sits on the start point; the others only while they end before the path does. + if !out.is_empty() && at + w * k / 2.0 > len + 1e-9 { + break; + } + out.push((at, k)); + *budget -= 1; + // At least a pixel between tile centres, so every layout ends. + at += (w.min(h) * k + spacing).max(1.0); + k = f64::from((k * progression) as f32); + } + if self.fit + && let Some(&(last, k)) = out.last() + && last > 0.0 + { + let stretch = (len - w * k / 2.0).max(0.0) / last; + for p in &mut out { + p.0 *= stretch; + } + } + out + } + + /// The tiles of a `width` x `height` pattern laid along `lines` over `rect` (row-major straight RGBA, transparent + /// where no tile lies). + pub fn render(&self, tile: &Tile, width: u32, height: u32, lines: &[Polyline], rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + if len == 0 || width == 0 || height == 0 { + return out; + } + // 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 size = (f64::from(width), f64::from(height)); + let mut budget = MAX_PATH_TILES; + for (n, line) in lines.iter().enumerate() { + let places = self.positions(line.length(), size, scale, &mut budget); + let at: Vec = places.iter().map(|p| p.0).collect(); + for (k, ((point, dir), &(_, scale))) in line.sample(&at).into_iter().zip(&places).enumerate() { + self.draw(tile, size, OnPath { point, dir, scale, id: (n as i64, k as i64) }, rect, &mut out); + } + } + out + } + + /// Draws tile `on` of a `size` pattern over what `out` (laid over `rect`) holds. + fn draw(&self, tile: &Tile, size: (f64, f64), on: OnPath, rect: Rect, out: &mut [[f32; 4]]) { + let (tw, th) = (size.0 * on.scale, size.1 * on.scale); + let turn = if self.angle.is_finite() { self.angle } else { 0.0 }; + // Counter-clockwise on screen (y down) is against the path's own turn. + let angle = if self.upright { 0.0 } else { -on.dir.1.atan2(on.dir.0).to_degrees() + turn }; + let distance = if self.distance.is_finite() { self.distance } else { 0.0 }; + let centre = (on.point.0 + on.dir.1 * distance, on.point.1 - on.dir.0 * distance); + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (centre.0 + hx * c + hy * s, centre.1 - hx * s + hy * c); + let place = Placement::anchored(origin, true, (0.0, 0.0), on.scale as f32, angle as f32); + // The pixels the turned tile can reach, inside `rect`. + let (ex, ey) = (c.abs() * tw / 2.0 + s.abs() * th / 2.0, s.abs() * tw / 2.0 + c.abs() * th / 2.0); + let clamp = |v: f64, lo: i32, hi: i32| if v.is_nan() { lo } else { v.clamp(f64::from(lo), f64::from(hi)) as i32 }; + let (x0, x1) = (clamp((centre.0 - ex).floor(), rect.x0, rect.x1), clamp((centre.0 + ex).ceil(), rect.x0, rect.x1)); + let (y0, y1) = (clamp((centre.1 - ey).floor(), rect.y0, rect.y1), clamp((centre.1 + ey).ceil(), rect.y0, rect.y1)); + // Mirrored top to bottom: each pixel is read from its reflection across the tile's middle line. + let mirror = self.alternate && on.id.1 % 2 == 0; + let axis = (c, -s); + let stride = rect.width() as usize; + for y in y0..y1 { + for x in x0..x1 { + let (mut px, mut py) = (f64::from(x) + 0.5, f64::from(y) + 0.5); + if mirror { + let (dx, dy) = (px - centre.0, py - centre.1); + let along = dx * axis.0 + dy * axis.1; + (px, py) = (centre.0 + 2.0 * along * axis.0 - dx, centre.1 + 2.0 * along * axis.1 - dy); + } + let (u, v) = place.map(px, py); + if !(0.0..size.0).contains(&u) || !(0.0..size.1).contains(&v) { + continue; + } + let mut q = tile.sample_area(&place, px, py); + let d = self.jitter.offsets(on.id.0, on.id.1); + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + // The new tile over what lies under it. + let i = (y - rect.y0) as usize * stride + (x - rect.x0) as usize; + let under = out[i]; + let a = q[3] + under[3] * (1.0 - q[3]); + if a > 0.0 { + let mut mixed = [0.0f32; 4]; + for ch in 0..3 { + mixed[ch] = (q[ch] * q[3] + under[ch] * under[3] * (1.0 - q[3])) / a; + } + mixed[3] = a.min(1.0); + out[i] = mixed; + } + } + } + } +} diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 413216ee28..b5049424fe 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -206,7 +206,14 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { // With a script the pattern is laid out tile by tile instead of repeated. if let Some(script) = script(p)? { out["script"] = json!(script); - let path = if photocraft_compose::scripted_pattern::uses_path(script) { script_path(s, p)? } else { None }; + use photocraft_compose::scripted_pattern::{needs_path, path_lines, uses_path}; + let path = if needs_path(script) { + Some(path_lines(&selected_path(s, p)?)) + } else if uses_path(script) { + script_path(s, p)? + } else { + None + }; let place = photocraft_compose::scripted_pattern::Area { rect: area, canvas: doc_bounds, path: path.as_deref() }; Source::Pixels(area, scripted(p, script, &tile, &pat, place)?) } else { @@ -449,6 +456,28 @@ fn script_path(s: &Session, p: &Value) -> Result Result { + const NONE: &str = "No path selected. Please select at least one path"; + let name = match p.get("path") { + // A plain message, as it is the user's to act on: the reference application's alert names no parameter. + None | Some(Value::Null) => return Err(EngineError::Other(NONE.into())), + Some(Value::String(name)) => name.as_str(), + Some(v) => return Err(bad(format!("`path` must be a path name, not {v}"))), + }; + let st = s.active().ok_or(EngineError::NoDocument)?; + let path = match name { + "work" => st.doc.work_path.as_ref(), + "layer" => st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| match &l.content { + photocraft_doc::LayerContent::Shape(shape) => Some(&shape.path), + _ => l.vector_mask.as_ref().map(|v| &v.path), + }), + name => st.doc.paths.iter().find(|q| q.name == name).map(|q| &q.path), + }; + path.cloned().ok_or_else(|| EngineError::Other(NONE.into())) +} + /// 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 index 25b1539b40..2748dd5d52 100644 --- a/crates/engine-paint/src/fill_script_brick_tests.rs +++ b/crates/engine-paint/src/fill_script_brick_tests.rs @@ -1,7 +1,7 @@ //! #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 -//! listed scripts without a layout yet answer "not supported". +//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the listed +//! scripts without a layout yet answer "not supported". use serde_json::{Value, json}; @@ -163,10 +163,8 @@ fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() { 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 ["placeAlongPath", "symmetryFill"] { - let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string(); - assert!(err.contains("not supported"), "{script}: {err}"); - } + let err = s.execute("edit.fill", brick(json!({"script": "symmetryFill"}))).unwrap_err().to_string(); + assert!(err.contains("not supported"), "{err}"); assert_eq!(undo_label(&s), before, "nothing was filled"); assert_eq!(pixel(&s, 5, 3)[3], 0.0); } diff --git a/crates/engine-paint/src/fill_script_place_along_path_tests.rs b/crates/engine-paint/src/fill_script_place_along_path_tests.rs new file mode 100644 index 0000000000..88f6eef0d5 --- /dev/null +++ b/crates/engine-paint/src/fill_script_place_along_path_tests.rs @@ -0,0 +1,247 @@ +//! #17430: Edit › Fill › Pattern with the Place Along Path script lays the pattern tile along the selected path +//! (`path`: "work", "layer" or a saved path's name). On a straight path the tiles are centred on the line, the first on +//! the start point, a step of the tile's shorter side apart, the last ending where the path does, every other tile +//! mirrored top to bottom. Without a selected path the fill is refused and nothing changes. + +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]; + +/// A 600 x 400 white document with an empty pixel layer on top (active) and the 40 x 30 probe pattern defined: left +/// half red, right half blue, the bottom-right 20 x 15 quarter green, so a turn and a mirror show. The saved path +/// "line" runs from (50,200) to (550,200). +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 30, "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(); + s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + set_path(&mut s, "line", json!([[50, 200], [550, 200]])); + s +} + +/// Saves an open path `name` through `knots`. +fn set_path(s: &mut Session, name: &str, knots: Value) { + s.execute("path.set", json!({"name": name, "path": {"subpaths": [{"closed": false, "knots": knots}]}})).unwrap(); +} + +/// Place Along Path along "line" with both randomness values at 0 and `extra` values on top. +fn along(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "placeAlongPath", "path": "line", "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 painted pixels' bounds, (x0, y0, x1, y1) exclusive, if any. +fn bounds(s: &Session) -> Option<(i32, i32, i32, i32)> { + let mut b: Option<(i32, i32, i32, i32)> = None; + for y in 0..400 { + for x in 0..600 { + if pixel(s, x, y)[3] > 0.0 { + b = Some(b.map_or((x, y, x + 1, y + 1), |(x0, y0, x1, y1)| (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)))); + } + } + } + b +} + +/// The colour runs along row `y` between `from` and `to`. +fn runs(s: &Session, y: i32, from: i32, to: i32) -> Vec<(i32, [u8; 3])> { + let mut out: Vec<(i32, [u8; 3])> = Vec::new(); + for x in from..to { + 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 tiles_step_along_a_straight_path_from_its_start_to_its_end() { + let mut s = session(); + let r = s.execute("edit.fill", along(json!({}))).unwrap(); + assert_eq!(r["script"], "placeAlongPath"); + // Centred on the line, the first tile on the start point, the last ending at the path's end. + assert_eq!(bounds(&s), Some((30, 185, 550, 215))); + // Each tile lies over the one before, 30 px on: 20 px of red, then the 10 px of the earlier tile left showing. The + // first, third, ... are mirrored, so their upper half shows green where the pattern has blue. + let top = runs(&s, 190, 30, 130); + assert_eq!(top, vec![(30, RED), (50, GREEN), (60, RED), (80, BLUE), (90, RED), (110, GREEN), (120, RED)]); + let bottom = runs(&s, 210, 30, 130); + assert_eq!(bottom, vec![(30, RED), (50, BLUE), (60, RED), (80, GREEN), (90, RED), (110, BLUE), (120, RED)]); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn alternate_patterns_off_leaves_every_tile_as_the_pattern() { + let mut s = session(); + s.execute("edit.fill", along(json!({"alternatePatterns": false}))).unwrap(); + assert_eq!(runs(&s, 190, 30, 100), vec![(30, RED), (50, BLUE), (60, RED), (80, BLUE), (90, RED)]); +} + +#[test] +fn tiles_turn_with_the_path_unless_rotation_is_skipped() { + // Down the canvas: each tile turns a quarter, so it is 30 px wide across the path. + let mut s = session(); + set_path(&mut s, "line", json!([[300, 50], [300, 350]])); + s.execute("edit.fill", along(json!({}))).unwrap(); + let (x0, _, x1, _) = bounds(&s).unwrap(); + assert_eq!((x0, x1), (285, 315)); + // Upright tiles stay 40 px wide. + let mut s = session(); + set_path(&mut s, "line", json!([[300, 50], [300, 350]])); + s.execute("edit.fill", along(json!({"skipSymbolRotation": true, "angleFromPath": 45}))).unwrap(); + let (x0, _, x1, _) = bounds(&s).unwrap(); + assert_eq!((x0, x1), (280, 320)); +} + +#[test] +fn distance_spacing_and_scale_move_the_tiles() { + let mut plain = session(); + plain.execute("edit.fill", along(json!({}))).unwrap(); + let plain = bounds(&plain).unwrap(); + // Distance lifts the tiles off the path, to the left of its direction (up for a path heading right). + let mut s = session(); + s.execute("edit.fill", along(json!({"distanceFromPath": 50}))).unwrap(); + let lifted = bounds(&s).unwrap(); + assert!(lifted.1 < plain.1 && lifted.3 < plain.3, "{lifted:?} above {plain:?}"); + // More spacing leaves gaps between the tiles. + let mut s = session(); + s.execute("edit.fill", along(json!({"spacing": 20}))).unwrap(); + assert!(pixel(&s, 72, 200)[3] == 0.0 && pixel(&s, 85, 200)[3] > 0.99, "a gap after the first tile"); + // A smaller scale makes smaller tiles. + let mut s = session(); + s.execute("edit.fill", along(json!({"patternScale": 0.5}))).unwrap(); + let small = bounds(&s).unwrap(); + assert!(small.3 - small.1 < plain.3 - plain.1, "{small:?} lower than {plain:?}"); + // A growing scale progression makes later tiles taller. + let mut s = session(); + s.execute("edit.fill", along(json!({"scaleProgression": 110}))).unwrap(); + let grown = bounds(&s).unwrap(); + assert!(grown.3 - grown.1 > plain.3 - plain.1, "{grown:?} taller than {plain:?}"); +} + +#[test] +fn adjust_spacing_to_fit_ignores_spacing_and_ends_at_the_path_end() { + let mut fit = session(); + fit.execute("edit.fill", along(json!({"adjustSpacingToFit": true}))).unwrap(); + let mut wide = session(); + wide.execute("edit.fill", along(json!({"adjustSpacingToFit": true, "spacing": 37}))).unwrap(); + assert_eq!(runs(&fit, 190, 0, 600), runs(&wide, 190, 0, 600), "Spacing does not apply"); + // A path whose length leaves a remainder: the steps stretch so the last tile still ends at the path end. + let mut s = session(); + set_path(&mut s, "line", json!([[50, 200], [565, 200]])); + s.execute("edit.fill", along(json!({"adjustSpacingToFit": true}))).unwrap(); + assert_eq!(bounds(&s).map(|b| (b.0, b.2)), Some((30, 565))); + let mut s = session(); + set_path(&mut s, "line", json!([[50, 200], [565, 200]])); + s.execute("edit.fill", along(json!({}))).unwrap(); + assert!(bounds(&s).unwrap().2 < 565, "without it the last tile stops short"); +} + +#[test] +fn without_a_selected_path_nothing_is_filled() { + let mut s = session(); + let before = undo_label(&s); + let mut p = along(json!({})); + p.as_object_mut().unwrap().remove("path"); + for p in [p, along(json!({"path": "no such path"})), along(json!({"path": "work"})), along(json!({"path": "layer"}))] { + let err = s.execute("edit.fill", p.clone()).unwrap_err().to_string(); + assert!(err.contains("No path selected"), "{p}: {err}"); + } + assert_eq!(undo_label(&s), before, "no history state"); + assert_eq!(bounds(&s), None, "no pixels"); +} + +#[test] +fn the_work_path_and_the_layer_path_can_be_followed() { + let mut s = session(); + s.execute("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[50, 100], [200, 100]]}]}})).unwrap(); + s.execute("edit.fill", along(json!({"path": "work"}))).unwrap(); + assert_eq!(bounds(&s).map(|b| (b.1, b.3)), Some((85, 115))); +} + +#[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": 400})).unwrap(); + s.execute("edit.fill", along(json!({"opacity": 50}))).unwrap(); + assert!((pixel(&s, 35, 200)[3] - 0.5).abs() < 0.01, "half opacity"); + assert_eq!(pixel(&s, 150, 200)[3], 0.0, "outside the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 35, 200)[3], 0.0, "one history state"); + // A blend mode applies too: Multiply over the empty layer still paints the tile's colour. + s.execute("select.deselect", json!({})).unwrap(); + s.execute("edit.fill", along(json!({"mode": "multiply"}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 35, 200)), RED); +} + +#[test] +fn bad_values_are_errors() { + let mut s = session(); + for bad in [json!({"path": 3}), json!({"adjustSpacingToFit": 1}), json!({"alternatePatterns": "yes"}), json!({"spacing": "far"})] { + assert!(s.execute("edit.fill", along(bad.clone())).is_err(), "{bad}"); + } + assert_eq!(bounds(&s), None); +} + +#[test] +fn never_panics_on_odd_paths_or_values() { + let paths = [ + json!([[300, 200]]), + json!([[300, 200], [300, 200]]), + json!([[300, 200], [300, 200], [400, 200]]), + json!([[-1e12, 200], [1e12, 200]]), + json!([[1e15, 1e15], [-1e15, -1e15]]), + json!([[0, 0], [600, 400], [0, 400], [600, 0]]), + ]; + let values = [ + json!({}), + json!({"patternScale": 1e9, "spacing": -1e12, "scaleProgression": 1e9}), + json!({"patternScale": 0, "scaleProgression": 0, "distanceFromPath": 1e12, "angleFromPath": -1e9}), + json!({"adjustSpacingToFit": true, "colorRandomness": 1, "brightnessRandomness": 1, "seed": 7}), + ]; + for knots in &paths { + for v in &values { + let mut s = session(); + set_path(&mut s, "line", knots.clone()); + s.execute("edit.fill", along(v.clone())).unwrap_or_else(|e| panic!("{knots} {v}: {e}")); + } + } + // A closed curved path and an empty one. + let mut s = session(); + let curve = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [300, 100], "in": [250, 100], "out": [350, 100]}, + {"anchor": [300, 300], "in": [350, 300], "out": [250, 300]} + ]}]}); + s.execute("path.set", json!({"name": "line", "path": curve})).unwrap(); + s.execute("edit.fill", along(json!({}))).unwrap(); + assert!(bounds(&s).is_some()); + s.execute("path.set", json!({"name": "line", "path": {"subpaths": []}})).unwrap(); + s.execute("edit.fill", along(json!({}))).unwrap(); +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index b49732a0fe..a826a1c106 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -50,6 +50,8 @@ mod fill_script_brick_tests; #[cfg(test)] mod fill_script_cross_weave_tests; #[cfg(test)] +mod fill_script_place_along_path_tests; +#[cfg(test)] mod fill_script_random_fill_tests; #[cfg(test)] mod fill_script_spiral_tests; diff --git a/crates/ui-egui/src/dialogs/fill_script_ui.rs b/crates/ui-egui/src/dialogs/fill_script_ui.rs index c59e0ec816..69951a93a6 100644 --- a/crates/ui-egui/src/dialogs/fill_script_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_script_ui.rs @@ -11,7 +11,7 @@ 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::{Area, Control, SCRIPTS, controls, render, sample_curve, uses_path}; +use photocraft_compose::scripted_pattern::{Area, Control, SCRIPTS, controls, greyed_by, render, sample_curve, uses_path}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -58,6 +58,12 @@ fn label(key: &str) -> Label { "ringSpacing" => tl!("Ring spacing"), "patternSpacing" => tl!("Pattern spacing"), "keepUpright" => tl!("Keep pattern upright"), + "adjustSpacingToFit" => tl!("Adjust spacing to fit"), + "angleFromPath" => tl!("Angle from path"), + "distanceFromPath" => tl!("Distance from path"), + "alternatePatterns" => tl!("Alternate patterns"), + "scaleProgression" => tl!("Scale progression"), + "skipSymbolRotation" => tl!("Skip symbol rotation"), _ => tl!("Value"), }) } @@ -65,9 +71,9 @@ fn label(key: &str) -> Label { /// The unit shown after a value's field, if any. fn unit(key: &str) -> Option