From 4244ec2b9ee743378db63a5b2688e2b57acaf4ff Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 18:33:35 +0530 Subject: [PATCH 01/12] perf: crop selection morphology and bound small-radius distances --- .github/workflows/ci.yml | 30 +++ .../examples/bench_selection_morphology.rs | 64 +++++++ crates/algo/src/selection.rs | 21 +-- crates/algo/src/selection/distance.rs | 58 +++++- crates/algo/src/selection/morphology.rs | 98 ++++++++++ crates/algo/src/selection/morphology/tests.rs | 177 ++++++++++++++++++ docs/gaps.md | 9 +- docs/selection-distance-performance.md | 60 ++++++ docs/target-app-parity.md | 9 +- 9 files changed, 509 insertions(+), 17 deletions(-) create mode 100644 crates/algo/examples/bench_selection_morphology.rs create mode 100644 crates/algo/src/selection/morphology.rs create mode 100644 crates/algo/src/selection/morphology/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cea1326c0c..0ff80a8468 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,10 @@ on: types: [opened, synchronize, reopened, labeled] workflow_dispatch: inputs: + selection_morphology: + description: "Compare selection morphology on 36 MP (Linux, exact outputs)" + type: boolean + default: false fuzz: description: "Run the fuzz job" type: boolean @@ -415,3 +419,29 @@ jobs: with: name: fuzz-${{ matrix.target.crate }}-${{ matrix.target.name }} path: crates/${{ matrix.target.crate }}/fuzz/artifacts + + selection-morphology: + if: inputs.selection_morphology == true + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + RAYON_NUM_THREADS: "4" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: selection-morphology-perf + - name: Compare exact outputs and release timings on 36 MP + run: | + set -o pipefail + cargo run --release -p photocraft-algo --example bench_selection_morphology | tee selection-morphology-perf.txt + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: selection-morphology-performance + path: selection-morphology-perf.txt + - name: Quick performance suite + run: cargo xtask perf --quick diff --git a/crates/algo/examples/bench_selection_morphology.rs b/crates/algo/examples/bench_selection_morphology.rs new file mode 100644 index 0000000000..076f3ef544 --- /dev/null +++ b/crates/algo/examples/bench_selection_morphology.rs @@ -0,0 +1,64 @@ +//! Compare the former full-canvas formulas with cropped morphology on 36 MP. +//! Run in release on CI; includes output allocation and checks exact equality. +use photocraft_algo::selection::{border, contract, edt, expand}; +use std::{hint::black_box, time::Instant}; + +type Op = fn(&[f32], usize, usize, f32) -> Vec; + +fn old_expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let seeds: Vec = m.iter().map(|v| *v >= 0.5).collect(); + m.iter().zip(edt(&seeds, w, h)).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect() +} +fn old_contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); + old_expand(&inv, w, h, r).iter().map(|v| 1.0 - v).collect() +} +fn old_border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); + let outside: Vec = inside.iter().map(|v| !v).collect(); + let (di, dout) = (edt(&inside, w, h), edt(&outside, w, h)); + inside.iter().zip(di.iter().zip(&dout)).map(|(s, (a, b))| (1.0 - ((if *s { b } else { a }) - 1.0) / r).clamp(0.0, 1.0)).collect() +} +fn main() -> Result<(), Box> { + let (w, h) = (6000, 6000); + println!("36 MP; median of three runs including allocation; RAYON_NUM_THREADS={}", std::env::var("RAYON_NUM_THREADS").unwrap_or_default()); + for (case, size) in [("sparse", 50), ("dense", 4000)] { + let mut m = vec![0.0; w * h]; + let start = (w - size) / 2; + for row in m.chunks_exact_mut(w).skip(start).take(size) { + if let Some(span) = row.get_mut(start..start + size) { + span.fill(1.0) + } + } + for r in [3.0, 50.0] { + for (name, old, new) in + [("expand", old_expand as Op, expand as Op), ("contract", old_contract as Op, contract as Op), ("border", old_border as Op, border as Op)] + { + let mut timings = [0.0; 2]; + let expected = old(&m, w, h, r); + if new(&m, w, h, r) != expected { + return Err(format!("output mismatch: {case} {name} {r}").into()); + } + drop(expected); + for (slot, op) in timings.iter_mut().zip([old, new]) { + let mut runs = [0.0; 3]; + for time in &mut runs { + let now = Instant::now(); + let result = black_box(op(black_box(&m), w, h, r)); + *time = now.elapsed().as_secs_f64() * 1000.0; + drop(result); + } + runs.sort_by(f64::total_cmp); + *slot = runs.get(1).copied().unwrap_or_default(); + } + println!( + "{case} {name} r={r}: old={:.2}ms new={:.2}ms speedup={:.2}x exact=true", + timings.first().copied().unwrap_or_default(), + timings.get(1).copied().unwrap_or_default(), + timings.first().copied().unwrap_or_default() / timings.get(1).copied().unwrap_or(1.0) + ); + } + } + } + Ok(()) +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 1e71a502c7..e714d2196a 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -763,6 +763,7 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec { mod distance; mod lasso; mod marquee; +mod morphology; pub use distance::edt; pub(crate) use lasso::clip_segment; @@ -770,18 +771,15 @@ pub use lasso::{MAX_PAINTED_TILES, polygon_edge_tiles, polygon_surface}; pub use marquee::{combine_sparse, combine_surfaces, ellipse_surface}; /// Grows the selection by `r` pixels. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); - let d = edt(&inside, w, h); - // A pixel whose centre is `d` away from the nearest selected centre is - // covered when d ≤ r (fractional radii give partial coverage). - m.iter().zip(d).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect() + morphology::modify(m, w, h, r, morphology::Kind::Expand) } /// Shrinks the selection by `r` pixels. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); - expand(&inv, w, h, r).into_iter().map(|v| 1.0 - v).collect() + morphology::modify(m, w, h, r, morphology::Kind::Contract) } /// Select › Modify › Border: a soft band `2r` wide centred on the selection edge, as in @@ -790,14 +788,9 @@ pub fn contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { /// either side (measured on Photoshop 27.11, Border 4: 63, 127, 191, 255 | 255, 191, 127, 63 /// across a straight edge, the same along the inside of a corner). It used to be a hard band /// `r` wide. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); - let outside: Vec = inside.iter().map(|v| !v).collect(); - let (to_inside, to_outside) = (edt(&inside, w, h), edt(&outside, w, h)); - if r <= 0.0 || to_inside.len() != m.len() || to_outside.len() != m.len() { - return vec![0.0; m.len()]; - } - inside.iter().zip(to_inside.iter().zip(&to_outside)).map(|(&sel, (&di, &dout))| (1.0 - ((if sel { dout } else { di }) - 1.0) / r).clamp(0.0, 1.0)).collect() + morphology::modify(m, w, h, r, morphology::Kind::Border) } /// Smooth: removes specks and rounds corners (box average of radius `round(r)`, edges diff --git a/crates/algo/src/selection/distance.rs b/crates/algo/src/selection/distance.rs index 2dad2d2cbb..53588904f0 100644 --- a/crates/algo/src/selection/distance.rs +++ b/crates/algo/src/selection/distance.rs @@ -3,9 +3,65 @@ const NO_SEED: u32 = u32::MAX; // Keep the public API's finite result for a mask with no selected pixel. -const EMPTY_DISTANCE: f32 = 1e10; +pub(super) const EMPTY_DISTANCE: f32 = 1e10; const BAND_ROWS: usize = 32; +/// Exact distances within `reach` (at most six pixels), EMPTY_DISTANCE beyond it. +/// Two contiguous vertical sweeps and a short horizontal stencil avoid envelopes, +/// transposes and task-local buffers. One byte per pixel stores capped vertical distances. +pub(super) fn edt_bounded(seeds: &[bool], w: usize, h: usize, reach: f32) -> Vec { + if w == 0 || h == 0 || w.checked_mul(h) != Some(seeds.len()) || !(0.0..=6.0).contains(&reach) { + return Vec::new(); + } + let radius = reach.ceil() as usize; + let cap = radius as u8 + 1; + let mut vertical: Vec = seeds.iter().map(|s| if *s { 0 } else { cap }).collect(); + for y in 1..h { + let (before, after) = vertical.split_at_mut(y * w); + if let (Some(prev), Some(row)) = (before.get((y - 1) * w..), after.get_mut(..w)) { + for (d, p) in row.iter_mut().zip(prev) { + *d = (*d).min(p.saturating_add(1)); + } + } + } + for y in (1..h).rev() { + let (before, after) = vertical.split_at_mut(y * w); + if let (Some(row), Some(next)) = (before.get_mut((y - 1) * w..), after.get(..w)) { + for (d, n) in row.iter_mut().zip(next) { + *d = (*d).min(n.saturating_add(1)); + } + } + } + let mut out = vec![EMPTY_DISTANCE; seeds.len()]; + for_chunks(&mut out, w, |y, dst| { + let Some(row) = vertical.get(y * w..(y + 1) * w) else { return }; + if row.iter().all(|d| *d == cap) { + return; + } + for (x, d) in dst.iter_mut().enumerate() { + if row.get(x) == Some(&0) { + *d = 0.0; + continue; + } + let left = x.saturating_sub(radius); + let right = x.saturating_add(radius).saturating_add(1).min(w); + let Some(span) = row.get(left..right) else { continue }; + let mut best = (radius + 1).pow(2); + for (i, &dy) in span.iter().enumerate() { + best = best.min((left + i).abs_diff(x).pow(2) + usize::from(dy).pow(2)); + if best == 1 { + break; + } + } + let distance = (best as f64).sqrt() as f32; + if distance <= reach { + *d = distance; + } + } + }); + out +} + /// Euclidean distance to the nearest `true` pixel, in row-major order. /// /// Empty or inconsistent dimensions return an empty buffer. A mask with no seeds returns diff --git a/crates/algo/src/selection/morphology.rs b/crates/algo/src/selection/morphology.rs new file mode 100644 index 0000000000..ac159c9e3c --- /dev/null +++ b/crates/algo/src/selection/morphology.rs @@ -0,0 +1,98 @@ +//! Radius-limited selection morphology. Only the nonzero bounds plus a halo need distances; +//! the flat public API still requires a canvas-sized output. Canvas edges are not implicit +//! seeds: the engine supplies padding when Apply effect at canvas bounds is requested. + +use super::distance::{EMPTY_DISTANCE, edt, edt_bounded}; + +#[derive(Clone, Copy)] +pub(super) enum Kind { + Expand, + Contract, + Border, +} + +#[derive(Debug, PartialEq)] +struct Window { + x0: usize, + x1: usize, + y0: usize, + y1: usize, +} + +fn window(m: &[f32], w: usize, h: usize, r: f32) -> Option { + let mut b = Window { x0: w, x1: 0, y0: h, y1: 0 }; + for (y, row) in m.chunks_exact(w).enumerate() { + if let Some(x) = row.iter().position(|v| *v != 0.0) { + b.x0 = b.x0.min(x); + b.y0 = b.y0.min(y); + b.y1 = y + 1; + b.x1 = b.x1.max(row.iter().rposition(|v| *v != 0.0).unwrap_or(x) + 1); + } + } + if b.x1 == 0 { + // Preserve the general EDT's finite no-seed sentinel even for library callers + // passing radii far beyond the command's 500 px limit. + return (r >= EMPTY_DISTANCE).then_some(Window { x0: 0, x1: w, y0: 0, y1: h }); + } + // Coverage reaches r + 1 centres; the extra pixel also supplies real outside seeds + // for erosion. Saturating arithmetic handles radii larger than the canvas. + let halo = (r.ceil() as usize).saturating_add(1); + Some(Window { x0: b.x0.saturating_sub(halo), x1: b.x1.saturating_add(halo).min(w), y0: b.y0.saturating_sub(halo), y1: b.y1.saturating_add(halo).min(h) }) +} + +pub(super) fn modify(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec { + if w == 0 || h == 0 || w.checked_mul(h) != Some(m.len()) || m.len() > isize::MAX as usize / 4 || !r.is_finite() || r < 0.0 { + return Vec::new(); + } + let mut out = match kind { + Kind::Expand => m.to_vec(), + // Retain the old complement's rounding for fractional input coverage. + Kind::Contract => m.iter().map(|v| 1.0 - (1.0 - v)).collect(), + Kind::Border => vec![0.0; m.len()], + }; + if matches!(kind, Kind::Border) && r == 0.0 { + return out; + } + let Some(b) = window(m, w, h, r) else { return out }; + let (cw, ch) = (b.x1 - b.x0, b.y1 - b.y0); + let mut seeds = Vec::with_capacity(cw * ch); + for row in m.chunks_exact(w).skip(b.y0).take(ch) { + if let Some(span) = row.get(b.x0..b.x1) { + seeds.extend(span.iter().map(|v| match kind { + // Do not replace this with v < 0.5: the old complement includes ties, + // including values that round to 0.5 after subtraction. + Kind::Contract => 1.0 - v >= 0.5, + _ => *v >= 0.5, + })); + } + } + let distance = |seeds: &[bool]| { + if r <= 5.0 { edt_bounded(seeds, cw, ch, r + 1.0) } else { edt(seeds, cw, ch) } + }; + let passes = if matches!(kind, Kind::Border) { 2 } else { 1 }; + for pass in 0..passes { + // Drop each distance plane before the next pass. Border never keeps two float + // distance planes or two seed masks alive together. + let d = distance(&seeds); + for (y, (src, dst)) in m.chunks_exact(w).zip(out.chunks_exact_mut(w)).skip(b.y0).take(ch).enumerate() { + let (Some(src), Some(dst), Some(dist)) = (src.get(b.x0..b.x1), dst.get_mut(b.x0..b.x1), d.get(y * cw..(y + 1) * cw)) else { continue }; + for ((v, out), d) in src.iter().zip(dst).zip(dist) { + *out = match kind { + Kind::Expand => v.max((r + 1.0 - d).clamp(0.0, 1.0)), + Kind::Contract => 1.0 - (1.0 - v).max((r + 1.0 - d).clamp(0.0, 1.0)), + Kind::Border if (*v >= 0.5) == (pass == 1) => (1.0 - (d - 1.0) / r).clamp(0.0, 1.0), + Kind::Border => *out, + }; + } + } + if pass + 1 < passes { + for seed in &mut seeds { + *seed = !*seed; + } + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/algo/src/selection/morphology/tests.rs b/crates/algo/src/selection/morphology/tests.rs new file mode 100644 index 0000000000..51db628476 --- /dev/null +++ b/crates/algo/src/selection/morphology/tests.rs @@ -0,0 +1,177 @@ +use super::*; +use crate::selection::{border, contract, expand}; + +fn oracle(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec { + let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); + match kind { + Kind::Expand => m.iter().zip(edt(&inside, w, h)).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect(), + Kind::Contract => { + let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); + oracle(&inv, w, h, r, Kind::Expand).iter().map(|v| 1.0 - v).collect() + } + Kind::Border => { + if r == 0.0 { + return vec![0.0; m.len()]; + } + let outside: Vec = inside.iter().map(|v| !v).collect(); + let di = edt(&inside, w, h); + let dout = edt(&outside, w, h); + inside.iter().zip(di.iter().zip(&dout)).map(|(sel, (di, dout))| (1.0 - ((if *sel { dout } else { di }) - 1.0) / r).clamp(0.0, 1.0)).collect() + } + } +} + +#[test] +fn matches_full_canvas_formulas() { + for (w, h) in [(1usize, 1usize), (1, 31), (37, 1), (39, 27)] { + for case in 0..9 { + let m: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + match case { + 0 => 0.0, + 1 => 1.0, + 2 => { + if x == w / 2 && y == h / 2 { + 1.0 + } else { + 0.0 + } + } + 3 => { + if x < w / 2 && y < h / 2 { + 1.0 + } else { + 0.0 + } + } + 4 => { + if x.abs_diff(w / 2) < 3 && y.abs_diff(h / 2) < 3 { + 1.0 + } else { + 0.0 + } + } + 5 => { + if x.abs_diff(w / 2) < 5 && y.abs_diff(h / 2) < 5 && (x.abs_diff(w / 2) > 2 || y.abs_diff(h / 2) > 2) { + 1.0 + } else { + 0.0 + } + } + 6 => [0.0, 0.1, 0.499_999_97, 0.5, 0.6, 1.0][(i * 31 + i / 7) % 6], + 7 => 0.25, + _ => { + if x == 0 || x + 1 == w || y == 0 || y + 1 == h { + 1.0 + } else { + 0.0 + } + } + } + }) + .collect(); + for r in [0.0, 0.25, 1.0, 1.5, 2.0, 4.25, 5.0, 5.01, 12.0, 100.0] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, w, h, r, kind), oracle(&m, w, h, r, kind), "{w}x{h} case {case} radius {r}"); + } + } + } + } +} + +#[test] +fn tiny_selection_uses_tiny_distance_window() { + let (w, h) = (1024, 768); + let mut m = vec![0.0; w * h]; + for y in 300..350 { + m[y * w + 400..y * w + 450].fill(1.0); + } + let b = window(&m, w, h, 5.0).unwrap(); + assert_eq!(b, Window { x0: 394, x1: 456, y0: 294, y1: 356 }); + assert_eq!((b.x1 - b.x0) * (b.y1 - b.y0), 62 * 62); +} + +#[test] +fn invalid_dimensions_and_radii_are_safe() { + for op in [expand, contract, border] { + for (w, h) in [(0, 1), (1, 0), (2, 2), (usize::MAX, 2)] { + assert!(op(&[1.0], w, h, 2.0).is_empty()); + } + for r in [f32::NAN, f32::INFINITY, -1.0] { + assert!(op(&[1.0], 1, 1, r).is_empty()); + } + } +} + +#[test] +fn bounded_distances_match_edt_within_reach() { + for (w, h) in [(1, 17), (23, 1), (31, 29)] { + for pattern in 0..4 { + let seeds: Vec = (0..w * h) + .map(|i| match pattern { + 0 => false, + 1 => true, + 2 => i == w * h / 2, + _ => (i * 73 + i / w * 11) % 19 == 0, + }) + .collect(); + let exact = edt(&seeds, w, h); + for reach in [1.0, 1.25, 2.0, 4.5, 6.0] { + let got = edt_bounded(&seeds, w, h, reach); + for (g, e) in got.iter().zip(&exact) { + if *e <= reach { assert_eq!(g, e) } else { assert!(*g > reach) } + } + } + } + } +} + +#[test] +fn every_three_by_three_mask_matches_with_a_cropped_halo() { + let (w, h) = (17, 19); + for bits in 0..512 { + let mut m = vec![0.0; w * h]; + for y in 0..3 { + for x in 0..3 { + if bits & (1 << (y * 3 + x)) != 0 { + m[(y + 7) * w + x + 6] = 1.0; + } + } + } + // Retain faint pixels beyond the binary selection's bounds too. + m[3 * w + 2] = 0.125; + for r in [0.0, 0.414_213_54, 0.414_213_66, 1.5, 3.0, 5.0, 5.5] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, w, h, r, kind), oracle(&m, w, h, r, kind), "mask {bits} radius {r}"); + } + } + } +} + +#[test] +fn enormous_finite_radii_keep_the_no_seed_sentinel_behavior() { + for m in [vec![0.0; 9], vec![1.0; 9], vec![0.25; 9]] { + for r in [1e10, 2e10, f32::MAX] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, 3, 3, r, kind), oracle(&m, 3, 3, r, kind)); + } + } + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn bounded_and_general_paths_are_worker_count_independent() { + let (w, h) = (400, 300); + let m: Vec = (0..w * h).map(|i| if (i * 73 + i / w * 11) % 19 == 0 { 1.0 } else { 0.0 }).collect(); + for r in [3.0, 9.0] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + let expected = oracle(&m, w, h, r, kind); + for workers in [1, 2, 4] { + let pool = rayon::ThreadPoolBuilder::new().num_threads(workers).build().unwrap(); + assert_eq!(pool.install(|| modify(&m, w, h, r, kind)), expected); + } + } + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 9168b453ba..43c245d9e7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -294,6 +294,12 @@ what an agent can't finish alone. - **Estimate:** 150–250 h. ### G2. Interactive performance +- **Measured progress (2026-10-26):** Expand, Contract and Border restrict distance work to + the nonzero bounds plus a radius halo. Small radii use capped distances; Contract avoids + inverted float masks and Border retains one distance plane. On 36 MP, twelve synthetic + comparisons measure 1.54–37.82× faster with exact output equality. Full-canvas mask + conversion and output remain; no GUI budget or readiness percentage changes. + [Method, measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). - **Measured progress (2026-10-10):** Tilt-Shift's existing per-level halo/copy optimization measures 1.07–1.49× faster across nine local 24 MP cases, with exact finite output bits. The filtered proxy improves for medium/large blur; its @@ -390,6 +396,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index f0db2a7093..d4a19dc719 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -73,3 +73,63 @@ EDT_WORKERS=1 cargo test --release -p photocraft-algo distance_transform_release The previous scalar implementation is retained only in the test module as the reference and benchmark baseline. + +## Cropped selection morphology (2026-10-26) + +Expand, Contract and Border now keep distance work inside the nonzero mask bounds, +expanded by `ceil(radius) + 1` and clipped to the supplied canvas. Nonzero bounds include +fractional coverage below the binary 0.5 threshold. Real pixels in the halo provide +outside seeds; cropping does not introduce an artificial selection edge. The engine's +existing canvas-bound padding remains responsible for Apply effect at canvas bounds. + +For radii up to 5 px, two vertical sweeps store capped distances in one byte per pixel. +A short horizontal stencil computes exact Euclidean distances only within `radius + 1`; +farther samples cannot contribute to the existing coverage formulas. Larger radii use +the general EDT above. Contract classifies complement seeds directly and writes the +complement coverage formula without allocating inverted float masks. Border runs its +two cropped transforms sequentially, reusing one seed mask and retaining one distance +plane at a time. + +A 50×50 selection at radius 5 needs a 62×62 distance window (3,844 samples), even on a +36 MP canvas. Seed, vertical and output-distance buffers total about 23 KB on the bounded +path, excluding allocator overhead. The flat API still scans its input for bounds and +returns a full-sized output (144 MB at 36 MP). Engine mask conversion, tiled writeback, +undo and compositing remain outside this optimization; this does not establish a GUI +latency budget or solve sparse document storage. + +Regression tests compare against the previous full-canvas formulas for empty/full masks, +one-row/column canvases, holes, edge-touching shapes, fractional radii, and fractional +coverage including complement rounding at 0.5. Every 3×3 binary mask is also checked +inside a larger canvas with a faint sample outside its binary bounds. The small-radius +distances are compared with the general EDT. Invalid dimensions and nonfinite/negative +radii return empty buffers. + +Reproduce on the fork through the CI workflow's optional `selection_morphology` input. +It runs `cargo run --release -p photocraft-algo --example bench_selection_morphology` +and `cargo xtask perf --quick` remotely. The comparison uses a 6000×6000 mask with either +a centred 50×50 square or a centred 4000×4000 square, radii 3 and 50, and four Rayon +workers. It checks every output sample against the previous formulas before timing; +reported medians include output allocation and exclude output destruction, with three +runs per implementation. These measurements are separate from the historical EDT-only +measurements above and do not change the scorecard baseline. + +Measurements from [scratch CI job 121583341033](https://github.com/wanikhawar/photocraft/actions/runs/40326176434/job/121583341033), +2026-10-26, commit `5afd231138368f9be856e8c21c2946f2e386797c`, GitHub-hosted Ubuntu 26.04, +stable Rust, normal release profile. The benchmark step completed successfully; the +superseded run was cancelled during the later quick performance build. The full validation +run is recorded in the PR. Times below are milliseconds; all twelve outputs match exactly. + +| Selection | Operation | Radius | Before p50 | After p50 | Speedup | +|---|---|---:|---:|---:|---:| +| 50×50 | Expand | 3 | 359.55 | 94.51 | 3.80× | +| 50×50 | Contract | 3 | 614.64 | 81.47 | 7.54× | +| 50×50 | Border | 3 | 738.30 | 19.52 | 37.82× | +| 50×50 | Expand | 50 | 357.84 | 99.76 | 3.59× | +| 50×50 | Contract | 50 | 601.19 | 81.19 | 7.41× | +| 50×50 | Border | 50 | 738.50 | 20.08 | 36.79× | +| 4000×4000 | Expand | 3 | 416.83 | 171.26 | 2.43× | +| 4000×4000 | Contract | 3 | 615.49 | 283.26 | 2.17× | +| 4000×4000 | Border | 3 | 802.48 | 377.78 | 2.12× | +| 4000×4000 | Expand | 50 | 414.50 | 268.96 | 1.54× | +| 4000×4000 | Contract | 50 | 610.98 | 260.77 | 2.34× | +| 4000×4000 | Border | 50 | 784.89 | 467.06 | 1.68× | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5c9fcd4b99..da3f528600 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; 12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -363,6 +363,12 @@ i7-9750H, 12 workers, 24 MP RGBA8, Good quality, amount 1: Spin 66.10 → 16.43 (4.02×), Zoom 19.19 → 5.35 s (3.59×), one paired run each, exact output equality. These are local measurements at amount 1; see [method and limits](radial-blur-performance.md). +2026-10-26: cropped Expand, Contract and Border measure 1.54–37.82× faster across twelve +36 MP synthetic mask cases on GitHub Actions, with exact output equality. Radii up to 5 px +use capped distances; Contract avoids inverted float masks and Border retains one distance +plane. Full-canvas mask conversion/output remain; no GUI budget or percentage changes. +See [measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). + 2026-10-10: native selection distance transforms measured 7.59–10.57x faster on six 24–36 MP synthetic masks on an AWS c7i.4xlarge (16 workers, three paired release runs). The transform also corrects f32 envelope errors past coordinate 4096, including nonzero @@ -574,6 +580,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | From d781e3ae0903fed9f492e6fe94ed38dac306ce20 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 18:34:50 +0530 Subject: [PATCH 02/12] ci: install native dependencies for the quick performance suite --- .github/workflows/ci.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ff80a8468..5e6f583a8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -430,6 +430,12 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + - name: Install Linux build dependencies + uses: storytold/craft-common-actions/actions/install-apt-packages@main + with: + packages: >- + libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev + libgtk-3-dev - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: From 977585aa249d9de33eae0b4d3d2ae3a523b52fd2 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 18:41:04 +0530 Subject: [PATCH 03/12] test: retain allocation reuse in the Contract performance baseline --- crates/algo/examples/bench_selection_morphology.rs | 2 +- docs/gaps.md | 4 ++-- docs/selection-distance-performance.md | 8 +++----- docs/target-app-parity.md | 4 ++-- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/crates/algo/examples/bench_selection_morphology.rs b/crates/algo/examples/bench_selection_morphology.rs index 076f3ef544..795ba74413 100644 --- a/crates/algo/examples/bench_selection_morphology.rs +++ b/crates/algo/examples/bench_selection_morphology.rs @@ -11,7 +11,7 @@ fn old_expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec { } fn old_contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); - old_expand(&inv, w, h, r).iter().map(|v| 1.0 - v).collect() + old_expand(&inv, w, h, r).into_iter().map(|v| 1.0 - v).collect() } fn old_border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); diff --git a/docs/gaps.md b/docs/gaps.md index 43c245d9e7..b8180b76c6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -296,7 +296,7 @@ what an agent can't finish alone. ### G2. Interactive performance - **Measured progress (2026-10-26):** Expand, Contract and Border restrict distance work to the nonzero bounds plus a radius halo. Small radii use capped distances; Contract avoids - inverted float masks and Border retains one distance plane. On 36 MP, twelve synthetic + inverted float masks and Border retains one distance plane. On 36 MP, eight synthetic comparisons measure 1.54–37.82× faster with exact output equality. Full-canvas mask conversion and output remain; no GUI budget or readiness percentage changes. [Method, measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). @@ -396,7 +396,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| -| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index d4a19dc719..bca853fafe 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -117,19 +117,17 @@ Measurements from [scratch CI job 121583341033](https://github.com/wanikhawar/ph 2026-10-26, commit `5afd231138368f9be856e8c21c2946f2e386797c`, GitHub-hosted Ubuntu 26.04, stable Rust, normal release profile. The benchmark step completed successfully; the superseded run was cancelled during the later quick performance build. The full validation -run is recorded in the PR. Times below are milliseconds; all twelve outputs match exactly. +run is recorded in the PR. Times below are milliseconds; this table reports Expand and Border (eight cases). +All twelve output comparisons, including Contract, matched exactly. The current benchmark +also times Contract using its original owning iterator so allocation reuse is preserved. | Selection | Operation | Radius | Before p50 | After p50 | Speedup | |---|---|---:|---:|---:|---:| | 50×50 | Expand | 3 | 359.55 | 94.51 | 3.80× | -| 50×50 | Contract | 3 | 614.64 | 81.47 | 7.54× | | 50×50 | Border | 3 | 738.30 | 19.52 | 37.82× | | 50×50 | Expand | 50 | 357.84 | 99.76 | 3.59× | -| 50×50 | Contract | 50 | 601.19 | 81.19 | 7.41× | | 50×50 | Border | 50 | 738.50 | 20.08 | 36.79× | | 4000×4000 | Expand | 3 | 416.83 | 171.26 | 2.43× | -| 4000×4000 | Contract | 3 | 615.49 | 283.26 | 2.17× | | 4000×4000 | Border | 3 | 802.48 | 377.78 | 2.12× | | 4000×4000 | Expand | 50 | 414.50 | 268.96 | 1.54× | -| 4000×4000 | Contract | 50 | 610.98 | 260.77 | 2.34× | | 4000×4000 | Border | 50 | 784.89 | 467.06 | 1.68× | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index da3f528600..5299f4612d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -363,7 +363,7 @@ i7-9750H, 12 workers, 24 MP RGBA8, Good quality, amount 1: Spin 66.10 → 16.43 (4.02×), Zoom 19.19 → 5.35 s (3.59×), one paired run each, exact output equality. These are local measurements at amount 1; see [method and limits](radial-blur-performance.md). -2026-10-26: cropped Expand, Contract and Border measure 1.54–37.82× faster across twelve +2026-10-26: cropped Expand, Contract and Border measure 1.54–37.82× faster across eight 36 MP synthetic mask cases on GitHub Actions, with exact output equality. Radii up to 5 px use capped distances; Contract avoids inverted float masks and Border retains one distance plane. Full-canvas mask conversion/output remain; no GUI budget or percentage changes. @@ -580,7 +580,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| -| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | From be43268ffa77908562239c8dab56f78e60265023 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:02:43 +0530 Subject: [PATCH 04/12] perf: crop Modify command mask conversion and selection replacement --- .github/workflows/ci.yml | 4 + crates/engine/src/selection_cmds.rs | 12 +- .../src/selection_cmds/modify_window.rs | 23 +++ .../src/selection_cmds/modify_window/tests.rs | 180 ++++++++++++++++++ docs/gaps.md | 7 +- docs/selection-distance-performance.md | 43 ++++- docs/target-app-parity.md | 6 +- 7 files changed, 261 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/selection_cmds/modify_window.rs create mode 100644 crates/engine/src/selection_cmds/modify_window/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e6f583a8e..6ec64bc6a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -444,6 +444,10 @@ jobs: run: | set -o pipefail cargo run --release -p photocraft-algo --example bench_selection_morphology | tee selection-morphology-perf.txt + - name: Compare cropped command reads and writeback on 36 MP + run: | + set -o pipefail + cargo test --release -p photocraft-engine --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: always() with: diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs index d6fc50aeea..f0cf6bb4a3 100644 --- a/crates/engine/src/selection_cmds.rs +++ b/crates/engine/src/selection_cmds.rs @@ -11,6 +11,8 @@ use serde_json::{Value, json}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; +mod modify_window; + fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } @@ -452,11 +454,15 @@ fn modify(s: &mut Session, p: &Value, op: &str) -> Result { // or a Select All would border to nothing. let at_bounds = op == "border" || b(p, "applyAtCanvasBounds", false); let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let area = doc.bounds(); - if area.size().area() > MAX_MODIFY_PIXELS as u64 { + let canvas = doc.bounds(); + if canvas.size().area() > MAX_MODIFY_PIXELS as u64 { return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); } - let (_, m) = current_mask(doc); + // Keep both mask conversion and tiled replacement within the affected region. The + // zero halo makes internal window edges inert; nonzero edges can only be canvas edges, + // so the existing Apply effect at canvas bounds padding still has the same meaning. + let area = if matches!(op, "expand" | "contract" | "border") { modify_window::area(doc, r) } else { canvas }; + let m = sel::mask_from_surface(doc.selection.as_ref(), area); let (w, h) = (area.width() as usize, area.height() as usize); // Feather reaches 3σ = 3 r (σ = r, as in Photoshop); the others reach r. A margin past that // keeps the canvas edge out of reach. A selection clear of the canvas edge needs none: both diff --git a/crates/engine/src/selection_cmds/modify_window.rs b/crates/engine/src/selection_cmds/modify_window.rs new file mode 100644 index 0000000000..0551ffa940 --- /dev/null +++ b/crates/engine/src/selection_cmds/modify_window.rs @@ -0,0 +1,23 @@ +//! The command's mask read, algorithm input/output and tiled replacement share this window. + +use photocraft_doc::Document; +use photocraft_geom::Rect; + +pub(super) fn area(doc: &Document, radius: f32) -> Rect { + let canvas = doc.bounds(); + let Some(selection) = doc.selection.as_ref() else { return Rect::EMPTY }; + // content_bounds describes differences from the default. A nonzero default means + // implicit selected pixels throughout the canvas, including with no allocated tiles. + if selection.default_pixel().first().is_some_and(|v| *v != 0.0) { + return canvas; + } + let bounds = selection.content_bounds().intersect(&canvas); + if bounds.is_empty() { + return Rect::EMPTY; + } + let halo = (radius.ceil() as i32).saturating_add(1); + bounds.inflate(halo).intersect(&canvas) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/selection_cmds/modify_window/tests.rs b/crates/engine/src/selection_cmds/modify_window/tests.rs new file mode 100644 index 0000000000..71935dcf7e --- /dev/null +++ b/crates/engine/src/selection_cmds/modify_window/tests.rs @@ -0,0 +1,180 @@ +use super::*; +use crate::Session; +use crate::selection_cmds::{crop_mask, pad_mask, touches_edge}; +use photocraft_algo::selection::{self as sel, SelectionMode}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_geom::Size; +use photocraft_raster::Surface; +use serde_json::json; + +fn document(w: u32, h: u32, selection: Surface) -> Document { + let mut doc = Document::new("modify", Size::new(w, h), ColorMode::Rgb, SampleType::U8); + doc.selection = Some(selection); + doc +} + +fn full_canvas_reference(doc: &Document, op: &str, radius: f32, at_bounds: bool) -> Option { + let canvas = doc.bounds(); + let m = sel::mask_from_surface(doc.selection.as_ref(), canvas); + let (w, h) = (canvas.width() as usize, canvas.height() as usize); + let pad = if touches_edge(&m, w, h) { radius.ceil() as usize + 2 } else { 0 }; + let (pw, ph) = (w + 2 * pad, h + 2 * pad); + let padded = if pad == 0 { m } else { pad_mask(&m, w, h, pad, op == "border" || at_bounds) }; + let out = match op { + "expand" => sel::expand(&padded, pw, ph, radius), + "contract" => sel::contract(&padded, pw, ph, radius), + _ => sel::border(&padded, pw, ph, radius), + }; + let out = if pad == 0 { out } else { crop_mask(&out, pw, pad, w, h) }; + sel::combine(None, &out, canvas, SelectionMode::Replace) +} + +#[test] +fn sparse_36mp_command_only_materializes_the_selection_halo() { + let bounds = Rect::new(3000, 3000, 3050, 3050); + let selection = sel::mask_to_surface(&vec![1.0; 50 * 50], bounds); + let doc = document(6000, 6000, selection); + assert_eq!(area(&doc, 5.0), Rect::new(2994, 2994, 3056, 3056)); + assert_eq!(area(&doc, 5.0).size().area(), 62 * 62); + let mut session = Session::new(); + session.add_document(doc, None); + for op in ["expand", "contract", "border"] { + session.execute(&format!("select.modify.{op}"), json!({"radius": 5})).unwrap(); + assert!(session.active().unwrap().doc.selection.is_some()); + } +} + +#[test] +fn cropped_commands_match_full_canvas_reads_padding_and_writeback() { + let canvas = Rect::new(0, 0, 75, 61); + for case in 0..8 { + let values: Vec = (0..75 * 61) + .map(|i| { + let (x, y) = (i % 75, i / 75); + match case { + 0 => 0.0, + 1 => 1.0, + 2 => { + if (28..39).contains(&x) && (22..33).contains(&y) { + 1.0 + } else { + 0.0 + } + } + 3 => { + if x < 12 && (15..35).contains(&y) { + 1.0 + } else { + 0.0 + } + } + 4 => { + if x >= 63 && y >= 48 { + 1.0 + } else { + 0.0 + } + } + 5 => { + if (25..45).contains(&x) && (18..38).contains(&y) && !(30..35).contains(&x) { + (i % 255 + 1) as f32 / 255.0 + } else { + 0.0 + } + } + _ => 0.0, + } + }) + .collect(); + let mut selection = sel::mask_to_surface(&values, canvas); + if case == 6 { + // Implicit full canvas with a hole: content_bounds only describes the hole. + selection = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + selection.write_pixel(35, 30, &[0.0]); + } else if case == 7 { + selection.write_pixel(-10, -10, &[1.0]); + } + let doc = document(75, 61, selection); + for radius in [1.0, 5.0, 9.5] { + for op in ["expand", "contract", "border"] { + for at_bounds in [false, true] { + let expected = full_canvas_reference(&doc, op, radius, at_bounds); + let mut session = Session::new(); + session.add_document(doc.clone(), None); + session.execute(&format!("select.modify.{op}"), json!({"radius": radius, "applyAtCanvasBounds": at_bounds})).unwrap(); + let actual = &session.active().unwrap().doc.selection; + assert_eq!(actual.is_some(), expected.is_some(), "case {case} {op} radius {radius} bounds {at_bounds}"); + assert_eq!( + sel::mask_from_surface(actual.as_ref(), canvas), + sel::mask_from_surface(expected.as_ref(), canvas), + "case {case} {op} radius {radius} bounds {at_bounds}" + ); + } + } + } + } +} + +#[test] +fn cropped_replacement_keeps_undo_and_redo() { + let canvas = Rect::new(0, 0, 75, 61); + let selection = sel::mask_to_surface(&vec![1.0; 10 * 10], Rect::new(30, 25, 40, 35)); + let doc = document(75, 61, selection); + let before = sel::mask_from_surface(doc.selection.as_ref(), canvas); + let mut session = Session::new(); + session.add_document(doc, None); + session.execute("select.modify.expand", json!({"radius": 5})).unwrap(); + let after = sel::mask_from_surface(session.active().unwrap().doc.selection.as_ref(), canvas); + assert_ne!(before, after); + session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sel::mask_from_surface(session.active().unwrap().doc.selection.as_ref(), canvas), before); + session.execute("edit.redo", json!({})).unwrap(); + assert_eq!(sel::mask_from_surface(session.active().unwrap().doc.selection.as_ref(), canvas), after); +} + +/// Isolate command-window savings: both paths use the optimized algorithm kernels, while +/// the reference retains full-canvas reads/writeback. Includes the undoable edit on both. +#[test] +#[ignore = "36 MP release benchmark; run on GitHub Actions"] +fn sparse_modify_release_comparison() { + use std::time::Instant; + let selection = sel::mask_to_surface(&vec![1.0; 50 * 50], Rect::new(3000, 3000, 3050, 3050)); + let doc = document(6000, 6000, selection); + for radius in [3.0, 50.0] { + for op in ["expand", "contract", "border"] { + let reference = full_canvas_reference(&doc, op, radius, false); + let expected = sel::mask_from_surface(reference.as_ref(), doc.bounds()); + let mut old_times = Vec::new(); + let mut new_times = Vec::new(); + for round in 0..3 { + for old in if round % 2 == 0 { [true, false] } else { [false, true] } { + let mut session = Session::new(); + session.add_document(doc.clone(), None); + let now = Instant::now(); + if old { + let result = full_canvas_reference(&doc, op, radius, false); + session + .edit("Modify selection", |doc, _| { + doc.selection = result; + Ok(()) + }) + .unwrap(); + } else { + session.execute(&format!("select.modify.{op}"), json!({"radius": radius})).unwrap(); + } + let elapsed = now.elapsed().as_secs_f64() * 1000.0; + if old { + old_times.push(elapsed) + } else { + new_times.push(elapsed) + } + assert_eq!(sel::mask_from_surface(session.active().unwrap().doc.selection.as_ref(), doc.bounds()), expected); + } + } + old_times.sort_by(f64::total_cmp); + new_times.sort_by(f64::total_cmp); + let (old, new) = (old_times[1], new_times[1]); + println!("36 MP command {op} r={radius}: full_canvas={old:.3}ms cropped={new:.3}ms speedup={:.2}x exact=true", old / new); + } + } +} diff --git a/docs/gaps.md b/docs/gaps.md index b8180b76c6..a23e79b649 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -297,8 +297,7 @@ what an agent can't finish alone. - **Measured progress (2026-10-26):** Expand, Contract and Border restrict distance work to the nonzero bounds plus a radius halo. Small radii use capped distances; Contract avoids inverted float masks and Border retains one distance plane. On 36 MP, eight synthetic - comparisons measure 1.54–37.82× faster with exact output equality. Full-canvas mask - conversion and output remain; no GUI budget or readiness percentage changes. + comparisons measure 1.54–37.82× faster with exact output equality. Command mask reads and replacement are also cropped; flat algorithm calls still return their input size; no GUI budget or readiness percentage changes. [Method, measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). - **Measured progress (2026-10-10):** Tilt-Shift's existing per-level halo/copy optimization measures 1.07–1.49× faster across nine local 24 MP cases, with exact @@ -396,7 +395,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| -| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index bca853fafe..b21a4df3ea 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -92,10 +92,11 @@ plane at a time. A 50×50 selection at radius 5 needs a 62×62 distance window (3,844 samples), even on a 36 MP canvas. Seed, vertical and output-distance buffers total about 23 KB on the bounded -path, excluding allocator overhead. The flat API still scans its input for bounds and -returns a full-sized output (144 MB at 36 MP). Engine mask conversion, tiled writeback, -undo and compositing remain outside this optimization; this does not establish a GUI -latency budget or solve sparse document storage. +path, excluding allocator overhead. The flat API still scans its supplied input for bounds and +returns an output of the same size (144 MB for a direct 36 MP call). The three Modify +commands now supply only the cropped selection window, including for mask conversion +and tiled replacement. Undo and compositing retain their existing behavior; this does +not establish a GUI latency budget or solve arbitrary sparse document operations. Regression tests compare against the previous full-canvas formulas for empty/full masks, one-row/column canvases, holes, edge-touching shapes, fractional radii, and fractional @@ -131,3 +132,37 @@ also times Contract using its original owning iterator so allocation reuse is pr | 4000×4000 | Border | 3 | 802.48 | 377.78 | 2.12× | | 4000×4000 | Expand | 50 | 414.50 | 268.96 | 1.54× | | 4000×4000 | Border | 50 | 784.89 | 467.06 | 1.68× | + + +### Cropped command reads and writeback + +The engine gets the selection surface's nonzero content bounds, inflates by +`ceil(radius) + 1`, clips to the canvas and reads only that rectangle for Expand, +Contract and Border. Internal rectangle edges have a zero halo, so existing padding +only replicates nonzero values at real canvas edges. A nonzero surface default selects +implicit pixels throughout the canvas and therefore uses the full canvas. Empty +selections clear normally. The existing oversized-canvas safety limit remains. + +Replacement already accepts a rectangle and builds a fresh sparse selection surface, +so it writes only affected tiles and retains the existing undoable transaction. The +shared `current_mask` helper and Grow/Similar are unchanged. Smooth and Feather keep +their existing command paths. + +Command tests compare against full-canvas reads, padding and replacement for empty/full +selections, both canvas-bounds settings, edge-touching masks, holes, fractional coverage, +nonzero implicit defaults and entirely off-canvas pixels. Undo and redo preserve the +selection. A synthetic 36 MP test verifies that a 50×50 selection at radius 5 supplies +only 62×62 samples and executes all three commands without full-canvas mask allocation. + +The optional CI benchmark also runs: + +```sh +cargo test --release -p photocraft-engine --lib sparse_modify_release_comparison -- --ignored --nocapture +``` + +This isolates command-window savings: both paths use the optimized algorithm kernels, +but the reference keeps full-canvas mask conversion and replacement. Both include the +undoable edit; session creation and full-canvas equality checks are outside timing. +Three rounds alternate execution order, with radii 3 and 50 on a 50×50 selection in a +6000×6000 canvas. The cropped path dispatches the actual command; the reference calls +the prior conversion/edit sequence directly. GUI rendering remains excluded. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5299f4612d..26b95ea479 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; 12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology and command mask conversion performance evidence added; 12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -366,7 +366,7 @@ These are local measurements at amount 1; see [method and limits](radial-blur-pe 2026-10-26: cropped Expand, Contract and Border measure 1.54–37.82× faster across eight 36 MP synthetic mask cases on GitHub Actions, with exact output equality. Radii up to 5 px use capped distances; Contract avoids inverted float masks and Border retains one distance -plane. Full-canvas mask conversion/output remain; no GUI budget or percentage changes. +plane. Command reads/writeback also use the cropped bounds; flat algorithm outputs retain input size; no GUI budget or percentage changes. See [measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). 2026-10-10: native selection distance transforms measured 7.59–10.57x faster on six @@ -580,7 +580,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| -| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | From 9282b1225722aa09a6c2e403f32de3606c7eec7a Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:05:27 +0530 Subject: [PATCH 05/12] ci: run the GPU performance suite on its macOS runner class --- .github/workflows/ci.yml | 22 ++++++++++++++++++++++ docs/selection-distance-performance.md | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ec64bc6a3..5a0386670b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -453,5 +453,27 @@ jobs: with: name: selection-morphology-performance path: selection-morphology-perf.txt + + selection-morphology-quick-perf: + if: inputs.selection_morphology == true + # Match perf-nightly.yml: Linux llvmpipe lacks the float render targets needed by + # bevel_bench, so its required GPU rows cannot be measured there. + runs-on: macos-15 + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: perf-release - name: Quick performance suite run: cargo xtask perf --quick + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: selection-morphology-quick-perf + path: | + target/perf/*.json + target/perf/summary.md diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index b21a4df3ea..073a941c03 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -107,7 +107,7 @@ radii return empty buffers. Reproduce on the fork through the CI workflow's optional `selection_morphology` input. It runs `cargo run --release -p photocraft-algo --example bench_selection_morphology` -and `cargo xtask perf --quick` remotely. The comparison uses a 6000×6000 mask with either +on Linux, and `cargo xtask perf --quick` on the project’s macOS performance runner class. The comparison uses a 6000×6000 mask with either a centred 50×50 square or a centred 4000×4000 square, radii 3 and 50, and four Rayon workers. It checks every output sample against the previous formulas before timing; reported medians include output allocation and exclude output destruction, with three From c66899e0a5bdb66d87b9790048802d532ac936ba Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:08:28 +0530 Subject: [PATCH 06/12] test: simplify selection fixtures for strict Clippy --- .../src/selection_cmds/modify_window/tests.rs | 32 +++---------------- 1 file changed, 4 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/selection_cmds/modify_window/tests.rs b/crates/engine/src/selection_cmds/modify_window/tests.rs index 71935dcf7e..35cc118a07 100644 --- a/crates/engine/src/selection_cmds/modify_window/tests.rs +++ b/crates/engine/src/selection_cmds/modify_window/tests.rs @@ -54,34 +54,10 @@ fn cropped_commands_match_full_canvas_reads_padding_and_writeback() { match case { 0 => 0.0, 1 => 1.0, - 2 => { - if (28..39).contains(&x) && (22..33).contains(&y) { - 1.0 - } else { - 0.0 - } - } - 3 => { - if x < 12 && (15..35).contains(&y) { - 1.0 - } else { - 0.0 - } - } - 4 => { - if x >= 63 && y >= 48 { - 1.0 - } else { - 0.0 - } - } - 5 => { - if (25..45).contains(&x) && (18..38).contains(&y) && !(30..35).contains(&x) { - (i % 255 + 1) as f32 / 255.0 - } else { - 0.0 - } - } + 2 if (28..39).contains(&x) && (22..33).contains(&y) => 1.0, + 3 if x < 12 && (15..35).contains(&y) => 1.0, + 4 if x >= 63 && y >= 48 => 1.0, + 5 if (25..45).contains(&x) && (18..38).contains(&y) && !(30..35).contains(&x) => (i % 255 + 1) as f32 / 255.0, _ => 0.0, } }) From 8a2acd5ad6cab688365107762d2cb53923217b89 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:26:33 +0530 Subject: [PATCH 07/12] fix: guard cropped selection bounds against corrupt tile coordinates --- .../engine/src/selection_cmds/modify_window.rs | 9 ++++++++- .../src/selection_cmds/modify_window/tests.rs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/selection_cmds/modify_window.rs b/crates/engine/src/selection_cmds/modify_window.rs index 0551ffa940..df839f10a3 100644 --- a/crates/engine/src/selection_cmds/modify_window.rs +++ b/crates/engine/src/selection_cmds/modify_window.rs @@ -1,7 +1,7 @@ //! The command's mask read, algorithm input/output and tiled replacement share this window. use photocraft_doc::Document; -use photocraft_geom::Rect; +use photocraft_geom::{Rect, TILE_SIZE}; pub(super) fn area(doc: &Document, radius: f32) -> Rect { let canvas = doc.bounds(); @@ -11,6 +11,13 @@ pub(super) fn area(doc: &Document, radius: f32) -> Rect { if selection.default_pixel().first().is_some_and(|v| *v != 0.0) { return canvas; } + // Raw tile coordinates can come from document data. content_bounds sorts by i32 + // coordinate differences, which can overflow outside the pixel-addressable range. + // The prior canvas reader only queries valid coordinates and safely ignores these. + let valid = (i32::MIN / TILE_SIZE)..=(i32::MAX / TILE_SIZE); + if selection.tiles().any(|(tile, _)| !valid.contains(&tile.tx) || !valid.contains(&tile.ty)) { + return canvas; + } let bounds = selection.content_bounds().intersect(&canvas); if bounds.is_empty() { return Rect::EMPTY; diff --git a/crates/engine/src/selection_cmds/modify_window/tests.rs b/crates/engine/src/selection_cmds/modify_window/tests.rs index 35cc118a07..4f8fe8fce6 100644 --- a/crates/engine/src/selection_cmds/modify_window/tests.rs +++ b/crates/engine/src/selection_cmds/modify_window/tests.rs @@ -154,3 +154,21 @@ fn sparse_modify_release_comparison() { } } } + +#[test] +fn corrupt_tile_coordinates_do_not_panic_while_finding_the_window() { + use photocraft_geom::TileCoord; + use std::sync::Arc; + let mut selection = Surface::new(PixelFormat::GRAY8); + let tile = selection.solid_tile(&[1.0]); + selection.put_tiles([(TileCoord::new(i32::MIN, i32::MIN), Arc::clone(&tile)), (TileCoord::new(i32::MAX, i32::MAX), tile)]); + let doc = document(75, 61, selection); + // Without the guard, content_bounds overflows while sorting these coordinates. + assert_eq!(area(&doc, 5.0), doc.bounds()); + for op in ["expand", "contract", "border"] { + let mut session = Session::new(); + session.add_document(doc.clone(), None); + session.execute(&format!("select.modify.{op}"), json!({"radius": 5})).unwrap(); + assert!(session.active().unwrap().doc.selection.is_none()); + } +} From d2263c6cf220aab4fcbb9d79d71ba1b6cf95238a Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:36:50 +0530 Subject: [PATCH 08/12] perf: retain uniform-mask shortcuts in bounded selection distances --- crates/algo/examples/bench_selection_morphology.rs | 2 +- crates/algo/src/selection/distance.rs | 7 +++++++ docs/selection-distance-performance.md | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/algo/examples/bench_selection_morphology.rs b/crates/algo/examples/bench_selection_morphology.rs index 795ba74413..71fbc7438e 100644 --- a/crates/algo/examples/bench_selection_morphology.rs +++ b/crates/algo/examples/bench_selection_morphology.rs @@ -22,7 +22,7 @@ fn old_border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { fn main() -> Result<(), Box> { let (w, h) = (6000, 6000); println!("36 MP; median of three runs including allocation; RAYON_NUM_THREADS={}", std::env::var("RAYON_NUM_THREADS").unwrap_or_default()); - for (case, size) in [("sparse", 50), ("dense", 4000)] { + for (case, size) in [("sparse", 50), ("dense", 4000), ("full", 6000)] { let mut m = vec![0.0; w * h]; let start = (w - size) / 2; for row in m.chunks_exact_mut(w).skip(start).take(size) { diff --git a/crates/algo/src/selection/distance.rs b/crates/algo/src/selection/distance.rs index 53588904f0..73b5b8f2a4 100644 --- a/crates/algo/src/selection/distance.rs +++ b/crates/algo/src/selection/distance.rs @@ -13,6 +13,13 @@ pub(super) fn edt_bounded(seeds: &[bool], w: usize, h: usize, reach: f32) -> Vec if w == 0 || h == 0 || w.checked_mul(h) != Some(seeds.len()) || !(0.0..=6.0).contains(&reach) { return Vec::new(); } + // Select All and empty complements need no sweeps, just as in the general EDT. + if !seeds.iter().any(|seed| *seed) { + return vec![EMPTY_DISTANCE; seeds.len()]; + } + if seeds.iter().all(|seed| *seed) { + return vec![0.0; seeds.len()]; + } let radius = reach.ceil() as usize; let cap = radius as u8 + 1; let mut vertical: Vec = seeds.iter().map(|s| if *s { 0 } else { cap }).collect(); diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index 073a941c03..d1abbe6f4c 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -166,3 +166,9 @@ undoable edit; session creation and full-canvas equality checks are outside timi Three rounds alternate execution order, with radii 3 and 50 on a 50×50 selection in a 6000×6000 canvas. The cropped path dispatches the actual command; the reference calls the prior conversion/edit sequence directly. GUI rendering remains excluded. + +Uniform bounded-distance masks retain the general EDT's no-sweep shortcuts: no seeds +return the finite empty-distance sentinel; all seeds return zero. The current algorithm +benchmark also includes a full-canvas selected mask to check Select All alongside the +sparse and dense partial selections. The historical table above covers its recorded +Expand/Border sparse and dense cases. From b6ee9f7c36a2153271ef29fadf55a96ba1f2616c Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:38:48 +0530 Subject: [PATCH 09/12] perf: avoid copying zero coverage outside the morphology window --- crates/algo/src/selection/morphology.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/algo/src/selection/morphology.rs b/crates/algo/src/selection/morphology.rs index ac159c9e3c..53b6ec3cf0 100644 --- a/crates/algo/src/selection/morphology.rs +++ b/crates/algo/src/selection/morphology.rs @@ -44,12 +44,9 @@ pub(super) fn modify(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec isize::MAX as usize / 4 || !r.is_finite() || r < 0.0 { return Vec::new(); } - let mut out = match kind { - Kind::Expand => m.to_vec(), - // Retain the old complement's rounding for fractional input coverage. - Kind::Contract => m.iter().map(|v| 1.0 - (1.0 - v)).collect(), - Kind::Border => vec![0.0; m.len()], - }; + // The window includes every nonzero sample, including fractional coverage, so all + // pixels beyond it are zero for every operation. No canvas-sized copy is needed. + let mut out = vec![0.0; m.len()]; if matches!(kind, Kind::Border) && r == 0.0 { return out; } From 8793bf5ca8c2c2264a08a64aa1a7cc626d3c82ea Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 19:54:43 +0530 Subject: [PATCH 10/12] perf: skip Border distance work when the mask has no edge --- crates/algo/src/selection/morphology.rs | 6 ++++++ docs/selection-distance-performance.md | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/crates/algo/src/selection/morphology.rs b/crates/algo/src/selection/morphology.rs index 53b6ec3cf0..4340ceb26b 100644 --- a/crates/algo/src/selection/morphology.rs +++ b/crates/algo/src/selection/morphology.rs @@ -63,6 +63,12 @@ pub(super) fn modify(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec Date: Tue, 27 Oct 2026 09:42:47 +0530 Subject: [PATCH 11/12] perf(selection): window marquee and lasso feather masks (#9794) * perf: window marquee and lasso feather masks to drawn bounds * perf: benchmark small feathered tool selections on a 24 MP canvas --- crates/algo/src/selection.rs | 17 +- crates/algo/src/selection/tests.rs | 20 +++ crates/engine/examples/bench_tool_feather.rs | 150 ++++++++++++++++++ crates/engine/src/cmd.rs | 5 +- crates/engine/src/cmd/selection_cmds.rs | 36 ++++- crates/engine/src/cmd/selection_cmds/tests.rs | 110 +++++++++++++ 6 files changed, 328 insertions(+), 10 deletions(-) create mode 100644 crates/engine/examples/bench_tool_feather.rs diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 70e815b2b2..c4fc913785 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -818,13 +818,23 @@ pub fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { /// rows are filled in parallel, and each sub-row tests only the edges that /// cross it (an active edge list over the edges sorted by their top). pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { + polygon_window(points, area, area, anti_alias) +} + +/// Rasterizes only `window` intersected with `canvas`, retaining the coordinate arithmetic of +/// [`polygon`] over the whole canvas. Keeping that origin avoids rounding changes in fractional +/// edge coverage when a feathered lasso uses a smaller working mask. +pub fn polygon_window(points: &[(f32, f32)], canvas: Rect, window: Rect, anti_alias: bool) -> Vec { + let area = window.intersect(&canvas); let (w, h) = (area.width() as usize, area.height() as usize); let mut m = vec![0.0f32; w * h]; if points.len() < 3 || w == 0 { return m; } let sub = if anti_alias { 4 } else { 1 }; - let sample_y = |py: usize, s: usize| area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; + let dx = (i64::from(area.x0) - i64::from(canvas.x0)) as usize; + let dy = (i64::from(area.y0) - i64::from(canvas.y0)) as usize; + let sample_y = |py: usize, s: usize| canvas.y0 as f32 + (dy + py) as f32 + (s as f32 + 0.5) / sub as f32; // A sub-row at y crosses the edge a→b iff top <= y < bottom; horizontal and NaN edges // never cross one. struct Edge { @@ -871,12 +881,13 @@ pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec xs.extend(active.iter().map(|&&Edge { a, b, .. }| a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0))); xs.sort_by(|a, b| a.total_cmp(b)); for span in xs.as_chunks::<2>().0 { - let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); + let (x0, x1) = ((span[0] - canvas.x0 as f32).max(0.0), (span[1] - canvas.x0 as f32).min(canvas.width() as f32)); if x1 <= x0 { continue; } - let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); + let (c0, c1) = ((x0.floor() as usize).saturating_sub(dx), (x1.ceil() as usize).saturating_sub(dx).min(w)); for (cx, v) in row.iter_mut().enumerate().take(c1).skip(c0) { + let cx = cx + dx; let cov = if anti_alias { ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) } else { diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 368633f03a..30ae9b23a2 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -654,3 +654,23 @@ fn combine_region_matches_combine() { } assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); } + +#[test] +fn polygon_window_keeps_full_canvas_fractional_coverage() { + for canvas in [Rect::new(0, 0, 110_000, 12), Rect::new(-123, -7, 109_877, 5)] { + let points = [(100_003.12, -2.3), (100_043.71, 2.19), (100_032.39, 9.2), (100_001.52, 4.17)]; + for aa in [false, true] { + let full = polygon(&points, canvas, aa); + for requested in [Rect::new(99_998, -10, 100_048, 15), Rect::new(100_010, -3, 100_030, 6), Rect::EMPTY] { + let area = requested.intersect(&canvas); + let local = polygon_window(&points, canvas, requested, aa); + let mut crop = Vec::new(); + for y in area.y0..area.y1 { + let start = (y - canvas.y0) as usize * canvas.width() as usize + (area.x0 - canvas.x0) as usize; + crop.extend_from_slice(&full[start..start + area.width() as usize]); + } + assert_eq!(local, crop, "canvas={canvas:?}, requested={requested:?}, aa={aa}"); + } + } + } +} diff --git a/crates/engine/examples/bench_tool_feather.rs b/crates/engine/examples/bench_tool_feather.rs new file mode 100644 index 0000000000..d7eabf0e53 --- /dev/null +++ b/crates/engine/examples/bench_tool_feather.rs @@ -0,0 +1,150 @@ +//! Feathered marquee / lasso on a 6000×4000 (24 MP) canvas: the pre-windowing reference +//! (shape → dense full-canvas mask → `sel::feather` → `sel::combine(None, …, Replace)`) +//! against the current `select.rect` / `select.lasso` commands, whose dense feather mask +//! stays a (50 + 2·(⌈3·4⌉+1))² = 76² = 5776-pixel window around the 50×50 shape. +//! `cargo run --release -p photocraft-engine --example bench_tool_feather [reps]` +use std::time::{Duration, Instant}; + +use photocraft_algo::selection as sel; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, Size}; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +type Res = Result>; + +const W: i32 = 6000; +const H: i32 = 4000; +/// A 50×50 shape centred on the canvas, feathered by 4 px. +const X: i32 = W / 2 - 25; +const Y: i32 = H / 2 - 25; +const SHAPE: i32 = 50; +const FEATHER: f32 = 4.0; +const DEFAULT_REPS: usize = 7; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Rect, + Ellipse, + Lasso, +} + +impl Kind { + fn label(self) -> &'static str { + match self { + Kind::Rect => "rect", + Kind::Ellipse => "ellipse", + Kind::Lasso => "lasso", + } + } + + fn command(self) -> &'static str { + match self { + Kind::Lasso => "select.lasso", + Kind::Rect | Kind::Ellipse => "select.rect", + } + } + + fn params(self) -> Value { + let r = json!({"x": X, "y": Y, "width": SHAPE, "height": SHAPE, "feather": FEATHER}); + match self { + Kind::Rect => r, + Kind::Ellipse => json!({"x": X, "y": Y, "width": SHAPE, "height": SHAPE, "ellipse": true, "feather": FEATHER}), + Kind::Lasso => json!({"points": [[X, Y], [X + SHAPE, Y], [X + SHAPE, Y + SHAPE], [X, Y + SHAPE]], "feather": FEATHER}), + } + } + + /// The path the windowed commands replaced: shape construction, a dense full-canvas f32 + /// mask, the full-canvas blur, and a full-canvas `Replace` combine against no old selection. + fn reference(self, area: Rect) -> Option { + let mask = match self { + Kind::Rect | Kind::Ellipse => { + let r = Rect::from_xywh(X, Y, SHAPE as u32, SHAPE as u32); + let shape = if self == Kind::Ellipse { + sel::ellipse_surface(r, area, true) + } else { + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(r.intersect(&area), &[1.0]); + s + }; + sel::mask_from_surface(Some(&shape), area) + } + // Raw floating-point coverage: never quantise before the blur. + Kind::Lasso => { + let e = (X + SHAPE) as f32; + let (x, y, ey) = (X as f32, Y as f32, (Y + SHAPE) as f32); + sel::polygon(&[(x, y), (e, y), (e, ey), (x, ey)], area, true) + } + }; + let (w, h) = (area.width() as usize, area.height() as usize); + let mask = sel::feather(&mask, w, h, FEATHER); + sel::combine(None, &mask, area, sel::SelectionMode::Replace) + } +} + +fn median(times: &[Duration]) -> Duration { + let mut sorted = times.to_vec(); + sorted.sort_unstable(); + let n = sorted.len(); + let Some(mid) = sorted.get(n / 2).copied() else { return Duration::ZERO }; + if n % 2 == 1 { mid } else { sorted.get(n / 2 - 1).copied().map_or(mid, |prev| (prev + mid) / 2) } +} + +fn main() -> Res<()> { + let reps = match std::env::args().nth(1) { + None => DEFAULT_REPS, + Some(v) => { + let n: usize = v.parse().map_err(|e| format!("reps `{v}` must be a whole number ({e})"))?; + if !(1..=1000).contains(&n) { + return Err("reps must be in 1..=1000".into()); + } + n + } + }; + // Sparse 24 MP document: `Document::new` plus an empty raster layer allocates no pixels. + let mut doc = Document::new("bench-24mp", Size::new(W as u32, H as u32), ColorMode::Grayscale, SampleType::U8); + let format = doc.pixel_format(); + doc.layers.push(Layer::raster("Layer 1", format)); + let mut s = Session::new(); + s.add_document(doc, None); + let area = s.active().map(|st| st.doc.bounds()).ok_or("no document")?; + + let full_px = W as u64 * H as u64; + let side = SHAPE as u64 + 2 * ((FEATHER * 3.0).ceil() as u64 + 1); + println!("tool feather, 6000×4000 = {full_px} px canvas, {SHAPE}×{SHAPE} shape, feather {FEATHER} px, median of {reps}"); + println!( + "dense f32 mask: full canvas {full_px} px / {} B vs windowed {side}×{side} = {} px / {} B ({}× fewer)\n", + full_px * 4, + side * side, + side * side * 4, + full_px / (side * side), + ); + for kind in [Kind::Rect, Kind::Ellipse, Kind::Lasso] { + // One untimed pass each: allocator and first-call setup stay out of the medians. + drop(std::hint::black_box(kind.reference(area))); + let _ = s.execute("select.deselect", json!({})); + s.execute(kind.command(), kind.params())?; + let mut reference = Vec::with_capacity(reps); + for _ in 0..reps { + let t = Instant::now(); + let out = kind.reference(area); + reference.push(t.elapsed()); + std::hint::black_box(&out); + drop(out); + } + let mut current = Vec::with_capacity(reps); + for _ in 0..reps { + let _ = s.execute("select.deselect", json!({})); + let t = Instant::now(); + s.execute(kind.command(), kind.params())?; + current.push(t.elapsed()); + } + let (r, c) = (median(&reference), median(¤t)); + let (ms, cm) = (r.as_secs_f64() * 1000.0, c.as_secs_f64() * 1000.0); + let speedup = if cm > 0.0 { ms / cm } else { f64::INFINITY }; + println!("{:<6} reference {ms:>9.2} ms current {cm:>9.2} ms speedup {speedup:>7.1}x", kind.label()); + } + Ok(()) +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 38ede534b1..5b5f37b4d6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -410,8 +410,9 @@ fn build() -> Vec { s }; if feather > 0.0 { - let m = sel::feather(&sel::mask_from_surface(Some(&shape), area), area.width() as usize, area.height() as usize, feather); - doc.selection = sel::combine(doc.selection.as_ref(), &m, area, sel::SelectionMode::parse(&mode)); + let window = selection_cmds::feather_window(r, area, feather); + let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); + doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); return Ok(()); } let old = doc.selection.take(); diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 4b8da7e796..0c3881ca10 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -600,10 +600,26 @@ pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[ } let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); if feather > 0.0 { - // The blur spreads past the polygon and isn't bit-identical over a smaller window. - let mut mask = sel::polygon(pts, area, b(p, "antiAlias", true)); - mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); - return set_selection(s, label, area, mask, mode(p)); + let (mut lo, mut hi) = ((f32::INFINITY, f32::INFINITY), (f32::NEG_INFINITY, f32::NEG_INFINITY)); + for &(x, y) in pts { + if x.is_finite() && y.is_finite() { + lo = (lo.0.min(x), lo.1.min(y)); + hi = (hi.0.max(x), hi.1.max(y)); + } + } + let bounds = if lo.0 <= hi.0 && lo.1 <= hi.1 { + Rect::new(lo.0.floor() as i32, lo.1.floor() as i32, hi.0.ceil() as i32, hi.1.ceil() as i32) + } else { + Rect::EMPTY + }; + let window = feather_window(bounds, area, feather); + let mask = sel::polygon_window(pts, area, window, b(p, "antiAlias", true)); + let mask = sel::feather(&mask, window.width() as usize, window.height() as usize, feather); + let selected = s.edit(label, |doc, _| { + doc.selection = combine_band(doc.selection.as_ref(), &mask, window, mode(p)); + Ok(doc.selection.is_some()) + })?; + return Ok(json!({ "selected": selected })); } // Only the rows the polygon spans (#4532): rows outside it are empty, and full-width rows // keep `polygon`'s coverage bit-identical (its x arithmetic is relative to the area's left @@ -633,7 +649,7 @@ fn polygon_rows(pts: &[(f32, f32)], area: Rect) -> Rect { /// [`sel::combine`] of a mask covering only `band` (zero elsewhere), giving exactly what the /// whole-canvas combine gives: Replace and Intersect are empty outside the band, and Add and /// Subtract keep the old selection there. -fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { +pub(crate) fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { let inside = sel::combine(old, mask, band, m); let Some(old) = old.filter(|_| matches!(m, SelectionMode::Add | SelectionMode::Subtract)) else { return inside }; if band.is_empty() { @@ -646,6 +662,16 @@ fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMod (s.tile_count() > 0).then_some(s) } +/// Keep dense feather masks local to the drawn shape. Clip before inflating: pixels outside +/// the canvas never contribute to the original full-canvas blur, even near a canvas edge. +pub(crate) fn feather_window(bounds: Rect, canvas: Rect, feather: f32) -> Rect { + let bounds = bounds.intersect(&canvas); + if bounds.is_empty() { + return Rect::EMPTY; + } + bounds.inflate(((feather * 3.0).ceil() as i32).saturating_add(1)).intersect(&canvas) +} + macro_rules! spec { ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } diff --git a/crates/engine/src/cmd/selection_cmds/tests.rs b/crates/engine/src/cmd/selection_cmds/tests.rs index 602262dc7f..0b28681172 100644 --- a/crates/engine/src/cmd/selection_cmds/tests.rs +++ b/crates/engine/src/cmd/selection_cmds/tests.rs @@ -725,3 +725,113 @@ fn lasso_over_its_rows_matches_the_whole_canvas() { assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); } } + +#[test] +fn feather_window_is_bounded_and_clipped_before_growing() { + let canvas = Rect::new(0, 0, 6000, 4000); + let window = feather_window(Rect::from_xywh(3000, 2000, 50, 50), canvas, 4.0); + assert_eq!(window, Rect::new(2987, 1987, 3063, 2063)); + assert_eq!(window.size().area(), 5776); + assert_eq!(feather_window(Rect::from_xywh(3000, 2000, 50, 50), canvas, 1000.0), canvas); + assert_eq!(feather_window(Rect::new(-5, -5, 10, 10), canvas, 2.5), Rect::new(0, 0, 19, 19)); + assert_eq!(feather_window(Rect::new(-20, -20, -1, -1), canvas, 20.0), Rect::EMPTY); + assert_eq!(feather_window(Rect::EMPTY, canvas, 1000.0), Rect::EMPTY); +} + +/// The stored coverage and history must match the previous full-canvas paths, including soft +/// old selections outside the working window and shapes clipped at every canvas edge. +#[test] +fn windowed_tool_feather_matches_full_canvas() { + let area = Rect::new(0, 0, 192, 160); + let shapes = [ + Rect::new(72, 61, 97, 89), + Rect::new(-12, -7, 24, 25), + Rect::new(177, 143, 210, 180), + Rect::new(-15, 65, -2, 80), + Rect::new(75, 65, 75, 80), + Rect::new(-5, -5, 200, 170), + ]; + for (case, r) in shapes.into_iter().enumerate() { + for tool in ["rect", "ellipse", "lasso"] { + for aa in [false, true] { + for radius in [0.05, 2.5, 7.0] { + let pts = [ + (r.x0 as f32 + 0.125, r.y0 as f32 + 0.375), + (r.x1 as f32, r.y0 as f32), + (r.x1 as f32 - 0.25, r.y1 as f32 + 0.125), + (r.x0 as f32, r.y1 as f32), + ]; + let input = if tool == "lasso" { + sel::polygon(&pts, area, aa) + } else { + let mut shape = Surface::new(photocraft_color::PixelFormat::GRAY8); + if tool == "ellipse" { + shape = sel::ellipse_surface(r, area, aa); + } else { + shape.fill_rect(r.intersect(&area), &[1.0]); + } + sel::mask_from_surface(Some(&shape), area) + }; + let mask = sel::feather(&input, area.width() as usize, area.height() as usize, radius); + for m in ["replace", "add", "subtract", "intersect"] { + for has_old in [false, true] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": area.width(), "height": area.height()})).unwrap(); + if has_old { + s.edit("soft selection", |doc, _| { + let mut old = Surface::new(photocraft_color::PixelFormat::GRAY8); + old.fill_rect(Rect::new(3, 4, 180, 150), &[0.6]); + old.fill_rect(Rect::new(70, 60, 90, 80), &[1.0]); + doc.selection = Some(old); + Ok(()) + }) + .unwrap(); + } + let before = s.active().unwrap().doc.selection.clone(); + let want = sel::combine(before.as_ref(), &mask, area, SelectionMode::parse(m)); + let steps = s.active().unwrap().history.past_len(); + let result = if tool == "lasso" { + s.execute("select.lasso", json!({"points": pts, "antiAlias": aa, "feather": radius, "mode": m})).unwrap() + } else { + s.execute("select.rect", json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "ellipse": tool == "ellipse", "antiAlias": aa, "feather": radius, "mode": m})).unwrap() + }; + let got = s.active().unwrap().doc.selection.clone(); + let read = |v: &Option| sel::mask_from_surface(v.as_ref(), area); + assert_eq!(read(&got), read(&want), "case {case}, {tool}, aa={aa}, radius={radius}, mode={m}, old={has_old}"); + assert_eq!(got.is_some(), want.is_some()); + if tool == "lasso" { + assert_eq!(result["selected"], want.is_some()); + } + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(read(&s.active().unwrap().doc.selection), read(&before)); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(read(&s.active().unwrap().doc.selection), read(&want)); + } + } + } + } + } + } +} + +#[test] +fn small_feathered_tools_work_on_large_sparse_documents_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000, "depth": depth, "background": "transparent"})).unwrap(); + for ellipse in [false, true] { + s.execute("select.rect", json!({"x": 3000, "y": 2000, "width": 50, "height": 50, "ellipse": ellipse, "feather": 4})).unwrap(); + let selection = s.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(selection.tile_count() <= 4); + assert!(Rect::new(2987, 1987, 3063, 2063).contains_rect(&selection.content_bounds())); + assert!(coverage(&s, 3025, 2025) > 0.95); + assert!(coverage(&s, 3000, 2025) > 0.1 && coverage(&s, 3000, 2025) < 0.8); + } + s.execute("select.lasso", json!({"points": [[3000, 2000], [3050, 2000], [3050, 2050], [3000, 2050]], "feather": 4})).unwrap(); + let selection = s.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(selection.tile_count() <= 4); + assert!(Rect::new(2987, 1987, 3063, 2063).contains_rect(&selection.content_bounds())); + assert!(coverage(&s, 3025, 2025) > 0.95); + } +} From 7ac7b8b106acccf6826d45ed5c9e481dfe341035 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:07:05 -0400 Subject: [PATCH 12/12] refactor(selection): take the feather reach from the blur (#9802) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The feather's ⌈3σ⌉ truncation radius was written out in the blur and again in two engine callers: the windowed marquee and lasso feather (#9794) and the canvas-edge padding of Select › Modify › Feather. selection::feather_reach returns it from the blur's own σ rules, and both callers use it, so a change to the blur's reach can't leave them behind. Output is unchanged; a test pins that the feather leaves everything past its reach at zero. --- crates/algo/src/selection.rs | 7 ++++++ crates/algo/src/selection/tests.rs | 13 +++++++++++ crates/algo/src/selection_blur.rs | 31 ++++++++++++++++++------- crates/engine/src/cmd/selection_cmds.rs | 9 +++---- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index bb7a521114..d6e1837dd1 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -806,6 +806,13 @@ pub fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { crate::selection_blur::feather(m, w, h, radius) } +/// How far [`feather`] spreads, in pixels (`⌈3σ⌉` with σ = `radius`, 0 when it changes nothing). +/// Samples farther than this from every nonzero sample stay 0, so a working window grown by this +/// much gives the same result as the whole canvas. +pub fn feather_reach(radius: f32) -> usize { + crate::selection_blur::feather_reach(radius) +} + /// Anti-aliased polygon (even-odd) coverage over `area`: exact horizontal /// coverage, 4 sub-rows per pixel row (or 1 when not anti-aliased). Bands of /// rows are filled in parallel, and each sub-row tests only the edges that diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 30ae9b23a2..226a4c5a68 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -674,3 +674,16 @@ fn polygon_window_keeps_full_canvas_fractional_coverage() { } } } + +#[test] +fn feather_leaves_everything_beyond_its_reach_at_zero() { + for radius in [0.05, 0.5, 2.5, 7.0, 40.0] { + let reach = feather_reach(radius); + let w = 3 * reach + 20; + let mut m = vec![0.0; w]; + m[0] = 1.0; + let out = feather(&m, w, 1, radius); + assert!(out[0] > 0.0, "radius {radius}"); + assert!(out[reach + 1..].iter().all(|v| *v == 0.0), "radius {radius}: nonzero past reach {reach}"); + } +} diff --git a/crates/algo/src/selection_blur.rs b/crates/algo/src/selection_blur.rs index 4c64250a68..1262e9b77f 100644 --- a/crates/algo/src/selection_blur.rs +++ b/crates/algo/src/selection_blur.rs @@ -542,13 +542,9 @@ impl CosKernel { } } -/// Select › Modify › Feather: Gaussian blur of the mask with `σ = radius`, the kernel truncated -/// at `⌈3σ⌉` and normalized, zero beyond the canvas. Photoshop's feather radius is the Gaussian's -/// σ (measured on Photoshop 27.11; the same mapping the mask feather uses, fitted on the -/// psd-tools corpus in `photocraft_compose::masks::feather_sigma`). It was `radius / 2`: half -/// as wide as Photoshop's. -pub(crate) fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { - let n = w.saturating_mul(h); +/// The feather's Gaussian σ for `radius`, capped at [`MAX_SIGMA`]. Below 0.1 the feather leaves +/// the mask as it is. +fn feather_sigma(radius: f32) -> f32 { let sigma = if radius.is_finite() { radius.max(0.0) } else if radius > 0.0 { @@ -556,11 +552,28 @@ pub(crate) fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { } else { 0.0 }; + sigma.min(MAX_SIGMA) +} + +/// How far [`feather`] spreads, in pixels: its kernel's truncation radius `⌈3σ⌉`, or 0 when it +/// leaves the mask as it is. Samples farther than this from every nonzero sample stay 0. +pub(crate) fn feather_reach(radius: f32) -> usize { + let sigma = feather_sigma(radius); + if sigma < 0.1 { 0 } else { (sigma * 3.0).ceil() as usize } +} + +/// Select › Modify › Feather: Gaussian blur of the mask with `σ = radius`, the kernel truncated +/// at `⌈3σ⌉` and normalized, zero beyond the canvas. Photoshop's feather radius is the Gaussian's +/// σ (measured on Photoshop 27.11; the same mapping the mask feather uses, fitted on the +/// psd-tools corpus in `photocraft_compose::masks::feather_sigma`). It was `radius / 2`: half +/// as wide as Photoshop's. +pub(crate) fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { + let n = w.saturating_mul(h); + let sigma = feather_sigma(radius); if sigma < 0.1 || m.len() != n || n == 0 { return m.to_vec(); } - let sigma = sigma.min(MAX_SIGMA); - let r = (sigma * 3.0).ceil() as usize; + let r = feather_reach(radius); let Some(b) = nonzero_bounds(m, w, h) else { return m.to_vec(); }; diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 9cf48f3545..362e889fa9 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -464,11 +464,11 @@ fn modify(s: &mut Session, p: &Value, op: &str) -> Result { let area = if matches!(op, "expand" | "contract" | "border") { modify_window::area(doc, r) } else { canvas }; let m = sel::mask_from_surface(doc.selection.as_ref(), area); let (w, h) = (area.width() as usize, area.height() as usize); - // Feather reaches 3σ = 3 r (σ = r, as in Photoshop); the others reach r. A margin past that + // Feather reaches ⌈3σ⌉ (σ = r, as in Photoshop); the others reach r. A margin past that // keeps the canvas edge out of reach. A selection clear of the canvas edge needs none: both // readings agree there. - let reach = if op == "feather" { r * 3.0 } else { r }; - let pad = if touches_edge(&m, w, h) { reach.ceil() as usize + 2 } else { 0 }; + let reach = if op == "feather" { sel::feather_reach(r) } else { r.ceil() as usize }; + let pad = if touches_edge(&m, w, h) { reach.saturating_add(2) } else { 0 }; let grown = |n: usize| pad.checked_mul(2).and_then(|p| n.checked_add(p)); let (Some(pw), Some(ph)) = (grown(w), grown(h)) else { return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); @@ -675,7 +675,8 @@ pub(crate) fn feather_window(bounds: Rect, canvas: Rect, feather: f32) -> Rect { if bounds.is_empty() { return Rect::EMPTY; } - bounds.inflate(((feather * 3.0).ceil() as i32).saturating_add(1)).intersect(&canvas) + let reach = i32::try_from(sel::feather_reach(feather)).unwrap_or(i32::MAX); + bounds.inflate(reach.saturating_add(1)).intersect(&canvas) } macro_rules! spec {