mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Fill: Spiral script pattern (#17432)
Fill > Pattern > Script > Spiral lays the pattern tile along a spiral around the canvas centre: rings one tile height plus Ring spacing apart, tiles one tile width plus Pattern spacing apart along the curve, turned with the curve unless Keep pattern upright is on. The script dialog gets check box rows, and one render entry point serves the engine and the preview for every script. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
519497b649
commit
499bf6089f
7 files changed
+572
-37
No files matched your search
@@ -1,9 +1,12 @@
|
||||
//! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a
|
||||
//! plain repeat. Brick Fill is the first script; the others extend [`SCRIPTS`] and [`controls`] with their own layout.
|
||||
//! plain repeat. Brick 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.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::pattern::{Placement, Tile};
|
||||
@@ -19,7 +22,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; 1] = ["brickFill"];
|
||||
pub const SUPPORTED: [&str; 2] = ["brickFill", "spiral"];
|
||||
|
||||
/// The parameter value of a script name, matched without regard to case.
|
||||
pub fn script_key(name: &str) -> Option<&'static str> {
|
||||
@@ -35,11 +38,17 @@ pub struct Control {
|
||||
pub max: f64,
|
||||
/// The most digits shown after the decimal mark.
|
||||
pub decimals: u32,
|
||||
/// A check box rather than a number: off is 0, on is 1.
|
||||
pub toggle: bool,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
const fn new(key: &'static str, default: f64, min: f64, max: f64, decimals: u32) -> Control {
|
||||
Control { key, default, min, max, decimals }
|
||||
Control { key, default, min, max, decimals, toggle: false }
|
||||
}
|
||||
|
||||
const fn toggle(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 }
|
||||
}
|
||||
|
||||
/// `v` inside the range; a non-finite value takes the factory value.
|
||||
@@ -55,6 +64,12 @@ pub fn spacing_range(width: u32, height: u32) -> (f64, f64) {
|
||||
(min, 3.0 * f64::from(width))
|
||||
}
|
||||
|
||||
/// The Ring spacing and Pattern spacing range of Spiral for a `width` x `height` tile, in pixels: the same overlap as
|
||||
/// [`spacing_range`], and up to two and a half tile widths apart (the measured -28 to 100 for a 40 x 30 tile).
|
||||
pub fn spiral_spacing_range(width: u32, height: u32) -> (f64, f64) {
|
||||
(spacing_range(width, height).0, 2.5 * f64::from(width))
|
||||
}
|
||||
|
||||
/// The values of `script` in its dialog's order, for a `width` x `height` pattern; `None` for an unknown script or one
|
||||
/// that does not paint yet.
|
||||
pub fn controls(script: &str, width: u32, height: u32) -> Option<Vec<Control>> {
|
||||
@@ -70,6 +85,44 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option<Vec<Control>> {
|
||||
Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0),
|
||||
])
|
||||
}
|
||||
"spiral" => {
|
||||
let (lo, hi) = spiral_spacing_range(width, height);
|
||||
Some(vec![
|
||||
Control::new("patternScale", 1.0, 0.1, 1.25, 2),
|
||||
Control::new("ringSpacing", 0.0, lo, hi, 0),
|
||||
Control::new("patternSpacing", 0.0, lo, hi, 0),
|
||||
Control::toggle("keepUpright", false),
|
||||
Control::new("colorRandomness", 0.05, 0.0, 1.0, 2),
|
||||
Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2),
|
||||
])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `script` laid out over `rect` of the document `canvas` (its bounds) with a `size` (width, height) pattern, its values read
|
||||
/// with `get` (already in range) and the per-tile randomness repeatable for `seed`; `None` for a script that does not
|
||||
/// paint.
|
||||
pub fn render(script: &str, get: &dyn Fn(&str) -> f64, seed: u64, canvas: Rect, tile: &Tile, size: (u32, u32), rect: Rect) -> Option<Vec<[f32; 4]>> {
|
||||
let (width, height) = size;
|
||||
let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed };
|
||||
match script {
|
||||
"brickFill" => {
|
||||
let brick =
|
||||
BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter };
|
||||
Some(brick.render(tile, width, height, rect))
|
||||
}
|
||||
"spiral" => {
|
||||
let spiral = Spiral {
|
||||
scale: get("patternScale"),
|
||||
ring_spacing: get("ringSpacing"),
|
||||
pattern_spacing: get("patternSpacing"),
|
||||
upright: get("keepUpright") >= 0.5,
|
||||
centre: ((f64::from(canvas.x0) + f64::from(canvas.x1)) / 2.0, (f64::from(canvas.y0) + f64::from(canvas.y1)) / 2.0),
|
||||
jitter,
|
||||
};
|
||||
Some(spiral.render(tile, width, height, rect))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -228,3 +281,174 @@ impl BrickFill {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Spiral: tiles one after another along a spiral that starts at `centre` and winds outwards counter-clockwise, its rings
|
||||
/// one tile height plus the Ring spacing apart and its tiles one tile width plus the Pattern spacing apart along the
|
||||
/// curve. Each tile turns with the curve (its top towards the centre) unless kept upright. Later, outer tiles lie over
|
||||
/// earlier ones.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Spiral {
|
||||
/// Tile size as a fraction (0.1..1.25).
|
||||
pub scale: f64,
|
||||
/// Pixels between neighbouring rings; negative overlaps them.
|
||||
pub ring_spacing: f64,
|
||||
/// Pixels between neighbouring tiles along the curve; negative overlaps them.
|
||||
pub pattern_spacing: f64,
|
||||
/// Keep every tile upright instead of turning it with the curve.
|
||||
pub upright: bool,
|
||||
/// Where the spiral starts, in document pixels.
|
||||
pub centre: (f64, f64),
|
||||
pub jitter: Jitter,
|
||||
}
|
||||
|
||||
/// Most tile positions worked out once per fill; a layout with more works each one out where a pixel needs it.
|
||||
const MAX_TABLE: usize = 1 << 20;
|
||||
|
||||
/// Most tiles tried for one pixel: bounds the work of layouts packed far tighter than a tile.
|
||||
const MAX_CANDIDATES: usize = 4096;
|
||||
|
||||
/// The spiral r = `b` θ, θ from 0 at the centre.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Curve {
|
||||
b: f64,
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
/// The length of the curve from the centre to angle `t`.
|
||||
fn arc(self, t: f64) -> f64 {
|
||||
0.5 * self.b * (t * (1.0 + t * t).sqrt() + t.asinh())
|
||||
}
|
||||
|
||||
/// The angle at curve length `s`. Starts above the answer (the length grows at least as fast as `b` t and as `b` t²/2),
|
||||
/// from where Newton's steps on the convex length fall towards it without passing it.
|
||||
fn angle_at(self, s: f64) -> f64 {
|
||||
if s.is_nan() || s <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut t = (s / self.b).min((2.0 * s / self.b).sqrt());
|
||||
for _ in 0..64 {
|
||||
let next = (t - (self.arc(t) - s) / (self.b * (1.0 + t * t).sqrt())).max(0.0);
|
||||
let done = (t - next).abs() <= 1e-12 * (1.0 + t);
|
||||
t = next;
|
||||
if done {
|
||||
break;
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
impl Spiral {
|
||||
/// The tiles of a `width` x `height` pattern laid along the spiral over `rect` (row-major straight RGBA, transparent
|
||||
/// where no tile 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];
|
||||
// At the f32 precision the placement maps with, so the tile bounds here are the ones it samples.
|
||||
let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 };
|
||||
let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale);
|
||||
let (cx, cy) = self.centre;
|
||||
if len == 0 || tw <= 0.0 || th <= 0.0 || !cx.is_finite() || !cy.is_finite() {
|
||||
return out;
|
||||
}
|
||||
let finite = |v: f64| if v.is_finite() { v } else { 0.0 };
|
||||
// At least a pixel between rings and between tiles, so every layout ends.
|
||||
let ring = (th + finite(self.ring_spacing)).max(1.0);
|
||||
let pitch = (tw + finite(self.pattern_spacing)).max(1.0);
|
||||
let curve = Curve { b: ring / TAU };
|
||||
// A tile can cover a pixel only when its centre lies within half its diagonal.
|
||||
let reach = tw.hypot(th) / 2.0;
|
||||
let far = [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x0, rect.y1), (rect.x1, rect.y1)]
|
||||
.iter()
|
||||
.map(|&(x, y)| (f64::from(x) - cx).hypot(f64::from(y) - cy))
|
||||
.fold(0.0, f64::max);
|
||||
let last = (curve.arc((far + reach) / curve.b) / pitch).ceil();
|
||||
// Each tile's angle on the curve, worked out once when the layout is small enough.
|
||||
let table: Vec<f64> = if last < MAX_TABLE as f64 { (0..=last as usize).map(|n| curve.angle_at(n as f64 * pitch)).collect() } else { Vec::new() };
|
||||
let angle_of = |n: i64| table.get(n as usize).copied().unwrap_or_else(|| curve.angle_at(n as f64 * pitch));
|
||||
let placement = |n: i64| {
|
||||
let t = angle_of(n);
|
||||
let r = curve.b * t;
|
||||
let (sin, cos) = t.sin_cos();
|
||||
// The centre on the curve (y down) and the direction the curve runs there, counter-clockwise.
|
||||
let (x, y) = (cx + r * cos, cy - r * sin);
|
||||
let angle = if self.upright { 0.0 } else { (curve.b * sin + r * cos).atan2(curve.b * cos - r * sin).to_degrees() };
|
||||
let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin());
|
||||
// The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise).
|
||||
let (hx, hy) = (-tw / 2.0, -th / 2.0);
|
||||
Placement::anchored((x + hx * c + hy * s, y - hx * s + hy * c), true, (0.0, 0.0), scale as f32, angle as f32)
|
||||
};
|
||||
let mut spans: Vec<(i64, i64)> = Vec::new();
|
||||
let mut i = 0;
|
||||
for y in rect.y0..rect.y1 {
|
||||
let py = f64::from(y) + 0.5;
|
||||
for x in rect.x0..rect.x1 {
|
||||
let px = f64::from(x) + 0.5;
|
||||
let (dx, dy) = (px - cx, cy - py);
|
||||
let r = dx.hypot(dy);
|
||||
let phi = dy.atan2(dx).rem_euclid(TAU);
|
||||
// The curve within reach lies between these angles, and on each turn only within `half` of the pixel's
|
||||
// own direction: a point at angle δ from it is at least 2 √(r ρ) sin(δ/2) away.
|
||||
let (lo, hi) = (((r - reach) / curve.b).max(0.0), (r + reach) / curve.b);
|
||||
let q = reach / (2.0 * (r * (r - reach).max(0.0)).sqrt());
|
||||
let half = if q.is_finite() && q < 1.0 { 2.0 * q.asin() } else { PI };
|
||||
// The tiles near the pixel on each turn, the outermost (topmost) turn first, until enough to try.
|
||||
spans.clear();
|
||||
let first = ((lo - half - phi) / TAU).ceil() as i64;
|
||||
let turns = ((hi + half - phi) / TAU).floor() as i64;
|
||||
let mut count = 0;
|
||||
for k in (first..=turns).rev() {
|
||||
let t = phi + TAU * k as f64;
|
||||
let (a, b) = ((t - half).max(lo), (t + half).min(hi));
|
||||
if a > b {
|
||||
continue;
|
||||
}
|
||||
let (n0, n1) = ((curve.arc(a) / pitch).floor().max(0.0) as i64, (curve.arc(b) / pitch).ceil() as i64);
|
||||
match spans.last_mut() {
|
||||
Some(last) if n1 + 1 >= last.0 => last.0 = last.0.min(n0),
|
||||
_ => spans.push((n0, n1)),
|
||||
}
|
||||
count += n1 - n0 + 1;
|
||||
if count > MAX_CANDIDATES as i64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut acc = [0.0f32; 4];
|
||||
let (mut layers, mut tried) = (0, 0);
|
||||
'tiles: for &(n0, n1) in &spans {
|
||||
for n in (n0..=n1).rev() {
|
||||
tried += 1;
|
||||
if layers >= MAX_LAYERS || tried > MAX_CANDIDATES || acc[3] >= 1.0 {
|
||||
break 'tiles;
|
||||
}
|
||||
let place = placement(n);
|
||||
let (u, v) = place.map(px, py);
|
||||
if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) {
|
||||
continue;
|
||||
}
|
||||
layers += 1;
|
||||
let mut q = tile.sample_area(&place, px, py);
|
||||
let d = self.jitter.offsets(n, 0);
|
||||
// Without a drift a tile keeps its exact colour, also a float one past 1.
|
||||
for ch in 0..3 {
|
||||
if d[ch] != 0.0 {
|
||||
q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
// Front to back: what is already in front covers this tile.
|
||||
let k = q[3] * (1.0 - acc[3]);
|
||||
for ch in 0..3 {
|
||||
acc[ch] += q[ch] * k;
|
||||
}
|
||||
acc[3] += k;
|
||||
}
|
||||
}
|
||||
if acc[3] > 0.0 {
|
||||
out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)];
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ 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);
|
||||
Source::Pixels(area, scripted(p, script, &tile, &pat, area)?)
|
||||
Source::Pixels(area, scripted(p, script, &tile, &pat, doc_bounds, area)?)
|
||||
} else {
|
||||
// Photoshop's Fill uses the canvas origin.
|
||||
let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle);
|
||||
@@ -209,16 +209,25 @@ fn script(p: &Value) -> Result<Option<&'static str>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The scripted pattern `script` laid out over `area`, with its values from `p` (each clamped to its range, the factory
|
||||
/// value when missing) and an optional whole-number `seed` for the per-tile randomness.
|
||||
fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, pat: &photocraft_doc::pattern::Pattern, area: Rect) -> Result<Vec<[f32; 4]>> {
|
||||
use photocraft_compose::scripted_pattern::{BrickFill, Jitter, controls};
|
||||
let controls =
|
||||
controls(script, pat.width, pat.height).ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill paints today")))?;
|
||||
/// The scripted pattern `script` laid out over `area` of the document `canvas`, with its values from `p` (each
|
||||
/// clamped to its range, the factory value when missing) and an optional whole-number `seed` for the per-tile randomness.
|
||||
fn scripted(
|
||||
p: &Value,
|
||||
script: &str,
|
||||
tile: &photocraft_compose::pattern::Tile,
|
||||
pat: &photocraft_doc::pattern::Pattern,
|
||||
canvas: Rect,
|
||||
area: Rect,
|
||||
) -> Result<Vec<[f32; 4]>> {
|
||||
use photocraft_compose::scripted_pattern::{SUPPORTED, controls, render};
|
||||
let unsupported = || bad(format!("the `{script}` script is not supported yet; only {} paint today", SUPPORTED.join(" and ")));
|
||||
let controls = controls(script, pat.width, pat.height).ok_or_else(unsupported)?;
|
||||
let mut values = std::collections::HashMap::new();
|
||||
for c in &controls {
|
||||
let v = match p.get(c.key) {
|
||||
None | Some(Value::Null) => c.default,
|
||||
Some(Value::Bool(on)) if c.toggle => f64::from(u8::from(*on)),
|
||||
Some(v) if c.toggle => return Err(bad(format!("`{}` must be true or false, not {v}", c.key))),
|
||||
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(format!("`{}` must be a number {}..{}, not {v}", c.key, c.min, c.max)))?,
|
||||
};
|
||||
values.insert(c.key, c.clamp(v));
|
||||
@@ -228,9 +237,7 @@ fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, p
|
||||
Some(v) => v.as_u64().ok_or_else(|| bad(format!("`seed` must be a whole number, not {v}")))?,
|
||||
};
|
||||
let get = |k: &str| values.get(k).copied().unwrap_or_default();
|
||||
let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed };
|
||||
let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter };
|
||||
Ok(brick.render(tile, pat.width, pat.height, area))
|
||||
render(script, &get, seed, canvas, tile, (pat.width, pat.height), area).ok_or_else(unsupported)
|
||||
}
|
||||
|
||||
/// The reference application refuses Fill on the Quick Mask with a colour-only blend mode, Preserve Transparency or
|
||||
|
||||
@@ -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 five
|
||||
//! 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,7 +163,7 @@ 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 ["crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"] {
|
||||
for script in ["crossWeave", "placeAlongPath", "randomFill", "symmetryFill"] {
|
||||
let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string();
|
||||
assert!(err.contains("not supported"), "{script}: {err}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! #17432: the Spiral scripted pattern lays the pattern tile along a spiral around the canvas centre. Its values are
|
||||
//! Pattern Scale, Ring spacing, Pattern spacing, Keep pattern upright and the shared randomness; the tiles turn with the
|
||||
//! curve unless kept upright (the reference application painted nothing then; PhotoCraft paints what its preview shows).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green. Defined as "probe"
|
||||
/// from a `mode` / `depth` document.
|
||||
fn define_probe(s: &mut Session, mode: &str, depth: u32) {
|
||||
s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap();
|
||||
for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] {
|
||||
s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
|
||||
}
|
||||
s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap();
|
||||
}
|
||||
|
||||
/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined.
|
||||
fn session_in(mode: &str, depth: u32) -> Session {
|
||||
let mut s = crate::session();
|
||||
define_probe(&mut s, mode, depth);
|
||||
s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
session_in("rgb", 8)
|
||||
}
|
||||
|
||||
/// Spiral with both randomness values at 0 and `extra` values on top.
|
||||
fn spiral(extra: Value) -> Value {
|
||||
let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "spiral", "colorRandomness": 0, "brightnessRandomness": 0});
|
||||
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Tiles far enough apart that none touches another: rings 90 px apart, tiles 140 px apart along the curve.
|
||||
fn apart(extra: Value) -> Value {
|
||||
let mut p = spiral(json!({"ringSpacing": 60, "patternSpacing": 100}));
|
||||
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 undo_label(s: &Session) -> Option<String> {
|
||||
s.active().unwrap().history.undo_label().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The painted area of the active layer: (x0, y0, x1, y1).
|
||||
fn painted_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 bounding boxes (x0, y0, x1, y1) of the separate painted blobs that do not touch the canvas edge.
|
||||
fn blobs(s: &Session) -> Vec<(i32, i32, i32, i32)> {
|
||||
let (w, h) = (600, 400);
|
||||
let mut seen = vec![false; (w * h) as usize];
|
||||
let mut out = Vec::new();
|
||||
for y0 in 0..h {
|
||||
for x0 in 0..w {
|
||||
if seen[(y0 * w + x0) as usize] || pixel(s, x0, y0)[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut b = (x0, y0, x0 + 1, y0 + 1);
|
||||
let mut stack = vec![(x0, y0)];
|
||||
seen[(y0 * w + x0) as usize] = true;
|
||||
while let Some((x, y)) = stack.pop() {
|
||||
b = (b.0.min(x), b.1.min(y), b.2.max(x + 1), b.3.max(y + 1));
|
||||
for (nx, ny) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] {
|
||||
if (0..w).contains(&nx) && (0..h).contains(&ny) && !seen[(ny * w + nx) as usize] && pixel(s, nx, ny)[3] > 0.0 {
|
||||
seen[(ny * w + nx) as usize] = true;
|
||||
stack.push((nx, ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
if b.0 > 0 && b.1 > 0 && b.2 < w && b.3 < h {
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a blob is no wider than `w` and no taller than `h` (plus a pixel of edge smoothing on each side).
|
||||
fn fits(b: &(i32, i32, i32, i32), w: i32, h: i32) -> bool {
|
||||
b.2 - b.0 <= w + 2 && b.3 - b.1 <= h + 2
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_upright_the_tiles_cover_the_whole_canvas() {
|
||||
let mut s = session();
|
||||
let r = s.execute("edit.fill", spiral(json!({"keepUpright": true}))).unwrap();
|
||||
assert_eq!(r["script"], "spiral");
|
||||
assert_eq!(painted_bounds(&s), Some((0, 0, 600, 400)));
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Fill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_with_the_curve_by_default_and_not_a_no_op() {
|
||||
// The factory values leave Keep pattern upright off.
|
||||
let mut s = session();
|
||||
let mut p = spiral(json!({}));
|
||||
p.as_object_mut().unwrap().remove("keepUpright");
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
s.execute("edit.fill", p).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history state");
|
||||
assert_eq!(painted_bounds(&s), Some((0, 0, 600, 400)), "the spiral fills the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upright_tiles_keep_the_tile_shape_and_turned_ones_lean() {
|
||||
let mut upright = session();
|
||||
upright.execute("edit.fill", apart(json!({"keepUpright": true}))).unwrap();
|
||||
let tiles = blobs(&upright);
|
||||
assert!(tiles.len() >= 5, "{tiles:?}");
|
||||
assert!(tiles.iter().all(|b| fits(b, 40, 30)), "upright tiles stay 40 x 30: {tiles:?}");
|
||||
let mut turned = session();
|
||||
turned.execute("edit.fill", apart(json!({"keepUpright": false}))).unwrap();
|
||||
let tiles = blobs(&turned);
|
||||
assert!(tiles.len() >= 5, "{tiles:?}");
|
||||
let leaning = tiles.iter().filter(|b| !fits(b, 40, 30) && !fits(b, 30, 40)).count();
|
||||
assert!(leaning * 2 > tiles.len(), "most tiles turn with the curve: {tiles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spiral_starts_at_the_canvas_centre_and_winds_outwards() {
|
||||
let mut s = session();
|
||||
s.execute("edit.fill", apart(json!({"keepUpright": true}))).unwrap();
|
||||
let tiles = blobs(&s);
|
||||
// The first tile sits on the centre.
|
||||
let first = tiles.iter().find(|b| (b.0..b.2).contains(&300) && (b.1..b.3).contains(&200)).copied();
|
||||
let (x0, y0, x1, y1) = first.unwrap_or_else(|| panic!("no tile on the centre: {tiles:?}"));
|
||||
assert!(((x0 + x1) - 600).abs() <= 2 && ((y0 + y1) - 400).abs() <= 2, "centred: {first:?}");
|
||||
// The others lie at different distances from it, out to the canvas edge.
|
||||
let mut dist: Vec<i32> = tiles.iter().map(|b| (((b.0 + b.2) / 2 - 300) as f64).hypot(((b.1 + b.3) / 2 - 200) as f64) as i32).collect();
|
||||
dist.sort_unstable();
|
||||
dist.dedup_by(|a, b| (*a - *b).abs() < 5);
|
||||
assert!(dist.len() >= 4, "tiles at several distances: {dist:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_and_scale_change_the_layout() {
|
||||
// Without spacing the tiles touch; with it they stand apart.
|
||||
let mut tight = session();
|
||||
tight.execute("edit.fill", spiral(json!({"keepUpright": true}))).unwrap();
|
||||
let mut loose = session();
|
||||
loose.execute("edit.fill", apart(json!({"keepUpright": true}))).unwrap();
|
||||
let gaps = |s: &Session| (0..600).step_by(7).flat_map(|x| (0..400).step_by(7).map(move |y| (x, y))).filter(|&(x, y)| pixel(s, x, y)[3] == 0.0).count();
|
||||
assert!(gaps(&loose) > gaps(&tight) * 2, "spacing leaves more of the canvas empty");
|
||||
// Half the scale halves the tiles.
|
||||
let mut small = session();
|
||||
small.execute("edit.fill", apart(json!({"keepUpright": true, "patternScale": 0.5}))).unwrap();
|
||||
let tiles = blobs(&small);
|
||||
assert!(tiles.len() >= 5 && tiles.iter().all(|b| fits(b, 20, 15)), "{tiles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomness_varies_tiles_only_above_zero() {
|
||||
let probe = |s: &Session| -> Vec<[u8; 3]> {
|
||||
blobs(s).iter().map(|b| pixel(s, b.0 + 3, (b.1 + b.3) / 2)).filter(|p| p[3] > 0.99).map(|p| [0, 1, 2].map(|c| (p[c] * 255.0).round() as u8)).collect()
|
||||
};
|
||||
let mut exact = session();
|
||||
exact.execute("edit.fill", apart(json!({"keepUpright": true}))).unwrap();
|
||||
assert!(probe(&exact).iter().all(|c| *c == [255, 0, 0]), "{:?}", probe(&exact));
|
||||
let mut drift = session();
|
||||
drift.execute("edit.fill", apart(json!({"keepUpright": true, "colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap();
|
||||
let tiles = probe(&drift);
|
||||
assert!(tiles.windows(2).any(|w| w[0] != w[1]), "tiles differ from each other: {tiles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_stays_in_the_selection_with_mode_and_opacity() {
|
||||
let mut s = session();
|
||||
s.execute("select.rect", json!({"x": 250, "y": 150, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("edit.fill", spiral(json!({"keepUpright": true, "opacity": 50}))).unwrap();
|
||||
let inside = pixel(&s, 300, 200);
|
||||
assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}");
|
||||
assert_eq!(painted_bounds(&s), Some((250, 150, 350, 250)), "clipped to the selection");
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Fill"));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(painted_bounds(&s), None, "one history state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_are_errors_and_extreme_ones_paint() {
|
||||
let mut s = session();
|
||||
for bad in [json!({"keepUpright": 1}), json!({"keepUpright": "yes"}), json!({"ringSpacing": "wide"}), json!({"patternSpacing": [1]})] {
|
||||
assert!(s.execute("edit.fill", spiral(bad.clone())).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(painted_bounds(&s), None, "a refused fill paints nothing");
|
||||
// The tightest packing at the smallest scale, and values far past the limits, clamp and paint.
|
||||
for extreme in [
|
||||
json!({"patternScale": 0.1, "ringSpacing": -28, "patternSpacing": -28}),
|
||||
json!({"patternScale": 0.1, "ringSpacing": -1e12, "patternSpacing": -1e12, "keepUpright": true}),
|
||||
json!({"patternScale": 1e9, "ringSpacing": 1e9, "patternSpacing": 1e9}),
|
||||
] {
|
||||
let mut s = session();
|
||||
s.execute("edit.fill", spiral(extreme.clone())).unwrap_or_else(|e| panic!("{extreme}: {e}"));
|
||||
assert!(pixel(&s, 300, 200)[3] > 0.0, "{extreme}: the centre tile is painted");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_tile_packed_tightly_still_ends() {
|
||||
// A 4000 x 4 tile with the rings 2 px apart: thousands of turns lie within reach of every pixel.
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
|
||||
s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap();
|
||||
s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 280, "y": 180, "width": 40, "height": 40})).unwrap();
|
||||
s.execute("edit.fill", spiral(json!({"pattern": "bar", "ringSpacing": -2, "patternSpacing": -2}))).unwrap();
|
||||
assert!(pixel(&s, 300, 200)[3] > 0.99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spiral_runs_in_every_mode_and_depth() {
|
||||
for (mode, depth) in [("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] {
|
||||
let mut s = session_in(mode, depth);
|
||||
s.execute("edit.fill", spiral(json!({"keepUpright": true}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}"));
|
||||
assert!(pixel(&s, 300, 200)[3] > 0.99, "{mode}/{depth}: painted");
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}");
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,8 @@ mod fill_quick_mask_refusals_tests;
|
||||
#[cfg(test)]
|
||||
mod fill_script_brick_tests;
|
||||
#[cfg(test)]
|
||||
mod fill_script_spiral_tests;
|
||||
#[cfg(test)]
|
||||
mod mixer_indexed_bitmap_tests;
|
||||
#[cfg(test)]
|
||||
mod mixer_toggle_commands_tests;
|
||||
|
||||
@@ -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::{BrickFill, Control, Jitter, SCRIPTS, controls};
|
||||
use photocraft_compose::scripted_pattern::{Control, SCRIPTS, controls, render};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
@@ -50,6 +50,9 @@ fn label(key: &str) -> Label {
|
||||
"colorRandomness" => tl!("Color randomness"),
|
||||
"brightnessRandomness" => tl!("Brightness randomness"),
|
||||
"patternRotateAngle" => tl!("Pattern rotate angle"),
|
||||
"ringSpacing" => tl!("Ring spacing"),
|
||||
"patternSpacing" => tl!("Pattern spacing"),
|
||||
"keepUpright" => tl!("Keep pattern upright"),
|
||||
_ => tl!("Value"),
|
||||
})
|
||||
}
|
||||
@@ -57,7 +60,7 @@ fn label(key: &str) -> Label {
|
||||
/// The unit shown after a value's field, if any.
|
||||
fn unit(key: &str) -> Option<Label> {
|
||||
match key {
|
||||
"spacing" => Some(Label::from(tl!("px"))),
|
||||
"spacing" | "ringSpacing" | "patternSpacing" => Some(Label::from(tl!("px"))),
|
||||
"offsetBetweenRows" => Some(Label::from(tl!("%"))),
|
||||
"patternRotateAngle" => Some(Label::from(tl!("°"))),
|
||||
_ => None,
|
||||
@@ -91,6 +94,10 @@ fn rows(controls: &[Control]) -> Vec<Param> {
|
||||
.separated_at(4),
|
||||
];
|
||||
for c in controls {
|
||||
if c.toggle {
|
||||
rows.push(Param::new(c.key, label(c.key), ParamKind::bool(c.default != 0.0)));
|
||||
continue;
|
||||
}
|
||||
let mut row = Param::new(c.key, label(c.key), ParamKind::range(c.min, c.max, c.default, SliderScale::Linear)).decimals(c.decimals);
|
||||
if let Some(unit) = unit(c.key) {
|
||||
row = row.unit_label(unit);
|
||||
@@ -100,19 +107,33 @@ fn rows(controls: &[Control]) -> Vec<Param> {
|
||||
rows
|
||||
}
|
||||
|
||||
/// The value of `c` in `f`: a check box reads as 0 or 1.
|
||||
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) }
|
||||
}
|
||||
|
||||
/// Sets `c` to `v` in `f`: a check box is on from 0.5.
|
||||
fn put(f: &mut DialogFields, c: &Control, v: f64) {
|
||||
if c.toggle {
|
||||
f.set(c.key, v >= 0.5);
|
||||
} else {
|
||||
f.set(c.key, v);
|
||||
}
|
||||
}
|
||||
|
||||
/// The factory values of `controls`, with Preset › Default.
|
||||
fn factory(controls: &[Control]) -> DialogFields {
|
||||
let mut f = DialogFields::new();
|
||||
f.set("preset", "default");
|
||||
for c in controls {
|
||||
f.set(c.key, c.default);
|
||||
put(&mut f, c, c.default);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// Whether the values of `f` are the factory values.
|
||||
fn is_factory(f: &DialogFields, controls: &[Control]) -> bool {
|
||||
controls.iter().all(|c| f.number(c.key).is_some_and(|v| (v - c.default).abs() < 1e-9))
|
||||
controls.iter().all(|c| value(f, c).is_some_and(|v| (v - c.default).abs() < 1e-9))
|
||||
}
|
||||
|
||||
/// The values a script dialog opens with: the ones confirmed last time (each kept in its range), else the factory values.
|
||||
@@ -124,8 +145,8 @@ fn opening(ctx: &egui::Context, key: &str, controls: &[Control]) -> DialogFields
|
||||
f.set("preset", preset);
|
||||
}
|
||||
for c in controls {
|
||||
if let Some(v) = saved.number(c.key) {
|
||||
f.set(c.key, c.clamp(v));
|
||||
if let Some(v) = value(&saved, c) {
|
||||
put(&mut f, c, c.clamp(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,9 +186,11 @@ pub fn params(script: &str, f: &DialogFields, fill: &Value) -> Value {
|
||||
p.insert("contents".into(), json!("pattern"));
|
||||
p.insert("script".into(), json!(script));
|
||||
for c in controls(script, 1, 1).unwrap_or_default() {
|
||||
if let Some(v) = f.number(c.key) {
|
||||
p.insert(c.key.into(), json!(v));
|
||||
}
|
||||
match (c.toggle, value(f, &c)) {
|
||||
(true, Some(v)) => p.insert(c.key.into(), json!(v >= 0.5)),
|
||||
(false, Some(v)) => p.insert(c.key.into(), json!(v)),
|
||||
(_, None) => None,
|
||||
};
|
||||
}
|
||||
Value::Object(p)
|
||||
}
|
||||
@@ -193,6 +216,7 @@ pub(crate) fn footer(app: &mut PhotocraftApp, _ctx: &egui::Context, id: DialogId
|
||||
for (k, v) in opening.as_object().into_iter().flatten() {
|
||||
match v {
|
||||
Value::String(s) => dialog.set_field(k.clone(), FieldValue::Text(s.clone())),
|
||||
Value::Bool(on) => dialog.set_field(k.clone(), FieldValue::Bool(*on)),
|
||||
v => {
|
||||
if let Some(n) = v.as_f64() {
|
||||
dialog.set_field(k.clone(), FieldValue::Number(n));
|
||||
@@ -236,7 +260,7 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if let Some(held) = app.framework.captured.get_mut(&key) {
|
||||
held["lastPreset"] = json!(now);
|
||||
}
|
||||
let picture = pattern.and_then(|p| preview(ctx, id, &p, &shown, &controls));
|
||||
let picture = pattern.and_then(|p| preview(ctx, id, script_of(&key), &p, &shown, &controls));
|
||||
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) {
|
||||
dialog.set_preview(Some(match picture {
|
||||
Some(texture) => PreviewState::Ready(egui::load::SizedTexture::from_handle(&texture)),
|
||||
@@ -246,11 +270,18 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview of the values `f`: the script laid out over a sample area with pattern `p`, on white. The texture is
|
||||
/// kept per dialog and drawn again only when the values or the pattern change.
|
||||
fn preview(ctx: &egui::Context, id: DialogId, p: &photocraft_doc::Pattern, f: &DialogFields, controls: &[Control]) -> Option<egui::TextureHandle> {
|
||||
let values: Vec<f64> = controls.iter().map(|c| c.clamp(f.number(c.key).unwrap_or(c.default))).collect();
|
||||
let stamp = format!("{}:{values:?}", p.id);
|
||||
/// The preview of the values `f`: `script` laid out over a sample area with pattern `p` (a spiral around its centre), on
|
||||
/// white. The texture is kept per dialog and drawn again only when the values or the pattern change.
|
||||
fn preview(
|
||||
ctx: &egui::Context,
|
||||
id: DialogId,
|
||||
script: &str,
|
||||
p: &photocraft_doc::Pattern,
|
||||
f: &DialogFields,
|
||||
controls: &[Control],
|
||||
) -> Option<egui::TextureHandle> {
|
||||
let values: Vec<f64> = controls.iter().map(|c| c.clamp(value(f, c).unwrap_or(c.default))).collect();
|
||||
let stamp = format!("{script}:{}:{values:?}", p.id);
|
||||
let cache = egui::Id::unique(("fill-script-preview", id.value()));
|
||||
if let Some((seen, texture)) = ctx.data(|d| d.get_temp::<(String, egui::TextureHandle)>(cache))
|
||||
&& seen == stamp
|
||||
@@ -259,9 +290,8 @@ fn preview(ctx: &egui::Context, id: DialogId, p: &photocraft_doc::Pattern, f: &D
|
||||
}
|
||||
let tile = photocraft_compose::pattern::Tile::new(p)?;
|
||||
let get = |k: &str| controls.iter().zip(&values).find(|(c, _)| c.key == k).map_or(0.0, |(_, v)| *v);
|
||||
let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed: 1 };
|
||||
let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter };
|
||||
let px = brick.render(&tile, p.width, p.height, photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32));
|
||||
let area = photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32);
|
||||
let px = render(script, &get, 1, area, &tile, (p.width, p.height), area)?;
|
||||
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);
|
||||
|
||||
@@ -169,10 +169,10 @@ fn the_fill_dialog_remembers_the_last_script() {
|
||||
let id = super::super::fill_ui::open(&mut app);
|
||||
set(&mut app, id, "contents", json!("pattern"));
|
||||
set(&mut app, id, "script", json!(true));
|
||||
set(&mut app, id, "scriptName", json!("spiral"));
|
||||
set(&mut app, id, "scriptName", json!("symmetryFill"));
|
||||
confirm(&mut app, id);
|
||||
pass(&mut app);
|
||||
// Spiral has no layout yet: the fill is refused as not supported instead of filling.
|
||||
// Symmetry Fill has no layout yet: the fill is refused as not supported instead of filling.
|
||||
assert_eq!(alpha(&app, 3, 3), 0.0);
|
||||
while open_count(&app) > 0 {
|
||||
let top = newest(&app);
|
||||
@@ -180,7 +180,7 @@ fn the_fill_dialog_remembers_the_last_script() {
|
||||
}
|
||||
let id = super::super::fill_ui::open(&mut app);
|
||||
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone();
|
||||
assert_eq!(fields.text("scriptName"), Some("spiral"));
|
||||
assert_eq!(fields.text("scriptName"), Some("symmetryFill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -207,3 +207,31 @@ fn a_typed_value_past_the_range_is_clamped_with_the_range_alert() {
|
||||
let script = dialogs.iter().find(|d| d.key.as_deref() == Some("edit.fill.script.brickFill")).map(|d| d.id).unwrap();
|
||||
assert_eq!(h.state().framework.dialogs.get_by_id::<HostedParamDialog>(script).unwrap().fields().number("patternScale"), Some(1.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spiral_has_the_keep_upright_check_box_and_its_ok_fills_with_it() {
|
||||
let mut app = app();
|
||||
let before = past(&app);
|
||||
fill_with_script(&mut app, "spiral");
|
||||
assert_eq!(top_key(&app).as_deref(), Some("edit.fill.script.spiral"));
|
||||
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(&app)).unwrap().fields().clone();
|
||||
assert_eq!(fields.bool("keepUpright"), Some(false), "off by default");
|
||||
assert_eq!((field(&app, "ringSpacing"), field(&app, "patternSpacing")), (Some(0.0), Some(0.0)));
|
||||
let mut h = harness(app);
|
||||
assert!(h.query_all_by_role(Role::Dialog).any(|n| n.accesskit_node().label().as_deref() == Some("Spiral")));
|
||||
let at = h.get_by_role_and_label(Role::CheckBox, "Keep pattern upright").rect().center();
|
||||
click(&mut h, at);
|
||||
h.run_steps(3);
|
||||
let mut app = h.into_state();
|
||||
assert_eq!(text(&app, "preset").as_deref(), Some("custom"), "ticking it leaves the factory values");
|
||||
let id = newest(&app);
|
||||
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone();
|
||||
assert_eq!(super::params("spiral", &fields, &json!({}))["keepUpright"], json!(true), "the fill gets the ticked box");
|
||||
confirm(&mut app, id);
|
||||
assert_eq!(past(&app), before + 1, "one history state");
|
||||
assert!(alpha(&app, 60, 45) > 0.99, "the centre tile is painted");
|
||||
// The next Spiral opens with the box still ticked.
|
||||
fill_with_script(&mut app, "spiral");
|
||||
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(&app)).unwrap().fields().clone();
|
||||
assert_eq!(fields.bool("keepUpright"), Some(true));
|
||||
}
|
||||
Reference in new issue
Block a user