PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Distance fields on threads: bevel size changes 2-3x cheaper (#2119) (#2162)
Sir Starcha737281faddd
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rsindex 1973ba761..e2ae63b5b 100644--- a/crates/compose/src/effects.rs+++ b/crates/compose/src/effects.rs@@ -167,33 +167,161 @@ fn edt(inside: &[bool], w: usize, h: usize) -> Vec<f32> {edt_nearest(inside, w, h).0}-/// [`edt`] plus the index of the nearest `inside` pixel.-fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec<f32>, Vec<usize>) {- const INF: f32 = 1e20;- let mut g: Vec<f32> = inside.iter().map(|&b| if b { 0.0 } else { INF }).collect();- let mut near_row = vec![0usize; w * h];- let mut nearest = vec![0usize; w * h];- let n = w.max(h);- let (mut f, mut o, mut v, mut z, mut nr) = (vec![0.0; n], vec![0.0; n], vec![0usize; n], vec![0.0f32; n + 1], vec![0usize; n]);- for x in 0..w {- for y in 0..h {- f[y] = g[y * w + x];+/// Maps with fewer pixels (or other units of work) than this are not worth spawning threads for.+const PAR_MIN: usize = 1 << 16;++/// Most threads one pass uses (as for the blurs, [`rows_par`]).+const PAR_THREADS: usize = 16;++#[cfg(test)]+thread_local! {+ /// Test hook: the thread count [`par_threads`] gives on this thread, whatever the work.+ static THREADS: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };+}++/// How many threads a pass over `work` pixels (or similar units) uses.+fn par_threads(work: usize) -> usize {+ #[cfg(test)]+ if let Some(n) = THREADS.with(std::cell::Cell::get) {+ return n;+ }+ if cfg!(target_arch = "wasm32") || work < PAR_MIN { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, PAR_THREADS) }+}++/// Runs `f(scratch, u, a_u, b_u)` for every unit `u` of two slices: unit `u` of `a` is+/// `a[u * unit_a..][..unit_a]` (the last may be shorter), the same of `b` with `unit_b`, which is 0+/// when there is no second slice. `work` says how big the whole pass is ([`par_threads`]). Groups of+/// units go to scoped OS threads, each with a scratch value from `init`; not to rayon, as for+/// [`rows_par`]: maps are built from inside rayon tiles, where a waiting worker steals other tiles.+/// A unit is computed from its own arguments alone, so the result does not depend on the threads.+fn par_units<S, A: Send, B: Send>(+ work: usize,+ a: &mut [A],+ unit_a: usize,+ b: &mut [B],+ unit_b: usize,+ init: impl Fn() -> S + Sync,+ f: impl Fn(&mut S, usize, &mut [A], &mut [B]) + Sync,+) {+ if unit_a == 0 {+ return;+ }+ let units = a.len().div_ceil(unit_a);+ let threads = par_threads(work).min(units);+ if threads <= 1 {+ run_units(&mut init(), 0, a, unit_a, b, unit_b, &f);+ return;+ }+ // Many more groups than threads, so that a heavy one (an edge-rich stretch) does not hold the rest up.+ let group = units.div_ceil(threads * 8).max(1);+ let mut groups = Vec::new();+ let (mut rest_a, mut rest_b, mut first) = (a, b, 0usize);+ while !rest_a.is_empty() {+ let (ga, na) = rest_a.split_at_mut((group * unit_a).min(rest_a.len()));+ let (gb, nb) = rest_b.split_at_mut((group * unit_b).min(rest_b.len()));+ groups.push((first, ga, gb));+ (rest_a, rest_b, first) = (na, nb, first + group);+ }+ let queue = std::sync::Mutex::new(groups.into_iter());+ let worker = || {+ let mut scratch = init();+ loop {+ let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next();+ let Some((first, ga, gb)) = next else { break };+ run_units(&mut scratch, first, ga, unit_a, gb, unit_b, &f);}- dt1(&f[..h], &mut o[..h], &mut v, &mut z, &mut nr[..h]);- for y in 0..h {- g[y * w + x] = o[y];- near_row[y * w + x] = nr[y];+ };+ std::thread::scope(|sc| {+ // A thread that cannot be spawned leaves its share to the others.+ for _ in 1..threads {+ let _ = std::thread::Builder::new().spawn_scoped(sc, worker);}+ worker();+ });+}++fn run_units<S, A, B>(scratch: &mut S, first: usize, a: &mut [A], unit_a: usize, b: &mut [B], unit_b: usize, f: &impl Fn(&mut S, usize, &mut [A], &mut [B])) {+ for (k, ua) in a.chunks_mut(unit_a).enumerate() {+ let ub = b.get_mut(k * unit_b..((k + 1) * unit_b).min(b.len())).unwrap_or(&mut []);+ f(scratch, first + k, ua, ub);}- for y in 0..h {- f[..w].copy_from_slice(&g[y * w..(y + 1) * w]);- dt1(&f[..w], &mut o[..w], &mut v, &mut z, &mut nr[..w]);- for x in 0..w {- g[y * w + x] = o[x].sqrt();- let px = nr[x];- nearest[y * w + x] = near_row[y * w + px] * w + px;- }+}++/// A `w × h` buffer of `fill`, then filled row by row through `f(y, row)`.+fn par_fill<T: Clone + Send>(w: usize, h: usize, fill: T, f: impl Fn(usize, &mut [T]) + Sync) -> Vec<T> {+ let mut out = vec![fill; w.saturating_mul(h)];+ par_units(out.len(), &mut out, w.max(1), &mut [] as &mut [()], 0, || (), |_, y, row, _| f(y, row));+ out+}++/// Working buffers of the 1D distance transform, for lines of up to `n` pixels.+struct Dt1Scratch {+ f: Vec<f32>,+ o: Vec<f32>,+ v: Vec<usize>,+ z: Vec<f32>,+ near: Vec<usize>,+}++impl Dt1Scratch {+ fn new(n: usize) -> Self {+ Dt1Scratch { f: vec![0.0; n], o: vec![0.0; n], v: vec![0; n], z: vec![0.0; n + 1], near: vec![0; n] }+ }+}++/// [`edt`] plus the index of the nearest `inside` pixel (as `u32`: a map past 2³² pixels has no+/// nearest pixel to give, and every distance is then "far").+///+/// Both passes run line by line in parallel: the columns, then the rows. The columns' results are+/// kept column by column (`gc[x * h + y]`) so that each thread writes its own stretch of them.+fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec<f32>, Vec<u32>) {+ const INF: f32 = 1e20;+ let total = w.saturating_mul(h);+ if total != inside.len() || total > u32::MAX as usize {+ return (vec![INF; inside.len()], vec![0; inside.len()]);}+ let n = w.max(h);+ let mut gc = vec![0.0f32; total];+ let mut nc = vec![0u32; total];+ par_units(+ total,+ &mut gc,+ h.max(1),+ &mut nc,+ h.max(1),+ || Dt1Scratch::new(n),+ |t, x, g, near| {+ for (y, f) in t.f[..h].iter_mut().enumerate() {+ *f = if inside[y * w + x] { 0.0 } else { INF };+ }+ dt1(&t.f[..h], &mut t.o[..h], &mut t.v, &mut t.z, &mut t.near[..h]);+ g.copy_from_slice(&t.o[..h]);+ for (d, &p) in near.iter_mut().zip(&t.near[..h]) {+ *d = p as u32;+ }+ },+ );+ let mut g = vec![0.0f32; total];+ let mut nearest = vec![0u32; total];+ par_units(+ total,+ &mut g,+ w.max(1),+ &mut nearest,+ w.max(1),+ || Dt1Scratch::new(n),+ |t, y, out, near| {+ for (x, f) in t.f[..w].iter_mut().enumerate() {+ *f = gc[x * h + y];+ }+ dt1(&t.f[..w], &mut t.o[..w], &mut t.v, &mut t.z, &mut t.near[..w]);+ for (x, (d, ne)) in out.iter_mut().zip(near.iter_mut()).enumerate() {+ *d = t.o[x].sqrt();+ let px = t.near[x];+ *ne = (nc[px * h + y] as usize * w + px) as u32;+ }+ },+ );(g, nearest)}@@ -274,9 +402,23 @@ fn dist_outside_by(s: &Map, m: Metric) -> Vec<f32> {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 inside = covered(s, |a| a > INSIDE_EPS);let (d, near) = edt_nearest(&inside, s.w, s.h);- (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()+ par_fill(s.w, s.h, 0.0f32, |y, row| {+ for (x, out) in row.iter_mut().enumerate() {+ let i = y * s.w + x;+ *out = if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i] as usize].min(1.0)) };+ }+ })+}++/// Which pixels of `s` satisfy `test`, row by row in parallel.+fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec<bool> {+ par_fill(s.w, s.h, false, |y, row| {+ for (e, &a) in row.iter_mut().zip(s.v.get(y * s.w..).unwrap_or_default()) {+ *e = test(a);+ }+ })}/// Distance from each pixel centre inside the shape to the shape's edge@@ -306,9 +448,14 @@ fn dist_inside_by(s: &Map, m: Metric) -> Vec<f32> {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 outside = covered(s, |a| a <= INSIDE_EPS);let (d, _) = edt_nearest(&outside, s.w, s.h);- d.iter().zip(&outside).map(|(d, o)| if *o { -0.5 } else { d - 0.5 }).collect()+ par_fill(s.w, s.h, 0.0f32, |y, row| {+ for (x, out) in row.iter_mut().enumerate() {+ let i = y * s.w + x;+ *out = if outside[i] { -0.5 } else { d[i] - 0.5 };+ }+ })}/// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage@@ -441,9 +588,9 @@ impl SharpEdges {/// the coverage gradient gives). Sharp pixels are partly covered and touch both an empty and a full/// pixel; hard edges and soft ramps have none and keep the `alpha - 1/2` of [`dist_outside`].///-/// An edge pixel is covered and has an empty neighbour, so a row by row pass over which pixels are-/// covered finds the few candidates without computing [`local_coverage`] of the whole map; the-/// coverage is then worked out where it is needed, by the same formula.+/// An edge pixel is covered and has an empty neighbour, so a pass over which pixels are covered finds+/// the few candidates without computing [`local_coverage`] of the whole map; the coverage is then+/// worked out where it is needed, by the same formula. Rows are independent and go in parallel.fn sharp_edges(s: &Map) -> SharpEdges {let (w, h) = (s.w, s.h);if w == 0 || h == 0 || s.v.len() != w * h || s.v.len() >= u32::MAX as usize {@@ -466,56 +613,64 @@ fn sharp_edges(s: &Map) -> SharpEdges {};// The coverage with the map's border repeated, for the gradient.let cov_clamped = |x: i64, y: i64| cov_at(x.max(0).min(wi - 1), y.max(0).min(hi - 1));- // Rows of "not empty" with a covered margin of one pixel on each side (off the map counts as covered:- // only a neighbour on the map can be empty).- let solid_row = |y: i64| -> Vec<bool> {- let mut row = vec![true; w + 2];- if (0..hi).contains(&y) {- for (x, &a) in s.v[y as usize * w..(y as usize + 1) * w].iter().enumerate() {- row[x + 1] = a.is_nan() || a > INSIDE_EPS;- }+ // Whether a pixel is not empty. Off the map counts as covered: only a neighbour on the map can be empty.+ let solid = |x: i64, y: i64| -> bool {+ if x < 0 || y < 0 || x >= wi || y >= hi {+ return true;}- row+ let a = s.v[y as usize * w + x as usize];+ a.is_nan() || a > INSIDE_EPS};- let mut slot = vec![0u32; w * h];- let mut pixels: Vec<EdgePixel> = Vec::new();- let (mut above, mut here, mut below) = (solid_row(-1), solid_row(0), solid_row(1));- let mut candidate = vec![false; w];- for y in 0..hi {- for x in 0..w {- candidate[x] = here[x + 1] && !(above[x] & above[x + 1] & above[x + 2] & here[x] & here[x + 2] & below[x] & below[x + 1] & below[x + 2]);- }- for x in 0..wi {- if !candidate[x as usize] {- continue;- }- let i = (y * wi + x) as usize;- let c = cov_at(x, y);- if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS {- continue;- }- let (mut empty, mut full) = (false, false);- for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) {- let (nx, ny) = (x + dx, y + dy);- if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi {+ let mut rows: Vec<Vec<EdgePixel>> = vec![Vec::new(); h];+ par_units(+ w * h,+ &mut rows,+ 1,+ &mut [] as &mut [()],+ 0,+ || (),+ |_, y, row, _| {+ let Some(row) = row.first_mut() else { return };+ let y = y as i64;+ for x in 0..wi {+ if !solid(x, y) || (-1..=1).all(|dy| (-1..=1).all(|dx| solid(x + dx, y + dy))) {continue;}- empty |= s.get(nx, ny) <= INSIDE_EPS;- full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS;- }- if !(empty && full) {- continue;+ let i = (y * wi + x) as usize;+ let c = cov_at(x, y);+ if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS {+ continue;+ }+ let (mut empty, mut full) = (false, false);+ for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) {+ let (nx, ny) = (x + dx, y + dy);+ if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi {+ continue;+ }+ empty |= s.get(nx, ny) <= INSIDE_EPS;+ full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS;+ }+ if !(empty && full) {+ continue;+ }+ let at = &cov_clamped;+ let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1));+ let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1));+ let len = gx.hypot(gy);+ let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) };+ row.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } });}- let at = &cov_clamped;- let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1));- let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1));- let len = gx.hypot(gy);- let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) };- pixels.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } });- slot[i] = pixels.len() as u32;+ },+ );+ let mut pixels: Vec<EdgePixel> = Vec::with_capacity(rows.iter().map(Vec::len).sum());+ for row in rows {+ pixels.extend(row);+ }+ let mut slot = vec![0u32; w * h];+ for (k, p) in pixels.iter().enumerate() {+ if let Some(s) = slot.get_mut(p.at as usize) {+ *s = k as u32 + 1;}- above = std::mem::replace(&mut here, std::mem::take(&mut below));- below = solid_row(y + 2);}refine_edge_normals(&mut pixels, &slot, w, h);SharpEdges { w, h, slot, pixels }@@ -537,9 +692,10 @@ fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usiz.map(|p| [(p.at as i64 % wi) as f32 - p.edge.offset * p.edge.normal[0], (p.at as i64 / wi) as f32 - p.edge.offset * p.edge.normal[1]]).collect();let before: Vec<SharpEdge> = pixels.iter().map(|p| p.edge).collect();- let mut near: Vec<[f32; 2]> = Vec::new();- for (k, pixel) in pixels.iter_mut().enumerate() {- let e = before[k];+ // Every pixel reads the unrefined edges around it and writes its own, so they go in parallel.+ let work = pixels.len().saturating_mul(32);+ par_units(work, pixels, 1, &mut [] as &mut [()], 0, Vec::<[f32; 2]>::new, |near, k, pixel, _| {+ let (Some(pixel), Some(&e)) = (pixel.first_mut(), before.get(k)) else { return };let (x, y) = (pixel.at as i64 % wi, pixel.at as i64 / wi);let (mut n, mut sum) = (0.0f32, [0.0f32; 2]);near.clear();@@ -557,11 +713,11 @@ fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usiz}}if near.len() < 3 {- continue;+ return;}let mean = [sum[0] / n, sum[1] / n];let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0f32, 0.0f32);- for p in &near {+ for p in near.iter() {let (dx, dy) = (p[0] - mean[0], p[1] - mean[1]);sxx += dx * dx;sxy += dx * dy;@@ -572,7 +728,7 @@ fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usizlet root = (0.25 * (sxx - syy) * (sxx - syy) + sxy * sxy).sqrt();let (along, across) = (((half + root) / n).max(0.0).sqrt(), ((half - root) / n).max(0.0).sqrt());if !(along > EDGE_LINE_MIN_SPREAD && across < EDGE_LINE_MAX_OFF) {- continue;+ return;}let angle = 0.5 * (2.0 * sxy).atan2(sxx - syy);let mut normal = [-angle.sin(), angle.cos()];@@ -581,7 +737,7 @@ fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usiz}pixel.edge.normal = normal;pixel.edge.offset = edge_offset(normal, pixel.cov);- }+ });}/// The edge points around a pixel must spread at least this far (px, standard deviation) along@@ -623,58 +779,66 @@ fn edge_distance(sharp: &SharpEdges, p: [usize; 2], q: [usize; 2], inside: bool)/// it caps the result where an edge lies exactly on a pixel boundary and has no sharp pixel; a mask/// without sharp pixels gives exactly [`dist_inside`]. Values past `reach` pixels are not refined.fn bevel_dist_inside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec<f32> {- let empty: Vec<bool> = s.v.iter().map(|&a| a <= INSIDE_EPS).collect();+ let empty = covered(s, |a| a <= INSIDE_EPS);let (d, near) = edt_nearest(&empty, s.w, s.h);- (0..d.len())- .map(|i| {- if empty[i] {- return -0.5;- }- if let Some(e) = sharp.get(i) {- return e.offset;- }- let plain = d[i] - 0.5;- if d[i] > reach + EDGE_MARGIN || sharp.is_empty() {- return plain;- }- // The sharp pixel next to the nearest empty one that is nearest to this pixel.- let (px, py) = ((i % s.w) as i64, (i / s.w) as i64);- let (ox, oy) = ((near[i] % s.w) as i64, (near[i] / s.w) as i64);- let q = (-1..=1)- .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy)))- .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize))- .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py));- match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) {- Some(refined) => refined.min(plain),- None => plain,- }- })- .collect()+ let at = |x: usize, y: usize| -> f32 {+ let i = y * s.w + x;+ if empty[i] {+ return -0.5;+ }+ if let Some(e) = sharp.get(i) {+ return e.offset;+ }+ let plain = d[i] - 0.5;+ if d[i] > reach + EDGE_MARGIN || sharp.is_empty() {+ return plain;+ }+ // The sharp pixel next to the nearest empty one that is nearest to this pixel.+ let (px, py) = (x as i64, y as i64);+ let (ox, oy) = ((near[i] as usize % s.w) as i64, (near[i] as usize / s.w) as i64);+ let q = (-1..=1)+ .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy)))+ .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize))+ .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py));+ match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) {+ Some(refined) => refined.min(plain),+ None => plain,+ }+ };+ par_fill(s.w, s.h, 0.0f32, |y, row| {+ for (x, out) in row.iter_mut().enumerate() {+ *out = at(x, y);+ }+ })}/// [`dist_outside`] for chiselled bevels, with sharp edge pixels placed as in [`bevel_dist_inside`].fn bevel_dist_outside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec<f32> {- let inside: Vec<bool> = s.v.iter().map(|&a| a > INSIDE_EPS).collect();+ let inside = covered(s, |a| a > INSIDE_EPS);let (d, near) = edt_nearest(&inside, s.w, s.h);- (0..d.len())- .map(|i| {- if let Some(e) = sharp.get(i) {- return -e.offset;- }- if inside[i] {- return -0.5;- }- let q = near[i];- let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) };- let (p, qp) = ([i % s.w, i / s.w], [q % s.w, q / s.w]);- let measured = if d[i] <= reach + EDGE_MARGIN {- edge_distance(sharp, p, qp, false)- } else {- e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false)- };- measured.unwrap_or(d[i] - e.offset)- })- .collect()+ let at = |x: usize, y: usize| -> f32 {+ let i = y * s.w + x;+ if let Some(e) = sharp.get(i) {+ return -e.offset;+ }+ if inside[i] {+ return -0.5;+ }+ let q = near[i] as usize;+ let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) };+ let (p, qp) = ([x, y], [q % s.w, q / s.w]);+ let measured = if d[i] <= reach + EDGE_MARGIN {+ edge_distance(sharp, p, qp, false)+ } else {+ e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false)+ };+ measured.unwrap_or(d[i] - e.offset)+ };+ par_fill(s.w, s.h, 0.0f32, |y, row| {+ for (x, out) in row.iter_mut().enumerate() {+ *out = at(x, y);+ }+ })}/// Pixels past the reach that are still refined, so the value is right where the ramp ends.@@ -1968,6 +2132,22 @@ pub fn distance_field(kind: FieldKind, alpha: Vec<f32>, w: usize, h: usize, reacmod tests {use super::*;+ /// Runs `f` with every parallel pass on this thread using `n` threads (1 = in order), whatever its size.+ fn with_threads<R>(n: usize, f: impl FnOnce() -> R) -> R {+ struct Restore(Option<usize>);+ impl Drop for Restore {+ fn drop(&mut self) {+ THREADS.with(|t| t.set(self.0));+ }+ }+ let _restore = Restore(THREADS.with(|t| t.replace(Some(n))));+ f()+ }++ fn bits(v: &[f32]) -> Vec<u32> {+ v.iter().map(|x| x.to_bits()).collect()+ }+#[test]fn edt_is_exact() {let (w, h) = (7, 5);@@ -2443,6 +2623,126 @@ mod tests {let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0));}+ #[test]+ fn par_units_visits_every_unit_once_with_its_own_slices() {+ // Lengths that leave a short last unit, no second slice, units of different sizes, and nothing at all.+ let cases: [(usize, usize, usize, usize); 8] =+ [(0, 3, 0, 0), (1, 1, 1, 1), (10, 3, 0, 0), (64, 8, 64, 8), (65, 8, 13, 1), (200, 1, 200, 1), (7, 7, 14, 2), (9, 4, 0, 5)];+ for (la, ua, lb, ub) in cases {+ for threads in [1, 2, 3, 8, 64] {+ let (mut a, mut b) = (vec![0u32; la], vec![0u32; lb]);+ let calls = std::sync::atomic::AtomicUsize::new(0);+ with_threads(threads, || {+ par_units(+ la,+ &mut a,+ ua,+ &mut b,+ ub,+ || (),+ |_, u, sa, sb| {+ calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ assert!(sa.len() <= ua && sb.len() <= ub);+ for (k, v) in sa.iter_mut().enumerate() {+ *v = (u * ua + k) as u32 + 1;+ }+ for (k, v) in sb.iter_mut().enumerate() {+ *v = (u * ub + k) as u32 + 1;+ }+ },+ );+ });+ assert_eq!(calls.into_inner(), la.div_ceil(ua), "{la} {ua} {lb} {ub} on {threads}");+ assert!(a.iter().enumerate().all(|(i, &v)| v == i as u32 + 1), "a: {la} {ua} {lb} {ub} on {threads}");+ // `b` is written for the units that exist in `a` and no further.+ let written = (la.div_ceil(ua) * ub).min(lb);+ assert!(b.iter().enumerate().all(|(i, &v)| v == if i < written { i as u32 + 1 } else { 0 }), "b: {la} {ua} {lb} {ub} on {threads}");+ }+ }+ // A unit size of 0 does nothing.+ let mut a = vec![1u8; 4];+ par_units(4, &mut a, 0, &mut [] as &mut [()], 0, || (), |_, _, _, _| panic!("no units"));+ }++ #[test]+ fn nearest_distances_do_not_depend_on_the_threads() {+ // Sizes that do not divide into the thread groups, lines of 1 pixel, and a noisy map where+ // many pixels are equally far from two seeds (the nearest one must resolve the same way).+ for (w, h) in [(37usize, 23usize), (1, 40), (40, 1), (2, 2), (101, 3), (64, 64)] {+ let mut seed = 7u32;+ let inside: Vec<bool> = (0..w * h)+ .map(|_| {+ seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);+ (seed >> 24).is_multiple_of(11)+ })+ .collect();+ let (d1, n1) = with_threads(1, || edt_nearest(&inside, w, h));+ for threads in [2, 3, 8] {+ let (d, n) = with_threads(threads, || edt_nearest(&inside, w, h));+ assert_eq!((bits(&d), n), (bits(&d1), n1.clone()), "{w}x{h} on {threads} threads");+ }+ // And the nearest pixel is a seed at exactly that distance.+ for (i, (&d, &q)) in d1.iter().zip(&n1).enumerate() {+ if inside.iter().any(|&b| b) {+ let (dx, dy) = ((i % w) as f32 - (q as usize % w) as f32, (i / w) as f32 - (q as usize / w) as f32);+ assert!(inside[q as usize] && (dx.hypot(dy) - d).abs() < 1e-3, "{w}x{h} at {i}: {d} vs seed {q}");+ }+ }+ }+ }++ #[test]+ fn nearest_distances_survive_degenerate_sizes() {+ // The slice does not match the size, or there is nothing: no panic, and a result per input pixel.+ for (len, w, h) in [(0usize, 0usize, 0usize), (0, 5, 0), (0, 0, 5), (6, 2, 2), (6, 4, 2), (1, 0, 1)] {+ let (d, n) = edt_nearest(&vec![true; len], w, h);+ assert_eq!((d.len(), n.len()), (len, len), "{len} px as {w}x{h}");+ }+ }++ #[test]+ fn chisel_fields_do_not_depend_on_the_threads() {+ // Edge pixels at every angle, curves, patchy opacity and an edge along the border, on sizes that+ // leave short last groups; one thread (in order) is the reference.+ let mut maps = vec![+ aa_disc(97, 83, 30.0),+ aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0),+ aa_bar(120, 120, 33.0, 100.0, 30.0),+ aa_bar(90, 130, 60.0, 150.0, 25.0),+ ];+ let mut patchy = aa_disc(101, 101, 40.0);+ for (i, v) in patchy.v.iter_mut().enumerate() {+ if (i % 101 / 13 + i / 101 / 17) % 5 == 0 {+ *v *= 0.6;+ }+ }+ maps.push(patchy);+ maps.push(aa_bar(64, 64, 40.0, 220.0, 30.0));+ for (k, m) in maps.iter().enumerate() {+ for reach in [3.0f32, 12.0] {+ let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach)));+ for threads in [2, 5, 16] {+ let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach)));+ assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads");+ let edges = |s: &SharpEdges| {+ s.pixels.iter().map(|p| (p.at, p.cov.to_bits(), p.edge.offset.to_bits(), p.edge.normal.map(f32::to_bits))).collect::<Vec<_>>()+ };+ assert_eq!(edges(&one.0), edges(&many.0), "map {k} sharp edges on {threads} threads");+ for (a, b) in one.1.iter().zip(&many.1) {+ assert_eq!(bits(a), bits(b), "map {k}, reach {reach} on {threads} threads");+ }+ }+ }+ }+ }++ /// The four fields that use the distance transform, of `m`.+ fn distance_field_of(m: &Map, reach: f32) -> Vec<Vec<f32>> {+ [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside]+ .map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach))+ .to_vec()+ }+fn aa_disc(w: usize, h: usize, r: f32) -> Map {let mut m = Map::new(w, h, 0.0);const N: usize = 16;diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 245648da1..3aace8056 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -1720,7 +1720,7 @@ fn large_documents_thumbnail_from_a_proxy() {/// parallel), each carrying a different effect.#[cfg(not(target_arch = "wasm32"))]fn nested_parallel_fx_doc() -> Document {- use photocraft_doc::{Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, StrokeFx, StrokePosition};+ use photocraft_doc::{Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, StrokeFx, StrokePosition};let mut d = doc_white(512, 512);let g = |a: f32| Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::rgb(0.2, 0.5, 0.9))], a, 1.0, photocraft_doc::GradientStyle::Linear, false);let mut shadow = Layer::new("shadow", LayerContent::Fill(g(0.0)));@@ -1748,11 +1748,32 @@ fn nested_parallel_fx_doc() -> Document {noise: 0.0,source: GlowSource::Edge,})];+ // A chiselled bevel: its distance transforms run on threads of their own, inside the tile that builds them.+ let mut chisel = solid_layer("chisel", Rect::new(60, 60, 450, 450), [0.8, 0.6, 0.2, 1.0]);+ chisel.effects.items = vec![Effect::BevelEmboss(Bevel {+ enabled: true,+ style: BevelStyle::InnerBevel,+ technique: BevelTechnique::ChiselHard,+ depth: 1.5,+ up: true,+ size: 9.0,+ soften: 0.0,+ angle: 120.0,+ altitude: 32.0,+ use_global_light: false,+ gloss_contour: Contour::Linear,+ highlight: FxCommon::new(BlendMode::Screen, 0.75),+ highlight_color: Color::WHITE,+ shadow: FxCommon::new(BlendMode::Multiply, 0.75),+ shadow_color: Color::BLACK,+ contour: None,+ texture: None,+ })];// Unaffected layers whose rows also render in parallel keep both workers stealing.let base = Layer::new("base", LayerContent::Fill(g(30.0)));let mut top = Layer::new("top", LayerContent::Fill(g(60.0)));top.opacity = 0.3;- d.layers.extend([base, shadow, stroke, glow, top]);+ d.layers.extend([base, shadow, stroke, glow, chisel, top]);d}diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rsindex 60abd264b..a74ff10a4 100644--- a/crates/gpu/src/fx.rs+++ b/crates/gpu/src/fx.rs@@ -7,14 +7,16 @@//!//! 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+//! use (`compose::effects::distance_field`). 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;+//! the reach again; large windows split into bands computed in parallel, except the Euclidean+//! fields (glows, chiselled bevels), which are one window that `distance_field` computes on all+//! threads itself;//! - 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.@@ -494,13 +496,35 @@ 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.+/// [`field_radius`], so a part is computed from a window grown by it.pub(crate) fn field(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect) -> Vec<f32> {field_banded(kind, reach, shape, region, out, field_radius(kind, reach) + 1)}-/// [`field`] with the band halo given (the tests shrink it to see that they notice).+/// Whether `distance_field` spreads `kind` over threads itself, line by line: the exact Euclidean+/// fields of precise glows and chiselled bevels. Those are computed from one window; for the others+/// (the chamfer fields, a sequential sweep) the window is cut into bands that go in parallel. Without+/// threads (wasm) there is nothing to spread over, and bands keep the memory small.+fn threaded_inside(kind: FieldKind) -> bool {+ !cfg!(target_arch = "wasm32") && matches!(kind, FieldKind::Outside | FieldKind::Inside | FieldKind::BevelOutside | FieldKind::BevelInside)+}++/// [`field`] with the halo given (the tests shrink it to see that they notice).+///+/// A band needs a halo of `reach + 9` rows for the bevel fields, so at a large size most of what a band+/// computes is its halo (three times the region at size 250), the bands only keep as many threads busy+/// as there are bands, and threads inside a band would pile onto those of the other bands. The Euclidean+/// fields run on all threads inside `distance_field`, from one window. That is also the window the CPU+/// compositor computes them from, so a rebuilt field is exactly the one it gives.fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect, halo: i32) -> Vec<f32> {+ if threaded_inside(kind) {+ let win = out.inflate(halo).intersect(®ion);+ if win.is_empty() {+ return Vec::new();+ }+ let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);+ return if win == out { f } else { crop(&f, win, out) };+ }let parts = par_map(bands(out, BAND.max(halo)), |band| {let win = band.inflate(halo).intersect(®ion);let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);@@ -730,11 +754,12 @@ mod tests {}}#[test]- fn banded_bevel_fields_match_whole_region_on_anti_aliased_edges() {+ fn windowed_bevel_fields_match_whole_region_on_anti_aliased_edges() {// The bevel fields read the edge pixels around the foot of the perpendicular and take the- // direction of each from its neighbours, so the band halo has to cover all of that. A wide- // bar with clean anti-aliased edges (almost along the 128 row bands, across them and at an- // angle) puts sharp edge pixels where the bands meet and inside the partial window.+ // direction of each from its neighbours, so the halo of a part of the region has to cover all of+ // that. A wide bar with clean anti-aliased edges (almost along the 128 row bands the other+ // fields use, across them and at an angle) puts sharp edge pixels where bands would meet and+ // inside the partial window. The whole region is one window, so it is exactly the CPU's field.let region = Rect::new(-20, -10, 300, 290);let (w, h) = (region.width() as usize, region.height() as usize);let part = Rect::new(40, 30, 170, 120);@@ -755,9 +780,9 @@ mod tests {for reach in [9, 24] {for kind in [FieldKind::BevelInside, FieldKind::BevelOutside] {let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32);- let differs = |banded: &[f32], out: Rect| {+ let differs = |part_field: &[f32], out: Rect| {let ow = out.width() as usize;- banded+ part_field.iter().enumerate().filter(|&(i, b)| {@@ -767,18 +792,18 @@ mod tests {}).count()};- assert_eq!(- differs(&field(kind, reach, &shape, region, region), region),- 0,- "{kind:?}, {deg} deg, reach {reach}: banded differs from whole"+ let all = field(kind, reach, &shape, region, region);+ assert!(+ all.iter().zip(&whole).all(|(a, b)| a.to_bits() == b.to_bits()),+ "{kind:?}, {deg} deg, reach {reach}: the whole region is not the CPU's field");assert_eq!(differs(&field(kind, reach, &shape, region, part), part),0,"{kind:?}, {deg} deg, reach {reach}: partial window differs from whole");- // The test can see a halo that is too small: two rows past the band is not enough.- too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, region, 2), region) > 0;+ // The test can see a halo that is too small: two rows past the part is not enough.+ too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, part, 2), part) > 0;}}}diff --git a/docs/development.md b/docs/development.mdindex 4b0f09114..85d8f8739 100644--- a/docs/development.md+++ b/docs/development.md@@ -259,7 +259,7 @@ translations do not affect the denominator. Unregistered locale TSV files are ig- The canvas is presented by a custom WGSL shader (`ui-egui/src/gpu_canvas.rs`): mip-mapped/nearest sampling, procedural checkerboard, pixel grid, tiling. Brush strokes upload only their damage rect.- **The canvas composites on the GPU** (`photocraft-gpu`, driven from `gpu_canvas.rs`), layer effects included. What the planner can't express returns `Unsupported` and the canvas falls back to the CPU compositor (`photocraft-compose`, also the reference for export and tests): Multichannel documents, and documents or effect regions over the texture limit. Pieces the GPU can't derive itself are rasterised once on the CPU and cached (`compose::masks` for vector masks, `compose::shape_split` for stroked shapes with clipped layers, effect distance fields). Timings of the interactive paths: `cargo run --release -p photocraft-ui-egui --example interactive_bench`; effects: `--example fx_bench` (`--compare files…` for GPU vs CPU); the cost of changing a chisel bevel's size (a dragged slider, GPU and CPU, ellipse and text): `--example bevel_bench`; large documents (open, refresh, thumbnails, a filter, a stroke, saves; one operation per run so `/usr/bin/time -l` gives its peak memory): `--example large_image_bench -- --size 14000x14000 --op psd`. The app requests the adapter's own texture limit (egui's default is 8192 px; see `gpu_canvas::use_adapter_limits`); beyond it the CPU fallback composites and uploads in bands (`compose::render_bands`), and exports, thumbnails and flattening stream bands too, so no full-size float composite is ever held. Rendering fidelity: `cargo run --release -p photocraft-io --example oracle_diff -- corpus/psd` (the whole PSD oracle table in seconds). `ui.inspect` → `perf.timings.gpuFallback` names the reason (`null` on the GPU path).-- **Layer effects on the GPU** (`gpu/src/fx.rs`, kernels in `gpu/src/compose.wgsl`). Every enabled effect becomes a *map program* over the layer's effect region (shift, dilate, Gaussian blur, glow ramp, bevel height and shading, contour, stroke band), mirroring `compose::effects` step by step; the chunked composite then paints through the maps, clipped to that region, and copies the result back into the backdrop in place, so a small text layer costs only its own pixels. The layer's shape (`compose::layer_shape`) and its distance fields (`compose::effects::distance_field`: a sequential transform whose tie-breaking a parallel GPU pass can't reproduce bit for bit) come from compose on the CPU, computed in parallel bands. Everything is cached per layer state: an unrelated edit, or an effect's colour or opacity, rebuilds nothing; a brush dab recomputes the touched 256² tiles grown by the effect reach; changing one effect's geometry rebuilds that effect only. Cache budget `gpu::FX_BUDGET` (1.5 GB, least recently drawn layers evicted first). `PHOTOCRAFT_FX_TRACE=1` prints the CPU time of each rebuild.+- **Layer effects on the GPU** (`gpu/src/fx.rs`, kernels in `gpu/src/compose.wgsl`). Every enabled effect becomes a *map program* over the layer's effect region (shift, dilate, Gaussian blur, glow ramp, bevel height and shading, contour, stroke band), mirroring `compose::effects` step by step; the chunked composite then paints through the maps, clipped to that region, and copies the result back into the backdrop in place, so a small text layer costs only its own pixels. The layer's shape (`compose::layer_shape`) and its distance fields (`compose::effects::distance_field`: a transform whose tie-breaking a parallel GPU pass can't reproduce bit for bit) come from compose on the CPU: bands computed in parallel, except the Euclidean fields of precise glows and chiselled bevels (a halo as tall as the bevel size would make most of a band's work redundant), which are one window whose passes run on all threads, the CPU compositor's own way. Everything is cached per layer state: an unrelated edit, or an effect's colour or opacity, rebuilds nothing; a brush dab recomputes the touched 256² tiles grown by the effect reach; changing one effect's geometry rebuilds that effect only. Cache budget `gpu::FX_BUDGET` (1.5 GB, least recently drawn layers evicted first). `PHOTOCRAFT_FX_TRACE=1` prints the CPU time of each rebuild.- The canvas grows a stroke's damage rect by the effect reach of the layers around it (`canvas::effect_reach`), so effects beyond the dab refresh too (on both paths).- **Numbers** (7360 × 4912, 8 text layers + one painted layer with drop shadow + stroke + bevel, Hue/Saturation on top; M4 Pro; `cargo run --release -p photocraft-ui-egui --example fx_bench`), CPU fallback → GPU: full refresh with warm effect maps 5.7 s → 47 ms; Hue/Saturation tweak above the effects 4.7 s → 31 ms; brush dab on a plain layer 32 → 1.7 ms; brush dab on the effect layer (its maps rebuilt around the dab) 659 → 3.7 ms; first refresh (all maps built) 6.4 s → 0.39 s. With the CPU ~14× oversubscribed by parallel builds (min of 7 runs): 8.1 s → 0.33 s, 9.9 s → 0.28 s, 28 → 2.2 ms, 1.7 s → 89 ms; moving a text layer 7 px 336 → 13 ms. `fx_bench --compare corpus/psd/…/*.psd` reports the GPU vs CPU difference on real files (30 of the 31 corpus files with effects render on the GPU, worst 0.12/255).- On the CPU path `compose::effect_maps` caches shadow, glow, bevel and satin maps per layer state (LRU, 768 MB budget).