mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
PSD gradients: read the interpolation method Photoshop writes; add Smooth (#3442)
Gradient fills and gradient effects read their interpolation method from `gs99`, a key Photoshop doesn't write. Gradient fill layers saved by Photoshop 27.11 store it as the enum `gradientsInterpolationMethod` (Perc, Lnr , Smoo, Gcls), so every Perceptual, Linear or Smooth gradient opened as Classic. It shows once the fill is re-rendered (any edit): measured against Photoshop's own composite of the saved file, a black→white Linear fill was up to 74 levels off and Perceptual 31; both are now within 1. `gs99` stays as a fallback. Smooth, Photoshop's default method since 2024 (also for Gradient Map), had no model. Measured on Photoshop 27.11 (scripted gradients on three colour pairs), it runs straight across each segment in Oklab with its own easing, the same curve for every pair, and Smoothness doesn't change it. The curve fits no simple formula, so it is a 17-point measured table. Two-stop Smooth gradients are within 2 levels (Classic was 31 to 83 off); with three or four stops within 11 to 25 (Classic 48 to 106), as Smooth also smooths across stops in a way not modelled yet. Corpus: no file changes status; psd-tools effect-enums.psd (Smoo gradient effects) goes from 7.10% to 6.13% differing pixels. Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
39aa849b47
commit
9237a8bdde
3 files changed
+86
-8
No files matched your search
+34
-2
@@ -214,6 +214,13 @@ pub(crate) fn enum_of<'a>(d: &'a Descriptor, key: &str) -> Option<&'a [u8]> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's interpolation method code. Photoshop (27.11, checked by saving gradient fill
|
||||
/// layers) stores it as the enum `gradientsInterpolationMethod` (`Perc`, `Lnr `, `Smoo`, `Gcls`);
|
||||
/// `gs99` is kept as a fallback.
|
||||
pub(crate) fn gradient_method(d: &Descriptor) -> Option<&[u8]> {
|
||||
enum_of(d, "gradientsInterpolationMethod").or_else(|| enum_of(d, "gs99"))
|
||||
}
|
||||
|
||||
pub(crate) fn bool_of(d: &Descriptor, key: &str) -> bool {
|
||||
matches!(d.get(key), Some(Value::Boolean(true)))
|
||||
}
|
||||
@@ -245,7 +252,7 @@ pub(crate) fn gradient_style_value(s: GradientStyle) -> Value {
|
||||
pub(crate) type Stops = (Vec<(f32, Color)>, Vec<(f32, f32)>);
|
||||
|
||||
/// Stops of a `Grdn` descriptor, baked to Photoshop's interpolation (smoothness `Intr`, stop
|
||||
/// midpoints, and the parent's `gs99` interpolation method when given).
|
||||
/// midpoints, and the parent's interpolation method when given, see [`gradient_method`]).
|
||||
pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> Stops {
|
||||
let raw = gradient_stops_raw(grad);
|
||||
let stops = if raw.stops.len() >= 2 {
|
||||
@@ -406,7 +413,7 @@ pub fn fill_from_desc(key: &[u8; 4], d: &Descriptor) -> Option<Fill> {
|
||||
b"GdFl" => {
|
||||
let angle = num(d.get("Angl")).unwrap_or(90.0) as f32;
|
||||
let scale = num(d.get("Scl ")).map_or(1.0, |v| v as f32 / 100.0);
|
||||
let raw = get_desc(d, "Grad").map(|g| gradient_stops_editable(g, enum_of(d, "gs99")));
|
||||
let raw = get_desc(d, "Grad").map(|g| gradient_stops_editable(g, gradient_method(d)));
|
||||
let (mut stops, midpoints) = raw.map(|r| (r.stops, r.mids)).unwrap_or_default();
|
||||
// Opacity stops with Photoshop's smoothness and opacity midpoints applied (raw when
|
||||
// the interpolation is plain); none when fully opaque.
|
||||
@@ -656,6 +663,31 @@ mod tests {
|
||||
assert!(opacity_stops.is_empty());
|
||||
}
|
||||
|
||||
/// Photoshop 27.11 stores a gradient's method as the enum `gradientsInterpolationMethod`
|
||||
/// (seen in gradient fill layers saved by scripted Photoshop): a black→white Linear gradient
|
||||
/// is at 188 of 255 halfway (measured), where Classic gives 128. The key used to be read as
|
||||
/// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic.
|
||||
#[test]
|
||||
fn gradient_fill_reads_the_interpolation_method() {
|
||||
use photocraft_color::Color;
|
||||
use photocraft_doc::{Fill, GradientStyle};
|
||||
use photocraft_psd::descriptor::{Id, Value};
|
||||
let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false);
|
||||
let (k, data) = super::write_fill(&f);
|
||||
let d = super::parse_prefix_versioned(&data).unwrap();
|
||||
let mid = |code: &str| {
|
||||
let d =
|
||||
d.clone().with("gradientsInterpolationMethod", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(code) });
|
||||
let back = super::fill_from_desc(&k, &d).unwrap();
|
||||
let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap();
|
||||
(ramp.sample(0.5)[0] * 255.0).round()
|
||||
};
|
||||
assert_eq!(mid("Gcls"), 128.0);
|
||||
assert!((mid("Lnr ") - 188.0).abs() <= 1.0, "Linear: {}", mid("Lnr "));
|
||||
assert!((mid("Perc") - 99.0).abs() <= 2.0, "Perceptual: {}", mid("Perc"));
|
||||
assert!((mid("Smoo") - 99.0).abs() <= 2.0, "Smooth: {}", mid("Smoo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lab_descriptor_colours_round_trip() {
|
||||
use photocraft_color::ColorMode;
|
||||
|
||||
@@ -144,7 +144,7 @@ fn common(d: &Descriptor, blend: BlendMode, opacity: f32) -> FxCommon {
|
||||
}
|
||||
|
||||
fn gradient_from(d: &Descriptor) -> Gradient {
|
||||
let (stops, opacity_stops) = get_desc(d, "Grad").map(|g| crate::blocks::gradient_stops_with(g, enum_of(d, "gs99"))).unwrap_or_default();
|
||||
let (stops, opacity_stops) = get_desc(d, "Grad").map(|g| crate::blocks::gradient_stops_with(g, crate::blocks::gradient_method(d))).unwrap_or_default();
|
||||
let off = get_desc(d, "Ofst");
|
||||
Gradient {
|
||||
stops: if stops.is_empty() { Gradient::default().stops } else { stops },
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
//! Photoshop gradient appearance → dense linear stops.
|
||||
//!
|
||||
//! Photoshop interpolates gradient colours with a *Smoothness* setting (0–100 %) and, since the
|
||||
//! 2023 releases, an interpolation *method* (Perceptual / Linear / Classic). The compositors
|
||||
//! 2023 releases, an interpolation *method* (Smooth / Perceptual / Linear / Classic). The compositors
|
||||
//! interpolate stops linearly in sRGB, so on import we sample Photoshop's curve into dense stops.
|
||||
//! The model was fitted to Photoshop's own composites in the test corpus (clean-room, from
|
||||
//! pixels): Smoothness blends linear interpolation with a Catmull-Rom spline through the stop
|
||||
//! colours (end tangents at half the chord slope); Perceptual interpolates in Oklab, Linear in
|
||||
//! linear light, Classic in sRGB. Stop midpoints remap each segment piecewise-linearly.
|
||||
//! Smooth (Photoshop's default since 2024) goes straight across each segment in Oklab with its own
|
||||
//! easing, measured on Photoshop 27.11 (scripted gradients, sampled every 8 px on three colour
|
||||
//! pairs: the same curve for each pair, and Smoothness doesn't change it). The curve fits no simple
|
||||
//! formula, so it is kept as the measured table [`SMOOTH_EASE`].
|
||||
|
||||
use photocraft_color::{Color, ColorMode};
|
||||
|
||||
@@ -15,6 +19,7 @@ pub(crate) enum Method {
|
||||
Classic,
|
||||
Perceptual,
|
||||
Linear,
|
||||
Smooth,
|
||||
}
|
||||
|
||||
impl Method {
|
||||
@@ -22,6 +27,7 @@ impl Method {
|
||||
match code {
|
||||
Some(b"Perc") => Method::Perceptual,
|
||||
Some(b"Lnr ") => Method::Linear,
|
||||
Some(b"Smoo") => Method::Smooth,
|
||||
_ => Method::Classic,
|
||||
}
|
||||
}
|
||||
@@ -63,7 +69,7 @@ fn into_space(m: Method, rgb: [f32; 3]) -> [f32; 3] {
|
||||
match m {
|
||||
Method::Classic => rgb,
|
||||
Method::Linear => rgb.map(lin),
|
||||
Method::Perceptual => to_oklab(rgb),
|
||||
Method::Perceptual | Method::Smooth => to_oklab(rgb),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,12 +77,23 @@ fn out_of_space(m: Method, p: [f32; 3]) -> [f32; 3] {
|
||||
match m {
|
||||
Method::Classic => p.map(|v| v.clamp(0.0, 1.0)),
|
||||
Method::Linear => p.map(enc),
|
||||
Method::Perceptual => from_oklab(p),
|
||||
Method::Perceptual | Method::Smooth => from_oklab(p),
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth's progress across a segment at u = 0, 1/16, …, 1 (Photoshop 27.11, measured as the
|
||||
/// position along the Oklab line between the two stop colours).
|
||||
const SMOOTH_EASE: [f32; 17] = [0.0, 0.0438, 0.099, 0.1644, 0.2303, 0.2988, 0.3667, 0.433, 0.4974, 0.5642, 0.6302, 0.6985, 0.7656, 0.8333, 0.8945, 0.9517, 1.0];
|
||||
|
||||
fn smooth_ease(u: f32) -> f32 {
|
||||
let x = u.clamp(0.0, 1.0) * 16.0;
|
||||
let i = (x.floor() as usize).min(15);
|
||||
let (a, b) = (SMOOTH_EASE.get(i).copied().unwrap_or(0.0), SMOOTH_EASE.get(i + 1).copied().unwrap_or(1.0));
|
||||
a + (b - a) * (x - i as f32)
|
||||
}
|
||||
|
||||
/// Colour at `t` for sorted stops (positions in 0..1) in `m`'s space.
|
||||
fn eval(stops: &[(f32, [f32; 3])], mids: &[f32], smooth: f32, t: f32) -> [f32; 3] {
|
||||
fn eval(stops: &[(f32, [f32; 3])], mids: &[f32], smooth: f32, t: f32, m: Method) -> [f32; 3] {
|
||||
let n = stops.len();
|
||||
if t <= stops[0].0 {
|
||||
return stops[0].1;
|
||||
@@ -92,6 +109,10 @@ fn eval(stops: &[(f32, [f32; 3])], mids: &[f32], smooth: f32, t: f32) -> [f32; 3
|
||||
let mid = mids.get(i).copied().unwrap_or(0.5).clamp(0.05, 0.95);
|
||||
u = if u <= mid { 0.5 * u / mid } else { 0.5 + 0.5 * (u - mid) / (1.0 - mid) };
|
||||
let (p0, p1) = (stops[i].1, stops[i + 1].1);
|
||||
if m == Method::Smooth {
|
||||
let e = smooth_ease(u);
|
||||
return std::array::from_fn(|c| p0[c] + (p1[c] - p0[c]) * e);
|
||||
}
|
||||
// Catmull-Rom tangents per unit t; the ends use half the chord slope.
|
||||
let tangent = |k: usize| -> [f32; 3] {
|
||||
let (a, b) = match k {
|
||||
@@ -138,7 +159,7 @@ pub(crate) fn bake(stops: Vec<(f32, Color)>, midpoints: &[f32], smoothness: f32,
|
||||
let mut out: Vec<(f32, Color)> = (0..=N)
|
||||
.map(|k| {
|
||||
let t = k as f32 / N as f32;
|
||||
let v = eval(&pts, midpoints, smoothness.clamp(0.0, 1.0), t);
|
||||
let v = eval(&pts, midpoints, smoothness.clamp(0.0, 1.0), t, method);
|
||||
if lab {
|
||||
return (t, Color { mode: ColorMode::Lab, c: [v[0].clamp(0.0, 1.0), v[1].clamp(0.0, 1.0), v[2].clamp(0.0, 1.0), 0.0], alpha: alpha(t) });
|
||||
}
|
||||
@@ -205,6 +226,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_matches_photoshop() {
|
||||
// Photoshop 27.11, Gradient tool, Method Smooth, dither off, 256 px wide, every 32 px.
|
||||
type Row = (&'static str, [f32; 3], [f32; 3], [[u8; 3]; 8]);
|
||||
let measured: [Row; 2] = [
|
||||
("black→white", [0.0; 3], [1.0; 3], [[0; 3], [4; 3], [29; 3], [63; 3], [99; 3], [137; 3], [179; 3], [221; 3]]),
|
||||
(
|
||||
"red→blue",
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0],
|
||||
[[255, 0, 0], [232, 51, 67], [202, 71, 105], [171, 81, 136], [140, 83, 162], [109, 80, 188], [76, 69, 213], [41, 49, 236]],
|
||||
),
|
||||
];
|
||||
for (name, a, b, want) in measured {
|
||||
let s = bake(vec![(0.0, Color::rgb(a[0], a[1], a[2])), (1.0, Color::rgb(b[0], b[1], b[2]))], &[0.5], 1.0, Method::Smooth);
|
||||
for (k, w) in want.iter().enumerate() {
|
||||
let x = k * 32;
|
||||
let got = at(&s, (x as f32 + 0.5) / 256.0).map(|v| (v * 255.0).round() as i32);
|
||||
for c in 0..3 {
|
||||
assert!((got[c] - i32::from(w[c])).abs() <= 2, "{name} x {x}: {got:?} vs Photoshop {w:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_lab_stops_interpolate_in_lab() {
|
||||
// Lab documents blend Classic gradients in L*a*b* (psd-tools 4x4_16bit_lab): the half-way
|
||||
|
||||
Reference in new issue
Block a user