PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Brush Scatter above 1000 % is rejected naming the value, and the renderer caps it so dabs stay finite (#977) (#1034)
yang7fec6e9469ce
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex d37af9492..982f6cd67 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -137,7 +137,9 @@ pub fn merge_brush(base: &BrushSettings, patch: &Value, cmd: &str) -> Result<BruOk(out)}-pub(crate) fn validate_brush_size(brush: &BrushSettings, cmd: &str) -> Result<()> {+/// Rejects brush sizes and Scatter amounts outside their documented ranges, before a brush is+/// stored or painted with.+pub(crate) fn validate_brush(brush: &BrushSettings, cmd: &str) -> Result<()> {let max = photocraft_paint::MAX_BRUSH_SIZE;if !brush.size.is_finite() || brush.size > max {return Err(bad(cmd, format!("brush size must be finite and at most {max} px")));@@ -145,6 +147,18 @@ pub(crate) fn validate_brush_size(brush: &BrushSettings, cmd: &str) -> Result<()if brush.dual_brush.enabled && (!brush.dual_brush.size.is_finite() || brush.dual_brush.size > max) {return Err(bad(cmd, format!("dual brush size must be finite and at most {max} px")));}+ // Scatter may exceed 1 (100 %) but not the 1000 % maximum: a huge amount pushed dab centres to+ // infinity (#977). `{:?}` keeps 1e38 short and shows infinity as `inf`.+ let scatter_max = photocraft_paint::MAX_SCATTER;+ let in_range = |v: f32| (0.0..=scatter_max).contains(&v);+ let sc = brush.scattering.scatter.jitter;+ if brush.scattering.enabled && !in_range(sc) {+ return Err(bad(cmd, format!("scatter amount {sc:?} is out of range: it must be between 0 and {scatter_max} (1000 %)")));+ }+ let ds = brush.dual_brush.scatter;+ if brush.dual_brush.enabled && !in_range(ds) {+ return Err(bad(cmd, format!("dual brush scatter amount {ds:?} is out of range: it must be between 0 and {scatter_max} (1000 %)")));+ }Ok(())}@@ -187,7 +201,7 @@ pub fn resolve_brush(s: &Session, p: &Value, cmd: &str) -> Result<BrushSettings>Some(v) => v,None => photocraft_paint::rng::seed_from_bytes(p.get("points").map(|v| v.to_string()).unwrap_or_default().as_bytes()),};- validate_brush_size(&b, cmd)?;+ validate_brush(&b, cmd)?;Ok(b)}@@ -632,11 +646,14 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {}if let Some(inner) = o.remove("brush") {let tmp = merge_brush(&b, &inner, cmd)?;+ // Before the second merge: a non-finite value would serialise as `null` there and be+ // reported as a type error instead of naming the value (#977).+ validate_brush(&tmp, cmd)?;b = tmp;}}b = merge_brush(&b, &patch, cmd)?;- validate_brush_size(&b, cmd)?;+ validate_brush(&b, cmd)?;let before = std::mem::replace(&mut s.tools.brush, b);// A coalesced gesture (one slider drag) journals as one call: remember the brush it started from.let key = p.get("coalesce").and_then(Value::as_str).filter(|_| p.get("preset").is_none() && p.get("reset").is_none());diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rsindex 9ef435169..e963ac70f 100644--- a/crates/engine/src/brush_cmds/tests.rs+++ b/crates/engine/src/brush_cmds/tests.rs@@ -541,3 +541,50 @@ fn coalesced_set_brush_calls_journal_once_per_gesture() {}assert_eq!(t.tools.brush, s.tools.brush);}++/// A Scatter amount beyond the 1000 % maximum (the issue's 1e38, just above the maximum, or one+/// that only fits as infinity) is rejected naming the value, before the session brush changes, by+/// `tools.setBrush` and by a stroke's own brush patch; the maximum itself and an ordinary amount+/// above 100 % still paint (#977).+#[test]+fn out_of_range_scatter_is_rejected_and_the_maximum_still_paints() {+ let new = || {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s+ };+ let scatter = |j: f64| json!({"scattering": {"enabled": true, "bothAxes": true, "scatter": {"jitter": j}}});+ let dual = |j: f64| json!({"dualBrush": {"enabled": true, "bothAxes": true, "size": 6, "scatter": j}});+ let stroke = json!({"points": [[10, 10]]});+ for (j, shown) in [(1e38, "1e38"), (10.01, "10.01"), (1e39, "inf"), (-1.0, "-1.0")] {+ for (patch, what) in [(scatter(j), "scatter"), (dual(j), "dual brush scatter")] {+ let mut s = new();+ let before = s.tools.brush.clone();+ let err = s.execute("tools.setBrush", json!({ "brush": patch.clone() })).unwrap_err();+ let msg = err.to_string();+ assert!(matches!(err, EngineError::BadParams { .. }) && msg.contains(what) && msg.contains(shown), "{j}: {msg}");+ assert_eq!(s.tools.brush, before, "a rejected scatter must not change the session brush");+ let (doc, revision) = (s.active().unwrap().doc.clone(), s.active().unwrap().revision);+ let err = paint_stroke(&mut s, &json!({"points": [[10, 10]], "brush": patch})).unwrap_err();+ assert!(matches!(err, EngineError::BadParams { .. }) && err.to_string().contains(shown), "{j}: {err}");+ assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc) && s.active().unwrap().revision == revision);+ }+ }+ // The issue's repro, end to end: a stroke after the rejected update still paints normally.+ let mut s = new();+ assert!(s.execute("tools.setBrush", json!({ "brush": scatter(1e38) })).is_err());+ assert!(s.execute("paint.stroke", stroke.clone()).is_ok());+ // The maximum (1000 %) is accepted and paints a finite, well-formed dab.+ for patch in [scatter(10.0), dual(10.0)] {+ let mut s = new();+ s.execute("tools.setBrush", json!({ "brush": patch })).unwrap();+ let r = s.execute("paint.stroke", stroke.clone()).unwrap();+ let d: Vec<i64> = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect();+ assert!(d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0, "{r}");+ }+ // Control: 200 % scatter paints where it did before the cap.+ let mut s = new();+ s.execute("tools.setBrush", json!({ "brush": scatter(2.0) })).unwrap();+ assert_eq!(s.execute("paint.stroke", stroke).unwrap(), json!({"damage": [17, 14, 23, 23]}));+}diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rsindex a531e92b7..611f0053a 100644--- a/crates/engine/src/retouch_cmds.rs+++ b/crates/engine/src/retouch_cmds.rs@@ -91,7 +91,7 @@ fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option<Layeerase: false,..base};- crate::brush_cmds::validate_brush_size(&brush, cmd)?;+ crate::brush_cmds::validate_brush(&brush, cmd)?;if crate::channel_cmds::is_channel_target(p) {return Ok((Stroke { brush, points: pts }, None));}diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rsindex 396ec7840..ddd089bfe 100644--- a/crates/engine/src/vector_cmds.rs+++ b/crates/engine/src/vector_cmds.rs@@ -1016,7 +1016,7 @@ fn path_stroke(s: &mut Session, p: &Value) -> Result<Value> {"brush" | "eraser" => {}o => return Err(bad("path.stroke", format!("unknown tool `{o}` (brush|pencil|eraser)"))),}- crate::brush_cmds::validate_brush_size(&brush, "path.stroke")?;+ crate::brush_cmds::validate_brush(&brush, "path.stroke")?;let lines = vector::flatten_path(&path, 0.1);let id = layer_id(s, p)?;let bg = s.tools.background;diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rsindex b43a39c73..914fc1a8e 100644--- a/crates/paint/src/brush.rs+++ b/crates/paint/src/brush.rs@@ -16,6 +16,11 @@ use crate::tile::GrayTile;/// Largest brush diameter accepted by the rasterizer and brush controls.pub const MAX_BRUSH_SIZE: f32 = 5000.0;+/// Largest Scatter amount (primary and Dual Brush): 10 = 1000 %, the Brush Settings slider's top.+/// Beyond it a dab could land arbitrarily far away, and an unbounded amount overflowed the dab+/// centre to infinity (#977).+pub const MAX_SCATTER: f32 = 10.0;+/// What drives a dynamic parameter (Photoshop's "Control" pop-ups).#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -461,17 +466,23 @@ impl Default for BrushSettings {}impl BrushSettings {- /// Copy the settings with the primary and dual diameters constrained for rasterization.+ /// Copy the settings with the primary and dual diameters and Scatter amounts constrained for+ /// rasterization.////// Engine commands reject out-of-range values; this is a final guard for direct users of the- /// infallible paint API, which must not turn malformed brush dimensions into giant allocations.+ /// infallible paint API, which must not turn malformed brush dimensions into giant allocations,+ /// nor a huge Scatter amount into non-finite dab centres (#977).pub fn bounded_for_render(&self) -> Self {let safe_size = |size: f32| {if size.is_finite() { size.clamp(0.5, MAX_BRUSH_SIZE) } else { 0.5 }};+ // NaN scatters nothing (as before: it never passed the `> 0` check); infinity is the maximum.+ let safe_scatter = |amount: f32| if amount.is_nan() { 0.0 } else { amount.clamp(0.0, MAX_SCATTER) };let mut brush = self.clone();brush.size = safe_size(brush.size);brush.dual_brush.size = safe_size(brush.dual_brush.size);+ brush.scattering.scatter.jitter = safe_scatter(brush.scattering.scatter.jitter);+ brush.dual_brush.scatter = safe_scatter(brush.dual_brush.scatter);brush}diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rsindex fca342801..2c5758ec2 100644--- a/crates/paint/src/brush_tests.rs+++ b/crates/paint/src/brush_tests.rs@@ -878,3 +878,80 @@ fn transfer_wetness_and_mix_vary_per_dab() {assert!(old.spacing_enabled && !old.shape_dynamics.brush_projection && old.shape_dynamics.tilt_scale == 0.0 && old.locks == SectionLocks::default());assert_eq!(old.mixer, crate::mixer::MixerSettings::default());}++/// Primary and Dual Brush dabs of a stroke (the generator, as the renderer drives it).+fn all_dabs(b: &BrushSettings, pts: &[StrokePoint]) -> (Vec<Dab>, Vec<Dab>) {+ let mut g = crate::dynamics::DabGenerator::new(b, 1.0);+ let (mut dabs, mut duals) = (Vec::new(), Vec::new());+ g.push(pts, &mut dabs, &mut duals);+ g.finish(&mut dabs, &mut duals);+ (dabs, duals)+}++/// A Scatter amount far beyond the 1000 % maximum (or non-finite), on the primary tip or the+/// Dual Brush, used to push dab centres to infinity and overflow the dab rectangle (#977). The+/// renderer caps it at the maximum, so dabs stay finite and within reach, and painting works at+/// every bit depth.+#[test]+fn huge_scatter_is_capped_and_renders_at_every_depth() {+ let pts = line(10.0, 40.0, 10.0);+ let with = |j: f32| BrushSettings {+ size: 20.0,+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(j), both_axes: true, count: 4, ..Default::default() },+ dual_brush: DualBrush { enabled: true, size: 6.0, scatter: j, both_axes: true, ..Default::default() },+ ..brush()+ };+ let capped = all_dabs(&with(MAX_SCATTER), &pts);+ // Primary reach: MAX_SCATTER radii of 10 px; dual reach: MAX_SCATTER radii of 3 px.+ let near = |ds: &[Dab], r: f64| ds.iter().all(|d| (d.center.x - 25.0).abs() <= 15.0 + r && (d.center.y - 10.0).abs() <= r);+ assert!(near(&capped.0, f64::from(MAX_SCATTER) * 10.0) && near(&capped.1, f64::from(MAX_SCATTER) * 3.0));+ for j in [MAX_SCATTER + 0.01, 1e6, 1e38, f32::MAX, f32::INFINITY] {+ let b = with(j);+ assert_eq!(all_dabs(&b, &pts), capped, "scatter {j} paints like the maximum");+ let ctx = BrushContext::new(&b);+ for d in &capped.0 {+ let r = ctx.dab_rect(d, false);+ assert!(!r.is_empty() && r.width() <= 24 && r.height() <= 24, "{r:?}");+ }+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));+ let damage = render_stroke(&mut s, &b, &pts, None, false, 1.0);+ assert!(!damage.is_empty() && damage.x0 > -200 && damage.x1 < 250, "scatter {j} at {sample:?}: {damage:?}");+ }+ }+ // A NaN amount scatters nothing, as a zero amount does.+ let none = all_dabs(&with(0.0), &pts);+ assert_eq!(all_dabs(&with(f32::NAN), &pts), none);+ assert!(none.0.iter().all(|d| d.center.y == 10.0));+}++/// Control: an ordinary Scatter amount above 100 % still scatters, unchanged by the cap (#977).+#[test]+fn ordinary_scatter_is_unchanged_by_the_cap() {+ let b = BrushSettings {+ size: 20.0,+ scattering: Scattering { enabled: true, scatter: Dynamic::jitter(2.0), both_axes: true, count: 3, ..Default::default() },+ dual_brush: DualBrush { enabled: true, size: 6.0, scatter: 1.5, both_axes: true, ..Default::default() },+ ..brush()+ };+ assert_eq!(b.bounded_for_render(), b);+ let (dabs, duals) = all_dabs(&b, &line(10.0, 200.0, 50.0));+ assert!(dabs.iter().any(|d| (d.center.y - 50.0).abs() > 10.0) && dabs.iter().all(|d| (d.center.y - 50.0).abs() <= 20.0));+ assert!(duals.iter().any(|d| (d.center.y - 50.0).abs() > 1.0) && duals.iter().all(|d| (d.center.y - 50.0).abs() <= 4.5));+}++/// The dab rectangle of a hostile centre (non-finite or beyond `i32`), from a direct caller of the+/// public API, saturates instead of overflowing (#977).+#[test]+fn dab_rect_of_a_far_or_non_finite_centre_does_not_overflow() {+ let ctx = BrushContext::new(&brush());+ for c in [f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 1e300, -1e300, f64::from(i32::MAX), f64::from(i32::MIN)] {+ let d = Dab::round(Point::new(c, c), 10.0, 1.0);+ for r in [ctx.dab_rect(&d, false), ctx.dab_rect(&d, true), crate::retouch::dab_rect(&d)] {+ assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "centre {c}: {r:?}");+ }+ }+ let huge = Dab::round(Point::new(5.0, 5.0), f32::INFINITY, 1.0);+ let r = crate::retouch::dab_rect(&huge);+ assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "{r:?}");+}diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rsindex 27fa5882a..6601a9f74 100644--- a/crates/paint/src/lib.rs+++ b/crates/paint/src/lib.rs@@ -31,8 +31,8 @@ pub mod rng;pub mod tile;pub use brush::{- BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MAX_BRUSH_SIZE, MaskMode, Pattern, PatternStyle, Pose, Scattering, SectionLocks,- ShapeDynamics, Smoothing, Texture, TipShape, Transfer,+ BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MAX_BRUSH_SIZE, MAX_SCATTER, MaskMode, Pattern, PatternStyle, Pose, Scattering,+ SectionLocks, ShapeDynamics, Smoothing, Texture, TipShape, Transfer,};pub use mixer::MixerSettings;pub use render::{BrushContext, StrokeRenderer, grid_center, grid_square, render_stroke};diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rsindex f76b11b2b..f84bca494 100644--- a/crates/paint/src/render.rs+++ b/crates/paint/src/render.rs@@ -109,6 +109,15 @@ fn prepare_pattern(b: &BrushSettings) -> Option<Arc<PatternImage>> {Some(Arc::new(img))}+/// The pixel rectangle `reach` (plus 1 px of anti-aliasing slack) around a dab's centre. The casts+/// saturate and the arithmetic saturates, so a far or non-finite centre or reach from a direct+/// caller gives a (possibly empty) rectangle instead of an `i32` overflow (#977).+pub(crate) fn rect_around(d: &Dab, reach: f32) -> Rect {+ let rr = (reach.ceil() as i32).saturating_add(1);+ let (cx, cy) = (d.center.x.floor() as i32, d.center.y.floor() as i32);+ Rect::new(cx.saturating_sub(rr), cy.saturating_sub(rr), cx.saturating_add(rr).saturating_add(1), cy.saturating_add(rr).saturating_add(1))+}+impl BrushContext {pub fn new(brush: &BrushSettings) -> Self {let brush = brush.bounded_for_render();@@ -145,9 +154,7 @@ impl BrushContext {pub fn dab_rect(&self, d: &Dab, dual: bool) -> Rect {let sampled = if dual { self.dual_tip.is_some() } else { self.tip.is_some() };let reach = if sampled { d.radius * std::f32::consts::SQRT_2 } else { d.radius };- let rr = reach.ceil() as i32 + 1;- let (cx, cy) = (d.center.x.floor() as i32, d.center.y.floor() as i32);- Rect::new(cx - rr, cy - rr, cx + rr + 1, cy + rr + 1)+ rect_around(d, reach)}/// Rasterise a dab over `rect` into `out` (tip shape × noise × per-tip texture × wet edges × flow).diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rsindex 9e316d106..7e853d837 100644--- a/crates/paint/src/retouch.rs+++ b/crates/paint/src/retouch.rs@@ -97,9 +97,7 @@ impl Footprint {/// Bounding rectangle of a dab (1 px of anti-aliasing slack included).pub fn dab_rect(d: &Dab) -> Rect {- let rr = d.radius.ceil() as i32 + 1;- let (cx, cy) = (d.center.x.floor() as i32, d.center.y.floor() as i32);- Rect::new(cx - rr, cy - rr, cx + rr + 1, cy + rr + 1)+ crate::render::rect_around(d, d.radius)}/// Rasterize one dab's coverage.