Skip to content

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

Threshold: split on Photoshop's luminosity of whole samples (threshold_rgb, threshold_16bits_rgb pass) (#5263)

Timothy Daly9954c2935e58
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs
index adf07006f..ca628dc6c 100644
--- a/crates/compose/src/adjust.rs
+++ b/crates/compose/src/adjust.rs
@@ -79,14 +79,7 @@ pub fn apply_with(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer) {
pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: Option<SampleType>) {
match adj {
Adjustment::Invert => map_rgb(buf, |c| [1.0 - c[0], 1.0 - c[1], 1.0 - c[2]]),
- Adjustment::Threshold { level } => {
- // Compared on the 8-bit grid like Photoshop (avoids float ties).
- let t = (level * 255.0).round();
- map_rgb(buf, |c| {
- let v = if (rgb_to_gray(c) * 255.0).round() >= t { 1.0 } else { 0.0 };
- [v; 3]
- })
- }
+ Adjustment::Threshold { level } => map_rgb(buf, |c| [if threshold_white(c, *level, depth) { 1.0 } else { 0.0 }; 3]),
Adjustment::Posterize { levels } => map_rgb(buf, |c| c.map(|v| posterize_in(v, *levels, depth))),
Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => {
// Legacy: contrast scales around 128/255, with brightness added before it when
@@ -251,6 +244,30 @@ fn legacy_brightness_contrast(brightness: f32, contrast: f32) -> impl Fn(f32) ->
move |v: f32| ((v + pre - LEGACY_PIVOT) * k + LEGACY_PIVOT + post).clamp(0.0, 1.0)
}
+/// Whether Threshold at `level` turns colour `c` white in a document of `depth` (`None`: unknown,
+/// treated as 8-bit). Photoshop splits on the luminosity 0.30 R + 0.59 G + 0.11 B (the blend
+/// modes' `lum`), not the Rec. 601 grey, of the document's whole sample values:
+/// - 8 bits: white when that luminosity, rounded to a level with halves down, reaches the level;
+/// - 16 bits: white when it reaches the level converted to 16 bits (128 → 16448);
+/// - 32 bits: white when it reaches the level.
+///
+/// Exact on every pixel of psd-tools threshold_rgb.psd, threshold_16bits_rgb.psd and
+/// threshold_16bits_grayscale.psd and of the photoshop corpus's rgb16 threshold-128.psd, where the
+/// Rec. 601 grey split 28 and 100 pixels of the first two the other way. The sums of
+/// `30 R + 59 G + 11 B` over whole samples are exact in f32 (at most 3 276 800).
+pub fn threshold_white(c: [f32; 3], level: f32, depth: Option<SampleType>) -> bool {
+ let t = (level * 255.0).round();
+ let sum = |q: f32| {
+ let [r, g, b] = c.map(|v| (v.clamp(0.0, 1.0) * q).round());
+ 30.0 * r + 59.0 * g + 11.0 * b
+ };
+ match depth {
+ None | Some(SampleType::U8) => sum(255.0) > 100.0 * t - 50.0,
+ Some(SampleType::U16) => sum(32768.0) >= 100.0 * (t * 32768.0 / 255.0).round(),
+ Some(SampleType::F32) => (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * 255.0 >= t,
+ }
+}
+
/// Applies an adjustment in a document of colour `mode`: [`apply_depth`], except that in Lab
/// and CMYK documents the adjustments Photoshop evaluates on the document's own channels do so
/// (see [`lab_channel_adjustment`] and [`cmyk_channel_adjustment`]).
@@ -1224,6 +1241,33 @@ mod tone_tests {
}
}
+ /// Pixel → Photoshop's split. 8-bit from psd-tools threshold_rgb.psd: the first three are
+ /// white though their Rec. 601 grey rounds below 60, and (131, 109, 99) sits exactly on 114.5
+ /// at level 115 (halves round down). 16-bit from threshold_16bits_rgb.psd and the photoshop
+ /// corpus's rgb16 threshold-128.psd, whose mid grey 16448 is level 128 in 16 bits.
+ #[test]
+ fn threshold_splits_on_the_luminosity_like_photoshop() {
+ let c8 = |r: u8, g: u8, b: u8| [r, g, b].map(|v| f32::from(v) / 255.0);
+ for (c, level, white) in
+ [(c8(87, 51, 31), 60u8, true), (c8(90, 49, 33), 60, true), (c8(68, 57, 50), 60, true), (c8(48, 63, 72), 60, false), (c8(131, 109, 99), 115, false)]
+ {
+ assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U8)), white, "8-bit {c:?} at {level}");
+ }
+ let c16 = |r: u16, g: u16, b: u16| [r, g, b].map(|v| f32::from(v) / 32768.0);
+ for (c, level, white) in [
+ (c16(8995, 7196, 6425), 60u8, false),
+ (c16(11180, 6554, 3984), 60, false),
+ (c16(16448, 16448, 16448), 128, true),
+ (c16(16447, 16447, 16447), 128, false),
+ ] {
+ assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U16)), white, "16-bit {c:?} at {level}");
+ }
+ // Through the adjustment: neutral black or white.
+ let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [87.0 / 255.0, 51.0 / 255.0, 31.0 / 255.0, 1.0]);
+ apply_depth(&Adjustment::Threshold { level: 60.0 / 255.0 }, &mut b, Transfer::Srgb, Some(SampleType::U8));
+ assert_eq!(b.px[0], [1.0, 1.0, 1.0, 1.0]);
+ }
+
/// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins
/// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3
/// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5.
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index cbec75da7..23985ec4e 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -623,8 +623,17 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
let p3 = op.p3;
switch op.kind {
case 1: { return 1.0 - c; } // Invert
- case 2: { // Threshold (p0.x = 8-bit level)
- return vec3(select(0.0, 1.0, round_half_up(gray(c) * 255.0) >= p0.x));
+ case 2: { // Threshold (compose::adjust::threshold_white)
+ // p0.x = 8-bit level; p0.y = 1: 8-bit levels, 2: 16-bit samples against p0.z, 0: float.
+ // Sums of 30 R + 59 G + 11 B over whole samples are exact in f32.
+ var white = lum(c) * 255.0 >= p0.x;
+ if p0.y > 0.5 {
+ let q = select(32768.0, 255.0, p0.y < 1.5);
+ let v = floor(clamp(c, vec3(0.0), vec3(1.0)) * q + 0.5);
+ let s = 30.0 * v.r + 59.0 * v.g + 11.0 * v.b;
+ white = select(s >= 100.0 * p0.z, s > 100.0 * p0.x - 50.0, p0.y < 1.5);
+ }
+ return vec3(select(0.0, 1.0, white));
}
case 3: { // Posterize (p0.x levels; p0.y = 1: 16-bit)
if p0.y > 0.5 { return vec3(posterize16(c.r, p0.x), posterize16(c.g, p0.x), posterize16(c.b, p0.x)); }
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index 636467fc5..ab11e448b 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -1597,7 +1597,13 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf
match adj {
Adjustment::Invert => (1, p, None),
Adjustment::Threshold { level } => {
- p[0][0] = (level * 255.0).round();
+ // The level, the depth's split (compose::adjust::threshold_white) and the level in 16 bits.
+ let t = (level * 255.0).round();
+ p[0] = match depth {
+ photocraft_color::SampleType::U8 => [t, 1.0, 0.0, 0.0],
+ photocraft_color::SampleType::U16 => [t, 2.0, (t * 32768.0 / 255.0).round(), 0.0],
+ photocraft_color::SampleType::F32 => [t, 0.0, 0.0, 0.0],
+ };
(2, p, None)
}
Adjustment::Posterize { levels } => {
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 7b2dfaf7c..7effa00f6 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -663,6 +663,9 @@ fn adjustment_layers() {
let pf = Adjustment::PhotoFilter { color: [0.93, 0.54, 0.0], density: 0.6, preserve_luminosity: true };
d.layers.push(Layer::new("pf", LayerContent::Adjustment(pf)));
check(&mut g, &d, &format!("photo filter {depth:?}"));
+ // Threshold: whole 16-bit samples against the level in 16 bits, or the float luminosity.
+ d.layers.push(Layer::new("th", LayerContent::Adjustment(Adjustment::Threshold { level: 0.5 })));
+ check(&mut g, &d, &format!("threshold {depth:?}"));
}
for adj in adjustments() {
for (mode, opacity, masked) in [(BlendMode::Normal, 1.0, false), (BlendMode::Multiply, 0.7, true)] {
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index 12f7c53d1..da3290c33 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 (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 (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 | 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) |
| 2026-10-13 | minor | Gradient Map adjustment layers are driven by the W3C luminosity (0.3, 0.59, 0.11), not the Rec. 601 grey: rgb8 and rgb16 gradient-map.psd pass; Photoshop-oracle floor 145 → 147 of 258 |
diff --git a/docs/gaps.md b/docs/gaps.md
index d858c67be..ffe53b373 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: 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: 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: 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 |
| 2026-10-13 | minor | G1: Gradient Map driven by the W3C luminosity (0.3, 0.59, 0.11), as Photoshop is; rgb8/rgb16 gradient-map pass; Photoshop-oracle floor 145 → 147 of 258 |