Skip to content

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

32-bit documents: Levels don't clip the input and output ranges (#403)

floflo7777313e0814133
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs
index 7a39527b8..bacdb8832 100644
--- a/crates/compose/src/adjust.rs
+++ b/crates/compose/src/adjust.rs
@@ -3,6 +3,7 @@
//! Formulas are documented approximations of Photoshop behaviour. Exact matching is tuned in
//! milestone M7 against Photoshop-rendered PSD composites (the oracle in `testkit`).
+use photocraft_color::SampleType;
use photocraft_color::convert::rgb_to_gray;
use photocraft_doc::Adjustment;
use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace};
@@ -68,10 +69,10 @@ pub fn apply_with(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer) {
apply_depth(adj, buf, transfer, None);
}
-/// Applies an adjustment with the document's tone transfer, on samples with `quantum` steps
-/// per unit (the document's integer depth, see `adjustment_quantum`): Levels then works on
-/// whole levels like Photoshop's (see [`levels_q`]).
-pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, quantum: Option<f32>) {
+/// Applies an adjustment with the document's tone transfer, in a document of `depth` (`None`:
+/// unrounded). Integer depths work on whole levels like Photoshop's (see [`levels_q`] and
+/// `adjustment_quantum`), 32-bit documents get its float Levels (see [`levels_float`]).
+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 } => {
@@ -119,7 +120,7 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, quant
})
}
Adjustment::Levels { space, .. } | Adjustment::Curves { space, .. } => {
- let luts = tone_luts_q(adj, quantum);
+ let luts = tone_luts_depth(adj, depth);
match space {
ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| lut(&luts[i], c[i]))),
ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(*space, &luts, c)),
@@ -248,6 +249,19 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {
}
}
+/// [`tone_luts_q`] in a document of `depth` (`None`: unrounded). 32-bit Levels use
+/// [`levels_float`], sampled on 0..1 and kept in 0..1 like every adjustment result here.
+pub fn tone_luts_depth(adj: &Adjustment, depth: Option<SampleType>) -> [Vec<f32>; 4] {
+ match (adj, depth) {
+ (Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => {
+ let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;
+ let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(c, levels_float(master, x(k))).clamp(0.0, 1.0)).collect();
+ [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()]
+ }
+ _ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)),
+ }
+}
+
/// Applies channel LUTs to a display-RGB colour in CMYK (ink brightness, 1 - ink) or Lab space,
/// through the conversions the document's surfaces use. The change is added as a difference of
/// two round trips, so channels a curve leaves alone (and out-of-gamut colours) stay exact.
@@ -525,6 +539,16 @@ pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option<f32>) -> f32 {
ch.out_black + t * (ch.out_white - ch.out_black)
}
+/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result
+/// to the output range there, and the midtone gamma is a plain power curve, mirrored below the
+/// black point (the oracle corpus' rgb32 and gray32 levels.psd: within 0.5/255, 10/255 off with
+/// the clipped curve).
+pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 {
+ let t = (v - ch.in_black) / (ch.in_white - ch.in_black).max(1e-6);
+ let t = t.signum() * t.abs().powf(1.0 / ch.gamma.max(0.01));
+ ch.out_black + t * (ch.out_white - ch.out_black)
+}
+
/// Photoshop curve: a natural cubic spline through the points (it may
/// overshoot between points, as Photoshop's does), constant outside the
/// first/last point, clamped to 0..=1, sampled into a LUT.
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 1591f953c..5ed69499d 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -1115,7 +1115,7 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
// Adjustment layers transform the backdrop, then blend the result back in.
if let LayerContent::Adjustment(adj) = &layer.content {
let mut adjusted = backdrop.clone();
- adjust::apply_depth(adj, &mut adjusted, cx.transfer, adjustment_quantum(cx.depth));
+ adjust::apply_depth(adj, &mut adjusted, cx.transfer, Some(cx.depth));
// Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result.
for c in clipped.iter().filter(|c| c.visible) {
composite_atop(c, &mut adjusted, cx);
@@ -1411,7 +1411,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let rect = base.rect;
if let LayerContent::Adjustment(adj) = &layer.content {
let mut adjusted = base.clone();
- adjust::apply_depth(adj, &mut adjusted, cx.transfer, adjustment_quantum(cx.depth));
+ adjust::apply_depth(adj, &mut adjusted, cx.transfer, Some(cx.depth));
let mv = mask_vals(layer, rect, cx);
for (i, p) in base.px.iter_mut().enumerate() {
let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i);
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 279ff063e..132181f91 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1152,6 +1152,25 @@ fn levels_work_on_whole_levels() {
}
}
+// 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.
+#[test]
+fn levels_dont_clip_in_32_bit() {
+ let ch = LevelsChannel { in_black: 15.0 / 255.0, in_white: 230.0 / 255.0, gamma: 1.3, out_black: 10.0 / 255.0, out_white: 245.0 / 255.0 };
+ let adj = Adjustment::Levels { master: ch, per_channel: Default::default(), space: Default::default(), black: LevelsChannel::default() };
+ let level = |depth, v| {
+ let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [v, v, v, 1.0]);
+ adjust::apply_depth(&adj, &mut b, adjust::Transfer::Srgb, Some(depth));
+ (b.px[0][0] * 255.0).round()
+ };
+ for (v, want) in [(0.0, 0.0), (0.0497, 3.0), (0.0976, 32.0), (0.4508, 140.0), (0.9473, 255.0), (1.0, 255.0)] {
+ assert_eq!(level(SampleType::F32, v), want, "{v}");
+ }
+ assert_eq!(level(SampleType::U8, 0.0), 10.0);
+ assert_eq!(level(SampleType::U8, 1.0), 245.0);
+}
+
// Exposure linearises RGB documents through a 2.2 power, not the sRGB curve: Photoshop lifts 76
// to 134 with an offset of 0.1738 (psd-tools adjustment_nested_composition_4).
#[test]
diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs
index e6a59339a..e4fc111c7 100644
--- a/crates/engine/src/adjust_params.rs
+++ b/crates/engine/src/adjust_params.rs
@@ -728,6 +728,24 @@ mod tests {
}
}
+ #[test]
+ fn destructive_levels_dont_clip_in_32_bit() {
+ // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in
+ // integer documents, but in a 32-bit document the curve runs on past it (then 0..1).
+ let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245});
+ for (depth, low, high) in [(8, 10.0, 245.0), (16, 10.0, 245.0), (32, 0.0, 255.0)] {
+ let mut s = crate::Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("image.adjustments.levels", params.clone()).unwrap();
+ let px = pixels(&s);
+ assert!((px[0][0] * 255.0 - low).abs() < 0.6, "black @{depth}: {:?}", px[0]);
+ assert!((px[1][0] * 255.0 - high).abs() < 0.6, "white @{depth}: {:?}", px[1]);
+ }
+ }
+
#[test]
fn cmyk_and_lab_documents_use_their_channels() {
let mut s = colourful("cmyk", 8);
diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs
index b1b2365d0..cd9c7837f 100644
--- a/crates/engine/src/pixels.rs
+++ b/crates/engine/src/pixels.rs
@@ -18,7 +18,10 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf
let raw = s.read_region(r);
let mut buf = Buffer { rect: r, px: raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)).collect() };
let orig = buf.clone();
- adjust::apply_with(adj, &mut buf, adjust::Transfer::for_document(mode, fmt.sample));
+ // 32-bit documents get the float behaviour of an adjustment layer there (Levels doesn't clip);
+ // integer depths keep the unrounded, clipped curves.
+ let depth = (fmt.sample == photocraft_color::SampleType::F32).then_some(fmt.sample);
+ adjust::apply_depth(adj, &mut buf, adjust::Transfer::for_document(mode, fmt.sample), depth);
let w = r.width() as usize;
let mut out = Vec::with_capacity(raw.len());
for (i, (a, o)) in buf.px.iter().zip(&orig.px).enumerate() {
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index 98464fab0..b087f8c6a 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -880,7 +880,7 @@ impl<'a> Planner<'a> {
}
let mut p = Pass::new(Kernel::Adjust, 0);
p.a = Some(src);
- let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, photocraft_compose::adjustment_quantum(self.cx.depth));
+ let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth);
p.adjust_kind = kind;
p.params = params;
p.lut = lut;
@@ -1427,7 +1427,7 @@ pub fn adjustment_on_gpu(adj: &Adjustment) -> bool {
}
/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`.
-pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, quantum: Option<f32>) -> Program {
+pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType) -> Program {
let mut p = [[0.0f32; 4]; 4];
match adj {
Adjustment::Invert => (1, p, None),
@@ -1460,7 +1460,9 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, quantum: Option<
(6, p, None)
}
// RGB space only (see `adjustment_on_gpu`); the rows are the CPU's channel∘master LUTs.
- Adjustment::Levels { .. } | Adjustment::Curves { .. } => (7, p, Some(adjust::tone_luts_q(adj, quantum).iter().take(3).map(|t| to_row(t)).collect())),
+ Adjustment::Levels { .. } | Adjustment::Curves { .. } => {
+ (7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect()))
+ }
Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => {
p[0] = [*hue, saturation / 100.0, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }];
if !*colorize && ranges.iter().any(|r| !r.is_neutral()) {
diff --git a/crates/io/tests/corpus.rs b/crates/io/tests/corpus.rs
index 309a4762a..4d8c28994 100644
--- a/crates/io/tests/corpus.rs
+++ b/crates/io/tests/corpus.rs
@@ -156,7 +156,7 @@ const PSD_TOOLS: Source = Source { label: "psd-tools corpus", dir: "corpus/psd-t
/// Our Photoshop-authored oracles (256 files; https://github.com/storytold/photocraft-corpus),
/// grouped by feature (`smart-filters`, `effects`, `text`, `adjustments/<mode><bits>`).
-const PHOTOSHOP: Source = Source { label: "photoshop oracles", dir: "corpus/photoshop", group_depth: 2, pass_floor: 130, roundtrip_floor: 258 };
+const PHOTOSHOP: Source = Source { label: "photoshop oracles", dir: "corpus/photoshop", group_depth: 2, pass_floor: 132, roundtrip_floor: 258 };
/// The corpus directory; a missing corpus fails the test.
fn locate(src: &Source) -> PathBuf {
diff --git a/docs/scorecard.md b/docs/scorecard.md
index bbc296966..e66ef87c9 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| Area | Done | Partial | Missing | Key numbers |
|---|---:|---:|---:|---|
| [Performance](#performance) | 3 | 22 | 12 | 46 scenarios: 3 within budget, 22 over budget or failing, 13 tracked only, 4 not run, 8 not measurable yet (baseline 2026-10-05) |
-| [File compatibility](#file-compatibility) | 1 | 8 | 18 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 130/256, round trip ≥ 258/256 |
+| [File compatibility](#file-compatibility) | 1 | 8 | 18 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 132/256, round trip ≥ 258/256 |
| [Tools](#tools) | 3 | 14 | 13 | |
| [Workspace and UI](#workspace-and-ui) | 0 | 4 | 19 | settings that do nothing: 60 of 134 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
@@ -84,7 +84,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
|---|---|---:|---:|---:|
| io corpus | `corpus/psd` | 170 | 146 | 169 |
| psd-tools corpus | `corpus/psd-tools` | 309 | 229 | 307 |
-| photoshop oracles | `corpus/photoshop` | 256 | 130 | 258 |
+| photoshop oracles | `corpus/photoshop` | 256 | 132 | 258 |
| Id | Target | Status | Issue | Note |
|---|---|---|---|---|