Skip to content

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

Masks: feathers blur with exactly the feather's variance (mask-parameters-no-real-channel passes) (#5163)

Timothy Dalyeb26e8f0d7bc
diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs
index d70947ec7..8323e1b93 100644
--- a/crates/compose/src/masks.rs
+++ b/crates/compose/src/masks.rs
@@ -171,9 +171,10 @@ fn key(layer: &Layer, canvas: Rect) -> u64 {
h.finish()
}
-/// Gaussian sigma of a mask feather of `px` pixels (Properties › Feather). Fitted on the
-/// psd-tools corpus (layer_mask_data.psd, mask-parameters-no-real-channel.psd: sigma = feather
-/// beats 0.33, 0.5, 0.7, 1.3 and 1.6 times it).
+/// Gaussian sigma of a mask feather of `px` pixels (Properties › Feather): the feather itself.
+/// Blurred with exactly that variance, psd-tools mask-parameters-no-real-channel.psd (6 px vector
+/// and 3 px pixel feather) matches Photoshop within 1.5 levels and layer_mask_data.psd's
+/// feathered edges are 27 % → 4 % off (the rest are its shapes' antialiased edges).
pub fn feather_sigma(px: f32) -> f32 {
if px.is_finite() { (px * FEATHER_SIGMA).clamp(0.0, MAX_FEATHER_SIGMA) } else { 0.0 }
}
@@ -188,37 +189,73 @@ pub fn has_feather(layer: &Layer) -> bool {
|| layer.vector_mask.as_ref().is_some_and(|v| v.enabled && feather_sigma(v.feather) > 0.0)
}
+/// One box pass: weight 1 on `±r` around each sample and `end` (0..1) on the two samples just
+/// beyond, so the pass's variance is any real number, not only the `r(r+1)/3` of whole boxes.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct BoxPass {
+ r: usize,
+ end: f32,
+}
+
+impl BoxPass {
+ /// The pass whose three-fold repetition has variance `sigma²` (an "extended box", Gwosdek et
+ /// al. 2011), or `None` when there is nothing to blur.
+ fn for_sigma(sigma: f32) -> Option<BoxPass> {
+ if !sigma.is_finite() || sigma <= 0.0 {
+ return None;
+ }
+ // Feathers top out at 1000 px; the cap keeps the radius arithmetic far from overflow.
+ let v = f64::from(sigma.min(MAX_FEATHER_SIGMA)).powi(2) / 3.0;
+ // The largest whole radius whose box variance r(r+1)/3 is at most v.
+ let mut r = (((12.0 * v + 1.0).sqrt() - 1.0) / 2.0).floor().max(0.0) as usize;
+ let var = |r: usize| (r as f64) * (r as f64 + 1.0) / 3.0;
+ while r > 0 && var(r) > v {
+ r -= 1;
+ }
+ while var(r + 1) <= v {
+ r += 1;
+ }
+ let (rf, n) = (r as f64, 2.0 * r as f64 + 1.0);
+ let end = (n * (rf * (rf + 1.0) / 3.0 - v)) / (2.0 * v - 2.0 * (rf + 1.0) * (rf + 1.0));
+ Some(BoxPass { r, end: end.clamp(0.0, 1.0) as f32 })
+ }
+}
+
/// Apply one of the three box passes to a single line. `scratch` preserves the input while
/// the sliding sum writes the output, matching the previous sequential implementation exactly.
-fn blur_line(line: &mut [f32], scratch: &mut [f32], r: usize) {
+fn blur_line(line: &mut [f32], scratch: &mut [f32], pass: BoxPass) {
if line.is_empty() {
return;
}
- let Ok(radius) = isize::try_from(r) else { return };
+ let Ok(radius) = isize::try_from(pass.r) else { return };
scratch.copy_from_slice(line);
let get = |i: isize| scratch[i.clamp(0, scratch.len() as isize - 1) as usize];
let mut acc: f32 = (-radius..=radius).map(get).sum();
- let n = (2 * r + 1) as f32;
+ let n = (2 * pass.r + 1) as f32 + 2.0 * pass.end;
+ // The sample leaving the window is the next one's low end weight.
+ let mut below = get(-radius - 1);
for (i, dst) in line.iter_mut().enumerate() {
- *dst = acc / n;
let i = i as isize;
- acc += get(i + radius + 1) - get(i - radius);
+ let (above, leaving) = (get(i + radius + 1), get(i - radius));
+ *dst = (acc + pass.end * (below + above)) / n;
+ acc += above - leaving;
+ below = leaving;
}
}
/// Apply three clamped box passes to independent contiguous rows. Scoped OS threads are used
/// instead of Rayon because mask construction can happen inside a Rayon tile job; nested Rayon
/// work here can deadlock when every worker waits on the same OnceLock (#276).
-fn blur_rows_chunk(v: &mut [f32], w: usize, r: usize) {
+fn blur_rows_chunk(v: &mut [f32], w: usize, pass: BoxPass) {
let mut scratch = vec![0.0; w];
for row in v.chunks_mut(w) {
for _ in 0..3 {
- blur_line(row, &mut scratch, r);
+ blur_line(row, &mut scratch, pass);
}
}
}
-fn blur_rows(v: &mut [f32], w: usize, r: usize) {
+fn blur_rows(v: &mut [f32], w: usize, pass: BoxPass) {
if w == 0 || v.is_empty() {
return;
}
@@ -229,14 +266,14 @@ fn blur_rows(v: &mut [f32], w: usize, r: usize) {
std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16).min(h.max(1))
};
if threads == 1 {
- blur_rows_chunk(v, w, r);
+ blur_rows_chunk(v, w, pass);
return;
}
let rows_per_worker = h.div_ceil(threads);
let chunk_len = rows_per_worker.saturating_mul(w);
std::thread::scope(|scope| {
for chunk in v.chunks_mut(chunk_len) {
- scope.spawn(move || blur_rows_chunk(chunk, w, r));
+ scope.spawn(move || blur_rows_chunk(chunk, w, pass));
}
});
}
@@ -256,35 +293,34 @@ fn transpose_into(v: &[f32], out: &mut [f32], w: usize, h: usize) {
}
}
-/// Approximate Gaussian blur of a `w`×`h` plane: three box passes per axis (edges clamp, which
-/// is exact here since the planes extend into constant mask regions). The axes are processed in
-/// parallel on bounded OS threads, preserving each line's floating-point operation order.
+/// Approximate Gaussian blur of a `w`×`h` plane: three box passes per axis whose variance is
+/// exactly `sigma²` ([`BoxPass`]; edges clamp, which is exact here since the planes extend into
+/// constant mask regions). Whole-pixel boxes rounded the variance (a 6 px feather blurred like
+/// 6.48 px, a 3 px one like 3.46) and missed Photoshop's feathered edges by up to 4 levels
+/// (psd-tools mask-parameters-no-real-channel.psd); the exact variance is within 1.5. The axes
+/// are processed in parallel on bounded OS threads, preserving each line's floating-point
+/// operation order.
fn gaussian(v: &mut [f32], w: usize, h: usize, sigma: f32) {
- if sigma <= 0.0 || w == 0 || h == 0 || v.len() != w.saturating_mul(h) {
- return;
- }
- // Box widths whose three-pass variance matches sigma² (Wells 1986 / Kovesi).
- let ideal = (12.0 * sigma * sigma / 3.0 + 1.0).sqrt();
- let r = (((ideal.floor() as usize) | 1).max(1) - 1) / 2;
- if r == 0 {
+ if w == 0 || h == 0 || v.len() != w.saturating_mul(h) {
return;
}
+ let Some(pass) = BoxPass::for_sigma(sigma) else { return };
// Reserve before modifying the input so allocation failure can use the sequential fallback
// without leaving a half-blurred mask.
let mut transposed = Vec::new();
if transposed.try_reserve_exact(v.len()).is_err() {
- gaussian_sequential(v, w, h, r);
+ gaussian_sequential(v, w, h, pass);
return;
}
transposed.resize(v.len(), 0.0);
- blur_rows(v, w, r);
+ blur_rows(v, w, pass);
transpose_into(v, &mut transposed, w, h);
- blur_rows(&mut transposed, h, r);
+ blur_rows(&mut transposed, h, pass);
transpose_into(&transposed, v, h, w);
}
/// Allocation-light reference path used if parallel transpose storage cannot be reserved.
-fn gaussian_sequential(v: &mut [f32], w: usize, h: usize, r: usize) {
+fn gaussian_sequential(v: &mut [f32], w: usize, h: usize, pass: BoxPass) {
let mut line = Vec::new();
let mut scratch = Vec::new();
let len = w.max(h);
@@ -300,7 +336,7 @@ fn gaussian_sequential(v: &mut [f32], w: usize, h: usize, r: usize) {
line[i] = if axis { v[i * w + k] } else { v[k * w + i] };
}
for _ in 0..3 {
- blur_line(&mut line[..line_len], &mut scratch[..line_len], r);
+ blur_line(&mut line[..line_len], &mut scratch[..line_len], pass);
}
for i in 0..line_len {
if axis {
@@ -693,14 +729,55 @@ mod tests {
}
}
+ /// Three passes have the variance sigma² exactly, for whole and fractional sigmas alike (whole
+ /// boxes rounded a 6 px feather to 6.48 and a 3 px one to 3.46).
+ #[test]
+ fn feather_blur_has_the_exact_variance() {
+ for sigma in [0.3f32, 1.0, 2.6, 3.0, 6.0, 13.7, 40.0] {
+ let (w, c) = (801usize, 400usize);
+ let mut v = vec![0.0f32; w];
+ v[c] = 1.0;
+ gaussian(&mut v, w, 1, sigma);
+ // Within the kernel's reach (the running sums leave ~1e-8 behind further out).
+ let reach = (8.0 * sigma) as usize + 4;
+ let var: f64 = v.iter().enumerate().skip(c - reach).take(2 * reach + 1).map(|(i, &x)| f64::from(x) * ((i as f64) - c as f64).powi(2)).sum();
+ assert!((var.sqrt() - f64::from(sigma)).abs() < 1e-3 * f64::from(sigma).max(1.0), "sigma {sigma}: {}", var.sqrt());
+ assert!((v.iter().sum::<f32>() - 1.0).abs() < 1e-4, "sigma {sigma} keeps the total");
+ }
+ assert_eq!(BoxPass::for_sigma(0.0), None);
+ assert_eq!(BoxPass::for_sigma(f32::NAN), None);
+ assert!(BoxPass::for_sigma(f32::MAX).is_some_and(|p| p.r < 2000 && (0.0..1.0).contains(&p.end)));
+ }
+
+ /// A feathered edge follows the Gaussian Photoshop draws with sigma = feather: psd-tools
+ /// mask-parameters-no-real-channel.psd (a 6 px vector and 3 px pixel feather) matches it
+ /// within 1.5 levels, where whole-pixel boxes were 4 off.
+ #[test]
+ fn a_feathered_edge_is_a_gaussian_step() {
+ // erf, Abramowitz & Stegun 7.1.26 (1.5e-7).
+ let erf = |x: f64| {
+ let t = 1.0 / (1.0 + 0.327_591_1 * x.abs());
+ let y = 1.0 - (((((1.061_405_429 * t - 1.453_152_027) * t) + 1.421_413_741) * t - 0.284_496_736) * t + 0.254_829_592) * t * (-x * x).exp();
+ y.copysign(x)
+ };
+ let (w, edge, sigma) = (240usize, 120usize, 6.0f32);
+ let mut v: Vec<f32> = (0..w).map(|i| if i >= edge { 1.0 } else { 0.0 }).collect();
+ gaussian(&mut v, w, 1, sigma);
+ for (i, &got) in v.iter().enumerate().skip(edge - 24).take(48) {
+ let d = (i as f64 - (edge as f64 - 0.5)) / f64::from(sigma);
+ let want = 0.5 * (1.0 + erf(d / std::f64::consts::SQRT_2));
+ // Three boxes are not quite a Gaussian: within 2.5 levels (whole boxes: 4.6).
+ assert!((f64::from(got) - want).abs() < 0.01, "{i}: {got} vs Gaussian {want}");
+ }
+ }
+
#[test]
fn parallel_gaussian_matches_the_sequential_reference() {
let (w, h, sigma): (usize, usize, f32) = (320, 256, 13.0);
let mut parallel: Vec<_> = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect();
let mut sequential = parallel.clone();
- let ideal = (12.0 * sigma * sigma / 3.0 + 1.0).sqrt();
- let r = (((ideal.floor() as usize) | 1).max(1) - 1) / 2;
- gaussian_sequential(&mut sequential, w, h, r);
+ let pass = BoxPass::for_sigma(sigma).unwrap();
+ gaussian_sequential(&mut sequential, w, h, pass);
gaussian(&mut parallel, w, h, sigma);
assert_eq!(parallel, sequential, "parallel blur must retain the exact per-line arithmetic");
}
@@ -711,12 +788,11 @@ mod tests {
use std::time::Instant;
let (w, h, sigma): (usize, usize, f32) = (6336, 7920, 1000.0);
- let ideal = (12.0 * sigma * sigma / 3.0 + 1.0).sqrt();
- let r = (((ideal.floor() as usize) | 1).max(1) - 1) / 2;
+ let pass = BoxPass::for_sigma(sigma).unwrap();
let source: Vec<_> = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect();
let mut sequential = source.clone();
let start = Instant::now();
- gaussian_sequential(&mut sequential, w, h, r);
+ gaussian_sequential(&mut sequential, w, h, pass);
let sequential_time = start.elapsed();
let mut parallel = source;
let start = Instant::now();
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index da3290c33..2108cfd86 100644
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@ -1,6 +1,6 @@
# File-format parity
-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write
@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-13 | minor | Mask feathers blur with exactly the feather's variance (three extended boxes; whole-pixel boxes rounded 6 px to 6.48): psd-tools mask-parameters-no-real-channel passes, layer_mask_data 27 % → 4 % off; psd-tools floor → 240 of 309 (main 239) |
| 2026-10-13 | minor | Threshold splits on the luminosity 0.30 R + 0.59 G + 0.11 B of whole samples, as Photoshop does (8-bit: rounded to a level, halves down; 16-bit: against the level in 16 bits), not the Rec. 601 grey: psd-tools threshold_rgb and threshold_16bits_rgb pass; psd-tools floor → 241 of 309 (main 239) |
| 2026-10-13 | minor | A pass-through group that is the base of a clipping group and holds an adjustment layer renders isolated, as Photoshop does (its blend modes still reach the backdrop): psd-tools passthrough_clipping_mask_adjustment passes (was 50 % of pixels off); psd-tools floor → 240 of 309 (main 239) |
| 2026-10-13 | minor | 16-bit Posterize bins the 16-bit sample and lands on 8-bit levels through a 16-bit step, as Photoshop does (RGB, Grayscale and the CMYK/Lab channel path): psd-tools posterize_16bits_rgb and posterize_16bits_grayscale pass; psd-tools floor → 241 of 309 (main 239) |
diff --git a/docs/gaps.md b/docs/gaps.md
index ffe53b373..5eca7bd6f 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-13 · **Change:** minor (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) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (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) · **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
@@ -262,6 +262,7 @@ what an agent can't finish alone.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-13 | minor | G1: mask feathers blur with exactly the feather's variance; psd-tools mask-parameters-no-real-channel passes, layer_mask_data 27 % → 4 % off; psd-tools floor → 240 of 309 |
| 2026-10-13 | minor | G1: Threshold splits on Photoshop's luminosity of whole samples (8- and 16-bit rules exact on four oracles); psd-tools threshold_rgb and threshold_16bits_rgb pass; psd-tools floor → 241 of 309 |
| 2026-10-13 | minor | G1: a pass-through group that is a clipping base and holds an adjustment layer renders isolated; psd-tools passthrough_clipping_mask_adjustment passes; psd-tools floor → 240 of 309 |
| 2026-10-13 | minor | G1: 16-bit Posterize bins the 16-bit sample, as Photoshop does (exact on two oracles); psd-tools floor → 241 of 309 |