Merge PR #18401: Fill: Place Along Path scripted pattern (#17430)

# Conflicts:
#	crates/compose/src/scripted_pattern.rs
#	crates/engine-paint/src/cmd/fill_cmds.rs
#	crates/engine-paint/src/fill_script_brick_tests.rs
#	crates/engine-paint/src/lib.rs
#	crates/ui-egui/src/dialogs/fill_script_ui.rs
#	crates/ui-egui/src/dialogs/fill_script_ui_tests.rs
This commit is contained in:
David Mann committed 2026-12-01 00:18:15 +01:00
commit a9e76540b6
8 files changed
+625 -21

No files matched your search

+196 -6
View File
@@ -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<Vec<Control>> {
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<Polyline> {
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<f64> = 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;
}
}
}
}
}
+30 -1
View File
@@ -206,7 +206,14 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
// 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<Option<Vec<photocraft_compose::
}
}
/// The path Place Along Path follows: the one `path` names, as the Paths panel selected it ("work", "layer" for the
/// active layer's shape path or vector mask, or a saved path's name). Without one nothing is filled.
fn selected_path(s: &Session, p: &Value) -> Result<photocraft_doc::Path> {
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<()> {
@@ -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);
}
@@ -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<String> {
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();
}
+2
View File
@@ -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;
+35 -8
View File
@@ -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<Label> {
match key {
"spacing" | "density" | "maxDistanceFromPath" | "ringSpacing" | "patternSpacing" => Some(Label::from(tl!("px"))),
"offsetBetweenRows" => Some(Label::from(tl!("%"))),
"patternRotateAngle" => Some(Label::from(tl!("°"))),
"spacing" | "density" | "maxDistanceFromPath" | "ringSpacing" | "patternSpacing" | "distanceFromPath" => Some(Label::from(tl!("px"))),
"offsetBetweenRows" | "scaleProgression" => Some(Label::from(tl!("%"))),
"patternRotateAngle" | "angleFromPath" => Some(Label::from(tl!("°"))),
_ => None,
}
}
@@ -90,8 +96,8 @@ pub(crate) fn script_options() -> Vec<(String, Label)> {
SCRIPTS.iter().map(|(k, _)| (k.to_string(), title(k))).collect()
}
/// The dialog rows of `controls`; Max distance from path is greyed without a selected path (`has_path`).
fn rows(controls: &[Control], has_path: bool) -> Vec<Param> {
/// The dialog rows of `script`'s `controls`; Max distance from path is greyed without a selected path (`has_path`).
fn rows(script: &str, controls: &[Control], has_path: bool) -> Vec<Param> {
let presets = PRESETS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect();
let mut rows = vec![
Param::new("preset", tl!("Preset:"), ParamKind::choice(presets, Some("default".into())))
@@ -111,6 +117,9 @@ fn rows(controls: &[Control], has_path: bool) -> Vec<Param> {
if c.key == "maxDistanceFromPath" && !has_path {
row = row.disabled();
}
if let Some(by) = greyed_by(script, c.key) {
row = row.enabled_when(by, false);
}
rows.push(row);
}
rows
@@ -163,9 +172,14 @@ fn opening(ctx: &egui::Context, key: &str, controls: &[Control]) -> DialogFields
}
/// Opens the dialog of `script` for the Fill whose `edit.fill` params are `fill`, on the document and layer `held`
/// names. A script without a dialog yet runs the fill as it is, so the engine reports it as not supported. A script that
/// names. A script without a dialog yet runs the fill as it is, so the engine reports it as not supported; so does
/// Place Along Path without a selected path, which the engine answers with "No path selected" (#17430). A script that
/// keeps to a path gets the Paths panel's selected path, when there is one.
pub(crate) fn open(app: &mut PhotocraftApp, script: &str, mut fill: Value, held: &Value) -> Option<DialogId> {
if script == "placeAlongPath" {
let path = app.ui.selected_path.clone().filter(|name| path_exists(app, name))?;
fill["path"] = json!(path);
}
let pattern = fill.get("pattern").and_then(Value::as_str).and_then(|id| photocraft_engine::pattern_cmds::resolve(&app.session, id));
let (w, h) = pattern.as_ref().map_or((1, 1), |p| (p.width, p.height));
let controls = controls(script, w, h)?;
@@ -184,7 +198,7 @@ pub(crate) fn open(app: &mut PhotocraftApp, script: &str, mut fill: Value, held:
captured["fill"] = fill;
captured["opening"] = Value::Object(opened);
captured["lastPreset"] = json!(fields.text("preset").unwrap_or("custom"));
let rows = rows(&controls, path.is_some());
let rows = rows(script, &controls, path.is_some());
let title = title(script);
Some(open_param(app, &key.clone(), fields, captured, move |fields| {
ParamDialog::new(key.clone(), title.clone(), rows.clone())
@@ -319,6 +333,19 @@ fn preview(
Some(texture)
}
/// Whether the document has the path `name` the Paths panel selected ("work", "layer" or a saved path).
fn path_exists(app: &PhotocraftApp, name: &str) -> bool {
let Some(st) = app.session.active() else { return false };
match name {
"work" => st.doc.work_path.is_some(),
"layer" => st
.active_layer
.and_then(|id| st.doc.layer(id))
.is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Shape(_)) || l.vector_mask.is_some()),
name => st.doc.paths.iter().any(|p| p.name == name),
}
}
#[cfg(test)]
#[path = "fill_script_ui_tests.rs"]
mod tests;
@@ -340,3 +340,51 @@ fn spiral_has_the_keep_upright_check_box_and_its_ok_fills_with_it() {
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(&app)).unwrap().fields().clone();
assert_eq!(fields.bool("keepUpright"), Some(true));
}
#[test]
fn place_along_path_without_a_selected_path_is_refused_without_its_dialog() {
let mut app = app();
app.run("path.set", json!({"name": "line", "path": {"subpaths": [{"closed": false, "knots": [[10, 45], [110, 45]]}]}})).unwrap();
app.ui.selected_path = None;
let before = past(&app);
fill_with_script(&mut app, "placeAlongPath");
assert_eq!(open_count(&app), 0, "the script dialog does not open");
assert!(app.ui.status_error && app.ui.status.contains("No path selected"), "{}", app.ui.status);
assert_eq!(past(&app), before, "no history state");
assert_eq!(alpha(&app, 15, 45), 0.0, "no pixels");
}
#[test]
fn place_along_path_follows_the_selected_path_and_greys_what_a_check_box_overrides() {
let mut app = app();
app.run("path.set", json!({"name": "line", "path": {"subpaths": [{"closed": false, "knots": [[10, 45], [110, 45]]}]}})).unwrap();
app.ui.selected_path = Some("line".into());
let before = past(&app);
fill_with_script(&mut app, "placeAlongPath");
assert_eq!(top_key(&app).as_deref(), Some("edit.fill.script.placeAlongPath"));
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(&app)).unwrap().fields().clone();
assert_eq!(
(fields.bool("alternatePatterns"), fields.bool("adjustSpacingToFit"), fields.bool("skipSymbolRotation")),
(Some(true), Some(false), Some(false))
);
let greyed = |h: &H, name: &str| {
h.query_all_by_role(Role::SpinButton)
.find(|n| n.accesskit_node().label().is_some_and(|l| l.starts_with(name)))
.unwrap_or_else(|| panic!("the {name} field"))
.accesskit_node()
.is_disabled()
};
let mut h = harness(app);
assert!(!greyed(&h, "Spacing") && !greyed(&h, "Angle from path"));
let id = newest(h.state());
set(h.state_mut(), id, "adjustSpacingToFit", json!(true));
set(h.state_mut(), id, "skipSymbolRotation", json!(true));
h.run_steps(3);
assert!(greyed(&h, "Spacing"), "Adjust spacing to fit greys Spacing");
assert!(greyed(&h, "Angle from path"), "Skip symbol rotation greys Angle from path");
let mut app = h.into_state();
confirm(&mut app, id);
assert_eq!(past(&app), before + 1, "one history state");
assert!(alpha(&app, 15, 45) > 0.99, "a tile on the path");
assert_eq!(alpha(&app, 15, 5), 0.0, "nothing away from it");
}
+63
View File
@@ -14,6 +14,9 @@ pub struct Polyline {
pub closed: bool,
}
/// One straight piece of a polyline: its start, its end and its length.
type Piece = ((f64, f64), (f64, f64), f64);
impl Polyline {
fn push(&mut self, p: (f64, f64), knot: bool) {
if let Some(&last) = self.pts.last()
@@ -28,6 +31,53 @@ impl Polyline {
self.pts.push(p);
self.knot.push(knot);
}
/// The pieces with a length, in order (a closed polyline's closing piece last): (start, end, length).
fn pieces(&self) -> Vec<Piece> {
let closing = if self.closed && self.pts.len() > 1 { self.pts.last().zip(self.pts.first()).map(|(a, b)| (*a, *b)) } else { None };
self.pts
.windows(2)
.map(|w| (w[0], w[1]))
.chain(closing)
.map(|(a, b)| (a, b, (b.0 - a.0).hypot(b.1 - a.1)))
.filter(|(_, _, len)| len.is_finite() && *len > 0.0)
.collect()
}
/// The length along the polyline, its closing piece included; pieces too long to measure count as 0.
pub fn length(&self) -> f64 {
self.pieces().iter().map(|(_, _, len)| len).sum()
}
/// The point and unit direction at each arc length of `at` (best in increasing order), measured from the first
/// point and clamped to the polyline. A polyline without length points along +x from its first point; an empty one
/// has no points.
pub fn sample(&self, at: &[f64]) -> Vec<((f64, f64), (f64, f64))> {
let Some(&first) = self.pts.first() else { return Vec::new() };
let pieces = self.pieces();
if pieces.is_empty() {
return at.iter().map(|_| (first, (1.0, 0.0))).collect();
}
let (mut i, mut start) = (0, 0.0);
at.iter()
.map(|&s| {
let s = if s.is_finite() { s.max(0.0) } else { 0.0 };
// Back to the first piece for a request before the current piece, or at its start once the cursor
// moved: a point on a corner takes the piece that ends there, in any order of requests.
if s < start || (s == start && i > 0) {
(i, start) = (0, 0.0);
}
while i + 1 < pieces.len() && s > start + pieces[i].2 {
start += pieces[i].2;
i += 1;
}
let (a, b, len) = pieces[i];
let t = ((s - start) / len).clamp(0.0, 1.0);
let dir = ((b.0 - a.0) / len, (b.1 - a.1) / len);
((a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t), dir)
})
.collect()
}
}
/// Straight segment: both control points lie on the chord (within 1e-9 px) between its ends.
@@ -297,6 +347,19 @@ mod tests {
}
}
#[test]
fn sampling_by_arc_length_gives_the_same_point_in_any_order() {
let line = Polyline { pts: vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], knot: vec![true; 3], closed: false };
assert_eq!(line.length(), 20.0);
let alone = line.sample(&[10.0]);
assert_eq!(alone, [((10.0, 0.0), (1.0, 0.0))], "a corner takes the piece that ends there");
assert_eq!(line.sample(&[15.0, 10.0])[1], alone[0], "also after a later request");
assert_eq!(line.sample(&[15.0, 5.0, 25.0]), [((10.0, 5.0), (0.0, 1.0)), ((5.0, 0.0), (1.0, 0.0)), ((10.0, 10.0), (0.0, 1.0))]);
// Closed, the closing piece counts.
let closed = Polyline { closed: true, ..line };
assert_eq!(closed.length(), 20.0 + 200f64.sqrt());
}
#[test]
fn hostile_curves_flatten_within_the_point_budget() {
// Unvalidated paths (a vector mask from a file, an imported SVG) can carry handles far