Merge pull request #12644 from x-labb/fix-12010-gradient-alpha-method

fix(engine): a gradient's transparency follows the interpolation method (#12010)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-13 09:38:21 +01:00
commit dd444f859e
6 files changed
+253 -15

No files matched your search

+2
View File
@@ -100,6 +100,8 @@ pub mod frame_cmds;
pub mod fx_view_cmds;
pub mod fx_visibility_cmds;
pub mod gallery_cmds;
#[cfg(test)]
mod gradient_alpha_method_tests;
pub mod gradient_fill_cmds;
pub mod group_view_cmds;
pub mod history_cmds;
@@ -0,0 +1,118 @@
//! #12010: the transparency of a gradient drawn with the Gradient tool follows the interpolation
//! method (Smooth by default) instead of a straight line. Reference: Foreground to Transparent,
//! Smooth, dragged (100, 300) to (700, 300): alpha 255 / 179 / 100 / 35 / 0 at x 50 / 250 / 400 /
//! 550 / 750.
use serde_json::{Value, json};
use crate::Session;
fn drawn(extra: Value) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap();
let mut p = json!({"gradient": "Foreground to Transparent", "from": [100, 300], "to": [700, 300], "dither": false});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("paint.gradient", p).unwrap();
s
}
fn alpha_at(s: &Session, x: i32) -> f32 {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!("a pixel layer") };
surface.pixel(x, 300)[3] * 255.0
}
#[test]
fn smooth_transparency_ramp_matches_the_reference() {
let s = drawn(json!({"method": "smooth"}));
for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn without_a_method_the_ramp_stays_straight() {
let s = drawn(json!({}));
for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn opaque_gradients_paint_the_same_with_a_method() {
let paint = |extra: Value| {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 8, "background": "white"})).unwrap();
let mut p = json!({"colors": ["#000000", "#ffffff"], "from": [0, 4], "to": [64, 4], "dither": false});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("paint.gradient", p).unwrap();
(0..64).map(|x| alpha_and_red(&s, x)).collect::<Vec<_>>()
};
fn alpha_and_red(s: &Session, x: i32) -> Vec<f32> {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!() };
surface.pixel(x, 4)
}
// The colours still follow the method; the alpha stays opaque.
let smooth = paint(json!({"method": "smooth"}));
assert!(smooth.iter().all(|p| (p[3] - 1.0).abs() < 1e-3));
assert_ne!(smooth, paint(json!({})));
}
// Not measured in the Gradient tool: the other methods, and Smooth below 100 % Smoothness, keep
// today's merged stops (each dense stop takes the nearest stop's alpha).
#[test]
fn unmeasured_methods_and_smoothness_keep_todays_ramp() {
for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] {
let s = drawn(extra.clone());
for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}");
}
}
}
fn drawn_colors(colors: Value) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap();
let p = json!({"colors": colors, "transparency": [[0, 100], [1, 0]], "method": "smooth", "from": [100, 300], "to": [700, 300], "dither": false});
s.execute("paint.gradient", p).unwrap();
s
}
#[test]
fn one_colour_with_a_transparency_ramp_follows_smooth() {
let s = drawn_colors(json!(["#ff0000"]));
for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn legacy_colours_keep_their_own_alpha() {
let s = drawn_colors(json!(["#ff000080", "#ff000080"]));
for (x, want) in [(50, 128.0), (400, 64.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}");
}
}
// paint_gradient scans the stops for every pixel: Smooth's colour and opacity bakes share their
// 97 positions and must not be cut into four per interval (385 stops).
#[test]
fn smooth_transparency_keeps_one_stop_per_sampled_position() {
use photocraft_color::Color;
let black = Color::rgb(0.0, 0.0, 0.0);
let stops = super::paint_cmds::smooth_split_stops((vec![(0.0, black), (1.0, black)], vec![(0.0, 1.0), (1.0, 0.0)]));
assert_eq!(stops.len(), 97);
assert!((stops[0].1[3] - 1.0).abs() < 1e-6 && stops[96].1[3].abs() < 1e-6);
}
+78 -9
View File
@@ -161,15 +161,26 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
// where straight stops give 0.0625.
let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) {
Some(m) if stops.len() >= 2 => {
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
let mids = vec![0.5; stops.len() - 1];
photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], c.alpha])
})
.collect()
let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0);
// Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by
// the method, the opacity by Smooth's measured transparency curve (#12010). Merged
// stops would take the nearest stop's alpha. The other methods and Smoothness values
// were not measured in the Gradient tool and keep the merged stops.
let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None };
match split {
Some(split) => smooth_split_stops(split),
None => {
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
let mids = vec![0.5; stops.len() - 1];
photocraft_io::bake_gradient(colors, &mids, smoothness, m)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], c.alpha])
})
.collect()
}
}
}
_ => stops,
};
@@ -188,6 +199,64 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Smooth's colour and opacity stops baked apart, then joined. Both bakes sample the same
/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut
/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for
/// every pixel. Positions that differ still go through `apply_opacity`.
pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops {
let mids = vec![0.5; cs.len().saturating_sub(1)];
let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], 1.0])
})
.collect();
let omids = vec![0.5; os.len().saturating_sub(1)];
let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids);
if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) {
return gradients::apply_opacity(colours, &opacity);
}
colours
.into_iter()
.zip(opacity)
.map(|((t, mut c), (_, a))| {
c[3] = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 };
(t, c)
})
.collect()
}
/// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own
/// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their
/// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient.
fn split_stops(s: &Session, p: &Value, fg: [f32; 4]) -> Result<Option<gradients::FillStops>> {
let (mut cs, os) = match gradients::tool_fill_stops(s, p)? {
Some(split) => split,
None => {
// The legacy `colors` list, evenly spaced.
let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default();
if colors.iter().any(|c| c[3] < 1.0) {
return Ok(None);
}
let n = colors.len();
let cs = colors
.iter()
.enumerate()
.map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2])))
.collect();
(cs, gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default())
}
};
if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) {
return Ok(None);
}
if let [(_, c)] = cs.as_slice() {
cs = vec![(0.0, *c), (1.0, *c)];
}
Ok(if cs.is_empty() { None } else { Some((cs, os)) })
}
/// Paint helper command specs.
pub fn specs() -> Vec<CommandSpec> {
vec![
+12 -3
View File
@@ -401,19 +401,28 @@ pub const STOP: &str = "gradient.presets.stop";
/// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient`
/// handles itself).
pub fn tool_stops(s: &Session, p: &Value) -> Result<Option<Stops>> {
Ok(tool_preset(s, p)?.map(|g| g.resolve(s.tools.foreground, s.tools.background)))
}
/// The same gradient as [`tool_stops`] with its colour and opacity stops kept apart, for the
/// interpolation `method`, which treats the two differently.
pub fn tool_fill_stops(s: &Session, p: &Value) -> Result<Option<FillStops>> {
Ok(tool_preset(s, p)?.map(|g| g.fill_stops(s.tools.foreground, s.tools.background)))
}
fn tool_preset(s: &Session, p: &Value) -> Result<Option<GradientPreset>> {
const CMD: &str = "paint.gradient";
if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) {
return Ok(None);
}
let g = if let Some(name) = str_param(p, "gradient") {
Ok(Some(if let Some(name) = str_param(p, "gradient") {
let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?;
s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)?
} else if p.get("stops").is_some() {
GradientPreset::from_params("Custom", p, CMD)?
} else {
s.presets.gradient.clone().with_transparency(p, CMD)?
};
Ok(Some(g.resolve(s.tools.foreground, s.tools.background)))
}))
}
/// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`.
+42 -2
View File
@@ -230,8 +230,8 @@ const OPACITY_RESPONSE: f32 = 0.65;
/// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency
/// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input
/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve: it was
/// not measured (the Photoshop build it was fitted on has no Smooth method).
/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve here: it
/// was measured only in the Gradient tool at 100 % Smoothness ([`bake_smooth_opacity`]).
pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> {
let method = if method == Method::Smooth { Method::Classic } else { method };
let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3);
@@ -271,6 +271,38 @@ pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32,
baked
}
/// Gamma of Smooth's opacity response: the opacity of a fully transparent gradient ramp is the
/// Oklab lightness curve's linear value `y` raised to `1 / 2.2`. Photoshop 27.11, "Foreground to
/// Transparent" dragged over 600 px: alpha 255 / 179 / 100 / 35 / 0 at 50 / 250 / 400 / 550 / 750
/// (#12010). The same ramp as an sRGB grey (`y` encoded with the sRGB curve) gives 30 at the dark
/// end, 5 levels off, where the 2.2 power gives 35.
const SMOOTH_OPACITY_GAMMA: f32 = 2.2;
/// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is
/// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses
/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Measured
/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it.
/// Constant opacity comes back as it is, clamped to 0..=1.
pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 };
if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) {
return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect();
}
let mut s = stops;
s.sort_by(|a, b| a.0.total_cmp(&b.0));
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect();
const N: usize = 96;
let mut baked: Vec<(f32, f32)> = (0..=N)
.map(|k| {
let t = k as f32 / N as f32;
let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0];
(t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 })
})
.collect();
baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
baked
}
#[cfg(test)]
mod tests {
use super::*;
@@ -426,6 +458,14 @@ mod tests {
assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01);
}
#[test]
fn smooth_opacity_clamps_constant_stops() {
let flat = vec![(0.0, 0.4), (1.0, 0.4)];
assert_eq!(bake_smooth_opacity(flat.clone(), &[0.5]), flat);
assert_eq!(bake_smooth_opacity(vec![(0.0, 2.0), (1.0, 2.0)], &[0.5]), vec![(0.0, 1.0), (1.0, 1.0)]);
assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]);
}
/// `eval` guards its own stops instead of relying on `bake`'s two-stop check.
#[test]
fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() {
+1 -1
View File
@@ -53,7 +53,7 @@ mod flat;
pub mod gradient_bake;
pub mod guides_map;
mod png_steps;
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_smooth_opacity as bake_gradient_smooth_opacity};
mod duotone_map;
mod kra;
pub mod linked;