Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

continued work

Brandon Thomas6b44c393fa36
diff --git a/Cargo.lock b/Cargo.lock
index 1c97a7844..433462287 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3419,6 +3419,7 @@ dependencies = [
"photocraft-geom",
"photocraft-raster",
"pollster 1.0.1",
+ "rayon",
"wgpu",
]
diff --git a/crates/algo/examples/bench_liquify.rs b/crates/algo/examples/bench_liquify.rs
new file mode 100644
index 000000000..f8e4213d4
--- /dev/null
+++ b/crates/algo/examples/bench_liquify.rs
@@ -0,0 +1,117 @@
+//! Liquify / Puppet / Perspective timings on a 24 MP image.
+//!
+//! ```sh
+//! cargo run --release -p photocraft-algo --example bench_liquify
+//! ```
+
+use std::time::Instant;
+
+use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, ProxyImage, apply_liquify, auto_cell};
+use photocraft_algo::perspective::{PerspectiveMap, Plane};
+use photocraft_algo::puppet::{PuppetDensity, PuppetMode, PuppetPin, PuppetWarp, deform, render};
+use photocraft_algo::transform::Interp;
+use photocraft_algo::warp::warp_mesh_surface;
+use photocraft_color::PixelFormat;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+fn main() {
+ let (w, h) = (6000, 4000);
+ let b = Rect::new(0, 0, w, h);
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ let mut row = vec![0.0f32; w as usize * 4];
+ for y in 0..h {
+ for x in 0..w as usize {
+ let v = (((x / 37) + (y as usize / 41)) % 2) as f32;
+ row[x * 4..x * 4 + 4].copy_from_slice(&[v, x as f32 / w as f32, y as f32 / h as f32, 1.0]);
+ }
+ s.write_region(Rect::new(0, y, w, y + 1), &row);
+ }
+ let cell = auto_cell(b);
+ println!("24 MP RGBA8, field cell {cell} px");
+
+ // Interactive: proxy + per-dab update.
+ let t = Instant::now();
+ let proxy = ProxyImage::new(&s, b, 1600);
+ println!("proxy {}×{} built in {:.1} ms", proxy.w, proxy.h, t.elapsed().as_secs_f64() * 1e3);
+ let mut out = vec![[0u8; 4]; proxy.w * proxy.h];
+ let t = Instant::now();
+ proxy.render(&LiquifyField::new(b, cell), [0, 0, proxy.w, proxy.h], &mut out);
+ println!("full proxy render {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
+ let t = Instant::now();
+ let mut field = LiquifyField::new(b, cell);
+ println!("field alloc {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
+ let mut st = LiquifyStroke::new(LiquifyTool::ForwardWarp, 600.0);
+ let mut worst = 0.0f64;
+ let mut total = 0.0;
+ let n = 60;
+ let mut prev = [2000.0, 2000.0, 1.0];
+ field.stroke_begin(&st, prev);
+ for k in 1..=n {
+ let p = [2000.0 + k as f64 * 25.0, 2000.0 + (k as f64 * 0.3).sin() * 200.0, 1.0];
+ let t = Instant::now();
+ let dirty = field.stroke_segment(&st, prev, p);
+ let r = proxy.proxy_rect(dirty);
+ proxy.render(&field, r, &mut out);
+ let ms = t.elapsed().as_secs_f64() * 1e3;
+ worst = worst.max(ms);
+ total += ms;
+ prev = p;
+ }
+ println!("forward-warp segment (600 px brush, 25 px moves) + proxy update: mean {:.2} ms, worst {:.2} ms", total / n as f64, worst);
+ st.tool = LiquifyTool::Bloat;
+ let t = Instant::now();
+ let mut d = Rect::EMPTY;
+ for _ in 0..20 {
+ d = field.stroke_segment(&st, [3000.0, 1500.0, 1.0], [3000.0, 1500.0, 1.0]);
+ }
+ println!("bloat dab alone: {:.2} ms", t.elapsed().as_secs_f64() * 1e3 / 20.0);
+ let t = Instant::now();
+ for _ in 0..20 {
+ proxy.render(&field, proxy.proxy_rect(d), &mut out);
+ }
+ println!("dab-sized proxy update alone: {:.2} ms", t.elapsed().as_secs_f64() * 1e3 / 20.0);
+ let t = Instant::now();
+ for _ in 0..20 {
+ let d = field.stroke_segment(&st, [3000.0, 1500.0, 1.0], [3000.0, 1500.0, 1.0]);
+ proxy.render(&field, proxy.proxy_rect(d), &mut out);
+ }
+ println!("bloat dab (600 px) + proxy update: {:.2} ms", t.elapsed().as_secs_f64() * 1e3 / 20.0);
+
+ let t = Instant::now();
+ let res = apply_liquify(&s, &field);
+ println!("apply on 24 MP (touched tiles only): {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+ // Worst case: every tile displaced.
+ let mut all = LiquifyField::new(b, cell);
+ for v in all.d.iter_mut() {
+ *v = [1.3, -0.7];
+ }
+ let t = Instant::now();
+ let _ = apply_liquify(&s, &all);
+ println!("apply on 24 MP (whole field displaced): {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+ drop(res);
+
+ // Puppet warp on a 24 MP layer.
+ let pw = PuppetWarp {
+ pins: vec![PuppetPin { src: [1000.0, 2000.0], dst: [1000.0, 2000.0], rotate: None, depth: 0 }, PuppetPin { src: [5000.0, 2000.0], dst: [4800.0, 1200.0], rotate: None, depth: 0 }, PuppetPin { src: [3000.0, 3500.0], dst: [3100.0, 3500.0], rotate: None, depth: 0 }],
+ mode: PuppetMode::Normal,
+ density: PuppetDensity::Normal,
+ expansion: 2.0,
+ };
+ let t = Instant::now();
+ let (solver, v, order) = deform(&s, b, &pw, photocraft_algo::puppet::ITERATIONS);
+ println!("puppet mesh {} verts / {} tris + ARAP ({} rounds): {:.1} ms", solver.mesh.verts.len(), solver.mesh.tris.len(), photocraft_algo::puppet::ITERATIONS, t.elapsed().as_secs_f64() * 1e3);
+ let dst: Vec<[f64; 2]> = pw.pins.iter().map(|p| p.dst).collect();
+ let t = Instant::now();
+ let _ = solver.solve(&dst, &[None; 3], PuppetMode::Normal, 4, Some(&v));
+ println!("puppet interactive re-solve (4 warm rounds): {:.2} ms", t.elapsed().as_secs_f64() * 1e3);
+ let t = Instant::now();
+ let _ = render(&s, b, &solver.mesh, &v, &order, Interp::Bicubic);
+ println!("puppet render 24 MP: {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+
+ let q = [[0.0, 0.0], [6000.0, 0.0], [6000.0, 4000.0], [0.0, 4000.0]];
+ let m = PerspectiveMap::new(&[Plane { src: q, dst: [[400.0, 0.0], [5600.0, 200.0], [6000.0, 4000.0], [0.0, 4000.0]] }]).unwrap();
+ let t = Instant::now();
+ let _ = warp_mesh_surface(&s, b, &|x, y| m.map(x, y), Interp::Bicubic);
+ println!("perspective warp 24 MP: {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+}
diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs
index a461e5b8a..76301fb32 100644
--- a/crates/algo/src/liquify.rs
+++ b/crates/algo/src/liquify.rs
@@ -40,6 +40,10 @@ pub enum LiquifyTool {
Thaw,
/// The Reconstruct… button: scales the whole (unfrozen) field toward zero by `amount` %.
ReconstructAll,
+ /// Mask Options › Mask All / None / Invert All (whole-field freeze edits).
+ FreezeAll,
+ ThawAll,
+ InvertFreeze,
}
impl LiquifyTool {
@@ -69,9 +73,17 @@ impl LiquifyTool {
LiquifyTool::Freeze => "Freeze Mask",
LiquifyTool::Thaw => "Thaw Mask",
LiquifyTool::ReconstructAll => "Reconstruct All",
+ LiquifyTool::FreezeAll => "Mask All",
+ LiquifyTool::ThawAll => "Mask None",
+ LiquifyTool::InvertFreeze => "Invert Mask",
}
}
+ /// Whole-field operations (no brush, no points).
+ pub fn is_global(self) -> bool {
+ matches!(self, LiquifyTool::ReconstructAll | LiquifyTool::FreezeAll | LiquifyTool::ThawAll | LiquifyTool::InvertFreeze)
+ }
+
/// Tools that act while the brush is held still (each recorded point is a dab).
pub fn is_stationary(self) -> bool {
!matches!(self, LiquifyTool::ForwardWarp | LiquifyTool::PushLeft)
@@ -203,53 +215,61 @@ impl LiquifyField {
/// Applies one stroke. Returns the document rectangle whose output changed.
pub fn apply_stroke(&mut self, s: &LiquifyStroke) -> Rect {
- if s.tool == LiquifyTool::ReconstructAll {
- let k = (s.amount.unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;
- for (v, f) in self.d.iter_mut().zip(&self.freeze) {
- let m = 1.0 - k * (1.0 - f);
- v[0] *= m;
- v[1] *= m;
+ match s.tool {
+ LiquifyTool::ReconstructAll => {
+ let k = (s.amount.unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32;
+ for (v, f) in self.d.iter_mut().zip(&self.freeze) {
+ let m = 1.0 - k * (1.0 - f);
+ v[0] *= m;
+ v[1] *= m;
+ }
+ return self.bounds;
}
+ LiquifyTool::FreezeAll => self.freeze.fill(1.0),
+ LiquifyTool::ThawAll => self.freeze.fill(0.0),
+ LiquifyTool::InvertFreeze => self.freeze.iter_mut().for_each(|f| *f = 1.0 - *f),
+ _ => {}
+ }
+ if s.tool.is_global() {
return self.bounds;
}
- let pts: Vec<[f64; 3]> = s.points.iter().filter(|p| p.len() >= 2).map(|p| [p[0], p[1], p.get(2).copied().unwrap_or(1.0).clamp(0.0, 1.0)]).collect();
+ let pts: Vec<[f64; 3]> = s.points.iter().filter(|p| p.len() >= 2).map(|p| [p[0], p[1], p.get(2).copied().unwrap_or(1.0)]).collect();
+ let Some(&first) = pts.first() else { return Rect::EMPTY };
+ let mut dirty = self.stroke_begin(s, first);
+ for w in pts.windows(2) {
+ dirty = dirty.union(&self.stroke_segment(s, w[0], w[1]));
+ }
+ dirty
+ }
+
+ /// Starts a stroke at `p` (`[x, y, pressure]`): stationary tools dab once there. Interactive
+ /// callers use this plus [`Self::stroke_segment`] per new point, which is exactly what
+ /// [`Self::apply_stroke`] does with the whole point list.
+ pub fn stroke_begin(&mut self, s: &LiquifyStroke, p: [f64; 3]) -> Rect {
+ if s.tool.is_stationary() && !s.tool.is_global() { self.dab(s, [p[0], p[1]], [0.0, 0.0], p[2].clamp(0.0, 1.0)) } else { Rect::EMPTY }
+ }
+
+ /// Continues a stroke from `a` to `b`: dabs every fifth of the brush radius (a stationary
+ /// tool held still dabs once at `b`).
+ pub fn stroke_segment(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect {
let mut dirty = Rect::EMPTY;
- let Some(&first) = pts.first() else { return dirty };
+ let (pa, pb) = (a[2].clamp(0.0, 1.0), b[2].clamp(0.0, 1.0));
+ let len = (b[0] - a[0]).hypot(b[1] - a[1]);
+ if len == 0.0 {
+ return if s.tool.is_stationary() { self.dab(s, [b[0], b[1]], [0.0, 0.0], pb) } else { dirty };
+ }
let r = (s.size / 2.0).max(0.5);
let spacing = (r * 0.2).max(0.5);
- if pts.len() == 1 || pts.windows(2).all(|w| w[0][..2] == w[1][..2]) {
- // The brush never moved: stationary tools dab at every recorded point, warps do nothing.
- if !s.tool.is_stationary() {
- return dirty;
- }
- for p in &pts {
- dirty = dirty.union(&self.dab(s, [p[0], p[1]], [0.0, 0.0], p[2]));
- }
- return dirty;
- }
- if s.tool.is_stationary() {
- dirty = dirty.union(&self.dab(s, [first[0], first[1]], [0.0, 0.0], first[2]));
- }
- for w in pts.windows(2) {
- let (a, b) = (w[0], w[1]);
- let len = (b[0] - a[0]).hypot(b[1] - a[1]);
- if len == 0.0 {
- if s.tool.is_stationary() {
- dirty = dirty.union(&self.dab(s, [b[0], b[1]], [0.0, 0.0], b[2]));
- }
- continue;
- }
- let steps = (len / spacing).ceil().max(1.0) as usize;
- for k in 1..=steps {
- let t0 = (k - 1) as f64 / steps as f64;
- let t1 = k as f64 / steps as f64;
- let c = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1];
- let delta = [(b[0] - a[0]) * (t1 - t0), (b[1] - a[1]) * (t1 - t0)];
- let pr = a[2] + (b[2] - a[2]) * t1;
- // Forward Warp centres the dab where the brush was (it drags what is under it).
- let centre = if s.tool.is_stationary() { c } else { [c[0] - delta[0], c[1] - delta[1]] };
- dirty = dirty.union(&self.dab(s, centre, delta, pr));
- }
+ let steps = (len / spacing).ceil().max(1.0) as usize;
+ for k in 1..=steps {
+ let t0 = (k - 1) as f64 / steps as f64;
+ let t1 = k as f64 / steps as f64;
+ let c = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1];
+ let delta = [(b[0] - a[0]) * (t1 - t0), (b[1] - a[1]) * (t1 - t0)];
+ let pr = pa + (pb - pa) * t1;
+ // Forward Warp centres the dab where the brush was (it drags what is under it).
+ let centre = if s.tool.is_stationary() { c } else { [c[0] - delta[0], c[1] - delta[1]] };
+ dirty = dirty.union(&self.dab(s, centre, delta, pr));
}
dirty
}
@@ -616,7 +636,7 @@ impl ProxyImage {
let (bx, by) = (f64::from(self.bounds.x0), f64::from(self.bounds.y0));
let row = |y: usize, line: &mut [[u8; 4]]| {
let py = by + (y as f64 + 0.5) * s;
- for x in x0..x1 {
+ for (x, slot) in line.iter_mut().enumerate().take(x1).skip(x0) {
let px = bx + (x as f64 + 0.5) * s;
let d = field.sample(px, py);
let (u, v) = ((px + d[0] - bx) / s - 0.5, (py + d[1] - by) / s - 0.5);
@@ -624,21 +644,20 @@ impl ProxyImage {
let (fu, fv) = ((u - iu) as f32, (v - iv) as f32);
let at = |x: f64, y: f64| self.px[(y.clamp(0.0, (self.h - 1) as f64) as usize) * self.w + x.clamp(0.0, (self.w - 1) as f64) as usize];
let (a, b, c, e) = (at(iu, iv), at(iu + 1.0, iv), at(iu, iv + 1.0), at(iu + 1.0, iv + 1.0));
- let mut o = [0u8; 4];
- for k in 0..4 {
+ *slot = std::array::from_fn(|k| {
let v = (a[k] * (1.0 - fu) + b[k] * fu) * (1.0 - fv) + (c[k] * (1.0 - fu) + e[k] * fu) * fv;
- o[k] = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
- }
- line[x] = o;
+ (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
+ });
}
};
let rows = &mut out[y0 * self.w..y1 * self.w];
+ // A dab's few thousand pixels are faster on this thread than waking the pool.
#[cfg(not(target_arch = "wasm32"))]
- {
+ if (x1 - x0) * (y1 - y0) > 150_000 {
use rayon::prelude::*;
rows.par_chunks_mut(self.w).enumerate().for_each(|(i, line)| row(y0 + i, line));
+ return;
}
- #[cfg(target_arch = "wasm32")]
rows.chunks_mut(self.w).enumerate().for_each(|(i, line)| row(y0 + i, line));
}
@@ -736,6 +755,16 @@ mod tests {
th.tool = LiquifyTool::Thaw;
g.apply_stroke(&th);
assert!(g.freeze_at(40.0, 32.0) < 0.01);
+ // Mask All / Invert / None.
+ g.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0));
+ assert!(g.freeze.iter().all(|f| *f == 1.0));
+ g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0));
+ assert!(g.freeze.iter().all(|f| *f == 0.0));
+ g.apply_stroke(&fr);
+ g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0));
+ assert!(g.freeze_at(40.0, 32.0) < 0.01 && g.freeze_at(5.0, 5.0) > 0.99);
+ g.apply_stroke(&LiquifyStroke::new(LiquifyTool::ThawAll, 1.0));
+ assert!(g.freeze.iter().all(|f| *f == 0.0));
}
#[test]
diff --git a/crates/algo/src/puppet.rs b/crates/algo/src/puppet.rs
index b998e81e0..ca0e78608 100644
--- a/crates/algo/src/puppet.rs
+++ b/crates/algo/src/puppet.rs
@@ -151,22 +151,28 @@ pub fn build_mesh(src: &Surface, bounds: Rect, density: PuppetDensity, expansion
}
}
} else {
- let mut row = Vec::new();
- for by in 0..bh {
+ // One block row per task (rows are independent).
+ let scan = |by: usize, out: &mut [bool]| {
let r = Rect::new(area.x0, area.y0 + by as i32 * g, area.x0 + bw as i32 * g, area.y0 + (by as i32 + 1) * g).intersect(&bounds);
if r.is_empty() || !src.has_tiles_in(r) {
- continue;
+ return;
}
- src.read_region_into(r, &mut row);
+ let row = src.read_region(r);
let rw = r.width() as usize;
for (i, p) in row.chunks_exact(n).enumerate() {
if p[n - 1] > ALPHA_MIN {
let x = r.x0 + (i % rw) as i32;
- let bx = ((x - area.x0) / g) as usize;
- cov[by * bw + bx] = true;
+ out[((x - area.x0) / g) as usize] = true;
}
}
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ cov.par_chunks_mut(bw).enumerate().for_each(|(by, out)| scan(by, out));
}
+ #[cfg(target_arch = "wasm32")]
+ cov.chunks_mut(bw).enumerate().for_each(|(by, out)| scan(by, out));
}
// Grow / shrink by the expansion (round stamp in block units).
let eb = (e.abs() / f64::from(g)).round() as i32;
@@ -324,6 +330,81 @@ impl Csr {
}
}
+/// Banded Cholesky factor `A = L Lᵀ` (grid meshes number their vertices row by row, so the
+/// system's bandwidth is about two mesh rows): factored once per pin set, then each global step
+/// is two triangular solves.
+struct BandChol {
+ n: usize,
+ p: usize,
+ /// Row `i` holds `L[i][i - p ..= i]`.
+ l: Vec<f64>,
+}
+
+impl BandChol {
+ /// `None` when the band would be too large (or the matrix isn't positive definite).
+ fn new(a: &Csr) -> Option<BandChol> {
+ let n = a.diag.len();
+ let mut p = 0;
+ for i in 0..n {
+ for k in a.rows[i]..a.rows[i + 1] {
+ p = p.max(i.abs_diff(a.cols[k]));
+ }
+ }
+ if n.saturating_mul(p + 1) > 40_000_000 {
+ return None;
+ }
+ let w = p + 1;
+ let mut l = vec![0.0f64; n * w];
+ for i in 0..n {
+ for k in a.rows[i]..a.rows[i + 1] {
+ let j = a.cols[k];
+ if j <= i {
+ l[i * w + (j + p - i)] = a.vals[k];
+ }
+ }
+ }
+ for i in 0..n {
+ let lo = i.saturating_sub(p);
+ for j in lo..=i {
+ let jlo = j.saturating_sub(p).max(lo);
+ let mut s = l[i * w + (j + p - i)];
+ for k in jlo..j {
+ s -= l[i * w + (k + p - i)] * l[j * w + (k + p - j)];
+ }
+ if i == j {
+ if s <= 0.0 || !s.is_finite() {
+ return None;
+ }
+ l[i * w + p] = s.sqrt();
+ } else {
+ l[i * w + (j + p - i)] = s / l[j * w + p];
+ }
+ }
+ }
+ Some(BandChol { n, p, l })
+ }
+
+ #[allow(clippy::needless_range_loop)] // band index arithmetic reads clearer with indices
+ fn solve(&self, b: &[f64], x: &mut [f64]) {
+ let (n, p, w) = (self.n, self.p, self.p + 1);
+ let mut y = b.to_vec();
+ for i in 0..n {
+ let mut s = y[i];
+ for k in i.saturating_sub(p)..i {
+ s -= self.l[i * w + (k + p - i)] * y[k];
+ }
+ y[i] = s / self.l[i * w + p];
+ }
+ for i in (0..n).rev() {
+ let mut s = y[i];
+ for k in i + 1..(i + p + 1).min(n) {
+ s -= self.l[k * w + (i + p - k)] * x[k];
+ }
+ x[i] = s / self.l[i * w + p];
+ }
+ }
+}
+
/// A pin bound to the mesh: barycentric weights on a triangle's vertices.
#[derive(Clone, Debug)]
struct Bound {
@@ -342,6 +423,7 @@ pub struct PuppetSolver {
/// Vertices of components without pins (held at rest).
anchored: Vec<bool>,
matrix: Csr,
+ chol: Option<BandChol>,
pin_weight: f64,
}
@@ -454,7 +536,8 @@ impl PuppetSolver {
}
}
let matrix = Csr::from_triplets(nv, trip);
- PuppetSolver { mesh, w, bound, pin_tris, anchored, matrix, pin_weight }
+ let chol = BandChol::new(&matrix);
+ PuppetSolver { mesh, w, bound, pin_tris, anchored, matrix, chol, pin_weight }
}
/// The ARAP energy of `v` for the given per-triangle linear maps (plus the pin terms).
@@ -550,8 +633,16 @@ impl PuppetSolver {
}
let mut sx: Vec<f64> = v.iter().map(|p| p[0]).collect();
let mut sy: Vec<f64> = v.iter().map(|p| p[1]).collect();
- self.matrix.solve(&bx, &mut sx);
- self.matrix.solve(&by, &mut sy);
+ match &self.chol {
+ Some(c) => {
+ c.solve(&bx, &mut sx);
+ c.solve(&by, &mut sy);
+ }
+ None => {
+ self.matrix.solve(&bx, &mut sx);
+ self.matrix.solve(&by, &mut sy);
+ }
+ }
for (i, p) in v.iter_mut().enumerate() {
*p = [sx[i], sy[i]];
}
@@ -570,16 +661,33 @@ impl PuppetSolver {
return (v, Vec::new());
}
if init.is_none_or(|i| i.len() != nv) {
- let ident = vec![[1.0, 0.0, 0.0, 1.0]; self.mesh.tris.len()];
- let mut r = ident;
- for (k, tris) in self.pin_tris.iter().enumerate() {
- if let Some(Some(deg)) = rotations.get(k) {
- let (s, c) = deg.to_radians().sin_cos();
- for &t in tris {
- r[t] = [c, -s, s, c];
+ // Start from R = I, or with rotated pins, each triangle turned by the inverse-distance
+ // weighted angle of the rotated pins (ARAP alone propagates a turn only slowly).
+ let rotated: Vec<([f64; 2], f64)> = self
+ .bound
+ .iter()
+ .zip(rotations)
+ .filter_map(|(b, r)| r.map(|deg| ((0..3).fold([0.0, 0.0], |a, k| [a[0] + b.bary[k] * self.mesh.verts[b.verts[k]][0], a[1] + b.bary[k] * self.mesh.verts[b.verts[k]][1]]), deg.to_radians())))
+ .collect();
+ let r: Vec<[f64; 4]> = self
+ .mesh
+ .tris
+ .iter()
+ .map(|t| {
+ if rotated.is_empty() {
+ return [1.0, 0.0, 0.0, 1.0];
}
- }
- }
+ let c = t.iter().fold([0.0, 0.0], |a, &i| [a[0] + self.mesh.verts[i][0] / 3.0, a[1] + self.mesh.verts[i][1] / 3.0]);
+ let (mut sw, mut sa) = (0.0, 0.0);
+ for (p, a) in &rotated {
+ let w = 1.0 / (dist2(*p, c) + 1.0);
+ sw += w;
+ sa += w * a;
+ }
+ let (s, co) = (sa / sw).sin_cos();
+ [co, -s, s, co]
+ })
+ .collect();
self.global(&r, pin_dst, &mut v);
}
let mut energies = Vec::with_capacity(iterations);
@@ -709,8 +817,6 @@ mod tests {
for (d, x) in v.iter().zip(&solver.mesh.verts) {
assert!((d[0] - x[0] - 10.0).abs() < 1e-3 && (d[1] - x[1] + 5.0).abs() < 1e-3, "{d:?} {x:?}");
}
- let err = v.iter().zip(&solver.mesh.verts).map(|(d, x)| (d[0] - x[0] - 10.0).abs().max((d[1] - x[1] + 5.0).abs())).fold(0.0, f64::max);
- eprintln!("max translation error {err:e}");
let out = puppet_warp(&s, b, &w, Interp::Bilinear);
assert_eq!(out.content_bounds(), b.translate(10, -5));
assert_eq!(out.pixel(30, 20), s.pixel(20, 25));
@@ -758,8 +864,12 @@ mod tests {
let pins = [[28.0, 14.0], [64.0, 62.0]];
let solver = PuppetSolver::new(mesh, &pins, &[false; 2]);
let order = solver.draw_order(&[1, 0], &pins);
- let last = *order.last().unwrap();
- let c = solver.mesh.tris[last].iter().fold(0.0, |a, &i| a + solver.mesh.verts[i][1] / 3.0);
- assert!(c < 55.0, "triangles near the raised pin draw last");
+ let near0 = |t: usize| {
+ let c = solver.mesh.tris[t].iter().fold([0.0, 0.0], |a, &i| [a[0] + solver.mesh.verts[i][0] / 3.0, a[1] + solver.mesh.verts[i][1] / 3.0]);
+ dist2(c, pins[0]) < dist2(c, pins[1])
+ };
+ // Triangles nearest the raised pin come last, all others first.
+ let k = order.iter().position(|&t| near0(t)).unwrap();
+ assert!(order[..k].iter().all(|&t| !near0(t)) && order[k..].iter().all(|&t| near0(t)));
}
}
diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rs
index 67682010e..6946c16ea 100644
--- a/crates/algo/src/warp.rs
+++ b/crates/algo/src/warp.rs
@@ -229,7 +229,9 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
}
}
let al = acc[a].clamp(0.0, 1.0);
- if al <= 0.0 {
+ // Float noise (a vertex a hair off the pixel grid) must not leave invisible
+ // colour behind in transparent pixels.
+ if al <= 1e-6 {
continue;
}
any = true;
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index 840af7c3e..8e16d106f 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -173,21 +173,124 @@ fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec<f32>, Vec<usize>) {
(g, nearest)
}
+/// Chamfer distance transform with a 5 × 5 mask of exact Euclidean step lengths (1, √2, √5),
+/// plus the index of the nearest `inside` pixel (0 on inside pixels). Photoshop's effect
+/// distances follow this metric: its stroke corners measure 3.236 = √5 + 1 at offset (1, 3)
+/// and 3.650 = √5 + √2 at (2, 3), where the exact distances are 3.162 and 3.606.
+fn chamfer_nearest(inside: &[bool], w: usize, h: usize) -> (Vec<f32>, Vec<usize>) {
+ chamfer_from(inside.iter().map(|&b| if b { 0.0 } else { CHAMFER_INF }).collect(), w, h)
+}
+
+const CHAMFER_INF: f32 = 1e20;
+
+/// [`chamfer_nearest`] from per-pixel start values (`CHAMFER_INF` = not a seed): the result is
+/// the minimum over seeds of start value + path length, so partly covered seeds can start at
+/// their sub-pixel edge offset.
+fn chamfer_from(mut d: Vec<f32>, w: usize, h: usize) -> (Vec<f32>, Vec<usize>) {
+ const S2: f32 = std::f32::consts::SQRT_2;
+ const S5: f32 = 2.236_068;
+ // Forward-pass neighbours (already visited in raster order); the backward pass mirrors them.
+ const FWD: [(i64, i64, f32); 8] = [(-1, 0, 1.0), (-1, -1, S2), (0, -1, 1.0), (1, -1, S2), (-1, -2, S5), (1, -2, S5), (-2, -1, S5), (2, -1, S5)];
+ let mut near: Vec<usize> = (0..w * h).collect();
+ let (wi, hi) = (w as i64, h as i64);
+ let mut relax = |x: i64, y: i64, sign: i64, d: &mut Vec<f32>, near: &mut Vec<usize>| {
+ let i = (y * wi + x) as usize;
+ let mut best = d[i];
+ let mut bn = near[i];
+ for &(ox, oy, wt) in &FWD {
+ let (nx, ny) = (x + ox * sign, y + oy * sign);
+ if nx < 0 || ny < 0 || nx >= wi || ny >= hi {
+ continue;
+ }
+ let j = (ny * wi + nx) as usize;
+ let c = d[j] + wt;
+ if c < best {
+ best = c;
+ bn = near[j];
+ }
+ }
+ d[i] = best;
+ near[i] = bn;
+ };
+ for y in 0..hi {
+ for x in 0..wi {
+ relax(x, y, 1, &mut d, &mut near);
+ }
+ }
+ for y in (0..hi).rev() {
+ for x in (0..wi).rev() {
+ relax(x, y, -1, &mut d, &mut near);
+ }
+ }
+ (d, near)
+}
+
/// Distance from each pixel centre outside the shape to the shape's edge.
/// Pixels with non-zero alpha are inside; the edge inside the nearest such
/// pixel is placed by its alpha (coverage), as Photoshop does. Inside pixels
/// get ≤ 0.
fn dist_outside(s: &Map) -> Vec<f32> {
+ dist_outside_by(s, Metric::Euclidean)
+}
+
+/// Distance metric for effect distance fields.
+#[derive(Clone, Copy, PartialEq)]
+enum Metric {
+ /// Exact Euclidean (spread/choke dilation, glows, bevels).
+ Euclidean,
+ /// 5 × 5 chamfer (strokes; see [`chamfer_nearest`]).
+ Chamfer,
+}
+
+fn nearest(inside: &[bool], w: usize, h: usize, m: Metric) -> (Vec<f32>, Vec<usize>) {
+ match m {
+ Metric::Euclidean => edt_nearest(inside, w, h),
+ Metric::Chamfer => chamfer_nearest(inside, w, h),
+ }
+}
+
+fn dist_outside_by(s: &Map, m: Metric) -> Vec<f32> {
+ if m == Metric::Chamfer {
+ // Seeds start at their sub-pixel edge offset (1 − coverage).
+ let start = s.v.iter().map(|&a| if a > INSIDE_EPS { 1.0 - a.min(1.0) } else { CHAMFER_INF }).collect();
+ let (d, _) = chamfer_from(start, s.w, s.h);
+ return d.iter().zip(&s.v).map(|(d, &a)| if a > INSIDE_EPS { -0.5 } else { d - 0.5 }).collect();
+ }
let inside: Vec<bool> = s.v.iter().map(|&a| a > INSIDE_EPS).collect();
- let (d, near) = edt_nearest(&inside, s.w, s.h);
+ let (d, near) = nearest(&inside, s.w, s.h, m);
(0..d.len()).map(|i| if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i]].min(1.0)) }).collect()
}
/// Distance from each pixel centre inside the shape to the shape's edge
/// (≤ 0 outside).
fn dist_inside(s: &Map) -> Vec<f32> {
+ dist_inside_by(s, Metric::Euclidean)
+}
+
+fn dist_inside_by(s: &Map, m: Metric) -> Vec<f32> {
+ if m == Metric::Chamfer {
+ // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at
+ // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in.
+ let cov = local_coverage(s);
+ let start = s
+ .v
+ .iter()
+ .zip(&cov.v)
+ .map(|(&a, &c)| {
+ if a <= INSIDE_EPS {
+ 0.0
+ } else if c < 1.0 - INSIDE_EPS {
+ c
+ } else {
+ CHAMFER_INF
+ }
+ })
+ .collect();
+ let (d, _) = chamfer_from(start, s.w, s.h);
+ return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect();
+ }
let outside: Vec<bool> = s.v.iter().map(|&a| a <= INSIDE_EPS).collect();
- let (d, _) = edt_nearest(&outside, s.w, s.h);
+ let (d, _) = nearest(&outside, s.w, s.h, m);
d.iter().zip(&outside).map(|(d, o)| if *o { -0.5 } else { d - 0.5 }).collect()
}
@@ -457,7 +560,7 @@ fn paint_pattern(dst: &mut Buffer, m: &Map, patterns: &[Pattern], name: &str, id
}
#[allow(clippy::too_many_arguments)]
-fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, big: Rect, blend: BlendMode, opacity: f32, patterns: &[Pattern]) {
+fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, anchor: (f64, f64), big: Rect, blend: BlendMode, opacity: f32, patterns: &[Pattern]) {
match p {
FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity),
FxPaint::Gradient(g) => {
@@ -474,7 +577,7 @@ fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, big: Rec
)
}
FxPaint::Pattern { name, id, scale } => {
- paint_pattern(dst, m, patterns, name, id, Placement::new(shape_bounds, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity)
+ paint_pattern(dst, m, patterns, name, id, Placement::anchored(anchor, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity)
}
}
}
@@ -611,8 +714,8 @@ pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLigh
.collect();
let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_)));
let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_));
- let (din, dout) = if has_stroke { (Some(dist_inside(&shape)), Some(dist_outside(&shape))) } else { (None, None) };
- let vdout = (has_stroke && vector_shape).then(|| dist_outside(&local_coverage(&shape)));
+ let (din, dout) = if has_stroke { (Some(dist_inside_by(&shape, Metric::Chamfer)), Some(dist_outside_by(&shape, Metric::Chamfer))) } else { (None, None) };
+ let vdout = (has_stroke && vector_shape).then(|| dist_outside_by(&local_coverage(&shape), Metric::Chamfer));
FxMaps { rect, shape, per, outer_bevel, din, dout, vdout }
}
@@ -629,6 +732,8 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
// Layer bounds (gradients aligned with the layer use the whole layer,
// independent of the render rect).
let sb = layer_bounds;
+ // Linked patterns tile from the effects reference point (else the layer's top-left).
+ let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0)));
let rect = backdrop.rect;
let before = backdrop.clone();
// Exterior effects are painted on a backdrop copy extended to `big`.
@@ -657,22 +762,30 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
for (i, e) in rev() {
if let Effect::OuterGlow(g) = e {
let m = fx(i, 0);
- paint_fx(&mut work, &m, &g.paint, sb, big, g.common.blend, g.common.opacity, patterns);
+ paint_fx(&mut work, &m, &g.paint, sb, anchor, big, g.common.blend, g.common.opacity, patterns);
}
}
- // The layer: content at fill opacity, then interior effects.
+ // The layer: content at fill opacity, then interior effects. Interior effects are painted
+ // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha
+ // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and
+ // keeps its alpha, as in Photoshop.
let fill = layer.fill_opacity;
- let mut lay = Buffer { rect: big, px: content.px.iter().map(|p| [p[0], p[1], p[2], p[3] * fill]).collect() };
- let full = shape.clone();
+ let inside = |a: f32| a > INSIDE_EPS;
+ let mut lay = Buffer { rect: big, px: content.px.iter().map(|p| [p[0], p[1], p[2], if inside(p[3]) { fill } else { 0.0 }]).collect() };
+ let rel = |m: Map| -> Map {
+ let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect();
+ Map { w: m.w, h: m.h, v }
+ };
+ let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() };
for (_, e) in rev() {
if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e {
- paint_pattern(&mut lay, &full, patterns, name, id, Placement::new(sb, *link, *phase, *scale, *angle), big, common.blend, common.opacity);
+ paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity);
}
}
for (_, e) in rev() {
if let Effect::GradientOverlay { common, gradient, .. } = e {
- paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, big, common.blend, common.opacity, patterns)
+ paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns)
}
}
for (_, e) in rev() {
@@ -682,25 +795,24 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
}
for (i, e) in rev() {
if let Effect::Satin(s) = e {
- let m = fx(i, 0);
+ let m = rel(fx(i, 0));
paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity);
}
}
for (i, e) in rev() {
if let Effect::InnerGlow(g) = e {
- let m = fx(i, 0);
- paint_fx(&mut lay, &m, &g.paint, sb, big, g.common.blend, g.common.opacity, patterns);
+ let m = rel(fx(i, 0));
+ paint_fx(&mut lay, &m, &g.paint, sb, anchor, big, g.common.blend, g.common.opacity, patterns);
}
}
for (i, e) in rev() {
if let Effect::InnerShadow(s) = e {
- let m = fx(i, 0);
+ let m = rel(fx(i, 0));
paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity);
}
}
- // Strokes. Outside parts are slid beneath the layer, so the first listed
- // (top) instance is processed first; inside parts are painted over it,
- // bottom instance first.
+ // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts
+ // are slid beneath it, so the first listed (top) instance is processed first.
let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect();
let (din, dout) = match (&maps.din, &maps.dout) {
(Some(a), Some(b)) if !strokes.is_empty() => (maps.crop_vec(a, big, 0.0), maps.crop_vec(b, big, FAR)),
@@ -711,7 +823,35 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
StrokePosition::Inside => (st.size, 0.0),
StrokePosition::Center => (st.size / 2.0, st.size / 2.0),
};
+ for st in strokes.iter().rev().copied() {
+ let (in_w, _) = widths(st);
+ if in_w <= 0.0 {
+ continue;
+ }
+ let mut m = Map::new(w, h, 0.0);
+ for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) {
+ *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 };
+ }
+ paint_fx(&mut lay, &m, &st.paint, sb, anchor, big, st.common.blend, st.common.opacity, patterns);
+ }
+ for (i, e) in rev() {
+ if let Effect::BevelEmboss(b) = e
+ && !maps.outer_bevel[i]
+ {
+ let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1)));
+ paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity);
+ paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity);
+ }
+ }
+ // The shape's own alpha.
+ for (p, a) in lay.px.iter_mut().zip(&shape.v) {
+ p[3] *= a.min(1.0);
+ }
let vdout = maps.vdout.as_ref().filter(|_| vector_shape && !strokes.is_empty()).map(|v| maps.crop_vec(v, big, FAR));
+ // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A
+ // higher stroke knocks out the ones below it (Photoshop: a Multiply stroke listed above a
+ // wider Normal stroke multiplies the backdrop, not the lower stroke).
+ let mut cover = vec![0.0f32; w * h];
for st in strokes.iter().copied() {
let (_, out_w) = widths(st);
if out_w <= 0.0 {
@@ -721,37 +861,24 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
// local coverage; the stroke never shows through the shape's pixels.
let d = vdout.as_ref().unwrap_or(&dout);
let mut m = Map::new(w, h, 0.0);
- for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(d) {
- *mv = if *a > INSIDE_EPS {
+ for (((mv, a), dv), c) in m.v.iter_mut().zip(&shape.v).zip(d).zip(cover.iter_mut()) {
+ let k = if inside(*a) {
if vector_shape { 0.0 } else { 1.0 }
} else {
(out_w + 0.5 - dv).clamp(0.0, 1.0)
};
+ *mv = k * (1.0 - *c);
+ *c += *mv;
}
- let mut under = Buffer::transparent(big);
- paint_fx(&mut under, &m, &st.paint, sb, big, BlendMode::Normal, st.common.opacity, patterns);
- for (u, l) in under.px.iter_mut().zip(&lay.px) {
- *u = psblend::composite(BlendMode::Normal, *u, *l, 1.0);
- }
- lay = under;
- }
- for st in strokes.iter().rev().copied() {
- let (in_w, _) = widths(st);
- if in_w <= 0.0 {
- continue;
- }
- let mut m = Map::new(w, h, 0.0);
- for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) {
- *mv = (in_w + 0.5 - dv).clamp(0.0, 1.0) * a;
- }
- paint_fx(&mut lay, &m, &st.paint, sb, big, st.common.blend, st.common.opacity, patterns);
+ paint_fx(&mut work, &m, &st.paint, sb, anchor, big, st.common.blend, st.common.opacity, patterns);
}
for (i, e) in rev() {
- if let Effect::BevelEmboss(b) = e {
- let (hi, sh, outer) = (fx(i, 0), fx(i, 1), maps.outer_bevel[i]);
- let dst = if outer { &mut work } else { &mut lay };
- paint_color(dst, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity);
- paint_color(dst, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity);
+ if let Effect::BevelEmboss(b) = e
+ && maps.outer_bevel[i]
+ {
+ let (hi, sh) = (fx(i, 0), fx(i, 1));
+ paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity);
+ paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity);
}
}
@@ -792,6 +919,39 @@ fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] {
out
}
+/// A distance field of an effect shape, as the map builders above compute it (for the GPU
+/// compositor, which builds the rest of the maps itself; keep in sync with `shadow_map`,
+/// `glow_map`, `bevel_maps` and `build_maps`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum FieldKind {
+ /// `dist_outside` of the shape: spread of drop shadows and softer outer glows, precise outer
+ /// and centre glows, bevels.
+ Outside,
+ /// `dist_inside` of the shape: precise edge inner glows, bevels.
+ Inside,
+ /// `dist_outside` of `1 - alpha`: choke of inner shadows, softer inner glows.
+ OutsideInverse,
+ /// Stroke distance outside the shape.
+ StrokeOutside,
+ /// Stroke distance inside the shape.
+ StrokeInside,
+ /// Stroke distance outside a shape layer's outline (from its local coverage).
+ StrokeOutsideVector,
+}
+
+/// The `kind` distance field of the shape `alpha` (row-major `w × h`).
+pub fn distance_field(kind: FieldKind, alpha: Vec<f32>, w: usize, h: usize) -> Vec<f32> {
+ let s = Map { w, h, v: alpha };
+ match kind {
+ FieldKind::Outside => dist_outside(&s),
+ FieldKind::Inside => dist_inside(&s),
+ FieldKind::OutsideInverse => dist_outside(&s.map(|a| 1.0 - a)),
+ FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer),
+ FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer),
+ FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Chamfer),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index fe7e3e791..8df3f324d 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -268,6 +268,13 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
Some(buf)
}
+/// The alpha of `layer`'s own content over `rect` (masks applied, row-major): the shape its
+/// effect maps are built from (for the GPU compositor). Zero for adjustment layers.
+pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec<f32> {
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns };
+ render_content(layer, rect, &cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; rect.width() as usize * rect.height() as usize])
+}
+
pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {
let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize];
s.read_rgba_into(rect, &mut px);
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs
index d5e445d3a..07a90a1d4 100644
--- a/crates/compose/src/pattern.rs
+++ b/crates/compose/src/pattern.rs
@@ -81,7 +81,15 @@ impl Placement {
/// `frame`: the layer's frame (used when `link`); `phase` in pixels; `scale` as a fraction;
/// `angle` in degrees counter-clockwise.
pub fn new(frame: Rect, link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement {
- let base = if link && !frame.is_empty() { (f64::from(frame.x0), f64::from(frame.y0)) } else { (0.0, 0.0) };
+ let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) };
+ Self::anchored(anchor, link, phase, scale, angle)
+ }
+
+ /// Like [`Placement::new`], with the linked origin given as a point. Layer effects anchor
+ /// linked patterns at the layer's effects reference point (PSD `fxrp`): Photoshop's
+ /// pattern overlays and pattern strokes match pixel-for-pixel tiled from there.
+ pub fn anchored(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement {
+ let base = if link { anchor } else { (0.0, 0.0) };
let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1));
let s = f64::from(scale);
let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 };
diff --git a/crates/compose/tests/artboard.rs b/crates/compose/tests/artboard.rs
new file mode 100644
index 000000000..c0904039f
--- /dev/null
+++ b/crates/compose/tests/artboard.rs
@@ -0,0 +1,67 @@
+//! Artboards: contents clipped to the board, background painted behind them, backdrop untouched
+//! outside. Checked at 8, 16 and 32-bit.
+
+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
+use photocraft_compose::{render, render_tiled};
+use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent};
+use photocraft_geom::{Rect, Size};
+
+fn artboard_doc(depth: SampleType, background: ArtboardBackground, blend: BlendMode) -> Document {
+ let mut d = Document::new("a", Size::new(40, 20), ColorMode::Rgb, depth);
+ let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
+ // A red layer spanning the whole canvas, inside an artboard covering x 10..30, y 5..15.
+ let mut red = Layer::raster("red", fmt);
+ red.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 10), &[1.0, 0.0, 0.0, 1.0]);
+ let mut g = Layer::group("Artboard 1", vec![red]);
+ g.blend = blend;
+ if let LayerContent::Group(gr) = &mut g.content {
+ gr.artboard = Some(Artboard { rect: Rect::new(10, 5, 30, 15), background, preset: String::new() });
+ }
+ d.layers.push(g);
+ d
+}
+
+fn close(a: [f32; 4], b: [f32; 4]) -> bool {
+ a.iter().zip(b).all(|(x, y)| (x - y).abs() < 2.0 / 255.0)
+}
+
+#[test]
+fn contents_are_clipped_and_background_painted() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for blend in [BlendMode::PassThrough, BlendMode::Normal] {
+ let d = artboard_doc(depth, ArtboardBackground::White, blend);
+ let buf = render(&d, d.bounds());
+ // Outside the board: nothing (the red layer is clipped away).
+ assert!(close(buf.get(2, 2), [0.0; 4]), "{depth:?} {:?}", buf.get(2, 2));
+ assert!(close(buf.get(35, 8), [0.0; 4]));
+ // Inside, over the red: red; inside below it: the white board background.
+ assert!(close(buf.get(15, 7), [1.0, 0.0, 0.0, 1.0]), "{:?}", buf.get(15, 7));
+ assert!(close(buf.get(15, 12), [1.0, 1.0, 1.0, 1.0]), "{:?}", buf.get(15, 12));
+ // Edges are half-open.
+ assert!(close(buf.get(29, 14), [1.0, 1.0, 1.0, 1.0]));
+ assert!(close(buf.get(30, 14), [0.0; 4]));
+ // Tiled rendering agrees with one pass.
+ assert_eq!(render_tiled(&d, d.bounds(), 7).px, buf.px);
+ }
+ }
+}
+
+#[test]
+fn background_kinds() {
+ let at = |bg| render(&artboard_doc(SampleType::U8, bg, BlendMode::PassThrough), Rect::from_xywh(20, 12, 1, 1)).px[0];
+ assert!(close(at(ArtboardBackground::Black), [0.0, 0.0, 0.0, 1.0]));
+ assert!(close(at(ArtboardBackground::Transparent), [0.0; 4]));
+ assert!(close(at(ArtboardBackground::Custom(Color::rgb(0.0, 0.0, 1.0))), [0.0, 0.0, 1.0, 1.0]));
+}
+
+#[test]
+fn backdrop_outside_the_board_is_untouched() {
+ let mut d = artboard_doc(SampleType::U8, ArtboardBackground::Transparent, BlendMode::PassThrough);
+ let mut bg = Layer::raster("bg", d.pixel_format());
+ bg.surface_mut().unwrap().fill_rect(d.bounds(), &[0.0, 1.0, 0.0, 1.0]);
+ d.layers.insert(0, bg);
+ let buf = render(&d, d.bounds());
+ assert!(close(buf.get(2, 2), [0.0, 1.0, 0.0, 1.0]));
+ assert!(close(buf.get(15, 7), [1.0, 0.0, 0.0, 1.0]));
+ assert!(close(buf.get(15, 12), [0.0, 1.0, 0.0, 1.0]));
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index cbbae72b5..5c65d90e2 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -145,6 +145,10 @@ pub struct Effects {
/// Original PSD `lfx2` (`lfxs` on groups) block data (object-effects version + descriptor),
/// written back verbatim on PSD export. Not duplicated in `Layer::psd_blocks`.
pub psd_raw: Option<Arc<Vec<u8>>>,
+ /// Effects reference point (PSD `fxrp`): where linked patterns (Pattern Overlay, pattern
+ /// strokes and glows) anchor their tiling. It moves with the layer. `None` = the layer's
+ /// top-left.
+ pub reference: Option<(f64, f64)>,
}
#[derive(Clone, Debug, PartialEq)]
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs
new file mode 100644
index 000000000..3306f8c4f
--- /dev/null
+++ b/crates/engine/src/artboard_cmds.rs
@@ -0,0 +1,436 @@
+//! Artboards: Layer › New › Artboard (from scratch, a group or the selected layers), artboard
+//! properties (board rect, background, preset), View › Clear Selected Artboard Guides, and
+//! File › Export › Artboards to Files / to PDF.
+//!
+//! An artboard is a top-level group with [`photocraft_doc::Artboard`] set; the compositor clips
+//! its children to the board and paints its background. Moving the group (Move tool,
+//! `layer.translate`) moves the board with its contents. The canvas grows to the right and
+//! bottom to fit new boards, like Photoshop's auto-expanding artboard canvas.
+
+use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent, LayerId, Size};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, color_param, int};
+use crate::file_cmds::{encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file};
+use crate::{EngineError, Result, Session};
+
+/// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages.
+pub const PRESETS: &[(&str, u32, u32)] = &[
+ ("iPhone 14", 390, 844),
+ ("iPhone 14 Pro Max", 430, 932),
+ ("Android 1080p", 360, 640),
+ ("iPad Pro 12.9", 1024, 1366),
+ ("Web 1280", 1280, 800),
+ ("Web 1366", 1366, 768),
+ ("Web 1920", 1920, 1080),
+ ("Instagram Post", 1080, 1080),
+ ("Letter", 612, 792),
+ ("A4", 595, 842),
+];
+
+/// Gap Photoshop leaves between a new artboard and the rightmost existing one.
+const GAP: i32 = 100;
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn has_artboards(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.has_artboards() { Ok(()) } else { Err("the document has no artboards".into()) }
+}
+
+fn export_artboards(s: &Session) -> std::result::Result<(), String> {
+ native_doc(s)?;
+ has_artboards(s)
+}
+
+/// The active layer's artboard (the layer itself or its top-level ancestor).
+fn active_artboard(s: &Session) -> Option<LayerId> {
+ let d = s.active()?;
+ d.doc.artboard_of(d.active_layer?)
+}
+
+fn has_active_artboard(s: &Session) -> std::result::Result<(), String> {
+ active_artboard(s).map(|_| ()).ok_or_else(|| "select an artboard (or a layer inside one)".into())
+}
+
+fn has_plain_group(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ let l = d.doc.layer(id).ok_or("no active layer")?;
+ if !l.is_group() || l.artboard().is_some() {
+ return Err("select a layer group".into());
+ }
+ if !d.doc.layers.iter().any(|t| t.id == id) {
+ return Err("artboards must be top-level: select a group that is not nested".into());
+ }
+ Ok(())
+}
+
+fn has_free_layers(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let sel = d.selected_layers();
+ if sel.is_empty() {
+ return Err("select one or more layers".into());
+ }
+ if sel.iter().any(|id| d.doc.artboard_of(*id).is_some()) {
+ return Err("the selection is already in an artboard".into());
+ }
+ Ok(())
+}
+
+fn preset_size(name: &str) -> Option<(u32, u32)> {
+ PRESETS.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(name)).map(|(_, w, h)| (*w, *h))
+}
+
+fn background_param(p: &Value, cmd: &str) -> Result<Option<ArtboardBackground>> {
+ let custom = p.get("color").map(|_| {
+ let c = color_param(p, "color", [1.0; 4]);
+ ArtboardBackground::Custom(Color::rgba(c[0], c[1], c[2], c[3]))
+ });
+ Ok(match p.get("background").and_then(Value::as_str) {
+ None => custom,
+ Some("white") => Some(ArtboardBackground::White),
+ Some("black") => Some(ArtboardBackground::Black),
+ Some("transparent") => Some(ArtboardBackground::Transparent),
+ Some("custom" | "other") => Some(custom.unwrap_or(ArtboardBackground::White)),
+ Some(o) => return Err(bad(cmd, format!("unknown background `{o}` (white|black|transparent|custom)"))),
+ })
+}
+
+/// `rect` as `[x, y, w, h]` or `x`/`y`/`width`/`height` keys over `base`.
+fn rect_param(p: &Value, base: Rect, cmd: &str) -> Result<Rect> {
+ if let Some(Value::Array(a)) = p.get("rect") {
+ let v: Vec<i32> = a.iter().filter_map(|x| x.as_f64().map(|f| f.round() as i32)).collect();
+ if v.len() != 4 || v[2] <= 0 || v[3] <= 0 {
+ return Err(bad(cmd, "\"rect\" must be [x, y, width, height] with a positive size"));
+ }
+ return Ok(Rect::from_xywh(v[0], v[1], v[2] as u32, v[3] as u32));
+ }
+ let x = int(p, "x").map_or(base.x0, |v| v as i32);
+ let y = int(p, "y").map_or(base.y0, |v| v as i32);
+ let w = int(p, "width").unwrap_or(i64::from(base.width()));
+ let h = int(p, "height").unwrap_or(i64::from(base.height()));
+ if w <= 0 || h <= 0 {
+ return Err(bad(cmd, "the artboard size must be positive"));
+ }
+ Ok(Rect::from_xywh(x, y, w as u32, h as u32))
+}
+
+/// Grow the canvas (right/bottom) so every artboard fits.
+fn fit_canvas(doc: &mut Document) {
+ let (mut w, mut h) = (doc.size.width as i64, doc.size.height as i64);
+ for (_, _, a) in doc.artboards() {
+ w = w.max(i64::from(a.rect.x1));
+ h = h.max(i64::from(a.rect.y1));
+ }
+ doc.size = Size::new(w.clamp(1, 300_000) as u32, h.clamp(1, 300_000) as u32);
+}
+
+fn next_artboard_name(doc: &Document) -> String {
+ let names: Vec<&str> = doc.artboards().into_iter().map(|b| b.1).collect();
+ (1..).map(|n| format!("Artboard {n}")).find(|n| !names.contains(&n.as_str())).expect("infinite")
+}
+
+fn set_artboard(l: &mut Layer, a: Artboard) {
+ if let LayerContent::Group(g) = &mut l.content {
+ g.artboard = Some(a);
+ g.expanded = true;
+ }
+ // Artboards composite like pass-through groups.
+ l.clipped = false;
+}
+
+fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layer.new.artboard";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let preset = p.get("preset").and_then(Value::as_str).unwrap_or("").to_string();
+ let (pw, ph) = match preset.as_str() {
+ "" => (d.doc.size.width, d.doc.size.height),
+ name => preset_size(name).ok_or_else(|| bad(cmd, format!("unknown preset `{name}`")))?,
+ };
+ // Default placement: right of the rightmost artboard, else the canvas origin.
+ let right = d.doc.artboards().iter().map(|b| b.2.rect.x1).max();
+ let top = d.doc.artboards().iter().map(|b| b.2.rect.y0).min().unwrap_or(0);
+ let base = match right {
+ Some(x) => Rect::from_xywh(x + GAP, top, pw, ph),
+ None => Rect::from_xywh(0, 0, pw, ph),
+ };
+ // A preset decides the size (dialogs send the canvas size alongside it).
+ let rect = if preset.is_empty() || p.get("rect").is_some() { rect_param(p, base, cmd)? } else { rect_param(&json!({"x": p.get("x"), "y": p.get("y")}), base, cmd)? };
+ let background = background_param(p, cmd)?.unwrap_or_default();
+ let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string);
+ let id = s.edit("New Artboard", |doc, active| {
+ let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), vec![]);
+ set_artboard(&mut g, Artboard { rect, background, preset });
+ let id = doc.insert_above(None, g);
+ fit_canvas(doc);
+ *active = Some(id);
+ Ok(id)
+ })?;
+ crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?;
+ Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
+}
+
+fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = p.get("layer").and_then(Value::as_u64).map(LayerId).or(d.active_layer).ok_or(EngineError::Other("no active layer".into()))?;
+ let canvas = d.doc.bounds();
+ let background = background_param(p, "layer.new.artboardFromGroup")?.unwrap_or_default();
+ let rect = s.edit("Artboard from Group", |doc, active| {
+ if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) {
+ return Err(EngineError::Other("artboards are made from a top-level layer group".into()));
+ }
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas);
+ set_artboard(l, Artboard { rect, background, preset: String::new() });
+ fit_canvas(doc);
+ *active = Some(id);
+ Ok(rect)
+ })?;
+ Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
+}
+
+fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
+ let sel = crate::layer_multi_cmds::selected(s);
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let canvas = d.doc.bounds();
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let background = background_param(p, "layer.new.artboardFromLayers")?.unwrap_or_default();
+ let (gid, rect) = s.edit("Artboard from Layers", |doc, active| {
+ let ids = crate::layer_multi_cmds::top_level(doc, &sel);
+ if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) {
+ return Err(EngineError::Other("select layers that are not in an artboard".into()));
+ }
+ let mut children = Vec::with_capacity(ids.len());
+ for id in &ids {
+ children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
+ }
+ let rect = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas);
+ let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children);
+ set_artboard(&mut g, Artboard { rect, background, preset: String::new() });
+ let gid = doc.insert_above(None, g);
+ fit_canvas(doc);
+ *active = Some(gid);
+ Ok((gid, rect))
+ })?;
+ crate::layer_multi_cmds::set_selection(s, vec![gid], Some(gid), Some(gid))?;
+ Ok(json!({"layer": gid.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
+}
+
+/// Properties panel / Artboard tool: board position and size, background, preset, name.
+/// Changing X/Y moves the board with its contents; changing W/H resizes it from the top left.
+fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layer.artboard.set";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = match p.get("layer").and_then(Value::as_u64) {
+ Some(v) => LayerId(v),
+ None => active_artboard(s).ok_or_else(|| bad(cmd, "no artboard selected"))?,
+ };
+ let old = d.doc.layer(id).and_then(Layer::artboard).cloned().ok_or_else(|| bad(cmd, "the layer is not an artboard"))?;
+ let preset = p.get("preset").and_then(Value::as_str).map(str::to_string);
+ let mut base = old.rect;
+ if let Some(name) = preset.as_deref().filter(|n| !n.is_empty()) {
+ let (w, h) = preset_size(name).ok_or_else(|| bad(cmd, format!("unknown preset `{name}`")))?;
+ base = Rect::from_xywh(base.x0, base.y0, w, h);
+ }
+ let rect = rect_param(p, base, cmd)?;
+ let background = background_param(p, cmd)?;
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let move_contents = p.get("moveContents").and_then(Value::as_bool).unwrap_or(true);
+ s.edit("Edit Artboard", |doc, _| {
+ let (dx, dy) = (rect.x0 - old.rect.x0, rect.y0 - old.rect.y0);
+ if move_contents && (dx, dy) != (0, 0) {
+ let snapshot = doc.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ crate::commands::translate_layer(&snapshot, l, dx, dy);
+ crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(dx), f64::from(dy));
+ }
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if let Some(n) = name {
+ l.name = n;
+ }
+ let a = l.artboard_mut().ok_or(EngineError::NoLayer(id))?;
+ a.rect = rect;
+ if let Some(b) = background {
+ a.background = b;
+ }
+ match preset {
+ Some(pr) => a.preset = pr,
+ // A hand-edited size no longer matches the preset.
+ None if rect.width() != old.rect.width() || rect.height() != old.rect.height() => a.preset.clear(),
+ None => {}
+ }
+ fit_canvas(doc);
+ Ok(())
+ })?;
+ Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
+}
+
+fn clear_artboard_guides(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = active_artboard(s).ok_or(EngineError::Other("no artboard selected".into()))?;
+ let r = d.doc.layer(id).and_then(Layer::artboard).map(|a| a.rect).ok_or(EngineError::NoLayer(id))?;
+ let inside_x = |x: &f32| f64::from(*x) > f64::from(r.x0) && f64::from(*x) < f64::from(r.x1);
+ let inside_y = |y: &f32| f64::from(*y) > f64::from(r.y0) && f64::from(*y) < f64::from(r.y1);
+ let n = d.doc.guides.vertical.iter().filter(|x| inside_x(x)).count() + d.doc.guides.horizontal.iter().filter(|y| inside_y(y)).count();
+ if n == 0 {
+ return Ok(json!({"cleared": 0}));
+ }
+ s.edit("Clear Selected Artboard Guides", |doc, _| {
+ doc.guides.vertical.retain(|x| !inside_x(x));
+ doc.guides.horizontal.retain(|y| !inside_y(y));
+ Ok(())
+ })?;
+ Ok(json!({"cleared": n}))
+}
+
+/// One artboard as its own document: the board's size, its group moved to the origin.
+pub fn artboard_document(doc: &Document, id: LayerId) -> Option<Document> {
+ let l = doc.layer(id)?;
+ let r = l.artboard()?.rect;
+ let mut group = l.clone();
+ group.visible = true;
+ crate::commands::translate_layer(doc, &mut group, -r.x0, -r.y0);
+ crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(-r.x0), f64::from(-r.y0));
+ let mut one = doc.clone();
+ one.name = l.name.clone();
+ one.size = Size::new(r.width(), r.height());
+ one.layers = vec![group];
+ one.channels.clear();
+ one.selection = None;
+ one.quick_mask = None;
+ one.layer_comps.clear();
+ one.last_applied_comp = None;
+ one.last_document_state = None;
+ let shift = |v: &[f32], o: i32, len: u32| v.iter().map(|g| g - o as f32).filter(|g| *g > 0.0 && *g < len as f32).collect::<Vec<_>>();
+ one.guides.vertical = shift(&doc.guides.vertical, r.x0, r.width());
+ one.guides.horizontal = shift(&doc.guides.horizontal, r.y0, r.height());
+ Some(one)
+}
+
+/// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first.
+fn chosen_artboards(doc: &Document, p: &Value) -> Vec<LayerId> {
+ let all: Vec<LayerId> = doc.artboards().into_iter().rev().map(|b| b.0).collect();
+ match p.get("artboards") {
+ Some(Value::Array(a)) => {
+ let want: Vec<u64> = a.iter().filter_map(Value::as_u64).collect();
+ all.into_iter().filter(|id| want.contains(&id.0)).collect()
+ }
+ _ => all,
+ }
+}
+
+/// File › Export › Artboards to Files: `<prefix>_<artboard name>.<format>` per board.
+fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.artboardsToFiles";
+ let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
+ let doc = d.doc.clone();
+ let mut files = Vec::new();
+ for id in chosen_artboards(&doc, p) {
+ let Some(one) = artboard_document(&doc, id) else { continue };
+ let name = if prefix.is_empty() { sanitize(&one.name) } else { format!("{}_{}", sanitize(&prefix), sanitize(&one.name)) };
+ let path = join(&dir, &format!("{name}.{format}"));
+ save_doc(&one, &path, f64_param(p, "quality"))?;
+ files.push(path);
+ }
+ if files.is_empty() {
+ return Err(bad(cmd, "no matching artboards"));
+ }
+ Ok(json!({"files": files}))
+}
+
+/// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes).
+/// Pages are sized so the image prints at its resolution.
+pub fn raster_pdf(pages: &[(u32, u32, f32, Vec<u8>)]) -> Vec<u8> {
+ let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
+ let mut offsets: Vec<usize> = Vec::new();
+ let mut obj = |out: &mut Vec<u8>, body: &[u8]| {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", offsets.len()).as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"\nendobj\n");
+ };
+ // Objects: 1 catalog, 2 page tree, then per page: page, contents, image.
+ let kids: Vec<String> = (0..pages.len()).map(|i| format!("{} 0 R", 3 + i * 3)).collect();
+ obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>");
+ obj(&mut out, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).as_bytes());
+ for (i, (w, h, dpi, jpeg)) in pages.iter().enumerate() {
+ let k = 72.0 / f64::from(dpi.max(1.0));
+ let (pw, ph) = (f64::from(*w) * k, f64::from(*h) * k);
+ let (contents, image) = (4 + i * 3, 5 + i * 3);
+ obj(&mut out, format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.3} {ph:.3}] /Resources << /XObject << /Im0 {image} 0 R >> >> /Contents {contents} 0 R >>").as_bytes());
+ let stream = format!("q {pw:.3} 0 0 {ph:.3} 0 0 cm /Im0 Do Q");
+ obj(&mut out, format!("<< /Length {} >>\nstream\n{stream}\nendstream", stream.len()).as_bytes());
+ let mut img = format!("<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {} >>\nstream\n", jpeg.len()).into_bytes();
+ img.extend_from_slice(jpeg);
+ img.extend_from_slice(b"\nendstream");
+ obj(&mut out, &img);
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
+ for o in &offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
+ out
+}
+
+/// File › Export › Artboards to PDF: one page per board (flattened over white, JPEG-encoded).
+fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.artboardsToPdf";
+ let path = str_param(p, "path", cmd)?.to_string();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let quality = f64_param(p, "quality").or(Some(10.0));
+ let mut pages = Vec::new();
+ for id in chosen_artboards(&doc, p) {
+ let Some(one) = artboard_document(&doc, id) else { continue };
+ let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]);
+ let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
+ let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8);
+ let mut surf = Surface::new(fmt);
+ let vals: Vec<f32> = buf.px.iter().flat_map(|px| photocraft_raster::from_rgba(&fmt, *px)).collect();
+ surf.write_region(one.bounds(), &vals);
+ flat.layers.push(Layer::new("Background", LayerContent::Raster(surf)));
+ let (jpeg, _) = encode(&flat, "page.jpg", quality)?;
+ pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg));
+ }
+ if pages.is_empty() {
+ return Err(bad(cmd, "no matching artboards"));
+ }
+ write_file(&path, &raster_pdf(&pages))?;
+ Ok(json!({"path": path, "pages": pages.len()}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ vec![
+ spec!("layer.new.artboard", "Artboard…", &["Layer", "New"], r##"{"rect":[x,y,w,h]? | "x","y","width","height"? (default: canvas size, right of the last board),"preset":"iPhone 14|Web 1920|A4|…"?,"name":str?,"background":"white|black|transparent|custom"="white","color":[r,g,b]|"#rrggbb"? (custom)} → {layer, rect}"##, has_doc, new_artboard),
+ spec!("layer.new.artboardFromGroup", "Artboard from Group…", &["Layer", "New"], r##"{"layer":id? (a top-level group; default active),"background":…?} → {layer, rect}"##, has_plain_group, artboard_from_group),
+ spec!("layer.new.artboardFromLayers", "Artboard from Layers…", &["Layer", "New"], r##"{"name":str?,"background":…?} (the selected layers) → {layer, rect}"##, has_free_layers, artboard_from_layers),
+ spec!("layer.artboard.set", "Edit Artboard", &[], r##"{"layer":id? (default: the active artboard),"x","y","width","height"?|"rect":[x,y,w,h]?,"preset":str?,"background":"white|black|transparent|custom"?,"color":…?,"name":str?,"moveContents":bool=true} → {layer, rect}"##, has_active_artboard, set_props),
+ spec!("view.clearSelectedArtboardGuides", "Clear Selected Artboard Guides", &["View"], "{} (guides inside the active artboard)", has_active_artboard, |s, _| clear_artboard_guides(s)),
+ spec!("file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, export_artboards, artboards_to_files),
+ spec!("file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, export_artboards, artboards_to_pdf),
+ ]
+}
+
+#[cfg(test)]
+#[path = "artboard_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rs
new file mode 100644
index 000000000..c38f79b7f
--- /dev/null
+++ b/crates/engine/src/artboard_cmds/tests.rs
@@ -0,0 +1,168 @@
+use super::*;
+use photocraft_geom::Rect;
+
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap();
+ s
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn add_square(s: &mut Session, r: Rect, rgba: [f32; 4]) -> LayerId {
+ s.edit("sq", |doc, active| {
+ let fmt = doc.pixel_format();
+ let mut l = Layer::raster(doc.next_layer_name("Layer"), fmt);
+ l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, rgba));
+ let id = doc.insert_above(None, l);
+ *active = Some(id);
+ Ok(id)
+ })
+ .unwrap()
+}
+
+#[test]
+fn new_artboards_place_and_grow_canvas() {
+ let mut s = session(8);
+ let r = s.execute("layer.new.artboard", json!({"rect": [0, 0, 100, 80]})).unwrap();
+ let a1 = LayerId(r["layer"].as_u64().unwrap());
+ assert_eq!(doc(&s).layer(a1).unwrap().name, "Artboard 1");
+ // Default: canvas-sized, right of the last board with a gap; the canvas grows.
+ let r = s.execute("layer.new.artboard", json!({"background": "black"})).unwrap();
+ assert_eq!(r["rect"], json!([200, 0, 100, 80]));
+ assert_eq!(doc(&s).size.width, 300);
+ let r = s.execute("layer.new.artboard", json!({"preset": "iPhone 14", "x": 0, "y": 100})).unwrap();
+ assert_eq!(r["rect"], json!([0, 100, 390, 844]));
+ assert_eq!(doc(&s).artboards().len(), 3);
+ assert!(s.execute("layer.new.artboard", json!({"preset": "Nope"})).is_err());
+ assert!(s.execute("layer.new.artboard", json!({"rect": [0, 0, 0, 5]})).is_err());
+ assert!(s.execute("layer.new.artboard", json!({"background": "plaid"})).is_err());
+ // Undo removes the board (and the canvas growth).
+ s.undo();
+ assert_eq!(doc(&s).artboards().len(), 2);
+ assert_eq!(doc(&s).size.height, 80);
+}
+
+#[test]
+fn from_layers_and_group_then_compose_clips() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let red = add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
+ let r = s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap();
+ assert_eq!(r["rect"], json!([10, 10, 20, 20]));
+ let gid = LayerId(r["layer"].as_u64().unwrap());
+ assert_eq!(doc(&s).artboard_of(red), Some(gid));
+ // Grow the board; the white background shows around the square, nothing outside it.
+ s.execute("layer.artboard.set", json!({"width": 40, "height": 40})).unwrap();
+ let px = |s: &Session, x, y| photocraft_compose::render(doc(s), Rect::new(x, y, x + 1, y + 1)).px[0];
+ assert!(px(&s, 40, 40)[0] > 0.99 && px(&s, 40, 40)[1] > 0.99, "{depth}");
+ assert!(px(&s, 15, 15)[1] < 0.01);
+ // Moving the board moves its contents.
+ s.execute("layer.artboard.set", json!({"x": 50, "y": 20})).unwrap();
+ let a = doc(&s).layer(gid).unwrap().artboard().unwrap().clone();
+ assert_eq!(a.rect, Rect::from_xywh(50, 20, 40, 40));
+ let surf = doc(&s).layer(red).unwrap().surface().unwrap();
+ assert_eq!(surf.content_bounds(), Rect::new(50, 20, 70, 40));
+ // layer.translate on the board does the same.
+ s.execute("layer.translate", json!({"layer": gid.0, "dx": -5, "dy": 0})).unwrap();
+ assert_eq!(doc(&s).layer(gid).unwrap().artboard().unwrap().rect.x0, 45);
+ assert_eq!(doc(&s).layer(red).unwrap().surface().unwrap().content_bounds().x0, 45);
+ // Background and name.
+ s.execute("layer.artboard.set", json!({"background": "custom", "color": "#00ff00", "name": "Green"})).unwrap();
+ let l = doc(&s).layer(gid).unwrap();
+ assert_eq!(l.name, "Green");
+ assert!(matches!(l.artboard().unwrap().background, ArtboardBackground::Custom(_)));
+ // A plain group becomes an artboard sized to its contents.
+ add_square(&mut s, Rect::new(0, 60, 8, 70), [0.0, 0.0, 1.0, 1.0]);
+ let g = s.execute("layer.groupLayers", json!({})).unwrap();
+ let gid2 = g["layer"].as_u64().unwrap();
+ assert!(s.is_enabled("layer.new.artboardFromGroup"));
+ let r = s.execute("layer.new.artboardFromGroup", json!({"layer": gid2})).unwrap();
+ assert_eq!(r["rect"], json!([0, 60, 8, 10]));
+ assert!(!s.is_enabled("layer.new.artboardFromGroup"));
+ }
+}
+
+#[test]
+fn clear_artboard_guides_only_inside() {
+ let mut s = session(8);
+ s.execute("layer.new.artboard", json!({"rect": [0, 0, 50, 50]})).unwrap();
+ s.edit("guides", |d, _| {
+ d.guides.vertical = vec![10.0, 70.0];
+ d.guides.horizontal = vec![20.0];
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(s.execute("view.clearSelectedArtboardGuides", json!({})).unwrap()["cleared"], 2);
+ assert_eq!(doc(&s).guides.vertical, vec![70.0]);
+ assert!(doc(&s).guides.horizontal.is_empty());
+ // Clear Canvas Guides leaves the artboard's guides.
+ s.edit("guides", |d, _| {
+ d.guides.vertical = vec![10.0, 70.0];
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(s.execute("view.clearCanvasGuides", json!({})).unwrap()["cleared"], 1);
+ assert_eq!(doc(&s).guides.vertical, vec![10.0]);
+}
+
+#[test]
+fn export_to_files_and_pdf() {
+ let mut s = session(16);
+ add_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]);
+ s.execute("layer.new.artboardFromLayers", json!({"name": "Red Board"})).unwrap();
+ s.execute("layer.new.artboard", json!({"rect": [20, 0, 30, 15], "name": "Empty/One", "background": "transparent"})).unwrap();
+ let dir = std::env::temp_dir().join(format!("photocraft-artboards-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let d = dir.to_string_lossy().into_owned();
+ let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "prefix": "site"})).unwrap();
+ let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
+ assert_eq!(files.len(), 2);
+ assert!(files[0].ends_with("site_Empty_One.png"), "{files:?}");
+ assert!(files[1].ends_with("site_Red Board.png"), "{files:?}");
+ let img = photocraft_io::import("x.png", &std::fs::read(&files[1]).unwrap()).unwrap().document;
+ assert_eq!((img.size.width, img.size.height), (10, 10));
+ let img2 = photocraft_io::import("x.png", &std::fs::read(&files[0]).unwrap()).unwrap().document;
+ assert_eq!((img2.size.width, img2.size.height), (30, 15));
+ // Layered PSD keeps the board, moved to the origin.
+ let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "prefix": "", "format": "psd", "artboards": [doc(&s).artboards()[0].0.0]})).unwrap();
+ let psd = photocraft_io::import("x.psd", &std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap().document;
+ assert_eq!(psd.artboards()[0].2.rect, Rect::new(0, 0, 10, 10));
+ let pdf = join(&d, "boards.pdf");
+ let r = s.execute("file.export.artboardsToPdf", json!({"path": pdf})).unwrap();
+ assert_eq!(r["pages"], 2);
+ let bytes = std::fs::read(&pdf).unwrap();
+ assert!(bytes.starts_with(b"%PDF-1.4"));
+ assert!(bytes.ends_with(b"%%EOF\n"));
+ let text = String::from_utf8_lossy(&bytes);
+ assert_eq!(text.matches("/Type /Page ").count(), 2);
+ assert_eq!(text.matches("/DCTDecode").count(), 2);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn raster_pdf_xref_offsets_point_at_objects() {
+ let pdf = raster_pdf(&[(2, 3, 72.0, vec![0xff, 0xd8, 0xff, 0xd9])]);
+ let text = String::from_utf8_lossy(&pdf).into_owned();
+ let xref = text.rfind("xref\n").unwrap();
+ let offsets: Vec<usize> = text[xref..].lines().skip(3).take(5).map(|l| l[..10].parse().unwrap()).collect();
+ for (i, o) in offsets.iter().enumerate() {
+ assert!(text[*o..].starts_with(&format!("{} 0 obj", i + 1)));
+ }
+ assert!(text.contains("/MediaBox [0 0 2.000 3.000]"));
+}
+
+#[test]
+fn disabled_without_artboards() {
+ let mut s = session(8);
+ for id in ["layer.artboard.set", "view.clearSelectedArtboardGuides", "file.export.artboardsToFiles", "file.export.artboardsToPdf", "layer.new.artboardFromGroup"] {
+ assert!(!s.is_enabled(id), "{id}");
+ }
+ assert!(s.is_enabled("layer.new.artboard"));
+ assert!(s.is_enabled("layer.new.artboardFromLayers"));
+ let _ = s.execute("layer.new.artboard", json!({}));
+ assert!(!s.is_enabled("layer.new.artboardFromLayers"));
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 74f4a97a6..a1116a569 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -780,6 +780,9 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::mode_cmds::specs());
v.extend(crate::pattern_cmds::specs());
v.extend(crate::warp_cmds::specs());
+ v.extend(crate::comps_cmds::specs());
+ v.extend(crate::artboard_cmds::specs());
+ v.extend(crate::distort_cmds::specs());
v
}
@@ -861,6 +864,10 @@ fn combine(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f32) -> f32) ->
/// `vector_cmds::translate_vectors`).
pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {
use photocraft_algo::resample::translate_surface;
+ // Linked patterns in the layer's effects move with it.
+ if let Some(r) = &mut l.effects.reference {
+ *r = (r.0 + f64::from(dx), r.1 + f64::from(dy));
+ }
if let Some(m) = &mut l.mask
&& m.linked
{
@@ -873,6 +880,10 @@ pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {
crate::type_cmds::refresh(doc, t);
}
LayerContent::Group(g) => {
+ // Moving an artboard moves the board with its contents.
+ if let Some(a) = &mut g.artboard {
+ a.rect = a.rect.translate(dx, dy);
+ }
for c in &mut g.children {
translate_layer(doc, c, dx, dy);
}
diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rs
new file mode 100644
index 000000000..81026aaaa
--- /dev/null
+++ b/crates/engine/src/comps_cmds.rs
@@ -0,0 +1,396 @@
+//! Window › Layer Comps: capture, apply and manage layer comps (`layerComp.*`), plus
+//! File › Export › Layer Comps to Files.
+//!
+//! A comp records every layer's visibility, position and appearance; its three options choose
+//! which of them applying restores (see [`photocraft_doc::comps`]). Comps live in the document,
+//! so every change here is one undoable history step. Commands that act on "the" comp take
+//! `"comp": id | name` and default to the comp applied (or created) last.
+
+use photocraft_doc::comps::{capture_states, layer_position, next_comp_id};
+use photocraft_doc::{CompLayerState, Document, LayerComp, LayerId};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::file_cmds::{f64_param, join, native_doc, sanitize, save_doc, stem, str_param};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn has_comps(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.layer_comps.is_empty() { Err("the document has no layer comps".into()) } else { Ok(()) }
+}
+
+fn has_last_state(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.last_document_state.is_some() { Ok(()) } else { Err("no comp has been applied over the document state".into()) }
+}
+
+fn export_comps(s: &Session) -> std::result::Result<(), String> {
+ native_doc(s)?;
+ has_comps(s)
+}
+
+/// The comp a command acts on: `"comp"` as an id or a name, else the last applied comp.
+fn comp_param(doc: &Document, p: &Value, cmd: &str) -> Result<u32> {
+ match p.get("comp") {
+ Some(Value::Number(n)) => {
+ let id = n.as_u64().ok_or_else(|| bad(cmd, "\"comp\" must be a comp id or name"))? as u32;
+ doc.comp(id).map(|c| c.id).ok_or_else(|| bad(cmd, format!("no layer comp with id {id}")))
+ }
+ Some(Value::String(name)) => doc.layer_comps.iter().find(|c| c.name == *name).map(|c| c.id).ok_or_else(|| bad(cmd, format!("no layer comp named \"{name}\""))),
+ Some(_) => Err(bad(cmd, "\"comp\" must be a comp id or name")),
+ None => doc
+ .last_applied_comp
+ .filter(|id| doc.comp(*id).is_some())
+ .or_else(|| doc.layer_comps.first().map(|c| c.id))
+ .ok_or_else(|| bad(cmd, "the document has no layer comps")),
+ }
+}
+
+fn index_of(doc: &Document, id: u32) -> usize {
+ doc.layer_comps.iter().position(|c| c.id == id).unwrap_or(0)
+}
+
+fn flag(p: &Value, key: &str, default: bool) -> bool {
+ p.get(key).and_then(Value::as_bool).unwrap_or(default)
+}
+
+/// Restores `comp`'s recorded state (only what its options select; `all` forces everything).
+/// Layers deleted since the capture are skipped. Position-locked layers still move, as in
+/// Photoshop, because the comp is not a user drag.
+pub fn apply_comp(doc: &mut Document, comp: &LayerComp, all: bool) {
+ let (vis, pos, app) = if all { (true, true, true) } else { (comp.apply_visibility, comp.apply_position, comp.apply_appearance) };
+ // Walk order (parents before children): a moved artboard carries its children, which are
+ // then placed absolutely, so the result does not depend on how far the parent moved.
+ let order: Vec<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ for id in order {
+ let Some(st) = comp.state(id) else { continue };
+ if pos
+ && let Some((x, y)) = st.position
+ && let Some((cx, cy)) = doc.layer(id).and_then(layer_position)
+ && (x, y) != (cx, cy)
+ {
+ let snapshot = doc.clone();
+ if let Some(l) = doc.layer_mut(id) {
+ crate::commands::translate_layer(&snapshot, l, x - cx, y - cy);
+ crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(x - cx), f64::from(y - cy));
+ }
+ }
+ let Some(l) = doc.layer_mut(id) else { continue };
+ if vis && let Some(v) = st.visible {
+ l.visible = v;
+ }
+ if app && let Some(a) = &st.appearance {
+ l.blend = a.blend;
+ l.opacity = a.opacity;
+ l.fill_opacity = a.fill_opacity;
+ l.effects = a.effects.clone();
+ }
+ }
+}
+
+fn new_comp(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
+ let names: Vec<&str> = d.doc.layer_comps.iter().map(|c| c.name.as_str()).collect();
+ (1..).map(|n| format!("Layer Comp {n}")).find(|n| !names.contains(&n.as_str())).expect("infinite")
+ });
+ let comment = p.get("comment").and_then(Value::as_str).unwrap_or_default().to_string();
+ let (v, pos, a) = (flag(p, "visibility", true), flag(p, "position", true), flag(p, "appearance", true));
+ let id = s.edit("New Layer Comp", |doc, _| {
+ let id = next_comp_id(doc);
+ let comp = LayerComp { id, name, comment, apply_visibility: v, apply_position: pos, apply_appearance: a, states: capture_states(doc) };
+ doc.layer_comps.push(comp);
+ doc.last_applied_comp = Some(id);
+ Ok(id)
+ })?;
+ Ok(json!({"comp": id}))
+}
+
+fn update_comp(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layerComp.update";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let what = p.get("what").and_then(Value::as_str).unwrap_or("all");
+ if !matches!(what, "all" | "visibility" | "position" | "appearance") {
+ return Err(bad(cmd, format!("unknown \"what\" `{what}` (all|visibility|position|appearance)")));
+ }
+ let every = p.get("comp").and_then(Value::as_str) == Some("*");
+ let ids: Vec<u32> = if every { d.doc.layer_comps.iter().map(|c| c.id).collect() } else { vec![comp_param(&d.doc, p, cmd)?] };
+ let label = match what {
+ "visibility" => "Update Layer Comp Visibility",
+ "position" => "Update Layer Comp Position",
+ "appearance" => "Update Layer Comp Appearance",
+ _ => "Update Layer Comp",
+ };
+ s.edit(label, |doc, _| {
+ let now = capture_states(doc);
+ for id in &ids {
+ let Some(c) = doc.layer_comps.iter_mut().find(|c| c.id == *id) else { continue };
+ if what == "all" {
+ c.states = now.clone();
+ continue;
+ }
+ // One property: refresh it on every live layer, keep the others as recorded.
+ let mut states: Vec<CompLayerState> = Vec::with_capacity(now.len());
+ for n in &now {
+ let mut st = c.state(n.layer).cloned().unwrap_or(CompLayerState { layer: n.layer, visible: None, position: None, appearance: None });
+ match what {
+ "visibility" => st.visible = n.visible,
+ "position" => st.position = n.position,
+ _ => st.appearance = n.appearance.clone(),
+ }
+ states.push(st);
+ }
+ c.states = states;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"updated": ids}))
+}
+
+fn apply(s: &mut Session, id: u32, label: &str) -> Result<Value> {
+ s.edit(label, |doc, _| {
+ let comp = doc.comp(id).cloned().ok_or_else(|| EngineError::Other(format!("no layer comp with id {id}")))?;
+ // Applying over the document's own state first remembers it as the Last Document State.
+ if doc.last_applied_comp.is_none_or(|c| doc.comp(c).is_none()) {
+ doc.last_document_state = Some(LayerComp {
+ id: 0,
+ name: "Last Document State".into(),
+ comment: String::new(),
+ apply_visibility: true,
+ apply_position: true,
+ apply_appearance: true,
+ states: capture_states(doc),
+ });
+ }
+ apply_comp(doc, &comp, false);
+ doc.last_applied_comp = Some(id);
+ Ok(())
+ })?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let missing = d.doc.comp(id).map(|c| c.missing_layers(&d.doc).len()).unwrap_or(0);
+ Ok(json!({"comp": id, "missingLayers": missing}))
+}
+
+fn apply_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, "layerComp.apply")?;
+ apply(s, id, "Apply Layer Comp")
+}
+
+fn step(s: &mut Session, delta: i64) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let n = d.doc.layer_comps.len() as i64;
+ let cur = d.doc.last_applied_comp.and_then(|id| d.doc.layer_comps.iter().position(|c| c.id == id));
+ let next = match cur {
+ Some(i) => (i as i64 + delta).rem_euclid(n),
+ None if delta > 0 => 0,
+ None => n - 1,
+ };
+ let id = d.doc.layer_comps[next as usize].id;
+ apply(s, id, "Apply Layer Comp")
+}
+
+fn delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, "layerComp.delete")?;
+ s.edit("Delete Layer Comp", |doc, _| {
+ doc.layer_comps.retain(|c| c.id != id);
+ if doc.last_applied_comp == Some(id) {
+ doc.last_applied_comp = None;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"deleted": id}))
+}
+
+fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, "layerComp.duplicate")?;
+ let new = s.edit("Duplicate Layer Comp", |doc, _| {
+ let i = index_of(doc, id);
+ let mut c = doc.layer_comps[i].clone();
+ c.id = next_comp_id(doc);
+ c.name = format!("{} copy", c.name);
+ let nid = c.id;
+ doc.layer_comps.insert(i + 1, c);
+ Ok(nid)
+ })?;
+ Ok(json!({"comp": new}))
+}
+
+fn rename(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layerComp.rename";
+ let name = str_param(p, "name", cmd)?.to_string();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, cmd)?;
+ s.edit("Rename Layer Comp", |doc, _| {
+ let i = index_of(doc, id);
+ doc.layer_comps[i].name = name;
+ Ok(())
+ })?;
+ Ok(json!({"comp": id}))
+}
+
+fn set_comment(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layerComp.setComment";
+ let comment = p.get("comment").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing \"comment\""))?.to_string();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, cmd)?;
+ s.edit("Layer Comp Options", |doc, _| {
+ let i = index_of(doc, id);
+ doc.layer_comps[i].comment = comment;
+ Ok(())
+ })?;
+ Ok(json!({"comp": id}))
+}
+
+fn set_options(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layerComp.setOptions";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id = comp_param(&d.doc, p, cmd)?;
+ let get = |k: &str| p.get(k).and_then(Value::as_bool);
+ let (v, pos, a, name) = (get("visibility"), get("position"), get("appearance"), p.get("name").and_then(Value::as_str).map(str::to_string));
+ if v.is_none() && pos.is_none() && a.is_none() && name.is_none() && p.get("comment").is_none() {
+ return Err(bad(cmd, "give \"visibility\", \"position\", \"appearance\", \"name\" or \"comment\""));
+ }
+ let comment = p.get("comment").and_then(Value::as_str).map(str::to_string);
+ s.edit("Layer Comp Options", |doc, _| {
+ let i = index_of(doc, id);
+ let c = &mut doc.layer_comps[i];
+ if let Some(v) = v {
+ c.apply_visibility = v;
+ }
+ if let Some(v) = pos {
+ c.apply_position = v;
+ }
+ if let Some(v) = a {
+ c.apply_appearance = v;
+ }
+ if let Some(n) = name {
+ c.name = n;
+ }
+ if let Some(n) = comment {
+ c.comment = n;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"comp": id}))
+}
+
+fn restore_last(s: &mut Session) -> Result<Value> {
+ s.edit("Restore Last Document State", |doc, _| {
+ let last = doc.last_document_state.clone().ok_or_else(|| EngineError::Other("no Last Document State".into()))?;
+ apply_comp(doc, &last, true);
+ doc.last_applied_comp = None;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+/// Comps that refer to deleted layers (Photoshop's warning triangle). `"clear": true` drops
+/// those stale states (Clear Layer Comp Warning) as one history step.
+fn update_warnings(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let warnings: Vec<Value> = d
+ .doc
+ .layer_comps
+ .iter()
+ .filter_map(|c| {
+ let missing = c.missing_layers(&d.doc);
+ (!missing.is_empty()).then(|| json!({"comp": c.id, "name": c.name, "missingLayers": missing.iter().map(|l| l.0).collect::<Vec<_>>()}))
+ })
+ .collect();
+ let n = warnings.len();
+ if flag(p, "clear", false) && n > 0 {
+ s.edit("Clear Layer Comp Warnings", |doc, _| {
+ let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ for c in &mut doc.layer_comps {
+ c.states.retain(|st| live.contains(&st.layer));
+ }
+ Ok(())
+ })?;
+ }
+ Ok(json!({"warnings": warnings, "count": n}))
+}
+
+fn list(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let comps: Vec<Value> = d
+ .doc
+ .layer_comps
+ .iter()
+ .map(|c| {
+ json!({
+ "id": c.id, "name": c.name, "comment": c.comment,
+ "visibility": c.apply_visibility, "position": c.apply_position, "appearance": c.apply_appearance,
+ "layers": c.states.len(), "missingLayers": c.missing_layers(&d.doc).len(),
+ })
+ })
+ .collect();
+ Ok(json!({"comps": comps, "lastApplied": d.doc.last_applied_comp, "hasLastDocumentState": d.doc.last_document_state.is_some()}))
+}
+
+/// File › Export › Layer Comps to Files: one file per comp, named
+/// `<prefix>_<index>_<comp name>.<format>`.
+fn comps_to_files(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.layerCompsToFiles";
+ let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
+ let doc = d.doc.clone();
+ let chosen: Vec<u32> = match p.get("comps") {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_u64).map(|v| v as u32).collect(),
+ _ if flag(p, "selectedOnly", false) => vec![comp_param(&doc, &json!({}), cmd)?],
+ _ => doc.layer_comps.iter().map(|c| c.id).collect(),
+ };
+ let mut files = Vec::new();
+ for (i, c) in doc.layer_comps.iter().enumerate().filter(|(_, c)| chosen.contains(&c.id)) {
+ let mut one = (*doc).clone();
+ apply_comp(&mut one, c, false);
+ one.last_applied_comp = Some(c.id);
+ let path = join(&dir, &format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&c.name)));
+ save_doc(&one, &path, f64_param(p, "quality"))?;
+ files.push(path);
+ }
+ if files.is_empty() {
+ return Err(bad(cmd, "no matching layer comps"));
+ }
+ Ok(json!({"files": files}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ vec![
+ spec!("layerComp.new", "New Layer Comp…", &[], r##"{"name":str="Layer Comp N","comment":str="","visibility":bool=true,"position":bool=true,"appearance":bool=true} → {comp}"##, has_doc, new_comp),
+ spec!("layerComp.update", "Update Layer Comp", &[], r##"{"comp":id|name|"*"? (default: last applied; "*" = all),"what":"all|visibility|position|appearance"="all"}"##, has_comps, update_comp),
+ spec!("layerComp.apply", "Apply Layer Comp", &[], r##"{"comp":id|name? (default: last applied)} → {comp, missingLayers}"##, has_comps, apply_cmd),
+ spec!("layerComp.previous", "Apply Previous Layer Comp", &[], "{}", has_comps, |s, _| step(s, -1)),
+ spec!("layerComp.next", "Apply Next Layer Comp", &[], "{}", has_comps, |s, _| step(s, 1)),
+ spec!("layerComp.delete", "Delete Layer Comp", &[], r##"{"comp":id|name?}"##, has_comps, delete),
+ spec!("layerComp.duplicate", "Duplicate Layer Comp", &[], r##"{"comp":id|name?} → {comp}"##, has_comps, duplicate),
+ spec!("layerComp.rename", "Rename Layer Comp", &[], r##"{"comp":id|name?,"name":str}"##, has_comps, rename),
+ spec!("layerComp.setComment", "Layer Comp Comment", &[], r##"{"comp":id|name?,"comment":str}"##, has_comps, set_comment),
+ spec!("layerComp.setOptions", "Layer Comp Options…", &[], r##"{"comp":id|name?,"visibility":bool?,"position":bool?,"appearance":bool?,"name":str?,"comment":str?}"##, has_comps, set_options),
+ spec!("layerComp.restoreLastDocumentState", "Restore Last Document State", &[], "{}", has_last_state, |s, _| restore_last(s)),
+ spec!("layerComp.updateWarnings", "Layer Comp Warnings", &[], r##"{"clear":bool=false (drop states of deleted layers)} → {warnings:[{comp,name,missingLayers}],count}"##, has_doc, update_warnings),
+ CommandSpec { journal: false, ..spec!("layerComp.list", "List Layer Comps", &[], "{} → {comps:[{id,name,comment,visibility,position,appearance,layers,missingLayers}],lastApplied,hasLastDocumentState}", has_doc, |s, _| list(s)) },
+ spec!("file.export.layerCompsToFiles", "Layer Comps to Files…", &["File", "Export"], r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"selectedOnly":bool=false (only the last applied comp),"comps":[id]?,"quality":0..12?} → {files}"##, export_comps, comps_to_files),
+ ]
+}
+
+#[cfg(test)]
+#[path = "comps_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/comps_cmds/tests.rs
new file mode 100644
index 000000000..e73976df5
--- /dev/null
+++ b/crates/engine/src/comps_cmds/tests.rs
@@ -0,0 +1,207 @@
+use super::*;
+use photocraft_color::BlendMode;
+use photocraft_doc::Layer;
+use photocraft_geom::Rect;
+
+fn session(depth: u32) -> (Session, LayerId, LayerId) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap();
+ let (a, b) = s
+ .edit("setup", |doc, _| {
+ let fmt = doc.pixel_format();
+ let mut a = Layer::raster("A", fmt);
+ a.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 14, 14), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
+ let mut b = Layer::raster("B", fmt);
+ b.surface_mut().unwrap().fill_rect(Rect::new(30, 20, 40, 30), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0]));
+ let (ia, ib) = (a.id, b.id);
+ doc.layers.push(a);
+ doc.layers.push(b);
+ Ok((ia, ib))
+ })
+ .unwrap();
+ (s, a, b)
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn pos(s: &Session, id: LayerId) -> Option<(i32, i32)> {
+ layer_position(doc(s).layer(id).unwrap())
+}
+
+#[test]
+fn capture_apply_visibility_position_appearance_independently() {
+ for depth in [8, 16, 32] {
+ let (mut s, a, b) = session(depth);
+ let c1 = s.execute("layerComp.new", json!({"name": "Start"})).unwrap()["comp"].as_u64().unwrap();
+ // Change all three properties.
+ s.execute("layer.translate", json!({"layer": a.0, "dx": 10, "dy": 5})).unwrap();
+ s.edit("t", |d, _| {
+ let l = d.layer_mut(b).unwrap();
+ l.visible = false;
+ l.blend = BlendMode::Multiply;
+ l.opacity = 0.5;
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(pos(&s, a), Some((14, 9)));
+
+ // Visibility only.
+ s.execute("layerComp.setOptions", json!({"comp": c1, "position": false, "appearance": false})).unwrap();
+ s.execute("layerComp.apply", json!({"comp": c1})).unwrap();
+ assert!(doc(&s).layer(b).unwrap().visible, "{depth}");
+ assert_eq!(pos(&s, a), Some((14, 9)));
+ assert_eq!(doc(&s).layer(b).unwrap().blend, BlendMode::Multiply);
+
+ // Position only.
+ s.edit("t", |d, _| {
+ d.layer_mut(b).unwrap().visible = false;
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layerComp.setOptions", json!({"comp": c1, "visibility": false, "position": true})).unwrap();
+ s.execute("layerComp.apply", json!({})).unwrap();
+ assert_eq!(pos(&s, a), Some((4, 4)));
+ assert!(!doc(&s).layer(b).unwrap().visible);
+
+ // Appearance only.
+ s.execute("layerComp.setOptions", json!({"comp": "Start", "position": false, "appearance": true})).unwrap();
+ s.execute("layerComp.apply", json!({})).unwrap();
+ let lb = doc(&s).layer(b).unwrap();
+ assert_eq!((lb.blend, lb.opacity, lb.visible), (BlendMode::Normal, 1.0, false));
+ // Pixels really moved (not just bounds bookkeeping).
+ let surf = doc(&s).layer(a).unwrap().surface().unwrap();
+ assert!(surf.pixel(5, 5)[3] > 0.9 && surf.pixel(16, 11)[3] < 0.1);
+ }
+}
+
+#[test]
+fn undo_redo_and_last_document_state() {
+ let (mut s, a, _) = session(8);
+ s.execute("layerComp.new", json!({})).unwrap();
+ assert_eq!(doc(&s).layer_comps[0].name, "Layer Comp 1");
+ s.execute("layer.translate", json!({"layer": a.0, "dx": 3, "dy": 0})).unwrap();
+ // A fresh document state (not a comp) is remembered when a comp is applied over it.
+ s.edit("forget", |d, _| {
+ d.last_applied_comp = None;
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layerComp.apply", json!({})).unwrap();
+ assert_eq!(pos(&s, a), Some((4, 4)));
+ assert!(doc(&s).last_document_state.is_some());
+ s.execute("layerComp.restoreLastDocumentState", json!({})).unwrap();
+ assert_eq!(pos(&s, a), Some((7, 4)));
+ assert_eq!(doc(&s).last_applied_comp, None);
+ // Each step is one undo.
+ assert!(s.undo());
+ assert_eq!(pos(&s, a), Some((4, 4)));
+ assert!(s.undo());
+ assert_eq!(pos(&s, a), Some((7, 4)));
+ assert!(s.redo());
+ assert_eq!(pos(&s, a), Some((4, 4)));
+ s.execute("layerComp.delete", json!({})).unwrap();
+ assert!(doc(&s).layer_comps.is_empty());
+ assert!(s.undo());
+ assert_eq!(doc(&s).layer_comps.len(), 1);
+}
+
+#[test]
+fn manage_comps_and_cycle() {
+ let (mut s, _, b) = session(8);
+ let c1 = s.execute("layerComp.new", json!({"name": "One", "comment": "first"})).unwrap()["comp"].as_u64().unwrap();
+ s.edit("hide", |d, _| {
+ d.layer_mut(b).unwrap().visible = false;
+ Ok(())
+ })
+ .unwrap();
+ let c2 = s.execute("layerComp.new", json!({"name": "Two"})).unwrap()["comp"].as_u64().unwrap();
+ let c3 = s.execute("layerComp.duplicate", json!({"comp": c1})).unwrap()["comp"].as_u64().unwrap();
+ let names: Vec<_> = doc(&s).layer_comps.iter().map(|c| c.name.clone()).collect();
+ assert_eq!(names, ["One", "One copy", "Two"]);
+ s.execute("layerComp.rename", json!({"comp": c3, "name": "Three"})).unwrap();
+ s.execute("layerComp.setComment", json!({"comp": "Three", "comment": "dup"})).unwrap();
+ assert_eq!(doc(&s).comp(c3 as u32).unwrap().comment, "dup");
+ // Next/previous cycle through the list order and wrap.
+ s.execute("layerComp.apply", json!({"comp": c2})).unwrap();
+ s.execute("layerComp.next", json!({})).unwrap();
+ assert_eq!(doc(&s).last_applied_comp, Some(c1 as u32));
+ assert!(doc(&s).layer(b).unwrap().visible);
+ s.execute("layerComp.previous", json!({})).unwrap();
+ assert_eq!(doc(&s).last_applied_comp, Some(c2 as u32));
+ assert!(!doc(&s).layer(b).unwrap().visible);
+ let l = s.execute("layerComp.list", json!({})).unwrap();
+ assert_eq!(l["comps"].as_array().unwrap().len(), 3);
+ // Update one property: the visibility recorded in "One" follows the document again.
+ s.execute("layerComp.update", json!({"comp": c1, "what": "visibility"})).unwrap();
+ assert_eq!(doc(&s).comp(c1 as u32).unwrap().state(b).unwrap().visible, Some(false));
+ s.execute("layerComp.update", json!({"comp": "*"})).unwrap();
+}
+
+#[test]
+fn warnings_for_deleted_layers() {
+ let (mut s, a, _) = session(8);
+ s.execute("layerComp.new", json!({})).unwrap();
+ assert_eq!(s.execute("layerComp.updateWarnings", json!({})).unwrap()["count"], 0);
+ s.edit("del", |d, _| {
+ d.remove(a);
+ Ok(())
+ })
+ .unwrap();
+ let w = s.execute("layerComp.updateWarnings", json!({})).unwrap();
+ assert_eq!(w["count"], 1);
+ assert_eq!(w["warnings"][0]["missingLayers"][0], a.0);
+ // Applying still works (missing layers are skipped) and reports them.
+ assert_eq!(s.execute("layerComp.apply", json!({})).unwrap()["missingLayers"], 1);
+ s.execute("layerComp.updateWarnings", json!({"clear": true})).unwrap();
+ assert_eq!(s.execute("layerComp.updateWarnings", json!({})).unwrap()["count"], 0);
+}
+
+#[test]
+fn disabled_states_and_bad_params() {
+ let mut s = Session::new();
+ assert!(!s.is_enabled("layerComp.new"));
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ assert!(s.is_enabled("layerComp.new"));
+ for id in ["layerComp.apply", "layerComp.update", "layerComp.next", "layerComp.delete", "file.export.layerCompsToFiles", "layerComp.restoreLastDocumentState"] {
+ assert!(!s.is_enabled(id), "{id}");
+ }
+ s.execute("layerComp.new", json!({})).unwrap();
+ assert!(s.execute("layerComp.apply", json!({"comp": 999})).is_err());
+ assert!(s.execute("layerComp.apply", json!({"comp": "nope"})).is_err());
+ assert!(s.execute("layerComp.update", json!({"what": "colour"})).is_err());
+ assert!(s.execute("layerComp.rename", json!({})).is_err());
+ assert!(s.execute("layerComp.setOptions", json!({})).is_err());
+}
+
+#[test]
+fn export_comps_to_files_naming() {
+ let (mut s, _, b) = session(8);
+ s.execute("layerComp.new", json!({"name": "With B"})).unwrap();
+ s.edit("hide", |d, _| {
+ d.layer_mut(b).unwrap().visible = false;
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layerComp.new", json!({"name": "No/B"})).unwrap();
+ let dir = std::env::temp_dir().join(format!("photocraft-comps-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let d = dir.to_string_lossy().into_owned();
+ let r = s.execute("file.export.layerCompsToFiles", json!({"dir": d, "prefix": "doc"})).unwrap();
+ let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
+ assert_eq!(files.len(), 2);
+ assert!(files[0].ends_with("doc_0000_With B.png"), "{files:?}");
+ assert!(files[1].ends_with("doc_0001_No_B.png"), "{files:?}");
+ // Each file shows its comp: B's blue square only in the first.
+ let blue = |path: &str| {
+ let doc = photocraft_io::import("x.png", &std::fs::read(path).unwrap()).unwrap().document;
+ photocraft_compose::render(&doc, Rect::new(35, 25, 36, 26)).px[0]
+ };
+ assert!(blue(&files[0])[2] > 0.9 && blue(&files[0])[0] < 0.1);
+ assert!(blue(&files[1])[2] > 0.9 && blue(&files[1])[0] > 0.9);
+ let r = s.execute("file.export.layerCompsToFiles", json!({"dir": d, "selectedOnly": true, "format": "jpg"})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), 1);
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/distort_cmds.rs
new file mode 100644
index 000000000..759cf5235
--- /dev/null
+++ b/crates/engine/src/distort_cmds.rs
@@ -0,0 +1,353 @@
+//! Filter › Liquify, Edit › Puppet Warp and Edit › Perspective Warp (plus their Layer › Smart
+//! Objects twins).
+//!
+//! All three take their whole edit as data, so each is one replayable command and one history
+//! step: Liquify the brush strokes (replayed onto a fresh displacement field,
+//! `photocraft_algo::liquify`), Puppet Warp the pins (`photocraft_algo::puppet`, ARAP on a mesh
+//! of the opaque region), Perspective Warp the planes (`photocraft_algo::perspective`). On a
+//! smart object each becomes a smart filter (as in Photoshop): the params are stored with the
+//! smart object and re-applied to a fresh render of the source, so editing never accumulates
+//! resampling. The params are the data in every case (strokes, pins and planes are small
+//! compared with a field or a mesh, and replay is deterministic), so nothing needs a blob.
+
+use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, apply_liquify, auto_cell};
+use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, straighten};
+use photocraft_algo::puppet::{PuppetDensity, PuppetMode, PuppetPin, PuppetWarp, puppet_warp};
+use photocraft_algo::transform::Interp;
+use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};
+use photocraft_color::PixelFormat;
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartFilter};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+pub const LIQUIFY: &str = "filter.liquify";
+pub const PUPPET: &str = "edit.puppetWarp";
+pub const PUPPET_SMART: &str = "layer.smartObjects.puppetWarp";
+pub const PERSPECTIVE: &str = "edit.perspectiveWarp";
+pub const PERSPECTIVE_SMART: &str = "layer.smartObjects.perspectiveWarp";
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+// ---------- params ----------
+
+/// Liquify params: the strokes and the field resolution (`meshSize`, px per field node).
+pub fn liquify_params(cmd: &str, p: &Value, canvas: Rect) -> Result<(Vec<LiquifyStroke>, f64)> {
+ let strokes: Vec<LiquifyStroke> = match p.get("strokes") {
+ Some(v) => serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("bad `strokes`: {e}")))?,
+ None => Vec::new(),
+ };
+ for s in &strokes {
+ s.validate().map_err(|e| bad(cmd, e))?;
+ }
+ let cell = match p.get("meshSize") {
+ None | Some(Value::Null) => auto_cell(canvas),
+ Some(v) => {
+ let c = v.as_f64().ok_or_else(|| bad(cmd, "`meshSize` is px per field node (1..64)"))?;
+ if !(1.0..=64.0).contains(&c) {
+ return Err(bad(cmd, "`meshSize` must be 1..64"));
+ }
+ c
+ }
+ };
+ Ok((strokes, cell))
+}
+
+/// Puppet Warp params.
+pub fn puppet_params(cmd: &str, p: &Value) -> Result<PuppetWarp> {
+ let pins: Vec<PuppetPin> = match p.get("pins") {
+ Some(v) => serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("bad `pins` (each {{\"src\":[x,y],\"dst\":[x,y],\"rotate\":deg?,\"depth\":n?}}): {e}")))?,
+ None => Vec::new(),
+ };
+ if pins.iter().any(|q| q.src.iter().chain(&q.dst).any(|v| !v.is_finite()) || q.rotate.is_some_and(|r| !r.is_finite())) {
+ return Err(bad(cmd, "pin coordinates must be finite"));
+ }
+ let mode = match p.get("mode").and_then(Value::as_str) {
+ Some(m) => PuppetMode::parse(m).ok_or_else(|| bad(cmd, format!("unknown mode \"{m}\" (rigid|normal|distort)")))?,
+ None => PuppetMode::Normal,
+ };
+ let density = match p.get("density").and_then(Value::as_str) {
+ Some(d) => PuppetDensity::parse(d).ok_or_else(|| bad(cmd, format!("unknown density \"{d}\" (fewer|normal|more)")))?,
+ None => PuppetDensity::Normal,
+ };
+ let expansion = p.get("expansion").and_then(Value::as_f64).unwrap_or(2.0);
+ if !expansion.is_finite() || expansion.abs() > 200.0 {
+ return Err(bad(cmd, "`expansion` must be -200..200 px"));
+ }
+ Ok(PuppetWarp { pins, mode, density, expansion })
+}
+
+/// Perspective Warp params (planes, after the optional straighten).
+pub fn perspective_params(cmd: &str, p: &Value) -> Result<Vec<Plane>> {
+ let mut planes: Vec<Plane> = match p.get("planes") {
+ Some(v) => serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("bad `planes` (each {{\"src\":[4×[x,y]],\"dst\":[4×[x,y]]}}): {e}")))?,
+ None => return Err(bad(cmd, "pass `planes`: [{\"src\":[[x,y]×4],\"dst\":[[x,y]×4]}]")),
+ };
+ if planes.is_empty() {
+ return Err(bad(cmd, "`planes` is empty"));
+ }
+ if planes.iter().any(|q| q.src.iter().chain(&q.dst).flatten().any(|v| !v.is_finite())) {
+ return Err(bad(cmd, "plane corners must be finite"));
+ }
+ if let Some(s) = p.get("straighten").and_then(Value::as_str) {
+ let mode = Straighten::parse(s).ok_or_else(|| bad(cmd, format!("unknown straighten \"{s}\" (horizontal|vertical|auto)")))?;
+ straighten(&mut planes, mode);
+ }
+ if PerspectiveMap::new(&planes).is_none() {
+ return Err(bad(cmd, "a plane is degenerate (its corners must form a quad)"));
+ }
+ Ok(planes)
+}
+
+fn interp(p: &Value) -> Interp {
+ Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"))
+}
+
+// ---------- pixel operations ----------
+
+/// Mixes `new` over `old` by the selection's coverage (premultiplied when there is alpha).
+fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface {
+ let area = old.content_bounds().union(&new.content_bounds());
+ let mut out = new.clone();
+ if area.is_empty() {
+ return out;
+ }
+ let fmt = old.format();
+ let n = fmt.channels();
+ let (o, w) = (old.read_region(area), new.read_region(area));
+ let mut r = vec![0.0f32; o.len()];
+ let aw = area.width() as usize;
+ for (i, ((op, np), rp)) in o.chunks_exact(n).zip(w.chunks_exact(n)).zip(r.chunks_exact_mut(n)).enumerate() {
+ let k = sel.sample_channel(area.x0 + (i % aw) as i32, area.y0 + (i / aw) as i32, 0).clamp(0.0, 1.0);
+ if !fmt.alpha {
+ for c in 0..n {
+ rp[c] = op[c] + (np[c] - op[c]) * k;
+ }
+ continue;
+ }
+ let a = n - 1;
+ let oa = op[a] + (np[a] - op[a]) * k;
+ rp[a] = oa;
+ for c in 0..a {
+ let pm = op[c] * op[a] + (np[c] * np[a] - op[c] * op[a]) * k;
+ rp[c] = if oa > 0.0 { (pm / oa).clamp(0.0, 1.0) } else { 0.0 };
+ }
+ }
+ out.write_region(area, &r);
+ out.prune();
+ out
+}
+
+/// Liquifies a surface over `canvas` (the field's extent).
+pub fn liquify_surface(surf: &Surface, strokes: &[LiquifyStroke], cell: f64, canvas: Rect) -> Surface {
+ let field = LiquifyField::from_strokes(canvas, cell, strokes);
+ apply_liquify(surf, &field)
+}
+
+/// Puppet-warps a surface's content.
+pub fn puppet_surface(surf: &Surface, w: &PuppetWarp, interp: Interp) -> Surface {
+ let b = surf.content_bounds();
+ if w.is_identity() || b.is_empty() {
+ return surf.clone();
+ }
+ puppet_warp(surf, b, w, interp)
+}
+
+/// Perspective-warps a surface's content.
+pub fn perspective_surface(surf: &Surface, planes: &[Plane], interp: Interp) -> Surface {
+ let b = surf.content_bounds();
+ if PerspectiveMap::is_identity(planes) || b.is_empty() {
+ return surf.clone();
+ }
+ let Some(m) = PerspectiveMap::new(planes) else { return surf.clone() };
+ warp_mesh_surface(surf, b, &|x, y| m.map(x, y), interp)
+}
+
+/// Smart-filter hook: re-applies a stored Liquify / Puppet / Perspective Warp to a rendered
+/// smart object (`None` for other ids).
+pub fn apply_to_surface(id: &str, params: &Value, surf: &Surface, canvas: Rect) -> Option<Surface> {
+ match id {
+ LIQUIFY => {
+ let (strokes, cell) = liquify_params(id, params, canvas).ok()?;
+ Some(liquify_surface(surf, &strokes, cell, canvas))
+ }
+ PUPPET | PUPPET_SMART => Some(puppet_surface(surf, &puppet_params(id, params).ok()?, interp(params))),
+ PERSPECTIVE | PERSPECTIVE_SMART => Some(perspective_surface(surf, &perspective_params(id, params).ok()?, interp(params))),
+ _ => None,
+ }
+}
+
+// ---------- commands ----------
+
+fn target(s: &Session, p: &Value) -> Result<LayerId> {
+ match p.get("layer").and_then(Value::as_u64) {
+ Some(v) => Ok(LayerId(v)),
+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())),
+ }
+}
+
+fn pixel_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ match &d.doc.layer(id).ok_or("no active layer")?.content {
+ LayerContent::Raster(_) => Ok(()),
+ LayerContent::Smart(sm) if sm.cache.is_some() => Ok(()),
+ other => Err(format!("needs a pixel layer or smart object (active layer is a {} layer)", other.kind_name())),
+ }
+}
+
+fn smart_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Smart(_)) => Ok(()),
+ _ => Err("the active layer is not a smart object".into()),
+ }
+}
+
+/// Unlocks a Background layer for an operation that exposes transparency (as Photoshop does).
+fn float_background(l: &mut Layer) {
+ if l.locks.position && l.name == "Background" {
+ l.locks.position = false;
+ l.locks.transparency = false;
+ l.name = "Layer 0".into();
+ }
+}
+
+fn check_locks(l: &Layer, position: bool) -> Result<()> {
+ if l.locks.all || l.locks.pixels || (position && l.locks.position) {
+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
+ }
+ Ok(())
+}
+
+/// Shared driver: a smart object records `cmd` as a smart filter; a pixel layer is edited in
+/// place by `f(surface, selection)`.
+type MaskFn<'a> = Option<&'a dyn Fn(&Surface) -> Surface>;
+
+fn run_on_layer(s: &mut Session, cmd: &str, label: &str, p: &Value, moves: bool, f: &dyn Fn(&Surface, Option<&Surface>, Rect) -> Surface, mask: MaskFn) -> Result<Value> {
+ let id = target(s, p)?;
+ let mut params = p.clone();
+ if let Value::Object(m) = &mut params {
+ m.remove("layer");
+ }
+ s.edit(label, |doc: &mut Document, _| {
+ let canvas = doc.bounds();
+ let selection = doc.selection.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if let LayerContent::Smart(_) = l.content {
+ let sf = SmartFilter { command: cmd.to_string(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
+ return crate::smart_cmds::add_smart_filter(doc, id, sf, selection.as_ref());
+ }
+ if moves {
+ float_background(l);
+ }
+ check_locks(l, moves)?;
+ let LayerContent::Raster(surf) = &mut l.content else {
+ return Err(EngineError::Other(format!("{label} needs a pixel layer (rasterize it first)")));
+ };
+ *surf = f(surf, selection.as_ref(), canvas);
+ // A linked layer mask follows a geometric warp.
+ if let (Some(mf), Some(m)) = (mask, l.mask.as_mut())
+ && m.linked
+ {
+ m.surface = mf(&m.surface);
+ }
+ Ok(())
+ })?;
+ Ok(json!({"layer": id.0, "changed": true}))
+}
+
+fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
+ let canvas = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();
+ let (strokes, cell) = liquify_params(LIQUIFY, p, canvas)?;
+ let id = target(s, p)?;
+ if strokes.is_empty() {
+ return Ok(json!({"layer": id.0, "changed": false}));
+ }
+ let t0 = std::time::Instant::now();
+ let field = LiquifyField::from_strokes(canvas, cell, &strokes);
+ let smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)));
+ if field.is_identity() && !smart {
+ return Ok(json!({"layer": id.0, "changed": false}));
+ }
+ let r = run_on_layer(s, LIQUIFY, "Liquify", p, false, &|surf, sel, _| {
+ let out = apply_liquify(surf, &field);
+ match sel {
+ Some(sel) => mix_by_selection(surf, &out, sel),
+ None => out,
+ }
+ }, None)?;
+ let mut r = r;
+ r["ms"] = json!(t0.elapsed().as_secs_f64() * 1000.0);
+ r["maxDisplacement"] = json!(field.max_displacement());
+ Ok(r)
+}
+
+/// Lifts the selected pixels (when there is a selection), deforms them with `f` and puts them
+/// back over the rest; without a selection deforms the whole surface.
+fn deform_selected(surf: &Surface, sel: Option<&Surface>, f: &dyn Fn(&Surface) -> Surface) -> Surface {
+ match sel {
+ Some(sel) => {
+ let (lifted, mut rest) = crate::transform_cmds::split_selected(surf, sel);
+ let moved = f(&lifted);
+ crate::transform_cmds::composite_over(&mut rest, &moved);
+ rest.prune();
+ rest
+ }
+ None => {
+ let fmt = surf.format();
+ let src = if fmt.alpha { surf.clone() } else { surf.convert(PixelFormat::new(fmt.mode, fmt.sample, true)) };
+ f(&src)
+ }
+ }
+}
+
+fn puppet(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ let w = puppet_params(cmd, p)?;
+ let id = target(s, p)?;
+ let smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)));
+ if w.is_identity() && !smart {
+ return Ok(json!({"layer": id.0, "changed": false}));
+ }
+ let it = interp(p);
+ run_on_layer(s, cmd, "Puppet Warp", p, true, &|surf, sel, _| deform_selected(surf, sel, &|x| puppet_surface(x, &w, it)), None)
+}
+
+fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ let planes = perspective_params(cmd, p)?;
+ let id = target(s, p)?;
+ let smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)));
+ if PerspectiveMap::is_identity(&planes) && !smart {
+ return Ok(json!({"layer": id.0, "changed": false, "planes": planes}));
+ }
+ let it = interp(p);
+ let map = PerspectiveMap::new(&planes);
+ let mask_fn = |m: &Surface| match &map {
+ Some(map) => warp_mesh_gray(m, &|x, y| map.map(x, y), Interp::Bilinear),
+ None => m.clone(),
+ };
+ let mut r = run_on_layer(s, cmd, "Perspective Warp", p, true, &|surf, sel, _| deform_selected(surf, sel, &|x| perspective_surface(x, &planes, it)), Some(&mask_fn))?;
+ r["planes"] = json!(planes);
+ Ok(r)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ const L: &str = r##"{"strokes":[{"tool":"forwardWarp|reconstruct|smooth|twirlCw|twirlCcw|pucker|bloat|pushLeft|freeze|thaw|reconstructAll","size":px=100,"density":0-100=50,"pressure":0-100=100,"rate":0-100=80,"points":[[x,y,pressure?]…],"amount":%? (reconstructAll)}…],"meshSize":px? (field resolution, px per node; default 2, or 4 above 4 MP),"layer":id?} — strokes replay in order on a fresh field; a selection limits the effect; on a smart object it becomes a smart filter"##;
+ const P: &str = r##"{"pins":[{"src":[x,y],"dst":[x,y],"rotate":deg?,"depth":n?}…],"mode":"rigid|normal|distort"="normal","density":"fewer|normal|more"="normal","expansion":px=2,"interpolation":"bicubic|bilinear|nearest","layer":id?} — mesh over the opaque region, as-rigid-as-possible; on a smart object it becomes a smart filter"##;
+ const Q: &str = r##"{"planes":[{"src":[[x,y]×4],"dst":[[x,y]×4]}…] (corners clockwise from top-left; corners that coincide in src are linked),"straighten":"horizontal|vertical|auto"?,"interpolation":"bicubic|bilinear|nearest","layer":id?}"##;
+ vec![
+ CommandSpec { id: LIQUIFY, label: "Liquify…", menu: &["Filter"], shortcut: Some("Cmd+Shift+X"), params: L, enabled: crate::filters::has_filterable_layer, journal: true, run: liquify },
+ CommandSpec { id: PUPPET, label: "Puppet Warp", menu: &["Edit"], shortcut: None, params: P, enabled: pixel_layer, journal: true, run: |s, p| puppet(s, p, PUPPET) },
+ CommandSpec { id: PUPPET_SMART, label: "Puppet Warp", menu: &["Layer", "Smart Objects"], shortcut: None, params: P, enabled: smart_layer, journal: true, run: |s, p| puppet(s, p, PUPPET_SMART) },
+ CommandSpec { id: PERSPECTIVE, label: "Perspective Warp", menu: &["Edit"], shortcut: None, params: Q, enabled: pixel_layer, journal: true, run: |s, p| perspective(s, p, PERSPECTIVE) },
+ CommandSpec { id: PERSPECTIVE_SMART, label: "Perspective Warp", menu: &["Layer", "Smart Objects"], shortcut: None, params: Q, enabled: smart_layer, journal: true, run: |s, p| perspective(s, p, PERSPECTIVE_SMART) },
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/distort_cmds/tests.rs b/crates/engine/src/distort_cmds/tests.rs
new file mode 100644
index 000000000..821b1e263
--- /dev/null
+++ b/crates/engine/src/distort_cmds/tests.rs
@@ -0,0 +1,205 @@
+use super::*;
+
+/// 80×60 document, a new layer with a patterned 50×30 block at (10, 10).
+fn session(depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let surf = l.surface_mut().unwrap();
+ for y in 10..40 {
+ for x in 10..60 {
+ let v = ((x / 3 + y / 3) % 2) as f32;
+ surf.write_pixel(x, y, &[v, 1.0 - v, (x as f32) / 80.0, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn active_surface(s: &Session) -> Surface {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone()
+}
+
+fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 {
+ a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
+}
+
+fn smart(s: &Session) -> photocraft_doc::SmartObject {
+ let st = s.active().unwrap();
+ match &st.doc.layer(st.active_layer.unwrap()).unwrap().content {
+ LayerContent::Smart(sm) => sm.clone(),
+ _ => panic!("not smart"),
+ }
+}
+
+#[test]
+fn liquify_identity_stroke_displacement_reconstruct_and_undo() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ let before = active_surface(&s);
+ let r = s.execute(LIQUIFY, json!({})).unwrap();
+ assert_eq!(r["changed"], false);
+ let r = s.execute(LIQUIFY, json!({"strokes": [{"tool": "forwardWarp", "size": 30, "pressure": 0, "points": [[30, 25], [45, 25]]}]})).unwrap();
+ assert_eq!(r["changed"], false, "zero pressure is a no-op");
+ let hist = s.active().unwrap().history.past_len();
+ let stroke = json!({"tool": "forwardWarp", "size": 30, "points": [[30, 25], [42, 25]]});
+ let r = s.execute(LIQUIFY, json!({"strokes": [stroke]})).unwrap();
+ assert_eq!(r["changed"], true);
+ assert!(r["maxDisplacement"].as_f64().unwrap() > 4.0);
+ assert_eq!(s.active().unwrap().history.past_len(), hist + 1, "one history step");
+ let after = active_surface(&s);
+ // The pattern moved right: the output at (42, 25) shows what was a few px to the left.
+ let d = (0..12).map(|k| worst_px(&after.pixel(42, 25), &before.pixel(42 - k, 25))).enumerate().min_by(|a, b| a.1.total_cmp(&b.1)).unwrap().0;
+ assert!(d >= 3, "{depth}: displaced by {d}");
+ assert_ne!(after, before);
+ // Reconstruct All in the same stroke list restores the original.
+ let mut s2 = session(depth);
+ s2.execute(LIQUIFY, json!({"strokes": [stroke, {"tool": "reconstructAll", "amount": 100}]})).unwrap();
+ assert!(worst(&active_surface(&s2), &before, Rect::new(0, 0, 80, 60)) <= 1.0 / 255.0);
+ s.undo();
+ assert_eq!(active_surface(&s), before);
+ assert!(s.execute(LIQUIFY, json!({"strokes": [{"tool": "melt", "points": [[1, 1]]}]})).is_err());
+ assert!(s.execute(LIQUIFY, json!({"strokes": [{"points": [[1]]}]})).is_err());
+ assert!(s.execute(LIQUIFY, json!({"strokes": [], "meshSize": 0})).is_err());
+ }
+}
+
+fn worst_px(a: &[f32], b: &[f32]) -> f32 {
+ a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
+}
+
+#[test]
+fn liquify_respects_the_selection() {
+ let mut s = session(8);
+ let before = active_surface(&s);
+ s.execute("select.all", json!({})).ok();
+ s.edit("sel", |doc, _| {
+ let mut sel = Surface::new(PixelFormat::GRAY8);
+ sel.fill_rect(Rect::new(0, 0, 35, 60), &[1.0]);
+ doc.selection = Some(sel);
+ Ok(())
+ })
+ .unwrap();
+ s.execute(LIQUIFY, json!({"strokes": [{"tool": "bloat", "size": 60, "points": [[35, 25], [35, 25], [35, 25], [35, 25]]}]})).unwrap();
+ let after = active_surface(&s);
+ assert_eq!(after.read_region(Rect::new(36, 0, 80, 60)), before.read_region(Rect::new(36, 0, 80, 60)), "unselected pixels stay");
+ assert_ne!(after.read_region(Rect::new(10, 10, 35, 40)), before.read_region(Rect::new(10, 10, 35, 40)));
+}
+
+#[test]
+fn puppet_identity_translation_and_undo() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ let before = active_surface(&s);
+ assert_eq!(s.execute(PUPPET, json!({})).unwrap()["changed"], false);
+ assert_eq!(s.execute(PUPPET, json!({"pins": [{"src": [20, 20], "dst": [20, 20]}]})).unwrap()["changed"], false);
+ s.execute(PUPPET, json!({"pins": [{"src": [30, 25], "dst": [36, 29]}], "mode": "rigid", "interpolation": "bilinear"})).unwrap();
+ let after = active_surface(&s);
+ assert_eq!(after.content_bounds(), Rect::new(16, 14, 66, 44), "{depth}");
+ assert!(worst(&after.convert(before.format()), &photocraft_algo::resample::translate_surface(&before, 6, 4), Rect::new(16, 14, 66, 44)) <= 1.0 / 255.0, "{depth}");
+ s.undo();
+ assert_eq!(active_surface(&s), before);
+ assert!(s.execute(PUPPET, json!({"pins": [{"src": [1, 1]}]})).is_err());
+ assert!(s.execute(PUPPET, json!({"pins": [], "mode": "wobbly"})).is_err());
+ assert!(s.execute(PUPPET, json!({"pins": [], "density": "lots"})).is_err());
+ }
+}
+
+#[test]
+fn puppet_two_pins_bend_the_block() {
+ let mut s = session(8);
+ // Hold the left end, lift the right end: the right side rises, the left stays.
+ s.execute(PUPPET, json!({"pins": [{"src": [15, 25], "dst": [15, 25]}, {"src": [55, 25], "dst": [55, 10]}], "mode": "normal", "density": "more"})).unwrap();
+ let after = active_surface(&s);
+ assert!(after.pixel(12, 25)[3] > 0.5, "the held end stays");
+ assert!(after.content_bounds().y0 < 6, "{:?}", after.content_bounds());
+}
+
+#[test]
+fn perspective_identity_known_homography_and_mask() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ let before = active_surface(&s);
+ let q = [[10.0, 10.0], [60.0, 10.0], [60.0, 40.0], [10.0, 40.0]];
+ let r = s.execute(PERSPECTIVE, json!({"planes": [{"src": q, "dst": q}]})).unwrap();
+ assert_eq!(r["changed"], false);
+ // Shift the whole quad by (5, 3): a pure translation of the layer.
+ let d = q.map(|p| [p[0] + 5.0, p[1] + 3.0]);
+ s.execute(PERSPECTIVE, json!({"planes": [{"src": q, "dst": d}], "interpolation": "bilinear"})).unwrap();
+ let after = active_surface(&s);
+ assert_eq!(after.content_bounds(), Rect::new(15, 13, 65, 43));
+ assert!(worst(&after.convert(before.format()), &photocraft_algo::resample::translate_surface(&before, 5, 3), Rect::new(15, 13, 65, 43)) <= 1.0 / 255.0, "{depth}");
+ s.undo();
+ assert_eq!(active_surface(&s), before);
+ }
+ // A keystone: corners land where asked.
+ let mut s = session(8);
+ let q = [[10.0, 10.0], [60.0, 10.0], [60.0, 40.0], [10.0, 40.0]];
+ let d = [[20.0, 10.0], [50.0, 10.0], [70.0, 50.0], [0.0, 50.0]];
+ s.execute("layer.layerMask.revealAll", json!({})).ok();
+ s.execute(PERSPECTIVE, json!({"planes": [{"src": q, "dst": d}]})).unwrap();
+ let after = active_surface(&s);
+ let b = after.content_bounds();
+ assert!(b.x0 <= 1 && b.x1 >= 69 && b.y1 >= 49 && b.y0 >= 9, "{b:?}");
+ assert!(after.pixel(15, 12)[3] < 0.1, "the top narrowed");
+ assert!(s.execute(PERSPECTIVE, json!({})).is_err());
+ assert!(s.execute(PERSPECTIVE, json!({"planes": [{"src": [[0, 0], [0, 0], [0, 0], [0, 0]], "dst": [[0, 0], [0, 0], [0, 0], [0, 0]]}]})).is_err());
+ assert!(s.execute(PERSPECTIVE, json!({"planes": [{"src": q, "dst": d}], "straighten": "sideways"})).is_err());
+}
+
+#[test]
+fn smart_objects_store_distortions_as_smart_filters_losslessly() {
+ for depth in [8u64, 16, 32] {
+ let mut s = session(depth);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let original = active_surface(&s);
+ assert!(s.is_enabled(PUPPET_SMART) && s.is_enabled(PERSPECTIVE_SMART));
+ s.execute(LIQUIFY, json!({"strokes": [{"tool": "twirlCw", "size": 40, "points": [[35, 25], [35, 25], [35, 25]]}]})).unwrap();
+ let liq = active_surface(&s);
+ assert_ne!(liq, original);
+ s.execute(PUPPET_SMART, json!({"pins": [{"src": [30, 25], "dst": [34, 25]}], "mode": "rigid"})).unwrap();
+ let q = [[10.0, 10.0], [60.0, 10.0], [60.0, 40.0], [10.0, 40.0]];
+ s.execute(PERSPECTIVE_SMART, json!({"planes": [{"src": q, "dst": [[12.0, 10.0], [58.0, 10.0], [60.0, 40.0], [10.0, 40.0]]}]})).unwrap();
+ let sm = smart(&s);
+ let ids: Vec<&str> = sm.smart_filters.iter().map(|f| f.command.as_str()).collect();
+ assert_eq!(ids, [LIQUIFY, PUPPET_SMART, PERSPECTIVE_SMART]);
+ // Deleting the top two filters re-renders exactly the liquified state; deleting all
+ // gives back the original pixels (nothing accumulated).
+ s.execute("layer.smartFilter.delete", json!({})).unwrap();
+ s.execute("layer.smartFilter.delete", json!({})).unwrap();
+ assert_eq!(active_surface(&s), liq, "{depth}");
+ s.execute("layer.smartFilter.delete", json!({})).unwrap();
+ assert_eq!(active_surface(&s), original, "{depth}");
+ s.undo();
+ assert_eq!(active_surface(&s), liq);
+ }
+}
+
+#[test]
+fn enabled_states() {
+ let mut s = session(8);
+ assert!(s.is_enabled(LIQUIFY) && s.is_enabled(PUPPET) && s.is_enabled(PERSPECTIVE));
+ assert!(!s.is_enabled(PUPPET_SMART) && !s.is_enabled(PERSPECTIVE_SMART));
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ assert!(!s.is_enabled(PUPPET) && !s.is_enabled(PERSPECTIVE));
+ let mut empty = Session::new();
+ assert!(!empty.is_enabled(LIQUIFY));
+ assert!(empty.execute(PUPPET, json!({"pins": []})).is_err());
+}
+
+#[test]
+fn background_layer_is_floated_by_geometric_warps() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap();
+ s.execute(PUPPET, json!({"pins": [{"src": [20, 15], "dst": [25, 15]}], "mode": "rigid"})).unwrap();
+ let st = s.active().unwrap();
+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ assert_eq!(l.name, "Layer 0");
+ assert!(l.surface().unwrap().format().alpha);
+ assert!(l.surface().unwrap().pixel(2, 15)[3] < 0.01, "exposed area is transparent");
+}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 21d679519..af806bfdd 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -27,11 +27,11 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
}
/// The file system is reachable (not on the web).
-fn native(_: &Session) -> std::result::Result<(), String> {
+pub(crate) fn native(_: &Session) -> std::result::Result<(), String> {
if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) }
}
-fn native_doc(s: &Session) -> std::result::Result<(), String> {
+pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> {
native(s)?;
has_doc(s)
}
@@ -84,14 +84,14 @@ fn read_file(path: &str) -> Result<Vec<u8>> {
}
#[cfg(not(target_arch = "wasm32"))]
-fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
+pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?;
}
std::fs::write(path, bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
#[cfg(target_arch = "wasm32")]
-fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
+pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
Err(EngineError::Other(format!("cannot write {path}: no file system on the web")))
}
@@ -120,7 +120,7 @@ fn file_name(path: &str) -> String {
path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
}
-fn stem(path: &str) -> String {
+pub(crate) fn stem(path: &str) -> String {
let n = file_name(path);
match n.rfind('.') {
Some(i) if i > 0 => n[..i].to_string(),
@@ -128,7 +128,7 @@ fn stem(path: &str) -> String {
}
}
-fn join(dir: &str, name: &str) -> String {
+pub(crate) fn join(dir: &str, name: &str) -> String {
if dir.is_empty() {
name.to_string()
} else if dir.ends_with('/') || dir.ends_with('\\') {
@@ -139,7 +139,7 @@ fn join(dir: &str, name: &str) -> String {
}
/// A file-name-safe version of a layer name.
-fn sanitize(name: &str) -> String {
+pub(crate) fn sanitize(name: &str) -> String {
let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect();
let s = s.trim().trim_matches('.').to_string();
if s.is_empty() { "layer".into() } else { s }
@@ -150,7 +150,7 @@ fn import(name: &str, bytes: &[u8]) -> Result<Document> {
}
/// Encodes `doc` for `path`'s extension. `quality` is Photoshop's 0–12 JPEG scale.
-fn encode(doc: &Document, path: &str, quality: Option<f64>) -> Result<(Vec<u8>, Vec<String>)> {
+pub(crate) fn encode(doc: &Document, path: &str, quality: Option<f64>) -> Result<(Vec<u8>, Vec<String>)> {
let mut opts = photocraft_io::ExportOptions::default();
if let Some(q) = quality {
opts.encode.jpeg_quality = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;
@@ -158,17 +158,17 @@ fn encode(doc: &Document, path: &str, quality: Option<f64>) -> Result<(Vec<u8>,
photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
-fn save_doc(doc: &Document, path: &str, quality: Option<f64>) -> Result<Vec<String>> {
+pub(crate) fn save_doc(doc: &Document, path: &str, quality: Option<f64>) -> Result<Vec<String>> {
let (bytes, warnings) = encode(doc, path, quality)?;
write_file(path, &bytes)?;
Ok(warnings)
}
-fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> {
+pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> {
p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") })
}
-fn f64_param(p: &Value, key: &str) -> Option<f64> {
+pub(crate) fn f64_param(p: &Value, key: &str) -> Option<f64> {
p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite())
}
@@ -940,14 +940,19 @@ fn guides_from_shape(s: &mut Session, p: &Value) -> Result<Value> {
fn clear_canvas_guides(s: &mut Session) -> Result<Value> {
let d = s.active().ok_or(EngineError::NoDocument)?;
- if d.doc.guides.vertical.is_empty() && d.doc.guides.horizontal.is_empty() {
+ // Guides inside an artboard belong to it (View › Clear Selected Artboard Guides); the rest
+ // are canvas guides. Without artboards every guide is a canvas guide.
+ let boards: Vec<Rect> = d.doc.artboards().iter().map(|b| b.2.rect).collect();
+ let in_x = move |x: f32| boards.iter().any(|r| f64::from(x) > f64::from(r.x0) && f64::from(x) < f64::from(r.x1));
+ let boards_y: Vec<Rect> = d.doc.artboards().iter().map(|b| b.2.rect).collect();
+ let in_y = move |y: f32| boards_y.iter().any(|r| f64::from(y) > f64::from(r.y0) && f64::from(y) < f64::from(r.y1));
+ let n = d.doc.guides.vertical.iter().filter(|x| !in_x(**x)).count() + d.doc.guides.horizontal.iter().filter(|y| !in_y(**y)).count();
+ if n == 0 {
return Ok(json!({"cleared": 0}));
}
- let n = d.doc.guides.vertical.len() + d.doc.guides.horizontal.len();
- // Without artboards every guide is a canvas guide.
s.edit("Clear Canvas Guides", |doc, _| {
- doc.guides.vertical.clear();
- doc.guides.horizontal.clear();
+ doc.guides.vertical.retain(|x| in_x(*x));
+ doc.guides.horizontal.retain(|y| in_y(*y));
Ok(())
})?;
Ok(json!({"cleared": n}))
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs
index 878a2f370..d5d95119c 100644
--- a/crates/engine/src/filters.rs
+++ b/crates/engine/src/filters.rs
@@ -130,6 +130,10 @@ pub fn apply_filter_to_surface(
selection: Option<&photocraft_raster::Surface>,
canvas: photocraft_geom::Rect,
) -> Option<photocraft_raster::Surface> {
+ // Liquify / Puppet Warp / Perspective Warp smart filters (distort_cmds).
+ if let Some(out) = crate::distort_cmds::apply_to_surface(id, params, surf, canvas) {
+ return Some(out);
+ }
let fp = params_for(id, params)?;
let sel_bounds = selection.map(photocraft_raster::Surface::content_bounds);
let content = surf.content_bounds();
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index d0aa2bf40..e5c8d7150 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -129,7 +129,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
*surf = resize_surface(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter });
});
let k = ((sx + sy) / 2.0) as f32;
- for_each_layer(&mut doc.layers, &mut |l| scale_effects(&mut l.effects, k));
+ for_each_layer(&mut doc.layers, &mut |l| {
+ scale_effects(&mut l.effects, k);
+ if let Some(r) = &mut l.effects.reference {
+ *r = (r.0 * sx, r.1 * sy);
+ }
+ });
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
ch.surface = resize_surface(&ch.surface, sx, sy, Resample::Bilinear);
}
@@ -154,6 +159,17 @@ fn translate_doc(doc: &mut Document, dx: i32, dy: i32) {
return;
}
for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy));
+ fn shift_fx_reference(layers: &mut [photocraft_doc::Layer], dx: f64, dy: f64) {
+ for l in layers {
+ if let Some(r) = &mut l.effects.reference {
+ *r = (r.0 + dx, r.1 + dy);
+ }
+ if let LayerContent::Group(g) = &mut l.content {
+ shift_fx_reference(&mut g.children, dx, dy);
+ }
+ }
+ }
+ shift_fx_reference(&mut doc.layers, f64::from(dx), f64::from(dy));
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
ch.surface = translate_surface(&ch.surface, dx, dy);
}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index ef21720cc..5e32d78c2 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -43,6 +43,8 @@ pub fn document(d: &DocState) -> Value {
"revision": d.revision,
"channels": crate::channel_cmds::channels_json(d),
"quickMask": doc.quick_mask.is_some(),
+ "layerComps": doc.layer_comps.iter().map(|c| json!({"id": c.id, "name": c.name})).collect::<Vec<_>>(),
+ "lastAppliedComp": doc.last_applied_comp,
})
}
@@ -74,6 +76,9 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId]) -> Value {
match &l.content {
LayerContent::Group(g) => {
v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected)).collect());
+ if let Some(a) = &g.artboard {
+ v["artboard"] = json!({"rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()], "background": a.background.name(), "preset": a.preset});
+ }
}
LayerContent::Adjustment(a) => {
v["adjustment"] = serde_json::to_value(a).unwrap_or(Value::Null);
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 57262f3d5..54ebb1eed 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -26,7 +26,7 @@ pub fn selected(s: &Session) -> Vec<LayerId> {
/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its
/// selected children), bottom-to-top.
-fn top_level(doc: &Document, ids: &[LayerId]) -> Vec<LayerId> {
+pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec<LayerId> {
let walk = doc.walk();
let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect();
paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect()
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index d8f22160f..f465ddb69 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -25,6 +25,7 @@ pub mod image_cmds;
pub mod paint_cmds;
pub mod pattern_cmds;
pub mod warp_cmds;
+pub mod distort_cmds;
pub mod selection_cmds;
pub mod brush_cmds;
pub mod extra_cmds;
@@ -38,6 +39,8 @@ pub mod prefs;
pub mod snap;
pub mod edit_menu_cmds;
pub mod align_cmds;
+pub mod artboard_cmds;
+pub mod comps_cmds;
use std::sync::Arc;
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index cdebeeead..ca420ce5c 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -186,6 +186,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
enabled: l.effects.enabled,
items: l.effects.items.clone(),
psd_raw: opt_blob(&l.effects.psd_raw, sink),
+ reference: l.effects.reference,
},
label: l.label,
content,
@@ -278,7 +279,7 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
}
fn effects_m(e: &Effects, sink: &mut dyn Sink) -> EffectsM {
- EffectsM { enabled: e.enabled, items: e.items.clone(), psd_raw: opt_blob(&e.psd_raw, sink) }
+ EffectsM { enabled: e.enabled, items: e.items.clone(), psd_raw: opt_blob(&e.psd_raw, sink), reference: e.reference }
}
fn comp_m(c: &LayerComp, sink: &mut dyn Sink) -> LayerCompM {
@@ -375,7 +376,12 @@ impl Loader<'_> {
blend: a.blend,
opacity: a.opacity,
fill_opacity: a.fill_opacity,
- effects: Effects { enabled: a.effects.enabled, items: a.effects.items.clone(), psd_raw: self.opt_blob(&a.effects.psd_raw)? },
+ effects: Effects {
+ enabled: a.effects.enabled,
+ items: a.effects.items.clone(),
+ psd_raw: self.opt_blob(&a.effects.psd_raw)?,
+ reference: a.effects.reference,
+ },
}),
None => None,
};
@@ -530,6 +536,7 @@ impl Loader<'_> {
enabled: m.effects.enabled,
items: m.effects.items.clone(),
psd_raw: self.opt_blob(&m.effects.psd_raw)?,
+ reference: m.effects.reference,
},
label: m.label,
content,
diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs
index 6568457df..40e85f5d2 100644
--- a/crates/format/src/manifest.rs
+++ b/crates/format/src/manifest.rs
@@ -158,6 +158,8 @@ pub struct EffectsM {
pub enabled: bool,
pub items: Vec<Effect>,
pub psd_raw: Option<Hash>,
+ #[serde(default)]
+ pub reference: Option<(f64, f64)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml
index 307546ac0..9cd2c1440 100644
--- a/crates/gpu/Cargo.toml
+++ b/crates/gpu/Cargo.toml
@@ -17,6 +17,10 @@ photocraft-compose = { workspace = true }
wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }
log = { workspace = true }
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+# Effect distance fields are computed in parallel bands.
+rayon = { workspace = true }
+
[dev-dependencies]
wgpu = { version = "30" }
pollster = "1"
diff --git a/crates/gpu/src/bounds.rs b/crates/gpu/src/bounds.rs
new file mode 100644
index 000000000..6ad39c717
--- /dev/null
+++ b/crates/gpu/src/bounds.rs
@@ -0,0 +1,130 @@
+//! Layer bounds exactly as `photocraft-compose` computes them (`layer_bounds`), with the per-tile
+//! content scan cached by copy-on-write tile identity, so an effect layer's region costs a hash
+//! lookup per tile instead of a pixel scan per frame.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, Weak};
+
+use photocraft_doc::{Layer, LayerContent};
+use photocraft_geom::{Rect, TILE_SIZE};
+use photocraft_raster::{Surface, Tile};
+
+struct Entry {
+ tile: Weak<Tile>,
+ /// Content bounds inside the tile (tile-local), for one default pixel.
+ default: Box<[u8]>,
+ bounds: Option<(u16, u16, u16, u16)>,
+}
+
+fn cache() -> &'static Mutex<HashMap<usize, Entry>> {
+ static C: std::sync::OnceLock<Mutex<HashMap<usize, Entry>>> = std::sync::OnceLock::new();
+ C.get_or_init(Default::default)
+}
+
+/// Pixels of `t` that differ from `dp` (tile-local half-open bounds).
+fn scan(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> {
+ let bpp = dp.len();
+ let ts = TILE_SIZE as usize;
+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);
+ for (y, row) in t.bytes().chunks_exact(ts * bpp).enumerate() {
+ let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue };
+ let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0);
+ x0 = x0.min(first);
+ x1 = x1.max(last + 1);
+ y0 = y0.min(y);
+ y1 = y + 1;
+ }
+ (x0 != usize::MAX).then_some((x0 as u16, y0 as u16, x1 as u16, y1 as u16))
+}
+
+/// `Surface::content_bounds`, cached per tile.
+pub fn content_bounds(s: &Surface) -> Rect {
+ if s.tile_count() == 0 {
+ return Rect::EMPTY;
+ }
+ let fmt = s.format();
+ let mut dp = vec![0u8; fmt.bytes_per_pixel()];
+ photocraft_raster::encode_pixel(&fmt, &s.default_pixel(), &mut dp);
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ if c.len() > 1 << 16 {
+ c.retain(|_, e| e.tile.strong_count() > 0);
+ }
+ let mut out = Rect::EMPTY;
+ for (coord, t) in s.tiles() {
+ let key = Arc::as_ptr(t) as usize;
+ let hit = c.get(&key).filter(|e| e.tile.upgrade().is_some_and(|u| Arc::ptr_eq(&u, t)) && *e.default == *dp).map(|e| e.bounds);
+ let b = match hit {
+ Some(b) => b,
+ None => {
+ let b = scan(t, &dp);
+ c.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b });
+ b
+ }
+ };
+ if let Some((x0, y0, x1, y1)) = b {
+ let o = coord.rect();
+ let r = Rect::new(o.x0 + x0 as i32, o.y0 + y0 as i32, o.x0 + x1 as i32, o.y0 + y1 as i32);
+ out = if out.is_empty() { r } else { out.union(&r) };
+ }
+ }
+ out
+}
+
+/// Bounds of a layer's own pixels (union over visible group children; the canvas for fill
+/// layers): `photocraft_compose::layer_bounds`.
+pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect {
+ match &layer.content {
+ LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| {
+ let b = layer_bounds(c, canvas);
+ if b.is_empty() {
+ acc
+ } else if acc.is_empty() {
+ b
+ } else {
+ acc.union(&b)
+ }
+ }),
+ LayerContent::Fill(_) => canvas,
+ _ => layer.surface().map_or(Rect::EMPTY, content_bounds),
+ }
+}
+
+/// The region a layer's effect maps cover: its bounds grown by the effect reach, within the
+/// canvas grown likewise (`photocraft_compose::effect_maps`).
+pub fn effect_region(layer: &Layer, canvas: Rect) -> Rect {
+ let m = photocraft_compose::effects::margin(layer);
+ layer_bounds(layer, canvas).inflate(m).intersect(&canvas.inflate(m))
+}
+
+/// Whether the layer's content is transparent outside its bounds (every surface it draws from
+/// has a transparent default pixel), so its effects can't change pixels outside the effect region.
+pub fn transparent_outside(layer: &Layer) -> bool {
+ match &layer.content {
+ LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).all(transparent_outside),
+ // Fill layers cover the canvas; their region contains it.
+ LayerContent::Fill(_) | LayerContent::Adjustment(_) => true,
+ _ => layer.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::PixelFormat;
+
+ #[test]
+ fn matches_surface_content_bounds() {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ assert_eq!(content_bounds(&s), s.content_bounds());
+ s.fill_rect(Rect::new(10, 300, 40, 700), &[1.0, 0.0, 0.0, 1.0]);
+ s.fill_rect(Rect::new(-50, 5, -3, 9), &[0.0, 0.0, 1.0, 0.5]);
+ assert_eq!(content_bounds(&s), s.content_bounds());
+ // Cached a second time, and after a change.
+ assert_eq!(content_bounds(&s), s.content_bounds());
+ s.fill_rect(Rect::new(600, 600, 601, 601), &[0.0, 1.0, 0.0, 1.0]);
+ assert_eq!(content_bounds(&s), s.content_bounds());
+ let mut g = Surface::with_default(PixelFormat::GRAY8, &[1.0]);
+ g.fill_rect(Rect::new(3, 3, 9, 9), &[0.5]);
+ assert_eq!(content_bounds(&g), g.content_bounds());
+ }
+}
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index 43a9c6376..fa789be86 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -1,7 +1,8 @@
// Photocraft GPU compositor kernels.
//
-// Every pass renders one chunk of the canvas into a straight-alpha RGBA16F accumulator, reading
-// its inputs with `textureLoad` at the same pixel. The functions mirror `photocraft-compose`
+// Every pass renders one chunk of the canvas into a straight-alpha RGBA32F accumulator, reading
+// its inputs with `textureLoad` at the same pixel. Effect-map kernels (`fs_m*`) render
+// single-channel maps over a layer's effect region instead (`chunk` = the region). The functions mirror `photocraft-compose`
// (the CPU reference) operation for operation; keep them in sync.
struct Chunk {
@@ -27,12 +28,22 @@ struct Op {
p1: vec4<f32>,
p2: vec4<f32>,
p3: vec4<f32>,
+ map_origin: vec2<i32>,
+ map_size: vec2<i32>,
+ p4: vec4<f32>,
};
const F_MASK: u32 = 1u; // layer has an enabled mask
const F_MASK_TEX: u32 = 2u; // mask pixels live in `mask_tex`
const F_TEX: u32 = 4u; // layer pixels live in `layer_tex`
const F_GRADIENT: u32 = 8u; // gradient fill (stops in `lut_tex`)
+const F_KNOCKOUT: u32 = 16u; // effect paint: the layer knocks out the coverage (drop shadow)
+const F_UNDER: u32 = 32u; // effect paint: slide beneath A (outside stroke)
+const F_VECTOR: u32 = 64u; // effect paint: shape layer (outside stroke never inside)
+const F_ATOP: u32 = 128u; // effect merge: clipped layer over an opaque base
+const F_GATE: u32 = 256u; // effect paint: coverage only inside the layer's shape
+const F_REL: u32 = 512u; // effect paint: coverage relative to the layer's alpha
+const F_STROKE_OUT: u32 = 1024u; // effect paint: outside stroke band
@group(0) @binding(0) var<uniform> chunk: Chunk;
@group(0) @binding(1) var<uniform> op: Op;
@@ -41,6 +52,9 @@ const F_GRADIENT: u32 = 8u; // gradient fill (stops in `lut_tex`)
@group(1) @binding(2) var layer_tex: texture_2d<f32>;
@group(1) @binding(3) var mask_tex: texture_2d<f32>;
@group(1) @binding(4) var lut_tex: texture_2d<f32>;
+@group(1) @binding(5) var tex_c: texture_2d<f32>;
+@group(1) @binding(6) var map_tex: texture_2d<f32>;
+@group(1) @binding(7) var pat_tex: texture_2d<f32>;
struct VOut { @builtin(position) pos: vec4<f32> };
@@ -464,11 +478,12 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
// ---- fills ----------------------------------------------------------------------------------
fn gradient_t(d: vec2<i32>) -> f32 {
- // p0 = (angle°, scale, reverse, style), p1 = canvas (x0, y0, w, h)
+ // p0 = (angle°, scale, reverse, style), p1 = frame (x0, y0, w, h)
let w = max(op.p1.z, 1.0);
let h = max(op.p1.w, 1.0);
- let cx = op.p1.x + w / 2.0;
- let cy = op.p1.y + h / 2.0;
+ // p2.xy: centre offset as a fraction of the bounds (gradient overlays; 0 for fills).
+ let cx = op.p1.x + w / 2.0 + op.p2.x * w;
+ let cy = op.p1.y + h / 2.0 + op.p2.y * h;
let a = radians(op.p0.x);
let s = sin(a);
let c = cos(a);
@@ -580,3 +595,280 @@ fn fs_lerp(in: VOut) -> @location(0) vec4<f32> {
let k = op.opacity * mask_value(doc_px(p));
return a + (b - a) * k;
}
+
+// ---- layer effects (compose::effects::composite_with_effects) -------------------------------
+
+const INSIDE_EPS: f32 = 0.5 / 255.0;
+
+// Effect map value at document pixel `d` (`outside` beyond the map's region, like
+// `FxMaps::crop`).
+fn map_value(d: vec2<i32>, outside: f32) -> f32 {
+ let q = d - op.map_origin;
+ if (inside(q, op.map_size)) {
+ return textureLoad(map_tex, q, 0).r;
+ }
+ return outside;
+}
+
+fn wrap(i: i32, n: i32) -> i32 {
+ return ((i % n) + n) % n;
+}
+
+// compose::pattern::Tile::sample through Placement::map. p3 = (origin, cos, sin),
+// p4 = (1 / scale, tile w, tile h); `pat_tex` holds premultiplied RGBA.
+fn pattern_sample(d: vec2<i32>) -> vec4<f32> {
+ let dx = f32(d.x) + 0.5 - op.p3.x;
+ let dy = f32(d.y) + 0.5 - op.p3.y;
+ let c = op.p3.z;
+ let s = op.p3.w;
+ let u = (dx * c - dy * s) * op.p4.x - 0.5;
+ let v = (dx * s + dy * c) * op.p4.x - 0.5;
+ let x0 = floor(u);
+ let y0 = floor(v);
+ let fx = u - x0;
+ let fy = v - y0;
+ let tw = i32(op.p4.y);
+ let th = i32(op.p4.z);
+ let ix = i32(x0);
+ let iy = i32(y0);
+ var acc = vec4(0.0);
+ let wy = array<f32, 2>(1.0 - fy, fy);
+ let wx = array<f32, 2>(1.0 - fx, fx);
+ for (var j = 0; j < 2; j++) {
+ if (wy[j] == 0.0) { continue; }
+ for (var i = 0; i < 2; i++) {
+ if (wx[i] == 0.0) { continue; }
+ acc += textureLoad(pat_tex, vec2(wrap(ix + i, tw), wrap(iy + j, th)), 0) * (wx[i] * wy[j]);
+ }
+ }
+ if (acc.a <= 0.0) { return vec4(0.0); }
+ return vec4(acc.rgb / acc.a, min(acc.a, 1.0));
+}
+
+// Effect paint colour at `d`: p2.z = 0 solid (`color`), 1 gradient (stops in `lut_tex`),
+// 2 pattern.
+fn fx_color(d: vec2<i32>) -> vec4<f32> {
+ let kind = i32(op.p2.z);
+ if (kind == 1) {
+ let t = gradient_t(d);
+ return vec4(lut(0, t), lut(1, t), lut(2, t), lut(3, t));
+ }
+ if (kind == 2) {
+ return pattern_sample(d);
+ }
+ return op.color;
+}
+
+// Effect chain steps (`kind`): 0 A at `opacity` × alpha; 1 an opaque copy of A (a clipping base
+// for clipped layers' effects); 2 A's colour with alpha `opacity` inside B's shape (the layer
+// before its interior effects); 3 A with its alpha × B's alpha (the shape's own alpha).
+@fragment
+fn fs_fxinit(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let c = textureLoad(tex_a, p, 0);
+ switch op.kind {
+ case 1: { return vec4(c.rgb, 1.0); }
+ case 2: { return vec4(c.rgb, select(0.0, op.opacity, c.a > INSIDE_EPS)); }
+ case 3: { return vec4(c.rgb, c.a * min(textureLoad(tex_b, p, 0).a, 1.0)); }
+ default: { return vec4(c.rgb, c.a * op.opacity); }
+ }
+}
+
+// effects::paint: composite `colour × coverage × opacity` into A. B is the layer (its alpha `a`
+// is the effect shape). Coverage `kind`: 0 the effect map, 1 full; then F_KNOCKOUT m × (1 − a),
+// F_GATE inside ? m : 0, F_REL inside ? min(m / a, 1) : 0, F_STROKE_OUT inside ? (vector ? 0 : 1)
+// : m. F_UNDER paints beneath A (outside strokes).
+@fragment
+fn fs_fxpaint(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let d = doc_px(p);
+ let dst = textureLoad(tex_a, p, 0);
+ let a = textureLoad(tex_b, p, 0).a;
+ let inside_shape = a > INSIDE_EPS;
+ var m = 1.0;
+ if (op.kind == 0) { m = map_value(d, op.p2.w); }
+ if ((op.flags & F_KNOCKOUT) != 0u) { m = m * (1.0 - a); }
+ if ((op.flags & F_GATE) != 0u && !inside_shape) { m = 0.0; }
+ if ((op.flags & F_REL) != 0u) {
+ if (inside_shape) { m = min(m / a, 1.0); } else { m = 0.0; }
+ }
+ if ((op.flags & F_STROKE_OUT) != 0u && inside_shape) {
+ m = select(1.0, 0.0, (op.flags & F_VECTOR) != 0u);
+ }
+ let k = m * op.opacity;
+ if ((op.flags & F_UNDER) != 0u) {
+ // Painted into a transparent buffer, then A goes over it.
+ var under = vec4(0.0);
+ if (k > 0.0) {
+ let c = fx_color(d);
+ under = composite(M_NORMAL, vec4(0.0), vec4(c.rgb, c.a * k), 1.0);
+ }
+ return composite(M_NORMAL, under, dst, 1.0);
+ }
+ if (k <= 0.0) { return dst; }
+ let c = fx_color(d);
+ return composite(op.mode, dst, vec4(c.rgb, c.a * k), 1.0);
+}
+
+fn mix_premul(a: vec4<f32>, b: vec4<f32>, k: f32) -> vec4<f32> {
+ let alpha = a.a + (b.a - a.a) * k;
+ if (alpha <= 0.0) { return vec4(0.0); }
+ return vec4((a.rgb * a.a + (b.rgb * b.a - a.rgb * a.a) * k) / alpha, alpha);
+}
+
+// The layer with its interior effects (B) over the exterior result (A) in the layer's mode, then
+// layer opacity against the backdrop C. F_ATOP: C is a clipping base: effects were painted over
+// it as if opaque and the base keeps its alpha.
+@fragment
+fn fs_fxmerge(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ var w = textureLoad(tex_a, p, 0);
+ let l = textureLoad(tex_b, p, 0);
+ let c = textureLoad(tex_c, p, 0);
+ if (l.a > 0.0) { w = composite(op.mode, w, l, 1.0); }
+ let atop = (op.flags & F_ATOP) != 0u;
+ var before = c;
+ if (atop) { before = vec4(c.rgb, 1.0); }
+ let o = mix_premul(before, w, op.opacity);
+ if (atop) {
+ if (c.a > 0.0) { return vec4(o.rgb, c.a); }
+ return c;
+ }
+ return o;
+}
+
+// ---- effect maps (compose::effects::build_maps) ----------------------------------------------
+//
+// Targets cover the effect region (`chunk` = region origin and size); reads outside it return 0,
+// like `Map::get`. Each kernel mirrors one step of the CPU map builders. The shape and its
+// distance fields come from the CPU (`compose::layer_shape`, `compose::effects::distance_field`).
+
+fn ra(p: vec2<i32>) -> f32 {
+ if (inside(p, chunk.size)) { return textureLoad(tex_a, p, 0).r; }
+ return 0.0;
+}
+fn mout(v: f32) -> vec4<f32> { return vec4(v, 0.0, 0.0, 1.0); }
+
+// Map::shifted by whole pixels: p0 = (dx, dy, outside, invert (1 - a before shifting)).
+@fragment
+fn fs_mshift(in: VOut) -> @location(0) vec4<f32> {
+ let s = local(in.pos) - vec2<i32>(i32(op.p0.x), i32(op.p0.y));
+ if (!inside(s, chunk.size)) { return mout(op.p0.z); }
+ var v = textureLoad(tex_a, s, 0).r;
+ if (op.p0.w > 0.5) { v = 1.0 - v; }
+ return mout(v);
+}
+
+// effects::dilate: max(A, clamp(r + 0.5 - dist_outside)), B = distances, p0.x = r.
+@fragment
+fn fs_mdilate(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let a = textureLoad(tex_a, p, 0).r;
+ let d = textureLoad(tex_b, p, 0).r;
+ return mout(max(a, clamp(op.p0.x + 0.5 - d, 0.0, 1.0)));
+}
+
+// effects::blur, one separable pass: p0 = (vertical, radius); weights in LUT row 0; zero outside
+// the region.
+@fragment
+fn fs_mblur(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let r = i32(op.p0.y);
+ var step = vec2(1, 0);
+ var n = chunk.size.x;
+ var c = p.x;
+ if (op.p0.x > 0.5) {
+ step = vec2(0, 1);
+ n = chunk.size.y;
+ c = p.y;
+ }
+ var acc = 0.0;
+ for (var k = 0; k <= 2 * r; k++) {
+ let i = c + k - r;
+ if (i >= 0 && i < n) {
+ acc += textureLoad(tex_a, p + step * (k - r), 0).r * textureLoad(lut_tex, vec2(k, 0), 0).r;
+ }
+ }
+ return mout(acc);
+}
+
+// Precise glow from a distance map: p0 = (solid, soft, invert).
+@fragment
+fn fs_mglow(in: VOut) -> @location(0) vec4<f32> {
+ let d = textureLoad(tex_a, local(in.pos), 0).r;
+ var m = clamp(1.0 - (d - op.p0.x) / op.p0.y, 0.0, 1.0);
+ if (d <= op.p0.x) { m = 1.0; }
+ if (op.p0.z > 0.5) { m = 1.0 - m; }
+ return mout(m);
+}
+
+// Last step of a coverage map: p0 = (|A - B| (satin), 1 - v, contour (LUT row 0), × shape
+// (`layer_tex`)).
+@fragment
+fn fs_mfinish(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ var v = textureLoad(tex_a, p, 0).r;
+ if (op.p0.x > 0.5) { v = abs(v - textureLoad(tex_b, p, 0).r); }
+ if (op.p0.y > 0.5) { v = 1.0 - v; }
+ if (op.p0.z > 0.5) { v = lut(0, v); }
+ if (op.p0.w > 0.5) { v = v * textureLoad(layer_tex, p, 0).r; }
+ return mout(v);
+}
+
+// Bevel height profile from A = dist_inside, B = dist_outside: p0 = (style (0 outer, 1 emboss,
+// 2 inner), size); the smooth (quarter sine) rounding comes from LUT row 0.
+@fragment
+fn fs_mbevelh(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let din = textureLoad(tex_a, p, 0).r;
+ let dout = textureLoad(tex_b, p, 0).r;
+ let size = op.p0.y;
+ var h: f32;
+ switch i32(op.p0.x) {
+ case 0: { h = 1.0 - clamp(dout / size, 0.0, 1.0); }
+ case 1: {
+ if (din > 0.0) {
+ h = 0.5 + 0.5 * clamp(din / (size / 2.0), 0.0, 1.0);
+ } else {
+ h = 0.5 - 0.5 * clamp(dout / (size / 2.0), 0.0, 1.0);
+ }
+ }
+ default: { h = clamp(din / size, 0.0, 1.0); }
+ }
+ return mout(lut(0, h));
+}
+
+// Bevel shading of the blurred height map A over shape S (`layer_tex`): p0 = light vector,
+// sin(altitude); p1 = (depth, outer, shadow (else highlight), contour (LUT row 0)).
+@fragment
+fn fs_mbevelshade(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let depth = op.p1.x;
+ let gx = (ra(p + vec2(1, 0)) - ra(p - vec2(1, 0))) * 0.5 * depth;
+ let gy = (ra(p + vec2(0, 1)) - ra(p - vec2(0, 1))) * 0.5 * depth;
+ let n = vec3(-gx, -gy, 1.0);
+ let len = sqrt(n.x * n.x + n.y * n.y + 1.0);
+ let shade = (n.x * op.p0.x + n.y * op.p0.y + n.z * op.p0.z) / len;
+ let se = op.p0.w;
+ let s = textureLoad(layer_tex, p, 0).r;
+ var region = s;
+ if (op.p1.y > 0.5) {
+ region = (1.0 - s) * select(0.0, 1.0, textureLoad(tex_a, p, 0).r > 0.0);
+ }
+ let k = shade - se;
+ var v = 0.0;
+ if (op.p1.z > 0.5) {
+ if (k <= 0.0) { v = clamp(-k / max(se, 1e-3), 0.0, 1.0) * region; }
+ } else if (k > 0.0) {
+ v = clamp(k / max(1.0 - se, 1e-3), 0.0, 1.0) * region;
+ }
+ if (op.p1.w > 0.5) { v = lut(0, v); }
+ return mout(v);
+}
+
+// Stroke band from a distance map: clamp(width + 0.5 - d), p0.x = width.
+@fragment
+fn fs_mstroke(in: VOut) -> @location(0) vec4<f32> {
+ let d = textureLoad(tex_a, local(in.pos), 0).r;
+ return mout(clamp(op.p0.x + 0.5 - d, 0.0, 1.0));
+}
diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs
new file mode 100644
index 000000000..73de9ae35
--- /dev/null
+++ b/crates/gpu/src/fx.rs
@@ -0,0 +1,631 @@
+//! Effect maps on the GPU (`photocraft_compose::effects::build_maps`).
+//!
+//! Every enabled effect of a layer becomes a small *map program*: a chain of single-channel
+//! fragment passes over the layer's effect region (shift, dilate, separable Gaussian blur, glow
+//! ramp, bevel height and shading, contour, stroke band), each mirroring one step of the CPU
+//! builders. Programs are pure functions of the effect settings and the global light.
+//!
+//! Inputs come from the CPU, computed by compose itself so they match it bit for bit: the
+//! layer's **shape** (`compose::layer_shape`) and the **distance fields** of it that the effects
+//! use (`compose::effects::distance_field`, an inherently sequential transform). Both are
+//! computed per layer state and uploaded once, and only where the layer changed:
+//!
+//! - damage is the union of the layer's tiles whose copy-on-write `Arc` changed, so a brush dab
+//! recomputes one 256² tile of shape;
+//! - a distance field is exact up to the distance its effects can use (beyond it every consumer
+//! saturates), so it is recomputed over the damage grown by that reach, from a window grown by
+//! the reach again; large windows split into bands computed in parallel;
+//! - each program re-runs only over the damage grown by its own reach, and only for effects
+//! whose settings changed; an unrelated edit (another layer, an adjustment, the effect's colour
+//! or opacity) reuses everything.
+
+use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use photocraft_compose::effects::FieldKind;
+use photocraft_doc::{BevelStyle, Contour, Effect, GlobalLight, GlowSource, GlowTechnique, Layer, LayerContent};
+use photocraft_geom::{Rect, TileCoord};
+use photocraft_raster::{Surface, Tile};
+
+use crate::plan::{Kernel, stroke_widths};
+
+/// Input of a map stage.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) enum In {
+ /// The layer's alpha over the region.
+ Shape,
+ /// A distance field of the shape.
+ Field(FieldKind),
+ /// Output of stage `n`.
+ Val(usize),
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct Stage {
+ pub kernel: Kernel,
+ pub a: Option<In>,
+ pub b: Option<In>,
+ /// Bound as `layer_tex` (the shape for `× shape` steps).
+ pub s: Option<In>,
+ /// LUT row 0 (blur weights, contour, sine profile).
+ pub lut: Option<Arc<Vec<f32>>>,
+ pub p0: [f32; 4],
+ pub p1: [f32; 4],
+ /// How far (px) the stage reads from its inputs around the output pixel.
+ pub radius: i32,
+ /// Final map index this stage writes (else a temporary).
+ pub out: Option<usize>,
+}
+
+/// The passes building one effect's maps.
+#[derive(Clone, Debug)]
+pub(crate) struct MapProgram {
+ /// Identity of the program (settings that change the maps; not colours or opacities).
+ pub key: u64,
+ pub maps: usize,
+ pub stages: Vec<Stage>,
+ /// Distance fields read, with the distance up to which each must be exact.
+ pub fields: Vec<(FieldKind, i32)>,
+}
+
+/// How far a field value depends on the shape, for a field exact up to `reach`.
+pub(crate) fn field_radius(kind: FieldKind, reach: i32) -> i32 {
+ // The nearest seed lies within the reach; local coverage reads one more pixel.
+ reach + 2 + i32::from(kind == FieldKind::StrokeOutsideVector)
+}
+
+impl MapProgram {
+ fn empty() -> Self {
+ MapProgram { key: 0, maps: 0, stages: Vec::new(), fields: Vec::new() }
+ }
+
+ /// Per-stage output window for a shape damage rect `d` (all inside `region`): what each stage
+ /// must recompute so every final map is exact over `d` grown by its reach. `field_reach`:
+ /// the reach each field was computed with.
+ pub fn windows(&self, d: Rect, region: Rect, field_reach: &dyn Fn(FieldKind) -> i32) -> Vec<Rect> {
+ let n = self.stages.len();
+ let reach_of = |reach: &[i32], i: Option<In>| match i {
+ Some(In::Val(k)) => reach[k],
+ Some(In::Field(f)) => field_radius(f, field_reach(f)),
+ _ => 0,
+ };
+ let mut reach = vec![0i32; n];
+ for (i, s) in self.stages.iter().enumerate() {
+ reach[i] = reach_of(&reach, s.a).max(reach_of(&reach, s.b)).max(reach_of(&reach, s.s)) + s.radius;
+ }
+ let mut need = vec![Rect::EMPTY; n];
+ for (i, s) in self.stages.iter().enumerate() {
+ if s.out.is_some() {
+ need[i] = d.inflate(reach[i]).intersect(&region);
+ }
+ }
+ for i in (0..n).rev() {
+ let w = need[i];
+ if w.is_empty() {
+ continue;
+ }
+ let s = &self.stages[i];
+ for inp in [s.a, s.b, s.s].into_iter().flatten() {
+ if let In::Val(k) = inp {
+ let grown = w.inflate(s.radius).intersect(&region);
+ need[k] = if need[k].is_empty() { grown } else { need[k].union(&grown) };
+ }
+ }
+ }
+ need
+ }
+
+ /// Physical temporary index per stage (None for final maps), reusing temporaries after
+ /// their last read; returns (assignment, temporaries needed).
+ pub fn temps(&self) -> (Vec<Option<usize>>, usize) {
+ let n = self.stages.len();
+ let mut last_use = vec![0usize; n];
+ for (i, s) in self.stages.iter().enumerate() {
+ for inp in [s.a, s.b, s.s].into_iter().flatten() {
+ if let In::Val(k) = inp {
+ last_use[k] = last_use[k].max(i);
+ }
+ }
+ }
+ let mut free: Vec<usize> = Vec::new();
+ let mut count = 0;
+ let mut out = vec![None; n];
+ let mut held: Vec<(usize, usize)> = Vec::new();
+ for i in 0..n {
+ // Release temporaries whose last reader was before this stage.
+ held.retain(|&(stage, t)| {
+ if last_use[stage] < i {
+ free.push(t);
+ false
+ } else {
+ true
+ }
+ });
+ if self.stages[i].out.is_some() {
+ continue;
+ }
+ let t = free.pop().unwrap_or_else(|| {
+ count += 1;
+ count - 1
+ });
+ out[i] = Some(t);
+ held.push((i, t));
+ }
+ (out, count)
+ }
+}
+
+struct B {
+ stages: Vec<Stage>,
+ fields: Vec<(FieldKind, i32)>,
+}
+
+fn stage(kernel: Kernel, a: Option<In>, b: Option<In>, p0: [f32; 4], radius: i32) -> Stage {
+ Stage { kernel, a, b, s: None, lut: None, p0, p1: [0.0; 4], radius, out: None }
+}
+
+impl B {
+ fn push(&mut self, s: Stage) -> In {
+ self.stages.push(s);
+ In::Val(self.stages.len() - 1)
+ }
+ fn field(&mut self, kind: FieldKind, width: f32) -> In {
+ self.fields.push((kind, reach_for(width)));
+ In::Field(kind)
+ }
+ /// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map
+ /// are skipped.
+ fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In {
+ if dx == 0.0 && dy == 0.0 && !invert {
+ return src;
+ }
+ let r = dx.abs().max(dy.abs()) as i32;
+ self.push(stage(Kernel::MShift, Some(src), None, [dx, dy, outside, f32::from(u8::from(invert))], r))
+ }
+ /// `dilate(src, r)` given `dist_outside(src)`.
+ fn dilate(&mut self, src: In, dist: In, r: f32) -> In {
+ self.push(stage(Kernel::MDilate, Some(src), Some(dist), [r, 0.0, 0.0, 0.0], 0))
+ }
+ fn blur(&mut self, src: In, size: f32) -> In {
+ let Some((r, w)) = blur_kernel(size) else { return src };
+ let w = Arc::new(w);
+ let mut h = stage(Kernel::MBlur, Some(src), None, [0.0, r as f32, 0.0, 0.0], r);
+ h.lut = Some(w.clone());
+ let h = self.push(h);
+ let mut v = stage(Kernel::MBlur, Some(h), None, [1.0, r as f32, 0.0, 0.0], r);
+ v.lut = Some(w);
+ self.push(v)
+ }
+ fn finish(&mut self, a: In, b: Option<In>, invert: bool, contour: &Contour, times_shape: bool, out: usize) {
+ let lut = contour_lut(contour);
+ let flag = |v: bool| f32::from(u8::from(v));
+ let mut s = stage(Kernel::MFinish, Some(a), b, [flag(b.is_some()), flag(invert), flag(lut.is_some()), flag(times_shape)], 0);
+ s.lut = lut.map(Arc::new);
+ if times_shape {
+ s.s = Some(In::Shape);
+ }
+ s.out = Some(out);
+ self.stages.push(s);
+ }
+}
+
+/// Distance up to which a field must be exact for a band / dilation of width `w`
+/// (`clamp(w + 0.5 - d)`, with `d` up to 1.5 px beyond the pixel distance).
+fn reach_for(w: f32) -> i32 {
+ (w.max(0.0).min(photocraft_compose::effects::MAX_REACH)).ceil() as i32 + 2
+}
+
+/// `compose::effects::blur`'s kernel: (radius, normalised weights), or None below sigma 0.2.
+pub(crate) fn blur_kernel(size: f32) -> Option<(i32, Vec<f32>)> {
+ // compose::effects::sigma_for
+ let sigma = size * 0.4;
+ if sigma < 0.2 || !sigma.is_finite() {
+ return None;
+ }
+ let r = (sigma * 3.0).ceil() as i64;
+ let kernel: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
+ let sum: f32 = kernel.iter().sum();
+ Some((r as i32, kernel.iter().map(|k| k / sum).collect()))
+}
+
+fn contour_lut(c: &Contour) -> Option<Vec<f32>> {
+ match c {
+ Contour::Linear => None,
+ Contour::Custom { points, .. } => Some(photocraft_compose::adjust::curve_lut(points)),
+ }
+}
+
+/// `compose::effects::offset`: shadow offset away from the light, whole pixels.
+fn offset(angle: f32, distance: f32) -> (f32, f32) {
+ let a = angle.to_radians();
+ ((-a.cos() * distance).round(), (a.sin() * distance).round())
+}
+
+fn sine_lut() -> Arc<Vec<f32>> {
+ static L: std::sync::OnceLock<Arc<Vec<f32>>> = std::sync::OnceLock::new();
+ L.get_or_init(|| Arc::new((0..4096).map(|k| (k as f32 / 4095.0 * std::f32::consts::FRAC_PI_2).sin()).collect())).clone()
+}
+
+/// The map program of one enabled effect (`build_maps`).
+pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> MapProgram {
+ let mut b = B { stages: Vec::new(), fields: Vec::new() };
+ let maps = match e {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => {
+ // shadow_map
+ let inner = matches!(e, Effect::InnerShadow(_));
+ let angle = if s.use_global_light { light.angle } else { s.angle };
+ let (dx, dy) = offset(angle, s.distance);
+ let src = b.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner);
+ let r = s.size * s.spread;
+ let mut m = src;
+ if r > 0.0 {
+ // dist_outside of the shifted map is the shifted field (integer offsets; shifted-in
+ // pixels are far away for a drop shadow, inside for an inner shadow).
+ let f = b.field(if inner { FieldKind::OutsideInverse } else { FieldKind::Outside }, r);
+ let d = if dx == 0.0 && dy == 0.0 { f } else { b.push(stage(Kernel::MShift, Some(f), None, [dx, dy, if inner { -0.5 } else { 1e10 }, 0.0], dx.abs().max(dy.abs()) as i32)) };
+ m = b.dilate(src, d, r);
+ }
+ let m = b.blur(m, s.size * (1.0 - s.spread));
+ b.finish(m, None, false, &s.contour, inner, 0);
+ 1
+ }
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => {
+ // glow_map
+ let inner = matches!(e, Effect::InnerGlow(_));
+ let edge = inner && g.source == GlowSource::Edge;
+ let center = inner && g.source == GlowSource::Center;
+ match g.technique {
+ GlowTechnique::Precise => {
+ let d = b.field(if edge { FieldKind::Inside } else { FieldKind::Outside }, g.size);
+ let solid = g.size * g.spread;
+ let soft = (g.size - solid).max(1e-3);
+ let m = b.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, f32::from(u8::from(center)), 0.0], 0));
+ b.finish(m, None, false, &g.contour, inner, 0);
+ }
+ GlowTechnique::Softer => {
+ // Inner glows (edge, and centre as 1 - the edge result) spread 1 - alpha.
+ let src = if inner { b.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape };
+ let r = g.size * g.spread;
+ let mut m = src;
+ if r > 0.0 {
+ let d = b.field(if inner { FieldKind::OutsideInverse } else { FieldKind::Outside }, r);
+ m = b.dilate(src, d, r);
+ }
+ let m = b.blur(m, g.size * (1.0 - g.spread));
+ b.finish(m, None, center, &g.contour, inner, 0);
+ }
+ }
+ 1
+ }
+ Effect::Satin(s) => {
+ // satin_map
+ let (dx, dy) = offset(s.angle, s.distance);
+ let a = b.shift(In::Shape, dx, dy, 0.0, false);
+ let a = b.blur(a, s.size);
+ let c = b.shift(In::Shape, -dx, -dy, 0.0, false);
+ let c = b.blur(c, s.size);
+ b.finish(a, Some(c), s.invert, &s.contour, true, 0);
+ 1
+ }
+ Effect::BevelEmboss(bv) => {
+ // bevel_maps
+ let size = bv.size.max(1.0);
+ let din = b.field(FieldKind::Inside, size);
+ let dout = b.field(FieldKind::Outside, size);
+ let style = match bv.style {
+ BevelStyle::OuterBevel => 0.0,
+ BevelStyle::Emboss | BevelStyle::PillowEmboss => 1.0,
+ _ => 2.0,
+ };
+ let mut h = stage(Kernel::MBevelH, Some(din), Some(dout), [style, size, 0.0, 0.0], 0);
+ h.lut = Some(sine_lut());
+ let h = b.push(h);
+ let h = b.blur(h, bv.soften.max(1.0));
+ let (angle, altitude) = if bv.use_global_light { (light.angle, light.altitude) } else { (bv.angle, bv.altitude) };
+ let (sa, ca) = angle.to_radians().sin_cos();
+ let (se, ce) = altitude.to_radians().sin_cos();
+ let depth = bv.depth * size * if bv.up { 1.0 } else { -1.0 };
+ let lut = contour_lut(&bv.gloss_contour).map(Arc::new);
+ for (which, out) in [(0.0, 0), (1.0, 1)] {
+ let mut s = stage(Kernel::MBevelShade, Some(h), None, [ca * ce, -sa * ce, se, se], 1);
+ s.p1 = [depth, f32::from(u8::from(style == 0.0)), which, f32::from(u8::from(lut.is_some()))];
+ s.lut = lut.clone();
+ s.s = Some(In::Shape);
+ s.out = Some(out);
+ b.stages.push(s);
+ }
+ 2
+ }
+ Effect::Stroke(st) => {
+ // composite_with_effects' stroke bands (maps 0 outside, 1 inside)
+ let (in_w, out_w) = stroke_widths(st);
+ if out_w > 0.0 {
+ let d = b.field(if vector_shape { FieldKind::StrokeOutsideVector } else { FieldKind::StrokeOutside }, out_w);
+ let mut s = stage(Kernel::MStroke, Some(d), None, [out_w, 0.0, 0.0, 0.0], 0);
+ s.out = Some(0);
+ b.stages.push(s);
+ }
+ if in_w > 0.0 {
+ let d = b.field(FieldKind::StrokeInside, in_w);
+ let mut s = stage(Kernel::MStroke, Some(d), None, [in_w, 0.0, 0.0, 0.0], 0);
+ s.out = Some(1);
+ b.stages.push(s);
+ }
+ 2
+ }
+ Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(),
+ };
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ for s in &b.stages {
+ (format!("{:?}", s.kernel), s.a, s.b, s.s, s.radius, s.out).hash(&mut h);
+ for v in s.p0.iter().chain(&s.p1) {
+ v.to_bits().hash(&mut h);
+ }
+ if let Some(l) = &s.lut {
+ for v in l.iter() {
+ v.to_bits().hash(&mut h);
+ }
+ }
+ }
+ (maps, &b.fields).hash(&mut h);
+ MapProgram { key: h.finish() | 1, maps, stages: b.stages, fields: b.fields }
+}
+
+// ---------------------------------------------------------------------------------------------
+// CPU inputs: shape and distance fields
+
+/// Row-major crop of the region-sized `shape` to `r` (inside `region`).
+fn crop(shape: &[f32], region: Rect, r: Rect) -> Vec<f32> {
+ let sw = region.width() as usize;
+ let mut out = Vec::with_capacity(r.width() as usize * r.height() as usize);
+ for y in r.y0..r.y1 {
+ let o = (y - region.y0) as usize * sw + (r.x0 - region.x0) as usize;
+ out.extend_from_slice(&shape[o..o + r.width() as usize]);
+ }
+ out
+}
+
+/// Rows `[y0, y1)` of `r` split into bands of about `rows`.
+fn bands(r: Rect, rows: i32) -> Vec<Rect> {
+ let mut out = Vec::new();
+ let mut y = r.y0;
+ while y < r.y1 {
+ out.push(Rect::new(r.x0, y, r.x1, (y + rows).min(r.y1)));
+ y += rows;
+ }
+ out
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn par_map<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync + Send) -> Vec<R> {
+ use rayon::prelude::*;
+ items.into_par_iter().map(f).collect()
+}
+
+#[cfg(target_arch = "wasm32")]
+fn par_map<T, R>(items: Vec<T>, f: impl Fn(T) -> R) -> Vec<R> {
+ items.into_iter().map(f).collect()
+}
+
+/// Band height for parallel field / shape computation.
+const BAND: i32 = 128;
+
+/// Field `kind` (exact up to `reach`) over `out` (inside `region`), computed from the
+/// region-sized `shape`. Values within the reach depend only on the shape within
+/// [`field_radius`], so each band is computed from a window grown by it.
+pub(crate) fn field(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect) -> Vec<f32> {
+ let halo = field_radius(kind, reach) + 1;
+ let parts = par_map(bands(out, BAND.max(halo)), |band| {
+ let win = band.inflate(halo).intersect(&region);
+ let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize);
+ crop(&f, win, band)
+ });
+ parts.concat()
+}
+
+/// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands.
+pub(crate) fn shape(doc: &photocraft_doc::Document, layer: &Layer, r: Rect) -> Vec<f32> {
+ if r.is_empty() {
+ return Vec::new();
+ }
+ par_map(bands(r, BAND), |band| photocraft_compose::layer_shape(doc, layer, band)).concat()
+}
+
+/// Write `v` (row-major over `r`) into the region-sized `shape`.
+pub(crate) fn paste(shape: &mut [f32], region: Rect, r: Rect, v: &[f32]) {
+ let sw = region.width() as usize;
+ let w = r.width() as usize;
+ for (row, src) in v.chunks_exact(w).enumerate() {
+ let o = (r.y0 - region.y0) as usize * sw + row * sw + (r.x0 - region.x0) as usize;
+ shape[o..o + w].copy_from_slice(src);
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Shape identity and damage
+
+pub(crate) type Tiles = HashMap<TileCoord, Arc<Tile>>;
+
+pub(crate) fn snapshot(s: &Surface) -> Tiles {
+ s.tiles().map(|(c, t)| (*c, t.clone())).collect()
+}
+
+/// Union of the tiles that differ between `old` and `s`.
+pub(crate) fn damage(old: &Tiles, s: &Surface) -> Rect {
+ let mut d = Rect::EMPTY;
+ let mut add = |r: Rect| d = if d.is_empty() { r } else { d.union(&r) };
+ for (c, t) in s.tiles() {
+ if old.get(c).is_none_or(|o| !Arc::ptr_eq(o, t)) {
+ add(c.rect());
+ }
+ }
+ for c in old.keys() {
+ if s.tile(*c).is_none() {
+ add(c.rect());
+ }
+ }
+ d
+}
+
+/// The surfaces a non-group layer's shape is read from: (content, mask).
+pub(crate) fn shape_sources(layer: &Layer) -> (Option<&Surface>, Option<&Surface>) {
+ let content = match &layer.content {
+ LayerContent::Fill(f) => layer.fill_cache.as_ref().filter(|c| c.fill == *f).map(|c| &c.surface),
+ _ => layer.surface(),
+ };
+ let mask = layer.mask.as_ref().filter(|m| m.enabled).map(|m| &m.surface);
+ (content, mask)
+}
+
+/// Everything a non-group layer's shape depends on except tile contents.
+pub(crate) fn shape_key(layer: &Layer, canvas: Rect, region: Rect) -> u64 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ layer.id.0.hash(&mut h);
+ (region.x0, region.y0, region.x1, region.y1).hash(&mut h);
+ let (content, mask) = shape_sources(layer);
+ match &layer.content {
+ LayerContent::Fill(f) => {
+ format!("{f:?}").hash(&mut h);
+ let fr = photocraft_compose::fill_frame(layer, canvas);
+ (fr.x0, fr.y0, fr.x1, fr.y1, content.is_some()).hash(&mut h);
+ }
+ other => std::mem::discriminant(other).hash(&mut h),
+ }
+ for s in [content, mask].into_iter().flatten() {
+ format!("{:?}{:?}", s.format(), s.default_pixel()).hash(&mut h);
+ }
+ if let Some(m) = &layer.mask {
+ (m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(&mut h);
+ }
+ format!("{:?}", layer.vector_mask).hash(&mut h);
+ h.finish()
+}
+
+/// Deep identity of a group (children, their pixels by tile pointer, settings).
+pub(crate) fn group_key(layer: &Layer, region: Rect, light: &GlobalLight) -> u64 {
+ fn surface_fp(s: &Surface, h: &mut std::collections::hash_map::DefaultHasher) {
+ format!("{:?}{:?}", s.format(), s.default_pixel()).hash(h);
+ for (c, t) in s.tiles() {
+ (c.tx, c.ty, Arc::as_ptr(t) as usize).hash(h);
+ }
+ }
+ fn walk(l: &Layer, h: &mut std::collections::hash_map::DefaultHasher) {
+ l.id.0.hash(h);
+ (l.visible, l.clipped, l.opacity.to_bits(), l.fill_opacity.to_bits(), format!("{:?}", l.blend)).hash(h);
+ match &l.content {
+ LayerContent::Group(g) => {
+ for c in &g.children {
+ walk(c, h);
+ }
+ }
+ LayerContent::Fill(f) => {
+ format!("{f:?}").hash(h);
+ if let Some(c) = &l.fill_cache {
+ surface_fp(&c.surface, h);
+ }
+ }
+ LayerContent::Adjustment(a) => format!("{a:?}").hash(h),
+ _ => {
+ if let Some(s) = l.surface() {
+ surface_fp(s, h);
+ }
+ }
+ }
+ if let Some(m) = &l.mask {
+ (m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(h);
+ surface_fp(&m.surface, h);
+ }
+ format!("{:?}{:?}", l.vector_mask, l.effects).hash(h);
+ h.write_u8(0xfe);
+ }
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ (region.x0, region.y0, region.x1, region.y1, light.angle.to_bits(), light.altitude.to_bits()).hash(&mut h);
+ match &layer.content {
+ LayerContent::Group(g) => {
+ for c in &g.children {
+ walk(c, &mut h);
+ }
+ if let Some(m) = &layer.mask {
+ (m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(&mut h);
+ surface_fp(&m.surface, &mut h);
+ }
+ }
+ _ => walk(layer, &mut h),
+ }
+ h.finish()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::BlendMode;
+ use photocraft_doc::FxCommon;
+
+ #[test]
+ fn programs_key_on_geometry_not_colour() {
+ let light = GlobalLight::default();
+ let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() };
+ let a = program(&Effect::DropShadow(s.clone()), &light, false);
+ s.color = photocraft_color::Color::rgb(1.0, 0.0, 0.0);
+ s.common = FxCommon::new(BlendMode::Screen, 0.3);
+ let b = program(&Effect::DropShadow(s.clone()), &light, false);
+ assert_eq!(a.key, b.key);
+ s.size += 1.0;
+ assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key);
+ }
+
+ #[test]
+ fn windows_grow_by_reach_and_temps_are_reused() {
+ let light = GlobalLight::default();
+ let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() };
+ s.spread = 0.5;
+ let p = program(&Effect::DropShadow(s), &light, false);
+ let region = Rect::new(-100, -100, 1000, 1000);
+ let d = Rect::new(0, 0, 10, 10);
+ let fr = |_| 5;
+ let w = p.windows(d, region, &fr);
+ let last = *w.last().unwrap();
+ assert!(last.contains_rect(&d.inflate(7)), "{last:?}");
+ // Earlier stages need at least as much as later ones read.
+ assert!(w[0].width() >= last.width());
+ let (t, n) = p.temps();
+ assert!(n <= 3, "{n} temporaries for {} stages", p.stages.len());
+ assert!(t.last().unwrap().is_none());
+ }
+
+ /// A distance field computed in bands from grown windows equals the whole-region field
+ /// wherever it is within its reach (the property incremental updates rely on).
+ #[test]
+ fn banded_fields_match_whole_region_within_reach() {
+ let region = Rect::new(-20, -10, 300, 290);
+ let (w, h) = (region.width() as usize, region.height() as usize);
+ let mut shape = vec![0.0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0);
+ let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos();
+ shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 };
+ }
+ }
+ for kind in [FieldKind::Outside, FieldKind::Inside, FieldKind::OutsideInverse, FieldKind::StrokeOutside, FieldKind::StrokeInside, FieldKind::StrokeOutsideVector] {
+ let reach = 9;
+ let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h);
+ let banded = field(kind, reach, &shape, region, region);
+ let part = Rect::new(40, 30, 170, 120);
+ let partial = field(kind, reach, &shape, region, part);
+ for (i, (a, b)) in whole.iter().zip(&banded).enumerate() {
+ if a.min(*b) < reach as f32 {
+ assert!((a - b).abs() < 1e-5, "{kind:?} at {i}: {a} vs {b}");
+ }
+ }
+ for (i, b) in partial.iter().enumerate() {
+ let (x, y) = (part.x0 + (i % part.width() as usize) as i32, part.y0 + (i / part.width() as usize) as i32);
+ let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize];
+ if a.min(*b) < reach as f32 {
+ assert!((a - b).abs() < 1e-5, "{kind:?} at ({x},{y}): {a} vs {b}");
+ }
+ }
+ }
+ }
+}
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 77ea8caea..933aa800e 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -9,16 +9,21 @@
//! back and uploads only what differs). RGBA8 tiles upload with zero conversion.
//! - **Planner** ([`plan`]). The layer tree becomes a linear list of passes over abstract
//! chunk-sized buffers (blend with every Photoshop mode, opacity × fill, masks, clipping groups,
-//! pass-through vs isolated groups, adjustments, solid / gradient fills).
+//! pass-through vs isolated groups, adjustments, solid / gradient fills, layer effects).
+//! - **Layer effects** ([`fx`]). Each effect layer's maps (shadow, glow, satin, bevel, stroke
+//! bands) are built by fragment passes over its effect region and cached on the GPU per layer
+//! state; a brush stroke rebuilds only the damaged tiles grown by the effect reach.
//! - **Execution.** The canvas is processed in chunks (1024² RGBA32F accumulators, reused), and
//! each finished chunk is handed to a caller-supplied sink, e.g. to encode it straight into a
//! display texture — no readback.
//!
-//! Anything the planner can't express (layer effects, layers clipped to pass-through groups,
-//! documents larger than the device's texture limit) returns [`Unsupported`]; callers fall back to
-//! the CPU compositor.
+//! Anything the planner can't express (vector masks, layers clipped to pass-through groups,
+//! uncached pattern fills, artboards, documents or effect regions larger than the device's
+//! texture limit) returns [`Unsupported`]; callers fall back to the CPU compositor.
#![forbid(unsafe_code)]
+pub mod bounds;
+pub mod fx;
pub mod plan;
use std::collections::HashMap;
@@ -26,7 +31,8 @@ use std::num::NonZeroU64;
use std::sync::Arc;
use photocraft_color::{PixelFormat, SampleType};
-use photocraft_doc::{DocId, Document, LayerId};
+use photocraft_compose::effects::FieldKind;
+use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, Pattern};
use photocraft_geom::{Rect, TILE_SIZE, TileCoord};
use photocraft_raster::{Surface, Tile};
@@ -36,11 +42,17 @@ pub use plan::{Kernel, Plan, Role, Unsupported, plan};
/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as
/// the CPU reference, and Color Burn/Dodge amplify input error.
pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
+/// Effect intermediates (distances, blurs) and layer shapes.
+const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float;
+/// Final effect coverage maps (0..1; half precision is ~1/4000).
+const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;
/// Side of the square chunks the canvas is processed in.
pub const CHUNK: u32 = 1024;
const STRIDE: u64 = 256;
const CHUNK_UNIFORM: u64 = 16;
-const OP_UNIFORM: u64 = 144;
+const OP_UNIFORM: u64 = 176;
+/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame.
+pub const FX_BUDGET: usize = 1536 << 20;
/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the
/// texture's origin.
@@ -58,6 +70,12 @@ pub struct Stats {
pub slots: u32,
pub tiles_uploaded: usize,
pub bytes_uploaded: usize,
+ /// Effect layers whose shape was (re)rendered, fully or partially.
+ pub fx_shapes: usize,
+ /// Effect map programs run (one per effect whose maps were rebuilt).
+ pub fx_programs: usize,
+ /// Effect-map pixels written (all stages).
+ pub fx_pixels: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -118,14 +136,176 @@ struct Resident {
last_used: u64,
}
-/// GPU compositor. Create once per device; call [`Compositor::render`] per refresh.
-pub struct Compositor {
- pipelines: HashMap<Kernel, wgpu::RenderPipeline>,
+/// A texture and its default view.
+#[derive(Clone)]
+struct Tex {
+ texture: wgpu::Texture,
+ view: wgpu::TextureView,
+}
+
+impl Tex {
+ fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage,
+ view_formats: &[],
+ });
+ let view = texture.create_view(&Default::default());
+ Tex { texture, view }
+ }
+ fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self {
+ Tex::new(device, label, r.width(), r.height(), format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST)
+ }
+ /// Upload R32F values (row-major over `r`) into this region-space texture at `r`.
+ fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) {
+ if r.is_empty() {
+ return;
+ }
+ let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo { texture: &self.texture, mip_level: 0, origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 }, aspect: wgpu::TextureAspect::All },
+ &bytes,
+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) },
+ wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 },
+ );
+ }
+ fn bytes(&self) -> usize {
+ let s = self.texture.size();
+ let bpp = match self.texture.format() {
+ wgpu::TextureFormat::R16Float => 2,
+ wgpu::TextureFormat::Rgba32Float => 16,
+ _ => 4,
+ };
+ s.width as usize * s.height as usize * bpp
+ }
+}
+
+/// Cached maps of one effect (one enabled item of a layer).
+struct ProgState {
+ key: u64,
+ maps: Vec<Option<Tex>>,
+}
+
+/// Cached effect state of one layer.
+struct FxEntry {
+ doc: DocId,
+ region: Rect,
+ shape_key: u64,
+ /// Tiles the shape was rendered from (content, mask): damage is their difference.
+ tiles: [Option<fx::Tiles>; 2],
+ /// Groups: a clone pinning the tile pointers `shape_key` hashes.
+ _pin: Option<Layer>,
+ /// The shape on the CPU (distance fields are computed from it) and on the GPU.
+ shape_cpu: Vec<f32>,
+ shape: Tex,
+ /// Distance fields: the reach each is exact to, and its texture.
+ fields: HashMap<FieldKind, (i32, Tex)>,
+ progs: Vec<ProgState>,
+ last_used: u64,
+}
+
+impl FxEntry {
+ fn bytes(&self) -> usize {
+ self.shape.bytes() + self.shape_cpu.len() * 4 + self.fields.values().map(|(_, t)| t.bytes()).sum::<usize>() + self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::<usize>()
+ }
+}
+
+/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted).
+#[derive(Clone)]
+struct Kit {
+ pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>,
bgl0: wgpu::BindGroupLayout,
bgl1: wgpu::BindGroupLayout,
dummy: wgpu::TextureView,
+}
+
+/// One draw of an effect-map kernel (outside the chunk loop).
+struct MapDraw {
+ kernel: Kernel,
+ format: wgpu::TextureFormat,
+ target: wgpu::TextureView,
+ /// Target-local scissor (x, y, w, h).
+ scissor: [u32; 4],
+ /// Chunk record: origin and size of the target's space.
+ space: [i32; 4],
+ op: Vec<u8>,
+ views: [Option<wgpu::TextureView>; 8],
+ lut: Option<Arc<Vec<f32>>>,
+}
+
+impl Kit {
+ /// Record `draws` (each its own render pass) into `encoder`.
+ fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) {
+ if draws.is_empty() {
+ return;
+ }
+ let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize];
+ for (i, d) in draws.iter().enumerate() {
+ let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]);
+ data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w);
+ data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op);
+ }
+ let ubuf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_fx_uniforms"), size: data.len() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ queue.write_buffer(&ubuf, 0, &data);
+ let bg0 = uniform_group(device, &self.bgl0, &ubuf);
+ for (i, d) in draws.iter().enumerate() {
+ let lut = d.lut.as_ref().map(|l| {
+ let mut row = [0.0f32; 4096];
+ row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]);
+ lut_texture(device, queue, &[row])
+ });
+ let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect();
+ if let Some((_, lv)) = &lut {
+ views[4] = lv;
+ }
+ let bg1 = texture_group(device, &self.bgl1, &views);
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("pc_fx_map"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &d.target, resolve_target: None, depth_slice: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store } })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]);
+ pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]);
+ pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]);
+ pass.set_bind_group(1, &bg1, &[]);
+ pass.draw(0..3, 0..1);
+ }
+ }
+}
+
+fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("pc_compose_uniforms"),
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }) },
+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }) },
+ ],
+ })
+}
+
+fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup {
+ let e: Vec<wgpu::BindGroupEntry> = views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect();
+ device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e })
+}
+
+/// GPU compositor. Create once per device; call [`Compositor::render`] per refresh.
+pub struct Compositor {
+ kit: Kit,
pool: Vec<(wgpu::Texture, wgpu::TextureView)>,
residents: HashMap<(LayerId, Role), Resident>,
+ fx: HashMap<LayerId, FxEntry>,
+ /// Effect temporaries (R32F, region sized) and the frame they were last used.
+ temps: Vec<(Tex, u64)>,
+ patterns: HashMap<String, (u64, Tex)>,
max_dim: u32,
frame: u64,
}
@@ -151,48 +331,51 @@ fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry {
/// The compositor's WGSL source (exposed for validation in tests).
pub const SHADER: &str = include_str!("compose.wgsl");
+/// Pass-level resources resolved for one plan.
+struct Bound<'p> {
+ views: Vec<(Option<ResidentRef>, Option<ResidentRef>)>,
+ keys: Vec<(LayerId, Role)>,
+ maps: Vec<Option<(wgpu::TextureView, Rect)>>,
+ patterns: Vec<Option<wgpu::TextureView>>,
+ _plan: std::marker::PhantomData<&'p ()>,
+}
+
impl Compositor {
pub fn new(device: &wgpu::Device) -> Self {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_uniforms"), entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)] });
- let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_textures"), entries: &[tex_entry(0), tex_entry(1), tex_entry(2), tex_entry(3), tex_entry(4)] });
+ let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_textures"), entries: &(0..8).map(tex_entry).collect::<Vec<_>>() });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_compose"), bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], immediate_size: 0 });
let mut pipelines = HashMap::new();
- for (k, entry) in [
- (Kernel::Content, "fs_content"),
- (Kernel::Mask, "fs_mask"),
- (Kernel::Blend, "fs_blend"),
- (Kernel::Atop, "fs_atop"),
- (Kernel::Adjust, "fs_adjust"),
- (Kernel::AdjMix, "fs_adjmix"),
- (Kernel::Lerp, "fs_lerp"),
- ] {
- let p = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some(entry),
- layout: Some(&layout),
- vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
- primitive: wgpu::PrimitiveState::default(),
- depth_stencil: None,
- multisample: wgpu::MultisampleState::default(),
- fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(entry), targets: &[Some(wgpu::ColorTargetState { format: ACC_FORMAT, blend: None, write_mask: wgpu::ColorWrites::ALL })], compilation_options: Default::default() }),
- multiview_mask: None,
- cache: None,
- });
- pipelines.insert(k, p);
+ for k in Kernel::DRAWN {
+ let entry = k.entry().expect("drawn kernels have an entry point");
+ let formats: &[wgpu::TextureFormat] = if k.is_map() { &[MAP32, MAP16] } else { &[ACC_FORMAT] };
+ for &format in formats {
+ let p = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(entry),
+ layout: Some(&layout),
+ vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(entry), targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], compilation_options: Default::default() }),
+ multiview_mask: None,
+ cache: None,
+ });
+ pipelines.insert((k, format), p);
+ }
+ }
+ let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view;
+ Self {
+ kit: Kit { pipelines, bgl0, bgl1, dummy },
+ pool: Vec::new(),
+ residents: HashMap::new(),
+ fx: HashMap::new(),
+ temps: Vec::new(),
+ patterns: HashMap::new(),
+ max_dim: device.limits().max_texture_dimension_2d,
+ frame: 0,
}
- let dummy = device
- .create_texture(&wgpu::TextureDescriptor {
- label: Some("pc_compose_dummy"),
- size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING,
- view_formats: &[],
- })
- .create_view(&Default::default());
- Self { pipelines, bgl0, bgl1, dummy, pool: Vec::new(), residents: HashMap::new(), max_dim: device.limits().max_texture_dimension_2d, frame: 0 }
}
/// Whether `doc` can be composited on the GPU.
@@ -201,12 +384,43 @@ impl Compositor {
if b.width() > self.max_dim || b.height() > self.max_dim {
return Err(Unsupported(format!("document larger than the GPU texture limit ({})", self.max_dim)));
}
- plan(doc).map(|_| ())
+ let p = plan(doc)?;
+ self.check_fx(doc, &p)
+ }
+
+ /// Effect regions and patterns must fit in textures.
+ fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> {
+ for f in &p.fx {
+ if f.region.width() > self.max_dim || f.region.height() > self.max_dim {
+ return Err(Unsupported(format!("effect region of `{}` larger than the GPU texture limit ({})", f.layer.name, self.max_dim)));
+ }
+ for e in f.layer.effects.items.iter().filter(|e| e.enabled()) {
+ for s in fx::program(e, &doc.global_light, false).stages {
+ if s.lut.as_ref().is_some_and(|l| l.len() > 4096) {
+ return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name)));
+ }
+ }
+ }
+ }
+ for pass in &p.passes {
+ if let Some(pat) = pass.pattern
+ && (pat.width > self.max_dim || pat.height > self.max_dim)
+ {
+ return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name)));
+ }
+ }
+ Ok(())
}
/// Drop GPU textures of a closed document.
pub fn forget_doc(&mut self, doc: DocId) {
self.residents.retain(|_, r| r.doc != doc);
+ self.fx.retain(|_, e| e.doc != doc);
+ }
+
+ /// GPU memory held by cached effect maps (bytes).
+ pub fn fx_cache_bytes(&self) -> usize {
+ self.fx.values().map(FxEntry::bytes).sum()
}
/// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is
@@ -227,32 +441,86 @@ impl Compositor {
}
let region = region.intersect(&canvas);
let plan = plan(doc)?;
+ self.check_fx(doc, &plan)?;
let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() };
if region.is_empty() {
return Ok(stats);
}
self.frame += 1;
- // Residency: bring every surface the plan samples up to date.
- let grid = tile_grid(canvas);
+ // Effect maps first (they may render group shapes through sub-plans).
+ for f in &plan.fx {
+ self.sync_fx(device, queue, encoder, doc, f, &mut stats);
+ }
+
+ // Chunks.
+ let mut chunks = Vec::new();
+ let mut y = region.y0;
+ while y < region.y1 {
+ let mut x = region.x0;
+ while x < region.x1 {
+ chunks.push(Rect::new(x, y, (x + CHUNK as i32).min(region.x1), (y + CHUNK as i32).min(region.y1)));
+ x += CHUNK as i32;
+ }
+ y += CHUNK as i32;
+ }
+ stats.chunks = chunks.len();
+ self.run_plan(device, queue, encoder, doc.id, canvas, &plan, &chunks, &mut stats, sink);
+
+ // Evict this document's textures whose layers are gone (hidden layers stay resident so
+ // toggling visibility costs no upload).
+ let frame = self.frame;
+ let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ self.residents.retain(|(id, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id));
+ self.fx.retain(|id, e| e.doc != doc.id || e.last_used == frame || live.contains(id));
+ self.evict_fx();
+ self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240);
+ Ok(stats)
+ }
+
+ /// Keep the effect cache within [`FX_BUDGET`], dropping layers not drawn this frame
+ /// (least recently used first).
+ fn evict_fx(&mut self) {
+ let mut total = self.fx_cache_bytes();
+ while total > FX_BUDGET {
+ let Some((&id, _)) = self.fx.iter().filter(|(_, e)| e.last_used != self.frame).min_by_key(|(_, e)| e.last_used) else { break };
+ if let Some(e) = self.fx.remove(&id) {
+ total = total.saturating_sub(e.bytes());
+ }
+ }
+ }
+
+ /// Bring every surface `plan` samples up to date and resolve its effect maps and patterns.
+ fn bind_plan<'p>(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, doc: DocId, canvas: Rect, plan: &Plan<'p>, stats: &mut Stats) -> Bound<'p> {
let mut views: Vec<(Option<ResidentRef>, Option<ResidentRef>)> = Vec::with_capacity(plan.passes.len());
let mut keys: Vec<(LayerId, Role)> = Vec::new();
+ let mut maps = Vec::with_capacity(plan.passes.len());
+ let mut patterns = Vec::with_capacity(plan.passes.len());
for p in &plan.passes {
- let tex = p.tex.and_then(|t| self.sync(device, queue, doc.id, t.layer, t.role, t.surface, grid, &mut stats)).map(|(k, r)| {
+ let tex = p.tex.and_then(|t| self.sync(device, queue, doc, t.layer, t.role, t.surface, tile_grid(canvas), stats)).map(|(k, r)| {
keys.push(k);
(keys.len() - 1, r)
});
- let mask = p.mask.and_then(|m| self.sync(device, queue, doc.id, m.layer, Role::Mask, m.surface, grid, &mut stats)).map(|(k, r)| {
+ let mask = p.mask.and_then(|m| self.sync(device, queue, doc, m.layer, Role::Mask, m.surface, tile_grid(canvas), stats)).map(|(k, r)| {
keys.push(k);
(keys.len() - 1, r)
});
views.push((tex, mask));
+ maps.push(p.map.and_then(|m| {
+ let e = self.fx.get(&plan.fx[m.fx].layer.id)?;
+ let t = e.progs.get(m.item)?.maps.get(m.map)?.as_ref()?;
+ Some((t.view.clone(), e.region))
+ }));
+ patterns.push(p.pattern.map(|pat| self.pattern_view(device, queue, pat)));
}
- // Evict this document's textures whose layers are gone (hidden layers stay resident so
- // toggling visibility costs no upload).
- let frame = self.frame;
- let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
- self.residents.retain(|(id, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id));
+ Bound { views, keys, maps, patterns, _plan: std::marker::PhantomData }
+ }
+
+ /// Run `plan` over `chunks` (document rects, at most CHUNK square), handing each finished
+ /// chunk to `sink`.
+ #[allow(clippy::too_many_arguments)]
+ fn run_plan(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, doc: DocId, canvas: Rect, plan: &Plan<'_>, chunks: &[Rect], stats: &mut Stats, sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>)) {
+ let bound = self.bind_plan(device, queue, doc, canvas, plan, stats);
// Chunk pool.
while self.pool.len() < plan.slots as usize {
@@ -263,26 +531,13 @@ impl Compositor {
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: ACC_FORMAT,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let v = t.create_view(&Default::default());
self.pool.push((t, v));
}
- // Chunks.
- let mut chunks = Vec::new();
- let mut y = region.y0;
- while y < region.y1 {
- let mut x = region.x0;
- while x < region.x1 {
- chunks.push(Rect::new(x, y, (x + CHUNK as i32).min(region.x1), (y + CHUNK as i32).min(region.y1)));
- x += CHUNK as i32;
- }
- y += CHUNK as i32;
- }
- stats.chunks = chunks.len();
-
// Uniforms: chunk records, then one record per pass.
let op_base = chunks.len() as u64 * STRIDE;
let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize];
@@ -290,72 +545,62 @@ impl Compositor {
let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]);
data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w);
}
- for (i, (p, (tex, mask))) in plan.passes.iter().zip(&views).enumerate() {
- let mut flags = 0u32;
- let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]);
- if let Some((_, r)) = tex {
- flags |= 4;
- to = [r[0], r[1]];
- ts = [r[2], r[3]];
- }
- let (mut density, mut mdefault) = (0.0, 1.0);
- if let Some(m) = &p.mask {
- flags |= 1;
- density = m.density;
- mdefault = m.default;
- if let Some((_, r)) = mask {
- flags |= 2;
- mo = [r[0], r[1]];
- ms = [r[2], r[3]];
- }
- }
- if p.gradient {
- flags |= 8;
- }
- let mut v = vec![I(plan::mode_index(p.mode)), I(p.adjust_kind), U(flags), U(0), F(p.opacity), F(density), F(mdefault), F(0.0), I(to[0]), I(to[1]), I(ts[0]), I(ts[1]), I(mo[0]), I(mo[1]), I(ms[0]), I(ms[1])];
- v.extend(p.color.iter().map(|f| F(*f)));
- for row in &p.params {
- v.extend(row.iter().map(|f| F(*f)));
- }
- let w = words(&v);
+ for (i, p) in plan.passes.iter().enumerate() {
+ let (tex, mask) = bound.views[i];
+ let map = bound.maps[i].as_ref().map(|(_, r)| *r);
+ let w = op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map);
let off = (op_base + i as u64 * STRIDE) as usize;
data[off..][..w.len()].copy_from_slice(&w);
}
let ubuf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_compose_uniforms"), size: data.len() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
queue.write_buffer(&ubuf, 0, &data);
- let bg0 = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("pc_compose_uniforms"),
- layout: &self.bgl0,
- entries: &[
- wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }) },
- wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }) },
- ],
- });
+ let bg0 = uniform_group(device, &self.kit.bgl0, &ubuf);
// Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk).
- let resident_views: Vec<&wgpu::TextureView> = keys.iter().map(|k| &self.residents[k].view).collect();
- let mut luts = Vec::new();
- for p in &plan.passes {
- luts.push(p.lut.as_ref().map(|rows| lut_texture(device, queue, rows)));
- }
+ let resident_views: Vec<&wgpu::TextureView> = bound.keys.iter().map(|k| &self.residents[k].view).collect();
+ let luts: Vec<_> = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect();
+ let dummy = &self.kit.dummy;
let mut bg1 = Vec::with_capacity(plan.passes.len());
for (i, p) in plan.passes.iter().enumerate() {
- if p.kernel == Kernel::Clear {
+ if p.kernel.entry().is_none() {
bg1.push(None);
continue;
}
- let slot = |s: Option<u32>| s.map_or(&self.dummy, |s| &self.pool[s as usize].1);
- let (tex, mask) = &views[i];
- let tv = tex.map_or(&self.dummy, |(k, _)| resident_views[k]);
- let mv = mask.map_or(&self.dummy, |(k, _)| resident_views[k]);
- let lv = luts[i].as_ref().map_or(&self.dummy, |(_, v)| v);
- let entries = [slot(p.a), slot(p.b), tv, mv, lv];
- let e: Vec<wgpu::BindGroupEntry> = entries.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect();
- bg1.push(Some(device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout: &self.bgl1, entries: &e })));
+ let slot = |s: Option<u32>| s.map_or(dummy, |s| &self.pool[s as usize].1);
+ let (tex, mask) = &bound.views[i];
+ let tv = tex.map_or(dummy, |(k, _)| resident_views[k]);
+ let mv = mask.map_or(dummy, |(k, _)| resident_views[k]);
+ let lv = luts[i].as_ref().map_or(dummy, |(_, v)| v);
+ let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v);
+ let pat = bound.patterns[i].as_ref().unwrap_or(dummy);
+ bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat])));
}
for (ci, c) in chunks.iter().enumerate() {
for (i, p) in plan.passes.iter().enumerate() {
+ let scissor = match p.clip {
+ Some(clip) => {
+ let r = clip.intersect(c);
+ if r.is_empty() {
+ continue;
+ }
+ Rect::new(r.x0 - c.x0, r.y0 - c.y0, r.x1 - c.x0, r.y1 - c.y0)
+ }
+ None => Rect::new(0, 0, c.width() as i32, c.height() as i32),
+ };
+ match p.kernel {
+ Kernel::CopyRect | Kernel::CopyFull => {
+ let src = &self.pool[p.a.expect("copy source") as usize].0;
+ let dst = &self.pool[p.dst as usize].0;
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo { texture: src, mip_level: 0, origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, aspect: wgpu::TextureAspect::All },
+ wgpu::TexelCopyTextureInfo { texture: dst, mip_level: 0, origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, aspect: wgpu::TextureAspect::All },
+ wgpu::Extent3d { width: scissor.width(), height: scissor.height(), depth_or_array_layers: 1 },
+ );
+ continue;
+ }
+ _ => {}
+ }
let target = &self.pool[p.dst as usize].1;
let clear = p.kernel == Kernel::Clear;
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -374,8 +619,8 @@ impl Compositor {
if clear {
continue;
}
- pass.set_pipeline(&self.pipelines[&p.kernel]);
- pass.set_scissor_rect(0, 0, c.width(), c.height());
+ pass.set_pipeline(&self.kit.pipelines[&(p.kernel, ACC_FORMAT)]);
+ pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height());
pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]);
pass.set_bind_group(1, bg1[i].as_ref(), &[]);
pass.draw(0..3, 0..1);
@@ -383,7 +628,6 @@ impl Compositor {
let (t, v) = &self.pool[plan.root as usize];
sink(encoder, ChunkOut { rect: *c, texture: t, view: v });
}
- Ok(stats)
}
/// Upload changed tiles of `surface`; returns the resident key and its region (x, y, w, h).
@@ -448,6 +692,245 @@ impl Compositor {
}
Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32]))
}
+
+ /// Premultiplied RGBA32F texture of a pattern (cached by pixel identity).
+ fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView {
+ let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64);
+ let key = format!("{}\u{0}{}", pat.id, pat.name);
+ if let Some((f, t)) = self.patterns.get(&key)
+ && *f == fp
+ {
+ return t.view.clone();
+ }
+ let (w, h) = (pat.width, pat.height);
+ let mut px = vec![[0.0f32; 4]; w as usize * h as usize];
+ pat.surface.read_rgba_into(pat.rect(), &mut px);
+ let bytes: Vec<u8> = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect();
+ let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ &bytes,
+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(h) },
+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
+ );
+ let v = t.view.clone();
+ self.patterns.insert(key, (fp, t));
+ v
+ }
+
+ /// A region-sized R32F temporary not in `taken`.
+ fn temp(&mut self, device: &wgpu::Device, region: Rect, taken: &[wgpu::TextureView]) -> wgpu::TextureView {
+ let (w, h) = (region.width(), region.height());
+ let frame = self.frame;
+ for (t, used) in &mut self.temps {
+ let s = t.texture.size();
+ if s.width == w && s.height == h && !taken.iter().any(|v| *v == t.view) {
+ *used = frame;
+ return t.view.clone();
+ }
+ }
+ let t = Tex::map(device, "pc_fx_temp", region, MAP32);
+ let v = t.view.clone();
+ self.temps.push((t, frame));
+ v
+ }
+
+ /// Build or update the effect maps of one layer.
+ fn sync_fx(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, doc: &Document, f: &plan::FxLayer<'_>, stats: &mut Stats) {
+ let layer = f.layer;
+ let region = f.region;
+ let canvas = doc.bounds();
+ let is_group = matches!(layer.content, LayerContent::Group(_));
+ let shape_key = if is_group { fx::group_key(layer, region, &doc.global_light) } else { fx::shape_key(layer, canvas, region) };
+ let (content_src, mask_src) = if is_group { (None, None) } else { fx::shape_sources(layer) };
+ let frame = self.frame;
+
+ // What changed: everything (new region / settings), some tiles, or nothing.
+ let mut damage = Rect::EMPTY;
+ let reuse = self.fx.get(&layer.id).is_some_and(|e| e.region == region && e.shape_key == shape_key);
+ if reuse {
+ let e = &self.fx[&layer.id];
+ for (old, cur) in e.tiles.iter().zip([content_src, mask_src]) {
+ let d = match (old, cur) {
+ (Some(o), Some(s)) => fx::damage(o, s),
+ (None, None) => Rect::EMPTY,
+ // A source appeared or vanished (the key changes with it too).
+ _ => region,
+ };
+ damage = if damage.is_empty() { d } else { damage.union(&d) };
+ }
+ damage = damage.intersect(&region);
+ } else {
+ let shape = Tex::map(device, "pc_fx_shape", region, MAP32);
+ let n = region.width() as usize * region.height() as usize;
+ self.fx.insert(layer.id, FxEntry { doc: doc.id, region, shape_key, tiles: [None, None], _pin: is_group.then(|| layer.clone()), shape_cpu: vec![0.0; n], shape, fields: HashMap::new(), progs: Vec::new(), last_used: frame });
+ damage = region;
+ }
+ let e = self.fx.get_mut(&layer.id).expect("inserted");
+ e.last_used = frame;
+ e.doc = doc.id;
+ e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)];
+ if region.is_empty() {
+ return;
+ }
+
+ let t_trace = std::time::Instant::now();
+ // Shape over the damage (compose's own alpha).
+ if !damage.is_empty() {
+ stats.fx_shapes += 1;
+ let ts = std::time::Instant::now();
+ let v = fx::shape(doc, layer, damage);
+ if std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some() {
+ eprintln!(" shape {}x{}: {:.2} ms", damage.width(), damage.height(), ts.elapsed().as_secs_f64() * 1000.0);
+ }
+ fx::paste(&mut e.shape_cpu, region, damage, &v);
+ e.shape.write_r32(queue, region, damage, &v);
+ }
+
+ // Programs, and the distance fields they read (max reach per field).
+ let vector_shape = matches!(layer.content, LayerContent::Shape(_));
+ let progs: Vec<fx::MapProgram> = layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program(e, &doc.global_light, vector_shape)).collect();
+ let mut want: HashMap<FieldKind, i32> = HashMap::new();
+ for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) {
+ let w = want.entry(*k).or_insert(0);
+ *w = (*w).max(*r);
+ }
+ e.fields.retain(|k, _| want.contains_key(k));
+ for (&kind, &reach) in &want {
+ let have = e.fields.get(&kind).map(|(r, _)| *r);
+ let out = match have {
+ Some(r) if r >= reach => {
+ if damage.is_empty() {
+ continue;
+ }
+ damage.inflate(fx::field_radius(kind, r)).intersect(&region)
+ }
+ _ => region,
+ };
+ let reach = have.filter(|r| *r >= reach).unwrap_or(reach);
+ let tf = std::time::Instant::now();
+ let v = fx::field(kind, reach, &e.shape_cpu, region, out);
+ if std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some() {
+ eprintln!(" field {kind:?} reach {reach} over {}x{}: {:.2} ms", out.width(), out.height(), tf.elapsed().as_secs_f64() * 1000.0);
+ }
+ if have.is_none_or(|r| r < reach) {
+ e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32)));
+ }
+ e.fields[&kind].1.write_r32(queue, region, out, &v);
+ stats.fx_pixels += out.width() as u64 * out.height() as u64;
+ }
+
+ if std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some() && !damage.is_empty() {
+ eprintln!("fx `{}`: damage {:?} shape+fields {:.2} ms", layer.name, damage, t_trace.elapsed().as_secs_f64() * 1000.0);
+ }
+ e.progs.truncate(progs.len());
+ while e.progs.len() < progs.len() {
+ e.progs.push(ProgState { key: 0, maps: Vec::new() });
+ }
+ for (i, prog) in progs.iter().enumerate() {
+ if prog.maps == 0 {
+ continue;
+ }
+ let e = self.fx.get_mut(&layer.id).expect("entry");
+ let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps;
+ let d = if same { damage } else { region };
+ if d.is_empty() {
+ continue;
+ }
+ if !same {
+ e.progs[i] = ProgState { key: prog.key, maps: (0..prog.maps).map(|k| prog.stages.iter().any(|s| s.out == Some(k)).then(|| Tex::map(device, "pc_fx_map", region, MAP16))).collect() };
+ }
+ stats.fx_programs += 1;
+ self.run_program(device, queue, encoder, layer.id, i, prog, d, stats);
+ }
+ }
+
+ /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`.
+ #[allow(clippy::too_many_arguments)]
+ fn run_program(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, layer: LayerId, item: usize, prog: &fx::MapProgram, d: Rect, stats: &mut Stats) {
+ let e = &self.fx[&layer];
+ let region = e.region;
+ let shape = e.shape.view.clone();
+ let finals: Vec<Option<wgpu::TextureView>> = e.progs[item].maps.iter().map(|m| m.as_ref().map(|t| t.view.clone())).collect();
+ let fields: HashMap<FieldKind, (i32, wgpu::TextureView)> = e.fields.iter().map(|(k, (r, t))| (*k, (*r, t.view.clone()))).collect();
+ let windows = prog.windows(d, region, &|k| fields.get(&k).map_or(0, |f| f.0));
+ let (assign, count) = prog.temps();
+ let mut temps: Vec<wgpu::TextureView> = Vec::with_capacity(count);
+ for _ in 0..count {
+ let v = self.temp(device, region, &temps);
+ temps.push(v);
+ }
+ let target_of = |i: usize| -> (wgpu::TextureView, wgpu::TextureFormat) {
+ match prog.stages[i].out {
+ Some(k) => (finals[k].clone().expect("final map allocated"), MAP16),
+ None => (temps[assign[i].expect("temporary assigned")].clone(), MAP32),
+ }
+ };
+ let view_of = |inp: Option<fx::In>| -> Option<wgpu::TextureView> {
+ match inp? {
+ fx::In::Shape => Some(shape.clone()),
+ fx::In::Field(k) => fields.get(&k).map(|f| f.1.clone()),
+ fx::In::Val(k) => Some(target_of(k).0),
+ }
+ };
+ let mut draws = Vec::with_capacity(prog.stages.len());
+ for (i, s) in prog.stages.iter().enumerate() {
+ let w = windows[i];
+ if w.is_empty() {
+ continue;
+ }
+ stats.fx_pixels += w.width() as u64 * w.height() as u64;
+ let (target, format) = target_of(i);
+ let mut p = plan::Pass::new(s.kernel, 0);
+ p.params[0] = s.p0;
+ p.params[1] = s.p1;
+ draws.push(MapDraw {
+ kernel: s.kernel,
+ format,
+ target,
+ scissor: [(w.x0 - region.x0) as u32, (w.y0 - region.y0) as u32, w.width(), w.height()],
+ space: [region.x0, region.y0, region.width() as i32, region.height() as i32],
+ op: op_words(&p, None, None, None),
+ views: [view_of(s.a), view_of(s.b), view_of(s.s), None, None, None, None, None],
+ lut: s.lut.clone(),
+ });
+ }
+ self.kit.run(device, queue, encoder, &draws);
+ }
+}
+
+/// The uniform record of a pass.
+fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option<Rect>) -> Vec<u8> {
+ let mut flags = p.flags;
+ let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]);
+ if let Some(r) = tex {
+ flags |= 4;
+ to = [r[0], r[1]];
+ ts = [r[2], r[3]];
+ }
+ let (mut density, mut mdefault) = (0.0, 1.0);
+ if let Some(m) = &p.mask {
+ flags |= 1;
+ density = m.density;
+ mdefault = m.default;
+ if let Some(r) = mask {
+ flags |= 2;
+ mo = [r[0], r[1]];
+ ms = [r[2], r[3]];
+ }
+ }
+ if p.gradient {
+ flags |= 8;
+ }
+ let (mpo, mps) = map.map_or(([0, 0], [0, 0]), |r| ([r.x0, r.y0], [r.width() as i32, r.height() as i32]));
+ let mut v = vec![I(plan::mode_index(p.mode)), I(p.adjust_kind), U(flags), U(0), F(p.opacity), F(density), F(mdefault), F(0.0), I(to[0]), I(to[1]), I(ts[0]), I(ts[1]), I(mo[0]), I(mo[1]), I(ms[0]), I(ms[1])];
+ v.extend(p.color.iter().map(|f| F(*f)));
+ for row in &p.params {
+ v.extend(row.iter().map(|f| F(*f)));
+ }
+ v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]);
+ v.extend(p.extra.iter().map(|f| F(*f)));
+ words(&v)
}
/// Canvas rounded out to whole tiles.
@@ -591,9 +1074,15 @@ pub fn f16_to_f32(h: u16) -> f32 {
/// Blocking readback of a composite (native tests and tools).
#[cfg(not(target_arch = "wasm32"))]
pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result<Vec<[f32; 4]>, Unsupported> {
+ render_to_vec_stats(comp, device, queue, doc, rect).map(|(v, _)| v)
+}
+
+/// [`render_to_vec`] plus the render's [`Stats`].
+#[cfg(not(target_arch = "wasm32"))]
+pub fn render_to_vec_stats(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result<(Vec<[f32; 4]>, Stats), Unsupported> {
let rect = rect.intersect(&doc.bounds());
let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new();
- comp.render(device, queue, doc, rect, |enc, out| {
+ let stats = comp.render(device, queue, doc, rect, |enc, out| {
let row = (out.rect.width() * 16).div_ceil(256) * 256;
let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_readback"), size: (row * out.rect.height()) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
enc.copy_texture_to_buffer(
@@ -620,7 +1109,7 @@ pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu:
}
}
}
- Ok(out)
+ Ok((out, stats))
}
#[cfg(test)]
@@ -639,6 +1128,16 @@ mod tests {
fn shader_validates() {
let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER)));
wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()).validate(&module).unwrap_or_else(|e| panic!("{e:?}"));
+ for k in Kernel::DRAWN {
+ let e = k.entry().unwrap();
+ assert!(module.entry_points.iter().any(|ep| ep.name == e), "missing entry point {e}");
+ }
+ }
+
+ #[test]
+ fn op_record_fits_the_uniform() {
+ let p = plan::Pass::new(Kernel::FxPaint, 0);
+ assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM);
}
#[test]
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index 572afd264..50a978f20 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -2,16 +2,25 @@
//!
//! The structure mirrors `photocraft_compose::composite_stack` / `composite_layer` /
//! `composite_atop` one to one, so both backends share Photoshop semantics (pass-through vs
-//! isolated groups, clipping, masks, opacity × fill, adjustments). Every pass reads slots and
-//! writes a fresh slot; slots are recycled as soon as nothing refers to them.
+//! isolated groups, clipping, masks, opacity × fill, adjustments, layer effects). Every pass
+//! reads slots and writes a fresh slot; slots are recycled as soon as nothing refers to them.
+//!
+//! Layer effects follow `photocraft_compose::effects::composite_with_effects`: the layer's
+//! effect maps (shadow / glow / satin / bevel coverage, stroke bands) are built once per layer
+//! state by [`crate::fx`] and sampled here; exterior effects paint into a copy of the backdrop,
+//! the layer at fill opacity takes the interior effects, and the two merge with the layer's mode
+//! and opacity. Effect passes are clipped to the layer's effect region and the result is copied
+//! back into the backdrop in place, so a small text layer costs only its own pixels.
use photocraft_color::BlendMode;
use photocraft_compose::adjust::{self, Transfer};
use photocraft_compose::effects::has_effects;
-use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId};
+use photocraft_doc::{Adjustment, Document, Effect, Fill, FxPaint, GlobalLight, Gradient, Layer, LayerContent, LayerId, Pattern, StrokePosition};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
+use crate::bounds;
+
/// Index of a chunk-sized accumulator texture.
pub type Slot = u32;
@@ -27,6 +36,89 @@ pub enum Kernel {
Adjust,
AdjMix,
Lerp,
+ /// Effect chain start: the layer at fill opacity, or an opaque copy of a clipping base.
+ FxInit,
+ /// Paint an effect through a coverage map (or the layer's alpha) into A.
+ FxPaint,
+ /// Layer + interior effects over the exterior result, then layer opacity against the backdrop.
+ FxMerge,
+ /// Copy slot A into `dst` (an existing slot) over the pass clip (no draw).
+ CopyRect,
+ /// Copy all of slot A into the fresh slot `dst` (no draw).
+ CopyFull,
+ // Effect-map kernels (single-channel targets over an effect region, see `fx`).
+ MShift,
+ MDilate,
+ MBlur,
+ MGlow,
+ MFinish,
+ MBevelH,
+ MBevelShade,
+ MStroke,
+}
+
+impl Kernel {
+ /// Fragment entry point in `compose.wgsl` (`None` for copies and clears).
+ pub fn entry(self) -> Option<&'static str> {
+ Some(match self {
+ Kernel::Clear | Kernel::CopyRect | Kernel::CopyFull => return None,
+ Kernel::Content => "fs_content",
+ Kernel::Mask => "fs_mask",
+ Kernel::Blend => "fs_blend",
+ Kernel::Atop => "fs_atop",
+ Kernel::Adjust => "fs_adjust",
+ Kernel::AdjMix => "fs_adjmix",
+ Kernel::Lerp => "fs_lerp",
+ Kernel::FxInit => "fs_fxinit",
+ Kernel::FxPaint => "fs_fxpaint",
+ Kernel::FxMerge => "fs_fxmerge",
+ Kernel::MShift => "fs_mshift",
+ Kernel::MDilate => "fs_mdilate",
+ Kernel::MBlur => "fs_mblur",
+ Kernel::MGlow => "fs_mglow",
+ Kernel::MFinish => "fs_mfinish",
+ Kernel::MBevelH => "fs_mbevelh",
+ Kernel::MBevelShade => "fs_mbevelshade",
+ Kernel::MStroke => "fs_mstroke",
+ })
+ }
+
+ /// Kernels that write effect maps (R32F / R16F targets) rather than RGBA accumulators.
+ pub fn is_map(self) -> bool {
+ matches!(
+ self,
+ Kernel::MShift
+ | Kernel::MDilate
+ | Kernel::MBlur
+ | Kernel::MGlow
+ | Kernel::MFinish
+ | Kernel::MBevelH
+ | Kernel::MBevelShade
+ | Kernel::MStroke
+ )
+ }
+
+ /// Every kernel with a pipeline.
+ pub const DRAWN: [Kernel; 18] = [
+ Kernel::Content,
+ Kernel::Mask,
+ Kernel::Blend,
+ Kernel::Atop,
+ Kernel::Adjust,
+ Kernel::AdjMix,
+ Kernel::Lerp,
+ Kernel::FxInit,
+ Kernel::FxPaint,
+ Kernel::FxMerge,
+ Kernel::MShift,
+ Kernel::MDilate,
+ Kernel::MBlur,
+ Kernel::MGlow,
+ Kernel::MFinish,
+ Kernel::MBevelH,
+ Kernel::MBevelShade,
+ Kernel::MStroke,
+ ];
}
/// Which resident texture a pass samples.
@@ -44,25 +136,46 @@ pub struct TexUse<'a> {
pub surface: &'a Surface,
}
+/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct MapRef {
+ pub fx: usize,
+ pub item: usize,
+ pub map: usize,
+}
+
#[derive(Clone, Debug)]
pub struct Pass<'a> {
pub kernel: Kernel,
pub dst: Slot,
pub a: Option<Slot>,
pub b: Option<Slot>,
+ pub c: Option<Slot>,
pub mode: BlendMode,
pub opacity: f32,
/// Layer pixels (raster / text / shape / smart cache / fill cache).
pub tex: Option<TexUse<'a>>,
- /// Colour outside `tex` (the surface's default pixel), or the solid fill colour.
+ /// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect
+ /// colour.
pub color: [f32; 4],
pub mask: Option<MaskUse<'a>>,
- /// Adjustment kind (see `adjust` in compose.wgsl) and parameters.
+ /// Adjustment kind (see `adjust` in compose.wgsl) and parameters; the coverage kind of an
+ /// effect paint.
pub adjust_kind: i32,
pub params: [[f32; 4]; 4],
- /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient fill stops).
+ pub extra: [f32; 4],
+ /// Extra shader flags (`F_KNOCKOUT`, …).
+ pub flags: u32,
+ /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient stops).
pub lut: Option<Vec<[f32; 4096]>>,
pub gradient: bool,
+ /// Effect map sampled by `FxPaint`.
+ pub map: Option<MapRef>,
+ /// Pattern painted by `FxPaint`.
+ pub pattern: Option<&'a Pattern>,
+ /// Only pixels inside this rect (document coordinates) are computed; the pass is skipped for
+ /// chunks it misses. Consumers of the slot must be clipped alike.
+ pub clip: Option<Rect>,
}
#[derive(Clone, Copy, Debug)]
@@ -74,8 +187,28 @@ pub struct MaskUse<'a> {
}
impl<'a> Pass<'a> {
- fn new(kernel: Kernel, dst: Slot) -> Self {
- Pass { kernel, dst, a: None, b: None, mode: BlendMode::Normal, opacity: 1.0, tex: None, color: [0.0; 4], mask: None, adjust_kind: 0, params: [[0.0; 4]; 4], lut: None, gradient: false }
+ pub(crate) fn new(kernel: Kernel, dst: Slot) -> Self {
+ Pass {
+ kernel,
+ dst,
+ a: None,
+ b: None,
+ c: None,
+ mode: BlendMode::Normal,
+ opacity: 1.0,
+ tex: None,
+ color: [0.0; 4],
+ mask: None,
+ adjust_kind: 0,
+ params: [[0.0; 4]; 4],
+ extra: [0.0; 4],
+ flags: 0,
+ lut: None,
+ gradient: false,
+ map: None,
+ pattern: None,
+ clip: None,
+ }
}
}
@@ -91,38 +224,96 @@ impl std::fmt::Display for Unsupported {
impl std::error::Error for Unsupported {}
+/// A layer whose effects the plan renders: its maps are built (or reused) before the chunks run.
+#[derive(Clone, Copy, Debug)]
+pub struct FxLayer<'a> {
+ pub layer: &'a Layer,
+ /// Region the maps cover (`compose::effect_maps`).
+ pub region: Rect,
+ /// Layer bounds (gradients and linked patterns are laid out in them).
+ pub bounds: Rect,
+}
+
#[derive(Debug)]
pub struct Plan<'a> {
pub passes: Vec<Pass<'a>>,
pub slots: u32,
pub root: Slot,
+ /// Effect layers in dependency order (a group's inner effect layers come first).
+ pub fx: Vec<FxLayer<'a>>,
+}
+
+/// Document-level inputs of a plan.
+#[derive(Clone, Copy)]
+pub struct DocCtx<'a> {
+ pub canvas: Rect,
+ pub transfer: Transfer,
+ pub light: GlobalLight,
+ pub patterns: &'a [Pattern],
+}
+
+impl<'a> DocCtx<'a> {
+ pub fn of(doc: &'a Document) -> Self {
+ DocCtx { canvas: doc.bounds(), transfer: Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns }
+ }
}
/// Build the pass list for `doc`.
pub fn plan(doc: &Document) -> Result<Plan<'_>, Unsupported> {
- let mut p = Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), canvas: doc.bounds(), transfer: Transfer::for_mode(doc.mode) };
+ let mut p = Planner::new(DocCtx::of(doc));
let root = p.clear();
let root = p.stack(&doc.layers, root)?;
- Ok(Plan { passes: p.passes, slots: p.refs.len() as u32, root })
+ Ok(p.finish(root))
}
struct Planner<'a> {
passes: Vec<Pass<'a>>,
free: Vec<Slot>,
refs: Vec<u32>,
- canvas: Rect,
- transfer: Transfer,
+ cx: DocCtx<'a>,
+ fx: Vec<FxLayer<'a>>,
}
-fn mask_use(layer: &Layer) -> Option<MaskUse<'_>> {
- let m = layer.mask.as_ref()?;
- if !m.enabled {
- return None;
- }
- Some(MaskUse { layer: layer.id, surface: &m.surface, density: m.density, default: m.surface.default_pixel().first().copied().unwrap_or(1.0) })
+/// Coverage source of an effect paint (`kind` in `fs_fxpaint`); flags refine it.
+#[derive(Clone, Copy)]
+enum Cov {
+ /// An effect map; `outside` beyond its region.
+ Map(MapRef, f32),
+ /// Full coverage.
+ One,
}
+/// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with
+/// `a` the layer's alpha and `inside` = `a > 0.5/255`:
+/// knockout `m × (1 − a)`; gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`;
+/// stroke-out `inside ? (vector ? 0 : 1) : m`.
+pub const F_KNOCKOUT: u32 = 16;
+/// Paint beneath A instead of over it (outside strokes).
+pub const F_UNDER: u32 = 32;
+/// Shape layer (outside strokes never show inside it).
+pub const F_VECTOR: u32 = 64;
+/// Merge onto an opaque clipping base, keeping its alpha.
+pub const F_ATOP: u32 = 128;
+pub const F_GATE: u32 = 256;
+pub const F_REL: u32 = 512;
+pub const F_STROKE_OUT: u32 = 1024;
+
+/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity`
+/// inside B's shape; A with alpha × B's alpha.
+pub const INIT_SCALE: i32 = 0;
+pub const INIT_OPAQUE: i32 = 1;
+pub const INIT_INSIDE: i32 = 2;
+pub const INIT_ALPHA: i32 = 3;
+
impl<'a> Planner<'a> {
+ fn new(cx: DocCtx<'a>) -> Self {
+ Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new() }
+ }
+
+ fn finish(self, root: Slot) -> Plan<'a> {
+ Plan { passes: self.passes, slots: self.refs.len() as u32, root, fx: self.fx }
+ }
+
fn alloc(&mut self) -> Slot {
if let Some(s) = self.free.pop() {
self.refs[s as usize] = 1;
@@ -146,13 +337,10 @@ impl<'a> Planner<'a> {
fn emit(&mut self, mut pass: Pass<'a>) -> Slot {
let dst = self.alloc();
pass.dst = dst;
- let (a, b) = (pass.a, pass.b);
+ let (a, b, c) = (pass.a, pass.b, pass.c);
self.passes.push(pass);
- if let Some(a) = a {
- self.release(a);
- }
- if let Some(b) = b {
- self.release(b);
+ for s in [a, b, c].into_iter().flatten() {
+ self.release(s);
}
dst
}
@@ -182,9 +370,6 @@ impl<'a> Planner<'a> {
if layer.artboard().is_some() {
return Err(Unsupported(format!("artboard `{}` (clipped and rendered on the CPU)", layer.name)));
}
- if has_effects(layer) {
- return Err(Unsupported(format!("layer effects on `{}`", layer.name)));
- }
if layer.vector_mask.is_some() {
return Err(Unsupported(format!("vector mask on `{}`", layer.name)));
}
@@ -196,21 +381,23 @@ impl<'a> Planner<'a> {
Ok(())
}
+ fn mask_use(&self, layer: &'a Layer) -> Option<MaskUse<'a>> {
+ let m = layer.mask.as_ref()?;
+ if !m.enabled {
+ return None;
+ }
+ Some(MaskUse { layer: layer.id, surface: &m.surface, density: m.density, default: m.surface.default_pixel().first().copied().unwrap_or(1.0) })
+ }
+
/// composite_layer
fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {
self.check(layer)?;
let opacity = layer.opacity * layer.fill_opacity;
let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect();
- if let LayerContent::Shape(sh) = &layer.content
- && sh.stroke.is_some()
- && !visible_clipped.is_empty()
- {
- // The vector stroke goes above the clipped layers (CPU path splits fill and stroke).
- return Err(Unsupported(format!("stroked shape `{}` with clipped layers", layer.name)));
- }
if let LayerContent::Group(g) = &layer.content
&& layer.blend == BlendMode::PassThrough
+ && !has_effects(layer)
{
if !visible_clipped.is_empty() {
return Err(Unsupported(format!("layers clipped to pass-through group `{}`", layer.name)));
@@ -222,7 +409,7 @@ impl<'a> Planner<'a> {
p.a = Some(before);
p.b = Some(after);
p.opacity = opacity;
- p.mask = mask_use(layer);
+ p.mask = self.mask_use(layer);
return Ok(self.emit(p));
}
self.release(before);
@@ -240,10 +427,22 @@ impl<'a> Planner<'a> {
p.b = Some(adjusted);
p.mode = layer.blend;
p.opacity = opacity;
- p.mask = mask_use(layer);
+ p.mask = self.mask_use(layer);
return Ok(self.emit(p));
}
+ if has_effects(layer) {
+ return self.effects(layer, &visible_clipped, backdrop, false);
+ }
+
+ if let LayerContent::Shape(sh) = &layer.content
+ && sh.stroke.is_some()
+ && !visible_clipped.is_empty()
+ {
+ // The vector stroke goes above the clipped layers (CPU path splits fill and stroke).
+ return Err(Unsupported(format!("stroked shape `{}` with clipped layers", layer.name)));
+ }
+
let mut content = self.content(layer)?;
for c in visible_clipped {
content = self.atop(c, content)?;
@@ -265,30 +464,35 @@ impl<'a> Planner<'a> {
if layer.mask.is_some() {
let mut p = Pass::new(Kernel::Mask, 0);
p.a = Some(s);
- p.mask = mask_use(layer);
+ p.mask = self.mask_use(layer);
return Ok(self.emit(p));
}
Ok(s)
}
LayerContent::Adjustment(_) => unreachable!("adjustments handled by the caller"),
- LayerContent::Fill(f) => {
- let mut p = Pass::new(Kernel::Content, 0);
- p.mask = mask_use(layer);
- match &layer.fill_cache {
- Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface),
- _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.canvas)),
- }
+ _ => {
+ let p = self.content_pass(layer);
Ok(self.emit(p))
}
+ }
+ }
+
+ /// The Content pass of a raster / text / shape / smart / fill layer.
+ fn content_pass(&self, layer: &'a Layer) -> Pass<'a> {
+ let mut p = Pass::new(Kernel::Content, 0);
+ p.mask = self.mask_use(layer);
+ match &layer.content {
+ LayerContent::Fill(f) => match &layer.fill_cache {
+ Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface),
+ _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas)),
+ },
_ => {
- let mut p = Pass::new(Kernel::Content, 0);
- p.mask = mask_use(layer);
if let Some(s) = layer.surface() {
self.surface_tex(&mut p, layer.id, s);
}
- Ok(self.emit(p))
}
}
+ p
}
fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) {
@@ -307,14 +511,7 @@ impl<'a> Planner<'a> {
}
Fill::Gradient { stops, angle, scale, style, reverse } => {
p.gradient = true;
- let style_i = match style {
- photocraft_doc::GradientStyle::Linear => 0.0,
- photocraft_doc::GradientStyle::Radial => 1.0,
- photocraft_doc::GradientStyle::Angle => 2.0,
- photocraft_doc::GradientStyle::Reflected => 3.0,
- photocraft_doc::GradientStyle::Diamond => 4.0,
- };
- p.params[0] = [*angle, *scale, if *reverse { 1.0 } else { 0.0 }, style_i];
+ p.params[0] = [*angle, *scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)];
let c = frame;
p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32];
let conv: Vec<(f32, [f32; 4])> = stops
@@ -350,9 +547,12 @@ impl<'a> Planner<'a> {
p.b = Some(adjusted);
p.mode = layer.blend;
p.opacity = opacity;
- p.mask = mask_use(layer);
+ p.mask = self.mask_use(layer);
return Ok(self.emit(p));
}
+ if has_effects(layer) {
+ return self.effects(layer, &[], base, true);
+ }
let content = self.content(layer)?;
let mut p = Pass::new(Kernel::Atop, 0);
p.a = Some(base);
@@ -366,12 +566,282 @@ impl<'a> Planner<'a> {
fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Slot {
let mut p = Pass::new(Kernel::Adjust, 0);
p.a = Some(src);
- let (kind, params, lut) = adjustment_program(adj, self.transfer);
+ let (kind, params, lut) = adjustment_program(adj, self.cx.transfer);
p.adjust_kind = kind;
p.params = params;
p.lut = lut;
self.emit(p)
}
+
+ /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop`
+ /// (atop = true: effects over the base treated as opaque, keeping the base's alpha).
+ /// Consumes `backdrop`.
+ fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result<Slot, Unsupported> {
+ let canvas = self.cx.canvas;
+ let region = bounds::effect_region(layer, canvas);
+ let sb = bounds::layer_bounds(layer, canvas);
+ let clip = if bounds::transparent_outside(layer) { region } else { canvas };
+ let mut content = self.content(layer)?;
+ if !matches!(layer.content, LayerContent::Group(_))
+ && let Some(p) = self.passes.last_mut()
+ {
+ p.clip = Some(clip);
+ }
+ for c in clipped {
+ content = self.atop(c, content)?;
+ }
+ let fx = self.fx.len();
+ self.fx.push(FxLayer { layer, region, bounds: sb });
+
+ let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect();
+ // Linked patterns tile from the effects reference point (else the layer's top-left).
+ let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0)));
+ let vector_shape = matches!(layer.content, LayerContent::Shape(_));
+ let map = |item: usize, map: usize| MapRef { fx, item, map };
+ let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect();
+ let init = |s: &mut Self, src: Slot, b: Option<Slot>, kind: i32, opacity: f32| {
+ let mut p = Pass::new(Kernel::FxInit, 0);
+ p.a = Some(src);
+ p.b = b;
+ p.adjust_kind = kind;
+ p.opacity = opacity;
+ p.clip = Some(clip);
+ s.emit(p)
+ };
+
+ // Exterior effects over the backdrop (an opaque copy of it for clipped layers).
+ let mut w = if atop {
+ let b = self.retain(backdrop);
+ init(self, b, None, INIT_OPAQUE, 1.0)
+ } else {
+ self.retain(backdrop)
+ };
+ for &(i, e) in &rev {
+ if let Effect::DropShadow(s) = e {
+ let flags = if s.knocks_out { F_KNOCKOUT } else { 0 };
+ w = self.paint(w, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, flags, clip, sb);
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::OuterGlow(g) = e {
+ let paint = self.fx_paint(&g.paint, anchor);
+ w = self.paint(w, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, 0, clip, sb);
+ }
+ }
+
+ // The layer: its colour at fill opacity inside its shape; interior effects are painted
+ // relative to the shape (coverage within it), then the shape's alpha applies.
+ let c = self.retain(content);
+ let mut l = init(self, c, None, INIT_INSIDE, layer.fill_opacity);
+ for &(_, e) in &rev {
+ if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e
+ && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty())
+ {
+ let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle));
+ l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb);
+ }
+ }
+ for &(_, e) in &rev {
+ if let Effect::GradientOverlay { common, gradient, .. } = e {
+ l = self.paint(l, content, Cov::One, &Paint::Gradient(gradient), common.blend, common.opacity, F_GATE, clip, sb);
+ }
+ }
+ for &(_, e) in &rev {
+ if let Effect::ColorOverlay { common, color } = e {
+ l = self.paint(l, content, Cov::One, &Paint::Color(color.to_rgb()), common.blend, common.opacity, F_GATE, clip, sb);
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::Satin(s) = e {
+ l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb);
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::InnerGlow(g) = e {
+ let paint = self.fx_paint(&g.paint, anchor);
+ l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_REL, clip, sb);
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::InnerShadow(s) = e {
+ l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb);
+ }
+ }
+ // Inside stroke parts are painted over the layer (bottom instance first).
+ for &(i, e) in &rev {
+ if let Effect::Stroke(st) = e {
+ let (in_w, _) = stroke_widths(st);
+ if in_w > 0.0 {
+ let paint = self.fx_paint(&st.paint, anchor);
+ l = self.paint(l, content, Cov::Map(map(i, 1), (in_w + 0.5).clamp(0.0, 1.0)), &paint, st.common.blend, st.common.opacity, F_GATE, clip, sb);
+ }
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::BevelEmboss(b) = e
+ && b.style != photocraft_doc::BevelStyle::OuterBevel
+ {
+ l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(b.highlight_color.to_rgb()), b.highlight.blend, b.highlight.opacity, F_REL, clip, sb);
+ l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb);
+ }
+ }
+ // The shape's own alpha.
+ let c = self.retain(content);
+ l = init(self, l, Some(c), INIT_ALPHA, 1.0);
+ // Outside stroke parts slide beneath the layer (top instance first).
+ for (i, e) in items.iter().copied().enumerate() {
+ if let Effect::Stroke(st) = e
+ && stroke_widths(st).1 > 0.0
+ {
+ let paint = self.fx_paint(&st.paint, anchor);
+ let flags = F_UNDER | F_STROKE_OUT | if vector_shape { F_VECTOR } else { 0 };
+ l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, BlendMode::Normal, st.common.opacity, flags, clip, sb);
+ }
+ }
+ for &(i, e) in &rev {
+ if let Effect::BevelEmboss(b) = e
+ && b.style == photocraft_doc::BevelStyle::OuterBevel
+ {
+ w = self.paint(w, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(b.highlight_color.to_rgb()), b.highlight.blend, b.highlight.opacity, 0, clip, sb);
+ w = self.paint(w, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb);
+ }
+ }
+
+ let mut p = Pass::new(Kernel::FxMerge, 0);
+ p.a = Some(w);
+ p.b = Some(l);
+ p.c = Some(self.retain(backdrop));
+ p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend };
+ p.opacity = layer.opacity;
+ p.flags = if atop { F_ATOP } else { 0 };
+ p.clip = Some(clip);
+ let merged = self.emit(p);
+ self.release(content);
+
+ // Write the clipped result back into the backdrop (in place when nothing else holds it).
+ let dst = if self.refs[backdrop as usize] == 1 {
+ backdrop
+ } else {
+ let n = self.alloc();
+ let mut p = Pass::new(Kernel::CopyFull, n);
+ p.a = Some(backdrop);
+ self.passes.push(p);
+ self.release(backdrop);
+ n
+ };
+ let mut p = Pass::new(Kernel::CopyRect, dst);
+ p.a = Some(merged);
+ p.clip = Some(clip);
+ self.passes.push(p);
+ self.release(merged);
+ Ok(dst)
+ }
+
+ fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> {
+ match p {
+ FxPaint::Color(c) => Paint::Color(c.to_rgb()),
+ FxPaint::Gradient(g) => Paint::Gradient(g),
+ FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty()) {
+ Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)),
+ None => Paint::None,
+ },
+ }
+ }
+
+ /// One effect paint into `dst` (consumed); reads the layer's alpha from `content` (kept).
+ #[allow(clippy::too_many_arguments)]
+ fn paint(&mut self, dst: Slot, content: Slot, cov: Cov, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Slot {
+ if matches!(paint, Paint::None) {
+ // Missing pattern: compose paints nothing.
+ return dst;
+ }
+ let mut p = Pass::new(Kernel::FxPaint, 0);
+ p.a = Some(dst);
+ p.b = Some(self.retain(content));
+ p.mode = blend;
+ p.opacity = opacity;
+ p.flags = flags;
+ p.clip = Some(clip);
+ match cov {
+ Cov::Map(m, outside) => {
+ p.adjust_kind = 0;
+ p.map = Some(m);
+ p.params[2][3] = outside;
+ }
+ Cov::One => p.adjust_kind = 1,
+ }
+ match paint {
+ Paint::None => {}
+ Paint::Color(c) => p.color = [c[0], c[1], c[2], 1.0],
+ Paint::Gradient(g) => {
+ p.params[0] = [g.angle, g.scale, if g.reverse { 1.0 } else { 0.0 }, style_index(g.style)];
+ p.params[1] = [sb.x0 as f32, sb.y0 as f32, sb.width() as f32, sb.height() as f32];
+ p.params[2][0] = g.offset.0;
+ p.params[2][1] = g.offset.1;
+ p.params[2][2] = 1.0;
+ let mut rows = vec![[0.0f32; 4096]; 4];
+ for k in 0..4096 {
+ let v = photocraft_compose::effects::sample_gradient(g, k as f32 / 4095.0);
+ for (ch, row) in rows.iter_mut().enumerate() {
+ row[k] = v[ch];
+ }
+ }
+ p.lut = Some(rows);
+ }
+ Paint::Pattern(pat, pl) => {
+ p.params[2][2] = 2.0;
+ p.params[3] = [pl.origin.0 as f32, pl.origin.1 as f32, pl.cs.0 as f32, pl.cs.1 as f32];
+ p.extra = [pl.inv_scale as f32, pat.width as f32, pat.height as f32, 0.0];
+ p.pattern = Some(pat);
+ }
+ }
+ self.emit(p)
+ }
+}
+
+/// Paint source of an effect.
+enum Paint<'a> {
+ None,
+ Color([f32; 3]),
+ Gradient(&'a Gradient),
+ Pattern(&'a Pattern, Placement),
+}
+
+/// `compose::pattern::Placement` (origin, inverse rotation, inverse scale).
+#[derive(Clone, Copy, Debug)]
+struct Placement {
+ origin: (f64, f64),
+ cs: (f64, f64),
+ inv_scale: f64,
+}
+
+/// `Placement::anchored`: linked patterns tile from `anchor` (the effects reference point).
+fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement {
+ let base = if link { anchor } else { (0.0, 0.0) };
+ let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1));
+ let s = f64::from(scale);
+ let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 };
+ let a = f64::from(angle).to_radians();
+ Placement { origin, cs: (a.cos(), a.sin()), inv_scale }
+}
+
+/// (inside width, outside width) of a stroke.
+pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) {
+ match st.position {
+ StrokePosition::Outside => (0.0, st.size),
+ StrokePosition::Inside => (st.size, 0.0),
+ StrokePosition::Center => (st.size / 2.0, st.size / 2.0),
+ }
+}
+
+fn style_index(s: photocraft_doc::GradientStyle) -> f32 {
+ match s {
+ photocraft_doc::GradientStyle::Linear => 0.0,
+ photocraft_doc::GradientStyle::Radial => 1.0,
+ photocraft_doc::GradientStyle::Angle => 2.0,
+ photocraft_doc::GradientStyle::Reflected => 3.0,
+ photocraft_doc::GradientStyle::Diamond => 4.0,
+ }
}
fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {
@@ -585,9 +1055,21 @@ mod tests {
}
#[test]
- fn effects_are_unsupported() {
+ fn effects_are_planned_in_place() {
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
- d.layers[0].effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE });
- assert!(plan(&d).is_err());
+ let mut l = Layer::raster("fx", d.pixel_format());
+ l.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 5, 5), &[1.0, 0.0, 0.0, 1.0]);
+ l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE });
+ l.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
+ d.layers.push(l);
+ let p = plan(&d).unwrap();
+ assert_eq!(p.fx.len(), 1);
+ let m = photocraft_compose::effects::margin(&d.layers[1]);
+ assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m)));
+ // The effect result lands back in the backdrop slot.
+ let last = p.passes.last().unwrap();
+ assert_eq!(last.kernel, Kernel::CopyRect);
+ assert_eq!(last.dst, p.root);
+ assert!(p.slots <= 6, "{} slots", p.slots);
}
}
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 587262e26..0e9534258 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -298,3 +298,353 @@ fn incremental_updates_follow_the_document() {
d.layers[0].opacity = 0.5;
check(&mut g, &d, "opacity");
}
+
+// ---- layer effects --------------------------------------------------------------------------
+
+use photocraft_doc::adjust::CurvePoint as Cp;
+use photocraft_doc::{
+ Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, Pattern, Satin, Shadow, StrokeFx, StrokePosition,
+};
+
+/// An anti-aliased blob (disc plus a soft-edged bar and a hole) with partially transparent parts,
+/// so effects see real edge coverage, concavities and interior alpha.
+fn blob(name: &str, fmt: PixelFormat, cx: f32, cy: f32, r: f32, color: [f32; 3]) -> Layer {
+ let mut l = Layer::raster(name, fmt);
+ let rect = Rect::new((cx - r - 12.0) as i32, (cy - r - 4.0) as i32, (cx + r + 14.0) as i32, (cy + r + 4.0) as i32);
+ let ch = fmt.channels();
+ let mut data = Vec::with_capacity(rect.width() as usize * rect.height() as usize * ch);
+ for y in rect.y0..rect.y1 {
+ for x in rect.x0..rect.x1 {
+ let (fx, fy) = (x as f32 + 0.5 - cx, y as f32 + 0.5 - cy);
+ let d = (fx * fx + fy * fy).sqrt();
+ let disc = (r - d + 0.5).clamp(0.0, 1.0);
+ let hole = ((d - r * 0.3) + 0.5).clamp(0.0, 1.0);
+ let bar = ((r * 0.25 - fy.abs()) + 0.5).clamp(0.0, 1.0) * ((r + 10.0 - fx.abs()) * 0.7).clamp(0.0, 1.0);
+ let a = (disc * hole).max(bar * 0.7);
+ let rgba = [color[0] * (0.7 + 0.3 * (fx / r).abs()), color[1], color[2] * (0.8 + 0.2 * (fy / r)), a];
+ let px = photocraft_raster::from_rgba(&fmt, rgba);
+ data.extend_from_slice(&px);
+ }
+ }
+ l.surface_mut().unwrap().write_region(rect, &data);
+ l
+}
+
+fn fx_doc(w: u32, h: u32, depth: SampleType) -> Document {
+ let mut d = Document::new("fx", Size::new(w, h), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, w, h), 7, 0.8));
+ d
+}
+
+fn contour() -> Contour {
+ Contour::Custom { name: "cove".into(), points: vec![Cp { input: 0.0, output: 0.1 }, Cp { input: 0.4, output: 0.8 }, Cp { input: 1.0, output: 0.6 }] }
+}
+
+fn shadow(blend: BlendMode, opacity: f32, angle: f32, distance: f32, size: f32, spread: f32) -> Shadow {
+ Shadow {
+ common: FxCommon::new(blend, opacity),
+ color: Color::rgb(0.1, 0.05, 0.3),
+ angle,
+ use_global_light: false,
+ distance,
+ spread,
+ size,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: true,
+ }
+}
+
+fn glow(paint: FxPaint, technique: GlowTechnique, size: f32, spread: f32, source: GlowSource) -> Glow {
+ Glow { common: FxCommon::new(BlendMode::Screen, 0.8), paint, technique, spread, size, contour: Contour::Linear, anti_alias: false, range: 0.5, jitter: 0.0, noise: 0.0, source }
+}
+
+fn gradient() -> Gradient {
+ Gradient {
+ stops: vec![(0.0, Color::rgb(1.0, 0.2, 0.0)), (0.5, Color::rgb(0.1, 0.9, 0.3)), (1.0, Color::rgb(0.2, 0.1, 1.0))],
+ opacity_stops: vec![(0.0, 1.0), (1.0, 0.4)],
+ style: GradientStyle::Linear,
+ angle: 30.0,
+ scale: 0.9,
+ reverse: false,
+ align: true,
+ offset: (0.1, -0.05),
+ }
+}
+
+fn bevel(style: BevelStyle, up: bool, size: f32, soften: f32) -> Bevel {
+ Bevel {
+ enabled: true,
+ style,
+ technique: BevelTechnique::Smooth,
+ depth: 1.3,
+ up,
+ size,
+ soften,
+ angle: 135.0,
+ altitude: 35.0,
+ use_global_light: true,
+ gloss_contour: Contour::Linear,
+ highlight: FxCommon::new(BlendMode::Screen, 0.8),
+ highlight_color: Color::rgb(1.0, 1.0, 0.9),
+ shadow: FxCommon::new(BlendMode::Multiply, 0.7),
+ shadow_color: Color::rgb(0.1, 0.0, 0.2),
+ }
+}
+
+fn stroke(size: f32, position: StrokePosition, paint: FxPaint) -> StrokeFx {
+ StrokeFx { common: FxCommon::new(BlendMode::Normal, 0.9), size, position, paint }
+}
+
+fn checker_pattern() -> Pattern {
+ let mut s = photocraft_raster::Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(Rect::new(0, 0, 6, 5), &[0.9, 0.2, 0.1, 1.0]);
+ s.fill_rect(Rect::new(0, 0, 3, 3), &[0.1, 0.3, 0.9, 0.6]);
+ s.fill_rect(Rect::new(3, 3, 6, 5), &[0.2, 0.8, 0.3, 1.0]);
+ Pattern::new("checker", s, 6, 5)
+}
+
+/// Every effect kind with several option combinations, one effect stack per case.
+fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
+ let pat = checker_pattern();
+ let pat_paint = FxPaint::Pattern { name: pat.name.clone(), id: pat.id.clone(), scale: 1.0 };
+ let mut ds_contour = shadow(BlendMode::Normal, 0.8, 200.0, 4.0, 9.0, 0.35);
+ ds_contour.contour = contour();
+ ds_contour.knocks_out = false;
+ let mut ds_global = shadow(BlendMode::Multiply, 0.75, 0.0, 6.0, 7.0, 0.0);
+ ds_global.use_global_light = true;
+ let mut og_contour = glow(FxPaint::Color(Color::rgb(1.0, 0.9, 0.2)), GlowTechnique::Softer, 9.0, 0.0, GlowSource::Edge);
+ og_contour.contour = contour();
+ let mut satin_inv = Satin { common: FxCommon::new(BlendMode::Multiply, 0.6), color: Color::rgb(0.3, 0.0, 0.4), angle: 19.0, distance: 7.0, size: 8.0, contour: contour(), anti_alias: false, invert: true };
+ let satin = Satin { common: FxCommon::new(BlendMode::Overlay, 0.7), color: Color::rgb(0.9, 0.4, 0.1), angle: 60.0, distance: 5.0, size: 6.0, contour: Contour::Linear, anti_alias: false, invert: false };
+ satin_inv.common.enabled = true;
+ let mut bevel_contour = bevel(BevelStyle::InnerBevel, true, 8.0, 3.0);
+ bevel_contour.gloss_contour = contour();
+ bevel_contour.use_global_light = false;
+ vec![
+ ("drop shadow", vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.75, 120.0, 6.0, 8.0, 0.0))]),
+ ("drop shadow spread contour", vec![Effect::DropShadow(ds_contour)]),
+ ("drop shadow hard", vec![Effect::DropShadow(shadow(BlendMode::Normal, 1.0, 45.0, 3.0, 0.0, 0.0))]),
+ ("drop shadow global light", vec![Effect::DropShadow(ds_global)]),
+ ("inner shadow", vec![Effect::InnerShadow(shadow(BlendMode::Multiply, 0.8, 120.0, 4.0, 6.0, 0.0))]),
+ ("inner shadow choke", vec![Effect::InnerShadow(shadow(BlendMode::Normal, 0.9, 300.0, 3.0, 7.0, 0.4))]),
+ ("outer glow softer", vec![Effect::OuterGlow(glow(FxPaint::Color(Color::rgb(1.0, 0.9, 0.2)), GlowTechnique::Softer, 10.0, 0.3, GlowSource::Edge))]),
+ ("outer glow contour", vec![Effect::OuterGlow(og_contour)]),
+ ("outer glow precise gradient", vec![Effect::OuterGlow(glow(FxPaint::Gradient(gradient()), GlowTechnique::Precise, 8.0, 0.25, GlowSource::Edge))]),
+ ("inner glow softer edge", vec![Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(0.9, 1.0, 0.8)), GlowTechnique::Softer, 7.0, 0.2, GlowSource::Edge))]),
+ ("inner glow softer center", vec![Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(0.9, 1.0, 0.8)), GlowTechnique::Softer, 6.0, 0.0, GlowSource::Center))]),
+ ("inner glow precise edge", vec![Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(0.2, 1.0, 0.8)), GlowTechnique::Precise, 6.0, 0.3, GlowSource::Edge))]),
+ ("inner glow precise center", vec![Effect::InnerGlow(glow(pat_paint.clone(), GlowTechnique::Precise, 5.0, 0.0, GlowSource::Center))]),
+ ("bevel inner", vec![Effect::BevelEmboss(bevel(BevelStyle::InnerBevel, true, 7.0, 2.0))]),
+ ("bevel outer", vec![Effect::BevelEmboss(bevel(BevelStyle::OuterBevel, true, 6.0, 0.0))]),
+ ("bevel emboss down", vec![Effect::BevelEmboss(bevel(BevelStyle::Emboss, false, 8.0, 1.0))]),
+ ("bevel pillow", vec![Effect::BevelEmboss(bevel(BevelStyle::PillowEmboss, true, 5.0, 4.0))]),
+ ("bevel contour own light", vec![Effect::BevelEmboss(bevel_contour)]),
+ ("satin", vec![Effect::Satin(satin)]),
+ ("satin inverted contour", vec![Effect::Satin(satin_inv)]),
+ ("stroke outside colour", vec![Effect::Stroke(stroke(4.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.95, 0.85, 0.1))))]),
+ ("stroke inside gradient", vec![Effect::Stroke(stroke(3.0, StrokePosition::Inside, FxPaint::Gradient(gradient())))]),
+ ("stroke centre pattern", vec![Effect::Stroke(stroke(5.0, StrokePosition::Center, pat_paint.clone()))]),
+ ("colour overlay", vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Multiply, 0.7), color: Color::rgb(0.2, 0.7, 0.9) }]),
+ ("gradient overlay", vec![Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 0.8), gradient: Gradient { style: GradientStyle::Radial, ..gradient() }, dither: false }]),
+ ("pattern overlay", vec![Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 0.9), name: pat.name.clone(), id: pat.id.clone(), scale: 1.0, angle: 0.0, link: true, phase: (2.0, 1.0) }]),
+ ("pattern overlay scaled rotated", vec![Effect::PatternOverlay { common: FxCommon::new(BlendMode::Screen, 0.8), name: pat.name.clone(), id: pat.id.clone(), scale: 1.7, angle: 30.0, link: false, phase: (0.0, 0.0) }]),
+ (
+ "multiple instances",
+ vec![
+ Effect::Stroke(stroke(2.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0)))),
+ Effect::Stroke(stroke(5.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.1, 0.1, 0.1)))),
+ Effect::DropShadow(shadow(BlendMode::Multiply, 0.6, 90.0, 4.0, 5.0, 0.0)),
+ Effect::DropShadow(shadow(BlendMode::Normal, 0.5, 270.0, 8.0, 3.0, 0.0)),
+ Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 0.3), color: Color::rgb(1.0, 0.0, 0.0) },
+ ],
+ ),
+ (
+ "full stack",
+ vec![
+ Effect::DropShadow(shadow(BlendMode::Multiply, 0.75, 120.0, 5.0, 6.0, 0.1)),
+ Effect::InnerShadow(shadow(BlendMode::Multiply, 0.5, 120.0, 3.0, 4.0, 0.0)),
+ Effect::OuterGlow(glow(FxPaint::Color(Color::rgb(1.0, 1.0, 0.6)), GlowTechnique::Softer, 6.0, 0.0, GlowSource::Edge)),
+ Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(1.0, 1.0, 0.6)), GlowTechnique::Softer, 4.0, 0.0, GlowSource::Edge)),
+ Effect::BevelEmboss(bevel(BevelStyle::InnerBevel, true, 5.0, 1.0)),
+ Effect::Satin(Satin { common: FxCommon::new(BlendMode::Multiply, 0.4), color: Color::rgb(0.0, 0.0, 0.0), angle: 19.0, distance: 4.0, size: 5.0, contour: Contour::Linear, anti_alias: false, invert: false }),
+ Effect::ColorOverlay { common: FxCommon::new(BlendMode::SoftLight, 0.5), color: Color::rgb(0.9, 0.3, 0.2) },
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Overlay, 0.4), gradient: gradient(), dither: false },
+ Effect::Stroke(stroke(3.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.0, 0.0, 0.0)))),
+ ],
+ ),
+ ]
+}
+
+/// GPU vs CPU over the whole document: Err with the worst pixel if over the tolerance.
+fn fx_diff(g: &mut Gpu, doc: &Document, what: &str) -> Result<photocraft_gpu::Stats, String> {
+ let cpu = photocraft_compose::flatten(doc);
+ let (out, stats) = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).map_err(|e| format!("{what}: {e}"))?;
+ let mut worst = (0.0f32, 0usize);
+ for (i, (c, o)) in cpu.px.iter().zip(&out).enumerate() {
+ let pc = [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]];
+ let po = [o[0] * o[3], o[1] * o[3], o[2] * o[3], o[3]];
+ for k in 0..4 {
+ let d = (pc[k] - po[k]).abs();
+ if d.is_nan() || d > worst.0 {
+ worst = (if d.is_nan() { 9.0 } else { d }, i);
+ }
+ }
+ }
+ let w = doc.size.width as usize;
+ let (x, y) = (worst.1 % w, worst.1 / w);
+ if worst.0 > TOL {
+ return Err(format!("{what}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]));
+ }
+ Ok(stats)
+}
+
+fn fx_check(g: &mut Gpu, doc: &Document, what: &str) -> photocraft_gpu::Stats {
+ fx_diff(g, doc, what).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn layer_effects_every_kind() {
+ let Some(mut g) = gpu() else { return };
+ let mut failures = Vec::new();
+ for depth in [SampleType::U8, SampleType::U16] {
+ for (name, fx) in effect_cases() {
+ let mut d = fx_doc(96, 80, depth);
+ d.patterns.push(checker_pattern());
+ let mut l = blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.9, 0.4, 0.2]);
+ l.effects.items = fx;
+ d.layers.push(l);
+ if let Err(e) = fx_diff(&mut g, &d, &format!("{name} {depth:?}")) {
+ failures.push(e);
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
+}
+
+#[test]
+fn layer_effects_opacity_fill_blend_and_off_canvas() {
+ let Some(mut g) = gpu() else { return };
+ let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1;
+ for (opacity, fill, blend) in [(0.7, 1.0, BlendMode::Normal), (1.0, 0.0, BlendMode::Normal), (0.6, 0.35, BlendMode::Multiply), (1.0, 0.5, BlendMode::Screen), (0.8, 1.0, BlendMode::Dissolve)] {
+ let mut d = fx_doc(96, 80, SampleType::U8);
+ let mut l = blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.2, 0.6, 0.9]);
+ l.effects.items = stack.clone();
+ l.opacity = opacity;
+ l.fill_opacity = fill;
+ l.blend = blend;
+ d.layers.push(l);
+ fx_check(&mut g, &d, &format!("opacity {opacity} fill {fill} {blend:?}"));
+ }
+ // Shapes partly off the canvas (their effects reach back in) and a masked effect layer.
+ let mut d = fx_doc(90, 70, SampleType::U8);
+ let mut l = blob("edge", d.pixel_format(), 4.0, 66.0, 18.0, [0.9, 0.9, 0.2]);
+ l.effects.items = stack.clone();
+ l.mask = Some(mask(Rect::new(0, 30, 50, 70), 77, 1.0));
+ d.layers.push(l);
+ fx_check(&mut g, &d, "off canvas + mask");
+ // Disabled master switch / disabled items are ignored.
+ let mut d = fx_doc(64, 64, SampleType::U8);
+ let mut l = blob("off", d.pixel_format(), 30.0, 30.0, 14.0, [0.9, 0.2, 0.2]);
+ l.effects.items = stack;
+ if let Effect::DropShadow(s) = &mut l.effects.items[0] {
+ s.common.enabled = false;
+ }
+ d.layers.push(l.clone());
+ fx_check(&mut g, &d, "disabled item");
+ d.layers[1].effects.enabled = false;
+ fx_check(&mut g, &d, "master switch off");
+}
+
+#[test]
+fn layer_effects_on_groups_clipping_and_fills() {
+ let Some(mut g) = gpu() else { return };
+ let ds = Effect::DropShadow(shadow(BlendMode::Multiply, 0.8, 120.0, 5.0, 6.0, 0.0));
+ let st = Effect::Stroke(stroke(3.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0))));
+ let bv = Effect::BevelEmboss(bevel(BevelStyle::InnerBevel, true, 5.0, 1.0));
+ // Effects on an isolated group and on a pass-through group (rendered isolated).
+ for blend in [BlendMode::Normal, BlendMode::PassThrough] {
+ let mut d = fx_doc(100, 80, SampleType::U8);
+ let a = blob("a", d.pixel_format(), 35.0, 35.0, 16.0, [0.9, 0.3, 0.2]);
+ let mut b = blob("b", d.pixel_format(), 62.0, 45.0, 14.0, [0.2, 0.3, 0.9]);
+ b.blend = BlendMode::Screen;
+ b.effects.items = vec![Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(1.0, 1.0, 0.5)), GlowTechnique::Softer, 4.0, 0.0, GlowSource::Edge))];
+ let mut grp = Layer::group("g", vec![a, b]);
+ grp.blend = blend;
+ grp.opacity = 0.85;
+ grp.effects.items = vec![ds.clone(), st.clone()];
+ d.layers.push(grp);
+ fx_check(&mut g, &d, &format!("group {blend:?}"));
+ }
+ // An effect layer as a clipping base, and a clipped layer with effects.
+ let mut d = fx_doc(100, 80, SampleType::U8);
+ let mut base = blob("base", d.pixel_format(), 45.0, 40.0, 24.0, [0.3, 0.8, 0.4]);
+ base.effects.items = vec![ds.clone(), bv.clone()];
+ let mut c1 = noise_layer("c1", PixelFormat::RGBA8, Rect::new(10, 10, 60, 50), 91, 0.4);
+ c1.clipped = true;
+ c1.blend = BlendMode::Multiply;
+ let mut c2 = blob("c2", d.pixel_format(), 60.0, 50.0, 12.0, [0.9, 0.9, 0.1]);
+ c2.clipped = true;
+ c2.effects.items = vec![st.clone(), ds.clone()];
+ c2.opacity = 0.8;
+ d.layers.extend([base, c1, c2]);
+ fx_check(&mut g, &d, "clipping with effects");
+ // A solid fill layer with a mask and effects; a gradient fill with a stroke.
+ let mut d = fx_doc(90, 70, SampleType::U8);
+ let mut solid = Layer::new("solid", LayerContent::Fill(Fill::Solid(Color::rgb(0.2, 0.5, 0.8))));
+ let mut m = LayerMask::reveal_all();
+ m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[0.0]);
+ m.surface.fill_rect(Rect::new(20, 15, 60, 50), &[1.0]);
+ solid.mask = Some(m);
+ solid.effects.items = vec![ds.clone(), st.clone(), bv];
+ d.layers.push(solid);
+ fx_check(&mut g, &d, "solid fill with effects");
+}
+
+#[test]
+fn layer_effects_update_incrementally() {
+ let Some(mut g) = gpu() else { return };
+ let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1;
+ let mut d = fx_doc(700, 600, SampleType::U8);
+ let mut l = blob("fx", d.pixel_format(), 300.0, 280.0, 200.0, [0.9, 0.4, 0.2]);
+ l.effects.items = stack;
+ d.layers.push(l);
+ d.layers.push(noise_layer("plain", PixelFormat::RGBA8, Rect::new(500, 20, 650, 120), 5, 0.0));
+ let first = fx_check(&mut g, &d, "initial");
+ assert!(first.fx_programs > 0 && first.fx_shapes == 1);
+ // An unrelated edit (another layer's pixels, the effect layer's opacity and an effect colour)
+ // reuses every map.
+ d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(520, 30, 560, 60), &[0.0, 1.0, 0.0, 1.0]);
+ d.layers[1].opacity = 0.8;
+ if let Effect::ColorOverlay { color, .. } = &mut d.layers[1].effects.items[6] {
+ *color = Color::rgb(0.1, 0.9, 0.9);
+ }
+ let s = fx_check(&mut g, &d, "unrelated edit");
+ assert_eq!((s.fx_shapes, s.fx_programs), (0, 0), "{s:?}");
+ // A dab on the effect layer recomputes a neighbourhood of it only.
+ d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(290, 270, 330, 300), &[0.1, 0.1, 0.9, 1.0]);
+ let s = fx_check(&mut g, &d, "dab on the effect layer");
+ assert_eq!(s.fx_shapes, 1);
+ assert!(s.fx_pixels < first.fx_pixels / 2, "partial {} vs full {}", s.fx_pixels, first.fx_pixels);
+ // Erasing to the layer's edge grows nothing; erasing all of it empties the effects.
+ d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(80, 60, 200, 200), &[0.0, 0.0, 0.0, 0.0]);
+ fx_check(&mut g, &d, "erase part");
+ // A setting change that keeps the effect reach rebuilds that effect only.
+ if let Effect::DropShadow(s) = &mut d.layers[1].effects.items[0] {
+ s.spread = 0.3;
+ }
+ let s = fx_check(&mut g, &d, "drop shadow spread");
+ assert_eq!(s.fx_programs, 1, "{s:?}");
+ // Moving the layer (new region) rebuilds everything.
+ let moved = {
+ let src = d.layers[1].surface().unwrap();
+ let b = src.content_bounds();
+ let mut dst = photocraft_raster::Surface::new(src.format());
+ dst.write_region(Rect::new(b.x0 + 17, b.y0 - 9, b.x1 + 17, b.y1 - 9), &src.read_region(b));
+ dst
+ };
+ *d.layers[1].surface_mut().unwrap() = moved;
+ fx_check(&mut g, &d, "moved");
+}
diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs
index bdccd8ad4..1fe76b93b 100644
--- a/crates/io/examples/oracle_diff.rs
+++ b/crates/io/examples/oracle_diff.rs
@@ -17,6 +17,9 @@ fn main() {
for l in doc.walk() {
let l = l.2;
println!(" layer {:?} {:?} blend {:?} op {} fill {} fill_cache {}", l.name, l.content.kind_name(), l.blend, l.opacity, l.fill_opacity, l.fill_cache.is_some());
+ if let photocraft_doc::LayerContent::Adjustment(a) = &l.content {
+ println!(" {}", format!("{a:?}").chars().take(800).collect::<String>());
+ }
if let photocraft_doc::LayerContent::Fill(f) = &l.content {
println!(" {f:?}");
}
@@ -29,6 +32,22 @@ fn main() {
let row: Vec<String> = (b.x0..b.x0 + 4).chain(b.x1 - 4..b.x1).map(|x| format!("{x}:{:.2}", m.surface.pixel(x, (b.y0 + b.y1) / 2)[0])).collect();
println!(" mask row: {}", row.join(" "));
}
+ if let Some(sf) = l.surface() {
+ let b = sf.content_bounds();
+ let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
+ for y in b.y0..b.y1 {
+ for x in b.x0..b.x1 {
+ let p = sf.pixel(x, y);
+ if p[p.len() - 1] > 0.0 {
+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
+ }
+ }
+ }
+ println!(" alpha bounds ({x0},{y0})-({x1},{y1})");
+ }
+ if let photocraft_doc::LayerContent::Shape(sh) = &l.content {
+ println!(" shape path bounds {:?}", sh.path.control_bounds());
+ }
if let Some(vm) = &l.vector_mask {
println!(" vector mask bounds {:?}", vm.path.control_bounds());
}
@@ -99,7 +118,7 @@ fn main() {
}
for rec in file.layers() {
println!("-- layer {:?}", String::from_utf8_lossy(&rec.name));
- if let Some(b) = rec.block(b"lfx2").or(rec.block(b"lmfx"))
+ if let Some(b) = rec.block(b"lmfx").or(rec.block(b"lfx2")).or(rec.block(b"lfxs"))
&& let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..])
{
walk(&vd.descriptor, 1);
@@ -133,6 +152,37 @@ fn main() {
println!("wrote {out}");
return;
}
+ if std::env::args().nth(3).as_deref() == Some("layerpx") {
+ // layerpx x y: each layer's own pixel (0-255).
+ let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0);
+ let y: i32 = std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0);
+ for l in doc.walk() {
+ if let Some(s) = l.2.surface() {
+ println!("{:?}: {:?}", l.2.name, s.pixel(x, y).iter().map(|v| (v * 255.0 * 100.0).round() / 100.0).collect::<Vec<_>>());
+ }
+ }
+ return;
+ }
+ if std::env::args().nth(3).as_deref() == Some("grid") {
+ // grid x0 y0 x1 y1 [channel]: ours / photoshop values (0-255, premultiplied colour).
+ let w = doc.size.width as usize;
+ let a: Vec<usize> = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect();
+ let ch: usize = std::env::args().nth(8).and_then(|s| s.parse().ok()).unwrap_or(3);
+ for (label, img) in [("ours", &ours), ("ps", &merged)] {
+ println!("{label} (channel {ch}):");
+ for y in a[1]..a[3] {
+ let row: Vec<String> = (a[0]..a[2])
+ .map(|x| {
+ let p = img[y * w + x];
+ let v = if ch == 3 { p[3] } else { p[ch] * p[3] };
+ format!("{:4}", (v * 255.0).round())
+ })
+ .collect();
+ println!(" y={y:4} {}", row.join(""));
+ }
+ }
+ return;
+ }
if std::env::args().nth(3).as_deref() == Some("worst") {
// The N worst pixels (premultiplied max channel error), with coordinates.
let w = doc.size.width as usize;
diff --git a/crates/io/examples/pattern_fit.rs b/crates/io/examples/pattern_fit.rs
index d0ded162c..46552918e 100644
--- a/crates/io/examples/pattern_fit.rs
+++ b/crates/io/examples/pattern_fit.rs
@@ -1,41 +1,31 @@
-//! TEMPORARY: fit the pattern tiling origin against Photoshop's merged image.
-//! args: file.psd x0 y0 x1 y1 (region with opaque pattern pixels)
+//! TEMPORARY: transfer-curve fit for an adjustment layer vs Photoshop's merged image.
+//! args: file.psd "layer name" x0 y0 x1 y1
fn main() {
let a: Vec<String> = std::env::args().collect();
let bytes = std::fs::read(&a[1]).unwrap();
let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();
let imp = photocraft_io::import(&a[1], &bytes).unwrap();
- let doc = &imp.document;
+ let mut doc = imp.document.clone();
let merged = photocraft_io::merged_composite(&file).unwrap();
let w = doc.size.width as usize;
- for rec in file.layers() {
- println!("rec {:?} rect t{} l{} b{} r{}", String::from_utf8_lossy(&rec.name), rec.rect.top, rec.rect.left, rec.rect.bottom, rec.rect.right);
- }
- let p = &doc.patterns[0];
- let tile = photocraft_compose::pattern::Tile::new(p).unwrap();
- let (pw, ph) = (p.width as i64, p.height as i64);
- let r: Vec<i64> = a[2..6].iter().map(|s| s.parse().unwrap()).collect();
- let mut best = Vec::new();
- for oy in 0..ph {
- for ox in 0..pw {
- let mut err = 0.0f64;
- let mut n = 0;
- for y in (r[1]..r[3]).step_by(1) {
- for x in (r[0]..r[2]).step_by(1) {
- let m = merged[y as usize * w + x as usize];
- if m[3] < 0.999 {
- continue;
- }
- let t = tile.sample((x - ox) as f64 + 0.5, (y - oy) as f64 + 0.5);
- err += (0..3).map(|c| (t[c] - m[c]).abs() as f64).sum::<f64>();
- n += 1;
- }
- }
- best.push((err / n.max(1) as f64, ox, oy));
+ let r: Vec<usize> = a[3..7].iter().map(|s| s.parse().unwrap()).collect();
+ let id = doc.walk().into_iter().find(|t| t.2.name == a[2]).map(|t| t.2.id).expect("layer");
+ doc.layer_mut(id).unwrap().visible = false;
+ let below = photocraft_compose::flatten(&doc).px;
+ let mut acc = vec![(0.0f64, 0usize); 256];
+ for y in r[1]..r[3] {
+ for x in r[0]..r[2] {
+ let i = y * w + x;
+ let v = (below[i][0] * 255.0).round().clamp(0.0, 255.0) as usize;
+ acc[v].0 += f64::from(merged[i][0]) * 255.0;
+ acc[v].1 += 1;
}
}
- best.sort_by(|a, b| a.0.total_cmp(&b.0));
- for b in best.iter().take(5) {
- println!("origin ({},{}) mean err {:.4}", b.1, b.2, b.0 * 255.0 / 3.0);
+ let mut line = Vec::new();
+ for (v, (s, n)) in acc.iter().enumerate() {
+ if *n > 0 {
+ line.push(format!("{v}:{:.1}", s / *n as f64));
+ }
}
+ println!("{}", line.join(" "));
}
diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs
index 017c14d91..7e42a3201 100644
--- a/crates/io/src/adjust_map.rs
+++ b/crates/io/src/adjust_map.rs
@@ -168,11 +168,105 @@ fn parse_any(key: &[u8; 4], data: &[u8], cged: Option<&[u8]>) -> Adjustment {
b"curv" => parse_curves(data),
b"selc" => parse_selective(data),
b"clrL" => parse_lookup(data),
+ b"grdm" => parse_gradient_map(data),
_ => None,
};
parsed.unwrap_or_else(|| unsupported(key, data))
}
+fn be32(d: &[u8], at: usize) -> Option<u32> {
+ d.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+}
+
+/// `grdm` (Adobe spec, "Gradient settings"): version (1, or 3 with an interpolation method
+/// key), reverse, dither, [method], name, colour stops (location /4096, midpoint %, colour
+/// space + four u16 components, 2 bytes), transparency stops, then smoothness (/4096) among
+/// noise-gradient fields. Smoothness, midpoints and the method are baked into dense stops like
+/// gradient fills. Noise gradients (no colour stops) and non-RGB stops stay unsupported.
+fn parse_gradient_map(d: &[u8]) -> Option<Adjustment> {
+ let version = be16(d, 0)?;
+ let reverse = *d.get(2)? != 0;
+ let (method, mut at) = match version {
+ 1 => (None, 4),
+ 3 => (Some(d.get(4..8)?), 8),
+ _ => return None,
+ };
+ at += 4 + be32(d, at)? as usize * 2;
+ let n = usize::from(be16(d, at)?);
+ at += 2;
+ let mut stops = Vec::with_capacity(n);
+ let mut mids = Vec::with_capacity(n);
+ for _ in 0..n {
+ let loc = (be32(d, at)? as f32 / 4096.0).clamp(0.0, 1.0);
+ let mid = be32(d, at + 4)? as f32 / 100.0;
+ if be16(d, at + 8)? != 0 {
+ return None;
+ }
+ let c = |k: usize| be16(d, at + 10 + 2 * k).map(|v| f32::from(v) / 65535.0);
+ stops.push((loc, photocraft_color::Color::rgb(c(0)?, c(1)?, c(2)?)));
+ mids.push(mid);
+ at += 20;
+ }
+ if stops.len() < 2 {
+ return None;
+ }
+ let nt = usize::from(be16(d, at)?);
+ at += 2 + nt * 10 + 2; // transparency stops, expansion count
+ let smooth = f32::from(be16(d, at)?) / 4096.0;
+ // Midpoint k applies to the segment after stop k (in location order).
+ let mut order: Vec<usize> = (0..stops.len()).collect();
+ order.sort_by(|a, b| stops[*a].0.total_cmp(&stops[*b].0));
+ let mids: Vec<f32> = order.iter().skip(1).map(|i| mids[*i]).collect();
+ let baked = crate::gradient_bake::bake(stops, &mids, smooth, crate::gradient_bake::Method::from_code(method));
+ let mut stops: Vec<(f32, [f32; 3])> = baked.iter().map(|(t, c)| (*t, c.to_rgb())).collect();
+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));
+ Some(Adjustment::GradientMap { stops, reverse })
+}
+
+/// `grdm` version 1 for [`Adjustment::GradientMap`] (Classic interpolation, Smoothness 0, so
+/// the stops are reproduced exactly).
+fn write_gradient_map(stops: &[(f32, [f32; 3])], reverse: bool) -> Vec<u8> {
+ let mut v = Vec::new();
+ put16(&mut v, 1);
+ v.push(u8::from(reverse));
+ v.push(0);
+ let name: Vec<u16> = "Custom".encode_utf16().chain(std::iter::once(0)).collect();
+ v.extend_from_slice(&(name.len() as u32).to_be_bytes());
+ for u in name {
+ put16(&mut v, u);
+ }
+ put16(&mut v, stops.len().min(usize::from(u16::MAX)) as u16);
+ for (t, c) in stops.iter().take(usize::from(u16::MAX)) {
+ v.extend_from_slice(&((t.clamp(0.0, 1.0) * 4096.0).round() as u32).to_be_bytes());
+ v.extend_from_slice(&50u32.to_be_bytes());
+ put16(&mut v, 0);
+ for k in 0..4 {
+ put16(&mut v, if k < 3 { (c[k].clamp(0.0, 1.0) * 65535.0).round() as u16 } else { 0 });
+ }
+ put16(&mut v, 0);
+ }
+ put16(&mut v, 2);
+ for t in [0u32, 4096] {
+ v.extend_from_slice(&t.to_be_bytes());
+ v.extend_from_slice(&50u32.to_be_bytes());
+ put16(&mut v, 255);
+ }
+ put16(&mut v, 2); // expansion count
+ put16(&mut v, 0); // smoothness
+ put16(&mut v, 32); // length
+ put16(&mut v, 0); // mode
+ v.extend_from_slice(&0u32.to_be_bytes()); // random seed
+ put16(&mut v, 0); // showing transparency
+ put16(&mut v, 0); // using vector colour
+ v.extend_from_slice(&2048u32.to_be_bytes()); // roughness
+ put16(&mut v, 3); // colour model
+ for x in [0u16, 0, 0, 0, 0x8000, 0x8000, 0x8000, 0x8000] {
+ put16(&mut v, x);
+ }
+ put16(&mut v, 0);
+ v
+}
+
/// `selc`: version, method (0 relative / 1 absolute), then 10 CMYK records of i16 percentages;
/// record 0 is reserved, records 1..=9 are reds … blacks.
fn parse_selective(d: &[u8]) -> Option<Adjustment> {
@@ -368,6 +462,7 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
v.extend_from_slice(&VersionedDescriptor::new(d).to_bytes());
return vec![(*b"clrL", v)];
}
+ Adjustment::GradientMap { stops, reverse } if stops.len() >= 2 => return vec![(*b"grdm", write_gradient_map(stops, *reverse))],
Adjustment::Unsupported { psd_key, raw } => {
let k = psd_key.as_bytes();
if k.len() == 4 {
@@ -383,6 +478,42 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
mod tests {
use super::*;
+ #[test]
+ fn gradient_map_v3_methods_and_smoothness() {
+ let classic = vec![(0.0, [0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 0.0])];
+ let v1 = write_gradient_map(&classic, false);
+ // Version 3 inserts the interpolation method after reverse/dither.
+ let v3 = |m: &[u8; 4]| {
+ let mut v = v1.clone();
+ v[1] = 3;
+ v.splice(4..4, m.iter().copied());
+ v
+ };
+ let at_t = |data: &[u8], t: f32| match parse(b"grdm", data, None, Channels::Rgb) {
+ Adjustment::GradientMap { stops, .. } => {
+ let i = stops.windows(2).position(|w| w[0].0 <= t && t <= w[1].0).unwrap();
+ let (x, y) = (stops[i], stops[i + 1]);
+ let u = (t - x.0) / (y.0 - x.0).max(1e-6);
+ std::array::from_fn::<f32, 3, _>(|k| x.1[k] + (y.1[k] - x.1[k]) * u)
+ }
+ other => panic!("{other:?}"),
+ };
+ let mid = |data: &[u8]| at_t(data, 0.5);
+ let c = mid(&v3(b"Gcls"));
+ assert!((c[0] - 0.5).abs() < 1e-3 && (c[2] - 0.5).abs() < 1e-3, "classic = sRGB lerp {c:?}");
+ let p = mid(&v3(b"Perc"));
+ assert!((p[0] - c[0]).abs() > 0.02, "perceptual differs from classic {p:?}");
+ // Smoothness 100 % (4096) bends a three-stop ramp.
+ let three = vec![(0.0, [0.0; 3]), (0.25, [1.0, 0.0, 0.0]), (0.75, [0.0, 0.0, 1.0]), (1.0, [1.0; 3])];
+ let mut smooth = write_gradient_map(&three, false);
+ let at = smooth.len() - 2 - 16 - 2 - 4 - 2 - 2 - 4 - 2 - 2 - 2;
+ smooth[at..at + 2].copy_from_slice(&4096u16.to_be_bytes());
+ let (a, b) = (at_t(&write_gradient_map(&three, false), 0.4), at_t(&smooth, 0.4));
+ assert!((0..3).any(|k| (a[k] - b[k]).abs() > 1e-3), "{a:?} {b:?}");
+ // Noise gradients (no colour stops) stay unsupported.
+ assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. }));
+ }
+
fn rt(a: Adjustment) {
let blocks = write(&a);
assert!(!blocks.is_empty(), "{a:?}");
@@ -417,6 +548,7 @@ mod tests {
per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])],
});
rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3] });
+ rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true });
rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) });
rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] });
let id = photocraft_cms::lutfile::LutFile::identity(5);
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index a72bf3716..a8929a860 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -275,6 +275,17 @@ impl Ex {
}
LayerContent::Raster(_) | LayerContent::Group(_) => {}
}
+ // Effects reference point: written from the field (in place, keeping block order).
+ match l.effects.reference {
+ Some((x, y)) => {
+ let data: Vec<u8> = x.to_be_bytes().into_iter().chain(y.to_be_bytes()).collect();
+ match raw.iter_mut().find(|(k, _)| k == b"fxrp") {
+ Some(e) => e.1 = data,
+ None => raw.push((*b"fxrp", data)),
+ }
+ }
+ None => raw.retain(|(k, _)| k != b"fxrp"),
+ }
if !matches!(l.content, LayerContent::Shape(_)) {
self.vector_mask_block(l, &mut raw);
}
@@ -381,6 +392,41 @@ impl Ex {
}
}
+/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order
+/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group).
+/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise
+/// groups are renumbered by first appearance. `None` when no layer is linked.
+fn link_group_resource(layers: &[Layer]) -> Option<Vec<u8>> {
+ fn walk(layers: &[Layer], out: &mut Vec<Option<u64>>) {
+ for l in layers {
+ if let LayerContent::Group(g) = &l.content {
+ out.push(None);
+ walk(&g.children, out);
+ }
+ out.push(l.link_group);
+ }
+ }
+ let mut per = Vec::new();
+ walk(layers, &mut per);
+ if per.iter().all(Option::is_none) {
+ return None;
+ }
+ let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g));
+ let mut seen: Vec<u64> = Vec::new();
+ let ids = per.iter().map(|g| match *g {
+ None => 0u16,
+ Some(g) if fits => g as u16,
+ Some(g) => {
+ let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| {
+ seen.push(g);
+ seen.len() - 1
+ });
+ u16::try_from(i + 1).unwrap_or(u16::MAX)
+ }
+ });
+ Some(ids.flat_map(u16::to_be_bytes).collect())
+}
+
/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2`
/// decodes to. `None` when there is nothing preserved or it can't be decoded.
fn effects_unchanged(l: &Layer) -> Option<bool> {
@@ -601,6 +647,9 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
resources.push(ImageResource::new(CLIPPING_PATH, data));
}
}
+ if let Some(groups) = link_group_resource(&doc.layers) {
+ resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups));
+ }
if let Some(x) = &doc.metadata.xmp {
resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));
}
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index e2a1a9ab1..407f5b5e6 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -169,14 +169,22 @@ impl Ctx<'_> {
let single = rec.block(b"lfx2").or_else(|| rec.block(b"lfxs"));
if let Some(fx) = rec.block(b"lmfx").or(single) {
let (enabled, items) = crate::effects_map::parse_lfx2(&fx.data).unwrap_or_else(|| (blocks::effects_enabled(&fx.data), Vec::new()));
- l.effects = Effects { enabled, items, psd_raw: single.map(|b| Arc::new(b.data.clone())) };
+ l.effects = Effects { enabled, items, psd_raw: single.map(|b| Arc::new(b.data.clone())), reference: None };
} else if let Some(fx) = rec.block(b"lrFX")
&& !rec.section_type().is_folder()
&& let Some((enabled, items)) = crate::effects_map::parse_lrfx(&fx.data)
{
// Legacy effects only on non-group layers (Photoshop ignores
// them on groups, see psd-tools effects/shape-fx.psd).
- l.effects = Effects { enabled, items, psd_raw: None };
+ l.effects = Effects { enabled, items, psd_raw: None, reference: None };
+ }
+ // Effects reference point (`fxrp`: two f64, x then y); also left in `psd_blocks`, where
+ // export overwrites it from the field.
+ if let Some(b) = rec.block(b"fxrp")
+ && let (Some(x), Some(y)) = (b.data.get(..8), b.data.get(8..16))
+ {
+ let f = |s: &[u8]| f64::from_be_bytes(s.try_into().unwrap_or([0; 8]));
+ l.effects.reference = Some((f(x), f(y)));
}
l.psd_id = rec.layer_id();
let name = l.name.clone();
@@ -306,6 +314,22 @@ impl Ctx<'_> {
}
}
+/// Sets `Layer::link_group` from resource 1026's per-record ids (`nodes` and `layers` correspond).
+fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16]) {
+ for (n, l) in nodes.iter().zip(layers.iter_mut()) {
+ let index = match n {
+ LayerNode::Layer { index } => *index,
+ LayerNode::Group { index, children, .. } => {
+ if let LayerContent::Group(g) = &mut l.content {
+ apply_link_groups(children, &mut g.children, ids);
+ }
+ *index
+ }
+ };
+ l.link_group = ids.get(index).copied().filter(|&g| g != 0).map(u64::from);
+ }
+}
+
fn preserved_blocks(rec: &LayerRecord) -> Vec<([u8; 4], Arc<Vec<u8>>)> {
rec.blocks.iter().filter(|b| !REGENERATED.contains(&&b.key)).map(|b| (b.key, Arc::new(b.data.clone()))).collect()
}
@@ -430,6 +454,12 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
if layered {
let tree = file.layer_tree();
doc.layers = cx.build(&tree);
+ // Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked).
+ if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) =
+ file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed)
+ {
+ apply_link_groups(&tree, &mut doc.layers, &groups);
+ }
if doc.layers.is_empty()
&& let Ok(all) = &merged
{
diff --git a/crates/io/tests/comps_artboards.rs b/crates/io/tests/comps_artboards.rs
new file mode 100644
index 000000000..9f9d66823
--- /dev/null
+++ b/crates/io/tests/comps_artboards.rs
@@ -0,0 +1,194 @@
+//! Layer comps (resource 1065 + per-layer `cmls`) and artboards (`artb`) through PSD and
+//! `.pcraft`: byte-exact while unchanged, regenerated after edits.
+
+use std::path::PathBuf;
+
+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::comps::capture_states;
+use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerComp, LayerContent};
+use photocraft_geom::{Rect, Size};
+use photocraft_io::comps_map::LAYER_COMPS;
+use photocraft_io::{ExportOptions, export, import};
+use photocraft_psd::PsdFile;
+
+fn corpus(rel: &str) -> Option<Vec<u8>> {
+ let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd").join(rel);
+ std::fs::read(p).ok()
+}
+
+fn to_psd(doc: &Document) -> Vec<u8> {
+ export(doc, "x.psd", &ExportOptions::default()).expect("export").bytes
+}
+
+fn layer_block<'a>(f: &'a PsdFile, name: &str, key: &[u8; 4]) -> Option<&'a [u8]> {
+ f.layers().iter().find(|r| r.name() == name).and_then(|r| r.block(key)).map(|b| b.data.as_slice())
+}
+
+#[test]
+fn corpus_layer_comps_import_and_verbatim_export() {
+ let Some(bytes) = corpus("ag-psd/read-write/layer-comps/src.psd") else { return };
+ let src = PsdFile::from_bytes(&bytes).unwrap();
+ let doc = import("src.psd", &bytes).unwrap().document;
+ let names: Vec<_> = doc.layer_comps.iter().map(|c| c.name.as_str()).collect();
+ assert_eq!(names, ["Layer Comp 1", "Layer Comp 2", "Layer Comp 3", "Layer Comp 4", "Layer Comp 5"]);
+ assert_eq!(doc.layer_comps[3].comment, "some comments");
+ assert_eq!(doc.layer_comps[1].captured_info(), 1);
+ assert_eq!(doc.layer_comps[4].captured_info(), 7);
+ assert_eq!(doc.last_applied_comp, Some(doc.layer_comps[3].id));
+ // Comp 2 hides some layers; comp 1 moves one by (-48, -35).
+ assert!(doc.layer_comps[1].states.iter().any(|s| s.visible == Some(false)));
+ let moved: Vec<_> = doc.layer_comps[0].states.iter().filter(|s| s.position.is_some()).collect();
+ assert_eq!(moved.len(), 1);
+ let l = doc.layer(moved[0].layer).unwrap();
+ let here = photocraft_doc::comps::layer_position(l).unwrap();
+ assert_eq!(moved[0].position, Some((here.0 - 48, here.1 - 35)));
+
+ // Unchanged: resource 1065 and every layer's shmd block are written back byte for byte.
+ let out = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
+ assert_eq!(out.resource(LAYER_COMPS).unwrap().data, src.resource(LAYER_COMPS).unwrap().data);
+ for r in src.layers().iter().filter(|r| r.block(b"shmd").is_some()) {
+ assert_eq!(layer_block(&out, &r.name(), b"shmd"), r.block(b"shmd").map(|b| b.data.as_slice()), "layer {}", r.name());
+ }
+
+ // Edited: regenerated, and it decodes back to the edited comps.
+ let mut edited = doc.clone();
+ edited.layer_comps[0].name = "Renamed".into();
+ edited.layer_comps.remove(2);
+ let bytes2 = to_psd(&edited);
+ let out2 = PsdFile::from_bytes(&bytes2).unwrap();
+ assert_ne!(out2.resource(LAYER_COMPS).unwrap().data, src.resource(LAYER_COMPS).unwrap().data);
+ let back = import("x.psd", &bytes2).unwrap().document;
+ assert_eq!(back.layer_comps.len(), 4);
+ assert_eq!(back.layer_comps[0].name, "Renamed");
+ for (a, b) in edited.layer_comps.iter().zip(&back.layer_comps) {
+ assert_eq!((a.id, a.captured_info(), &a.comment), (b.id, b.captured_info(), &b.comment));
+ let pick = |c: &LayerComp| c.states.iter().map(|s| (s.visible, s.position)).collect::<Vec<_>>();
+ assert_eq!(pick(a), pick(b), "comp {}", a.name);
+ }
+ assert_eq!(back.last_applied_comp, edited.last_applied_comp);
+ // Other metadata items in shmd (`cust`) survive regeneration.
+ let r = out2.layers().iter().find(|r| r.block(b"shmd").is_some()).unwrap();
+ let items = photocraft_psd::metadata::parse_shmd(&r.block(b"shmd").unwrap().data).unwrap();
+ assert!(items.iter().any(|i| &i.key == b"cust"));
+ assert!(items.iter().any(|i| &i.key == b"cmls"));
+
+ // All comps deleted: the resource and the cmls items go away.
+ let mut none = doc.clone();
+ none.layer_comps.clear();
+ none.last_applied_comp = None;
+ none.last_document_state = None;
+ let out3 = PsdFile::from_bytes(&to_psd(&none)).unwrap();
+ assert!(out3.resource(LAYER_COMPS).is_none());
+ for r in out3.layers() {
+ if let Some(b) = r.block(b"shmd") {
+ assert!(photocraft_psd::metadata::parse_shmd(&b.data).unwrap().iter().all(|i| &i.key != b"cmls"));
+ }
+ }
+}
+
+#[test]
+fn corpus_artboards_import_and_verbatim_export() {
+ let Some(bytes) = corpus("psd-tools/gradient-sizes.psd") else { return };
+ let src = PsdFile::from_bytes(&bytes).unwrap();
+ let doc = import("g.psd", &bytes).unwrap().document;
+ let boards = doc.artboards();
+ assert_eq!(boards.len(), 3);
+ let rects: Vec<Rect> = boards.iter().map(|b| b.2.rect).collect();
+ assert!(rects.contains(&Rect::new(0, 0, 64, 64)));
+ assert!(rects.contains(&Rect::new(0, 73, 64, 105)));
+ assert!(rects.contains(&Rect::new(73, 0, 105, 64)));
+ assert!(boards.iter().all(|b| b.2.background == ArtboardBackground::White));
+
+ let out = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
+ for r in src.layers().iter().filter(|r| r.block(b"artb").is_some()) {
+ assert_eq!(layer_block(&out, &r.name(), b"artb"), r.block(b"artb").map(|b| b.data.as_slice()), "artboard {}", r.name());
+ }
+ // A changed board is regenerated.
+ let mut edited = doc.clone();
+ let id = edited.artboards()[0].0;
+ let a = edited.layer_mut(id).unwrap().artboard_mut().unwrap();
+ a.background = ArtboardBackground::Black;
+ a.rect = a.rect.translate(5, 0);
+ let want = a.clone();
+ let back = import("x.psd", &to_psd(&edited)).unwrap().document;
+ assert!(back.artboards().iter().any(|b| *b.2 == want));
+}
+
+fn synthetic(depth: SampleType) -> Document {
+ let mut d = Document::new("s", Size::new(80, 40), ColorMode::Rgb, depth);
+ let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
+ let mut a = Layer::raster("A", fmt);
+ a.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 20, 20), &[1.0, 0.0, 0.0, 1.0]);
+ let mut b = Layer::raster("B", fmt);
+ b.surface_mut().unwrap().fill_rect(Rect::new(44, 4, 60, 20), &[0.0, 0.0, 1.0, 1.0]);
+ let mut g1 = Layer::group("Board 1", vec![a]);
+ let mut g2 = Layer::group("Board 2", vec![b]);
+ if let LayerContent::Group(g) = &mut g1.content {
+ g.artboard = Some(Artboard { rect: Rect::new(0, 0, 40, 40), background: ArtboardBackground::White, preset: "Custom".into() });
+ }
+ if let LayerContent::Group(g) = &mut g2.content {
+ g.artboard = Some(Artboard { rect: Rect::new(40, 0, 80, 40), background: ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)), preset: String::new() });
+ }
+ d.layers = vec![g1, g2];
+ let states = capture_states(&d);
+ d.layer_comps.push(LayerComp { id: 11, name: "Both".into(), comment: "all".into(), apply_visibility: true, apply_position: true, apply_appearance: false, states });
+ d.layers[1].visible = false;
+ if let Some(ch) = d.layers[0].children_mut() {
+ ch[0].blend = BlendMode::Multiply;
+ }
+ let mut states = capture_states(&d);
+ states.retain(|s| s.layer != d.layers[0].id);
+ d.layer_comps.push(LayerComp { id: 12, name: "One".into(), comment: String::new(), apply_visibility: true, apply_position: false, apply_appearance: true, states });
+ d.last_applied_comp = Some(12);
+ d
+}
+
+#[test]
+fn synthetic_psd_roundtrip_all_depths() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let d = synthetic(depth);
+ let back = import("x.psd", &to_psd(&d)).unwrap().document;
+ let boards: Vec<_> = back.artboards().into_iter().map(|b| (b.1.to_string(), b.2.clone())).collect();
+ let want: Vec<_> = d.artboards().into_iter().map(|b| (b.1.to_string(), b.2.clone())).collect();
+ assert_eq!(boards, want, "{depth:?}");
+ assert_eq!(back.layer_comps.len(), 2);
+ assert_eq!(back.last_applied_comp, Some(12));
+ for (a, b) in d.layer_comps.iter().zip(&back.layer_comps) {
+ assert_eq!((a.id, &a.name, &a.comment, a.captured_info()), (b.id, &b.name, &b.comment, b.captured_info()));
+ // Layer ids differ after import: compare by layer name.
+ let named = |doc: &Document, c: &LayerComp| {
+ let mut v: Vec<_> = c.states.iter().map(|s| (doc.layer(s.layer).unwrap().name.clone(), s.visible, s.position)).collect();
+ v.sort_by(|x, y| x.0.cmp(&y.0));
+ v
+ };
+ assert_eq!(named(&d, a), named(&back, b), "{depth:?} comp {}", a.name);
+ }
+ // Re-exporting the imported document is byte-stable for comps and artboards.
+ let f1 = PsdFile::from_bytes(&to_psd(&back)).unwrap();
+ let f2 = PsdFile::from_bytes(&to_psd(&import("x.psd", &to_psd(&back)).unwrap().document)).unwrap();
+ assert_eq!(f1.resource(LAYER_COMPS).map(|r| &r.data), f2.resource(LAYER_COMPS).map(|r| &r.data));
+ for r in f1.layers() {
+ for key in [b"artb", b"shmd"] {
+ assert_eq!(r.block(key).map(|b| &b.data), layer_block(&f2, &r.name(), key).map(|d| d.to_vec()).as_ref(), "{}", r.name());
+ }
+ }
+ }
+}
+
+#[test]
+fn synthetic_pcraft_roundtrip_keeps_everything() {
+ let mut d = synthetic(SampleType::U16);
+ d.last_document_state = Some(LayerComp { id: 0, name: "Last Document State".into(), comment: String::new(), apply_visibility: true, apply_position: true, apply_appearance: true, states: capture_states(&d) });
+ let bytes = photocraft_format::save_to_bytes(&d, &Default::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ assert_eq!(back.layer_comps, d.layer_comps);
+ assert_eq!(back.last_applied_comp, d.last_applied_comp);
+ assert_eq!(back.last_document_state, d.last_document_state);
+ assert_eq!(back.artboards().len(), 2);
+ assert_eq!(back.layers[1].artboard(), d.layers[1].artboard());
+ // Remapped ids still point at the same layers.
+ let fresh = photocraft_format::load_from_bytes_with(&bytes, &photocraft_format::LoadOptions { preserve_ids: false, ..Default::default() }).unwrap();
+ let c = &fresh.layer_comps[0];
+ assert_eq!(c.states.len(), fresh.layer_count());
+ assert!(c.states.iter().all(|s| fresh.layer(s.layer).is_some()));
+}
diff --git a/crates/ui-egui/examples/fx_bench.rs b/crates/ui-egui/examples/fx_bench.rs
index a9549ab28..3484bc348 100644
--- a/crates/ui-egui/examples/fx_bench.rs
+++ b/crates/ui-egui/examples/fx_bench.rs
@@ -164,6 +164,14 @@ fn main() {
};
let cpu = |doc: &Document, r: Rect| if no_cpu { None } else { Some(cpu_time(doc, r)) };
+ if args.iter().any(|a| a == "--baseline") {
+ let mut plain = doc.clone();
+ for l in &mut plain.layers {
+ l.effects.items.clear();
+ }
+ let _ = gt(&plain, full);
+ report("baseline: no effects, full refresh", full, None, gt(&plain, full));
+ }
photocraft_compose::purge_effect_cache();
report("full refresh, cold effect caches", full, cpu(&doc, full), gt(&doc, full));
report("full refresh, warm caches", full, cpu(&doc, full), gt(&doc, full));
diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rs
new file mode 100644
index 000000000..26d561d31
--- /dev/null
+++ b/crates/ui-egui/src/artboard_ui.rs
@@ -0,0 +1,199 @@
+//! Artboards in the shell: the pasteboard between boards and the board names on the canvas,
+//! View › Fit Artboard on Screen, and the Properties panel section (X/Y/W/H, preset,
+//! background). Everything that changes the document is `layer.artboard.set` and friends.
+
+use egui::{Align2, Color32, Pos2, Rect, Stroke};
+use photocraft_doc::{ArtboardBackground, Document, Layer};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::ViewXform;
+use crate::theme::Tokens;
+
+/// Screen rects covering the document image minus every artboard (vertical slabs between the
+/// boards' x edges, split around the boards they cross).
+pub fn pasteboard_rects(xf: &ViewXform, doc: &Document) -> Vec<Rect> {
+ let canvas = doc.bounds();
+ let boards: Vec<photocraft_geom::Rect> = doc.artboards().iter().map(|b| b.2.rect.intersect(&canvas)).filter(|r| !r.is_empty()).collect();
+ let mut xs: Vec<i32> = vec![canvas.x0, canvas.x1];
+ for b in &boards {
+ xs.extend([b.x0, b.x1]);
+ }
+ xs.sort_unstable();
+ xs.dedup();
+ let mut out = Vec::new();
+ for w in xs.windows(2) {
+ let (x0, x1) = (w[0], w[1]);
+ let mut spans: Vec<(i32, i32)> = boards.iter().filter(|b| b.x0 <= x0 && b.x1 >= x1).map(|b| (b.y0, b.y1)).collect();
+ spans.sort_unstable();
+ let mut y = canvas.y0;
+ for (a, b) in spans {
+ if a > y {
+ out.push(xf.doc_rect(photocraft_geom::Rect::new(x0, y, x1, a)));
+ }
+ y = y.max(b);
+ }
+ if y < canvas.y1 {
+ out.push(xf.doc_rect(photocraft_geom::Rect::new(x0, y, x1, canvas.y1)));
+ }
+ }
+ out
+}
+
+/// Board outlines and names (the active board's name is highlighted, as in Photoshop).
+pub fn draw_frames(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ let Some(st) = app.session.active() else { return };
+ let t = Tokens::get(painter.ctx());
+ let active = st.active_layer.and_then(|id| st.doc.artboard_of(id));
+ for (id, name, a) in st.doc.artboards() {
+ let r = xf.doc_rect(a.rect);
+ let on = active == Some(id);
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, if on { t.accent } else { Color32::from_black_alpha(90) }), egui::StrokeKind::Outside);
+ let pos = Pos2::new(r.left(), r.top() - 4.0);
+ painter.text(pos, Align2::LEFT_BOTTOM, name, egui::FontId::proportional(11.0), if on { t.text } else { t.text_dim });
+ }
+}
+
+/// View › Fit Artboard on Screen: zoom to the active artboard (or the first one).
+pub fn fit_artboard(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let i = app.session.active_index().ok_or("no document")?;
+ let st = app.session.active().ok_or("no document")?;
+ let id = st.active_layer.and_then(|l| st.doc.artboard_of(l)).or_else(|| st.doc.artboards().last().map(|b| b.0)).ok_or("the document has no artboards")?;
+ let b = st.doc.layer(id).and_then(Layer::artboard).map(|a| a.rect).ok_or("no artboard")?;
+ let area = app.last_canvas_rect.size();
+ let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) };
+ let v = &mut app.ui.views[i];
+ // Leave room for the name above the board.
+ v.zoom = ((area.x - 60.0) / b.width().max(1) as f32).min((area.y - 80.0) / b.height().max(1) as f32).clamp(0.01, 64.0);
+ v.center = [(b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0];
+ v.fit_pending = false;
+ Ok(json!({"zoom": v.zoom, "artboard": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
+}
+
+/// Properties panel for an artboard.
+pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
+ let Some(a) = layer.artboard().cloned() else { return };
+ let t = Tokens::get(ui.ctx());
+ let key = |k: &str| format!("artboard-{}-{k}", layer.id.0);
+ let mut edit: Option<Value> = None;
+ ui.label(egui::RichText::new("Artboard").font(crate::theme::semibold(12.0)).color(t.text));
+ ui.add_space(4.0);
+ let mut preset = a.preset.clone();
+ let mut opts: Vec<(String, &str)> = vec![(String::new(), "Custom")];
+ opts.extend(photocraft_engine::artboard_cmds::PRESETS.iter().map(|(n, _, _)| (n.to_string(), *n)));
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Size").color(t.text_dim).size(12.0));
+ if crate::widgets::dropdown(ui, &key("preset"), &mut preset, &opts, 150.0) && !preset.is_empty() {
+ edit = Some(json!({"layer": layer.id.0, "preset": preset}));
+ }
+ });
+ let num = |ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>| -> bool {
+ ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0));
+ crate::widgets::value_field(ui, v, range, "px", 64.0).changed()
+ };
+ let r = a.rect;
+ ui.horizontal(|ui| {
+ let (mut w, mut h) = (r.width() as f32, r.height() as f32);
+ let cw = num(ui, "W", &mut w, 1.0..=300_000.0);
+ let ch = num(ui, "H", &mut h, 1.0..=300_000.0);
+ if cw || ch {
+ edit = Some(json!({"layer": layer.id.0, "width": w.round(), "height": h.round(), "coalesce": key("wh")}));
+ }
+ });
+ ui.horizontal(|ui| {
+ let (mut x, mut y) = (r.x0 as f32, r.y0 as f32);
+ let cx = num(ui, "X", &mut x, -300_000.0..=300_000.0);
+ let cy = num(ui, "Y", &mut y, -300_000.0..=300_000.0);
+ if cx || cy {
+ edit = Some(json!({"layer": layer.id.0, "x": x.round(), "y": y.round(), "coalesce": key("xy")}));
+ }
+ });
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Artboard Background Color").color(t.text_dim).size(12.0));
+ });
+ ui.horizontal(|ui| {
+ let mut bg = a.background.name().to_string();
+ let opts = [("white".to_string(), "White"), ("black".to_string(), "Black"), ("transparent".to_string(), "Transparent"), ("custom".to_string(), "Other…")];
+ if crate::widgets::dropdown(ui, &key("bg"), &mut bg, &opts, 120.0) {
+ edit = Some(json!({"layer": layer.id.0, "background": bg}));
+ }
+ if let ArtboardBackground::Custom(c) = a.background {
+ let [r8, g8, b8, _] = c.to_rgba8();
+ let mut rgb = [r8, g8, b8];
+ if ui.color_edit_button_srgb(&mut rgb).changed() {
+ edit = Some(json!({"layer": layer.id.0, "background": "custom", "color": format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]), "coalesce": key("color")}));
+ }
+ }
+ });
+ if let Some(p) = edit
+ && let Err(e) = app.run("layer.artboard.set", p)
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::menus::{invoke as menu, is_live, menu_items};
+
+ fn app() -> (PhotocraftApp, egui::Context) {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 100, "height": 50})).unwrap();
+ app.sync_views();
+ (app, egui::Context::default())
+ }
+
+ #[test]
+ fn pasteboard_is_the_canvas_minus_the_boards() {
+ let (mut app, _) = app();
+ app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap();
+ app.run("layer.new.artboard", json!({"rect": [60, 10, 40, 30]})).unwrap();
+ let doc = app.session.active().unwrap().doc.clone();
+ let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, egui::vec2(100.0, 50.0)), zoom: 1.0, center: [50.0, 25.0], flip: false };
+ let rects = pasteboard_rects(&xf, &doc);
+ let area: f32 = rects.iter().map(|r| r.area()).sum();
+ // 100×50 canvas − 40×50 − 40×30 boards.
+ assert!((area - (5000.0 - 2000.0 - 1200.0)).abs() < 0.5, "{rects:?}");
+ assert!(rects.iter().all(|r| !r.intersects(Rect::from_min_max(Pos2::new(0.5, 0.5), Pos2::new(39.5, 49.5)))));
+ }
+
+ #[test]
+ fn fit_artboard_and_menu_items() {
+ let (mut app, ctx) = app();
+ for id in ["view.fitArtboardOnScreen", "window.panel.layerComps", "layer.new.artboard", "file.export.artboardsToFiles", "file.export.artboardsToPdf", "file.export.layerCompsToFiles", "view.clearSelectedArtboardGuides"] {
+ assert!(is_live(id), "{id}");
+ }
+ let enabled = |app: &PhotocraftApp, id: &str| menu_items(app).into_iter().find(|i| i.id == id).is_some_and(|i| i.enabled);
+ assert!(!enabled(&app, "view.fitArtboardOnScreen"));
+ // Menu clicks without params open dialogs for the parameterised commands.
+ let r = menu(&mut app, &ctx, "layer.new.artboard", json!({})).unwrap();
+ assert!(r.get("dialog").is_some());
+ app.run("layer.new.artboard", json!({"rect": [200, 0, 50, 20]})).unwrap();
+ assert!(enabled(&app, "view.fitArtboardOnScreen"));
+ let r = menu(&mut app, &ctx, "view.fitArtboardOnScreen", json!({})).unwrap();
+ assert_eq!(r["bounds"], json!([200, 0, 250, 20]));
+ let i = app.session.active_index().unwrap();
+ assert_eq!(app.ui.views[i].center, [225.0, 10.0]);
+ assert!(menu(&mut app, &ctx, "file.export.artboardsToFiles", json!({})).unwrap().get("dialog").is_some());
+ // Window › Layer Comps shows the third History tab.
+ menu(&mut app, &ctx, "window.panel.layerComps", json!({})).unwrap();
+ assert!(app.ui.panels.history);
+ assert_eq!(app.ui.dock_tabs.history, 2);
+ }
+
+ #[test]
+ fn comp_target_follows_selection_then_last_applied() {
+ let (mut app, _) = app();
+ assert_eq!(crate::comps_ui::target(&app), None);
+ let a = app.run("layerComp.new", json!({})).unwrap()["comp"].as_u64().unwrap() as u32;
+ let b = app.run("layerComp.new", json!({})).unwrap()["comp"].as_u64().unwrap() as u32;
+ assert_eq!(crate::comps_ui::target(&app), Some(b));
+ app.ui.layer_comp_selected = Some(a);
+ assert_eq!(crate::comps_ui::target(&app), Some(a));
+ app.ui.layer_comp_selected = Some(999);
+ assert_eq!(crate::comps_ui::target(&app), Some(b));
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index a9f1f9e7c..1183e1e6d 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -146,6 +146,10 @@ fn downsample(buf: &photocraft_compose::Buffer, factor: u32) -> photocraft_compo
/// The document to render: the committed one, or a clone with the live adjustment preview applied.
fn display_doc(app: &PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {
let st = &app.session.documents()[idx];
+ // Puppet / Perspective Warp previews hide the layer they draw on a mesh.
+ if let Some(shown) = crate::distort_ui::display_doc(app, idx) {
+ return shown;
+ }
if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview)
&& app.session.active_index() == Some(idx)
&& st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some()
@@ -698,6 +702,34 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
painter.image(tex, img_rect, uv, Color32::WHITE);
}
+ // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
+ if doc.has_artboards() {
+ let t = crate::theme::Tokens::get(&ctx);
+ let pasteboard = crate::prefs_ui::pasteboard_color(app);
+ let dot_tex = dots(&ctx, &t);
+ for r in crate::artboard_ui::pasteboard_rects(&xf, &doc) {
+ let r = r.intersect(rect);
+ if !r.is_positive() {
+ continue;
+ }
+ match pasteboard {
+ Some(c) => {
+ painter.rect_filled(r, 0.0, c);
+ }
+ None => {
+ painter.rect_filled(r, 0.0, t.canvas);
+ if let Some(id) = dot_tex {
+ // Same phase as the dots around the document.
+ let uv = Rect::from_min_max(((r.min - rect.min) / 22.0).to_pos2(), ((r.max - rect.min) / 22.0).to_pos2());
+ painter.image(id, r, uv, Color32::WHITE);
+ }
+ }
+ }
+ }
+ if primary {
+ crate::artboard_ui::draw_frames(app, &painter, &xf);
+ }
+ }
// Pixel grid at high zoom (the GPU path draws its own).
if !on_gpu && pixel_grid && view.zoom >= 12.0 {
@@ -837,6 +869,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
crate::type_tool::draw_overlay(app, &painter, &xf);
crate::transform_tool::draw_overlay(app, &painter, &xf);
+ crate::distort_ui::draw_overlay(app, &painter, &xf);
crate::retouch_ui::draw_source_marker(app, &painter, &xf);
crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);
// Tool cursors (Photoshop-style).
@@ -1105,6 +1138,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
if crate::transform_tool::pointer(app, ev, mods) {
return;
}
+ if crate::distort_ui::pointer(app, ev, mods) {
+ return;
+ }
let tool = app.ui.tool;
// Move tool over a guide drags the guide (off the canvas deletes it).
match ev {
diff --git a/crates/ui-egui/src/comps_ui.rs b/crates/ui-egui/src/comps_ui.rs
new file mode 100644
index 000000000..cfb100965
--- /dev/null
+++ b/crates/ui-egui/src/comps_ui.rs
@@ -0,0 +1,166 @@
+//! Window › Layer Comps panel (a tab of the History card).
+//!
+//! Rows: the Last Document State, then each comp with its apply marker, name, warning triangle
+//! (layers deleted since capture) and the three apply toggles (visibility, position,
+//! appearance). Footer: previous / next comp, update, new, delete. Every action is a
+//! `layerComp.*` engine command; the selection is `UiState::layer_comp_selected`.
+
+use egui::{Align2, Rect, Sense, Stroke, pos2, vec2};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+/// The comp footer and row actions act on: the panel selection if still valid, else the last
+/// applied comp.
+pub fn target(app: &PhotocraftApp) -> Option<u32> {
+ let doc = &app.session.active()?.doc;
+ app.ui.layer_comp_selected.filter(|id| doc.comp(*id).is_some()).or(doc.last_applied_comp.filter(|id| doc.comp(*id).is_some()))
+}
+
+fn run(app: &mut PhotocraftApp, id: &str, p: Value) {
+ if let Err(e) = app.run(id, p) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+}
+
+pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let Some(st) = app.session.active() else {
+ ui.label(egui::RichText::new("No document").color(t.text_faint).size(11.5));
+ return;
+ };
+ let doc = st.doc.clone();
+ let selected = target(app);
+ let applied = doc.last_applied_comp;
+ let max_h = (ui.available_height() - 70.0).clamp(80.0, 320.0);
+ let mut action: Option<(&'static str, Value)> = None;
+ let mut select: Option<u32> = None;
+ let row_h = 26.0;
+ egui::ScrollArea::vertical().id_salt("comps-rows").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {
+ // Last Document State.
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ if applied.is_none() {
+ ui.painter().rect_filled(rect, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ let marker = Rect::from_center_size(pos2(rect.left() + 14.0, rect.center().y), vec2(12.0, 12.0));
+ ui.painter().rect_stroke(marker, 2.0, Stroke::new(1.0, t.text_faint), egui::StrokeKind::Inside);
+ if applied.is_none() {
+ crate::icons::paint(ui, marker, "check", 10.0, t.icon);
+ }
+ ui.painter().text(pos2(rect.left() + 30.0, rect.center().y), Align2::LEFT_CENTER, "Last Document State", egui::FontId::proportional(12.0), t.text_dim);
+ if resp.clicked() && doc.last_document_state.is_some() && applied.is_some() {
+ action = Some(("layerComp.restoreLastDocumentState", json!({})));
+ }
+ ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));
+
+ if doc.layer_comps.is_empty() {
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new("Capture the visibility, position and style of every layer with + below, then switch between versions.").color(t.text_faint).size(11.5));
+ }
+ for c in &doc.layer_comps {
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ if selected == Some(c.id) {
+ ui.painter().rect_filled(rect, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ // Apply marker (click to apply).
+ let marker = Rect::from_center_size(pos2(rect.left() + 14.0, rect.center().y), vec2(12.0, 12.0));
+ ui.painter().rect_stroke(marker, 2.0, Stroke::new(1.0, t.text_faint), egui::StrokeKind::Inside);
+ if applied == Some(c.id) {
+ crate::icons::paint(ui, marker, "check", 10.0, t.accent);
+ }
+ // The three apply toggles, right-aligned.
+ let toggles = [("eye", "Visibility", c.apply_visibility, "visibility"), ("move", "Position", c.apply_position, "position"), ("sparkles", "Appearance (Layer Style)", c.apply_appearance, "appearance")];
+ let mut x = rect.right() - 14.0;
+ let mut toggle_hit = false;
+ for (icon, tip, on, key) in toggles.iter().rev() {
+ let r = Rect::from_center_size(pos2(x, rect.center().y), vec2(20.0, 20.0));
+ let hov = ui.rect_contains_pointer(r);
+ if hov {
+ ui.painter().rect_filled(r, 3.0, t.hover);
+ }
+ crate::icons::paint(ui, r, icon, 13.0, if *on { t.icon } else { t.text_faint.gamma_multiply(0.45) });
+ if hov && resp.clicked() {
+ toggle_hit = true;
+ action = Some(("layerComp.setOptions", json!({"comp": c.id, *key: !on})));
+ }
+ if hov {
+ resp.clone().on_hover_text(format!("Apply {tip}: {}", if *on { "on" } else { "off" }));
+ }
+ x -= 22.0;
+ }
+ let missing = c.missing_layers(&doc).len();
+ let mut name_x = rect.left() + 30.0;
+ if missing > 0 {
+ let r = Rect::from_center_size(pos2(name_x + 7.0, rect.center().y), vec2(14.0, 14.0));
+ crate::icons::paint(ui, r, "triangle-alert", 12.0, t.warning);
+ if ui.rect_contains_pointer(r) {
+ resp.clone().on_hover_text(format!("{missing} layer(s) recorded by this comp were deleted. Update the comp, or clear the warning."));
+ if resp.clicked() {
+ toggle_hit = true;
+ action = Some(("layerComp.updateWarnings", json!({"clear": true})));
+ }
+ }
+ name_x += 18.0;
+ }
+ let galley_w = (x - name_x).max(20.0);
+ let name = ui.painter().layout(c.name.clone(), egui::FontId::proportional(12.0), t.text, galley_w);
+ ui.painter().galley(pos2(name_x, rect.center().y - name.size().y / 2.0), name, t.text);
+ if !c.comment.is_empty() && resp.hovered() {
+ resp.clone().on_hover_text(&c.comment);
+ }
+ if resp.clicked() && !toggle_hit {
+ select = Some(c.id);
+ if resp.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 24.0) {
+ action = Some(("layerComp.apply", json!({"comp": c.id})));
+ }
+ }
+ if resp.double_clicked() && !toggle_hit {
+ action = Some(("layerComp.apply", json!({"comp": c.id})));
+ }
+ ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator.gamma_multiply(0.5)));
+ }
+ });
+ // Footer: apply previous, apply next | update, new, delete (Photoshop's order).
+ ui.add_space(4.0);
+ let has = !doc.layer_comps.is_empty();
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ if crate::icons::button(ui, "chevrons-left", 24.0, false, "Apply previous selected layer comp").clicked() && has {
+ action = Some(("layerComp.previous", json!({})));
+ }
+ if crate::icons::button(ui, "chevrons-right", 24.0, false, "Apply next selected layer comp").clicked() && has {
+ action = Some(("layerComp.next", json!({})));
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 24.0, false, "Delete layer comp").clicked()
+ && let Some(id) = selected
+ {
+ action = Some(("layerComp.delete", json!({"comp": id})));
+ }
+ if crate::icons::button(ui, "file-plus", 24.0, false, "Create new layer comp").clicked() {
+ action = Some(("layerComp.new", json!({})));
+ }
+ if crate::icons::button(ui, "rotate-cw", 24.0, false, "Update layer comp (visibility, position and appearance)").clicked()
+ && let Some(id) = selected
+ {
+ action = Some(("layerComp.update", json!({"comp": id})));
+ }
+ });
+ });
+ if let Some(id) = select {
+ app.ui.layer_comp_selected = Some(id);
+ }
+ if let Some((cmd, p)) = action {
+ let created = cmd == "layerComp.new";
+ run(app, cmd, p);
+ if created {
+ app.ui.layer_comp_selected = app.session.active().and_then(|d| d.doc.last_applied_comp);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 27b8733f8..c32ae74e1 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -325,6 +325,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
"document": app.session.active().map(photocraft_engine::inspect::document),
"perf": {"fps": app.fps, "timings": app.perf},
"brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity},
+ "distort": app.distort.describe(),
})
}
diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs
new file mode 100644
index 000000000..caddeaf8f
--- /dev/null
+++ b/crates/ui-egui/src/distort_ui.rs
@@ -0,0 +1,198 @@
+//! Interactive Liquify (full-window dialog), Puppet Warp and Perspective Warp (on-canvas modes).
+//!
+//! All three are previews over plain data (strokes, pins, planes); committing runs the engine
+//! command with that data (`filter.liquify`, `edit.puppetWarp`, `edit.perspectiveWarp`, or the
+//! smart-object twins), so the result is one history step and exactly replayable. This module
+//! holds the shared runtime state and the hooks the shell calls (menus, pointer, keys, overlay,
+//! options bar); the modes live in `liquify_ui`, `puppet_ui` and `perspective_ui`.
+
+use std::sync::Arc;
+
+use egui::{Color32, ColorImage};
+use photocraft_doc::{Document, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+
+/// Runtime state of the distortion modes (not serialisable: textures, solvers).
+#[derive(Default)]
+pub struct Distort {
+ pub liquify: Option<crate::liquify_ui::LiquifyDialog>,
+ pub puppet: Option<crate::puppet_ui::PuppetSession>,
+ pub perspective: Option<crate::perspective_ui::PerspSession>,
+}
+
+impl Distort {
+ pub fn active(&self) -> bool {
+ self.liquify.is_some() || self.puppet.is_some() || self.perspective.is_some()
+ }
+
+ /// Short description for `ui.inspect`.
+ pub fn describe(&self) -> Value {
+ json!({
+ "liquify": self.liquify.as_ref().map(|d| d.describe()),
+ "puppet": self.puppet.as_ref().map(|p| p.describe()),
+ "perspective": self.perspective.as_ref().map(|p| p.describe()),
+ })
+ }
+}
+
+/// The active layer's pixels (a pixel layer, or a smart object's rendering) and its id.
+pub(crate) fn active_pixels(app: &PhotocraftApp) -> Result<(LayerId, Surface, bool), String> {
+ let st = app.session.active().ok_or("no document")?;
+ let id = st.active_layer.ok_or("no active layer")?;
+ let l = st.doc.layer(id).ok_or("no layer")?;
+ match &l.content {
+ LayerContent::Raster(s) => Ok((id, s.clone(), false)),
+ LayerContent::Smart(sm) => sm.cache.clone().map(|c| (id, c, true)).ok_or_else(|| "the smart object has no pixels".to_string()),
+ other => Err(format!("needs a pixel layer or smart object (active layer is a {} layer)", other.kind_name())),
+ }
+}
+
+/// The document with layer `id` hidden (what shows behind a live preview of that layer).
+pub(crate) fn without_layer(doc: &Document, id: LayerId) -> Arc<Document> {
+ let mut d = doc.clone();
+ if let Some(l) = d.layer_mut(id) {
+ l.visible = false;
+ }
+ Arc::new(d)
+}
+
+/// A texture image of `surf` over `r`, downsampled so the longer side is at most `max_side`.
+pub(crate) fn surface_image(surf: &Surface, r: Rect, max_side: usize) -> ColorImage {
+ let (w, h) = (r.width().max(1) as usize, r.height().max(1) as usize);
+ let k = w.max(h).div_ceil(max_side).max(1);
+ let (tw, th) = (w.div_ceil(k), h.div_ceil(k));
+ let mut px = vec![Color32::TRANSPARENT; tw * th];
+ let mut row = vec![[0u8; 4]; w];
+ for ty in 0..th {
+ let y = r.y0 + (ty * k) as i32;
+ surf.read_rgba8_into(Rect::new(r.x0, y, r.x1, y + 1), &mut row);
+ for tx in 0..tw {
+ let p = row[(tx * k).min(w - 1)];
+ let a = if surf.format().alpha { p[3] } else { 255 };
+ px[ty * tw + tx] = Color32::from_rgba_unmultiplied(p[0], p[1], p[2], a);
+ }
+ }
+ ColorImage::new([tw, th], px)
+}
+
+/// The document shown on the canvas while Puppet or Perspective Warp previews a layer.
+pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {
+ if app.session.active_index() != Some(idx) {
+ return None;
+ }
+ if let Some(p) = &app.distort.puppet {
+ return Some((p.preview_doc.clone(), (1 << 42) + p.key));
+ }
+ if let Some(p) = &app.distort.perspective {
+ return Some((p.preview_doc.clone(), (1 << 42) + p.key));
+ }
+ None
+}
+
+/// Menu / control routing. `Some` when this module handles the invocation.
+pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ let empty = params.as_object().is_none_or(|o| o.is_empty());
+ let ui = params.get("ui");
+ match id {
+ "filter.liquify" if empty => Some(crate::liquify_ui::open(app, ctx).map(|_| json!({"liquify": app.distort.describe()["liquify"]}))),
+ "filter.liquify" if ui.is_some() && app.distort.liquify.is_some() => Some(crate::liquify_ui::control(app, ui.unwrap_or(&Value::Null))),
+ "edit.puppetWarp" | "layer.smartObjects.puppetWarp" if empty => Some(crate::puppet_ui::begin(app, ctx, id).map(|_| json!({"puppet": app.distort.describe()["puppet"]}))),
+ "edit.puppetWarp" | "layer.smartObjects.puppetWarp" if ui.is_some() && app.distort.puppet.is_some() => Some(crate::puppet_ui::control(app, ui.unwrap_or(&Value::Null))),
+ "edit.perspectiveWarp" | "layer.smartObjects.perspectiveWarp" if empty => Some(crate::perspective_ui::begin(app, ctx, id).map(|_| json!({"perspective": app.distort.describe()["perspective"]}))),
+ "edit.perspectiveWarp" | "layer.smartObjects.perspectiveWarp" if ui.is_some() && app.distort.perspective.is_some() => Some(crate::perspective_ui::control(app, ui.unwrap_or(&Value::Null))),
+ _ => None,
+ }
+}
+
+/// Pointer events (document coordinates) while a mode is active. True when consumed.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
+ if app.distort.liquify.is_some() {
+ crate::liquify_ui::pointer(app, ev, mods);
+ return true;
+ }
+ if app.distort.puppet.is_some() {
+ crate::puppet_ui::pointer(app, ev, mods);
+ return true;
+ }
+ if app.distort.perspective.is_some() {
+ crate::perspective_ui::pointer(app, ev, mods);
+ return true;
+ }
+ false
+}
+
+/// Keyboard: ↩ commits, Esc cancels (and Liquify's own shortcuts). True when the key handling
+/// of the rest of the app should be skipped.
+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
+ use egui::{Key, Modifiers};
+ let enter = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter));
+ let esc = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
+ if app.distort.liquify.is_some() {
+ if enter(ctx) {
+ crate::liquify_ui::commit(app);
+ } else if esc(ctx) {
+ app.distort.liquify = None;
+ } else {
+ crate::liquify_ui::keys(app, ctx);
+ }
+ return true;
+ }
+ if app.distort.puppet.is_some() {
+ if enter(ctx) {
+ crate::puppet_ui::commit(app);
+ } else if esc(ctx) {
+ app.distort.puppet = None;
+ }
+ return true;
+ }
+ if app.distort.perspective.is_some() {
+ if enter(ctx) {
+ crate::perspective_ui::commit(app);
+ } else if esc(ctx) {
+ app.distort.perspective = None;
+ }
+ return true;
+ }
+ false
+}
+
+/// Canvas overlay for the on-canvas modes.
+pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ if let Some(p) = &app.distort.puppet {
+ crate::puppet_ui::draw(p, painter, xf);
+ }
+ if let Some(p) = &app.distort.perspective {
+ crate::perspective_ui::draw(p, painter, xf);
+ }
+}
+
+/// Options bar for the on-canvas modes. True when drawn.
+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool {
+ if app.distort.puppet.is_some() {
+ crate::puppet_ui::options_bar(app, ui);
+ return true;
+ }
+ if app.distort.perspective.is_some() {
+ crate::perspective_ui::options_bar(app, ui);
+ return true;
+ }
+ false
+}
+
+/// Full-window dialogs (Liquify).
+pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.distort.liquify.is_some() {
+ crate::liquify_ui::show(app, ctx);
+ }
+}
+
+/// Screen distance (document px) that counts as "on" a handle at the current zoom.
+pub(crate) fn tolerance(app: &PhotocraftApp) -> f64 {
+ let z = app.session.active_index().and_then(|i| app.ui.views.get(i)).map_or(1.0, |v| v.zoom.max(0.01));
+ 8.0 / f64::from(z)
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1d6c84dad..b59518f7b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -8,10 +8,12 @@
pub mod actions;
pub mod adjust_ui;
+pub mod artboard_ui;
pub mod brush_panel;
pub mod canvas;
pub mod channel_view;
pub mod channels_panel;
+pub mod comps_ui;
pub mod control;
pub mod dialogs;
pub mod export_dialog;
@@ -37,6 +39,10 @@ pub mod state;
pub mod theme;
pub mod tone;
pub mod transform_tool;
+pub mod distort_ui;
+pub mod liquify_ui;
+pub mod puppet_ui;
+pub mod perspective_ui;
pub mod type_tool;
pub mod vector_ui;
pub mod view_cmds;
@@ -162,6 +168,8 @@ pub struct PhotocraftApp {
pub(crate) doc_hist: Option<(DocId, u64, f64, std::sync::Arc<tone::Histograms>)>,
/// Free Transform preview (document without the moving pixels + their texture).
pub(crate) transform_preview: Option<transform_tool::TransformPreview>,
+ /// Liquify dialog, Puppet Warp and Perspective Warp sessions (distort_ui).
+ pub(crate) distort: distort_ui::Distort,
/// Signature of the image we last put on the OS clipboard (to tell ours from other apps').
os_clip_sig: Option<u64>,
/// Pointer position over the canvas (document px), for the Info panel and status bar.
@@ -224,6 +232,7 @@ impl PhotocraftApp {
info_sample: None,
os_clip_sig: None,
transform_preview: None,
+ distort: Default::default(),
tone_hist: None,
doc_hist: None,
gpu: None,
@@ -499,6 +508,7 @@ impl eframe::App for PhotocraftApp {
brush_panel::window(self, &ctx);
palette::show(self, &ctx);
dialogs::show(self, &ctx);
+ distort_ui::show(self, &ctx);
canvas::extra_windows(self, &ctx);
self.perf.frame(gpu_canvas::now_ms() - t0);
// Synthetic input is injected one press/release step per frame: keep frames coming until
diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/liquify_ui.rs
new file mode 100644
index 000000000..1d3e9c66f
--- /dev/null
+++ b/crates/ui-egui/src/liquify_ui.rs
@@ -0,0 +1,720 @@
+//! Filter › Liquify…: a full-window dialog like Photoshop's (tool strip on the left, properties on
+//! the right, preview in the middle, OK / Cancel).
+//!
+//! The preview is a CPU proxy: the layer box-downsampled once to at most 1600 px
+//! (`ProxyImage`), re-rendered through the displacement field only where a dab changed it
+//! (bilinear field and source), and uploaded with a partial texture update. A dab plus its
+//! update costs well under a millisecond on a 24 MP layer (see `bench_liquify`). Strokes are
+//! recorded exactly as the engine replays them (`stroke_begin` + `stroke_segment` per point), so
+//! OK runs `filter.liquify` with the same strokes and gets the same field.
+
+use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};
+use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, ProxyImage, auto_cell};
+use photocraft_doc::LayerId;
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::ToolEvent;
+use crate::theme::Tokens;
+use crate::widgets;
+
+/// Longest side of the preview proxy (px).
+const PROXY_SIDE: usize = 1600;
+const LEFT_W: f32 = 48.0;
+const RIGHT_W: f32 = 292.0;
+
+/// Options shown in the properties panel (and settable over the control channel).
+#[derive(Clone, Debug)]
+pub struct LiquifyOpts {
+ pub tool: LiquifyTool,
+ pub size: f32,
+ pub density: f32,
+ pub pressure: f32,
+ pub rate: f32,
+ pub show_mesh: bool,
+ /// 0 small, 1 medium, 2 large.
+ pub mesh_size: usize,
+ pub show_mask: bool,
+ pub show_backdrop: bool,
+ pub backdrop_opacity: f32,
+ pub reconstruct_amount: f32,
+}
+
+impl Default for LiquifyOpts {
+ fn default() -> Self {
+ LiquifyOpts { tool: LiquifyTool::ForwardWarp, size: 100.0, density: 50.0, pressure: 100.0, rate: 80.0, show_mesh: false, mesh_size: 1, show_mask: true, show_backdrop: false, backdrop_opacity: 50.0, reconstruct_amount: 100.0 }
+ }
+}
+
+pub struct LiquifyDialog {
+ pub layer: LayerId,
+ layer_name: String,
+ canvas: Rect,
+ cell: f64,
+ pub field: LiquifyField,
+ pub strokes: Vec<LiquifyStroke>,
+ /// The stroke being drawn and its last point.
+ cur: Option<(LiquifyStroke, [f64; 3])>,
+ proxy: ProxyImage,
+ out: Vec<[u8; 4]>,
+ tex: Option<TextureHandle>,
+ /// Proxy pixels to re-render and upload (x0, y0, x1, y1).
+ dirty: Option<[usize; 4]>,
+ backdrop: Option<TextureHandle>,
+ mask_tex: Option<TextureHandle>,
+ mask_dirty: bool,
+ pub opts: LiquifyOpts,
+ /// Screen px per document px (0 = fit on next frame) and the view centre (document px).
+ zoom: f32,
+ center: [f64; 2],
+ hover: Option<[f64; 2]>,
+ last_dab: f64,
+ /// Last dab + proxy update time (ms), shown in the footer.
+ pub dab_ms: f64,
+}
+
+fn union(a: Option<[usize; 4]>, b: [usize; 4]) -> Option<[usize; 4]> {
+ if b[0] >= b[2] || b[1] >= b[3] {
+ return a;
+ }
+ Some(match a {
+ Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])],
+ None => b,
+ })
+}
+
+impl LiquifyDialog {
+ pub fn describe(&self) -> Value {
+ json!({
+ "layer": self.layer.0,
+ "tool": self.opts.tool,
+ "size": self.opts.size,
+ "strokes": self.strokes.len() + usize::from(self.cur.is_some()),
+ "meshSize": self.cell,
+ "maxDisplacement": self.field.max_displacement(),
+ "proxy": [self.proxy.w, self.proxy.h],
+ "dabMs": self.dab_ms,
+ })
+ }
+
+ fn template(&self) -> LiquifyStroke {
+ let o = &self.opts;
+ LiquifyStroke { tool: o.tool, size: f64::from(o.size), density: f64::from(o.density), pressure: f64::from(o.pressure), rate: f64::from(o.rate), points: Vec::new(), amount: None }
+ }
+
+ fn mark(&mut self, doc_rect: Rect, mask: bool) {
+ if doc_rect.is_empty() {
+ return;
+ }
+ self.dirty = union(self.dirty, self.proxy.proxy_rect(doc_rect));
+ self.mask_dirty |= mask;
+ }
+
+ fn begin(&mut self, p: [f64; 3], now: f64) {
+ let mut s = self.template();
+ s.points.push(p.to_vec());
+ let t0 = crate::gpu_canvas::now_ms();
+ let d = self.field.stroke_begin(&s, p);
+ self.mark(d, matches!(s.tool, LiquifyTool::Freeze | LiquifyTool::Thaw));
+ self.render_dirty();
+ self.dab_ms = crate::gpu_canvas::now_ms() - t0;
+ self.cur = Some((s, p));
+ self.last_dab = now;
+ }
+
+ fn extend(&mut self, p: [f64; 3], now: f64) {
+ let Some((mut s, last)) = self.cur.take() else { return };
+ let t0 = crate::gpu_canvas::now_ms();
+ let d = self.field.stroke_segment(&s, last, p);
+ s.points.push(p.to_vec());
+ self.mark(d, matches!(s.tool, LiquifyTool::Freeze | LiquifyTool::Thaw));
+ self.render_dirty();
+ self.dab_ms = crate::gpu_canvas::now_ms() - t0;
+ self.cur = Some((s, p));
+ self.last_dab = now;
+ }
+
+ fn end(&mut self) {
+ if let Some((s, _)) = self.cur.take() {
+ self.strokes.push(s);
+ }
+ }
+
+ /// Applies a whole-field operation (Reconstruct…, mask buttons) as a stroke.
+ fn global(&mut self, tool: LiquifyTool, amount: Option<f64>) {
+ self.end();
+ let mut s = LiquifyStroke::new(tool, 1.0);
+ s.amount = amount;
+ let d = self.field.apply_stroke(&s);
+ self.strokes.push(s);
+ self.mark(d, true);
+ }
+
+ fn rebuild(&mut self) {
+ self.field = LiquifyField::from_strokes(self.canvas, self.cell, &self.strokes);
+ self.dirty = Some([0, 0, self.proxy.w, self.proxy.h]);
+ self.mask_dirty = true;
+ }
+
+ fn undo(&mut self) {
+ self.end();
+ if self.strokes.pop().is_some() {
+ self.rebuild();
+ }
+ }
+
+ fn restore_all(&mut self) {
+ self.cur = None;
+ self.strokes.clear();
+ self.rebuild();
+ }
+
+ /// Re-renders the dirty proxy pixels into `out` (the texture upload happens in `show`).
+ fn render_dirty(&mut self) {
+ if let Some(r) = self.dirty {
+ self.proxy.render(&self.field, r, &mut self.out);
+ }
+ }
+
+ fn upload(&mut self, ctx: &egui::Context) {
+ let (w, h) = (self.proxy.w, self.proxy.h);
+ match (&mut self.tex, self.dirty.take()) {
+ (None, _) => {
+ self.proxy.render(&self.field, [0, 0, w, h], &mut self.out);
+ let img = egui::ColorImage::new([w, h], self.out.iter().map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3])).collect());
+ self.tex = Some(ctx.load_texture("liquify-proxy", img, egui::TextureOptions::LINEAR));
+ }
+ (Some(tex), Some(r)) => {
+ let (x0, y0, x1, y1) = (r[0].min(w), r[1].min(h), r[2].min(w), r[3].min(h));
+ if x1 > x0 && y1 > y0 {
+ let mut px = Vec::with_capacity((x1 - x0) * (y1 - y0));
+ for y in y0..y1 {
+ px.extend(self.out[y * w + x0..y * w + x1].iter().map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3])));
+ }
+ tex.set_partial([x0, y0], egui::ColorImage::new([x1 - x0, y1 - y0], px), egui::TextureOptions::LINEAR);
+ }
+ }
+ _ => {}
+ }
+ if self.mask_dirty || self.mask_tex.is_none() {
+ self.mask_dirty = false;
+ let f = &self.field;
+ let img = egui::ColorImage::new([f.w, f.h], f.freeze.iter().map(|v| Color32::from_rgba_unmultiplied(230, 40, 40, (v.clamp(0.0, 1.0) * 140.0) as u8)).collect());
+ match &mut self.mask_tex {
+ Some(t) => t.set(img, egui::TextureOptions::LINEAR),
+ None => self.mask_tex = Some(ctx.load_texture("liquify-mask", img, egui::TextureOptions::LINEAR)),
+ }
+ }
+ }
+}
+
+/// Opens the dialog on the active layer.
+pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ let (layer, surf, _) = crate::distort_ui::active_pixels(app)?;
+ let st = app.session.active().ok_or("no document")?;
+ let canvas = st.doc.bounds();
+ let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
+ let cell = auto_cell(canvas);
+ let proxy = ProxyImage::new(&surf, canvas, PROXY_SIDE);
+ let out = vec![[0u8; 4]; proxy.w * proxy.h];
+ let center = [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0];
+ let mut d = LiquifyDialog {
+ layer,
+ layer_name: name,
+ canvas,
+ cell,
+ field: LiquifyField::new(canvas, cell),
+ strokes: Vec::new(),
+ cur: None,
+ proxy,
+ out,
+ tex: None,
+ dirty: None,
+ backdrop: None,
+ mask_tex: None,
+ mask_dirty: true,
+ opts: LiquifyOpts::default(),
+ zoom: 0.0,
+ center,
+ hover: None,
+ last_dab: 0.0,
+ dab_ms: 0.0,
+ };
+ // A sensible starting brush: about a tenth of the image.
+ d.opts.size = ((canvas.width().max(canvas.height()) as f32) / 10.0).round().clamp(10.0, 1500.0);
+ d.upload(ctx);
+ app.distort.liquify = Some(d);
+ Ok(())
+}
+
+/// OK: runs `filter.liquify` with the recorded strokes (one history step).
+pub fn commit(app: &mut PhotocraftApp) {
+ let Some(mut d) = app.distort.liquify.take() else { return };
+ d.end();
+ if d.strokes.is_empty() {
+ return;
+ }
+ let p = json!({"strokes": d.strokes, "meshSize": d.cell, "layer": d.layer.0});
+ let _ = app.run("filter.liquify", p);
+}
+
+/// Control channel: `filter.liquify {"ui": {...}}` while the dialog is open.
+pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
+ if ui.get("commit").and_then(Value::as_bool) == Some(true) {
+ commit(app);
+ return Ok(json!({"committed": true}));
+ }
+ if ui.get("cancel").and_then(Value::as_bool) == Some(true) {
+ app.distort.liquify = None;
+ return Ok(json!({"cancelled": true}));
+ }
+ let d = app.distort.liquify.as_mut().ok_or("Liquify is not open")?;
+ if let Some(t) = ui.get("tool") {
+ d.opts.tool = serde_json::from_value(t.clone()).map_err(|e| format!("bad tool: {e}"))?;
+ }
+ let num = |k: &str| ui.get(k).and_then(Value::as_f64).map(|v| v as f32);
+ let flag = |k: &str| ui.get(k).and_then(Value::as_bool);
+ if let Some(v) = num("size") {
+ d.opts.size = v.clamp(1.0, 15000.0);
+ }
+ if let Some(v) = num("density") {
+ d.opts.density = v.clamp(0.0, 100.0);
+ }
+ if let Some(v) = num("pressure") {
+ d.opts.pressure = v.clamp(0.0, 100.0);
+ }
+ if let Some(v) = num("rate") {
+ d.opts.rate = v.clamp(0.0, 100.0);
+ }
+ if let Some(v) = flag("showMesh") {
+ d.opts.show_mesh = v;
+ }
+ if let Some(v) = flag("showMask") {
+ d.opts.show_mask = v;
+ }
+ if let Some(v) = flag("showBackdrop") {
+ d.opts.show_backdrop = v;
+ }
+ if let Some(v) = ui.get("meshSize").and_then(Value::as_str) {
+ d.opts.mesh_size = match v {
+ "small" => 0,
+ "large" => 2,
+ _ => 1,
+ };
+ }
+ if flag("undo") == Some(true) {
+ d.undo();
+ }
+ if flag("restoreAll") == Some(true) {
+ d.restore_all();
+ }
+ if let Some(a) = num("reconstruct") {
+ d.global(LiquifyTool::ReconstructAll, Some(f64::from(a)));
+ }
+ for (k, t) in [("maskAll", LiquifyTool::FreezeAll), ("maskNone", LiquifyTool::ThawAll), ("invertMask", LiquifyTool::InvertFreeze)] {
+ if flag(k) == Some(true) {
+ d.global(t, None);
+ }
+ }
+ Ok(d.describe())
+}
+
+/// Pointer in document coordinates (from the preview or the control channel).
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) {
+ let now = crate::gpu_canvas::now_ms();
+ let Some(d) = app.distort.liquify.as_mut() else { return };
+ match ev {
+ ToolEvent::Down { x, y, pressure } => d.begin([x, y, f64::from(pressure)], now),
+ ToolEvent::Move { x, y, pressure } => {
+ d.hover = Some([x, y]);
+ if d.cur.is_some() {
+ d.extend([x, y, f64::from(pressure)], now);
+ }
+ }
+ ToolEvent::Up { x, y } => {
+ if let Some((_, last)) = d.cur
+ && (last[0] != x || last[1] != y)
+ {
+ d.extend([x, y, last[2]], now);
+ }
+ d.end();
+ }
+ }
+}
+
+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let Some(d) = app.distort.liquify.as_mut() else { return };
+ if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) {
+ d.undo();
+ }
+ if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::OpenBracket)) {
+ d.opts.size = (d.opts.size * 0.9).max(1.0);
+ }
+ if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::CloseBracket)) {
+ d.opts.size = (d.opts.size * 1.1).min(15000.0);
+ }
+ let tools = [(egui::Key::W, LiquifyTool::ForwardWarp), (egui::Key::R, LiquifyTool::Reconstruct), (egui::Key::E, LiquifyTool::Smooth), (egui::Key::C, LiquifyTool::TwirlCw), (egui::Key::S, LiquifyTool::Pucker), (egui::Key::B, LiquifyTool::Bloat), (egui::Key::O, LiquifyTool::PushLeft), (egui::Key::F, LiquifyTool::Freeze), (egui::Key::D, LiquifyTool::Thaw)];
+ for (k, t) in tools {
+ if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k)) {
+ d.opts.tool = t;
+ }
+ }
+}
+
+fn tool_icon(t: LiquifyTool) -> &'static str {
+ match t {
+ LiquifyTool::ForwardWarp => "pointer",
+ LiquifyTool::Reconstruct => "brush-cleaning",
+ LiquifyTool::Smooth => "droplet",
+ LiquifyTool::TwirlCw => "rotate-cw",
+ LiquifyTool::TwirlCcw => "undo-2",
+ LiquifyTool::Pucker => "scan",
+ LiquifyTool::Bloat => "maximize-2",
+ LiquifyTool::PushLeft => "chevrons-left",
+ LiquifyTool::Freeze => "lock",
+ LiquifyTool::Thaw => "lock-open",
+ _ => "circle",
+ }
+}
+
+fn shortcut(t: LiquifyTool) -> &'static str {
+ match t {
+ LiquifyTool::ForwardWarp => "W",
+ LiquifyTool::Reconstruct => "R",
+ LiquifyTool::Smooth => "E",
+ LiquifyTool::TwirlCw => "C",
+ LiquifyTool::Pucker => "S",
+ LiquifyTool::Bloat => "B",
+ LiquifyTool::PushLeft => "O",
+ LiquifyTool::Freeze => "F",
+ LiquifyTool::Thaw => "D",
+ _ => "",
+ }
+}
+
+fn load_backdrop(app: &PhotocraftApp, ctx: &egui::Context, layer: LayerId, canvas: Rect) -> Option<TextureHandle> {
+ let st = app.session.active()?;
+ let doc = crate::distort_ui::without_layer(&st.doc, layer);
+ let buf = photocraft_compose::render(&doc, canvas);
+ let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
+ let flat: Vec<f32> = buf.px.iter().flat_map(|p| *p).collect();
+ s.write_region(canvas, &flat);
+ Some(ctx.load_texture("liquify-backdrop", crate::distort_ui::surface_image(&s, canvas, PROXY_SIDE), egui::TextureOptions::LINEAR))
+}
+
+/// Draws the dialog (a full-window layer over the app).
+pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let t = Tokens::get(ctx);
+ let screen = ctx.content_rect();
+ if app.distort.liquify.as_ref().is_some_and(|d| d.opts.show_backdrop && d.backdrop.is_none()) {
+ let tex = app.distort.liquify.as_ref().map(|d| (d.layer, d.canvas)).and_then(|(layer, canvas)| load_backdrop(app, ctx, layer, canvas));
+ if let Some(d) = app.distort.liquify.as_mut() {
+ d.backdrop = tex;
+ }
+ }
+ let mut action: Option<&str> = None;
+ let mut events: Vec<ToolEvent> = Vec::new();
+ egui::Area::new(egui::Id::new("liquify-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
+ let Some(d) = app.distort.liquify.as_mut() else { return };
+ d.upload(ctx);
+ let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover());
+ let painter = ui.painter().clone();
+ painter.rect_filled(full, 0.0, t.chrome);
+ // Title strip.
+ let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0));
+ painter.rect_filled(title, 0.0, t.dock);
+ painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator));
+ let pct = if d.zoom > 0.0 { d.zoom * 100.0 } else { 100.0 };
+ painter.text(title.center(), Align2::CENTER_CENTER, format!("Liquify ({}, {:.0}%)", d.layer_name, pct), FontId::proportional(13.0), t.text);
+ let body = ERect::from_min_max(pos2(full.left(), title.bottom()), full.max);
+ // Left tool strip.
+ let left = ERect::from_min_size(body.min, vec2(LEFT_W, body.height()));
+ painter.rect_filled(left, 0.0, t.dock);
+ painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator));
+ let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0))));
+ strip.spacing_mut().item_spacing.y = 4.0;
+ for tool in LiquifyTool::ALL {
+ let tip = format!("{} ({})", tool.label(), shortcut(tool));
+ if crate::icons::button(&mut strip, tool_icon(tool), 34.0, d.opts.tool == tool, &tip).clicked() {
+ d.opts.tool = tool;
+ }
+ if matches!(tool, LiquifyTool::Smooth | LiquifyTool::PushLeft) {
+ strip.add_space(6.0);
+ }
+ }
+ // Right properties panel.
+ let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height()));
+ painter.rect_filled(right, 0.0, t.dock);
+ painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator));
+ let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 12.0))));
+ egui::ScrollArea::vertical().id_salt("liquify-props").show(&mut props, |ui| {
+ ui.spacing_mut().item_spacing.y = 6.0;
+ widgets::section_label(ui, "Brush Tool Options");
+ widgets::slider_row(ui, "Size", &mut d.opts.size, 1.0..=3000.0, "", None);
+ widgets::slider_row(ui, "Density", &mut d.opts.density, 0.0..=100.0, "", None);
+ widgets::slider_row(ui, "Pressure", &mut d.opts.pressure, 0.0..=100.0, "", None);
+ widgets::slider_row(ui, "Rate", &mut d.opts.rate, 0.0..=100.0, "", None);
+ widgets::hairline(ui);
+ widgets::section_label(ui, "Brush Reconstruct Options");
+ widgets::slider_row(ui, "Amount", &mut d.opts.reconstruct_amount, 0.0..=100.0, "%", None);
+ ui.horizontal(|ui| {
+ if widgets::secondary_button(ui, "Reconstruct", 110.0).clicked() {
+ let a = f64::from(d.opts.reconstruct_amount);
+ d.global(LiquifyTool::ReconstructAll, Some(a));
+ }
+ if widgets::secondary_button(ui, "Restore All", 110.0).clicked() {
+ d.restore_all();
+ }
+ });
+ widgets::hairline(ui);
+ widgets::section_label(ui, "Mask Options");
+ ui.horizontal(|ui| {
+ if widgets::secondary_button(ui, "None", 70.0).clicked() {
+ d.global(LiquifyTool::ThawAll, None);
+ }
+ if widgets::secondary_button(ui, "Mask All", 80.0).clicked() {
+ d.global(LiquifyTool::FreezeAll, None);
+ }
+ if widgets::secondary_button(ui, "Invert All", 80.0).clicked() {
+ d.global(LiquifyTool::InvertFreeze, None);
+ }
+ });
+ widgets::hairline(ui);
+ widgets::section_label(ui, "View Options");
+ widgets::checkbox(ui, &mut d.opts.show_mesh, "Show Mesh");
+ ui.horizontal(|ui| {
+ ui.label("Mesh Size");
+ widgets::dropdown(ui, "liquify-mesh-size", &mut d.opts.mesh_size, &[(0, "Small"), (1, "Medium"), (2, "Large")], 110.0);
+ });
+ widgets::checkbox(ui, &mut d.opts.show_mask, "Show Mask");
+ widgets::checkbox(ui, &mut d.opts.show_backdrop, "Show Backdrop");
+ if d.opts.show_backdrop {
+ widgets::slider_row(ui, "Opacity", &mut d.opts.backdrop_opacity, 0.0..=100.0, "", None);
+ }
+ widgets::hairline(ui);
+ ui.label(egui::RichText::new(format!("{} stroke(s) · field {} px/node · dab {:.2} ms", d.strokes.len(), d.cell, d.dab_ms)).color(t.text_faint).size(11.0));
+ });
+ // Footer buttons.
+ let foot = ERect::from_min_size(pos2(right.left() + 14.0, right.bottom() - 48.0), vec2(RIGHT_W - 28.0, 32.0));
+ let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center)));
+ if widgets::primary_button(&mut fb, "OK", 84.0).clicked() {
+ action = Some("ok");
+ }
+ if widgets::secondary_button(&mut fb, "Cancel", 84.0).clicked() {
+ action = Some("cancel");
+ }
+ // Preview.
+ let area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(right.left(), body.bottom()));
+ painter.rect_filled(area, 0.0, t.canvas);
+ let (cw, ch) = (d.canvas.width() as f32, d.canvas.height() as f32);
+ if d.zoom <= 0.0 {
+ d.zoom = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / ch).clamp(0.01, 4.0);
+ d.center = [f64::from(d.canvas.x0) + f64::from(cw) / 2.0, f64::from(d.canvas.y0) + f64::from(ch) / 2.0];
+ }
+ let resp = ui.interact(area, egui::Id::new("liquify-preview"), Sense::click_and_drag());
+ // Wheel zooms about the pointer.
+ if resp.hovered() {
+ let scroll = ui.input(|i| i.smooth_scroll_delta.y);
+ if scroll != 0.0
+ && let Some(hp) = resp.hover_pos()
+ {
+ let before = to_doc(d, area, hp);
+ d.zoom = (d.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0);
+ let after = to_doc(d, area, hp);
+ d.center = [d.center[0] + before[0] - after[0], d.center[1] + before[1] - after[1]];
+ }
+ }
+ let img = ERect::from_min_max(to_screen(d, area, [f64::from(d.canvas.x0), f64::from(d.canvas.y0)]), to_screen(d, area, [f64::from(d.canvas.x1), f64::from(d.canvas.y1)]));
+ let clip = painter.with_clip_rect(area);
+ widgets::checker(&clip, img.intersect(area), 8.0);
+ let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
+ if d.opts.show_backdrop
+ && let Some(b) = &d.backdrop
+ {
+ clip.image(b.id(), img, uv, Color32::from_white_alpha((d.opts.backdrop_opacity / 100.0 * 255.0) as u8));
+ }
+ // The proxy covers whole proxy pixels, a little past the canvas edge.
+ let pr = ERect::from_min_max(img.min, img.min + vec2(d.proxy.w as f32 * d.proxy.scale as f32 * d.zoom, d.proxy.h as f32 * d.proxy.scale as f32 * d.zoom));
+ if let Some(tex) = &d.tex {
+ clip.image(tex.id(), pr, uv, Color32::WHITE);
+ }
+ if d.opts.show_mask
+ && let Some(m) = &d.mask_tex
+ {
+ let f = &d.field;
+ let mr = ERect::from_min_size(img.min - vec2(0.5, 0.5) * d.zoom * f.cell as f32 + vec2(0.5, 0.5) * d.zoom, vec2(f.w as f32, f.h as f32) * f.cell as f32 * d.zoom);
+ clip.image(m.id(), mr, uv, Color32::WHITE);
+ }
+ if d.opts.show_mesh {
+ draw_mesh(d, &clip, area);
+ }
+ // Brush outline.
+ if let Some(hp) = resp.hover_pos() {
+ let r = d.opts.size * 0.5 * d.zoom;
+ clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK));
+ clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE));
+ d.hover = Some(to_doc(d, area, hp));
+ }
+ clip.rect_stroke(img, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
+ // Mouse → strokes (Space or middle button pans).
+ let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down());
+ if pan && resp.dragged() {
+ let dl = resp.drag_delta();
+ d.center = [d.center[0] - f64::from(dl.x / d.zoom), d.center[1] - f64::from(dl.y / d.zoom)];
+ } else if let Some(pp) = resp.interact_pointer_pos() {
+ let q = to_doc(d, area, pp);
+ let pr = 1.0;
+ if resp.drag_started() || (resp.is_pointer_button_down_on() && d.cur.is_none()) {
+ events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: pr });
+ } else if resp.dragged() || resp.is_pointer_button_down_on() {
+ let moved = d.cur.as_ref().is_some_and(|(_, l)| l[0] != q[0] || l[1] != q[1]);
+ // Stationary tools keep working while the brush is held still (30 dabs/s).
+ let held = d.opts.tool.is_stationary() && crate::gpu_canvas::now_ms() - d.last_dab > 33.0;
+ if moved || held {
+ events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: pr });
+ }
+ ctx.request_repaint();
+ }
+ }
+ if resp.drag_stopped() || (d.cur.is_some() && !ui.input(|i| i.pointer.primary_down())) {
+ let q = d.cur.as_ref().map(|(_, l)| [l[0], l[1]]).unwrap_or_default();
+ events.push(ToolEvent::Up { x: q[0], y: q[1] });
+ }
+ });
+ for ev in events {
+ pointer(app, ev, egui::Modifiers::NONE);
+ }
+ match action {
+ Some("ok") => commit(app),
+ Some("cancel") => app.distort.liquify = None,
+ _ => {}
+ }
+}
+
+fn to_screen(d: &LiquifyDialog, area: ERect, p: [f64; 2]) -> Pos2 {
+ area.center() + vec2(((p[0] - d.center[0]) as f32) * d.zoom, ((p[1] - d.center[1]) as f32) * d.zoom)
+}
+
+fn to_doc(d: &LiquifyDialog, area: ERect, p: Pos2) -> [f64; 2] {
+ let v = (p - area.center()) / d.zoom;
+ [d.center[0] + f64::from(v.x), d.center[1] + f64::from(v.y)]
+}
+
+/// The deformed mesh: where the source grid lines land. Each output sample knows its source
+/// position `p + d(p)`, so a source line `x = c` is the iso-line of that function, traced with
+/// marching squares on a sample grid four times finer than the mesh (exact for any field, unlike
+/// inverting the field point by point, which fails where it folds).
+fn draw_mesh(d: &LiquifyDialog, painter: &egui::Painter, area: ERect) {
+ let c = d.canvas;
+ let cells = [64.0, 40.0, 24.0][d.opts.mesh_size.min(2)];
+ let step = f64::from(c.width().max(c.height())) / cells;
+ let h = step / 4.0;
+ let nx = (f64::from(c.width()) / h).ceil() as usize + 1;
+ let ny = (f64::from(c.height()) / h).ceil() as usize + 1;
+ let (x0, y0) = (f64::from(c.x0), f64::from(c.y0));
+ let mut src = Vec::with_capacity(nx * ny);
+ for j in 0..ny {
+ for i in 0..nx {
+ let p = [x0 + i as f64 * h, y0 + j as f64 * h];
+ let v = d.field.sample(p[0], p[1]);
+ src.push([p[0] + v[0], p[1] + v[1]]);
+ }
+ }
+ let stroke = Stroke::new(0.75, Color32::from_rgba_unmultiplied(90, 90, 90, 210));
+ let pos = |i: usize, j: usize| [x0 + i as f64 * h, y0 + j as f64 * h];
+ for axis in 0..2 {
+ let origin = if axis == 0 { x0 } else { y0 };
+ for jj in 0..ny - 1 {
+ for ii in 0..nx - 1 {
+ let corners = [(ii, jj), (ii + 1, jj), (ii + 1, jj + 1), (ii, jj + 1)];
+ let vals = corners.map(|(i, j)| src[j * nx + i][axis]);
+ let (lo, hi) = (vals.iter().copied().fold(f64::MAX, f64::min), vals.iter().copied().fold(f64::MIN, f64::max));
+ let mut k = ((lo - origin) / step).ceil() as i64;
+ while origin + k as f64 * step <= hi {
+ let level = origin + k as f64 * step;
+ let mut pts: Vec<[f64; 2]> = Vec::with_capacity(4);
+ for e in 0..4 {
+ let (a, b) = (vals[e] - level, vals[(e + 1) % 4] - level);
+ if (a <= 0.0) != (b <= 0.0) {
+ let t = a / (a - b);
+ let (pa, pb) = (pos(corners[e].0, corners[e].1), pos(corners[(e + 1) % 4].0, corners[(e + 1) % 4].1));
+ pts.push([pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t]);
+ }
+ }
+ for seg in pts.chunks_exact(2) {
+ painter.line_segment([to_screen(d, area, seg[0]), to_screen(d, area, seg[1])], stroke);
+ }
+ k += 1;
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app_with_layer() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.session.execute("file.new", json!({"width": 120, "height": 80, "depth": 8})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session
+ .edit("paint", |doc, active| {
+ let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for y in 10..70 {
+ for x in 10..110 {
+ let v = ((x / 5 + y / 5) % 2) as f32;
+ s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ app.sync_views();
+ app
+ }
+
+ #[test]
+ fn dialog_strokes_match_the_engine_and_commit_once() {
+ let ctx = egui::Context::default();
+ let mut app = app_with_layer();
+ open(&mut app, &ctx).unwrap();
+ control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap();
+ for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 48.0, y: 41.0, pressure: 1.0 }, ToolEvent::Move { x: 56.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 56.0, y: 40.0 }] {
+ pointer(&mut app, ev, egui::Modifiers::NONE);
+ }
+ control(&mut app, &json!({"tool": "bloat"})).unwrap();
+ for ev in [ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 80.0, y: 40.0 }] {
+ pointer(&mut app, ev, egui::Modifiers::NONE);
+ }
+ let d = app.distort.liquify.as_ref().unwrap();
+ assert_eq!(d.strokes.len(), 2);
+ // Replaying the recorded strokes gives exactly the interactive field.
+ let replay = LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes);
+ assert_eq!(replay, d.field);
+ assert!(d.field.max_displacement() > 3.0);
+ // Undo inside the dialog drops the last stroke.
+ control(&mut app, &json!({"undo": true})).unwrap();
+ assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1);
+ let before = app.session.active().unwrap().history.past_len();
+ control(&mut app, &json!({"commit": true})).unwrap();
+ assert!(app.distort.liquify.is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+ }
+
+ #[test]
+ fn menu_opens_the_dialog_and_routes_pointer_events() {
+ let ctx = egui::Context::default();
+ let mut app = app_with_layer();
+ let r = crate::distort_ui::menu(&mut app, &ctx, "filter.liquify", &json!({})).unwrap().unwrap();
+ assert!(r["liquify"]["proxy"].is_array());
+ assert!(crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE));
+ crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE);
+ assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1);
+ control(&mut app, &json!({"cancel": true})).unwrap();
+ assert!(app.distort.liquify.is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), 2, "cancel records nothing");
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index c95ce95c8..e93caef2d 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -111,6 +111,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
if let Some(r) = crate::view_cmds::invoke(app, ctx, id, &params) {
return r;
}
+ // Liquify dialog, Puppet Warp and Perspective Warp modes (and their control params).
+ if let Some(r) = crate::distort_ui::menu(app, ctx, id, &params) {
+ return r;
+ }
if let Some(profile) = proof_preset(id) {
// View › Proof Setup presets: set the proof profile and turn Proof Colors on.
app.run("view.proofSetup", json!({"profile": profile}))?;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 5540abbc4..32aa67f26 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -246,6 +246,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::transform_tool::options_bar(app, ui);
return;
}
+ if crate::distort_ui::options_bar(app, ui) {
+ return;
+ }
let tool = app.ui.tool;
if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Eraser)) || tool == Tool::QuickSelection {
brush_preset_chip(ui, &mut app.session.tools.brush);
@@ -615,7 +618,11 @@ fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Pan
}
if p.history {
let mut sel = app.ui.dock_tabs.history;
- widgets::card(ui, "history", &["History", "Actions"], &mut sel, |ui, tab| if tab == 0 { history(app, ui) } else { crate::actions::panel(app, ui) });
+ widgets::card(ui, "history", &["History", "Actions", "Layer Comps"], &mut sel, |ui, tab| match tab {
+ 0 => history(app, ui),
+ 1 => crate::actions::panel(app, ui),
+ _ => crate::comps_ui::panel(app, ui),
+ });
app.ui.dock_tabs.history = sel;
}
if p.layers {
@@ -1572,6 +1579,7 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
icons::paint(ui, r, icon, 15.0, t.icon);
let kind = match &layer.content {
LayerContent::Adjustment(a) => a.label().to_string(),
+ LayerContent::Group(g) if g.artboard.is_some() => "Artboard".to_string(),
other => format!("{} Layer", other.kind_name()),
};
ui.label(RichText::new(kind).color(t.text));
@@ -1581,6 +1589,8 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.add_space(6.0);
if let LayerContent::Adjustment(adj) = &layer.content {
adjustment_controls(app, ui, id, adj);
+ } else if layer.artboard().is_some() {
+ crate::artboard_ui::properties(app, ui, &layer);
} else {
layer_controls(app, ui, &layer);
if matches!(layer.content, LayerContent::Text(_)) {
diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs
index e1197326f..8830a4031 100644
--- a/crates/ui-egui/src/parity.rs
+++ b/crates/ui-egui/src/parity.rs
@@ -7,7 +7,7 @@ use crate::menu_catalog::CATALOG;
use crate::menus::is_live;
/// Minimum number of live catalog items. Raise it when parity grows; never lower it.
-pub const FLOOR: usize = 513;
+pub const FLOOR: usize = 527;
/// One top-level menu's coverage.
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/ui-egui/src/perspective_ui.rs b/crates/ui-egui/src/perspective_ui.rs
new file mode 100644
index 000000000..d5b3d68eb
--- /dev/null
+++ b/crates/ui-egui/src/perspective_ui.rs
@@ -0,0 +1,354 @@
+//! Edit › Perspective Warp on the canvas.
+//!
+//! **Layout** mode: drag on the image to draw a plane, drag its corners onto the image's
+//! perspective lines; a corner dropped near another plane's corner snaps to it, which links the
+//! planes along that edge. **Warp** mode: drag corners (linked corners move together) and the
+//! image follows; the options bar straightens near-vertical / near-horizontal edges. ↩ / Commit
+//! runs `edit.perspectiveWarp` with the planes. The preview is the layer texture on a 40×40 mesh
+//! pushed through the same piecewise-homography map the engine uses.
+
+use std::sync::Arc;
+
+use egui::{Color32, Pos2, Stroke, TextureHandle, pos2};
+use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, linked_corners, plane_point, straighten};
+use photocraft_doc::{Document, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PerspMode {
+ Layout,
+ Warp,
+}
+
+enum Drag {
+ NewPlane { start: [f64; 2], cur: [f64; 2] },
+ /// Linked corners being moved, and the pointer offset from the corner.
+ Corner { group: Vec<(usize, usize)>, offset: [f64; 2] },
+}
+
+pub struct PerspSession {
+ pub key: u64,
+ pub layer: LayerId,
+ command: String,
+ bounds: Rect,
+ pub planes: Vec<Plane>,
+ pub mode: PerspMode,
+ drag: Option<Drag>,
+ texture: TextureHandle,
+ opacity: f32,
+ pub preview_doc: Arc<Document>,
+ /// Preview mesh: (screen-independent destination points) for a 40×40 grid over `bounds`.
+ grid: Vec<[f64; 2]>,
+}
+
+const GRID: usize = 40;
+
+impl PerspSession {
+ pub fn describe(&self) -> Value {
+ json!({"layer": self.layer.0, "mode": self.mode, "planes": self.planes})
+ }
+
+ fn update_grid(&mut self) {
+ let b = self.bounds;
+ let map = if self.mode == PerspMode::Warp { PerspectiveMap::new(&self.planes) } else { None };
+ self.grid.clear();
+ for j in 0..=GRID {
+ for i in 0..=GRID {
+ let x = f64::from(b.x0) + f64::from(b.width()) * i as f64 / GRID as f64;
+ let y = f64::from(b.y0) + f64::from(b.height()) * j as f64 / GRID as f64;
+ let (u, v) = map.as_ref().map_or((x, y), |m| m.map(x, y));
+ self.grid.push([u, v]);
+ }
+ }
+ }
+
+ fn corners(&self, p: usize) -> &[[f64; 2]; 4] {
+ if self.mode == PerspMode::Layout { &self.planes[p].src } else { &self.planes[p].dst }
+ }
+
+ fn corner_at(&self, p: [f64; 2], tol: f64) -> Option<(usize, usize)> {
+ let mut best = None;
+ let mut bd = tol;
+ for pi in 0..self.planes.len() {
+ for (ci, c) in self.corners(pi).iter().enumerate() {
+ let d = (c[0] - p[0]).hypot(c[1] - p[1]);
+ if d <= bd {
+ bd = d;
+ best = Some((pi, ci));
+ }
+ }
+ }
+ best
+ }
+
+ fn snap(&self, p: [f64; 2], tol: f64, skip: &[(usize, usize)]) -> [f64; 2] {
+ for (pi, pl) in self.planes.iter().enumerate() {
+ for (ci, c) in pl.src.iter().enumerate() {
+ if !skip.contains(&(pi, ci)) && (c[0] - p[0]).hypot(c[1] - p[1]) <= tol {
+ return *c;
+ }
+ }
+ }
+ p
+ }
+
+ fn set_corner(&mut self, group: &[(usize, usize)], p: [f64; 2]) {
+ for &(pi, ci) in group {
+ if self.mode == PerspMode::Layout {
+ self.planes[pi].src[ci] = p;
+ }
+ self.planes[pi].dst[ci] = p;
+ }
+ }
+}
+
+pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context, command: &str) -> Result<(), String> {
+ if app.ui.transform.is_some() {
+ return Err("finish Free Transform first".into());
+ }
+ let (layer, surface, _) = crate::distort_ui::active_pixels(app)?;
+ let st = app.session.active().ok_or("no document")?;
+ let l = st.doc.layer(layer).ok_or("no layer")?;
+ let bounds = surface.content_bounds();
+ if bounds.is_empty() {
+ return Err("Could not use Perspective Warp: the layer is empty".into());
+ }
+ let opacity = l.opacity * l.fill_opacity;
+ let preview_doc = crate::distort_ui::without_layer(&st.doc, layer);
+ let key = app.ui.alloc_id();
+ let texture = ctx.load_texture(format!("persp-{key}"), crate::distort_ui::surface_image(&surface, bounds, 2048), egui::TextureOptions::LINEAR);
+ let mut s = PerspSession { key, layer, command: command.to_string(), bounds, planes: Vec::new(), mode: PerspMode::Layout, drag: None, texture, opacity, preview_doc, grid: Vec::new() };
+ s.update_grid();
+ app.distort.perspective = Some(s);
+ app.ui.status = "Perspective Warp: draw planes along the image's perspective, then switch to Warp".into();
+ Ok(())
+}
+
+pub fn commit(app: &mut PhotocraftApp) {
+ let Some(s) = app.distort.perspective.take() else { return };
+ if s.planes.is_empty() || PerspectiveMap::is_identity(&s.planes) {
+ return;
+ }
+ let _ = app.run(&s.command, json!({"planes": s.planes, "layer": s.layer.0}));
+}
+
+fn set_mode(s: &mut PerspSession, m: PerspMode) {
+ s.mode = m;
+ if m == PerspMode::Warp {
+ // Linked corners share one position from here on.
+ photocraft_algo::perspective::unify(&mut s.planes);
+ }
+ s.update_grid();
+}
+
+/// Control channel: `edit.perspectiveWarp {"ui": {...}}` while the mode is active.
+pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
+ if ui.get("commit").and_then(Value::as_bool) == Some(true) {
+ commit(app);
+ return Ok(json!({"committed": true}));
+ }
+ if ui.get("cancel").and_then(Value::as_bool) == Some(true) {
+ app.distort.perspective = None;
+ return Ok(json!({"cancelled": true}));
+ }
+ let s = app.distort.perspective.as_mut().ok_or("Perspective Warp is not active")?;
+ if let Some(m) = ui.get("mode").and_then(Value::as_str) {
+ set_mode(s, if m == "warp" { PerspMode::Warp } else { PerspMode::Layout });
+ }
+ if let Some(p) = ui.get("planes") {
+ s.planes = serde_json::from_value(p.clone()).map_err(|e| format!("bad planes: {e}"))?;
+ s.update_grid();
+ }
+ if let Some(st) = ui.get("straighten").and_then(Value::as_str) {
+ let m = Straighten::parse(st).ok_or("straighten: horizontal|vertical|auto")?;
+ straighten(&mut s.planes, m);
+ s.update_grid();
+ }
+ Ok(s.describe())
+}
+
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) {
+ let tol = crate::distort_ui::tolerance(app);
+ let Some(s) = app.distort.perspective.as_mut() else { return };
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ let p = [x, y];
+ if let Some((pi, ci)) = s.corner_at(p, tol) {
+ let c = s.corners(pi)[ci];
+ // Move every corner linked to this one.
+ let group = linked_corners(&s.planes).into_iter().find(|g| g.contains(&(pi, ci))).unwrap_or_else(|| vec![(pi, ci)]);
+ s.drag = Some(Drag::Corner { group, offset: [c[0] - x, c[1] - y] });
+ } else if s.mode == PerspMode::Layout {
+ let start = s.snap(p, tol, &[]);
+ s.drag = Some(Drag::NewPlane { start, cur: p });
+ }
+ }
+ ToolEvent::Move { x, y, .. } => match &mut s.drag {
+ Some(Drag::NewPlane { cur, .. }) => *cur = [x, y],
+ Some(Drag::Corner { group, offset }) => {
+ let group = group.clone();
+ let mut q = [x + offset[0], y + offset[1]];
+ if s.mode == PerspMode::Layout {
+ q = s.snap(q, tol, &group);
+ }
+ s.set_corner(&group, q);
+ if s.mode == PerspMode::Warp {
+ s.update_grid();
+ }
+ }
+ None => {}
+ },
+ ToolEvent::Up { x, y } => {
+ match s.drag.take() {
+ Some(Drag::NewPlane { start, .. }) => {
+ let end = s.snap([x, y], tol, &[]);
+ let (x0, y0, x1, y1) = (start[0].min(end[0]), start[1].min(end[1]), start[0].max(end[0]), start[1].max(end[1]));
+ if x1 - x0 > 4.0 && y1 - y0 > 4.0 {
+ // Keep the snapped corners exact.
+ let mut q = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
+ for c in q.iter_mut() {
+ *c = s.snap(*c, tol, &[]);
+ }
+ s.planes.push(Plane::identity(q));
+ }
+ }
+ Some(Drag::Corner { group, offset }) => {
+ let mut q = [x + offset[0], y + offset[1]];
+ if s.mode == PerspMode::Layout {
+ q = s.snap(q, tol, &group);
+ }
+ s.set_corner(&group, q);
+ }
+ None => {}
+ }
+ s.update_grid();
+ }
+ }
+}
+
+pub fn draw(s: &PerspSession, painter: &egui::Painter, xf: &ViewXform) {
+ let scr = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32);
+ let mut mesh = egui::Mesh::with_texture(s.texture.id());
+ let tint = Color32::from_white_alpha((s.opacity.clamp(0.0, 1.0) * 255.0) as u8);
+ for j in 0..=GRID {
+ for i in 0..=GRID {
+ let p = s.grid[j * (GRID + 1) + i];
+ mesh.vertices.push(egui::epaint::Vertex { pos: scr(p), uv: pos2(i as f32 / GRID as f32, j as f32 / GRID as f32), color: tint });
+ }
+ }
+ for j in 0..GRID {
+ for i in 0..GRID {
+ let a = (j * (GRID + 1) + i) as u32;
+ mesh.add_triangle(a, a + 1, a + GRID as u32 + 2);
+ mesh.add_triangle(a, a + GRID as u32 + 2, a + GRID as u32 + 1);
+ }
+ }
+ painter.add(mesh);
+ let accent = crate::theme::Tokens::get(painter.ctx()).accent;
+ let warp = s.mode == PerspMode::Warp;
+ for p in &s.planes {
+ // Plane grid at thirds (like Photoshop's), then the outline.
+ let thin = Stroke::new(0.75, Color32::from_rgba_unmultiplied(255, 255, 255, 150));
+ for k in 1..3 {
+ let t = k as f64 / 3.0;
+ painter.line_segment([scr(plane_point(p, t, 0.0, warp)), scr(plane_point(p, t, 1.0, warp))], thin);
+ painter.line_segment([scr(plane_point(p, 0.0, t, warp)), scr(plane_point(p, 1.0, t, warp))], thin);
+ }
+ let q = if warp { &p.dst } else { &p.src };
+ let pts: Vec<Pos2> = q.iter().map(|c| scr(*c)).collect();
+ painter.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.5, accent)));
+ for c in pts {
+ painter.circle_filled(c, 4.5, Color32::WHITE);
+ painter.circle_stroke(c, 4.5, Stroke::new(1.25, accent));
+ }
+ }
+ if let Some(Drag::NewPlane { start, cur }) = &s.drag {
+ let r = egui::Rect::from_two_pos(scr(*start), scr(*cur));
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);
+ }
+}
+
+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let Some(s) = app.distort.perspective.as_mut() else { return };
+ if crate::widgets::pill_tab(ui, "Layout", s.mode == PerspMode::Layout).clicked() {
+ set_mode(s, PerspMode::Layout);
+ }
+ if crate::widgets::pill_tab(ui, "Warp", s.mode == PerspMode::Warp).clicked() && !s.planes.is_empty() {
+ set_mode(s, PerspMode::Warp);
+ }
+ crate::widgets::vline(ui, 22.0);
+ if s.mode == PerspMode::Warp {
+ for (label, tip, m) in [("Straighten", "Automatically straighten near-vertical line segments", Straighten::Vertical), ("Level", "Automatically level near-horizontal line segments", Straighten::Horizontal), ("Both", "Automatically straighten and level", Straighten::Auto)] {
+ if ui.button(label).on_hover_text(tip).clicked() {
+ straighten(&mut s.planes, m);
+ s.update_grid();
+ }
+ }
+ } else {
+ ui.label(format!("{} plane(s)", s.planes.len()));
+ if ui.button("Remove Planes").clicked() {
+ s.planes.clear();
+ s.update_grid();
+ }
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::widgets::primary_button(ui, "✓", 32.0).on_hover_text("Commit Perspective Warp (↩)").clicked() {
+ commit(app);
+ } else if crate::widgets::secondary_button(ui, "⊘", 32.0).on_hover_text("Cancel (Esc)").clicked() {
+ app.distort.perspective = None;
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn layout_snaps_planes_then_warp_and_commit() {
+ let ctx = egui::Context::default();
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 120, "depth": 8})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session
+ .edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 190, 110), &[0.2, 0.6, 0.9, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ app.sync_views();
+ crate::distort_ui::menu(&mut app, &ctx, "edit.perspectiveWarp", &json!({})).unwrap().unwrap();
+ let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE);
+ // Two planes sharing an edge (the second starts at the first one's corner and snaps).
+ ev(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Move { x: 100.0, y: 100.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 });
+ ev(&mut app, ToolEvent::Down { x: 120.0, y: 30.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 180.0, y: 101.0 });
+ // Drop its left corners next to the first plane's right corners: they snap.
+ ev(&mut app, ToolEvent::Down { x: 120.0, y: 30.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 102.0, y: 21.0 });
+ ev(&mut app, ToolEvent::Down { x: 120.0, y: 101.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 101.0, y: 99.0 });
+ let s = app.distort.perspective.as_ref().unwrap();
+ assert_eq!(s.planes.len(), 2);
+ assert_eq!(s.planes[1].src[0], [100.0, 20.0], "snapped to the first plane's corner");
+ assert_eq!(s.planes[1].src[3], [100.0, 100.0]);
+ control(&mut app, &json!({"mode": "warp"})).unwrap();
+ // Dragging the shared top corner moves both planes.
+ ev(&mut app, ToolEvent::Down { x: 100.0, y: 20.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 100.0, y: 5.0 });
+ let s = app.distort.perspective.as_ref().unwrap();
+ assert_eq!(s.planes[0].dst[1], [100.0, 5.0]);
+ assert_eq!(s.planes[1].dst[0], [100.0, 5.0]);
+ assert_eq!(s.planes[0].src[1], [100.0, 20.0], "warp mode keeps the layout");
+ let before = app.session.active().unwrap().history.past_len();
+ commit(&mut app);
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+ }
+}
diff --git a/crates/ui-egui/src/puppet_ui.rs b/crates/ui-egui/src/puppet_ui.rs
new file mode 100644
index 000000000..4a745c4da
--- /dev/null
+++ b/crates/ui-egui/src/puppet_ui.rs
@@ -0,0 +1,400 @@
+//! Edit › Puppet Warp on the canvas: click on the mesh to add pins, drag pins to move them,
+//! ⌥-click a pin to remove it; the options bar sets mode, density, expansion, mesh visibility,
+//! the selected pin's depth and rotation. ↩ / Commit runs `edit.puppetWarp` with the pins.
+//!
+//! The preview is the layer texture on the deformed triangle mesh (an egui textured mesh, drawn
+//! by the GPU), re-solved with a few warm-started ARAP rounds per drag event (well under a
+//! millisecond with the banded Cholesky factor). When a drag ends the mesh is solved from scratch
+//! exactly like the engine, so what you see at rest is what Commit produces.
+
+use std::sync::Arc;
+
+use egui::{Color32, Stroke, TextureHandle, pos2, vec2};
+use photocraft_algo::puppet::{ITERATIONS, PuppetDensity, PuppetMesh, PuppetMode, PuppetPin, PuppetSolver, PuppetWarp, build_mesh};
+use photocraft_doc::{Document, LayerId};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+
+pub struct PuppetSession {
+ pub key: u64,
+ pub layer: LayerId,
+ /// Command to commit with (`edit.puppetWarp` or `layer.smartObjects.puppetWarp`).
+ command: String,
+ surface: Surface,
+ bounds: Rect,
+ pub warp: PuppetWarp,
+ pub show_mesh: bool,
+ pub selected: Option<usize>,
+ drag: Option<usize>,
+ mesh: PuppetMesh,
+ solver: Option<PuppetSolver>,
+ pub deformed: Vec<[f64; 2]>,
+ order: Vec<usize>,
+ texture: TextureHandle,
+ opacity: f32,
+ pub preview_doc: Arc<Document>,
+}
+
+impl PuppetSession {
+ pub fn describe(&self) -> Value {
+ json!({
+ "layer": self.layer.0,
+ "pins": self.warp.pins,
+ "mode": self.warp.mode,
+ "density": self.warp.density,
+ "expansion": self.warp.expansion,
+ "vertices": self.mesh.verts.len(),
+ "triangles": self.mesh.tris.len(),
+ "selected": self.selected,
+ })
+ }
+
+ fn rebuild_mesh(&mut self) {
+ self.mesh = build_mesh(&self.surface, self.bounds, self.warp.density, self.warp.expansion);
+ self.rebind();
+ }
+
+ /// New solver for the current pin set (pins added/removed, rotation fixed or freed).
+ fn rebind(&mut self) {
+ let src: Vec<[f64; 2]> = self.warp.pins.iter().map(|p| p.src).collect();
+ let fixed: Vec<bool> = self.warp.pins.iter().map(|p| p.rotate.is_some()).collect();
+ self.solver = Some(PuppetSolver::new(self.mesh.clone(), &src, &fixed));
+ self.solve(true);
+ }
+
+ /// Solves the deformation: exactly like the engine (`exact`), or a few warm rounds.
+ fn solve(&mut self, exact: bool) {
+ let Some(solver) = &self.solver else { return };
+ let dst: Vec<[f64; 2]> = self.warp.pins.iter().map(|p| p.dst).collect();
+ let rot: Vec<Option<f64>> = self.warp.pins.iter().map(|p| p.rotate).collect();
+ let warm = (!exact && self.deformed.len() == self.mesh.verts.len()).then_some(self.deformed.as_slice());
+ let (v, _) = solver.solve(&dst, &rot, self.warp.mode, if exact { ITERATIONS } else { 6 }, warm);
+ self.deformed = v;
+ let src: Vec<[f64; 2]> = self.warp.pins.iter().map(|p| p.src).collect();
+ let depths: Vec<i32> = self.warp.pins.iter().map(|p| p.depth).collect();
+ self.order = solver.draw_order(&depths, &src);
+ }
+
+ fn pin_at(&self, p: [f64; 2], tol: f64) -> Option<usize> {
+ self.warp.pins.iter().enumerate().filter(|(_, q)| (q.dst[0] - p[0]).hypot(q.dst[1] - p[1]) <= tol).min_by(|a, b| dist(a.1.dst, p).total_cmp(&dist(b.1.dst, p))).map(|(i, _)| i)
+ }
+
+ /// The rest position of a point on the deformed mesh (where a new pin attaches).
+ fn rest_of(&self, p: [f64; 2]) -> Option<[f64; 2]> {
+ for &t in self.order.iter().rev() {
+ let tri = self.mesh.tris[t];
+ let [a, b, c] = tri.map(|i| self.deformed[i]);
+ let det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
+ if det.abs() < 1e-12 {
+ continue;
+ }
+ let l1 = ((p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1])) / det;
+ let l2 = ((b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1])) / det;
+ let l0 = 1.0 - l1 - l2;
+ if l0 >= 0.0 && l1 >= 0.0 && l2 >= 0.0 {
+ let [ra, rb, rc] = tri.map(|i| self.mesh.verts[i]);
+ return Some([l0 * ra[0] + l1 * rb[0] + l2 * rc[0], l0 * ra[1] + l1 * rb[1] + l2 * rc[1]]);
+ }
+ }
+ None
+ }
+}
+
+fn dist(a: [f64; 2], b: [f64; 2]) -> f64 {
+ (a[0] - b[0]).hypot(a[1] - b[1])
+}
+
+/// Starts Puppet Warp on the active layer.
+pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context, command: &str) -> Result<(), String> {
+ if app.ui.transform.is_some() {
+ return Err("finish Free Transform first".into());
+ }
+ let (layer, surface, _) = crate::distort_ui::active_pixels(app)?;
+ let st = app.session.active().ok_or("no document")?;
+ let l = st.doc.layer(layer).ok_or("no layer")?;
+ let bounds = surface.content_bounds();
+ if bounds.is_empty() {
+ return Err("Could not use Puppet Warp: the layer is empty".into());
+ }
+ let opacity = l.opacity * l.fill_opacity;
+ let preview_doc = crate::distort_ui::without_layer(&st.doc, layer);
+ let img = crate::distort_ui::surface_image(&surface, bounds, 2048);
+ let key = app.ui.alloc_id();
+ let texture = ctx.load_texture(format!("puppet-{key}"), img, egui::TextureOptions::LINEAR);
+ let mut s = PuppetSession {
+ key,
+ layer,
+ command: command.to_string(),
+ surface,
+ bounds,
+ warp: PuppetWarp { pins: Vec::new(), mode: PuppetMode::Normal, density: PuppetDensity::Normal, expansion: 2.0 },
+ show_mesh: true,
+ selected: None,
+ drag: None,
+ mesh: PuppetMesh::default(),
+ solver: None,
+ deformed: Vec::new(),
+ order: Vec::new(),
+ texture,
+ opacity,
+ preview_doc,
+ };
+ s.rebuild_mesh();
+ if s.mesh.tris.is_empty() {
+ return Err("Could not use Puppet Warp: no opaque pixels".into());
+ }
+ app.distort.puppet = Some(s);
+ Ok(())
+}
+
+pub fn commit(app: &mut PhotocraftApp) {
+ let Some(s) = app.distort.puppet.take() else { return };
+ if s.warp.is_identity() {
+ return;
+ }
+ let mut p = serde_json::to_value(&s.warp).unwrap_or_default();
+ p["layer"] = json!(s.layer.0);
+ let _ = app.run(&s.command, p);
+}
+
+/// Control channel: `edit.puppetWarp {"ui": {...}}` while the mode is active.
+pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
+ if ui.get("commit").and_then(Value::as_bool) == Some(true) {
+ commit(app);
+ return Ok(json!({"committed": true}));
+ }
+ if ui.get("cancel").and_then(Value::as_bool) == Some(true) {
+ app.distort.puppet = None;
+ return Ok(json!({"cancelled": true}));
+ }
+ let s = app.distort.puppet.as_mut().ok_or("Puppet Warp is not active")?;
+ let mut remesh = false;
+ if let Some(m) = ui.get("mode").and_then(Value::as_str) {
+ s.warp.mode = PuppetMode::parse(m).ok_or("mode: rigid|normal|distort")?;
+ }
+ if let Some(d) = ui.get("density").and_then(Value::as_str) {
+ s.warp.density = PuppetDensity::parse(d).ok_or("density: fewer|normal|more")?;
+ remesh = true;
+ }
+ if let Some(e) = ui.get("expansion").and_then(Value::as_f64) {
+ s.warp.expansion = e.clamp(-200.0, 200.0);
+ remesh = true;
+ }
+ if let Some(v) = ui.get("showMesh").and_then(Value::as_bool) {
+ s.show_mesh = v;
+ }
+ if remesh {
+ s.rebuild_mesh();
+ } else {
+ s.solve(true);
+ }
+ Ok(s.describe())
+}
+
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) {
+ let tol = crate::distort_ui::tolerance(app);
+ let Some(s) = app.distort.puppet.as_mut() else { return };
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ let p = [x, y];
+ if let Some(i) = s.pin_at(p, tol) {
+ if mods.alt {
+ s.warp.pins.remove(i);
+ s.selected = None;
+ s.rebind();
+ } else {
+ s.selected = Some(i);
+ s.drag = Some(i);
+ }
+ } else if !mods.alt
+ && let Some(src) = s.rest_of(p)
+ {
+ s.warp.pins.push(PuppetPin { src, dst: p, rotate: None, depth: 0 });
+ s.selected = Some(s.warp.pins.len() - 1);
+ s.drag = s.selected;
+ s.rebind();
+ }
+ }
+ ToolEvent::Move { x, y, .. } => {
+ if let Some(i) = s.drag
+ && let Some(pin) = s.warp.pins.get_mut(i)
+ && pin.dst != [x, y]
+ {
+ pin.dst = [x, y];
+ s.solve(false);
+ }
+ }
+ ToolEvent::Up { x, y } => {
+ if let Some(i) = s.drag.take() {
+ if let Some(pin) = s.warp.pins.get_mut(i) {
+ pin.dst = [x, y];
+ }
+ s.solve(true);
+ }
+ }
+ }
+}
+
+pub fn draw(s: &PuppetSession, painter: &egui::Painter, xf: &ViewXform) {
+ let b = s.bounds;
+ let (w, h) = (f64::from(b.width()), f64::from(b.height()));
+ let mut mesh = egui::Mesh::with_texture(s.texture.id());
+ let tint = Color32::from_white_alpha((s.opacity.clamp(0.0, 1.0) * 255.0) as u8);
+ for (d, r) in s.deformed.iter().zip(&s.mesh.verts) {
+ let uv = pos2(((r[0] - f64::from(b.x0)) / w) as f32, ((r[1] - f64::from(b.y0)) / h) as f32);
+ mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(d[0] as f32, d[1] as f32), uv, color: tint });
+ }
+ for &t in &s.order {
+ let [a, bb, c] = s.mesh.tris[t];
+ mesh.add_triangle(a as u32, bb as u32, c as u32);
+ }
+ painter.add(mesh);
+ if s.show_mesh {
+ let line = Stroke::new(0.6, Color32::from_rgba_unmultiplied(40, 40, 40, 150));
+ let mut seen = std::collections::HashSet::new();
+ for tri in &s.mesh.tris {
+ for k in 0..3 {
+ let (i, j) = (tri[k].min(tri[(k + 1) % 3]), tri[k].max(tri[(k + 1) % 3]));
+ if seen.insert((i, j)) {
+ let (p, q) = (s.deformed[i], s.deformed[j]);
+ painter.line_segment([xf.to_screen(p[0] as f32, p[1] as f32), xf.to_screen(q[0] as f32, q[1] as f32)], line);
+ }
+ }
+ }
+ }
+ // Pins: yellow discs with a black ring; the selected pin has a black centre (Photoshop).
+ for (i, p) in s.warp.pins.iter().enumerate() {
+ let c = xf.to_screen(p.dst[0] as f32, p.dst[1] as f32);
+ painter.circle_filled(c, 5.5, Color32::from_rgb(255, 214, 10));
+ painter.circle_stroke(c, 5.5, Stroke::new(1.25, Color32::BLACK));
+ if s.selected == Some(i) {
+ painter.circle_filled(c, 2.0, Color32::BLACK);
+ if let Some(r) = p.rotate {
+ let a = (r as f32).to_radians();
+ painter.circle_stroke(c, 18.0, Stroke::new(1.0, Color32::WHITE));
+ painter.line_segment([c, c + vec2(a.cos(), a.sin()) * 18.0], Stroke::new(1.0, Color32::WHITE));
+ }
+ }
+ }
+}
+
+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let Some(s) = app.distort.puppet.as_mut() else { return };
+ let mut remesh = false;
+ let mut resolve = false;
+ let mut rebind = false;
+ ui.label("Mode:");
+ let mode = s.warp.mode;
+ crate::widgets::dropdown(ui, "puppet-mode", &mut s.warp.mode, &[(PuppetMode::Rigid, "Rigid"), (PuppetMode::Normal, "Normal"), (PuppetMode::Distort, "Distort")], 90.0);
+ resolve |= mode != s.warp.mode;
+ ui.label("Density:");
+ let density = s.warp.density;
+ crate::widgets::dropdown(ui, "puppet-density", &mut s.warp.density, &[(PuppetDensity::Fewer, "Fewer Points"), (PuppetDensity::Normal, "Normal"), (PuppetDensity::More, "More Points")], 110.0);
+ remesh |= density != s.warp.density;
+ ui.label("Expansion:");
+ let mut e = s.warp.expansion as f32;
+ if crate::widgets::value_field(ui, &mut e, -50.0..=100.0, "px", 56.0).changed() {
+ s.warp.expansion = f64::from(e);
+ remesh = true;
+ }
+ crate::widgets::checkbox(ui, &mut s.show_mesh, "Show Mesh");
+ crate::widgets::vline(ui, 22.0);
+ if let Some(i) = s.selected.filter(|i| *i < s.warp.pins.len()) {
+ ui.label("Pin Depth:");
+ if ui.small_button("+").on_hover_text("Bring the selected pin forward").clicked() {
+ s.warp.pins[i].depth += 1;
+ resolve = true;
+ }
+ if ui.small_button("−").on_hover_text("Send the selected pin backward").clicked() {
+ s.warp.pins[i].depth -= 1;
+ resolve = true;
+ }
+ ui.label("Rotate:");
+ let mut fixed = s.warp.pins[i].rotate.is_some();
+ let was = fixed;
+ crate::widgets::dropdown(ui, "puppet-rotate", &mut fixed, &[(false, "Auto"), (true, "Fixed")], 70.0);
+ if fixed != was {
+ s.warp.pins[i].rotate = fixed.then_some(0.0);
+ rebind = true;
+ }
+ if let Some(r) = s.warp.pins[i].rotate {
+ let mut a = r as f32;
+ if crate::widgets::value_field(ui, &mut a, -360.0..=360.0, "°", 52.0).changed() {
+ s.warp.pins[i].rotate = Some(f64::from(a));
+ resolve = true;
+ }
+ }
+ crate::widgets::vline(ui, 22.0);
+ }
+ if ui.button("Remove All Pins").clicked() {
+ s.warp.pins.clear();
+ s.selected = None;
+ rebind = true;
+ }
+ if remesh {
+ s.rebuild_mesh();
+ } else if rebind {
+ s.rebind();
+ } else if resolve {
+ s.solve(true);
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::widgets::primary_button(ui, "✓", 32.0).on_hover_text("Commit Puppet Warp (↩)").clicked() {
+ commit(app);
+ } else if crate::widgets::secondary_button(ui, "⊘", 32.0).on_hover_text("Cancel (Esc)").clicked() {
+ app.distort.puppet = None;
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pins_drag_and_commit_through_the_engine() {
+ let ctx = egui::Context::default();
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session
+ .edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ app.sync_views();
+ crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap();
+ let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE);
+ // Two pins: hold the left end, drag the right end up.
+ ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 });
+ ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 });
+ let s = app.distort.puppet.as_ref().unwrap();
+ assert_eq!(s.warp.pins.len(), 2);
+ assert_eq!(s.warp.pins[1].dst, [75.0, 20.0]);
+ // ⌥-click removes; clicking off the mesh adds nothing.
+ ev(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 });
+ assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 2);
+ crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers { alt: true, ..Default::default() });
+ assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 1);
+ ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 });
+ ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 });
+ control(&mut app, &json!({"mode": "rigid", "density": "more"})).unwrap();
+ let expected = app.distort.puppet.as_ref().unwrap().deformed.clone();
+ assert!(!expected.is_empty());
+ let before = app.session.active().unwrap().history.past_len();
+ crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({"ui": {"commit": true}})).unwrap().unwrap();
+ assert!(app.distort.puppet.is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+ let st = app.session.active().unwrap();
+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();
+ assert!(b.y0 < 25, "the right end went up: {b:?}");
+ }
+}
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index 9bb064d2f..e22f49d72 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -50,6 +50,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
if ctx.egui_wants_keyboard_input() || !app.ui.dialogs.is_empty() {
return;
}
+ // Liquify / Puppet Warp / Perspective Warp: ↩ commits, Esc cancels.
+ if crate::distort_ui::keys(app, ctx) {
+ return;
+ }
// Free Transform: ↩ commits, Esc cancels.
if app.ui.transform.is_some() {
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 6cf335905..a7e563065 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -421,6 +421,9 @@ pub struct UiState {
/// Recorded actions (Actions panel).
#[serde(default)]
pub actions: crate::actions::Actions,
+ /// Layer Comps panel: the selected comp (by comp id).
+ #[serde(default)]
+ pub layer_comp_selected: Option<u32>,
/// View extras: rulers (⌘R), grid (⌘'), guides (⌘;), snapping (⇧⌘;), locked guides (⌥⌘;).
#[serde(default)]
pub extras: Extras,
@@ -472,6 +475,7 @@ impl Default for UiState {
extras: Extras::default(),
view: Default::default(),
actions: Default::default(),
+ layer_comp_selected: None,
layer_filter: Vec::new(),
pen: None,
selected_path: None,
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index 261a82f95..253585551 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -174,6 +174,7 @@ fn panel_tab(app: &PhotocraftApp, id: &str) -> Option<(&'static str, usize)> {
"window.panel.histogram" => ("navigator", 1),
"window.panel.navigator" => ("navigator", 0),
"window.panel.actions" => ("history", 1),
+ "window.panel.layerComps" => ("history", 2),
"window.panel.history" => ("history", 0),
"window.panel.channels" => ("layers", 1),
"window.panel.paths" => ("layers", 2),
@@ -226,6 +227,8 @@ pub fn handles(id: &str) -> bool {
| "view.twoHundredPercent"
| "view.printSize"
| "view.fitLayersOnScreen"
+ | "view.fitArtboardOnScreen"
+ | "window.panel.layerComps"
| "view.flipHorizontal"
| "view.pixelAspectRatioCorrection"
| "view.patternPreview"
@@ -257,6 +260,7 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {
Some(match id {
"view.screenMode.cycle" => app.ui.text_edit.is_none(),
"view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" => doc,
+ "view.fitArtboardOnScreen" => app.session.active().is_some_and(|d| d.doc.has_artboards()),
i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] {
"consolidateAllToTabs" => true,
"floatInWindow" | "newWindowForDocument" => doc,
@@ -363,6 +367,10 @@ fn wraps(id: &str) -> bool {
| "file.scripts.imageProcessor"
| "file.scripts.loadFilesIntoStack"
| "file.export.layersToFiles"
+ | "file.export.layerCompsToFiles"
+ | "file.export.artboardsToFiles"
+ | "file.export.artboardsToPdf"
+ | "layer.new.artboard"
| "file.export.colorLookupTables"
| "view.newGuideLayout"
| "type.warpText"
@@ -491,6 +499,7 @@ fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Res
Ok(json!({"zoom": app.ui.views[i].zoom}))
}
"view.fitLayersOnScreen" => fit_layers(app),
+ "view.fitArtboardOnScreen" => crate::artboard_ui::fit_artboard(app),
_ => Err(format!("unhandled {id}")),
}
}
@@ -759,6 +768,26 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
let (_, _, name) = doc?;
dialog(app, json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true}), json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}))
}
+ "file.export.layerCompsToFiles" | "file.export.artboardsToFiles" => {
+ let (_, _, name) = doc?;
+ let prefix = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string();
+ let fields = if id == "file.export.layerCompsToFiles" {
+ json!({"dir": dir, "prefix": prefix, "format": "png", "selectedOnly": false})
+ } else {
+ json!({"dir": dir, "prefix": prefix, "format": "png"})
+ };
+ dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}))
+ }
+ "file.export.artboardsToPdf" => {
+ let (_, _, name) = doc?;
+ let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string();
+ dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({}))
+ }
+ "layer.new.artboard" => {
+ let (w, h, _) = doc?;
+ let presets: Vec<&str> = std::iter::once("").chain(photocraft_engine::artboard_cmds::PRESETS.iter().map(|p| p.0)).collect();
+ dialog(app, json!({"name": "", "preset": "", "width": w, "height": h, "background": "white"}), json!({"preset": presets, "background": ["white", "black", "transparent"]}))
+ }
"file.export.colorLookupTables" => {
let (_, _, name) = doc?;
let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string();
diff --git a/docs/parity.md b/docs/parity.md
index 84e3b51ce..3d8fc697c 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -2,29 +2,26 @@
Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand.
-**518 of 625 menu items live (82.9%).**
+**532 of 625 menu items live (85.1%).**
| Menu | Live | Total | % |
|---|---:|---:|---:|
-| File | 25 | 50 | 50% |
-| Edit | 71 | 75 | 95% |
+| File | 28 | 50 | 56% |
+| Edit | 73 | 75 | 97% |
| Image | 50 | 61 | 82% |
-| Layer | 140 | 160 | 88% |
+| Layer | 145 | 160 | 91% |
| Type | 41 | 44 | 93% |
| Select | 22 | 25 | 88% |
-| Filter | 66 | 75 | 88% |
-| View | 59 | 74 | 80% |
-| Window | 44 | 61 | 72% |
+| Filter | 67 | 75 | 89% |
+| View | 61 | 74 | 82% |
+| Window | 45 | 61 | 74% |
## Not yet implemented
-### File (25)
+### File (22)
- Export › Export Preferences… (`file.export.exportPreferences`)
- Export › Save for Web (Legacy)… (`file.export.saveForWebLegacy`)
-- Export › Artboards to Files… (`file.export.artboardsToFiles`)
-- Export › Artboards to PDF… (`file.export.artboardsToPdf`)
-- Export › Layer Comps to Files… (`file.export.layerCompsToFiles`)
- Export › Data Sets as Files… (`file.export.dataSetsAsFiles`)
- Export › Paths to Illustrator… (`file.export.pathsToIllustrator`)
- Export › Render Video… (`file.export.renderVideo`)
@@ -46,11 +43,9 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Print… (`file.print`)
- Print One Copy (`file.printOneCopy`)
-### Edit (4)
+### Edit (2)
- Check Spelling… (`edit.checkSpelling`)
-- Puppet Warp (`edit.puppetWarp`)
-- Perspective Warp (`edit.perspectiveWarp`)
- Presets › Migrate Presets (`edit.presets.migratePresets`)
### Image (11)
@@ -67,14 +62,9 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Analysis › Count Tool (`image.analysis.countTool`)
- Analysis › Place Scale Marker… (`image.analysis.placeScaleMarker`)
-### Layer (20)
+### Layer (15)
-- New › Artboard… (`layer.new.artboard`)
-- New › Artboard from Group… (`layer.new.artboardFromGroup`)
-- New › Artboard from Layers… (`layer.new.artboardFromLayers`)
- New › Frame from Layers (`layer.new.frameFromLayers`)
-- Smart Objects › Perspective Warp (`layer.smartObjects.perspectiveWarp`)
-- Smart Objects › Puppet Warp (`layer.smartObjects.puppetWarp`)
- Video Layers › New Blank Video Layer (`layer.videoLayers.newBlankVideoLayer`)
- Video Layers › New Video Layer from File… (`layer.videoLayers.newVideoLayerFromFile`)
- Video Layers › Insert Blank Frame (`layer.videoLayers.insertBlankFrame`)
@@ -102,19 +92,18 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Sky (`select.sky`)
- Transform Selection (`select.transformSelection`)
-### Filter (9)
+### Filter (8)
- Filter Gallery… (`filter.filterGallery`)
- Camera Raw Filter… (`filter.cameraRaw`)
- Adaptive Wide Angle… (`filter.adaptiveWideAngle`)
- Lens Correction… (`filter.lensCorrection`)
-- Liquify… (`filter.liquify`)
- Vanishing Point… (`filter.vanishingPoint`)
- Render › Flame… (`filter.render.flame`)
- Render › Picture Frame… (`filter.render.pictureFrame`)
- Render › Tree… (`filter.render.tree`)
-### View (15)
+### View (13)
- Proof Setup › Working Cyan Plate (`view.proofSetup.workingCyanPlate`)
- Proof Setup › Working Magenta Plate (`view.proofSetup.workingMagentaPlate`)
@@ -126,13 +115,11 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Proof Setup › Color Blindness — Deuteranopia-type (`view.proofSetup.colorBlindnessDeuteranopia`)
- Pixel Aspect Ratio › Custom Pixel Aspect Ratio… (`view.pixelAspectRatio.custom`)
- 32-bit Preview Options… (`view.thirtyTwoBitPreviewOptions`)
-- Fit Artboard on Screen (`view.fitArtboardOnScreen`)
- Show › Show Extras Options… (`view.show.showExtrasOptions`)
-- Clear Selected Artboard Guides (`view.clearSelectedArtboardGuides`)
- Lock Slices (`view.lockSlices`)
- Clear Slices (`view.clearSlices`)
-### Window (17)
+### Window (16)
- Workspace › New Workspace… (`window.workspace.newWorkspace`)
- Workspace › Delete Workspace… (`window.workspace.deleteWorkspace`)
@@ -141,7 +128,6 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Clone Source (`window.panel.cloneSource`)
- Glyphs (`window.panel.glyphs`)
- Gradients (`window.panel.gradients`)
-- Layer Comps (`window.panel.layerComps`)
- Measurement Log (`window.panel.measurementLog`)
- Modifier Keys (`window.panel.modifierKeys`)
- Notes (`window.panel.notes`)