Skip to content

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

feat(gradients): Photoshop's interpolation method for Gradient Overlay, gradient Stroke and the Gradient tool (#4292)

MrCloudy2b79d0a0bcf61
diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs
index b7fc8b7b0..fbbc949e2 100644
--- a/crates/engine/src/layer_style.rs
+++ b/crates/engine/src/layer_style.rs
@@ -52,9 +52,21 @@ fn color(p: &Value, k: &str, d: [f32; 3]) -> Color {
let c = color_of(p, k).map_or(d, |c| c.to_rgb());
Color::rgb(c[0], c[1], c[2])
}
+/// The stops of a two-colour gradient, baked with Photoshop's interpolation when `method` names
+/// one (`classic`, `perceptual`, `linear`, `smooth`; `smoothness` 0..=100, default 100 as in
+/// Photoshop): the compositors interpolate stops linearly, so the curve becomes dense stops, as on
+/// PSD import. Photoshop 27.11's Classic Gradient Overlay eases (t + smoothstep(t)) / 2 between the
+/// colours: a straight ramp was up to 12 levels off.
+fn gradient_stops(p: &Value, from: Color, to: Color) -> Vec<(f32, Color)> {
+ let stops = vec![(0.0, from), (1.0, to)];
+ match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) {
+ Some(m) => photocraft_io::bake_gradient(stops, &[0.5], (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m),
+ None => stops,
+ }
+}
fn gradient(p: &Value) -> Gradient {
Gradient {
- stops: vec![(0.0, color(p, "from", [0.0; 3])), (1.0, color(p, "to", [1.0; 3]))],
+ stops: gradient_stops(p, color(p, "from", [0.0; 3]), color(p, "to", [1.0; 3])),
style: gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")),
angle: f(p, "angle", 90.0),
scale: f(p, "scale", 100.0) / 100.0,
@@ -546,6 +558,13 @@ fn fresh_effect(kind: &str) -> Option<Effect> {
/// Edits an existing gradient in place: only the end colours and geometry.
/// Intermediate stops, opacity stops, alignment and offset survive a round trip.
fn overlay_gradient(g: &mut Gradient, p: &Value) {
+ // A method rebuilds the gradient from its end colours (the stops between are the old curve).
+ if p.get("method").and_then(Value::as_str).is_some_and(|m| photocraft_io::GradientMethod::from_name(m).is_some()) {
+ let ends = (g.stops.first().map(|s| s.1), g.stops.last().map(|s| s.1));
+ let from = color_of(p, "from").or(ends.0).unwrap_or(Color::BLACK);
+ let to = color_of(p, "to").or(ends.1).unwrap_or(Color::WHITE);
+ g.stops = gradient_stops(p, from, to);
+ }
if let Some(c) = color_of(p, "from")
&& let Some(first) = g.stops.first_mut()
{
@@ -983,13 +1002,13 @@ pub fn specs() -> Vec<CommandSpec> {
style_cmd!(
"stroke",
"Stroke…",
- r##"{"size":px=3,"position":"outside|inside|center","color":"#rrggbb","from":"#rrggbb","to":"#rrggbb","style":str,"angle":deg,"opacity":0..100,"blend":str,"add":bool}"##
+ r##"{"size":px=3,"position":"outside|inside|center","color":"#rrggbb","from":"#rrggbb","to":"#rrggbb","method":"classic|perceptual|linear|smooth"?,"smoothness":0..100=100,"style":str,"angle":deg,"opacity":0..100,"blend":str,"add":bool}"##
),
style_cmd!("colorOverlay", "Color Overlay…", r##"{"color":"#rrggbb","opacity":0..100=100,"blend":str,"add":bool}"##),
style_cmd!(
"gradientOverlay",
"Gradient Overlay…",
- r##"{"from":"#rrggbb","to":"#rrggbb","style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"##
+ r##"{"from":"#rrggbb","to":"#rrggbb","method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"##
),
style_cmd!(
"patternOverlay",
@@ -1342,6 +1361,26 @@ mod tests {
assert!((at(&lut("Cove - Deep"), 0.0) - 0.26).abs() < 0.02, "Cove - Deep starts above zero");
}
+ #[test]
+ fn gradient_overlay_method_matches_photoshop() {
+ // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at
+ // t = 1/16 and 0.5 in the middle; straight stops would give 0.0625.
+ let mut s = session();
+ s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "method": "classic"})).unwrap();
+ let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() };
+ let at = |t: f32| {
+ let w = gradient.stops.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).unwrap();
+ let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-6);
+ w[0].1.to_rgb()[0] + (w[1].1.to_rgb()[0] - w[0].1.to_rgb()[0]) * u
+ };
+ assert!((at(1.0 / 16.0) - 0.037).abs() < 0.004, "{}", at(1.0 / 16.0));
+ assert!((at(0.5) - 0.5).abs() < 0.004, "{}", at(0.5));
+ // Without a method the two stops stay as they are.
+ s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "add": true})).unwrap();
+ let plain = effects(&s).iter().filter(|e| matches!(e, Effect::GradientOverlay { gradient, .. } if gradient.stops.len() == 2)).count();
+ assert_eq!(plain, 1, "the added overlay keeps its two stops");
+ }
+
#[test]
fn contour_presets_and_custom_curves_apply_in_one_undo_step() {
let mut s = session();
diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs
index 4dc39f151..497d7f4fb 100644
--- a/crates/engine/src/paint_cmds.rs
+++ b/crates/engine/src/paint_cmds.rs
@@ -123,6 +123,23 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
gradients::apply_opacity(cs, &gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default())
}
};
+ // Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense
+ // stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16
+ // 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()
+ }
+ _ => stops,
+ };
let reverse = b(p, "reverse", false);
let opacity = opacity(p, "paint.gradient")?;
let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal);
@@ -155,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Gradient",
menu: &[],
shortcut: None,
- params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
+ params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
enabled: crate::commands::has_paintable,
run: gradient,
journal: true,
diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs
index c9265a910..e452ae9e1 100644
--- a/crates/io/src/gradient_bake.rs
+++ b/crates/io/src/gradient_bake.rs
@@ -14,8 +14,9 @@
use photocraft_color::{Color, ColorMode};
+/// Photoshop's gradient interpolation methods.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(crate) enum Method {
+pub enum Method {
Classic,
Perceptual,
Linear,
@@ -23,6 +24,16 @@ pub(crate) enum Method {
}
impl Method {
+ /// The method a command names (`classic`, `perceptual`, `linear`, `smooth`); `None` otherwise.
+ pub fn from_name(name: &str) -> Option<Method> {
+ match name.to_ascii_lowercase().as_str() {
+ "classic" => Some(Method::Classic),
+ "perceptual" => Some(Method::Perceptual),
+ "linear" => Some(Method::Linear),
+ "smooth" => Some(Method::Smooth),
+ _ => None,
+ }
+ }
pub(crate) fn from_code(code: Option<&[u8]>) -> Method {
match code {
Some(b"Perc") => Method::Perceptual,
@@ -140,7 +151,7 @@ fn eval(stops: &[(f32, [f32; 3])], mids: &[f32], smooth: f32, t: f32, m: Method)
/// Dense linear stops reproducing Photoshop's interpolation. Returns the input unchanged when it
/// already interpolates linearly in sRGB.
-pub(crate) fn bake(stops: Vec<(f32, Color)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, Color)> {
+pub fn bake(stops: Vec<(f32, Color)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, Color)> {
let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3);
// Classic interpolates in the stops' own model: Lab stops (Lab documents) blend in L*a*b*, which the
// compositors' sRGB interpolation can't reproduce (psd-tools 4x4_16bit_lab).
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 0a1577714..9852a4851 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -42,6 +42,7 @@ pub mod effects_map;
pub mod exr_parts;
mod flat;
mod gradient_bake;
+pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};
mod kra;
pub mod linked;
mod multichannel_map;