Skip to content

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

Brushes: Photoshop's texture Height/Subtract modes, Brightness and Contrast (#3340) (#3749)

David Mann81bff2aaa426
diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs
index 225869ea7..6230e2764 100644
--- a/crates/io/src/abr_map.rs
+++ b/crates/io/src/abr_map.rs
@@ -389,7 +389,9 @@ impl Mapper<'_> {
t.invert = boolean(d, "InvT").unwrap_or(false);
t.scale = pct(d, "textureScale").unwrap_or(1.0).clamp(0.01, 10.0);
t.brightness = (num(d, "textureBrightness").unwrap_or(0.0) / 150.0).clamp(-1.0, 1.0) as f32;
- t.contrast = (num(d, "textureContrast").unwrap_or(0.0) / 50.0).clamp(-1.0, 2.0) as f32;
+ // Photoshop's -50..100 onto the model's -1..1 (negative and positive scale apart).
+ let c = num(d, "textureContrast").unwrap_or(0.0);
+ t.contrast = (if c < 0.0 { c / 50.0 } else { c / 100.0 }).clamp(-1.0, 1.0) as f32;
t.mode = mask_mode(enum_value(d, "textureBlendMode")).unwrap_or(MaskMode::Multiply);
t.depth = pct(d, "textureDepth").unwrap_or(1.0).clamp(0.0, 1.0);
let mut dj = self.dynamic(obj(d, "textureDepthDynamics"));
diff --git a/crates/io/src/abr_map/tests.rs b/crates/io/src/abr_map/tests.rs
index 9837f4ea4..013f307f8 100644
--- a/crates/io/src/abr_map/tests.rs
+++ b/crates/io/src/abr_map/tests.rs
@@ -153,7 +153,7 @@ fn v6_settings_map_onto_brush_sections() {
assert_eq!((sc.count, sc.scatter.jitter, sc.scatter.control, sc.scatter.fade_steps, sc.count_jitter.jitter), (3, 2.5, Control::Fade, 40, 0.5));
let tx = &b.texture;
assert!(tx.enabled && tx.each_tip && tx.invert);
- assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.5, MaskMode::ColorBurn, 0.6));
+ assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.25, MaskMode::ColorBurn, 0.6));
assert_eq!((tx.depth_jitter.jitter, tx.depth_jitter.minimum), (0.3, 0.2));
let Pattern::Tile(pt) = &tx.pattern else { panic!("embedded pattern expected, got {:?}", tx.pattern) };
assert_eq!((pt.width, pt.height, pt.data[3]), (4, 2, 65535));
@@ -330,3 +330,50 @@ fn sampled_tip_paints_the_brush_colour_never_black() {
assert!(painted > 0, "the imported tip painted nothing");
assert!(painted < 64 * 64, "the tip covered everything - coverage was treated as solid colour");
}
+
+/// #3340: Photoshop's texture Contrast runs -50..100; the model maps -50..0 and 0..100 onto
+/// -1..0 and 0..1 (as Brush Settings shows it), so +24 must not read back as +48.
+#[test]
+fn texture_contrast_maps_both_halves() {
+ for (c, want) in [(24, 0.24), (100, 1.0), (-30, -0.6), (-50, -1.0), (0, 0.0)] {
+ let preset = Descriptor::new("brushPreset")
+ .with("Nm ", t("C"))
+ .with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0))))
+ .with("useTexture", Value::Boolean(true))
+ .with("textureContrast", Value::Integer(c));
+ let bytes = write_v6(2, &[], &[], &[preset], false).unwrap();
+ let imp = read_abr(&bytes, "Test").unwrap();
+ let got = imp.presets[0].brush.texture.contrast;
+ assert!((got - want).abs() < 1e-6, "contrast {c}: {got}");
+ }
+}
+
+/// #3340: a Height-mode brush at a low depth with a darkened pattern (how Photoshop's own
+/// "Pen" presets in the reported file are set up) imported but painted nothing.
+#[test]
+fn low_depth_height_texture_brush_paints() {
+ use photocraft_color::PixelFormat;
+ use photocraft_paint::StrokePoint;
+ use photocraft_paint::render::render_stroke;
+ use photocraft_raster::Surface;
+
+ for mode in ["Hght", "linearHeight"] {
+ let preset = Descriptor::new("brushPreset")
+ .with("Nm ", t("Pen"))
+ .with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0)).with("Hrdn", prc(100.0)).with("Spcn", prc(5.0))))
+ .with("useTexture", Value::Boolean(true))
+ .with("textureBlendMode", en("BlnM", mode))
+ .with("textureDepth", prc(13.0))
+ .with("textureBrightness", Value::Integer(-87))
+ .with("textureContrast", Value::Integer(5))
+ .with("Txtr", Value::Descriptor(Descriptor::new("Ptrn").with("Nm ", t("Grit")).with("Idnt", t("pat-uuid"))));
+ let bytes = write_v6(2, &[], &[grit_pattern()], &[preset], false).unwrap();
+ let imp = read_abr(&bytes, "Test").unwrap();
+ let b = imp.presets[0].brush.clone();
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ render_stroke(&mut s, &b, &[StrokePoint::new(10.0, 20.0, 1.0), StrokePoint::new(50.0, 20.0, 1.0)], None, false, 1.0);
+ let covered = (12..48).filter(|&x| s.rgba(x, 20)[3] > 0.5).count();
+ // 13 % depth reaches 1.55 pattern ranges: above the whole darkened Grit pattern.
+ assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels");
+ }
+}
diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs
index 25ebea5ef..48e7f48d3 100644
--- a/crates/paint/src/brush.rs
+++ b/crates/paint/src/brush.rs
@@ -270,7 +270,7 @@ pub struct Texture {
pub scale: f32,
/// -1..1 (Photoshop's -150..150 mapped to ±1).
pub brightness: f32,
- /// -1..1.
+ /// -1..1: Photoshop's -50..0 mapped to -1..0 and its 0..100 to 0..1.
pub contrast: f32,
/// Apply the texture to every dab (enables depth jitter) instead of once to the stroke.
pub each_tip: bool,
@@ -281,6 +281,21 @@ pub struct Texture {
pub depth_jitter: Dynamic,
}
+impl Texture {
+ /// A pattern value (0..1) after Brightness, Contrast and Invert: the value the mode combines
+ /// with the brush. Measured against Photoshop (#3340): Brightness shifts the pattern by
+ /// `brightness / 255` (±150 moves it 150 levels of 255, not all the way to white or black);
+ /// positive Contrast steepens it around mid-grey by `1 / (1 − c/100)` after the shift (100 is
+ /// a threshold), negative Contrast flattens it by `1 + c/100` before the shift; Invert is last.
+ pub fn level(&self, v: f32) -> f32 {
+ let b = if self.brightness.is_finite() { self.brightness.clamp(-1.0, 1.0) * (150.0 / 255.0) } else { 0.0 };
+ let c = if self.contrast.is_finite() { self.contrast.clamp(-1.0, 1.0) } else { 0.0 };
+ let x = if c >= 0.0 { (v + b - 0.5) / (1.0 - c).max(1e-4) + 0.5 } else { (v - 0.5) * (1.0 + c / 2.0) + 0.5 + b };
+ let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.5 };
+ if self.invert { 1.0 - x } else { x }
+ }
+}
+
impl Default for Texture {
fn default() -> Self {
Self {
diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs
index a68f84f1f..664aca9c0 100644
--- a/crates/paint/src/brush_tests.rs
+++ b/crates/paint/src/brush_tests.rs
@@ -6,7 +6,7 @@ use photocraft_raster::Surface;
use crate::brush::*;
use crate::dynamics::{Smoother, smooth_points};
-use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke};
+use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke, texture_combine};
use crate::tile::GrayTile;
use crate::{Dab, Stroke, StrokePoint, dabs};
@@ -525,7 +525,9 @@ fn texture_modulates_coverage() {
b.texture.invert = false;
b.texture.brightness = 1.0;
let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
- assert!(s.rgba(46, 30)[3] > 0.9);
+ // +150 lifts a black texel by 150 levels of 255, not to white (#3340).
+ let lifted = s.rgba(46, 30)[3];
+ assert!((lifted - 150.0 / 255.0).abs() < 0.02, "{lifted}");
// All modes keep zero coverage at zero and stay in range.
for m in [
MaskMode::Multiply,
@@ -544,6 +546,12 @@ fn texture_modulates_coverage() {
let v = mask_combine(m, 0.7, t, 0.8);
assert!((0.0..=1.0).contains(&v), "{m:?}");
}
+ for t in [0.0, 0.3, 1.0] {
+ assert_eq!(texture_combine(m, 0.0, t, 1.0), 0.0, "{m:?}");
+ let v = texture_combine(m, 0.7, t, 0.8);
+ assert!((0.0..=1.0).contains(&v), "{m:?}");
+ }
+ assert!((0.0..=1.0).contains(&texture_combine(m, 0.7, f32::NAN, f32::INFINITY)), "{m:?}");
// Full-white texture never reduces multiply-like masks below the brush.
assert!(mask_combine(m, 0.6, 1.0, 1.0) >= 0.6 - 1e-5 || matches!(m, MaskMode::Overlay), "{m:?}");
}
@@ -555,6 +563,98 @@ fn texture_modulates_coverage() {
assert!(d.iter().any(|x| x.depth < 0.6));
}
+/// Texture Brightness and Contrast as Photoshop applies them, measured by stroking a 0..255 grey
+/// ramp pattern in Multiply mode at 100 % depth (the stroke's opacity is then the pattern value):
+/// (setting, ramp value, opacity read back), in levels of 255 (#3340).
+#[test]
+fn texture_brightness_and_contrast_match_photoshop() {
+ let level = |brightness: f32, contrast: f32, invert: bool, v: f32| {
+ // The model's ranges: brightness ±150 → ±1; contrast -50..0 → -1..0, 0..100 → 0..1.
+ let c = if contrast < 0.0 { contrast / 50.0 } else { contrast / 100.0 };
+ let t = Texture { brightness: brightness / 150.0, contrast: c, invert, ..Default::default() };
+ t.level(v / 255.0) * 255.0
+ };
+ for (b, c, inv, v, want) in [
+ (87.0, 0.0, false, 8.0, 95.0),
+ (87.0, 0.0, false, 200.0, 255.0),
+ (-87.0, 0.0, false, 104.0, 17.0),
+ (150.0, 0.0, false, 8.0, 158.0),
+ (0.0, 50.0, false, 104.0, 81.0),
+ (0.0, 50.0, false, 136.0, 145.0),
+ (0.0, -50.0, false, 8.0, 67.0),
+ (0.0, -50.0, false, 248.0, 188.0),
+ (0.0, 100.0, false, 120.0, 0.0),
+ (0.0, 100.0, false, 136.0, 255.0),
+ // Positive contrast after the shift, negative contrast before it.
+ (40.0, 50.0, false, 104.0, 161.0),
+ (40.0, 50.0, false, 40.0, 33.0),
+ (-40.0, -30.0, false, 120.0, 82.0),
+ (-40.0, -30.0, false, 248.0, 172.0),
+ // Invert comes last.
+ (40.0, 0.0, true, 8.0, 207.0),
+ (0.0, 50.0, true, 72.0, 238.0),
+ ] {
+ let got = level(b, c, inv, v);
+ assert!((got - want).abs() <= 2.0, "brightness {b}, contrast {c}, invert {inv}, ramp {v}: {got} (Photoshop {want})");
+ }
+}
+
+/// The Texture modes that differ from the Dual Brush's, against single Photoshop dabs over a
+/// 0..255 ramp: (mode, depth, brush coverage, ramp value, opacity read back), in levels of 255.
+#[test]
+fn texture_modes_match_photoshop() {
+ use MaskMode::*;
+ for (m, d, v, t, want) in [
+ // Height: a low depth paints the dark valleys only, more depth fills the pattern.
+ (Height, 0.0, 255.0, 8.0, 0.0),
+ (Height, 0.01, 255.0, 8.0, 28.0),
+ (Height, 0.05, 255.0, 8.0, 148.0),
+ (Height, 0.05, 255.0, 136.0, 20.0),
+ (Height, 0.13, 255.0, 8.0, 255.0),
+ (Height, 0.13, 255.0, 152.0, 244.0),
+ (Height, 0.13, 255.0, 248.0, 148.0),
+ (Height, 0.13, 186.0, 88.0, 201.0),
+ (Height, 0.13, 142.0, 104.0, 116.0),
+ (Height, 0.25, 255.0, 248.0, 255.0),
+ // Linear Height: graded by the pattern while the reach stays below its top.
+ (LinearHeight, 0.01, 255.0, 152.0, 15.0),
+ (LinearHeight, 0.05, 255.0, 8.0, 151.0),
+ (LinearHeight, 0.05, 255.0, 152.0, 63.0),
+ (LinearHeight, 0.10, 255.0, 72.0, 240.0),
+ (LinearHeight, 0.13, 101.0, 120.0, 82.0),
+ (LinearHeight, 0.13, 142.0, 104.0, 130.0),
+ // Subtract: the light parts take paint away.
+ (Subtract, 1.0, 255.0, 8.0, 247.0),
+ (Subtract, 1.0, 255.0, 248.0, 7.0),
+ (Subtract, 0.5, 224.0, 72.0, 188.0),
+ // Color Burn / Color Dodge below full depth.
+ (ColorBurn, 0.5, 224.0, 72.0, 207.0),
+ (ColorDodge, 0.5, 99.0, 120.0, 130.0),
+ // Unchanged modes.
+ (Multiply, 0.13, 255.0, 8.0, 223.0),
+ (Darken, 0.5, 255.0, 8.0, 131.0),
+ ] {
+ let got = texture_combine(m, v / 255.0, t / 255.0, d) * 255.0;
+ assert!((got - want).abs() <= 3.0, "{m:?} depth {d}, coverage {v}, ramp {t}: {got} (Photoshop {want})");
+ }
+}
+
+/// #3340: an imported Height-mode brush at a low depth with a darkened pattern painted nothing.
+#[test]
+fn low_depth_height_texture_paints() {
+ let tile = GrayTile::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { 0.45 } else { 0.6 });
+ for mode in [MaskMode::Height, MaskMode::LinearHeight] {
+ let b = BrushSettings {
+ size: 40.0,
+ texture: Texture { enabled: true, pattern: Pattern::Tile(tile.clone()), mode, depth: 0.13, brightness: -87.0 / 150.0, ..Default::default() },
+ ..brush()
+ };
+ let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60);
+ let a = s.rgba(50, 30)[3];
+ assert!(a > 0.95, "{mode:?}: {a}");
+ }
+}
+
#[test]
fn dual_brush_intersects() {
// Dual tip: small dabs far apart → the stroke survives only where they land.
diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs
index 621565188..cbba537e1 100644
--- a/crates/paint/src/presets.rs
+++ b/crates/paint/src/presets.rs
@@ -107,7 +107,9 @@ fn dry_media(base: &BrushSettings) -> Vec<BrushPreset> {
spacing: 0.12,
shape_dynamics: ShapeDynamics { enabled: true, size: pressure_min(0.5), angle: Dynamic::controlled(Control::Direction), ..Default::default() },
transfer: transfer(pressure_min(0.3), Dynamic::default()),
- texture: Texture { mode: MaskMode::Subtract, ..paper(5, 0.7) },
+ // Subtract takes paint away where the pattern is light (#3340); inverting keeps
+ // these presets as they were designed, with the dark parts taking it away.
+ texture: Texture { mode: MaskMode::Subtract, invert: true, ..paper(5, 0.7) },
..base.clone()
},
),
@@ -129,6 +131,7 @@ fn dry_media(base: &BrushSettings) -> Vec<BrushPreset> {
pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 2 },
depth: 0.55,
mode: MaskMode::Subtract,
+ invert: true,
..Default::default()
},
..base.clone()
@@ -379,6 +382,7 @@ fn special_effects(base: &BrushSettings) -> Vec<BrushPreset> {
enabled: true,
pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 1 },
mode: MaskMode::Subtract,
+ invert: true,
depth: 0.7,
..Default::default()
},
diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs
index a92b75fbd..94ac63a79 100644
--- a/crates/paint/src/render.rs
+++ b/crates/paint/src/render.rs
@@ -108,6 +108,40 @@ pub fn mask_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 {
r.clamp(0.0, 1.0)
}
+/// How far a Height-mode dab at full depth and coverage reaches into the pattern, in pattern
+/// ranges (measured against Photoshop, #3340).
+const HEIGHT_REACH: f32 = 12.0;
+
+/// Combine brush coverage `v` with a Texture pattern value `t` at `depth` (Brush Settings ›
+/// Texture). Where it differs from [`mask_combine`] (still used for the Dual Brush) it follows
+/// Photoshop as measured with single dabs over a grey ramp (#3340):
+/// - Subtract takes `depth × t` away, so a white pattern removes the most paint.
+/// - Color Dodge and Color Burn move the pattern toward their neutral colour as depth falls.
+/// - Height treats the pattern as a height field the brush presses into: the paint reaches
+/// `12 × depth × v` and fills whatever lies below that, so a low depth paints only the dark
+/// valleys, from about 17 % the whole pattern is under the paint, and a brighter pattern
+/// takes paint away.
+/// - Linear Height is Height, but where the reach stays below the top of the pattern the paint
+/// fades with the pattern instead of being cut off.
+pub fn texture_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 {
+ if v <= 0.0 {
+ return 0.0;
+ }
+ let r = match mode {
+ MaskMode::Subtract => v - d * t,
+ MaskMode::ColorDodge => v / (1.0 - d * t).max(1e-3),
+ MaskMode::ColorBurn => 1.0 - (1.0 - v) / (1.0 - d + d * t).max(1e-3),
+ // Photoshop steps the depth in 1/255ths here, which shows at the lowest depths.
+ MaskMode::Height => HEIGHT_REACH * (d * 255.0).round() / 255.0 * v - t,
+ MaskMode::LinearHeight => {
+ let reach = HEIGHT_REACH * (d * 255.0).round() / 255.0 * v;
+ if reach < 1.0 { reach * (1.0 - t) } else { reach - t }
+ }
+ _ => mask_combine(mode, v, t, d),
+ };
+ if r.is_finite() { r.clamp(0.0, 1.0) } else { 0.0 }
+}
+
/// A stroke-ready brush: the settings plus prepared tip mips and texture.
#[derive(Clone, Debug)]
pub struct BrushContext {
@@ -129,11 +163,8 @@ fn prepare_pattern(b: &BrushSettings) -> Option<Arc<PatternImage>> {
_ => return None,
},
};
- let (br, ct) = (t.brightness.clamp(-1.0, 1.0), t.contrast.clamp(-1.0, 1.0));
for v in &mut img.data {
- let mut x = (*v - 0.5) * (1.0 + ct) + 0.5 + br;
- x = x.clamp(0.0, 1.0);
- *v = if t.invert { 1.0 - x } else { x };
+ *v = t.level(*v);
}
Some(Arc::new(img))
}
@@ -326,7 +357,7 @@ impl BrushContext {
val += (hard - val) * 0.7;
}
if tex_tip {
- val = mask_combine(b.texture.mode, val, self.texture_at(x, y), d.depth);
+ val = texture_combine(b.texture.mode, val, self.texture_at(x, y), d.depth);
}
if wet {
val *= wet_factor(rn);
@@ -366,7 +397,7 @@ impl BrushContext {
m = mask_combine(b.dual_brush.mode, m, dv, 1.0);
}
if self.texture.is_some() && !b.texture.each_tip {
- m = mask_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0));
+ m = texture_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0));
}
m
}
diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/brush_sections.rs
index 7fae63ffd..16332e4d0 100644
--- a/crates/ui-egui/src/brush_sections.rs
+++ b/crates/ui-egui/src/brush_sections.rs
@@ -395,14 +395,9 @@ fn pattern_swatch(ui: &mut egui::Ui, tx: &paint::Texture) {
_ => paint::tile::PatternImage { width: 1, height: 1, data: vec![0.5] },
},
};
- let (br, ct) = (tx.brightness.clamp(-1.0, 1.0), tx.contrast.clamp(-1.0, 1.0));
let px: Vec<u8> = (0..n * n)
.flat_map(|i| {
- let v = img.sample_wrap((i % n) as f32, (i / n) as f32);
- let mut x = ((v - 0.5) * (1.0 + ct) + 0.5 + br).clamp(0.0, 1.0);
- if tx.invert {
- x = 1.0 - x;
- }
+ let x = tx.level(img.sample_wrap((i % n) as f32, (i / n) as f32));
let g = (x * 255.0).round() as u8;
[g, g, g, 255]
})