From 6c9ec00fa80adc34e10461083be4675e901f205e Mon Sep 17 00:00:00 2001 From: durtyrobbin Date: Sun, 11 Oct 2026 12:40:20 -0400 Subject: [PATCH] studio: live mixer foundation Preserve validated painting-studio phase 1 as its own source commit. Content tree: 371bfeb4cdc79f3e2e9357047141a393811ec1a5 Qualification details and remaining gates are retained in the phase documentation. Local commit authorized by durtyrobbin; no publication or upstream merge. --- crates/engine/examples/mixer_probe.rs | 66 +++ crates/engine/src/brush_cmds.rs | 63 +-- crates/engine/src/brush_cmds/mixer_live.rs | 402 ++++++++++++++++++ .../engine/src/brush_cmds/mixer_live_tests.rs | 226 ++++++++++ crates/engine/src/float_cmds.rs | 3 +- crates/engine/src/lib.rs | 2 + crates/paint/src/mixer.rs | 174 +++++--- crates/ui-egui/src/alt_click_tests.rs | 30 ++ crates/ui-egui/src/alt_grab.rs | 2 +- crates/ui-egui/src/brush_panel_tests.rs | 6 +- crates/ui-egui/src/canvas.rs | 201 ++++++++- crates/ui-egui/src/panels.rs | 26 ++ crates/ui-egui/src/shortcuts.rs | 3 + docs/mixer-live.md | 147 +++++++ 14 files changed, 1241 insertions(+), 110 deletions(-) create mode 100644 crates/engine/examples/mixer_probe.rs create mode 100644 crates/engine/src/brush_cmds/mixer_live.rs create mode 100644 crates/engine/src/brush_cmds/mixer_live_tests.rs create mode 100644 docs/mixer-live.md diff --git a/crates/engine/examples/mixer_probe.rs b/crates/engine/examples/mixer_probe.rs new file mode 100644 index 0000000000..d39b297661 --- /dev/null +++ b/crates/engine/examples/mixer_probe.rs @@ -0,0 +1,66 @@ +//! Reproducible CPU-engine latency probe; not a hardware pointer-to-display qualification. +use photocraft_engine::{Session, brush_cmds::mixer_live::LiveMixer}; +use photocraft_geom::Rect; +use photocraft_paint::{ + BrushSettings, Stroke, StrokePoint, + mixer::{MixerState, apply_mixer_stroke}, +}; +use photocraft_raster::Surface; +use serde_json::json; +use std::time::Instant; + +fn main() -> Result<(), Box> { + let mut results = Vec::new(); + for size in [16.0, 64.0, 256.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width":6000,"height":4000,"background":"#808080"}))?; + s.execute("layer.new.layer", json!({"name":"Source"}))?; + s.edit("fixture", |doc, id| { + if let Some(layer) = id.and_then(|id| doc.layer_mut(id)) + && let Some(surface) = layer.surface_mut() + { + surface.fill_rect(Rect::new(0, 0, 500, 800), &[1.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(500, 0, 1000, 800), &[0.0, 1.0, 0.0, 1.0]); + } + Ok(()) + })?; + s.execute("layer.new.layer", json!({"name":"Paint"}))?; + let baseline_doc = s.active().ok_or("no document")?.doc.clone(); + let params = json!({"points":[[200,400]],"size":size,"seed":42,"wet":100,"mix":85,"brush":{"pressureSize":false,"spacing":0.25}}); + let start = Instant::now(); + let mut live = LiveMixer::begin(&s, ¶ms)?; + let begin_ms = start.elapsed().as_secs_f64() * 1000.0; + let mut times = Vec::new(); + let mut points = vec![StrokePoint::new(200.0, 400.0, 1.0)]; + for i in 1..=60 { + let point = StrokePoint::new(200.0 + 10.0 * f64::from(i), 400.0 + 20.0 * (f64::from(i) / 10.0).sin(), 1.0); + let start = Instant::now(); + live.push(&[point])?; + times.push(start.elapsed().as_secs_f64() * 1000.0); + points.push(point); + } + let area = live.bounds(); + let commit = live.prepare_commit(&mut s)?; + let start = Instant::now(); + s.execute("paint.mixerBrush", commit)?; + let commit_ms = start.elapsed().as_secs_f64() * 1000.0; + let mut baseline = Surface::new(photocraft_color::PixelFormat::RGBA8); + let mut state = MixerState::default(); + state.load(s.tools.foreground); + let stroke = Stroke { brush: BrushSettings { size, pressure_size: false, spacing: 0.25, ..Default::default() }, points }; + let settings = photocraft_paint::MixerSettings { wet: 1.0, mix: 0.85, ..Default::default() }; + // Baseline's historical frozen-composite path, including its one source composition. + let start = Instant::now(); + let buffer = photocraft_compose::render(&baseline_doc, area); + let mut source = Surface::new(photocraft_color::PixelFormat::RGBA32F); + source.write_region(area, &buffer.px.iter().flatten().copied().collect::>()); + apply_mixer_stroke(&mut baseline, Some(&source), &stroke, &settings, &mut state, None, false); + let baseline_ms = start.elapsed().as_secs_f64() * 1000.0; + times.sort_by(f64::total_cmp); + results.push(json!({"size":size,"document":[6000,4000],"layers":3,"moves":60,"begin_ms":begin_ms, + "move_median_ms":times.get(30),"move_p95_ms":times.get(57),"move_max_ms":times.last(), + "prepared_commit_ms":commit_ms,"baseline_frozen_composite_full_stroke_ms":baseline_ms})); + } + println!("{}", serde_json::to_string_pretty(&json!({"scope":"CPU engine only; no OS, tablet, display, or GPU latency claim","results":results}))?); + Ok(()) +} diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs index a0a217c303..d984363bca 100644 --- a/crates/engine/src/brush_cmds.rs +++ b/crates/engine/src/brush_cmds.rs @@ -8,7 +8,7 @@ use photocraft_doc::LayerContent; use photocraft_geom::Rect; -use photocraft_paint::mixer::{MixerSettings, apply_mixer_stroke}; +use photocraft_paint::mixer::MixerSettings; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement}; use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke}; use photocraft_raster::Surface; @@ -546,51 +546,9 @@ fn pct(p: &Value, k: &str, d: f32) -> f32 { num(p, k).unwrap_or(d).clamp(0.0, 100.0) / 100.0 } +pub mod mixer_live; fn mixer_brush(s: &mut Session, p: &Value) -> Result { - let cmd = "paint.mixerBrush"; - let pts = parse_points(p, cmd)?; - let brush = resolve_brush(s, p, cmd)?; - // The brush's Mixer Brush options, overridden by the scalar params. - let bm = &brush.mixer; - let m = MixerSettings { - wet: pct(p, "wet", bm.wet * 100.0), - load: pct(p, "load", bm.load * 100.0), - mix: pct(p, "mix", bm.mix * 100.0), - flow: pct(p, "flow", bm.flow * 100.0), - sample_all_layers: flag(p, "sampleAllLayers", bm.sample_all_layers), - }; - let sample_all = m.sample_all_layers; - let (clean, load_after) = (flag(p, "cleanAfterStroke", true), flag(p, "loadAfterStroke", true)); - let mut state = s.tools.mixer.clone(); - if load_after || state.reservoir.is_none() { - state.load(color(p.get("color"), s.tools.foreground)); - } - let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) }; - let stroke = Stroke { brush, points: pts }; - let dmg = s.edit("Mixer Brush", |doc, _| { - let sel = doc.selection.clone(); - let sample = if sample_all { - let ds = photocraft_paint::dabs(&stroke); - let ctx = photocraft_paint::BrushContext::new(&stroke.brush); - let area = ds.iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false))); - let buf = photocraft_compose::render(doc, area); - let mut surf = Surface::new(photocraft_color::PixelFormat::RGBA32F); - let flat: Vec = buf.px.iter().flatten().copied().collect(); - if !area.is_empty() { - surf.write_region(area, &flat); - } - Some(surf) - } else { - None - }; - let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; - Ok(apply_mixer_stroke(surf, sample.as_ref(), &stroke, &m, &mut state, sel.as_ref(), lock)) - })?; - if clean { - state.clean(); - } - s.tools.mixer = state; - Ok(damage_json(s, dmg)) + mixer_live::run(s, p) } fn color_replacement(s: &mut Session, p: &Value) -> Result { @@ -918,6 +876,16 @@ macro_rules! spec { /// Brush command specs. pub fn specs() -> Vec { vec![ + spec!( + "brush.mixer.sample", + "Sample Mixer Brush", + r#"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?]],"sampleAllLayers":bool=brush setting,"size":px?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}}"#, + |s| s.active().map(|_| ()).ok_or_else(|| "no document".into()), + mixer_live::sample, + true + ), + spec!("brush.mixer.load", "Load Mixer Brush", r##"{"color":"#rrggbb"?=foreground}"##, always, mixer_live::load, true), + spec!("brush.mixer.clean", "Clean Mixer Brush", "{}", always, mixer_live::clean, true), spec!( "paint.pencil", "Pencil", @@ -929,7 +897,7 @@ pub fn specs() -> Vec { spec!( "paint.mixerBrush", "Mixer Brush", - r##"{"points":[…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"wet":0..100=brush.mixer.wet,"load":0..100=brush.mixer.load,"mix":0..100=brush.mixer.mix,"flow":0..100=brush.mixer.flow,"color":"#rrggbb"?=foreground,"sampleAllLayers":bool=brush.mixer.sampleAllLayers,"cleanAfterStroke":bool=true,"loadAfterStroke":bool=true,"seed":u64?}"##, + r##"{"points":[…] (max 65536 samples, 2048px per segment),"brush":{…}?,"preset":name?,"size":0.5..512 px?,"wet":0..100=brush.mixer.wet,"load":0..100=brush.mixer.load,"mix":0..100=brush.mixer.mix,"flow":0..100=brush.mixer.flow,"color":"#rrggbb"?=foreground,"sampleAllLayers":bool=brush.mixer.sampleAllLayers,"cleanAfterStroke":bool=brush.mixer.cleanAfterStroke,"loadAfterStroke":bool=brush.mixer.reloadAfterStroke,"seed":u64?,"mixerState":{reservoir,amount,pickup,spatial} (optional captured replay state; spatial is null or 4096 RGBA colors)}"##, has_paintable, mixer_brush, true @@ -962,3 +930,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod mixer_live_tests; diff --git a/crates/engine/src/brush_cmds/mixer_live.rs b/crates/engine/src/brush_cmds/mixer_live.rs new file mode 100644 index 0000000000..21f4c7e99e --- /dev/null +++ b/crates/engine/src/brush_cmds/mixer_live.rs @@ -0,0 +1,402 @@ +//! Incremental Mixer Brush transaction. Source pixels are composed before each dab; +//! only the selected target changes. Dropping the transaction cancels it. +use super::*; +use photocraft_color::{PixelFormat, SampleType}; +use photocraft_doc::{Document, LayerId}; +use photocraft_paint::dynamics::DabGenerator; +use photocraft_paint::mixer::{MixerState, apply_mixer_dab}; +use photocraft_paint::retouch::{Region, mix_back}; +use photocraft_paint::{BrushContext, Dab}; +use std::collections::BTreeSet; +use std::sync::Arc; + +const CMD: &str = "paint.mixerBrush"; +const MAX_TILES: usize = 256; +const TILE: i32 = 256; + +fn valid_color(color: &[f32; 4]) -> bool { + color.iter().all(|v| v.is_finite() && v.abs() <= 1_000_000.0) +} + +fn valid_state(state: &MixerState) -> bool { + state.amount.is_finite() + && state.reservoir.as_ref().is_none_or(valid_color) + && state.pickup.as_ref().is_none_or(valid_color) + && state.spatial.as_ref().is_none_or(|colors| colors.len() == 4096 && colors.iter().all(valid_color)) +} + +#[derive(Clone)] +struct Core { + doc: Arc, + generator: DabGenerator, + ctx: BrushContext, + pre: Surface, + work: Surface, + tiles: BTreeSet<(i32, i32)>, + state: MixerState, + settings: MixerSettings, + layer: Option, + params: Value, + selection: Option, + lock: bool, + color_restrict: Option, + count: usize, + last: Option, + bounds: Rect, +} + +impl Core { + fn apply(&mut self, dabs: &[Dab]) -> Result { + if self.count.saturating_add(dabs.len()) > 250_000 { + return Err(bad(CMD, "stroke exceeds 250000 dabs; start another stroke")); + } + let mut damage = Rect::EMPTY; + for dab in dabs { + let index = self.count; + self.count += 1; + let r = self.ctx.dab_rect(dab, false); + if r.is_empty() { + continue; + } + let full = self.ctx.dab_rect(dab, false); + if u64::from(full.width()).saturating_mul(u64::from(full.height())) > 1_048_576 { + return Err(bad(CMD, "Mixer Brush footprint exceeds 1048576 pixels")); + } + // Float working tiles avoid repeated integer-depth quantization. Initialize only + // touched tiles, keeping unchanged source tiles shared by the document snapshots. + for ty in r.y0.div_euclid(TILE)..=(r.y1 - 1).div_euclid(TILE) { + for tx in r.x0.div_euclid(TILE)..=(r.x1 - 1).div_euclid(TILE) { + if !self.tiles.contains(&(tx, ty)) { + if self.tiles.len() >= MAX_TILES { + return Err(bad(CMD, "Mixer Brush stroke working set exceeds 256 tiles")); + } + let tile = Rect::new(tx * TILE, ty * TILE, (tx + 1) * TILE, (ty + 1) * TILE); + self.work.write_region(tile, &self.pre.read_region(tile)); + self.tiles.insert((tx, ty)); + } + } + } + // Render the visible document including the active layer exactly once, before + // deposition. Masks, transforms, blend modes and adjustments use the compositor. + let sample = self.settings.sample_all_layers.then(|| { + let buf = photocraft_compose::render(&self.doc, r); + let mut sample = Surface::new(PixelFormat::RGBA32F); + sample.write_region(r, &buf.px.iter().flatten().copied().collect::>()); + sample + }); + let fp = self.ctx.footprint(dab, index); + let mut region = Region::read(&self.work, r); + apply_mixer_dab(&mut region, &fp, self.pre.format(), sample.as_ref(), &self.settings, &mut self.state, self.lock); + region.write(&mut self.work); + let original = Region::read(&self.pre, r); + let (target, _) = crate::channel_cmds::target_surface(Arc::make_mut(&mut self.doc), self.layer, &self.params)?; + mix_back(target, &original, ®ion, r, 1.0, self.selection.as_ref(), self.lock); + if let Some(k) = self.color_restrict { + let n = target.channels(); + let mut values = target.read_region(r); + let before = self.pre.read_region(r); + for (new, old) in values.chunks_exact_mut(n).zip(before.chunks_exact(n)) { + for (c, (new, old)) in new.iter_mut().zip(old).enumerate() { + if c != k { + *new = *old; + } + } + } + target.write_region(r, &values); + } + damage = damage.union(&r); + } + self.bounds = self.bounds.union(&damage); + Ok(damage) + } +} + +/// A real, cancellable paint result, displayed by the existing damage-aware canvas. +pub struct LiveMixer { + pub doc: Arc, + pub seed: u64, + core: Core, + state: MixerState, + tail: Rect, + cmyk: Option>, + original: Arc, + points: Vec, + original_state: MixerState, +} + +impl LiveMixer { + pub fn begin(s: &Session, p: &Value) -> Result { + has_paintable(s).map_err(EngineError::Other)?; + if p.get("points").and_then(Value::as_array).is_some_and(|v| v.len() > 65_536) { + return Err(bad(CMD, "stroke exceeds 65536 recorded input samples")); + } + let points = parse_points(p, CMD)?; + let brush = resolve_brush(s, p, CMD)?; + // Reject unsupported sizes before allocating a dense brush footprint. + if brush.size > 512.0 { + return Err(bad(CMD, "live Mixer Brush size is limited to 512 pixels")); + } + let bm = &brush.mixer; + let settings = MixerSettings { + wet: pct(p, "wet", bm.wet * 100.0), + load: pct(p, "load", bm.load * 100.0), + mix: pct(p, "mix", bm.mix * 100.0), + flow: pct(p, "flow", bm.flow * 100.0), + sample_all_layers: flag(p, "sampleAllLayers", bm.sample_all_layers) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels, + clean_after_stroke: flag(p, "cleanAfterStroke", bm.clean_after_stroke), + reload_after_stroke: flag(p, "loadAfterStroke", bm.reload_after_stroke), + }; + let initial_state = if let Some(value) = p.get("mixerState") { + if value.get("spatial").and_then(Value::as_array).is_some_and(|v| v.len() != 4096) { + return Err(bad(CMD, "spatial reservoir must contain exactly 4096 colors")); + } + serde_json::from_value::(value.clone()).map_err(|e| bad(CMD, e.to_string()))? + } else { + s.tools.mixer.clone() + }; + let mut state = initial_state; + if !valid_state(&state) { + return Err(bad(CMD, "loaded paint must be finite and color magnitudes at most 1000000")); + } + if state.spatial.is_none() && settings.reload_after_stroke { + let color = color(p.get("color"), s.tools.foreground); + if !valid_color(&color) { + return Err(bad(CMD, "loaded color must be finite and magnitudes at most 1000000")); + } + state.load(color); + } + let layer = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) }; + let mut doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone(); + let selection = doc.selection.clone(); + let (target, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; + let pre = target.clone(); + let work = Surface::new(PixelFormat { sample: SampleType::F32, ..pre.format() }); + let core = Core { + doc: Arc::new(doc), + generator: DabGenerator::new(&brush, num(p, "zoom").unwrap_or(1.0)), + ctx: BrushContext::new(&brush), + pre, + work, + tiles: BTreeSet::new(), + state: state.clone(), + settings, + layer, + params: p.clone(), + selection, + lock, + color_restrict: crate::channel_cmds::color_restriction(s, CMD, p), + count: 0, + last: None, + bounds: Rect::EMPTY, + }; + let mut live = Self { + doc: core.doc.clone(), + seed: brush.seed, + core, + state, + tail: Rect::EMPTY, + cmyk: doc_cmyk_space(s), + original: s.active().ok_or(EngineError::NoDocument)?.doc.clone(), + points: Vec::new(), + original_state: s.tools.mixer.clone(), + }; + live.push(&points)?; + Ok(live) + } + + pub fn bounds(&self) -> Rect { + self.core.bounds.union(&self.tail) + } + pub fn wants_time(&self) -> bool { + self.core.generator.wants_time() + } + + /// Batches and individual input samples produce identical results. The speculative end + /// dab / smoothing tail is displayed but never fed into the next accepted input. + pub fn push(&mut self, points: &[StrokePoint]) -> Result { + check_coords(points, CMD)?; + if self.points.len().saturating_add(points.len()) > 65_536 { + return Err(bad(CMD, "stroke exceeds 65536 recorded input samples")); + } + let mut last = self.core.last; + for point in points { + if last.is_some_and(|p| (point.x - p.x).hypot(point.y - p.y) > 2048.0) { + return Err(bad(CMD, "input segment exceeds 2048 pixels; supply interpolated input")); + } + last = Some(*point); + } + let cmyk = self.cmyk.clone(); + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + let old_tail = self.tail; + let mut damage = Rect::EMPTY; + for point in points { + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + self.core.generator.push(&[*point], &mut dabs, &mut dual); + damage = damage.union(&self.core.apply(&dabs)?); + self.core.last = Some(*point); + } + let mut finished = self.core.clone(); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + finished.generator.finish(&mut dabs, &mut dual); + self.tail = finished.apply(&dabs)?; + self.doc = finished.doc; + self.state = finished.state; + self.points.extend_from_slice(points); + Ok(damage.union(&old_tail).union(&self.tail)) + }) + } + + fn commit_params(&self) -> Result { + let mut params = self.core.params.clone(); + params["points"] = serde_json::to_value(&self.points).map_err(|e| bad(CMD, e.to_string()))?; + params["brush"] = serde_json::to_value(&self.core.ctx.brush).map_err(|e| bad(CMD, e.to_string()))?; + params["seed"] = json!(self.seed); + params["color"] = json!(self.core.ctx.brush.color); + if params.get("mixerState").is_none() { + params["mixerState"] = serde_json::to_value(&self.original_state).map_err(|e| bad(CMD, e.to_string()))?; + } + Ok(params) + } + + /// Stage the already rendered pixels for the ordinary journaled command. Refuse stale + /// document/tool state. The command consumes this single-use cache only for identical params. + pub fn prepare_commit(self, session: &mut Session) -> Result { + if !session.active().is_some_and(|st| Arc::ptr_eq(&st.doc, &self.original) && (self.core.layer.is_none() || st.active_layer == self.core.layer)) + || session.tools.mixer != self.original_state + { + return Err(bad(CMD, "document or loaded paint changed during the stroke")); + } + let params = self.commit_params()?; + session.prepared_mixer = Some(self); + Ok(params) + } +} + +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let cached = s.prepared_mixer.take().filter(|live| { + s.active().is_some_and(|st| Arc::ptr_eq(&st.doc, &live.original)) + && s.tools.mixer == live.original_state + && live.commit_params().is_ok_and(|params| params == *p) + }); + let live = match cached { + Some(live) => live, + None => LiveMixer::begin(s, p)?, + }; + let damage = live.bounds(); + s.edit("Mixer Brush", |doc, _| { + *doc = (*live.doc).clone(); + Ok(()) + })?; + let mut state = live.state; + if live.core.settings.clean_after_stroke { + state.clean(); + } + if live.core.settings.reload_after_stroke && state.reservoir.is_some() { + state.amount = 1.0; + } + s.tools.mixer = state; + Ok(damage_json(s, damage)) +} + +/// Sampling changes only session tool state, never document pixels or document Undo. +pub(super) fn sample(s: &mut Session, p: &Value) -> Result { + if p.get("points").and_then(Value::as_array).is_some_and(|v| v.len() != 1) { + return Err(bad("brush.mixer.sample", "exactly one sample point is required")); + } + let points = parse_points(p, "brush.mixer.sample")?; + if points.len() != 1 { + return Err(bad("brush.mixer.sample", "exactly one sample point is required")); + } + let mut brush = resolve_brush(s, p, "brush.mixer.sample")?; + if brush.size > 512.0 { + return Err(bad("brush.mixer.sample", "sampling size is limited to 512 pixels")); + } + brush.flow = 1.0; + let dabs = photocraft_paint::dabs(&Stroke { brush: brush.clone(), points }); + let dab = dabs.first().ok_or_else(|| bad("brush.mixer.sample", "brush has no contact"))?; + let ctx = BrushContext::new(&brush); + let rect = ctx.dab_rect(dab, false); + if u64::from(rect.width()).saturating_mul(u64::from(rect.height())) > 1_048_576 { + return Err(bad("brush.mixer.sample", "sampling footprint is too large")); + } + let fp = ctx.footprint(dab, 0); + let st = s.active().ok_or(EngineError::NoDocument)?; + let mut doc = crate::float_cmds::displayed(st, (0, 0)).unwrap_or_else(|| (*st.doc).clone()); + let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) }; + let cmyk = doc_cmyk_space(s); + let load = photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || -> Result> { + let surface = if flag(p, "sampleAllLayers", brush.mixer.sample_all_layers) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels { + let buf = photocraft_compose::render(&doc, rect); + let mut surface = Surface::new(PixelFormat::RGBA32F); + surface.write_region(rect, &buf.px.iter().flatten().copied().collect::>()); + surface + } else if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels { + id.and_then(|id| doc.layer(id)) + .and_then(|layer| layer.surface()) + .cloned() + .ok_or_else(|| bad("brush.mixer.sample", "current layer has no raster pixels to sample"))? + } else { + crate::channel_cmds::target_surface(&mut doc, id, p)?.0.clone() + }; + let mut load = Vec::with_capacity(4096); + let (sin, cos) = dab.angle.sin_cos(); + for row in 0..64 { + for col in 0..64 { + let mut u = ((col as f32 + 0.5) / 32.0 - 1.0) * dab.radius; + let mut v = ((row as f32 + 0.5) / 32.0 - 1.0) * (dab.radius * dab.roundness).max(0.5); + if dab.flip_x { + u = -u; + } + if dab.flip_y { + v = -v; + } + let (mut dx, mut up) = (u * cos + v * sin, u * sin - v * cos); + if dab.proj_scale < 0.999 { + let (sin, cos) = dab.proj_angle.sin_cos(); + let along = (dx * cos + up * sin) * (dab.proj_scale.max(0.05) - 1.0); + dx += along * cos; + up += along * sin; + } + let x = (dab.center.x as f32 + dx).floor() as i32; + let y = (dab.center.y as f32 - up).floor() as i32; + let mut color = surface.rgba(x, y); + color[3] *= fp.at(x, y).clamp(0.0, 1.0); + load.push(color); + } + } + Ok(load) + })?; + let mut average = [0.0f32; 4]; + for c in &load { + for k in 0..3 { + average[k] += c[k] * c[3]; + } + average[3] += c[3]; + } + if average[3] > 0.0 { + for k in 0..3 { + average[k] /= average[3]; + } + } + average[3] = 1.0; + s.tools.mixer.load(average); + s.tools.mixer.spatial = Some(load); + s.tools.mixer.clean(); + Ok(json!({"width":64,"height":64,"color":average})) +} + +pub(super) fn load(s: &mut Session, p: &Value) -> Result { + let color = color(p.get("color"), s.tools.foreground); + if !valid_color(&color) { + return Err(bad("brush.mixer.load", "loaded color must be finite and magnitudes at most 1000000")); + } + s.tools.mixer.load(color); + Ok(json!({"loaded":true})) +} + +pub(super) fn clean(s: &mut Session, _: &Value) -> Result { + s.tools.mixer = MixerState::default(); + // Cleaning is an explicit empty-brush choice, so do not silently reload the next stroke. + s.tools.brush.mixer.reload_after_stroke = false; + Ok(json!({"loaded":false})) +} diff --git a/crates/engine/src/brush_cmds/mixer_live_tests.rs b/crates/engine/src/brush_cmds/mixer_live_tests.rs new file mode 100644 index 0000000000..b13dc6ed3e --- /dev/null +++ b/crates/engine/src/brush_cmds/mixer_live_tests.rs @@ -0,0 +1,226 @@ +use super::mixer_live::LiveMixer; +use super::*; +use photocraft_color::PixelFormat; + +fn fixture(fmt: PixelFormat) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":192,"height":96,"background":"#808080"})).unwrap(); + s.execute("layer.new.layer", json!({"name":"Source"})).unwrap(); + s.edit("fixture", |doc, id| { + let (surface, _) = crate::channel_cmds::target_surface(doc, *id, &json!({}))?; + *surface = Surface::new(fmt); + surface.fill_rect(Rect::new(0, 0, 96, 96), &[1.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(96, 0, 192, 96), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({"name":"Paint"})).unwrap(); + s.edit("depth", |doc, id| { + *crate::channel_cmds::target_surface(doc, *id, &json!({}))?.0 = Surface::new(fmt); + Ok(()) + }) + .unwrap(); + s +} + +fn target(s: &Session) -> Surface { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() +} + +#[test] +fn mixer_live_empty_layer_exact_commit_undo_source_preservation_and_chunking() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut s = fixture(fmt); + assert!(s.tools.brush.mixer.sample_all_layers); + let before = s.active().unwrap().doc.clone(); + let params = json!({"points":[[40,48]],"seed":47,"size":24,"wet":100,"mix":100,"cleanAfterStroke":false}); + let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + assert!(live.doc.layer(id).unwrap().surface().unwrap().rgba(40, 48)[3] > 0.0); + assert_eq!(target(&s).rgba(40, 48)[3], 0.0, "preview must not edit the session"); + let mut points = vec![StrokePoint::new(40.0, 48.0, 1.0)]; + for x in [56.0, 72.0, 88.0, 104.0, 120.0, 136.0, 152.0] { + let p = StrokePoint::new(x, 48.0, 1.0); + live.push(&[p]).unwrap(); + points.push(p); + } + let preview = live.doc.layer(id).unwrap().surface().unwrap().clone(); + let mut full = params.clone(); + full["points"] = json!(points); + s.execute("paint.mixerBrush", full).unwrap(); + assert_eq!(preview.read_region(before.bounds()), target(&s).read_region(before.bounds()), "live/replay tolerance is exactly zero"); + for old in &before.layers { + if old.id != id { + assert_eq!( + old.surface().unwrap().read_region(before.bounds()), + s.active().unwrap().doc.layer(old.id).unwrap().surface().unwrap().read_region(before.bounds()) + ); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(target(&s).read_region(before.bounds()), before.layer(id).unwrap().surface().unwrap().read_region(before.bounds())); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(target(&s).read_region(before.bounds()), preview.read_region(before.bounds())); + } +} + +#[test] +fn mixer_live_current_layer_matches_reference_and_cancels() { + let mut s = fixture(PixelFormat::RGBA32F); + let p = json!({"points":[[30,30],[60,34],[100,60]],"seed":9,"size":16,"sampleAllLayers":false,"wet":65,"mix":70,"load":90}); + let mut expected = target(&s); + let brush = resolve_brush(&s, &p, "paint.mixerBrush").unwrap(); + let mut state = photocraft_paint::mixer::MixerState::default(); + state.load(s.tools.foreground); + photocraft_paint::mixer::apply_mixer_stroke( + &mut expected, + None, + &Stroke { brush, points: parse_points(&p, "paint.mixerBrush").unwrap() }, + &MixerSettings { wet: 0.65, mix: 0.70, load: 0.90, sample_all_layers: false, ..Default::default() }, + &mut state, + None, + false, + ); + let live = LiveMixer::begin(&s, &p).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let actual = live.doc.layer(id).unwrap().surface().unwrap().read_region(s.active().unwrap().doc.bounds()); + let expected = expected.read_region(s.active().unwrap().doc.bounds()); + let max = actual.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(max <= 1e-6, "reference error {max}"); + drop(live); + assert_eq!(target(&s).rgba(30, 30)[3], 0.0); + s.execute("brush.mixer.clean", json!({})).unwrap(); + s.execute("paint.mixerBrush", json!({"points":[[30,30],[60,30]],"sampleAllLayers":false,"wet":0})).unwrap(); + assert_eq!(target(&s).rgba(30, 30)[3], 0.0, "clean brush must stay empty"); +} + +#[test] +fn mixer_sample_is_spatial_and_never_edits_document() { + let mut s = fixture(PixelFormat::RGBA8); + let before = s.active().unwrap().doc.clone(); + s.execute("brush.mixer.sample", json!({"points":[[96,48]],"size":40,"brush":{"hardness":1.0,"pressureSize":false}})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc)); + let load = s.tools.mixer.spatial.as_ref().unwrap(); + assert_eq!(load.len(), 4096); + assert!(load.iter().any(|p| p[0] > 0.9 && p[1] < 0.1 && p[3] > 0.9)); + assert!(load.iter().any(|p| p[1] > 0.9 && p[0] < 0.1 && p[3] > 0.9)); + s.execute("paint.mixerBrush", json!({"points":[[48,48]],"size":40,"wet":0,"mix":0,"brush":{"hardness":1.0,"pressureSize":false}})).unwrap(); + assert!(target(&s).rgba(40, 48)[0] > 0.9); + assert!(target(&s).rgba(56, 48)[1] > 0.9); + assert!(s.tools.mixer.spatial.is_some(), "sample persists across strokes"); +} + +#[test] +fn mixer_live_smoothing_tail_and_invalid_input() { + let mut s = fixture(PixelFormat::RGBA16); + let p = json!({"points":[[20,40]],"size":12,"seed":42,"brush":{"smoothing":{"amount":0.6,"catchUpOnEnd":true}}}); + let mut live = LiveMixer::begin(&s, &p).unwrap(); + live.push(&[StrokePoint::new(60.0, 40.0, 0.6)]).unwrap(); + live.push(&[StrokePoint::new(100.0, 48.0, 1.0)]).unwrap(); + let before = live.doc.clone(); + assert!(live.push(&[StrokePoint::new(f64::NAN, 0.0, 1.0)]).is_err()); + assert!(std::sync::Arc::ptr_eq(&before, &live.doc)); + let mut commit = p.clone(); + commit["points"] = json!([[20, 40, 1], [60, 40, 0.6], [100, 48, 1]]); + s.execute("paint.mixerBrush", commit).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + assert_eq!( + live.doc.layer(id).unwrap().surface().unwrap().read_region(s.active().unwrap().doc.bounds()), + target(&s).read_region(s.active().unwrap().doc.bounds()) + ); + assert!(s.execute("paint.mixerBrush", json!({"points":[[0,0]],"size":5000})).is_err()); + assert!(s.execute("brush.mixer.sample", json!({"points":[[0,0],[1,1]]})).is_err()); +} + +#[test] +fn mixer_sampling_obeys_masks_opacity_blend_and_current_layer_switch() { + let mut s = fixture(PixelFormat::RGBA8); + let source = s.active().unwrap().doc.layers.iter().find(|l| l.name == "Source").unwrap().id; + s.edit("source composition", |doc, _| { + let layer = doc.layer_mut(source).unwrap(); + layer.opacity = 0.4; + layer.blend = photocraft_color::BlendMode::Multiply; + layer.mask = Some(photocraft_doc::LayerMask::hide_all()); + Ok(()) + }) + .unwrap(); + let expected = photocraft_compose::render(&s.active().unwrap().doc, Rect::new(39, 39, 40, 40)).px[0]; + s.execute("brush.mixer.sample", json!({"points":[[40,40]],"size":8})).unwrap(); + let actual = s.tools.mixer.reservoir.unwrap(); + for c in 0..3 { + assert!((actual[c] - expected[c]).abs() < 1e-5); + } + s.execute("brush.mixer.clean", json!({})).unwrap(); + s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":8,"wet":100,"mix":100,"sampleAllLayers":false})).unwrap(); + assert_eq!(target(&s).rgba(50, 40)[3], 0.0, "current empty layer provides no paint"); + s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":8,"wet":100,"mix":100,"sampleAllLayers":true})).unwrap(); + assert!(target(&s).rgba(50, 40)[3] > 0.9, "all layers supplies the visible composite"); +} + +#[test] +fn mixer_overlapping_dabs_resample_the_evolving_composite() { + let mut s = fixture(PixelFormat::RGBA32F); + s.execute("tools.setColors", json!({"foreground":"#0000ff"})).unwrap(); + let params = json!({"points":[[50,48]],"size":20,"seed":1,"wet":100,"mix":50,"cleanAfterStroke":false}); + let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); + live.push(&[StrokePoint::new(54.0, 48.0, 1.0), StrokePoint::new(50.0, 48.0, 1.0)]).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let pixel = live.doc.layer(id).unwrap().surface().unwrap().rgba(50, 48); + assert!(pixel[2] > 0.5, "deposited blue feeds back into later pickups: {pixel:?}"); +} + +#[test] +fn mixer_prepared_commit_uses_displayed_pixels_and_rejects_stale_documents() { + let mut s = fixture(PixelFormat::RGBA8); + let p = json!({"points":[[20,40]],"size":16,"target":"pixels","seed":55}); + let mut live = LiveMixer::begin(&s, &p).unwrap(); + live.push(&[StrokePoint::new(80.0, 40.0, 0.6)]).unwrap(); + let shown = live.doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let steps = s.active().unwrap().history.past_len(); + let commit = live.prepare_commit(&mut s).unwrap(); + assert!(s.prepared_mixer.is_some()); + s.execute("paint.mixerBrush", commit.clone()).unwrap(); + assert!(s.prepared_mixer.is_none()); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + assert_eq!(target(&s).read_region(shown.bounds()), shown.layer(id).unwrap().surface().unwrap().read_region(shown.bounds())); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("paint.mixerBrush", commit).unwrap(); + assert_eq!(target(&s).read_region(shown.bounds()), shown.layer(id).unwrap().surface().unwrap().read_region(shown.bounds())); + let stale = LiveMixer::begin(&s, &p).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert!(stale.prepare_commit(&mut s).is_err()); +} + +#[test] +fn mixer_load_commands_preserve_floating_selection_and_history() { + let mut s = fixture(PixelFormat::RGBA8); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.float", json!({"dx":8,"dy":0,"copy":true})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + for (command, params) in [("brush.mixer.sample", json!({"points":[[96,48]],"size":24})), ("brush.mixer.load", json!({})), ("brush.mixer.clean", json!({}))] + { + s.execute(command, params).unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + } +} + +#[test] +fn mixer_rejects_malformed_load_and_retains_or_reloads_paint() { + let mut s = fixture(PixelFormat::RGBA8); + let before = s.active().unwrap().doc.clone(); + for state in [json!({"spatial":[]}), json!({"spatial":[[1,0,0,1]]}), json!({"amount":"bad"}), json!({"reservoir":[1e300,0,0,1]})] { + assert!(s.execute("paint.mixerBrush", json!({"points":[[40,40]],"mixerState":state})).is_err()); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc)); + } + assert!(s.execute("brush.mixer.load", json!({"color":[1e300,0,0,1]})).is_err()); + s.execute("brush.mixer.load", json!({"color":"#ff0000"})).unwrap(); + s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":10,"loadAfterStroke":false,"load":10})).unwrap(); + assert!(s.tools.mixer.amount > 0.0 && s.tools.mixer.amount < 1.0); + s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":10,"loadAfterStroke":true,"load":10})).unwrap(); + assert_eq!(s.tools.mixer.amount, 1.0); +} diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rs index 892f754748..645d761fd5 100644 --- a/crates/engine/src/float_cmds.rs +++ b/crates/engine/src/float_cmds.rs @@ -205,7 +205,8 @@ pub fn drop_floating(s: &mut Session) -> Result { /// Commands that leave a floating piece floating: its own, and ones that don't touch documents. fn keeps_floating(id: &str) -> bool { - matches!(id, "select.float" | "select.drop") || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p)) + matches!(id, "select.float" | "select.drop" | "brush.mixer.sample" | "brush.mixer.load" | "brush.mixer.clean") + || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p)) } /// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up: diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca09663707..a802cf1607 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -325,6 +325,8 @@ pub struct Session { docs: Vec, active: Option, pub tools: ToolState, + /// One validated Mixer Brush result awaiting its normal command dispatch. Never persisted. + pub(crate) prepared_mixer: Option, /// Log of executed commands (for action recording and debugging). pub journal: Vec<(String, Value)>, /// Coalescing key of the command being executed. diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index afb8092cd2..4c35019cba 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -26,11 +26,13 @@ pub struct MixerSettings { pub flow: f32, /// Pick up colour from all visible layers instead of the target layer only. pub sample_all_layers: bool, + pub clean_after_stroke: bool, + pub reload_after_stroke: bool, } impl Default for MixerSettings { fn default() -> Self { - Self { wet: 0.5, load: 0.5, mix: 0.5, flow: 1.0, sample_all_layers: false } + Self { wet: 0.5, load: 0.5, mix: 0.5, flow: 1.0, sample_all_layers: true, clean_after_stroke: true, reload_after_stroke: true } } } @@ -44,11 +46,14 @@ pub struct MixerState { pub amount: f32, /// Colour picked up from the canvas (straight RGBA), None = clean. pub pickup: Option<[f32; 4]>, + /// A bounded 64 x 64 spatial load in tip-local coordinates. Empty cells carry no paint. + pub spatial: Option>, } impl MixerState { /// Load the reservoir with a colour (full). pub fn load(&mut self, color: [f32; 4]) { + self.spatial = None; self.reservoir = Some(color); self.amount = 1.0; } @@ -58,6 +63,34 @@ impl MixerState { } } +/// Sample a spatial load at a dab pixel using the dab's rotation, aspect and flips. +/// Keeping the reservoir in tip coordinates lets it follow subsequent brush poses. +pub fn load_at(load: &[[f32; 4]], dab: &crate::Dab, x: f32, y: f32) -> [f32; 4] { + let mut dx = x - dab.center.x as f32; + let mut dy = y - dab.center.y as f32; + if dab.proj_scale < 0.999 { + let (sin, cos) = dab.proj_angle.sin_cos(); + let along = (dx * cos - dy * sin) * (1.0 / dab.proj_scale.max(0.05) - 1.0); + dx += along * cos; + dy -= along * sin; + } + let (sin, cos) = dab.angle.sin_cos(); + let mut u = (dx * cos - dy * sin) / dab.radius.max(0.01); + let mut v = (dx * sin + dy * cos) / (dab.radius * dab.roundness).max(0.5); + if dab.flip_x { + u = -u; + } + if dab.flip_y { + v = -v; + } + if !(-1.0..1.0).contains(&u) || !(-1.0..1.0).contains(&v) { + return [0.0; 4]; + } + let col = ((u + 1.0) * 32.0) as usize; + let row = ((v + 1.0) * 32.0) as usize; + load.get(row * 64 + col).copied().unwrap_or([0.0; 4]) +} + /// Paint a Mixer Brush stroke. `sample` is the surface colour is picked up from (the layer itself /// when None; a flattened composite for Sample All Layers). Returns the damaged rectangle. pub fn apply_mixer_stroke( @@ -70,6 +103,23 @@ pub fn apply_mixer_stroke( lock_transparency: bool, ) -> Rect { let fmt = target.format(); + let mut st = stroke.clone(); + st.brush.opacity = 1.0; + apply_dab_stroke(target, &st, selection, lock_transparency, 0, |work, fp| { + apply_mixer_dab(work, fp, fmt, sample, m, state, lock_transparency); + }) +} + +/// One incremental wet-paint dab, shared by recorded strokes and the live document transaction. +pub fn apply_mixer_dab( + work: &mut crate::retouch::Region, + fp: &crate::retouch::Footprint, + fmt: photocraft_color::PixelFormat, + sample: Option<&Surface>, + m: &MixerSettings, + state: &mut MixerState, + lock_transparency: bool, +) { let n = fmt.channels(); let a = alpha_index(&fmt); let nc = fmt.mode.color_channels(); @@ -84,70 +134,86 @@ pub fn apply_mixer_stroke( let mut amount = if res.is_some() { state.amount.clamp(0.0, 1.0) } else { 0.0 }; let mut pickup: Option> = state.pickup.map(native); let (wet, mix, flow, load) = (m.wet.clamp(0.0, 1.0), m.mix.clamp(0.0, 1.0), m.flow.clamp(0.0, 1.0), m.load.clamp(0.0, 1.0)); - let mut st = stroke.clone(); - st.brush.opacity = 1.0; let mut acc = vec![0.0f32; n]; let mut paint = vec![0.0f32; n]; - let dmg = apply_dab_stroke(target, &st, selection, lock_transparency, 0, |work, fp| { - // Transfer › Wetness / Mix Jitter scale the settings per dab. - let (wet, mix) = (wet * fp.dab.wet.clamp(0.0, 1.0), mix * fp.dab.mix.clamp(0.0, 1.0)); - // Sample the canvas under the dab. - acc.iter_mut().for_each(|v| *v = 0.0); - let (mut wsum, mut asum) = (0.0f32, 0.0f32); - let r = fp.rect.intersect(&work.rect); + // Transfer › Wetness / Mix Jitter scale the settings per dab. + let (wet, mix) = (wet * fp.dab.wet.clamp(0.0, 1.0), mix * fp.dab.mix.clamp(0.0, 1.0)); + // Sample the canvas under the dab. + acc.iter_mut().for_each(|v| *v = 0.0); + let (mut wsum, mut asum) = (0.0f32, 0.0f32); + let r = fp.rect.intersect(&work.rect); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let w = fp.at(x, y); + if w <= 0.0 { + continue; + } + let px: Vec = match sample { + Some(s) => { + let v = s.pixel(x, y); + if s.format() == fmt { v } else { from_rgba(&fmt, s.rgba(x, y)) } + } + None => work.px(x, y).to_vec(), + }; + let al = a.map_or(1.0, |ai| px[ai]); + for c in 0..nc { + acc[c] += px[c] * w * al; + } + wsum += w; + asum += w * al; + } + } + if asum > 1e-6 && wet > 0.0 { + let ca = asum / wsum.max(1e-6); + let canvas: Vec = (0..n).map(|c| if c < nc { acc[c] / asum } else { 1.0 }).collect(); + pickup = Some(match pickup.take() { + None => canvas, + Some(p) => p.iter().zip(&canvas).map(|(p, c)| p + (c - p) * PICKUP_RATE * wet * ca).collect(), + }); + } + let wr = if res.is_some() { amount * (1.0 - mix * wet) } else { 0.0 }; + let wp = if pickup.is_some() { mix * wet } else { 0.0 }; + let total = wr + wp; + if total > 1e-6 { + for c in 0..n { + let rv = res.as_ref().map_or(0.0, |v| v[c]); + let pv = pickup.as_ref().map_or(0.0, |v| v[c]); + paint[c] = (rv * wr + pv * wp) / total; + } + let dep = total.min(1.0) * flow; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let w = fp.at(x, y); - if w <= 0.0 { - continue; - } - let px: Vec = match sample { - Some(s) => { - let v = s.pixel(x, y); - if s.format() == fmt { v } else { from_rgba(&fmt, s.rgba(x, y)) } - } - None => work.px(x, y).to_vec(), - }; - let al = a.map_or(1.0, |ai| px[ai]); - for c in 0..nc { - acc[c] += px[c] * w * al; - } - wsum += w; - asum += w * al; - } - } - if asum > 1e-6 && wet > 0.0 { - let ca = asum / wsum.max(1e-6); - let canvas: Vec = (0..n).map(|c| if c < nc { acc[c] / asum } else { 1.0 }).collect(); - pickup = Some(match pickup.take() { - None => canvas, - Some(p) => p.iter().zip(&canvas).map(|(p, c)| p + (c - p) * PICKUP_RATE * wet * ca).collect(), - }); - } - let wr = if res.is_some() { amount * (1.0 - mix * wet) } else { 0.0 }; - let wp = if pickup.is_some() { mix * wet } else { 0.0 }; - let total = wr + wp; - if total > 1e-6 { - for c in 0..n { - let rv = res.as_ref().map_or(0.0, |v| v[c]); - let pv = pickup.as_ref().map_or(0.0, |v| v[c]); - paint[c] = (rv * wr + pv * wp) / total; - } - let dep = total.min(1.0) * flow; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let k = fp.at(x, y) * dep; - if k > 0.0 { + let k = fp.at(x, y) * dep; + if k > 0.0 { + if let Some(load) = &state.spatial { + let loaded = load_at(load, &fp.dab, x as f32 + 0.5, y as f32 + 0.5); + let local = from_rgba(&fmt, loaded); + let local_wr = wr * loaded[3]; + let local_total = local_wr + wp; + if local_total > 1e-6 { + let mut mixed = paint.clone(); + for (c, value) in mixed.iter_mut().enumerate() { + *value = (local.get(c).copied().unwrap_or(0.0) * local_wr + + pickup.as_ref().and_then(|p| p.get(c)).copied().unwrap_or(0.0) * wp) + / local_total; + } + if let Some(ai) = a + && let Some(alpha) = mixed.get_mut(ai) + { + *alpha = 1.0; + } + over_native(&fmt, work.px_mut(x, y), &mixed, fp.at(x, y) * local_total.min(1.0) * flow, lock_transparency); + } + } else { over_native(&fmt, work.px_mut(x, y), &paint, k, lock_transparency); } } } } - amount *= 1.0 - 0.08 * (1.0 - load); - }); + } + amount *= 1.0 - 0.08 * (1.0 - load); state.amount = amount; state.pickup = pickup.map(|p| to_rgba(&fmt, &p)); - dmg } #[cfg(test)] diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index d4a20b04ae..b027c3bf7f 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -111,6 +111,36 @@ fn alt_click_with_the_brush_samples_the_foreground() { assert_eq!(h.state().session.tools.foreground, [0.0, 1.0, 0.0, 1.0], "⌥-click sampled green"); } +#[test] +fn mixer_alt_click_samples_the_tip_through_zoomed_rotated_canvas_input() { + for (zoom, rotation) in [(0.5, 0.0), (1.0, 0.0), (2.0, 30.0)] { + let mut app = two_colours(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":24,"roundness":0.4,"hardness":1.0,"pressureSize":false,"mixer":{"wet":0.0,"mix":0.0}}})).unwrap(); + let mut h = harness(app); + h.state_mut().ui.tool = Tool::MixerBrush; + h.state_mut().ui.views[0].zoom = zoom; + h.state_mut().ui.views[0].rotation = rotation; + h.run_steps(2); + let before = h.state().session.active().unwrap().doc.clone(); + let steps = h.state().session.active().unwrap().history.past_len(); + click(&mut h, 100.0, 50.0, Modifiers::ALT); + let state = &h.state().session.tools.mixer; + let load = state.spatial.as_ref().expect("Alt loads a spatial brush tip"); + assert!(load.iter().any(|c| c[0] > 0.9 && c[1] < 0.1 && c[3] > 0.9)); + assert!(load.iter().any(|c| c[1] > 0.9 && c[0] < 0.1 && c[3] > 0.9)); + assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc)); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); + click(&mut h, 40.0, 50.0, Modifiers::NONE); + let st = h.state().session.active().unwrap(); + let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert!(surface.rgba(34, 50)[0] > 0.9 && surface.rgba(46, 50)[1] > 0.9, "loaded halves follow document coordinates at {zoom}x/{rotation}°"); + assert_eq!(st.history.past_len(), steps + 1); + assert!(crate::alt_grab::alt_click_tool(Tool::MixerBrush, Modifiers::ALT)); + assert!(!crate::alt_grab::alt_click_tool(Tool::MixerBrush, Modifiers::ALT | Modifiers::CTRL)); + } +} + #[test] fn alt_click_sets_the_clone_source_and_a_drag_paints_it() { let mut h = harness(two_colours()); diff --git a/crates/ui-egui/src/alt_grab.rs b/crates/ui-egui/src/alt_grab.rs index 0ba09bad7a..bd1efea422 100644 --- a/crates/ui-egui/src/alt_grab.rs +++ b/crates/ui-egui/src/alt_grab.rs @@ -29,7 +29,7 @@ struct Watch { /// Tools whose ⌥-click does something: the ⌥ Eyedropper and the clone source point. pub(crate) fn alt_click_tool(tool: Tool, mods: egui::Modifiers) -> bool { - crate::canvas::alt_samples(tool, mods) || (mods.alt && !mods.ctrl && matches!(tool, Tool::CloneStamp | Tool::Healing)) + crate::canvas::alt_samples(tool, mods) || (mods.alt && !mods.ctrl && matches!(tool, Tool::MixerBrush | Tool::CloneStamp | Tool::Healing)) } /// The status-bar message for an ⌥-click the desktop took. diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs index c61b48c1be..c599a5a093 100644 --- a/crates/ui-egui/src/brush_panel_tests.rs +++ b/crates/ui-egui/src/brush_panel_tests.rs @@ -97,7 +97,7 @@ fn edit_section(i: usize, b: &mut BrushSettings) { b.transfer.flow = dynamic(0.25, Control::Fade, 0.3); b.transfer.wetness = dynamic(0.35, Control::PenPressure, 0.1); b.transfer.mix = dynamic(0.45, Control::Fade, 0.2); - b.mixer = paint::MixerSettings { wet: 0.9, load: 0.15, mix: 0.7, flow: 0.8, sample_all_layers: true }; + b.mixer = paint::MixerSettings { wet: 0.9, load: 0.15, mix: 0.7, flow: 0.8, sample_all_layers: true, ..Default::default() }; } 7 => { let p = &mut b.pose; @@ -391,11 +391,11 @@ fn mixer_brush_options_update_the_persisted_mixer_settings() { h.drop_at(at); h.run_steps(2); - assert!(h.state().session.tools.brush.mixer.sample_all_layers); + assert!(!h.state().session.tools.brush.mixer.sample_all_layers); assert_eq!(h.state().session.journal.len(), initial + 1); let (id, params) = h.state().session.journal.last().unwrap(); assert_eq!(id, "tools.setBrush"); - assert_eq!(params["brush"]["mixer"]["sampleAllLayers"], true); + assert_eq!(params["brush"]["mixer"]["sampleAllLayers"], false); } #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a04e299f19..55ec7c4397 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -353,6 +353,7 @@ enum EngineStroke { Brush(Box), Retouch(photocraft_engine::retouch_cmds::LiveRetouch), Dab(photocraft_engine::retouch_cmds::LiveDab), + Mixer(Box), } impl EngineStroke { @@ -361,6 +362,7 @@ impl EngineStroke { fn wants_time(&self) -> bool { match self { EngineStroke::Brush(l) => l.wants_time(), + EngineStroke::Mixer(l) => l.wants_time(), EngineStroke::Retouch(_) | EngineStroke::Dab(_) => false, } } @@ -370,6 +372,7 @@ impl EngineStroke { Self::Brush(s) => &s.doc, Self::Retouch(s) => &s.doc, Self::Dab(s) => &s.doc, + Self::Mixer(s) => &s.doc, } } fn bounds(&self) -> DRect { @@ -377,6 +380,7 @@ impl EngineStroke { Self::Brush(s) => s.bounds(), Self::Retouch(s) => s.bounds(), Self::Dab(s) => s.bounds(), + Self::Mixer(s) => s.bounds(), } } fn push(&mut self, pts: &[photocraft_engine::paint::StrokePoint]) -> photocraft_engine::Result { @@ -384,12 +388,14 @@ impl EngineStroke { Self::Brush(s) => s.push(pts), Self::Retouch(s) => s.push(pts), Self::Dab(s) => s.push(pts), + Self::Mixer(s) => s.push(pts), } } /// The jitter seed the commit must reuse (the Clone Stamp's comes from the session brush). fn seed(&self) -> Option { match self { Self::Brush(s) => Some(s.seed), + Self::Mixer(s) => Some(s.seed), Self::Retouch(_) => None, Self::Dab(_) => None, } @@ -444,8 +450,10 @@ fn stroke_params(app: &PhotocraftApp, tool: Tool, erase: bool, points: &[Vec bool { - matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser | Tool::Blur | Tool::Sharpen | Tool::Smudge | Tool::Dodge | Tool::Burn | Tool::Sponge) - || live_retouch_command(tool).is_some() + matches!( + tool, + Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser | Tool::Blur | Tool::Sharpen | Tool::Smudge | Tool::Dodge | Tool::Burn | Tool::Sponge + ) || live_retouch_command(tool).is_some() } /// The retouching tools drawn live (`LiveRetouch`), by the command their live stroke previews. @@ -561,7 +569,10 @@ fn begin_live_stroke(app: &PhotocraftApp) -> Option { static STROKES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let st = app.session.active()?; let d = app.drag.as_ref()?; - let stroke = if let Some((cmd, mut p)) = crate::retouch_ui::dab_params(app, d.tool) { + let stroke = if d.tool == Tool::MixerBrush { + let p = stroke_params(app, d.tool, false, &app.stylus.stroke_points(&d.points)); + EngineStroke::Mixer(Box::new(photocraft_engine::brush_cmds::mixer_live::LiveMixer::begin(&app.session, &p).ok()?)) + } else if let Some((cmd, mut p)) = crate::retouch_ui::dab_params(app, d.tool) { // The params `retouch_ui::finish_stroke` commits; Sample All Layers isn't previewed. p["points"] = json!(d.points); p["target"] = paint_target(app); @@ -583,6 +594,20 @@ fn begin_live_stroke(app: &PhotocraftApp) -> Option { /// Render the drag points the live stroke hasn't seen yet, with the pen pressure, tilt and /// rotation the commit's `paint.stroke` gets for them. +pub(crate) fn cancel_mixer_on_context_change(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + if !app.drag.as_ref().is_some_and(|drag| drag.tool == Tool::MixerBrush) { + return false; + } + let changed = app.ui.tool != Tool::MixerBrush + || app.live_stroke.as_ref().is_some_and(|live| !app.session.active().is_some_and(|st| st.doc.id == live.doc && st.revision == live.revision)); + if changed || ctx.input(|input| !input.focused) || ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + app.drag = None; + app.live_stroke = None; + return true; + } + false +} + fn feed_live_stroke(app: &mut PhotocraftApp) { // A batched move replays several samples in one frame and calls this once at the end, so the // per-sample calls from `tool_event` are skipped (see `canvas_view`). @@ -609,7 +634,15 @@ fn feed_live_stroke(app: &mut PhotocraftApp) { l.fed = d.points.len(); match l.stroke.push(&pts) { Ok(r) => l.damage.push(r), - Err(_) => app.live_stroke = None, + Err(e) => { + let mixer = d.tool == Tool::MixerBrush; + app.live_stroke = None; + if mixer { + app.drag = None; + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + } } } @@ -621,9 +654,16 @@ fn tap_at_peak_pressure(app: &mut PhotocraftApp) { return; } let peak = f64::from(app.stylus.tap_pressure()); - if let Some(p) = app.drag.as_mut().filter(|d| d.points.len() == 1).and_then(|d| d.points.first_mut()) { + let mut refresh_mixer = false; + if let Some(d) = app.drag.as_mut().filter(|d| d.points.len() == 1) + && let Some(p) = d.points.first_mut() + { + refresh_mixer = d.tool == Tool::MixerBrush && peak > p[2]; p[2] = p[2].max(peak); } + if refresh_mixer { + app.live_stroke = begin_live_stroke(app); + } } /// While a stroke is held still, its point repeats this often (in ms) so time-based brush @@ -3959,6 +3999,17 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) return; } // View › Snap / Snap To and smart guides (snap_ui.rs). + if app.ui.tool == Tool::MixerBrush && mods.alt && !mods.ctrl && app.drag.is_none() { + if let ToolEvent::Down { x, y, pressure } = ev { + let pen = app.stylus.sample().unwrap_or_default(); + let p = json!({"points":[[x,y,pressure,pen.tilt_x,pen.tilt_y,pen.rotation]],"target":paint_target(app)}); + if let Err(e) = app.run("brush.mixer.sample", p) { + app.ui.status = e; + app.ui.status_error = true; + } + } + return; + } let raw = ev; // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first; the // Move tool (⌘ with a painting tool too, `event_tool`) drags it from anywhere. @@ -4231,6 +4282,18 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) app.stylus.record_point(); } app.live_stroke = if strokes_live(tool) { begin_live_stroke(app) } else { None }; + if tool == Tool::MixerBrush && app.live_stroke.is_none() { + // A refused mixer stroke must never fall back to a stand-in trail and paint + // unexpectedly on release. Surface the engine's concrete error immediately. + if let Some(d) = app.drag.as_ref() { + let p = stroke_params(app, tool, false, &app.stylus.stroke_points(&d.points)); + if let Err(e) = photocraft_engine::brush_cmds::mixer_live::LiveMixer::begin(&app.session, &p) { + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + } + app.drag = None; + } } ToolEvent::Move { x, y, pressure } => { // Polygonal Lasso: ⌥ held while the button is down draws freehand into the polygon; @@ -4456,6 +4519,36 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { { app.last_stroke_end = Some((st.doc.id, [end[0], end[1]])); } + if d.tool == Tool::MixerBrush { + // The release can carry a new endpoint, including moves deferred in this frame. + // Feed those samples before offering the already-rendered document for commit. + app.drag = Some(d); + let deferred = std::mem::replace(&mut app.defer_live_stroke, false); + feed_live_stroke(app); + app.defer_live_stroke = deferred; + let Some(d) = app.drag.take() else { return }; + let live = app.live_stroke.take(); + if let Some(l) = live { + let (doc, key, steps) = (l.doc, l.key, l.damage.len() as u64); + if let EngineStroke::Mixer(mixer) = l.stroke { + match mixer.prepare_commit(&mut app.session) { + Ok(p) => { + if app.run("paint.mixerBrush", p).is_ok() { + shown_as_document(app, doc, |k| k == 0 || (key..=key + steps).contains(&k)); + } + } + Err(e) => { + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + } + } + } else { + let p = stroke_params(app, d.tool, false, &app.stylus.stroke_points(&d.points)); + let _ = app.run("paint.mixerBrush", p); + } + return; + } // A live Clone Stamp preview ends here; the commit below replaces it. if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() { app.live_stroke = None; @@ -5591,6 +5684,104 @@ mod tests { } } + #[test] + fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":16,"mixer":{"wet":1.0,"mix":0.7},"smoothing":{"amount":0.0}}})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let count = app.session.active().unwrap().history.past_len(); + let alt = egui::Modifiers { alt: true, ..Default::default() }; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Move { x: 35.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 35.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none()); + assert!(app.session.tools.mixer.spatial.is_some()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + app.run("brush.mixer.load", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 30.0, pressure: 0.6 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + let shown = display_doc(&mut app, 0).0; + let id = app.session.active().unwrap().active_layer.unwrap(); + let pixel = shown.layer(id).unwrap().surface().unwrap().rgba(45, 30); + assert!(pixel[0] > 0.0 && pixel[1] > 0.0 && pixel[3] > 0.0, "actual red/green mixture {pixel:?}"); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), count); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), count + 1); + assert_eq!( + shown.layer(id).unwrap().surface().unwrap().read_region(before.bounds()), + st.doc.layer(id).unwrap().surface().unwrap().read_region(before.bounds()) + ); + app.session.undo(); + assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(45, 30)[3], 0.0); + } + + #[test] + fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { + for deferred in [false, true] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + app.defer_live_stroke = deferred; + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 95.0, y: 30.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + let id = app.session.active().unwrap().active_layer.unwrap(); + assert!(doc.layer(id).unwrap().surface().unwrap().rgba(92, 30)[3] > 0.0); + let params = app.session.journal.iter().rev().find(|(name, _)| name == "paint.mixerBrush").unwrap().1.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *before); + app.run("paint.mixerBrush", params).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *doc); + } + } + + #[test] + fn mixer_escape_focus_loss_and_tool_switch_cancel_without_an_edit() { + for mode in 0..3 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + let ctx = egui::Context::default(); + let mut raw = egui::RawInput { focused: mode != 1, ..Default::default() }; + if mode == 0 { + raw.events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + } + if mode == 2 { + app.ui.tool = Tool::Brush; + } + ctx.begin_pass(raw); + assert!(cancel_mixer_on_context_change(&mut app, &ctx)); + let _ = ctx.end_pass(); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none() && app.live_stroke.is_none()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + } + } + #[test] fn brush_drag_shows_the_real_stroke_and_commits_it() { // The drag used to draw a hard, flat stand-in and only showed the soft brush on release. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 444036c57f..b3ba2472b2 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -973,6 +973,32 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } widgets::vline(ui, 22.0); widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); + ui.menu_button(tl!("Paint Load"), |ui| { + ui.label(tl!("Alt-click the canvas to load the brush tip")); + if ui.button(tl!("Load Brush")).clicked() { let _ = app.run("brush.mixer.load", json!({})); } + if ui.button(tl!("Clean Brush")).clicked() { + let _ = app.run("brush.mixer.clean", json!({})); + b.mixer.reload_after_stroke = false; + } + widgets::checkbox(ui, &mut b.mixer.clean_after_stroke, tl!("Clean pickup after stroke")); + widgets::checkbox(ui, &mut b.mixer.reload_after_stroke, tl!("Reload after stroke")); + let (rect, _) = ui.allocate_exact_size(egui::vec2(64.0, 64.0), egui::Sense::hover()); + ui.painter().rect_filled(rect, 0.0, t.canvas); + let state = &app.session.tools.mixer; + let mut buffer = photocraft_compose::Buffer::transparent(photocraft_geom::Rect::new(0, 0, 32, 32)); + for (i, pixel) in buffer.px.iter_mut().enumerate() { + *pixel = state.spatial.as_ref().and_then(|v| v.get((i / 32) * 128 + (i % 32) * 2)).copied() + .or(state.reservoir).unwrap_or([0.0; 4]); + pixel[3] *= state.amount; + } + let display = app.session.active().and_then(|st| app.session.color.canvas_display_for(&st.doc, app.session.color.main_display).ok()); + let image = display.map_or_else(|| buffer.to_rgba8(), |display| display.to_rgba8(&buffer)); + for y in 0..32 { for x in 0..32 { + let c = image.pixels.get((y * 32 + x) * 4..(y * 32 + x + 1) * 4).unwrap_or(&[0; 4]); + let color = Color32::from_rgba_unmultiplied(c[0],c[1],c[2],c[3]); + ui.painter().rect_filled(egui::Rect::from_min_size(rect.min + egui::vec2(x as f32 * 2.0,y as f32 * 2.0),egui::vec2(2.0,2.0)),0.0,color); + }} + }); } Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee if t.pro => { ui.spacing_mut().item_spacing.x = 2.0; diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 6584dfa042..ec88de0db1 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -276,6 +276,9 @@ pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInpu } pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { + if crate::canvas::cancel_mixer_on_context_change(app, ctx) { + return; + } // However the tool was picked (toolbar, flyout, shortcut, automation), its group's key brings // it back later (#2608). app.ui.remember_group_tool(); diff --git a/docs/mixer-live.md b/docs/mixer-live.md new file mode 100644 index 0000000000..46dd923b68 --- /dev/null +++ b/docs/mixer-live.md @@ -0,0 +1,147 @@ +# Incremental Mixer Brush + +This change is the foundation of the requested Mixer Brush 2.0 work. It does not +implement the floating palette, harmony wheel, physical brush rack or bristle workshop. +Those must follow qualification of the painting and sampling foundation. These +original studio features do not change Photoshop parity counts. + +## Traced cause + +Baseline: upstream main `29f1ff9e90f2581ea2964e3276d85c71ab7e79a0`. +`ui-egui/src/canvas.rs::strokes_live` excludes Mixer Brush. `retouch_ui::finish_stroke` +dispatches `paint.mixerBrush` on pointer release. The engine's `mixer_brush` builds +all dabs and calls `apply_mixer_stroke` inside one document edit. The translucent +trail is therefore not the mixed result. This is deferred tool execution, not an +observed GPU invalidation failure. + +The old Sample All Layers path also rendered a single frozen composite spanning +the complete stroke. Later dabs could not sample the paint they just deposited. + +## Implemented path + +`brush_cmds::mixer_live::LiveMixer` uses the existing `DabGenerator`, `BrushContext`, +copy-on-write document/surfaces and native-channel Mixer Brush algorithm. Its float +working tiles avoid quantizing paint after every dab. The canvas displays that real +document copy and uses the existing damage rectangles and texture updates. + +An uncommitted smoothing/end-point tail is calculated on a copy of the incremental +state. It is displayed immediately and never contaminates the next input sample. +Dropping the live transaction cancels painting. Failed live strokes cancel rather +than reverting to a placeholder trail. The recorded command uses the same path and +creates one Undo edit. Release stages the already rendered document for the normal +command dispatcher, guarded by the original document and loaded-paint identity and +exact captured parameters. That one-use cache avoids repainting on release. Recorded +commands include the brush, seed, input samples and initial reservoir for deterministic +replay through the same incremental algorithm. Escape, focus loss, tool changes and +stale document context cancel the UI transaction. + +## Sampling semantics + +* Sample All Layers defaults on for new Mixer settings. Existing explicit false + preferences remain false. +* With it on, each dab reads the CPU compositor's visible document immediately + before depositing paint, including the active layer once. This includes visible + layers above the target as well as below it. Masks, adjustments, transforms, + opacity and blend modes follow the CPU compositor. Only the target surface changes. +* With it off, dabs read the evolving target working pixels. An empty target supplies + no pickup color. Masks/channels always use current-target semantics. +* Selection coverage is applied when the float working result is written to the + preview target. The next all-layer sample sees that selection-constrained result. +* Alt/Option + primary press loads a 64 x 64 spatial tip reservoir in document + coordinates. It does not create a document edit, rasterize a layer, or start a + paint drag. Coverage, tip shape, rotation, flips, aspect and projection are sampled. + The normalized spatial load follows subsequent dab poses. Resolution is bounded; + subpixel gaps smaller than a reservoir cell are not losslessly represented. +* Load Brush replaces the spatial load with foreground paint. Clean Brush empties + it and disables automatic reload. The pickup-clean and reload settings are part + of the existing serialized brush settings. The loaded reservoir persists during + the application session, including tool switches; restart persistence is not added. +* Native pixel conversion enters the document's CMYK profile scope, as the existing + brush engine does. The loaded-tip preview uses the document-to-monitor canvas + transform. Cross-document reservoir color-profile conversion is not implemented; + reload/sample in the destination document before painting between profiles. + +Commands: `brush.mixer.sample`, `brush.mixer.load`, `brush.mixer.clean`, +and the existing `paint.mixerBrush`. UI text uses the existing localization system; +new translations are not supplied for every catalog yet. + +## Resource envelope and limitations + +Live mixer size is limited to 512 pixels; dense footprints to 1,048,576 pixels; +one input segment to 2,048 pixels; one stroke to 250,000 dabs and 256 working tiles +(256 x 256 pixels each). Requests beyond these limits return errors. A spatial load +uses 64 KiB of float color data. Document snapshots share untouched tiles. These +limits are explicit initial engineering bounds, not hardware qualification. + +No fluid solver or grouped-bristle deformation model is introduced. Existing brush +tip/dynamics support is reused. Windows pen tilt/rotation remain limited by the +existing winit input path. Native Linux Wayland, X11/Wacom, macOS and WebAssembly +hardware interaction must be tested on those systems; simulated pen events do not +establish hardware qualification. + +## Verification + +`brush_cmds/mixer_live_tests.rs` covers live output, exact commit equivalence at +8/16/32-bit depth, reference-algorithm comparison, cancellation, Undo/Redo, spatial +loading, composite sampling, current-layer behavior, overlap feedback, floating +selection preservation, malformed reservoirs, depletion and reload. +`canvas.rs` covers the pointer-down/move/release and Alt-sampling routes. The existing +Mixer options test verifies the new default and persistence through `tools.setBrush`. + +`cargo run --release -p photocraft-engine --example mixer_probe` measures CPU engine +begin/move/prepared-commit costs on a 24 MP three-layer document. It is not an OS pointer-to- +display latency test. Run it under a recorded machine/build configuration and keep +its actual JSON results with the review evidence. + +## Upstream compatibility + +No PDF Binder #2011 or PDF integration #2751 code is modified. This branch starts +from upstream main, not the PDF branch. Relevant open work inspected on 2026-10-11: +#2131 (precomputed stroke commit), #3098/#2885/#2379 (brush performance), #2902 +(GPU tiles), #1911 (Windows pen input), #2516 (tip outline/persistence), #3039 +(Stroke Path), #3111 (mask locks). No upstream merge, force push or deployment is +performed. These PRs can change shared canvas/brush code and must be checked again +before integration. The private sibling craftrules checkout was not available. + +## Initial measured envelope (2026-10-11) + +Windows x64, Intel Core i7-9700K (8 cores), rustc 1.97.1, release with LTO disabled +and 16 codegen units. Synthetic 6000 x 4000 RGB8 document, three layers, 60 input +moves of roughly 10 pixels, spacing 25%, round brush, no simulated bristles. +Initial CPU-only results (milliseconds): + +| Brush | Begin | Move median | Move p95 | Move max | Prepared commit | Historical frozen-composite full stroke | +|---|---:|---:|---:|---:|---:|---:| +| 16 px | 1.83 | 0.43 | 1.43 | 2.85 | 0.58 | 12.00 | +| 64 px | 2.73 | 1.36 | 2.37 | 2.62 | 0.64 | 39.22 | +| 256 px | 24.88 | 0.003 | 24.70 | 24.97 | 0.95 | 164.46 | + +At 256 px, many 10 px moves emit no dab at 25% spacing, explaining the low median; +the p95/max matter for interaction. The baseline is the historical algorithm's +whole-stroke cost, not baseline frame latency. New live work is distributed over +input updates, so the commit column is not a claim of total algorithm speedup. +The 256 px p95 already exceeds a 16.67 ms / 60 Hz frame budget before GPU presentation. +These measurements do not qualify pen hardware or establish a worst-case memory bound. +The realtime mixer remains PARTIAL as a release qualification, despite the tested +functional slice. The expanded Creative Painting Studio task continues with dense +2K/4K/8K benchmarks, mixer optimization, then a dynamic stamp editor and procedural +tools. Palette, rack, AI guidance/result/comparison and grouped-bristle capabilities +are NOT IMPLEMENTED in this foundation commit. Expensive bristle simulation remains +gated on measured fast-mode performance. Larger brush optimization, full hardware +input qualification, reservoir profile tagging and restart persistence remain open. + +Native qualification: 1,207 engine, 84 paint and 1,828 UI unit tests passed, together +with the engine integration tests, command panic hunt, layering, Clippy and WASM +checks. The broad native run stopped at a concurrent GPU rotation-test access +violation on WARP, matching upstream #3212; serial isolation is recorded separately. +`xtask perf --quick` completed but reported over-budget existing canvas scenarios; +successful execution is not a painting-performance PASS. Photoshop menu parity +stays unchanged. + +Upstream refreshed on 2026-10-11 to `e44d96e1d4671b8d9fd64fbabdf88fa8abf0441e`. +Ordinary-brush prepared commits (#2131) have now landed and must be preserved on +integration. Open AI PRs #2878 (provider interface / Gemini), #730 (OpenAI), #2879 +(options UI), #2995 (subject selection) and #2649 (background removal) were identified. +Provider work must reconcile those existing contributions. No external AI provider +has been invoked, and publishing advanced palette/bristle/AI components requires +the owner's separate release approval after licensing review.