diff --git a/crates/engine-paint/src/cmd/brush_cmds.rs b/crates/engine-paint/src/cmd/brush_cmds.rs index 715b533127..e07b0102ed 100644 --- a/crates/engine-paint/src/cmd/brush_cmds.rs +++ b/crates/engine-paint/src/cmd/brush_cmds.rs @@ -9,7 +9,7 @@ use crate::preset_store::PresetStoreExt; use photocraft_geom::Rect; use photocraft_paint::mixer::MixerSettings; -use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; +use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, ToleranceControl, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{BrushPreset, BrushSettings, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped}; // The sampled-tip tile type, which the tests build tips from. @@ -991,6 +991,8 @@ fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSet limits: parse(p, cmd, "limits")?.unwrap_or(Limits::Contiguous), // 1..100 %, as the reference's field takes it: 0 and below run as 1 (#11930). tolerance: pct(p, "tolerance", 30.0).max(0.01), + // The popup's "Tolerance:" control (#17786): `penPressure` scales it by each dab's pressure. + tolerance_control: parse(p, cmd, "toleranceControl")?.unwrap_or(ToleranceControl::Off), anti_alias: flag(p, "antiAlias", true), color: brush.color, // The inks the foreground was picked as, when it was picked as CMYK (the same pair a Brush @@ -1575,7 +1577,7 @@ pub fn specs() -> Vec { spec!( "paint.colorReplacement", "Color Replacement Tool", - r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":1..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##, + r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":1..100=30,"toleranceControl":"off|penPressure|stylusWheel"="off" (penPressure: each dab uses tolerance x its pen pressure),"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##, crate::cmd::has_paintable, color_replacement, true diff --git a/crates/engine-paint/src/cmd/retouch_cmds/tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/tests.rs index 7e52873a22..9823d8f55c 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/tests.rs @@ -712,6 +712,7 @@ fn protect_detail_dabs_on_one_centre_apply_at_most_one_dab_at_each_pixel() { proj_scale: 1.0, wet: 1.0, mix: 1.0, + pressure: 1.0, }; let mut shares = super::dab::ProtectDetailShares::default(); let (mut applied, mut largest) = (std::collections::HashMap::new(), std::collections::HashMap::new()); diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 1d15eb8529..51962e59e3 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -777,6 +777,7 @@ impl DabBuilder { proj_scale, wet, mix, + pressure: s.point.pressure.clamp(0.0, 1.0), }); } } @@ -832,6 +833,7 @@ impl DualBuilder { proj_scale: 1.0, wet: 1.0, mix: 1.0, + pressure: 1.0, }); } } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 5f7838d325..0b57379bda 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -180,6 +180,9 @@ pub struct Dab { /// Mixer Brush multipliers of Wet and Mix (Transfer › Wetness/Mix Jitter), 1 = as set. pub wet: f32, pub mix: f32, + /// The pen pressure at this dab (0..1, 1 for an input without pen data), for effects whose + /// own setting follows it, like Color Replacement's Tolerance control (#17786). + pub pressure: f32, } impl Dab { @@ -201,6 +204,7 @@ impl Dab { proj_scale: 1.0, wet: 1.0, mix: 1.0, + pressure: 1.0, } } } diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index 1b54eb508d..b1149505c8 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -44,6 +44,19 @@ pub enum Limits { FindEdges, } +/// What the Tolerance follows during a stroke (the brush popup's "Tolerance:" control, #17786). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ToleranceControl { + /// The full Tolerance at every dab. + #[default] + Off, + /// Each dab uses Tolerance x the pen pressure at that dab. + PenPressure, + /// Kept at the full Tolerance: only measured without wheel data, where it does that. + StylusWheel, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct ReplaceSettings { @@ -52,6 +65,8 @@ pub struct ReplaceSettings { pub limits: Limits, /// 0..1 (max per-channel RGB distance). pub tolerance: f32, + /// Whether [`ReplaceSettings::tolerance`] follows the pen pressure, dab by dab. + pub tolerance_control: ToleranceControl, pub anti_alias: bool, /// Replacement (foreground) colour, straight RGBA. pub color: [f32; 4], @@ -70,6 +85,7 @@ impl Default for ReplaceSettings { sampling: Sampling::Continuous, limits: Limits::Contiguous, tolerance: 0.3, + tolerance_control: ToleranceControl::Off, anti_alias: true, color: [1.0, 0.0, 0.0, 1.0], color_inks: None, @@ -82,6 +98,10 @@ impl Default for ReplaceSettings { #[path = "replace_tolerance_falloff_tests.rs"] mod replace_tolerance_falloff_tests; +#[cfg(test)] +#[path = "replace_tolerance_pressure_tests.rs"] +mod replace_tolerance_pressure_tests; + fn dist(a: &[f32; 4], b: [f32; 3]) -> f32 { (a[0] - b[0]).abs().max((a[1] - b[1]).abs()).max((a[2] - b[2]).abs()) } @@ -141,10 +161,16 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut let l = photocraft_color::convert::srgb_to_lab(fg); [(l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] }; - let tol = rs.tolerance.clamp(0.0, 1.0); + let full_tol = rs.tolerance.clamp(0.0, 1.0); let soft = rs.anti_alias && rs.limits != Limits::FindEdges; let mut once: Option<[f32; 3]> = None; - let match_w = move |d: f32| -> f32 { + // The dab's own tolerance: on Pen Pressure the Tolerance times the pen pressure at the dab, as + // the reference measures (#17786); a mouse reports full pressure, so it keeps the whole Tolerance. + let dab_tol = move |fp: &Footprint| match rs.tolerance_control { + ToleranceControl::PenPressure => full_tol * fp.dab.pressure.clamp(0.0, 1.0), + ToleranceControl::Off | ToleranceControl::StylusWheel => full_tol, + }; + let match_w = move |d: f32, tol: f32| -> f32 { if d > tol { 0.0 } else if soft && tol > 0.0 { @@ -178,6 +204,7 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut if r.is_empty() { return; } + let tol = dab_tol(fp); let (w, h) = (r.width() as usize, r.height() as usize); let mut pre_px = vec![[0.0f32; 4]; w * h]; pre.read_rgba_into(r, &mut pre_px); @@ -194,7 +221,7 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut if c[3] <= 0.0 { continue; } - weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(&c, sampled)); + weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(&c, sampled), tol); } } if rs.limits != Limits::Discontiguous { diff --git a/crates/paint/src/replace_tolerance_pressure_tests.rs b/crates/paint/src/replace_tolerance_pressure_tests.rs new file mode 100644 index 0000000000..1b5065e37e --- /dev/null +++ b/crates/paint/src/replace_tolerance_pressure_tests.rs @@ -0,0 +1,121 @@ +//! #17786: with the Tolerance control on Pen Pressure each dab replaces only the colours within +//! Tolerance x its pen pressure, as the reference application measures on a ladder of stripes. + +use super::*; +use crate::{BrushSettings, StrokePoint}; +use photocraft_color::PixelFormat; + +/// Stripes, 5 px tall, stripe i = (128, 5 i, 128): each 5 green levels further from stripe 0. +const STRIPES: i32 = 35; +const STRIPE_H: i32 = 5; +/// The ladder's middle row, where the strokes run. +const MID: f64 = (STRIPES * STRIPE_H) as f64 / 2.0; + +fn stripe(i: i32) -> [f32; 4] { + [128.0 / 255.0, (5 * i) as f32 / 255.0, 128.0 / 255.0, 1.0] +} + +/// The ladder across `width` px after a stroke through `points`: Background Swatch on stripe 0's +/// colour, Discontiguous, Color mode with blue. +fn ladder(width: i32, size: f32, pressure_size: bool, tolerance: f32, control: ToleranceControl, points: Vec) -> Surface { + let fmt = PixelFormat::RGBA8; + let mut s = Surface::new(fmt); + for i in 0..STRIPES { + s.fill_rect(Rect::new(0, i * STRIPE_H, width, (i + 1) * STRIPE_H), &photocraft_raster::from_rgba(&fmt, stripe(i))); + } + let stroke = Stroke { brush: BrushSettings { size, hardness: 1.0, spacing: 0.25, pressure_size, ..Default::default() }, points }; + let rs = ReplaceSettings { + mode: ReplaceMode::Color, + sampling: Sampling::BackgroundSwatch, + limits: Limits::Discontiguous, + tolerance: tolerance / 100.0, + tolerance_control: control, + color: [0.0, 0.0, 1.0, 1.0], + background: stripe(0), + ..Default::default() + }; + apply_color_replacement(&mut s, &stroke, &rs, None, false).expect("the stroke fits"); + s +} + +/// Whether stripe i changed in column `x`. +fn changed(s: &Surface, x: i32, i: i32) -> bool { + let c = s.rgba(x, i * STRIPE_H + STRIPE_H / 2); + let want = stripe(i); + (0..3).any(|k| ((c[k] - want[k]) * 255.0).abs() >= 0.5) +} + +/// The highest stripe changed in column `x` (-1: none). Stripes below it change too. +fn reach(s: &Surface, x: i32) -> i32 { + let top = (0..STRIPES).rev().find(|&i| changed(s, x, i)).unwrap_or(-1); + for i in 0..top { + assert!(changed(s, x, i), "column {x}: stripe {i} kept while stripe {top} changed"); + } + top +} + +/// One click at pressure `p` with a 281 px tip, which covers the whole ladder. +fn click(tolerance: f32, control: ToleranceControl, point: StrokePoint) -> i32 { + let s = ladder(300, 281.0, false, tolerance, control, vec![StrokePoint { x: 150.0, y: MID, ..point }]); + reach(&s, 150) +} + +fn pen(p: f32) -> StrokePoint { + StrokePoint::new(0.0, 0.0, p) +} + +#[test] +fn pen_pressure_scales_the_tolerance_of_a_click() { + // The reference's ladder (+-1 stripe): (Tolerance, pressure, highest stripe replaced). + for (tolerance, p, want) in [(100.0, 0.1, 5), (100.0, 0.5, 25), (50.0, 0.25, 6), (50.0, 0.5, 12), (50.0, 1.0, 26)] { + let got = click(tolerance, ToleranceControl::PenPressure, pen(p)); + assert!((got - want).abs() <= 1, "Tolerance {tolerance} at pressure {p}: stripes 0..{got}, the reference 0..{want}"); + } +} + +#[test] +fn a_very_light_pen_replaces_only_the_matching_colour() { + // Tolerance 2 %: the reference keeps stripe 1 too; the +-1 stripe of the other readings lets + // its edge pixels, at the very end of the soft falloff, take a trace of the colour. + assert!(click(100.0, ToleranceControl::PenPressure, pen(0.02)) <= 1); +} + +#[test] +fn off_the_mouse_and_the_stylus_wheel_keep_the_full_tolerance() { + let full = click(100.0, ToleranceControl::Off, pen(1.0)); + assert_eq!(full, STRIPES - 1, "Tolerance 100 replaces every stripe under the tip"); + assert_eq!(click(100.0, ToleranceControl::Off, pen(0.1)), full, "Off ignores the pressure"); + assert_eq!(click(100.0, ToleranceControl::StylusWheel, pen(0.1)), full, "Stylus Wheel without wheel data ignores it"); + assert_eq!(click(100.0, ToleranceControl::PenPressure, StrokePoint::without_pressure(0.0, 0.0)), full, "the mouse"); + // A lower Tolerance with the mouse stays where it is without the control. + let mouse = click(50.0, ToleranceControl::PenPressure, StrokePoint::without_pressure(0.0, 0.0)); + assert_eq!(mouse, click(50.0, ToleranceControl::Off, pen(0.3))); +} + +#[test] +fn a_pressure_ramp_grades_the_tolerance_dab_by_dab() { + // 0.1 -> 1.0 from x 100 to x 500 with a 201 px tip at Tolerance 100. + let pts = (0..=40).map(|k| StrokePoint::new(100.0 + 10.0 * f64::from(k), MID, 0.1 + 0.9 * k as f32 / 40.0)).collect(); + let s = ladder(700, 201.0, false, 100.0, ToleranceControl::PenPressure, pts); + // The stripes changed in a column. Its rows far from the stroke are covered only by the dabs + // right at it, those near the stroke also by the firmer dabs up to 100 px further on, so the + // changed stripes needn't be one run from stripe 0 here. + let count = |x: i32| (0..STRIPES).filter(|&i| changed(&s, x, i)).count(); + let counts: Vec = [100, 150, 200, 250].iter().map(|&x| count(x)).collect(); + assert!(counts.windows(2).all(|w| w[0] < w[1]), "more stripes change as the pressure grows: {counts:?}"); + assert!(counts[3] < STRIPES as usize, "short of full pressure, some stripes stay: {counts:?}"); + assert_eq!(reach(&s, 500), STRIPES - 1, "full pressure replaces everything under the tip"); +} + +#[test] +fn size_and_tolerance_follow_the_pen_together() { + // At pressure 0.5 the 281 px tip shrinks to about 140 px (rows MID +- 70) and the Tolerance + // 100 to 50 (stripes 0..25). + let both = ladder(300, 281.0, true, 100.0, ToleranceControl::PenPressure, vec![StrokePoint::new(150.0, MID, 0.5)]); + let size_only = ladder(300, 281.0, true, 100.0, ToleranceControl::Off, vec![StrokePoint::new(150.0, MID, 0.5)]); + let tolerance_only = ladder(300, 281.0, false, 100.0, ToleranceControl::PenPressure, vec![StrokePoint::new(150.0, MID, 0.5)]); + let (near_top, middle, near_bottom) = (1, 12, 31); + assert!(changed(&tolerance_only, 150, near_top) && !changed(&both, 150, near_top), "the smaller tip misses the top stripes"); + assert!(changed(&size_only, 150, near_bottom) && !changed(&both, 150, near_bottom), "the lower tolerance keeps the far stripes"); + assert!(changed(&both, 150, middle), "inside both, the stripe is replaced"); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 7292c0ca15..82b7cd808f 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -157,6 +157,8 @@ pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value { // As the field stores it (#11930), so a restored fraction replaces the same pixels before // and after the options bar shows it. "tolerance": crate::eraser_ui::stored_tolerance(o.cr_tolerance), + // The popup's "Tolerance:" control (#17786): on Pen Pressure each dab's tolerance follows the pen. + "toleranceControl": o.cr_tolerance_control, "antiAlias": o.cr_anti_alias, // A mask or channel target is refused: the tool recolours layer pixels only. "target": crate::canvas::paint_target(app),