Skip to content

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

Levels: whole levels at every step and Photoshop's shadow toe (levels_rgb + stack oracle pass) (#5143)

Timothy Dalyd24f6e9d5fac
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs
index 07b3dfa93..673178c68 100644
--- a/crates/compose/src/adjust.rs
+++ b/crates/compose/src/adjust.rs
@@ -943,39 +943,53 @@ pub fn levels(ch: &LevelsChannel, v: f32) -> f32 {
}
/// [`levels`] on samples with `quantum` steps per unit (8-bit: 255). Photoshop works on whole
-/// levels: the input is a level, and the input-range stretch is rounded (half up) to a whole
-/// level before the midtone gamma, so a 44..214 range maps 45, 46, 47, 48 → 1.5, 3, 4.5, 6 →
-/// 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the steps). In a LUT
-/// the result is a staircase that is exact at every level.
+/// levels in three steps, each rounded half up to a whole level: the input-range stretch, the
+/// midtone gamma ([`levels_gamma`]) and the output range. So a 44..214 range maps 45, 46, 47, 48
+/// → 1.5, 3, 4.5, 6 → 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the
+/// steps), and an output range narrower than 0..255 maps neighbouring gamma levels to one level
+/// (psd-tools levels_rgb: 43..48 → 58 through a 0.47 channel gamma and the master's 48..255).
+/// In a LUT the result is a staircase that is exact at every level.
pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option<f32>) -> f32 {
let range = (ch.in_white - ch.in_black).max(1e-6);
- let u = match quantum.filter(|q| q.is_finite() && *q >= 1.0) {
+ let quantum = quantum.filter(|q| q.is_finite() && *q >= 1.0);
+ let whole = |x: f32| match quantum {
+ Some(q) => (x * q + 0.5).floor() / q,
+ None => x,
+ };
+ let u = match quantum {
Some(q) => {
let v = (v * q).round() / q;
(((v - ch.in_black) / range).clamp(0.0, 1.0) * q + 0.5 + 1e-3).floor() / q
}
None => ((v - ch.in_black) / range).clamp(0.0, 1.0),
};
- let g = ch.gamma.max(0.01);
- let t = if g > 1.0 {
- // A midtone gamma > 1 lifts shadows, and a pure `u^(1/g)` has infinite slope at black —
- // which Photoshop bounds, giving a soft shadow toe (initial slope ≈ 2^gamma, verified against
- // the real app). Soft-min (p-norm) of the power curve with that line; reduces to the exact
- // power curve in the body, so highlights are unchanged. gamma <= 1 is untouched. Slope and
- // sharpness fitted on whole-level input (`levels_q`): a 0..255 ramp at gamma 2.0 and
- // psd-tools levels_grayscale's gamma 1.78 (within one level of Photoshop on both).
- let power = u.powf(1.0 / g);
- let line = 0.93 * 2.0f32.powf(g) * u;
- if power <= 1e-6 || line <= 1e-6 {
- power.min(line)
- } else {
- let p = 10.0; // p-norm sharpness, fit to Photoshop ground truth
- (power.powf(-p) + line.powf(-p)).powf(-1.0 / p)
- }
- } else {
- u.powf(1.0 / g)
- };
- ch.out_black + t * (ch.out_white - ch.out_black)
+ let t = whole(levels_gamma(u, ch.gamma.max(0.01)));
+ whole(ch.out_black + t * (ch.out_white - ch.out_black))
+}
+
+/// Exponent of the shadow toe in [`levels_gamma`] (fitted; see there).
+const LEVELS_TOE_POWER: f32 = 2.2;
+
+/// Levels' midtone gamma `g` on `u` in 0..1: `u^(1/g)`, except that above 1, where that power
+/// curve is infinitely steep at black, Photoshop starts along a toe `a·u − b·u^q` of slope
+/// `a = 2^g` that joins the curve with the same value and slope. `q` = [`LEVELS_TOE_POWER`] is
+/// fitted on whole-level oracles at gamma 1.16, 1.22, 1.3, 1.78 and 2.0 (psd-tools levels_rgb
+/// and levels_grayscale, the photoshop corpus's rgb8 and gray8 levels.psd, a measured 0..255
+/// ramp): all but 2 of their 1118 levels exact, the others within one. Below 1 the power curve is
+/// exact (gamma 0.67 and 0.7: every level).
+pub fn levels_gamma(u: f32, g: f32) -> f32 {
+ let c = 1.0 / g;
+ if g <= 1.0 {
+ return u.powf(c);
+ }
+ let (a, q) = (2f32.powf(g), LEVELS_TOE_POWER);
+ // Where the toe meets the curve: a·u1 − b·u1^q = u1^c and a − q·b·u1^(q−1) = c·u1^(c−1).
+ let u1 = ((1.0 - c / q) / (a * (1.0 - 1.0 / q))).powf(1.0 / (1.0 - c));
+ if u >= u1 || u1 <= 0.0 {
+ return u.powf(c);
+ }
+ let b = (a * u1 - u1.powf(c)) / u1.powf(q);
+ a * u - b * u.powf(q)
}
/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 328bada00..a2f1e617e 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1748,7 +1748,7 @@ fn modern_brightness_matches_photoshop() {
}
// Levels ground truth from Adobe Photoshop 2026 (adjustLevels on a 0..255 ramp). Verifies our
-// `levels()` matches the real app, including the gamma>1 soft shadow toe (initial slope 2^gamma).
+// `levels()` matches the real app, including the gamma>1 shadow toe (initial slope 2^gamma).
#[test]
fn levels_matches_photoshop() {
let ident = |g: f32| LevelsChannel { in_black: 0.0, in_white: 1.0, gamma: g, out_black: 0.0, out_white: 1.0 };
@@ -1764,8 +1764,8 @@ fn levels_matches_photoshop() {
let want = ((x as f32 / 255.0).powi(2) * 255.0).round();
assert_eq!(got, want, "levels gamma 0.5 x={x}");
}
- // Endpoints pinned; identity is identity. (The gamma>1 toe's soft-min leaves white within a
- // few parts in 1e5 of 1.0 — invisible at any bit depth; exact at 8-bit.)
+ // Endpoints pinned; identity is identity. (The gamma>1 toe ends before white, so white
+ // stays exactly 1.0.)
assert_eq!(adjust::levels(&ident(2.5), 0.0), 0.0);
assert_eq!((adjust::levels(&ident(2.5), 1.0) * 255.0).round(), 255.0);
assert!((adjust::levels(&ident(2.5), 1.0) - 1.0).abs() < 5e-4);
@@ -1806,6 +1806,86 @@ fn levels_work_on_whole_levels() {
}
}
+// Every Levels step lands on a whole level in 8 bits, and the gamma's shadow toe starts at
+// slope 2^gamma (`adjust::levels_gamma`). Level → Photoshop's level, exact, from:
+// - psd-tools levels_rgb.psd, Levels 2 (each channel, then the master): master 0..213, gamma
+// 1.22, output 48..255; R gamma 0.47 to 0..194; B 61..255, gamma 0.47, to 0..213. Narrow
+// output ranges merge neighbouring levels (R 43..48 → 58, G 8, 9 → 63, B 89, 90 → 54).
+// - the photoshop corpus's rgb8 levels.psd: master 15..230, gamma 1.3, output 10..245.
+// - psd-tools levels_grayscale.psd, Levels 3: 44..214, gamma 1.78 (52 → 37 is one level off).
+#[test]
+fn levels_steps_match_photoshop() {
+ let ch = |ib: f32, iw: f32, gamma: f32, ob: f32, ow: f32| LevelsChannel {
+ in_black: ib / 255.0,
+ in_white: iw / 255.0,
+ gamma,
+ out_black: ob / 255.0,
+ out_white: ow / 255.0,
+ };
+ let id = LevelsChannel::default();
+ let levels = |master: LevelsChannel, per_channel: [LevelsChannel; 3]| Adjustment::Levels {
+ master,
+ per_channel,
+ space: Default::default(),
+ black: LevelsChannel::default(),
+ };
+ let run = |adj: &Adjustment, xs: &[u8]| {
+ let px = xs.iter().map(|&x| f32::from(x) / 255.0).map(|v| [v, v, v, 1.0]).collect();
+ let mut b = Buffer { rect: Rect::new(0, 0, xs.len() as i32, 1), px };
+ adjust::apply_depth(adj, &mut b, adjust::Transfer::Srgb, Some(SampleType::U8));
+ b.px
+ };
+ let rgb = levels(ch(0.0, 213.0, 1.22, 48.0, 255.0), [ch(0.0, 255.0, 0.47, 0.0, 194.0), id.clone(), ch(61.0, 255.0, 0.47, 0.0, 213.0)]);
+ let xs = [2, 8, 9, 15, 16, 43, 45, 48, 55, 61, 72, 79, 84, 89, 90, 101, 106, 120, 150, 180, 200];
+ let want: [[u8; 21]; 3] = [
+ [48, 48, 48, 50, 50, 58, 58, 58, 63, 63, 69, 72, 76, 79, 79, 86, 89, 100, 123, 153, 174],
+ [51, 63, 63, 72, 72, 103, 106, 109, 116, 122, 133, 141, 145, 149, 150, 160, 165, 178, 204, 228, 244],
+ [48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 50, 51, 54, 54, 54, 63, 63, 76, 102, 136, 164],
+ ];
+ for (k, p) in run(&rgb, &xs).iter().enumerate() {
+ for c in 0..3 {
+ assert_eq!((p[c] * 255.0).round(), f32::from(want[c][k]), "levels_rgb channel {c} at {}", xs[k]);
+ }
+ }
+ let single = |c: LevelsChannel| levels(c, [id.clone(), id.clone(), id.clone()]);
+ let oracles: [(Adjustment, &[u8], &[u8]); 2] = [
+ (
+ single(ch(15.0, 230.0, 1.3, 10.0, 245.0)),
+ &[0, 21, 22, 49, 82, 118, 154, 176, 195, 215, 235, 251],
+ &[10, 25, 27, 66, 106, 144, 178, 198, 215, 232, 245, 245],
+ ),
+ (
+ single(ch(44.0, 214.0, 1.78, 0.0, 255.0)),
+ &[44, 45, 46, 47, 48, 49, 50, 51, 53, 55, 57, 60, 65, 70, 80, 100, 150, 200, 214],
+ &[0, 7, 10, 17, 20, 26, 29, 35, 43, 51, 58, 66, 79, 89, 107, 137, 196, 243, 255],
+ ),
+ ];
+ for (adj, xs, want) in &oracles {
+ for ((p, x), w) in run(adj, xs).iter().zip(*xs).zip(*want) {
+ assert_eq!((p[0] * 255.0).round(), f32::from(*w), "levels at {x}");
+ }
+ }
+}
+
+// The shadow toe stays a well-behaved curve for any gamma: from 0 to 1, rising, and without a
+// jump where it meets the power curve.
+#[test]
+fn levels_gamma_toe_is_monotone_for_any_gamma() {
+ for g in [1.0001, 1.05, 1.5, 3.0, 9.99, 1e6, f32::INFINITY] {
+ let mut last = 0.0f32;
+ for k in 0..=4096 {
+ let u = k as f32 / 4096.0;
+ let t = adjust::levels_gamma(u, g);
+ assert!(t.is_finite() && (0.0..=1.0 + 1e-6).contains(&t), "gamma {g} at {u}: {t}");
+ assert!(t >= last - 1e-6, "gamma {g} falls at {u}: {last} -> {t}");
+ // Never steeper than the toe's initial slope 2^g.
+ assert!(k == 0 || t - last <= 2f32.powf(g) / 4096.0 + 1e-4, "gamma {g} jumps at {u}: {last} -> {t}");
+ last = t;
+ }
+ assert!((adjust::levels_gamma(1.0, g) - 1.0).abs() < 1e-6, "gamma {g}: white");
+ }
+}
+
// The oracle corpus' rgb32 levels.psd: input 15..230, gamma 1.3, output 10..245. In a
// 32-bit document neither range clips and the gamma is a plain power curve mirrored below black:
// 0.0497 → 3 (the clipped curve gives 10), 0.9473 → 255 (245). Integer documents still clip.
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index 5931f5c6e..598eca008 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 (32-bit adjustments unclipped; Photoshop-oracle floor 149/258; 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
+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; 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 | Levels round the gamma and output steps to whole levels too (8-bit), and the gamma above 1 starts along a toe of slope 2^gamma that joins the power curve: psd-tools levels_rgb and rgb8 stack-levels-curves-hue-posterize pass, rgb8/gray8 levels.psd exact; Photoshop-oracle floor 145 → 146 of 258, psd-tools 236 → 238 of 309 |
| 2026-10-13 | minor | 32-bit documents: legacy Brightness/Contrast, Channel Mixer, Photo Filter and the Black & White tint keep values above 1 and below 0 as Photoshop does (rgb32/gray32 brightness-contrast-legacy, rgb32 channel-mixer and black-white-tint pass); Photoshop-oracle floor 145 → 149 of 258 |
| 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) |
diff --git a/docs/gaps.md b/docs/gaps.md
index 2cfa3f07e..6af065862 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 (G11: Batch Include All Subfolders landed; 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) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (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) · **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
@@ -92,8 +92,8 @@ what an agent can't finish alone.
- **2026-10-13 evidence:** Batch supports [output naming templates](batch-naming.md) using
`{name}`, `{serial}` and a captured UTC `{date}`, with a starting serial number. Colliding
names remain errors; custom output names cannot replace inputs. AUTO-219-5 stays partial.
-- **Missing:** document-independent action recording (AUTO-219-1), Batch open-document inputs, progress/cancel and an error-log file
- (AUTO-219-5; Include All Subfolders landed 2026-10-11, #3753), ExtendScript/UXP compatibility. `.atn` steps outside the
+- **Missing:** document-independent action recording (AUTO-219-1), Batch recursion, open-document inputs, progress/cancel and an error-log file
+ (AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside the
mapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,
Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop steps
that fail at playback by name.
@@ -262,6 +262,7 @@ what an agent can't finish alone.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-13 | minor | G1: Levels round every step to whole levels and use Photoshop's shadow toe (slope 2^gamma); levels_rgb and stack-levels-curves-hue-posterize pass; Photoshop-oracle floor 145 → 146 of 258, psd-tools 236 → 238 of 309 |
| 2026-10-13 | minor | G1: 32-bit legacy Brightness/Contrast (pivot 127), Channel Mixer (1/1024 steps, constant ×255/512), Photo Filter and Black & White tint unclipped as Photoshop computes them, CPU and GPU; Photoshop-oracle floor 145 → 149 of 258 |
| 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 |
@@ -286,7 +287,6 @@ what an agent can't finish alone.
| 2026-10-11 | minor | G13: Czech dynamic UI text localized; engine messages and native review remain open |
| 2026-10-11 | minor | G8: triple/quadruple/five-click type selection done (TYPE-218-8, #3493); Type evidence recounted |
| 2026-10-11 | minor | G8: Character panel OpenType buttons landed (TYPE-218-5, #3752); Numerals and Stylistic Sets submenus still missing |
-| 2026-10-11 | minor | G11: Batch and Image Processor gained Include All Subfolders (AUTO-219-5 stays partial; #3753) |
| 2026-10-10 | minor | G2: recorded Tilt-Shift computation/filtered-proxy measurements and limits; gap and estimate remain open |
| 2026-10-10 | minor | Checked against the alpha gate (no alpha blockers); #2374 marked closed |
| 2026-10-10 | major | First version, from the full re-measure against Photoshop 2026 27.11.0 and the open issues |