Merge PR #18396: Fill: Symmetry Fill script with 33 symmetry types (#17433)

# 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
This commit is contained in:
David Mann committed 2026-12-01 00:33:46 +01:00
commit 79f18d531c
8 files changed
+720 -17

No files matched your search

+29 -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, Place Along Path, Random Fill and Spiral paint today; the others extend
//! [`SCRIPTS`], [`controls`] and [`render`] with their own layout.
//! plain repeat. Every script paints: Brick Fill, Cross Weave, Place Along Path, Random Fill, Spiral and Symmetry Fill
//! ([`symmetry`]); each has its own [`controls`] and layout in [`render`].
//!
//! 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.
@@ -14,6 +14,10 @@ use photocraft_vector::flatten::flatten_path;
use crate::pattern::{Placement, Tile};
pub mod symmetry;
pub use symmetry::{SYMMETRY_TYPES, SymmetryFill};
/// 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"),
@@ -25,7 +29,7 @@ pub const SCRIPTS: [(&str, &str); 6] = [
];
/// The scripts that paint today; the rest are listed but answer "not supported yet".
pub const SUPPORTED: [&str; 5] = ["brickFill", "crossWeave", "placeAlongPath", "randomFill", "spiral"];
pub const SUPPORTED: [&str; 6] = ["brickFill", "crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"];
/// Whether `script` keeps its tiles near the selected path when there is one.
pub fn uses_path(script: &str) -> bool {
@@ -140,6 +144,14 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option<Vec<Control>> {
Control::new("colorRandomness", 0.05, 0.0, 1.0, 2),
Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2),
]),
"symmetryFill" => Some(vec![
Control::new("symmetryType", symmetry::DEFAULT_TYPE as f64, 1.0, SYMMETRY_TYPES.len() as f64, 0),
Control::new("patternScale", 1.0, 0.25, 1.25, 2),
Control::new("translationAlongWidth", 75.0, -100.0, 100.0, 0),
Control::new("translationAlongHeight", 75.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),
]),
_ => None,
}
}
@@ -424,12 +436,13 @@ impl CrossWeave {
}
}
/// Where a scripted pattern goes: the `rect` it paints, the document `canvas` (its bounds) and, for a script that
/// [`uses_path`], the selected `path` when there is one.
/// Where a scripted pattern goes: the `rect` it paints, the document `canvas` (its bounds), the `centre` a symmetry
/// turns about and, for a script that [`uses_path`], the selected `path` when there is one.
#[derive(Clone, Copy, Debug)]
pub struct Area<'a> {
pub rect: Rect,
pub canvas: Rect,
pub centre: (f64, f64),
pub path: Option<&'a [Polyline]>,
}
@@ -437,7 +450,7 @@ pub struct Area<'a> {
/// from `value` (by [`Control`] key) and the per-tile randomness from `seed`. `None` for a script that does not paint
/// yet.
pub fn render(script: &str, value: &dyn Fn(&str) -> f64, seed: u64, tile: &Tile, size: (u32, u32), area: Area) -> Option<Vec<[f32; 4]>> {
let Area { rect, canvas, path } = area;
let Area { rect, canvas, centre, path } = area;
let jitter = Jitter { color: value("colorRandomness") as f32, brightness: value("brightnessRandomness") as f32, seed };
let (width, height) = size;
match script {
@@ -489,6 +502,16 @@ pub fn render(script: &str, value: &dyn Fn(&str) -> f64, seed: u64, tile: &Tile,
};
Some(layout.render(tile, width, height, path.unwrap_or_default(), rect))
}
"symmetryFill" => {
let fill = SymmetryFill {
kind: value("symmetryType"),
scale: value("patternScale"),
shift: (value("translationAlongWidth"), value("translationAlongHeight")),
centre,
jitter,
};
Some(fill.render(tile, width, height, rect))
}
_ => None,
}
}
@@ -0,0 +1,366 @@
//! Symmetry Fill (#17433): the pattern tile repeated by one of 33 symmetry types about a centre point (the selection's
//! centre, the canvas centre without one).
//!
//! The tile (the *motif*) sits with its centre moved from the symmetry centre by the two translations, in percent of
//! the scaled tile's width and height; every element of the chosen symmetry places one copy of it. The finite types
//! (1-3) place a few copies, the friezes (10-16) repeat them along a horizontal band through the centre, the 17
//! wallpaper groups (17-33) over a lattice whose rotation centre is the symmetry centre, and the dilations (6-9) scale
//! the copies about the centre. Only types 1 and 33 are measured in the reference application; the others follow the
//! textbook definition of their group:
//!
//! - 4 and 5 repeat along the vertical line of type 1's mirror (5 mirrored about it at every half step);
//! - 6 scales by 1.5 per step, 7 by 1.2 with a 30° turn for twelve steps, 8 by 1.4 with a quarter turn back for eight
//! steps, 9 by 1.1 with a 20° turn in both directions until the copies are too small or too large to show.
//!
//! The lattice size is 1.5 times the motif's distance from the centre and at least the tile's diagonal, which spaces
//! the 6-fold centres of the default P6M about as far apart as measured (57 px for a 40 x 30 tile at 75 %, 75 %).
use photocraft_geom::Rect;
use super::{Jitter, MAX_LAYERS};
use crate::pattern::Tile;
/// The symmetry types in the Symmetry type list's order; the `symmetryType` value is the 1-based position.
pub const SYMMETRY_TYPES: [&str; 33] = [
"1: line reflection",
"2: point reflection",
"3: rotation symmetry with 4 elements around the center",
"4: translation symmetry",
"5: glide reflection",
"6: dilatation symmetry",
"7: dilative rotation symmetry",
"8: a different dilative rotation symmetry",
"9: infinite dilative rotation symmetry",
"10: translation frieze",
"11: glide reflection frieze",
"12: translation line reflection frieze",
"13: translation mirror reflection frieze",
"14: translation point reflection frieze",
"15: translation double reflection frieze",
"16: glide reflection rotation frieze",
"17: wallpaperP1 symmetry",
"18: wallpaperP2 symmetry",
"19: wallpaperPM symmetry",
"20: wallpaperPG symmetry",
"21: wallpaperPMM symmetry",
"22: wallpaperCM symmetry",
"23: wallpaperPMG symmetry",
"24: wallpaperPGG symmetry",
"25: wallpaperCMM symmetry",
"26: wallpaperP4 symmetry",
"27: wallpaperP4M symmetry",
"28: wallpaperP4G symmetry",
"29: wallpaperP3 symmetry",
"30: wallpaperP3M1 symmetry",
"31: wallpaperP31M symmetry",
"32: wallpaperP6 symmetry",
"33: wallpaperP6M symmetry",
];
/// The factory symmetry type: P6M.
pub const DEFAULT_TYPE: usize = 33;
/// Most copies the dilations place: bounds the work for a tiny tile on a large area.
const MAX_DILATION_STEPS: i64 = 256;
/// Symmetry Fill's values.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SymmetryFill {
/// 1..=33, the position in [`SYMMETRY_TYPES`]; out of range takes the nearest, non-finite the default.
pub kind: f64,
/// Tile size as a fraction (0.25..1.25).
pub scale: f64,
/// The motif's shift from the centre, right and down, in percent of the scaled tile's width and height.
pub shift: (f64, f64),
/// The point the symmetry turns about, in document pixels.
pub centre: (f64, f64),
pub jitter: Jitter,
}
/// An affine map of the plane relative to the symmetry centre: `p ↦ m·p + t`.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Map {
m: [f64; 4],
t: (f64, f64),
}
impl Map {
const IDENTITY: Map = Map { m: [1.0, 0.0, 0.0, 1.0], t: (0.0, 0.0) };
/// A turn by `deg` about the centre.
fn turn(deg: f64) -> Map {
let (s, c) = deg.to_radians().sin_cos();
Map { m: [c, -s, s, c], t: (0.0, 0.0) }
}
/// The mirror image across the line through the centre at `deg` from the x axis (0: horizontal, 90: vertical).
fn mirror(deg: f64) -> Map {
let (s, c) = (2.0 * deg).to_radians().sin_cos();
Map { m: [c, s, s, -c], t: (0.0, 0.0) }
}
fn shifted(self, dx: f64, dy: f64) -> Map {
Map { t: (self.t.0 + dx, self.t.1 + dy), ..self }
}
fn scaled(self, k: f64) -> Map {
Map { m: self.m.map(|v| v * k), t: (self.t.0 * k, self.t.1 * k) }
}
fn apply(&self, (x, y): (f64, f64)) -> (f64, f64) {
(self.m[0] * x + self.m[1] * y + self.t.0, self.m[2] * x + self.m[3] * y + self.t.1)
}
/// How much the map enlarges lengths.
fn stretch(&self) -> f64 {
(self.m[0] * self.m[3] - self.m[1] * self.m[2]).abs().sqrt()
}
fn inverse(&self) -> Option<Map> {
let det = self.m[0] * self.m[3] - self.m[1] * self.m[2];
if !det.is_finite() || det.abs() < 1e-12 {
return None;
}
let m = [self.m[3] / det, -self.m[1] / det, -self.m[2] / det, self.m[0] / det];
let t = (-(m[0] * self.t.0 + m[1] * self.t.1), -(m[2] * self.t.0 + m[3] * self.t.1));
Some(Map { m, t })
}
}
/// Where the copies go.
enum Layout {
/// A fixed list of copies, the last on top.
Copies(Vec<Map>),
/// The copies `reps` repeated over the lattice of `e1` and `e2` (a band along `e1` without `e2`).
Lattice { e1: (f64, f64), e2: Option<(f64, f64)>, reps: Vec<Map> },
}
fn turns(n: u32) -> Vec<Map> {
(0..n).map(|i| Map::turn(f64::from(i) * 360.0 / f64::from(n))).collect()
}
fn mirrors(degrees: &[f64]) -> Vec<Map> {
degrees.iter().map(|d| Map::mirror(*d)).collect()
}
/// Copies scaled by `k` and turned by `deg` per step about the centre, for the steps `steps`, the largest first.
fn dilations(k: f64, deg: f64, steps: std::ops::RangeInclusive<i64>) -> Layout {
let (lo, hi) = (*steps.start(), *steps.end());
let lo = lo.max(hi - MAX_DILATION_STEPS + 1);
Layout::Copies((lo..=hi).rev().map(|n| Map::turn(n as f64 * deg).scaled(k.powf(n as f64))).collect())
}
/// The layout of `kind` for lattice size `a`; `steps(k)` is the range of dilation steps that can show for ratio `k`.
fn layout(kind: usize, a: f64, steps: impl Fn(f64) -> std::ops::RangeInclusive<i64>) -> Layout {
let half = a / 2.0;
let (mx, my, r180) = (Map::mirror(90.0), Map::mirror(0.0), Map::turn(180.0));
let id = Map::IDENTITY;
let band = |reps: Vec<Map>| Layout::Lattice { e1: (a, 0.0), e2: None, reps };
let grid = |e2: (f64, f64), reps: Vec<Map>| Layout::Lattice { e1: (a, 0.0), e2: Some(e2), reps };
let (oblique, square, centred, hex) = ((0.25 * a, a), (0.0, a), (half, 0.75 * a), (half, a * 3f64.sqrt() / 2.0));
match kind {
1 => Layout::Copies(vec![id, mx]),
2 => Layout::Copies(vec![id, r180]),
3 => Layout::Copies(turns(4)),
4 => Layout::Lattice { e1: (0.0, a), e2: None, reps: vec![id] },
5 => Layout::Lattice { e1: (0.0, a), e2: None, reps: vec![id, mx.shifted(0.0, half)] },
6 => dilations(1.5, 0.0, steps(1.5)),
7 => dilations(1.2, 30.0, 0..=11),
8 => dilations(1.4, -90.0, 0..=7),
9 => dilations(1.1, 20.0, steps(1.1)),
10 => band(vec![id]),
11 => band(vec![id, my.shifted(half, 0.0)]),
12 => band(vec![id, mx]),
13 => band(vec![id, my]),
14 => band(vec![id, r180]),
15 => band(vec![id, mx, my, r180]),
16 => band(vec![id, mx, my.shifted(half, 0.0), r180.shifted(half, 0.0)]),
17 => grid(oblique, vec![id]),
18 => grid(oblique, vec![id, r180]),
19 => grid(square, vec![id, mx]),
20 => grid(square, vec![id, mx.shifted(0.0, half)]),
21 => grid(square, vec![id, mx, my, r180]),
22 => grid(centred, vec![id, mx]),
23 => grid(square, vec![id, r180, mx.shifted(half, 0.0), my.shifted(half, 0.0)]),
24 => grid(square, vec![id, r180, mx.shifted(half, half), my.shifted(half, half)]),
25 => grid(centred, vec![id, mx, my, r180]),
26 => grid(square, turns(4)),
27 => grid(square, [turns(4), mirrors(&[0.0, 45.0, 90.0, 135.0])].concat()),
28 => grid(square, [turns(4), mirrors(&[0.0, 45.0, 90.0, 135.0]).into_iter().map(|m| m.shifted(half, half)).collect()].concat()),
29 => grid(hex, turns(3)),
30 => grid(hex, [turns(3), mirrors(&[90.0, 30.0, 150.0])].concat()),
31 => grid(hex, [turns(3), mirrors(&[0.0, 60.0, 120.0])].concat()),
32 => grid(hex, turns(6)),
_ => grid(hex, [turns(6), mirrors(&[0.0, 30.0, 60.0, 90.0, 120.0, 150.0])].concat()),
}
}
/// One copy that may cover a pixel: its place in the drawing order (higher on top), the map from the pixel back to the
/// motif, and how much it enlarges the motif.
#[derive(Clone, Copy)]
struct Candidate {
order: (i64, i64, usize),
back: Map,
stretch: f64,
}
impl SymmetryFill {
/// The type, 1..=33.
pub fn kind(&self) -> usize {
if self.kind.is_finite() { self.kind.round().clamp(1.0, SYMMETRY_TYPES.len() as f64) as usize } else { DEFAULT_TYPE }
}
/// The copies of a `width` x `height` pattern laid out over `rect` (row-major straight RGBA, transparent where no
/// copy lies).
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];
let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale.max(0.01) } else { 1.0 };
let (w, h) = (f64::from(width), f64::from(height));
let centre = if self.centre.0.is_finite() && self.centre.1.is_finite() { self.centre } else { (0.0, 0.0) };
if len == 0 || width == 0 || height == 0 {
return out;
}
let (hw, hh) = (w * scale / 2.0, h * scale / 2.0);
let pct = |v: f64| if v.is_finite() { v / 100.0 } else { 0.0 };
let shift = (pct(self.shift.0) * 2.0 * hw, pct(self.shift.1) * 2.0 * hh);
// The motif's top-left corner on a whole pixel, so the mirrored and quarter-turned copies land on whole pixels
// too and show the tile's pixels unblended (the measured line reflection: y 207-237 for a corner at 207.5).
let corner = ((centre.0 + shift.0 - hw + 1e-9).floor() - centre.0, (centre.1 + shift.1 - hh + 1e-9).floor() - centre.1);
let motif = (corner.0 + hw, corner.1 + hh);
let radius = hw.hypot(hh);
let a = (1.5 * shift.0.hypot(shift.1)).max(2.0 * radius).max(1.0);
// How far the area reaches from the centre: the dilations stop once a copy is four times that size.
let reach = [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x0, rect.y1), (rect.x1, rect.y1)]
.iter()
.map(|&(x, y)| (f64::from(x) - centre.0).hypot(f64::from(y) - centre.1))
.fold(0.0, f64::max);
let small = w.min(h) * scale;
let large = w.max(h) * scale;
let steps = |k: f64| {
let lo = ((0.5 / large).ln() / k.ln()).floor() as i64;
let hi = ((4.0 * (reach + 1.0) / small).ln() / k.ln()).ceil().max(0.0) as i64;
lo.min(hi)..=hi
};
let layout = layout(self.kind(), a, steps);
// The fixed copies with their inverse, centre and reach; the lattice representatives with their inverse.
let fixed: Vec<(Map, (f64, f64), f64)> = match &layout {
Layout::Copies(maps) => maps.iter().filter_map(|m| Some((m.inverse()?, m.apply(motif), radius * m.stretch()))).collect(),
Layout::Lattice { .. } => Vec::new(),
};
let reps: Vec<(Map, (f64, f64))> = match &layout {
Layout::Lattice { reps, .. } => reps.iter().filter_map(|m| Some((m.inverse()?, m.apply(motif)))).collect(),
Layout::Copies(_) => Vec::new(),
};
let mut found: Vec<Candidate> = Vec::new();
let mut i = 0;
for y in rect.y0..rect.y1 {
for x in rect.x0..rect.x1 {
let p = (f64::from(x) + 0.5 - centre.0, f64::from(y) + 0.5 - centre.1);
found.clear();
match &layout {
Layout::Copies(_) => {
for (k, (back, c, r)) in fixed.iter().enumerate() {
if (p.0 - c.0).powi(2) + (p.1 - c.1).powi(2) <= r * r {
found.push(Candidate { order: (0, 0, k), back: *back, stretch: 1.0 / back.stretch() });
}
}
}
Layout::Lattice { e1, e2, .. } => {
for (k, (back, c)) in reps.iter().enumerate() {
lattice_points(*e1, *e2, (p.0 - c.0, p.1 - c.1), radius, |row, col, off| {
if found.len() < MAX_LAYERS {
// Back from the shifted copy: first undo the lattice step, then the representative.
let back = Map { t: back.apply((-off.0, -off.1)), ..*back };
found.push(Candidate { order: (row, col, k), back, stretch: 1.0 });
}
});
}
}
}
found.sort_unstable_by_key(|c| std::cmp::Reverse(c.order));
out[i] = self.composite(tile, &found, p, corner, scale, (w, h));
i += 1;
}
}
out
}
/// The copies `found` (topmost first) over the pixel at `p` (relative to the centre), front to back.
fn composite(&self, tile: &Tile, found: &[Candidate], p: (f64, f64), corner: (f64, f64), scale: f64, (w, h): (f64, f64)) -> [f32; 4] {
let mut acc = [0.0f32; 4];
for c in found {
if acc[3] >= 1.0 {
break;
}
let to_tile = |q: (f64, f64)| ((q.0 - corner.0) / scale, (q.1 - corner.1) / scale);
let (u, v) = to_tile(c.back.apply(p));
if !(0.0..w).contains(&u) || !(0.0..h).contains(&v) {
continue;
}
// A copy drawn smaller than the tile averages the tile pixels under the document pixel.
let taps = if c.stretch * scale < 1.0 { (1.0 / (c.stretch * scale)).ceil().min(4.0) as usize } else { 1 };
let mut q = [0.0f32; 4];
for j in 0..taps {
for t in 0..taps {
let off = |n: usize| (n as f64 + 0.5) / taps as f64 - 0.5;
let (u, v) = to_tile(c.back.apply((p.0 + off(t), p.1 + off(j))));
// Clamped inside the tile: the copies are separate tiles, so no edge blends with the opposite one.
let s = tile.sample(u.clamp(0.5, w - 0.5), v.clamp(0.5, h - 0.5));
for ch in 0..3 {
q[ch] += s[ch] * s[3];
}
q[3] += s[3];
}
}
if q[3] <= 0.0 {
continue;
}
let mut q = [q[0] / q[3], q[1] / q[3], q[2] / q[3], q[3] / (taps * taps) as f32];
let d = self.jitter.offsets(c.order.0, c.order.1.wrapping_mul(64).wrapping_add(c.order.2 as i64));
// Without a drift a copy 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);
}
}
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 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)] } else { [0.0; 4] }
}
}
/// Calls `hit(row, col, point)` for each point `row·e2 + col·e1` of the lattice (the band when `e2` is `None`) within
/// `radius` of `d`.
fn lattice_points(e1: (f64, f64), e2: Option<(f64, f64)>, d: (f64, f64), radius: f64, mut hit: impl FnMut(i64, i64, (f64, f64))) {
let near = |q: (f64, f64)| (d.0 - q.0).powi(2) + (d.1 - q.1).powi(2) <= radius * radius;
let Some(e2) = e2 else {
let len2 = e1.0 * e1.0 + e1.1 * e1.1;
let along = (d.0 * e1.0 + d.1 * e1.1) / len2;
let span = radius / len2.sqrt();
for col in (along - span).ceil() as i64..=(along + span).floor() as i64 {
let q = (col as f64 * e1.0, col as f64 * e1.1);
if near(q) {
hit(0, col, q);
}
}
return;
};
let det = e1.0 * e2.1 - e1.1 * e2.0;
// The rows of the inverse basis: d's lattice coordinates, and how far `radius` reaches in each.
let inv = [e2.1 / det, -e2.0 / det, -e1.1 / det, e1.0 / det];
let (fc, fr) = (inv[0] * d.0 + inv[1] * d.1, inv[2] * d.0 + inv[3] * d.1);
let (sc, sr) = (radius * inv[0].hypot(inv[1]), radius * inv[2].hypot(inv[3]));
for row in (fr - sr).ceil() as i64..=(fr + sr).floor() as i64 {
for col in (fc - sc).ceil() as i64..=(fc + sc).floor() as i64 {
let q = (col as f64 * e1.0 + row as f64 * e2.0, col as f64 * e1.1 + row as f64 * e2.1);
if near(q) {
hit(row, col, q);
}
}
}
}
+4 -1
View File
@@ -214,7 +214,10 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
} else {
None
};
let place = photocraft_compose::scripted_pattern::Area { rect: area, canvas: doc_bounds, path: path.as_deref() };
// A symmetry turns about the selection's centre, the canvas centre without one.
let centre = if sel.is_some() { area } else { doc_bounds };
let centre = (f64::from(centre.x0 + centre.x1) / 2.0, f64::from(centre.y0 + centre.y1) / 2.0);
let place = photocraft_compose::scripted_pattern::Area { rect: area, canvas: doc_bounds, centre, path: path.as_deref() };
Source::Pixels(area, scripted(p, script, &tile, &pat, place)?)
} else {
// Photoshop's Fill uses the canvas origin.
@@ -1,7 +1,6 @@
//! #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.
use serde_json::{Value, json};
@@ -158,13 +157,11 @@ fn the_fill_stays_in_the_selection_with_mode_and_opacity() {
}
#[test]
fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() {
fn an_unknown_script_is_an_error_and_fills_nothing() {
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}");
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,193 @@
//! #17433: Symmetry Fill repeats the pattern tile by one of 33 symmetry types about the canvas centre (the selection's
//! centre with one). `1: line reflection` puts the tile and its mirror image either side of the vertical centre line,
//! `33: wallpaperP6M` (the default) fills the area with 6-fold turned and mirrored copies; every type stays inside the
//! selection and fills as one history state "Fill".
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.
fn define_probe(s: &mut 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();
}
/// A 600 x 400 white RGB/8 document with an empty pixel layer on top (active), the probe defined.
fn session() -> Session {
let mut s = crate::session();
define_probe(&mut s);
s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s
}
/// Symmetry Fill with both randomness values at 0 and `extra` values on top.
fn symmetry(extra: Value) -> Value {
let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "symmetryFill", "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 ends.
fn painted_bounds(s: &Session, w: i32, h: i32) -> Option<(i32, i32, i32, i32)> {
let mut b: Option<(i32, i32, i32, i32)> = None;
for y in 0..h {
for x in 0..w {
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
}
fn undo_label(s: &Session) -> Option<String> {
s.active().unwrap().history.undo_label().map(str::to_string)
}
#[test]
fn line_reflection_puts_the_tile_and_its_mirror_image_either_side_of_the_centre() {
let mut s = session();
let r = s.execute("edit.fill", symmetry(json!({"symmetryType": 1}))).unwrap();
assert_eq!(r["script"], "symmetryFill");
assert_eq!(painted_bounds(&s, 600, 400), Some((250, 207, 350, 237)), "two tiles, measured bounds");
// Right of x 300 the tile as it is (red on the left), left of it the mirror image (red on the right).
assert_eq!([rgb8(pixel(&s, 315, 210)), rgb8(pixel(&s, 345, 210)), rgb8(pixel(&s, 345, 230))], [RED, BLUE, GREEN]);
assert_eq!([rgb8(pixel(&s, 285, 210)), rgb8(pixel(&s, 255, 210)), rgb8(pixel(&s, 255, 230))], [RED, BLUE, GREEN]);
assert_eq!(pixel(&s, 300, 220)[3], 0.0, "a gap between the two");
assert_eq!(undo_label(&s).as_deref(), Some("Fill"));
}
#[test]
fn the_default_p6m_fills_the_area_with_six_fold_turned_and_mirrored_copies() {
let mut s = session();
s.execute("edit.fill", symmetry(json!({}))).unwrap();
let c = (300.0f64, 200.0f64);
let painted = |x: f64, y: f64| pixel(&s, x.floor() as i32, y.floor() as i32)[3] > 0.0;
let points: Vec<(f64, f64)> = (60..340).step_by(3).flat_map(|y| (160..440).step_by(3).map(move |x| (f64::from(x) + 0.5, f64::from(y) + 0.5))).collect();
let covered = points.iter().filter(|p| painted(p.0, p.1)).count();
assert!(covered > 3 * (points.len() - covered), "mostly covered: {covered} of {}", points.len());
assert!(covered < points.len(), "small gaps stay transparent");
// Overlapping copies hide each other, so the symmetry shows in what is painted: the same after a 60° turn about
// the centre and after a mirror across the vertical through it, and clearly less so after a 45° turn.
let same_after = |map: &dyn Fn(f64, f64) -> (f64, f64)| {
points
.iter()
.filter(|p| {
let q = map(p.0 - c.0, p.1 - c.1);
painted(p.0, p.1) == painted(c.0 + q.0, c.1 + q.1)
})
.count()
};
let turn = |deg: f64| {
let (sn, cs) = deg.to_radians().sin_cos();
move |x: f64, y: f64| (x * cs - y * sn, x * sn + y * cs)
};
let (sixty, mirrored, odd) = (same_after(&turn(60.0)), same_after(&|x, y| (-x, y)), same_after(&turn(45.0)));
let n = points.len();
assert!(sixty * 100 > n * 95, "6-fold turn: {sixty} of {n}");
assert!(mirrored * 100 > n * 95, "mirror: {mirrored} of {n}");
assert!(odd < sixty && n - odd > 3 * (n - sixty), "a 45° turn is no symmetry: {odd} vs {sixty} of {n}");
}
#[test]
fn every_type_paints_its_own_layout_inside_the_selection_as_one_fill() {
let mut s = session();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap();
let mut layouts: Vec<Vec<bool>> = Vec::new();
for kind in 1..=33 {
s.execute("edit.fill", symmetry(json!({"symmetryType": kind}))).unwrap();
assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "type {kind}");
let b = painted_bounds(&s, 600, 400).unwrap_or_else(|| panic!("type {kind} painted nothing"));
assert!(b.2 <= 200 && b.3 <= 150, "type {kind} painted outside the selection: {b:?}");
layouts.push((0..150).step_by(2).flat_map(|y| (0..200).step_by(2).map(move |x| (x, y))).map(|(x, y)| pixel(&s, x, y)[3] > 0.0).collect());
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(painted_bounds(&s, 600, 400), None, "type {kind}: one history state");
}
for (i, a) in layouts.iter().enumerate() {
for (j, b) in layouts.iter().enumerate().skip(i + 1) {
assert_ne!(a, b, "types {} and {} paint the same", i + 1, j + 1);
}
}
}
#[test]
fn a_selection_moves_the_centre_to_its_own() {
let mut s = session();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1}))).unwrap();
// Mirrored about x 100, the selection's centre line, and shifted down from its middle (y 75).
assert_eq!(painted_bounds(&s, 600, 400), Some((50, 82, 150, 112)));
assert_eq!(rgb8(pixel(&s, 115, 90)), RED);
assert_eq!(rgb8(pixel(&s, 85, 90)), RED);
}
#[test]
fn fill_mode_and_opacity_apply_to_the_copies() {
let mut s = session();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "opacity": 50}))).unwrap();
let px = pixel(&s, 315, 210);
assert!((px[3] - 0.5).abs() < 0.01, "half opacity: {px:?}");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "mode": "dissolve", "opacity": 50}))).unwrap();
let opaque = (310..350).filter(|x| pixel(&s, *x, 210)[3] > 0.99).count();
assert!(opaque > 0 && opaque < 40, "dissolve keeps some pixels whole: {opaque}");
}
#[test]
fn values_are_clamped_to_symmetry_fills_own_ranges() {
let mut s = session();
// Scale stops at 0.25 (not Brick Fill's 0.1) and the type at 1..33.
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "patternScale": 0.1}))).unwrap();
let small = painted_bounds(&s, 600, 400);
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "patternScale": 0.25}))).unwrap();
assert_eq!(painted_bounds(&s, 600, 400), small);
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.fill", symmetry(json!({"symmetryType": -4}))).unwrap();
assert_eq!(painted_bounds(&s, 600, 400), Some((250, 207, 350, 237)), "below the range takes type 1");
s.execute("edit.undo", json!({})).unwrap();
let before = undo_label(&s);
let err = s.execute("edit.fill", symmetry(json!({"symmetryType": "p6m"}))).unwrap_err().to_string();
assert!(err.contains("symmetryType"), "{err}");
assert_eq!(undo_label(&s), before, "nothing was filled");
}
#[test]
fn translation_moves_the_tile_away_from_the_centre() {
let mut s = session();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "translationAlongWidth": 0, "translationAlongHeight": 0}))).unwrap();
// Centred on the mirror line the tile and its mirror image overlap into one 40 px wide block.
let (x0, _, x1, _) = painted_bounds(&s, 600, 400).unwrap();
assert!(x0 >= 270 && x1 <= 330 && x1 - x0 == 40, "{x0}..{x1}");
}
#[test]
fn colour_randomness_varies_the_copies_only_above_zero() {
let mut s = session();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1}))).unwrap();
assert_eq!(rgb8(pixel(&s, 315, 210)), rgb8(pixel(&s, 285, 210)), "both copies exact at 0");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.fill", symmetry(json!({"symmetryType": 1, "colorRandomness": 1, "seed": 3}))).unwrap();
assert_ne!(rgb8(pixel(&s, 315, 210)), rgb8(pixel(&s, 285, 210)), "each copy drifts on its own");
}
+2
View File
@@ -56,6 +56,8 @@ mod fill_script_random_fill_tests;
#[cfg(test)]
mod fill_script_spiral_tests;
#[cfg(test)]
mod fill_script_symmetry_tests;
#[cfg(test)]
mod mixer_indexed_bitmap_tests;
#[cfg(test)]
mod mixer_toggle_commands_tests;
@@ -0,0 +1,86 @@
//! #17433: the Symmetry Fill dialog picks the symmetry type from a list (factory `33: wallpaperP6M symmetry`); the
//! picked type reaches the fill, is remembered after OK, and Cancel fills nothing.
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::smart_filter_dialog::tests::{cancel, confirm, newest, open_count, pass, set};
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap();
app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
app.run("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap();
app.run("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app
}
/// Opens Fill with the probe pattern and Symmetry Fill chosen, and presses OK: the Symmetry Fill dialog opens.
fn open_symmetry(app: &mut PhotocraftApp) {
let id = super::super::fill_ui::open(app);
set(app, id, "contents", json!("pattern"));
let probe = app.session.patterns.items.iter().find(|p| p.name == "probe").map(|p| p.id.clone());
set(app, id, "pattern", json!(probe));
set(app, id, "script", json!(true));
set(app, id, "scriptName", json!("symmetryFill"));
confirm(app, id);
pass(app);
}
fn text(app: &PhotocraftApp, key: &str) -> Option<String> {
app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(app))?.fields().text(key).map(str::to_string)
}
fn painted(app: &PhotocraftApp, x: i32, y: i32) -> bool {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] > 0.0
}
fn past(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
#[test]
fn the_symmetry_type_is_a_list_that_opens_on_p6m() {
let mut app = app();
open_symmetry(&mut app);
assert_eq!(text(&app, "symmetryType").as_deref(), Some("33"));
crate::theme::install_fonts(app.ctx());
let mut h = Harness::builder()
.with_context(app.ctx().clone())
.with_size(vec2(1400.0, 900.0))
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
h.run_steps(4);
let list =
h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().is_some_and(|l| l.starts_with("Symmetry type"))).expect("a Symmetry type list");
assert!(format!("{:?}", list.accesskit_node()).contains("33: wallpaperP6M symmetry"), "shows the factory type");
}
#[test]
fn the_picked_type_fills_and_is_remembered_and_cancel_fills_nothing() {
let mut app = app();
let before = past(&app);
open_symmetry(&mut app);
let id = newest(&app);
cancel(&mut app, id);
assert_eq!((open_count(&app), past(&app)), (0, before), "Cancel: no history state");
open_symmetry(&mut app);
let id = newest(&app);
set(&mut app, id, "symmetryType", json!("1"));
pass(&mut app);
assert_eq!(text(&app, "preset").as_deref(), Some("custom"), "a picked type is a custom value");
confirm(&mut app, id);
assert_eq!(past(&app), before + 1);
// Line reflection: the tile right of the centre line and its mirror image left of it, nothing far away.
assert!(painted(&app, 315, 210) && painted(&app, 285, 210));
assert!(!painted(&app, 20, 20));
open_symmetry(&mut app);
assert_eq!(text(&app, "symmetryType").as_deref(), Some("1"), "reopens on the confirmed type");
}
+38 -5
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, greyed_by, render, sample_curve, uses_path};
use photocraft_compose::scripted_pattern::{Area, Control, SCRIPTS, SYMMETRY_TYPES, controls, greyed_by, render, sample_curve, uses_path};
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
@@ -64,6 +64,9 @@ fn label(key: &str) -> Label {
"alternatePatterns" => tl!("Alternate patterns"),
"scaleProgression" => tl!("Scale progression"),
"skipSymbolRotation" => tl!("Skip symbol rotation"),
"symmetryType" => tl!("Symmetry type"),
"translationAlongWidth" => tl!("Pattern translation along width"),
"translationAlongHeight" => tl!("Pattern translation along height"),
_ => tl!("Value"),
})
}
@@ -74,6 +77,8 @@ fn unit(key: &str) -> Option<Label> {
"spacing" | "density" | "maxDistanceFromPath" | "ringSpacing" | "patternSpacing" | "distanceFromPath" => Some(Label::from(tl!("px"))),
"offsetBetweenRows" | "scaleProgression" => Some(Label::from(tl!("%"))),
"patternRotateAngle" | "angleFromPath" => Some(Label::from(tl!("°"))),
"translationAlongWidth" => Some(Label::from(tl!("% of width"))),
"translationAlongHeight" => Some(Label::from(tl!("% of height"))),
_ => None,
}
}
@@ -96,6 +101,16 @@ pub(crate) fn script_options() -> Vec<(String, Label)> {
SCRIPTS.iter().map(|(k, _)| (k.to_string(), title(k))).collect()
}
/// The values picked from a list instead of typed: Symmetry Fill's type, held as the entry's number ("1".."33").
fn is_choice(key: &str) -> bool {
key == "symmetryType"
}
/// The Symmetry type list: the 33 types by number, in the reference order.
fn symmetry_types() -> Vec<(String, Label)> {
SYMMETRY_TYPES.iter().enumerate().map(|(i, name)| ((i + 1).to_string(), Label::from(tl!(name)))).collect()
}
/// 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();
@@ -106,6 +121,11 @@ fn rows(script: &str, controls: &[Control], has_path: bool) -> Vec<Param> {
.separated_at(4),
];
for c in controls {
if is_choice(c.key) {
let default = format!("{}", c.default as i64);
rows.push(Param::new(c.key, label(c.key), ParamKind::choice(symmetry_types(), Some(default))));
continue;
}
if c.toggle {
rows.push(Param::new(c.key, label(c.key), ParamKind::bool(c.default >= 0.5)));
continue;
@@ -125,15 +145,17 @@ fn rows(script: &str, controls: &[Control], has_path: bool) -> Vec<Param> {
rows
}
/// The value of `c` in `f`, a check box as 1 (on) or 0 (off).
/// The value of `c` in `f`, a check box as 1 (on) or 0 (off), a list entry as its number.
fn value(f: &DialogFields, c: &Control) -> Option<f64> {
if c.toggle { f.bool(c.key).map(|on| f64::from(u8::from(on))) } else { f.number(c.key) }
if c.toggle { f.bool(c.key).map(|on| f64::from(u8::from(on))) } else { f.number(c.key).or_else(|| f.text(c.key)?.parse().ok()) }
}
/// Sets `c` in `f` to `v`, a check box on from 0.5.
/// Sets `c` in `f` to `v`, a check box on from 0.5, a list entry by its number.
fn set_value(f: &mut DialogFields, c: &Control, v: f64) {
if c.toggle {
f.set(c.key, v >= 0.5);
} else if is_choice(c.key) {
f.set(c.key, format!("{}", c.clamp(v).round() as i64));
} else {
f.set(c.key, v);
}
@@ -324,7 +346,14 @@ fn preview(
let get = |k: &str| controls.iter().zip(&values).find(|(c, _)| c.key == k).map_or(0.0, |(_, v)| *v);
let curve = (on_path && uses_path(script)).then(|| sample_curve(PREVIEW));
let area = photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32);
let px = render(script, &get, 1, &tile, (p.width, p.height), Area { rect: area, canvas: area, path: curve.as_deref() })?;
let px = render(
script,
&get,
1,
&tile,
(p.width, p.height),
Area { rect: area, canvas: area, centre: (f64::from(PREVIEW) / 2.0, f64::from(PREVIEW) / 2.0), path: curve.as_deref() },
)?;
let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let rgba: Vec<u8> = px.iter().flat_map(|q| [0, 1, 2].map(|c| level(q[c] * q[3] + (1.0 - q[3]))).into_iter().chain([255])).collect();
let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &rgba);
@@ -349,3 +378,7 @@ fn path_exists(app: &PhotocraftApp, name: &str) -> bool {
#[cfg(test)]
#[path = "fill_script_ui_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "fill_script_symmetry_ui_tests.rs"]
mod symmetry_tests;