From a8f21a383d81bd034644cfec31c5fc82d08b71df Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:07:38 +0000 Subject: [PATCH] Brush tip is Tracked: the Brush Preset field runs only for the presets, the tip and the values it shows photocraft-paint's BrushSettings::tip is a Tracked; tools.setBrush keeps its revision when the new brush's tip equals the old one. The options bar's field takes the presets, the tip and a BrushFace (size, hardness, angle, roundness) as props instead of the whole brush, so an Opacity or Flow write replays it. Trial: brush_settle_trials. --- crates/engine/examples/bench_big_brush.rs | 2 +- crates/engine/examples/bench_brush_mips.rs | 2 +- crates/engine/src/cmd/brush_cmds.rs | 15 ++++-- .../define_brush_color_density_tests.rs | 2 +- .../define_brush_merged_source_tests.rs | 2 +- .../define_brush_no_selection_tests.rs | 2 +- .../src/cmd/brush_cmds/mixer_live_tests.rs | 2 +- crates/engine/src/cmd/brush_cmds/tests.rs | 8 +-- crates/engine/src/cmd/edit_menu_cmds/tests.rs | 2 +- crates/engine/src/cmd/preset_import_cmds.rs | 6 +-- crates/engine/src/cmd/retouch_cmds/tests.rs | 2 +- crates/engine/src/preset_store.rs | 10 ++-- crates/engine/src/preset_store/tests.rs | 26 ++++----- crates/io/src/abr_map.rs | 6 +-- crates/io/src/abr_map/tests.rs | 6 +-- crates/paint/Cargo.toml | 2 +- crates/paint/src/brush.rs | 8 ++- crates/paint/src/brush_tests.rs | 6 +-- crates/paint/src/mip_cache_render_tests.rs | 10 ++-- crates/paint/src/outline.rs | 6 +-- crates/paint/src/presets.rs | 26 ++++----- crates/paint/src/render/reference.rs | 6 +-- crates/paint/src/tile.rs | 4 +- crates/ui-egui/src/brush_settle_trials.rs | 44 +++++++++++++++ crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/panels/brush_panel/brushes.rs | 11 ++-- .../ui-egui/src/panels/brush_panel/tests.rs | 6 +-- crates/ui-egui/src/panels/brush_preview.rs | 2 +- crates/ui-egui/src/panels/brush_sections.rs | 4 +- crates/ui-egui/src/prefs/prefs_ui/tests.rs | 4 +- crates/ui-egui/src/preset_files_ui.rs | 2 +- crates/ui-egui/src/tools/brush_cursor.rs | 4 +- crates/ui-egui/src/tools/brush_picker.rs | 54 ++++++++++++------- 33 files changed, 183 insertions(+), 111 deletions(-) create mode 100644 crates/ui-egui/src/brush_settle_trials.rs diff --git a/crates/engine/examples/bench_big_brush.rs b/crates/engine/examples/bench_big_brush.rs index 5c08a18e14..5a7f0c3bfc 100644 --- a/crates/engine/examples/bench_big_brush.rs +++ b/crates/engine/examples/bench_big_brush.rs @@ -49,7 +49,7 @@ fn main() -> Result<(), Box> { "transfer": {"enabled": true, "opacity": pressure, "flow": pressure}, }))?, }; - base.tip = TipShape::Sampled(tip(70, 73, 1)); + *base.tip = TipShape::Sampled(tip(70, 73, 1)); base.dual_brush.tip = TipShape::Sampled(tip(100, 97, 2)); let mut no_dual = base.clone(); no_dual.dual_brush.enabled = false; diff --git a/crates/engine/examples/bench_brush_mips.rs b/crates/engine/examples/bench_brush_mips.rs index 33ed7417eb..de7798dd29 100644 --- a/crates/engine/examples/bench_brush_mips.rs +++ b/crates/engine/examples/bench_brush_mips.rs @@ -51,7 +51,7 @@ fn main() -> Result<(), Box> { // A fresh allocation makes every cold preparation a genuine miss. Copying // samples and materializing the document are outside all measured stages. for trial in 0..8 { - s.tools.brush.tip = original + *s.tools.brush.tip = original .as_ref() .map_or(TipShape::Round, |t| TipShape::Sampled(GrayTile { width: t.width, height: t.height, data: t.data.as_ref().to_vec().into() })); let t = Instant::now(); diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index f2ccdeb3dc..c0d43e1670 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -996,7 +996,7 @@ fn presets_list(s: &mut Session, p: &Value) -> Result { "builtin": pr.builtin, "size": pr.brush.size, "hardness": pr.brush.hardness, - "tip": match &pr.brush.tip { TipShape::Round => "round", TipShape::Sampled(_) | TipShape::Stored(_) => "sampled" }, + "tip": match &*pr.brush.tip { TipShape::Round => "round", TipShape::Sampled(_) | TipShape::Stored(_) => "sampled" }, }); if full { // Full settings embed the bitmaps: load stored tips (a tip that can't be loaded @@ -1247,7 +1247,7 @@ pub(crate) fn sampled_brush(cmd: &str, v: &[f32], w: usize, h: usize) -> Result< data.extend((x0..x1).map(|x| at(x, y))); } let tip = GrayTile::from_f32(tw, th, &data); - let brush = BrushSettings { tip: TipShape::Sampled(tip), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() }; + let brush = BrushSettings { tip: TipShape::Sampled(tip).into(), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() }; Ok((brush, tw, th)) } @@ -1298,7 +1298,12 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result { s.tools.foreground = c; } } - let before = std::mem::replace(&mut *s.tools.brush, b); + let mut before = std::mem::replace(&mut *s.tools.brush, b); + // A brush the call built anew holds a new tip source: when the tip is the one it had, it keeps its revision, so the + // views that show the tip replay. + if s.tools.brush.tip == before.tip { + std::mem::swap(&mut s.tools.brush.tip, &mut before.tip); + } // 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()); let continuing = |s: &Session, k: &str| { @@ -1342,7 +1347,7 @@ fn remembered_brush(s: &Session) -> Option { pub fn remembered_settings(b: &BrushSettings) -> Option { let (tip, dual, pattern) = (ref_tip(&b.tip)?, ref_tip(&b.dual_brush.tip)?, ref_pattern(&b.texture.pattern)?); let mut c = b.clone(); - (c.tip, c.dual_brush.tip, c.texture.pattern) = (tip, dual, pattern); + (c.tip, c.dual_brush.tip, c.texture.pattern) = (tip.into(), dual, pattern); serde_json::to_value(&c).ok() } @@ -1402,7 +1407,7 @@ fn ref_pattern(p: &Pattern) -> Option { fn light_json(b: &BrushSettings, skip: (bool, bool, bool)) -> Value { let mut c = b.clone(); if skip.0 { - c.tip = TipShape::Round; + c.tip = TipShape::Round.into(); } if skip.1 { c.dual_brush.tip = TipShape::Round; diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs index 8a1cd6391a..e7d27eb57a 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs @@ -76,7 +76,7 @@ fn rgb_source(depth: u32, rgba: [f32; 4]) -> Session { } fn tip(s: &Session) -> &GrayTile { - let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + let TipShape::Sampled(tip) = &*s.tools.brush.tip else { panic!("expected a sampled tip") }; tip } diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs index b037a4a692..8848e1df2e 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs @@ -4,7 +4,7 @@ use photocraft_doc::Layer; const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"]; fn tip(s: &Session) -> &GrayTile { - let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + let TipShape::Sampled(tip) = &*s.tools.brush.tip else { panic!("expected a sampled tip") }; tip } diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs index bfa6bab374..f15bdb4ec9 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs @@ -17,7 +17,7 @@ fn source(depth: u32) -> Session { } fn tip(s: &Session) -> &GrayTile { - let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + let TipShape::Sampled(tip) = &*s.tools.brush.tip else { panic!("expected a sampled tip") }; tip } diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs index f277e32720..be24f3038e 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs @@ -385,7 +385,7 @@ fn mixer_default_does_not_sample_other_layers() { fn mixer_shared_live_commit_keeps_the_journal_compact() { let mut s = fixture(PixelFormat::RGBA8); s.execute("brush.mixer.sample", json!({"points":[[96,48]],"size":40})).unwrap(); - s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(256, 256, |_, _| 1.0)); + s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(256, 256, |_, _| 1.0)).into(); for x in [40.0, 60.0, 80.0] { let p = json!({"points":[[x,48]],"size":12,"seed":7,"wet":0,"mix":0}); let live = LiveMixer::begin(&s, &p).unwrap(); diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index cb996dde74..4d7013ca30 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -571,7 +571,7 @@ fn an_uncaptured_preset_size_keeps_dual_brush_proportions() { fn set_brush_keeps_untouched_bitmaps_and_replaces_touched_ones() { let tile = |w, h, k: u32| GrayTile::from_fn(w, h, move |x, y| ((x * k + y) % 5) as f32 / 4.0); let base = BrushSettings { - tip: TipShape::Sampled(tile(900, 700, 3)), + tip: TipShape::Sampled(tile(900, 700, 3)).into(), dual_brush: photocraft_paint::DualBrush { tip: TipShape::Sampled(tile(30, 20, 2)), ..Default::default() }, texture: photocraft_paint::Texture { pattern: photocraft_paint::Pattern::Tile(tile(64, 64, 1)), ..Default::default() }, ..Default::default() @@ -591,13 +591,13 @@ fn set_brush_keeps_untouched_bitmaps_and_replaces_touched_ones() { cmd, ) .unwrap(); - assert_eq!((&b.tip, &b.dual_brush.tip), (&TipShape::Round, &TipShape::Round)); + assert_eq!((&*b.tip, &b.dual_brush.tip), (&TipShape::Round, &TipShape::Round)); assert!(matches!(b.texture.pattern, photocraft_paint::Pattern::Procedural { size: 32, .. })); // A section replaced by a non-object is an error, not a silently kept bitmap. assert!(merge_brush(&base, &json!({"dualBrush": 3}), cmd).is_err()); assert!(merge_brush(&base, &json!(null), cmd).is_err()); // Speed: a panel edit on a big imported tip doesn't base64 the tip. - let big = BrushSettings { tip: TipShape::Sampled(tile(2500, 2500, 7)), ..Default::default() }; + let big = BrushSettings { tip: TipShape::Sampled(tile(2500, 2500, 7)).into(), ..Default::default() }; let t0 = std::time::Instant::now(); for i in 0..10 { merge_brush(&big, &json!({"size": 10 + i}), cmd).unwrap(); @@ -620,7 +620,7 @@ fn define_brush_from_selection() { let r = s.execute("brush.defineFromSelection", json!({"name": "Blob"})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(6), Some(4))); assert_eq!(s.tools.brush.size, 6.0); - assert!(matches!(&s.tools.brush.tip, TipShape::Sampled(t) if t.width == 6 && t.height == 4 && t.get(0, 0) == 1.0)); + assert!(matches!(&*s.tools.brush.tip, TipShape::Sampled(t) if t.width == 6 && t.height == 4 && t.get(0, 0) == 1.0)); assert!(s.tools.presets.iter().any(|p| p.name == "Blob")); // Paint with it. s.execute("select.deselect", json!({})).unwrap(); diff --git a/crates/engine/src/cmd/edit_menu_cmds/tests.rs b/crates/engine/src/cmd/edit_menu_cmds/tests.rs index 092b0f0158..4b49b954eb 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/tests.rs @@ -251,7 +251,7 @@ fn purge_all_releases_prepared_brush_tips_even_without_a_document() { let _purge_test_guard = PURGE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use photocraft_paint::{BrushContext, BrushSettings, Dab, GrayTile, TipShape}; let mut s = Session::new(); - let brush = BrushSettings { tip: TipShape::Sampled(GrayTile::from_fn(31, 17, |x, y| ((x + y) % 5) as f32 / 4.0)), ..Default::default() }; + let brush = BrushSettings { tip: TipShape::Sampled(GrayTile::from_fn(31, 17, |x, y| ((x + y) % 5) as f32 / 4.0)).into(), ..Default::default() }; let ctx = BrushContext::new(&brush); let dab = Dab::round(photocraft_geom::Point::new(12.5, 14.5), 10.0, 1.0); let rect = ctx.dab_rect(&dab, false); diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 8dd706b078..02e115630b 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -509,7 +509,7 @@ mod tests { assert_eq!(r["imported"], json!(["Hard Round 2", "9 px Round"])); assert_eq!(s.tools.presets.len(), before + 2); assert!(s.tools.presets.iter().filter(|p| p.group == "Legacy").all(|p| !p.builtin)); - assert!(matches!(s.tools.brush.tip, photocraft_paint::TipShape::Sampled(_))); + assert!(matches!(*s.tools.brush.tip, photocraft_paint::TipShape::Sampled(_))); // Re-import with `replace` replaces the group. s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy", "replace": true})).unwrap(); assert_eq!(s.tools.presets.len(), before + 2); @@ -758,11 +758,11 @@ mod tests { let r = s.execute("brush.presets.importImage", json!({"data": data, "fileName": "Stamp.png"})).unwrap(); assert_eq!(r, json!({"name": "Stamp", "width": 10, "height": 6}), "cropped to the dark block"); let pr = s.tools.presets.iter().find(|p| p.name == "Stamp").unwrap(); - let TipShape::Sampled(tip) = &pr.brush.tip else { panic!("sampled tip expected") }; + let TipShape::Sampled(tip) = &*pr.brush.tip else { panic!("sampled tip expected") }; assert_eq!((tip.width, tip.height), (10, 6)); assert!((pr.brush.size - 10.0).abs() < 1e-6); assert_eq!(s.tools.current_preset.as_deref(), Some("Stamp"), "the imported brush is current"); - assert!(matches!(s.tools.brush.tip, TipShape::Sampled(_))); + assert!(matches!(*s.tools.brush.tip, TipShape::Sampled(_))); // A second import keeps the first: a new name, and `select: false` leaves the brush alone. let r = s.execute("brush.presets.importImage", json!({"data": data, "fileName": "Stamp.png", "select": false})).unwrap(); assert_eq!(r["name"], "Stamp 2"); diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 9d59a301b0..82d0bb0302 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2394,7 +2394,7 @@ fn live_dab_batches_match_the_accumulating_renderer() { for case in ["soft", "hard", "sampled", "dynamics", "smoothing", "smoothing_catch_up"] { *s.tools.brush = BrushSettings::default(); match case { - "sampled" => s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(9, 7, |x, y| ((x * 3 + y) % 11) as f32 / 10.0)), + "sampled" => s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(9, 7, |x, y| ((x * 3 + y) % 11) as f32 / 10.0)).into(), "dynamics" => { let b = &mut s.tools.brush; b.scattering.enabled = true; diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index cf80f952b2..624c7e04f3 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -402,7 +402,7 @@ fn settings_only(b: &mut BrushSettings) -> BrushSettings { fn set_stored(b: &mut BrushSettings, refs: [Option; 3]) { let [tip, dual, texture] = refs; if let Some(r) = tip { - b.tip = TipShape::Stored(r); + b.tip = TipShape::Stored(r).into(); } if let Some(r) = dual { b.dual_brush.tip = TipShape::Stored(r); @@ -1236,7 +1236,7 @@ impl Session { } Ok(()) }; - if let TipShape::Stored(r) = &mut b.tip { + if let TipShape::Stored(r) = &mut *b.tip { load(r)?; } if let TipShape::Stored(r) = &mut b.dual_brush.tip { @@ -1261,11 +1261,11 @@ fn link_stored_tips(st: &PresetStore, b: &mut BrushSettings) -> bool { st.tips.contains_key(&h).then(|| StoredTile { key: h, width: g.width, height: g.height, preview: Arc::new(g.preview(PREVIEW_SIDE)), full: None }) }; let mut linked = false; - if let TipShape::Sampled(g) = &b.tip + if let TipShape::Sampled(g) = &*b.tip && let Some(r) = link(g) - && let TipShape::Sampled(g) = std::mem::take(&mut b.tip) + && let TipShape::Sampled(g) = std::mem::take(&mut *b.tip) { - b.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(g)), ..r }); + b.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(g)), ..r }).into(); linked = true; } if let TipShape::Sampled(g) = &b.dual_brush.tip diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index acbbd8db42..3088cdcc6d 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -44,7 +44,7 @@ fn tip16(w: u32, h: u32, seed: u32) -> GrayTile { } fn sampled(name: &str, group: &str, tip: GrayTile) -> BrushPreset { - let brush = BrushSettings { size: 42.0, spacing: 0.1, tip: TipShape::Sampled(tip), ..Default::default() }; + let brush = BrushSettings { size: 42.0, spacing: 0.1, tip: TipShape::Sampled(tip).into(), ..Default::default() }; BrushPreset { name: name.into(), brush, builtin: false, group: group.into(), folder: Vec::new(), captures: Default::default() } } @@ -169,7 +169,7 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() { // 16-bit ones: an 8-bit tip this small is its own preview. assert_eq!(files.iter().filter(|f| f.starts_with("tips/")).count(), 6, "{files:?}"); // The session keeps previews, not the bitmaps (#1843). - assert!(user(&s).iter().all(|p| matches!(&p.brush.tip, TipShape::Stored(r) if !r.is_loaded()))); + assert!(user(&s).iter().all(|p| matches!(&*p.brush.tip, TipShape::Stored(r) if !r.is_loaded()))); assert!(files.contains(&INDEX_FILE.to_string())); let (t, w) = session(&dir); @@ -189,11 +189,11 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() { fn commands_persist_and_delete_removes_from_disk() { let dir = TempDir::new("commands"); let (mut s, _) = session(&dir); - s.tools.brush.tip = TipShape::Sampled(tip16(20, 20, 4)); + s.tools.brush.tip = TipShape::Sampled(tip16(20, 20, 4)).into(); s.execute("brush.presets.save", json!({"name": "Scribble"})).unwrap(); assert_eq!(dir.files().iter().filter(|f| f.starts_with("tips/")).count(), 2, "the tip and its preview"); // The tool's brush now is the saved preset's stored tip, still loaded. - assert!(matches!(&s.tools.brush.tip, TipShape::Stored(r) if r.is_loaded())); + assert!(matches!(&*s.tools.brush.tip, TipShape::Stored(r) if r.is_loaded())); let (t, _) = session(&dir); let p = photocraft_paint::presets::find(&t.tools.presets, "Scribble").expect("saved preset reloads"); assert_eq!(p.brush.tip, s.tools.brush.tip); @@ -397,7 +397,7 @@ fn write_failures_are_warnings() { std::fs::write(&dir.0, b"not a dir").unwrap(); let mut s = Session::new(); s.attach_preset_store(open_dir(&dir.0)); - s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)); + s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)).into(); s.execute("brush.presets.save", json!({"name": "Nope"})).unwrap(); let w = s.preset_store.as_mut().unwrap().take_warnings(); assert!(!w.is_empty()); @@ -510,7 +510,7 @@ fn reopening_a_library_decodes_no_tips_and_using_a_brush_decodes_only_its_own() let user_presets = user(&t); assert_eq!(user_presets.len(), n as usize); for p in &user_presets { - let TipShape::Stored(r) = &p.brush.tip else { panic!("{} is not a stored tip", p.name) }; + let TipShape::Stored(r) = &*p.brush.tip else { panic!("{} is not a stored tip", p.name) }; assert!(!r.is_loaded() && (r.width, r.height) == (side, side)); assert!(r.preview.width <= PREVIEW_SIDE && r.preview.height <= PREVIEW_SIDE); } @@ -520,7 +520,7 @@ fn reopening_a_library_decodes_no_tips_and_using_a_brush_decodes_only_its_own() // Using one brush decodes exactly its tip; painting and picking it again reuse it. t.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); t.execute("tools.setBrush", json!({"preset": "Big 3"})).unwrap(); - let TipShape::Stored(r) = &t.tools.brush.tip else { panic!("the brush keeps its stored tip") }; + let TipShape::Stored(r) = &*t.tools.brush.tip else { panic!("the brush keeps its stored tip") }; assert_eq!(r.full.as_deref(), Some(&tip8(side, side, 3)), "the tool paints with the full tip"); assert_eq!(cache(&t).decodes, 1); t.execute("paint.stroke", json!({"points": [[10, 10], [50, 50]], "brush": {"size": 30}})).unwrap(); @@ -528,7 +528,7 @@ fn reopening_a_library_decodes_no_tips_and_using_a_brush_decodes_only_its_own() t.execute("tools.setBrush", json!({"preset": "Big 3"})).unwrap(); assert_eq!((cache(&t).decodes, cache(&t).tips), (1, 1)); // Picking a preset never loads the library's other tips, and the library stays light. - assert!(user(&t).iter().all(|p| matches!(&p.brush.tip, TipShape::Stored(r) if !r.is_loaded()))); + assert!(user(&t).iter().all(|p| matches!(&*p.brush.tip, TipShape::Stored(r) if !r.is_loaded()))); // The panel's "current brush" match still works on a stored tip. let picked = photocraft_paint::presets::find(&t.tools.presets, "Big 3").unwrap(); assert_eq!(picked.brush.tip, t.tools.brush.tip); @@ -558,7 +558,7 @@ fn the_decoded_tip_cache_stays_within_its_budget() { t.preset_store.as_ref().unwrap().set_tip_cache_limit(0); assert_eq!(cache(&t).tips, 0); t.execute("tools.setBrush", json!({"preset": "Big 1"})).unwrap(); - assert!(matches!(&t.tools.brush.tip, TipShape::Stored(r) if r.is_loaded())); + assert!(matches!(&*t.tools.brush.tip, TipShape::Stored(r) if r.is_loaded())); } #[test] @@ -568,7 +568,7 @@ fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() { let mut t = Session::new(); t.attach_preset_store(open(Box::new(mem.clone()))); t.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); - let key = |t: &Session, name: &str| match &photocraft_paint::presets::find(&t.tools.presets, name).unwrap().brush.tip { + let key = |t: &Session, name: &str| match &*photocraft_paint::presets::find(&t.tools.presets, name).unwrap().brush.tip { TipShape::Stored(r) => r.key.clone(), other => panic!("{other:?}"), }; @@ -629,7 +629,7 @@ fn a_store_without_previews_makes_them_once_and_then_loads_lazily() { let w = s.attach_preset_store(open(Box::new(mem.clone()))); assert!(w.is_empty(), "{w:?}"); let a = photocraft_paint::presets::find(&s.tools.presets, "Old A").unwrap().clone(); - assert!(matches!(&a.brush.tip, TipShape::Stored(r) if (r.width, r.height) == (300, 200) && !r.is_loaded())); + assert!(matches!(&*a.brush.tip, TipShape::Stored(r) if (r.width, r.height) == (300, 200) && !r.is_loaded())); assert!(matches!(&a.brush.texture.pattern, Pattern::Stored(r) if r.key == hashes[1])); // Attaching rewrote the group with sizes and previews. let rewritten: serde_json::Value = serde_json::from_slice(&mem.read(&file, MAX_GROUP_BYTES).unwrap()).unwrap(); @@ -649,7 +649,7 @@ fn a_store_without_previews_makes_them_once_and_then_loads_lazily() { let out = t.execute("edit.presets.exportImportPresets", json!({"action": "export"})).unwrap(); let back: Vec = serde_json::from_value(out["data"]["brushes"].clone()).unwrap(); let a = back.iter().find(|p| p.name == "Old A").unwrap(); - assert_eq!(a.brush.tip, TipShape::Sampled(tips[0].clone())); + assert_eq!(a.brush.tip, TipShape::Sampled(tips[0].clone()).into()); assert_eq!(a.brush.texture.pattern, Pattern::Tile(tips[1].clone())); } @@ -751,7 +751,7 @@ fn a_group_file_that_failed_to_load_is_not_overwritten() { mem.files.lock().unwrap().insert(file.clone(), newer.clone()); let mut s = Session::new(); s.attach_preset_store(open(Box::new(mem.clone()))); - s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)); + s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0)).into(); s.execute("brush.presets.save", json!({"name": "New"})).unwrap(); assert_eq!(mem.files.lock().unwrap().get(&file), Some(&newer), "a file the store could not read was overwritten"); assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty()); diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs index 9ca85b8830..12f1a5e966 100644 --- a/crates/io/src/abr_map.rs +++ b/crates/io/src/abr_map.rs @@ -82,7 +82,7 @@ pub fn map_file_with(f: &AbrFile, group: &str, ctl: &photocraft_raster::Interrup ), LegacyTip::Sampled(s) => { let (tip, size) = m.tip(s); - (BrushSettings { size, tip, aliased: !b.anti_alias, ..base }, format!("Sampled Brush {}", i + 1)) + (BrushSettings { size, tip: tip.into(), aliased: !b.anti_alias, ..base }, format!("Sampled Brush {}", i + 1)) } }; let name = if b.name.trim().is_empty() { default_name } else { b.name.trim().to_string() }; @@ -93,7 +93,7 @@ pub fn map_file_with(f: &AbrFile, group: &str, ctl: &photocraft_raster::Interrup for (i, s) in f.samples.iter().enumerate() { step(i)?; let (tip, size) = m.tip(s); - let brush = BrushSettings { pressure_size: false, spacing: 0.25, size, tip, ..Default::default() }; + let brush = BrushSettings { pressure_size: false, spacing: 0.25, size, tip: tip.into(), ..Default::default() }; out.presets.push(BrushPreset { name: format!("Sampled Brush {}", i + 1), brush, @@ -359,7 +359,7 @@ impl Mapper<'_> { let mut b = BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() }; if let Some(t) = obj(d, "Brsh") { let (tip, sampled_size) = self.tip_shape(t)?; - b.tip = tip; + b.tip = tip.into(); b.size = num(t, "Dmtr").map(|v| v as f32).or(sampled_size).unwrap_or(b.size).clamp(1.0, 5000.0); if let Some(v) = pct(t, "Hrdn") { b.hardness = v.clamp(0.0, 1.0); diff --git a/crates/io/src/abr_map/tests.rs b/crates/io/src/abr_map/tests.rs index 930af83fa6..fd4e6a8c52 100644 --- a/crates/io/src/abr_map/tests.rs +++ b/crates/io/src/abr_map/tests.rs @@ -177,7 +177,7 @@ fn v6_settings_map_onto_brush_sections() { let p = &imp.presets[0]; assert_eq!((p.name.as_str(), p.group.as_str(), p.builtin), ("Kitchen Sink", "Test", false)); let b = &p.brush; - let TipShape::Sampled(tile) = &b.tip else { panic!("sampled tip expected") }; + let TipShape::Sampled(tile) = &*b.tip else { panic!("sampled tip expected") }; assert_eq!((tile.width, tile.height), (16, 8)); assert_eq!((tile.data[0], tile.data[1]), (65535, 0)); assert_eq!((b.size, b.angle, b.roundness, b.spacing, b.flip_x, b.flip_y), (64.0, 30.0, 0.8, 0.4, true, false)); @@ -210,7 +210,7 @@ fn v6_settings_map_onto_brush_sections() { assert!(imp.warnings.iter().any(|w| w.contains("someFutureKey")), "{:?}", imp.warnings); // The computed preset. let r = &imp.presets[1].brush; - assert_eq!((r.tip.clone(), r.size, r.hardness, r.spacing, r.pressure_size), (TipShape::Round, 19.0, 0.0, 0.1, false)); + assert_eq!(((*r.tip).clone(), r.size, r.hardness, r.spacing, r.pressure_size), (TipShape::Round, 19.0, 0.0, 0.1, false)); } } @@ -322,7 +322,7 @@ fn big_tips_are_downsampled() { let s = AbrSample { id: "$big".into(), width: 3000, height: 1500, depth: 8, data: vec![200; 3000 * 1500] }; let bytes = write_v6(2, &[s], &[], &[], true).unwrap(); let imp = read_abr(&bytes, "g").unwrap(); - let TipShape::Sampled(t) = &imp.presets[0].brush.tip else { panic!() }; + let TipShape::Sampled(t) = &*imp.presets[0].brush.tip else { panic!() }; assert_eq!((t.width, t.height), (MAX_TIP_EDGE, 1250)); assert_eq!(imp.presets[0].brush.size, 3000.0); assert!(imp.warnings.iter().any(|w| w.contains("downsampled"))); diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index ac72c7818c..0bcf2ef424 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -8,7 +8,7 @@ license.workspace = true workspace = true [dependencies] -craft-tracked = { workspace = true } +craft-tracked = { workspace = true, features = ["serde"] } craft-ui-macros = { workspace = true } photocraft-geom = { workspace = true } photocraft-color = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index e1bcac309c..9cead7df8f 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -7,6 +7,7 @@ //! Units: sizes are pixels, angles are degrees, every percentage is a 0..1 fraction (scatter and //! texture scale may exceed 1, like Photoshop's 1000 % scatter). +use craft_tracked::Tracked; use photocraft_color::BlendMode; use serde::{Deserialize, Serialize}; @@ -589,7 +590,10 @@ pub struct BrushSettings { #[plain_data(assume = "a fieldless enum of blend modes")] pub mode: BlendMode, // --- Brush Tip Shape --- - pub tip: TipShape, + /// Tracked on its own, so a reader that shows the tip (a picker's tip picture) knows by its revision whether the + /// tip changed, without comparing bitmaps. `tools.setBrush` keeps the tip's revision when it leaves the tip as it + /// is. + pub tip: Tracked, /// Degrees, counter-clockwise. pub angle: f32, /// 0..1 (1 = circle). @@ -647,7 +651,7 @@ impl Default for BrushSettings { erase: false, behind: false, mode: BlendMode::Normal, - tip: TipShape::Round, + tip: Tracked::new(TipShape::Round), angle: 0.0, roundness: 1.0, flip_x: false, diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 4880f0a5ab..558b3436de 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -118,7 +118,7 @@ fn hard_edge_is_sharp() { fn sampled_tip_is_scaled_and_oriented() { // Tip: left half painted. let tip = GrayTile::from_fn(16, 16, |x, _| if x < 8 { 1.0 } else { 0.0 }); - let b = BrushSettings { tip: TipShape::Sampled(tip), ..brush() }; + let b = BrushSettings { tip: TipShape::Sampled(tip).into(), ..brush() }; let d = Dab::round(Point::new(50.0, 50.0), 20.0, 1.0); let r = raster(&b, &d); assert!(at(&r, 40, 50) > 0.99 && at(&r, 60, 50) < 0.01); @@ -1351,7 +1351,7 @@ fn sampled_dabs_are_the_same_in_their_tight_box_with_rows_cut_to_the_tip() { // the pixels match scanning the whole square that fits any rotation, which is 0 elsewhere. let tip = GrayTile::from_fn(37, 23, |x, y| 0.05 + ((x * 7 + y * 13) % 11) as f32 / 11.0); let dual = DualBrush { enabled: true, tip: TipShape::Sampled(GrayTile::from_fn(15, 40, |x, _| 0.1 + (x % 3) as f32 / 3.0)), ..Default::default() }; - let b = BrushSettings { tip: TipShape::Sampled(tip), dual_brush: dual, ..brush() }; + let b = BrushSettings { tip: TipShape::Sampled(tip).into(), dual_brush: dual, ..brush() }; let ctx = BrushContext::new(&b); let half_pi = std::f32::consts::FRAC_PI_2; for angle in [0.0, 0.3, -1.1, half_pi, half_pi + 1e-6, half_pi - 3e-7, 3.0, std::f32::consts::PI] { @@ -1955,7 +1955,7 @@ fn general_loop_strokes_render_the_same_in_parallel_and_serially_at_every_depth( let tip = GrayTile::from_fn(16, 16, |x, y| if (x + y) % 3 == 0 { 1.0 } else { 0.4 }); let mut textured = BrushSettings { size: 120.0, hardness: 0.3, ..brush() }; textured.texture = Texture { enabled: true, pattern: Pattern::Tile(tip.clone()), each_tip: true, ..Default::default() }; - let strokes = [BrushSettings { size: 120.0, tip: TipShape::Sampled(tip), color: [0.9, 0.2, 0.1, 1.0], ..brush() }, textured]; + let strokes = [BrushSettings { size: 120.0, tip: TipShape::Sampled(tip).into(), color: [0.9, 0.2, 0.1, 1.0], ..brush() }, textured]; let full = Rect::new(0, 0, 400, 200); let formats = [PixelFormat::RGBA8, PixelFormat::RGBA8.with_sample(SampleType::U16), PixelFormat::RGBA32F]; struct Restore; diff --git a/crates/paint/src/mip_cache_render_tests.rs b/crates/paint/src/mip_cache_render_tests.rs index 69b61782d5..22b9aecfb7 100644 --- a/crates/paint/src/mip_cache_render_tests.rs +++ b/crates/paint/src/mip_cache_render_tests.rs @@ -8,7 +8,7 @@ use photocraft_geom::Point; fn contexts_share_primary_and_dual_mips_across_settings_and_symmetry_passes() { let tip = GrayTile::from_fn(31, 17, |x, y| ((x + y) % 5) as f32 / 4.0); let brush = BrushSettings { - tip: TipShape::Sampled(tip.clone()), + tip: TipShape::Sampled(tip.clone()).into(), dual_brush: DualBrush { enabled: true, tip: TipShape::Sampled(tip), ..Default::default() }, ..Default::default() }; @@ -28,15 +28,15 @@ fn contexts_share_primary_and_dual_mips_across_settings_and_symmetry_passes() { fn loading_or_replacing_a_stored_tip_never_reuses_its_preview_mips() { let preview = GrayTile::from_fn(8, 8, |_, _| 0.1); let stored = StoredTile { key: "unchanged-key".into(), width: 32, height: 32, preview: Arc::new(preview), full: None }; - let mut brush = BrushSettings { tip: TipShape::Stored(stored.clone()), ..Default::default() }; + let mut brush = BrushSettings { tip: TipShape::Stored(stored.clone()).into(), ..Default::default() }; let before = BrushContext::new(&brush); let full = GrayTile::from_fn(32, 32, |_, _| 0.9); - brush.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(full.clone())), ..stored.clone() }); + brush.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(full.clone())), ..stored.clone() }).into(); let loaded = BrushContext::new(&brush); assert!(!Arc::ptr_eq(before.tip.as_ref().unwrap(), loaded.tip.as_ref().unwrap())); assert_eq!(loaded.tip.as_ref().unwrap().levels, Mips::new(&full).levels); let replacement = GrayTile::from_fn(32, 32, |_, _| 0.3); - brush.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(replacement.clone())), ..stored }); + brush.tip = TipShape::Stored(StoredTile { full: Some(Arc::new(replacement.clone())), ..stored }).into(); let replaced = BrushContext::new(&brush); assert!(!Arc::ptr_eq(loaded.tip.as_ref().unwrap(), replaced.tip.as_ref().unwrap())); assert_eq!(replaced.tip.as_ref().unwrap().levels, Mips::new(&replacement).levels); @@ -46,7 +46,7 @@ fn loading_or_replacing_a_stored_tip_never_reuses_its_preview_mips() { fn cached_and_uncached_strokes_match_exactly_at_native_depths_and_modes() { let tip = GrayTile::from_fn(31, 17, |x, y| ((x * 13 + y * 7) % 31) as f32 / 30.0); let brush = BrushSettings { - tip: TipShape::Sampled(tip.clone()), + tip: TipShape::Sampled(tip.clone()).into(), dual_brush: DualBrush { enabled: true, size: 19.0, tip: TipShape::Sampled(tip.clone()), ..Default::default() }, size: 27.0, angle: 0.4, diff --git a/crates/paint/src/outline.rs b/crates/paint/src/outline.rs index 52ba178e0d..5dd7182252 100644 --- a/crates/paint/src/outline.rs +++ b/crates/paint/src/outline.rs @@ -25,7 +25,7 @@ pub fn tip_outline(b: &BrushSettings, full: bool) -> Option>> let ro = b.roundness.clamp(0.0, 1.0).max(0.5 / (b.size / 2.0)).min(1.0); let (sn, cs) = b.angle.to_radians().sin_cos(); let (fx, fy) = (if b.flip_x { -1.0 } else { 1.0 }, if b.flip_y { -1.0 } else { 1.0 }); - match &b.tip { + match &*b.tip { TipShape::Round => { // The normal cursor is the 50 % contour, matching the plain-circle path (#2744): // the soft tip falls off as (1 - t²)⁴, not the old smoothstep midpoint. @@ -300,12 +300,12 @@ mod tests { let (dx, dy) = (x as f32 - 15.5, y as f32 - 15.5); (1.0 - (dx * dx + dy * dy).sqrt() / 16.0).clamp(0.0, 1.0) }); - let b = BrushSettings { size: 20.0, tip: TipShape::Sampled(disc), ..Default::default() }; + let b = BrushSettings { size: 20.0, tip: TipShape::Sampled(disc).into(), ..Default::default() }; let rings = tip_outline(&b, false).expect("a sampled disc traces"); assert!(rings.iter().all(|r| r.len() >= 3)); assert!(rings.iter().flatten().all(|p| p[0].is_finite() && p[1].is_finite() && p[0].hypot(p[1]) <= 1.001)); let blank = GrayTile::from_fn(8, 8, |_, _| 0.0); - let b = BrushSettings { size: 20.0, tip: TipShape::Sampled(blank), ..Default::default() }; + let b = BrushSettings { size: 20.0, tip: TipShape::Sampled(blank).into(), ..Default::default() }; assert!(tip_outline(&b, false).is_none()); } diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index f7411fcc82..18b15b93a8 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -89,7 +89,7 @@ fn dry_media(base: &BrushSettings) -> Vec { "Chalk", BrushSettings { size: 40.0, - tip: TipShape::Sampled(chalk_tip(64, 7)), + tip: TipShape::Sampled(chalk_tip(64, 7)).into(), spacing: 0.2, shape_dynamics: ShapeDynamics { enabled: true, @@ -105,7 +105,7 @@ fn dry_media(base: &BrushSettings) -> Vec { "Charcoal", BrushSettings { size: 45.0, - tip: TipShape::Sampled(charcoal_tip(64, 4)), + tip: TipShape::Sampled(charcoal_tip(64, 4)).into(), 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()), @@ -119,7 +119,7 @@ fn dry_media(base: &BrushSettings) -> Vec { "Pastel", BrushSettings { size: 50.0, - tip: TipShape::Sampled(chalk_tip(64, 31)), + tip: TipShape::Sampled(chalk_tip(64, 31)).into(), spacing: 0.15, shape_dynamics: ShapeDynamics { enabled: true, @@ -155,7 +155,7 @@ fn dry_media(base: &BrushSettings) -> Vec { "Dry Bristle", BrushSettings { size: 50.0, - tip: TipShape::Sampled(bristle_tip(64, 5)), + tip: TipShape::Sampled(bristle_tip(64, 5)).into(), spacing: 0.04, shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::controlled(Control::Direction), ..Default::default() }, transfer: Transfer { @@ -170,7 +170,7 @@ fn dry_media(base: &BrushSettings) -> Vec { "Rake", BrushSettings { size: 60.0, - tip: TipShape::Sampled(rake_tip(64, 3, 7)), + tip: TipShape::Sampled(rake_tip(64, 3, 7)).into(), spacing: 0.03, shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::controlled(Control::Direction), ..Default::default() }, transfer: transfer(pressure_min(0.25), Dynamic::default()), @@ -222,7 +222,7 @@ fn wet_media(base: &BrushSettings) -> Vec { "Oil Bristle", BrushSettings { size: 70.0, - tip: TipShape::Sampled(bristle_tip(64, 41)), + tip: TipShape::Sampled(bristle_tip(64, 41)).into(), spacing: 0.03, shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::controlled(Control::Direction), size: pressure_min(0.6), ..Default::default() }, color_dynamics: ColorDynamics { enabled: true, per_tip: false, fg_bg: Dynamic::jitter(0.15), brightness_jitter: 0.05, ..Default::default() }, @@ -251,7 +251,7 @@ fn wet_media(base: &BrushSettings) -> Vec { "Ink Wash Sponge", BrushSettings { size: 70.0, - tip: TipShape::Sampled(sponge_tip(96, 8)), + tip: TipShape::Sampled(sponge_tip(96, 8)).into(), spacing: 0.3, flow: 0.6, wet_edges: true, @@ -269,7 +269,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Spatter", BrushSettings { size: 60.0, - tip: TipShape::Sampled(spatter_tip(64, 11, 14)), + tip: TipShape::Sampled(spatter_tip(64, 11, 14)).into(), spacing: 0.6, shape_dynamics: ShapeDynamics { enabled: true, @@ -287,7 +287,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Stipple", BrushSettings { size: 40.0, - tip: TipShape::Sampled(spatter_tip(64, 77, 40)), + tip: TipShape::Sampled(spatter_tip(64, 77, 40)).into(), spacing: 0.5, shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::jitter(1.0), flip_x_jitter: true, ..Default::default() }, scattering: Scattering { enabled: true, scatter: Dynamic::jitter(0.6), both_axes: true, ..Default::default() }, @@ -312,7 +312,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Foliage", BrushSettings { size: 50.0, - tip: TipShape::Sampled(leaf_tip(64)), + tip: TipShape::Sampled(leaf_tip(64)).into(), spacing: 0.35, shape_dynamics: ShapeDynamics { enabled: true, @@ -338,7 +338,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Grass", BrushSettings { size: 70.0, - tip: TipShape::Sampled(grass_tip(96, 6, 11)), + tip: TipShape::Sampled(grass_tip(96, 6, 11)).into(), spacing: 0.25, shape_dynamics: ShapeDynamics { enabled: true, @@ -356,7 +356,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Sparkle", BrushSettings { size: 40.0, - tip: TipShape::Sampled(star_tip(64)), + tip: TipShape::Sampled(star_tip(64)).into(), spacing: 1.5, shape_dynamics: ShapeDynamics { enabled: true, size: Dynamic { jitter: 0.8, minimum: 0.15, ..Default::default() }, ..Default::default() }, scattering: Scattering { enabled: true, scatter: Dynamic::jitter(2.5), both_axes: true, ..Default::default() }, @@ -368,7 +368,7 @@ fn special_effects(base: &BrushSettings) -> Vec { "Sponge Texture", BrushSettings { size: 60.0, - tip: TipShape::Sampled(sponge_tip(64, 19)), + tip: TipShape::Sampled(sponge_tip(64, 19)).into(), spacing: 0.45, shape_dynamics: ShapeDynamics { enabled: true, angle: Dynamic::jitter(1.0), ..Default::default() }, transfer: transfer(Dynamic::jitter(0.3), Dynamic::default()), diff --git a/crates/paint/src/render/reference.rs b/crates/paint/src/render/reference.rs index c7dc366bb2..2a3a87f8f7 100644 --- a/crates/paint/src/render/reference.rs +++ b/crates/paint/src/render/reference.rs @@ -248,7 +248,7 @@ fn feature_and_exceptional_dabs_match_scalar_bits() { b.aliased = true; b.square = true; } - 3 => b.tip = TipShape::Sampled(tip.clone()), + 3 => b.tip = TipShape::Sampled(tip.clone()).into(), 4 => { b.texture.enabled = true; b.texture.each_tip = true; @@ -337,7 +337,7 @@ fn general_loop_cases() -> Vec<(&'static str, BrushContext, Dab, bool, bool)> { }; let ctx = |b: BrushSettings| BrushContext::new(&b); vec![ - ("sampled", ctx(BrushSettings { tip: TipShape::Sampled(tip.clone()), ..base() }), dab(0.4, 1.0, 1.0), false, false), + ("sampled", ctx(BrushSettings { tip: TipShape::Sampled(tip.clone()).into(), ..base() }), dab(0.4, 1.0, 1.0), false, false), ( "per-tip texture", ctx({ @@ -439,7 +439,7 @@ fn parallel_general_loop_matches_the_frozen_reference() { fn general_loop_survives_empty_rects_and_nan_dabs() { let _restore = RestoreThreshold; let tip = GrayTile::from_fn(8, 5, |x, y| ((x + y) % 7) as f32 / 6.0); - let sampled = BrushContext::new(&BrushSettings { tip: TipShape::Sampled(tip), ..Default::default() }); + let sampled = BrushContext::new(&BrushSettings { tip: TipShape::Sampled(tip).into(), ..Default::default() }); let plain = BrushContext::new(&BrushSettings::default()); for threshold in [0, usize::MAX] { set_parallel_min_pixels(threshold); diff --git a/crates/paint/src/tile.rs b/crates/paint/src/tile.rs index cb33623b2d..5944dfd7df 100644 --- a/crates/paint/src/tile.rs +++ b/crates/paint/src/tile.rs @@ -396,9 +396,9 @@ mod tests { let c = t.clone(); assert!(std::sync::Arc::ptr_eq(&t.data, &c.data)); assert_eq!(t, c); - let brush = crate::brush::BrushSettings { tip: crate::brush::TipShape::Sampled(t.clone()), ..Default::default() }; + let brush = crate::brush::BrushSettings { tip: crate::brush::TipShape::Sampled(t.clone()).into(), ..Default::default() }; let copy = brush.clone(); - let crate::brush::TipShape::Sampled(ct) = ©.tip else { panic!("sampled") }; + let crate::brush::TipShape::Sampled(ct) = &*copy.tip else { panic!("sampled") }; assert!(std::sync::Arc::ptr_eq(&t.data, &ct.data), "the settings' clone shares the tip"); } diff --git a/crates/ui-egui/src/brush_settle_trials.rs b/crates/ui-egui/src/brush_settle_trials.rs new file mode 100644 index 0000000000..b1b818bb82 --- /dev/null +++ b/crates/ui-egui/src/brush_settle_trials.rs @@ -0,0 +1,44 @@ +//! The options bar's Brush Preset field runs only for what it shows (the presets, the brush's size, hardness, angle, +//! roundness and tip): a brush write that leaves those alone replays it, and the paint members, which show the +//! opacity, run. + +use craft::ui::runtime::measure::{MemoRun, last_pass_memo_runs}; +use egui::{Event, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// How the memoized view whose props type is named `props` took part in the last pass. +fn run_of(h: &H, props: &str) -> Option { + last_pass_memo_runs(&h.ctx).into_iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| run) +} + +#[test] +fn a_brush_write_that_leaves_the_shown_values_alone_replays_the_brush_preset_field() { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, crate::Services::default()); + app.ui.tool = Tool::Brush; + app + }); + h.run_steps(8); + let at = h.state().last_canvas_rect.center(); + h.event(Event::PointerMoved(at)); + h.run_steps(4); + assert_eq!(run_of(&h, "brush_picker::FieldProps"), Some(MemoRun::Replayed), "the field replays at rest"); + for (step, opacity) in [0.5, 0.6, 0.7].into_iter().enumerate() { + h.state_mut().run("tools.setBrush", json!({"brush": {"opacity": opacity}})).unwrap(); + h.run_steps(1); + assert_eq!(run_of(&h, "brush_picker::FieldProps"), Some(MemoRun::Replayed), "opacity step {step}: the field shows no opacity"); + assert!(run_of(&h, "paint::PaintProps").is_some_and(|run| run != MemoRun::Replayed), "opacity step {step}: the paint members show it"); + } + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 42}})).unwrap(); + h.run_steps(1); + assert!(run_of(&h, "brush_picker::FieldProps").is_some_and(|run| run != MemoRun::Replayed), "a size write runs the field"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a89837fb4c..6eeb594a61 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -940,6 +940,8 @@ mod move_outline_tests; #[cfg(test)] mod move_bar_distribute_gear_tests; +#[cfg(test)] +mod brush_settle_trials; #[cfg(test)] mod chrome_settle_trials; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/brush_panel/brushes.rs b/crates/ui-egui/src/panels/brush_panel/brushes.rs index 6c92468f98..f1c498a485 100644 --- a/crates/ui-egui/src/panels/brush_panel/brushes.rs +++ b/crates/ui-egui/src/panels/brush_panel/brushes.rs @@ -17,7 +17,7 @@ use egui::{ColorImage, Pos2, Rect, pos2}; use photocraft_engine::BrushSettings; use photocraft_engine::brush_key_cmds::panel_layout; use photocraft_engine::brush_preset_cmds::MAX_FOLDER_DEPTH; -use photocraft_engine::paint::{BrushPreset, MAX_BRUSH_SIZE}; +use photocraft_engine::paint::{BrushPreset, MAX_BRUSH_SIZE, TipShape}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -89,7 +89,7 @@ fn picture(cx: &ContentPainterCx, rect: Rect, key: impl Hash + 'static, image: i /// rows out of view) take none. fn paint_of(b: &BrushSettings) -> BrushRowPaint { let brush = b.clone(); - BrushRowPaint::new(tip_paint(b), move |cx, rect| { + BrushRowPaint::new(tip_paint(&b.tip, (b.hardness, b.angle, b.roundness)), move |cx, rect| { let color = Tokens::get(cx.painter.ctx()).text; let size = [rect.width().round().clamp(1.0, 1024.0) as usize, rect.height().round().clamp(1.0, 1024.0) as usize]; let stroke_sig = brush_preview::preview_sig(&brush); @@ -97,11 +97,10 @@ fn paint_of(b: &BrushSettings) -> BrushRowPaint { }) } -/// How the engine draws `b`'s tip (its falloff, angle and roundness, a sampled tip's shape) in the theme's text +/// How the engine draws `tip` with the falloff, angle and roundness `shape` (a sampled tip's shape) in the theme's text /// colour: a preset's thumbnail and the Brush Preset chip's current tip. -pub(crate) fn tip_paint(b: &BrushSettings) -> impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static { - let tip = b.tip.clone(); - let shape = (b.hardness, b.angle, b.roundness); +pub(crate) fn tip_paint(tip: &TipShape, shape: (f32, f32, f32)) -> impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static { + let tip = tip.clone(); move |cx, rect| { let color = Tokens::get(cx.painter.ctx()).text; let tip_key = brush_preview::tip_sig(&tip, shape.0, shape.1, shape.2, (false, false)); diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 1416829ba4..8c5c7278db 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -185,7 +185,7 @@ fn every_section_round_trips_through_set_brush() { fn patches_are_minimal_and_skip_unchanged_bitmaps() { let tip = TipShape::Sampled(GrayTile::from_fn(400, 300, |x, y| ((x * y) % 7) as f32 / 7.0)); let old = BrushSettings { - tip: tip.clone(), + tip: tip.clone().into(), texture: paint::Texture { pattern: Pattern::Tile(GrayTile::from_fn(64, 64, |x, _| x as f32 / 64.0)), ..Default::default() }, ..Default::default() }; @@ -195,7 +195,7 @@ fn patches_are_minimal_and_skip_unchanged_bitmaps() { assert_eq!(brush_patch(&old, &new), json!({"shapeDynamics": {"enabled": true}})); assert_eq!(brush_patch(&old, &old), json!({})); // A changed tip is sent whole. - let new = BrushSettings { tip: TipShape::Round, ..old.clone() }; + let new = BrushSettings { tip: TipShape::Round.into(), ..old.clone() }; assert_eq!(brush_patch(&old, &new), json!({"tip": "round"})); // Applying any of these through the engine gives back `new`. let mut app = app(); @@ -447,7 +447,7 @@ fn every_section_draws_without_issuing_commands() { for i in 0..SECTIONS.len() { edit_section(i, &mut b); } - b.tip = TipShape::Sampled(GrayTile::from_fn(50, 40, |x, y| ((x ^ y) & 1) as f32)); + b.tip = TipShape::Sampled(GrayTile::from_fn(50, 40, |x, y| ((x ^ y) & 1) as f32)).into(); *h.state_mut().session.tools.brush = b.clone(); let n = h.state().session.journal.len(); h.run_steps(4); diff --git a/crates/ui-egui/src/panels/brush_preview.rs b/crates/ui-egui/src/panels/brush_preview.rs index 2d17b401ba..dd973e027d 100644 --- a/crates/ui-egui/src/panels/brush_preview.rs +++ b/crates/ui-egui/src/panels/brush_preview.rs @@ -236,7 +236,7 @@ mod tests { // Loading the tip re-renders the thumbnail; the stroke preview paints with the preview. let sig = |t: paint::StoredTile| tip_sig(&TipShape::Stored(t), 1.0, 0.0, 1.0, (false, false)); assert_ne!(sig(r.clone()), sig(loaded)); - let b = BrushSettings { tip: TipShape::Stored(r), size: 900.0, ..Default::default() }; + let b = BrushSettings { tip: TipShape::Stored(r).into(), size: 900.0, ..Default::default() }; let px = preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]); assert!(px.as_chunks::<4>().0.iter().any(|p| p[3] > 128)); } diff --git a/crates/ui-egui/src/panels/brush_sections.rs b/crates/ui-egui/src/panels/brush_sections.rs index 96cca36dfb..49c182b619 100644 --- a/crates/ui-egui/src/panels/brush_sections.rs +++ b/crates/ui-egui/src/panels/brush_sections.rs @@ -320,7 +320,7 @@ impl Pane<'_> { if let Some(name) = self.tip_grid(ui, "brush-tip-grid", selected) && let Some((tip, size, hardness, angle, roundness, spacing)) = self.preset_tip(&name) { - (b.tip, b.size, b.hardness, b.angle, b.roundness, b.spacing) = (tip, size, hardness, angle, roundness, spacing); + (b.tip, b.size, b.hardness, b.angle, b.roundness, b.spacing) = (tip.into(), size, hardness, angle, roundness, spacing); self.out.picked = Some(name); return; } @@ -338,7 +338,7 @@ impl Pane<'_> { b.angle = tip.degrees as f32; b.roundness = tip.roundness as f32; } - let round = matches!(b.tip, TipShape::Round); + let round = matches!(*b.tip, TipShape::Round); self.field(ui, tl!("Hardness"), &mut b.hardness, d.hardness, AMOUNT, round); self.spacing(ui, b, d.spacing); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index fe6902bb93..a46aae1957 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1276,7 +1276,7 @@ fn the_saved_brush_owner_follows_the_saved_last_brush() { crate::tool_memory::persist(&mut app, &ctx); // The Brush's tip becomes a big sampled one, then the Blur tool takes over that brush (the Eraser has its own // starting tip since #11936). - app.session.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(400, 300, |x, y| ((x * y) % 7) as f32 / 7.0)); + app.session.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(400, 300, |x, y| ((x * y) % 7) as f32 / 7.0)).into(); app.session.tools.brush_changed(); app.ui.tool = Tool::Blur; crate::paint_mouse::sync_tool_brush(&mut app); @@ -1292,7 +1292,7 @@ fn the_saved_brush_owner_follows_the_saved_last_brush() { assert_eq!(app2.session.tools.brush.size, 77.0); // Once the Blur tool's brush is saved, the Blur tool owns it in the preferences too. - app.session.tools.brush.tip = TipShape::Round; + app.session.tools.brush.tip = TipShape::Round.into(); app.session.tools.brush.size = 33.0; app.session.tools.brush_changed(); crate::last_brush::persist(&mut app, &ctx); diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 7f756288c7..cd6d2a8434 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -299,7 +299,7 @@ mod tests { } assert!(!app.ui.status_error, "{}", app.ui.status); assert_eq!(app.session.tools.current_preset.as_deref(), Some("Leaf")); - let TipShape::Sampled(tip) = &app.session.tools.brush.tip else { panic!("sampled tip expected") }; + let TipShape::Sampled(tip) = &*app.session.tools.brush.tip else { panic!("sampled tip expected") }; assert_eq!((tip.width, tip.height), (3, 8)); assert!(is_shown(&app, "brushes"), "the Brushes tab shows the new brush"); } diff --git a/crates/ui-egui/src/tools/brush_cursor.rs b/crates/ui-egui/src/tools/brush_cursor.rs index d5e4321704..0dfd344722 100644 --- a/crates/ui-egui/src/tools/brush_cursor.rs +++ b/crates/ui-egui/src/tools/brush_cursor.rs @@ -33,7 +33,7 @@ pub(crate) struct TipKey { impl TipKey { fn of(b: &BrushSettings) -> Self { Self { - tip: b.tip.clone(), + tip: (*b.tip).clone(), angle: b.angle, roundness: b.roundness, hardness: b.hardness, @@ -46,7 +46,7 @@ impl TipKey { /// A round tip with no angle or flattening: the circle says it all. fn is_plain(b: &BrushSettings) -> bool { - matches!(b.tip, TipShape::Round) && b.angle == 0.0 && b.roundness >= 1.0 + matches!(*b.tip, TipShape::Round) && b.angle == 0.0 && b.roundness >= 1.0 } /// The size and kind of the aliased cursor tip the `tool` has: the Pencil's, the Eraser's in Pencil mode, and the diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index ea1b3fd2a8..35a8b6501c 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -31,23 +31,38 @@ pub(crate) struct PickerInput { rows: Vec>, current: Option, values: BrushPickerValues, - brush: BrushSettings, + tip: TipShape, + face: BrushFace, +} + +/// What the picker shows of the brush besides its tip: the head's values and the tip picture's shape. +#[derive(Clone, Copy, MemoProps)] +struct BrushFace { + size: f32, + hardness: f32, + angle: f32, + roundness: f32, +} + +impl BrushFace { + fn of(brush: &BrushSettings) -> Self { + Self { size: brush.size, hardness: brush.hardness, angle: brush.angle, roundness: brush.roundness } + } } impl PickerInput { /// The rows, the current preset and the brush values as the app holds them now. pub(crate) fn of(app: &PhotocraftApp, env: &Env) -> Self { let tools = &app.session.tools; - Self::new(tools.presets.as_slice(), &tools.brush, current_key(tools), app.ui.brush_picker_state.parts, env) + Self::new(tools.presets.as_slice(), &tools.brush.tip, BrushFace::of(&tools.brush), current_key(tools), app.ui.brush_picker_state.parts, env) } - /// The rows of `presets` with the card `parts`, `current` picked, and the values of `brush`. - fn new(presets: &[BrushPreset], brush: &BrushSettings, current: Option, parts: BrushCardParts, env: &Env) -> Self { - let brush = brush.clone(); - let round = brush.tip == TipShape::Round; - let values = BrushPickerValues::new(f64::from(brush.size), round.then_some(f64::from(brush.hardness))) - .with_tip(TipAngle::new(f64::from(brush.angle), f64::from(brush.roundness))); - Self { rows: preset_rows(presets, env, parts), current, values, brush } + /// The rows of `presets` with the card `parts`, `current` picked, and the brush's `tip` and `face`. + fn new(presets: &[BrushPreset], tip: &TipShape, face: BrushFace, current: Option, parts: BrushCardParts, env: &Env) -> Self { + let round = *tip == TipShape::Round; + let values = BrushPickerValues::new(f64::from(face.size), round.then_some(f64::from(face.hardness))) + .with_tip(TipAngle::new(f64::from(face.angle), f64::from(face.roundness))); + Self { rows: preset_rows(presets, env, parts), current, values, tip: tip.clone(), face } } /// Every row's key, in list order. @@ -62,7 +77,7 @@ impl PickerInput { .import() .gear_rows(gear_rows) .resizable(SaveKey::new("photocraft.brush_picker")) - .tip(std::sync::Arc::new(tip_paint(&self.brush))) + .tip(std::sync::Arc::new(tip_paint(&self.tip, (self.face.hardness, self.face.angle, self.face.roundness)))) } } @@ -125,8 +140,8 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) { let mut input = PickerInput::of(app, &env); let mut open = true; let background_eraser = app.ui.tool == Tool::BackgroundEraser; - let row_before = input.brush.clone(); - let mut row_brush = input.brush.clone(); + let row_before = (*app.session.tools.brush).clone(); + let mut row_brush = row_before.clone(); let mut tolerance = app.ui.tool_options.bg_tolerance_control.clone(); let mut key = None; let out = { @@ -148,11 +163,13 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) { } } -/// Every input of the options bar's picker field: the presets and the brush it shows, and the picker's view state. +/// Every input of the options bar's picker field: the presets, what it shows of the brush (its tip and face), and the +/// picker's view state. #[derive(MemoProps)] struct FieldProps<'a> { presets: &'a Tracked>>, - brush: &'a Tracked, + tip: &'a Tracked, + face: BrushFace, current: Option, enabled: bool, state: &'a mut Tracked>, @@ -163,14 +180,15 @@ struct FieldProps<'a> { struct FieldEvent(BrushPresetPickerOutput, Vec); /// The closed picker field of the options bar, which opens the popover. `enabled` is false for the Eraser in Block -/// mode, which paints with no brush. A memoized view: it runs when the presets, the brush, the current preset or the -/// picker's state change, while its popover is open, or when input reaches it. +/// mode, which paints with no brush. A memoized view: it runs when the presets, the brush's tip or face, the current +/// preset or the picker's state change, while its popover is open, or when input reaches it. pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bool) { let mut sent = Vec::new(); let tools = &app.session.tools; let props = FieldProps { presets: &tools.presets, - brush: &tools.brush, + tip: &tools.brush.tip, + face: BrushFace::of(&tools.brush), current: current_key(tools), enabled, state: &mut app.ui.brush_picker_state, @@ -185,7 +203,7 @@ pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bo /// The picker field's view. fn field_view(props: &mut FieldProps<'_>, ui: &mut egui::Ui) { let env = Env::of(ui); - let mut input = PickerInput::new(props.presets.as_slice(), props.brush, props.current.clone(), props.state.parts, &env); + let mut input = PickerInput::new(props.presets.as_slice(), props.tip, props.face, props.current.clone(), props.state.parts, &env); let out = input.picker(bind_tracked!(props.state)).enabled(props.enabled).show(ui); let keys = if out.picks.is_empty() { Vec::new() } else { input.keys() }; props.out.send(FieldEvent(out, keys));