PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(algo,engine): paint Select and Mask Brush, Lasso and Refine Edge Brush tile by tile
Khawar Zamman Wani56bbe6b80b88
diff --git a/crates/algo/src/matting.rs b/crates/algo/src/matting.rsindex 892a5f145..f9f3036eb 100644--- a/crates/algo/src/matting.rs+++ b/crates/algo/src/matting.rs@@ -238,7 +238,7 @@ pub fn morph(src: &[f32], w: usize, h: usize, r: usize, grow: bool) -> Vec<f32>mod brush;mod morphology;-pub use brush::{EdgeBrush, EdgeStroke, MAX_SWEPT_AREA, SIZE_RANGE as BRUSH_SIZE_RANGE, brush_region, stroke_area, swept_area};+pub use brush::{EdgeBrush, EdgeStroke, MAX_SWEPT_AREA, SIZE_RANGE as BRUSH_SIZE_RANGE, brush_surface, painted_tiles, stroke_area, swept_area};/// Running max (or min) over a window of radius `r` (edge-clipped), van Herk / Gil–Werman:/// three comparisons per sample whatever the radius.diff --git a/crates/algo/src/matting/brush.rs b/crates/algo/src/matting/brush.rsindex ee54ea187..24e4c82ad 100644--- a/crates/algo/src/matting/brush.rs+++ b/crates/algo/src/matting/brush.rs@@ -10,11 +10,17 @@//! size), the colour-line model of A. Levin, D. Lischinski and Y. Weiss, "A Closed-Form Solution//! to Natural Image Matting" (CVPR 2006), with one foreground and one background colour per window.-use photocraft_geom::Rect;+use std::collections::{BTreeMap, BTreeSet};++use photocraft_color::PixelFormat;+use photocraft_geom::{Rect, TILE_SIZE, TileCoord};+use photocraft_raster::Surface;use super::box_mean;use crate::segment::RgbImage;-use crate::selection::Region;+use crate::selection::{MAX_PAINTED_TILES, clip_segment};++const TS: usize = TILE_SIZE as usize;/// One Refine Edge Brush stroke, in document pixels.#[derive(Clone, Debug, PartialEq)]@@ -30,12 +36,15 @@ pub struct EdgeStroke {/// Brush diameters the strokes may use.pub const SIZE_RANGE: std::ops::RangeInclusive<f32> = 1.0..=5000.0;-/// The painted area: signed coverage (`+1` refined, `−1` restored, `0` untouched) over `bbox`.+/// The painted area: signed coverage (`+1` refined, `−1` restored, `0` untouched), kept only for+/// the tiles the strokes paint, so a thin stroke across a huge canvas costs those tiles, not its+/// bounding box (#8783).#[derive(Clone, Debug, PartialEq)]pub struct EdgeBrush {+ /// Where the strokes can paint.bbox: Rect,- /// Coverage × 127, row-major over `bbox`.- v: Vec<i8>,+ /// Coverage × 127 per painted tile, row-major over the tile.+ tiles: BTreeMap<TileCoord, Vec<i8>>,/// Bounds of the added (positive) coverage.added: Rect,/// Box radius of the colour estimate (pixels).@@ -89,11 +98,73 @@ pub fn stroke_area(points: &[(f32, f32)], size: f32) -> f64 {if len.is_finite() { len * size + size * size } else { f64::INFINITY }}+/// The tiles of `canvas` a round brush `size` px wide along `points` can paint, in order; `None`+/// when that is more than `limit` (a thin stroke sweeps little but touches a whole tile wherever+/// it passes, so this, not [`MAX_SWEPT_AREA`], bounds what painting it allocates; #8783).+pub fn painted_tiles(points: &[(f32, f32)], size: f32, canvas: Rect, limit: usize) -> Option<BTreeSet<TileCoord>> {+ let r = size.clamp(*SIZE_RANGE.start(), *SIZE_RANGE.end()) / 2.0;+ let mut set = BTreeSet::new();+ // Consecutive pieces mostly fall in the same tiles.+ let mut last: Option<Rect> = None;+ for (a, b) in segments(points, r, canvas) {+ let seg = dab_bounds(a, r).union(&dab_bounds(b, r)).intersect(&canvas);+ // The tile coordinates `seg` spans (inclusive).+ let span =+ Rect::new(seg.x0.div_euclid(TILE_SIZE), seg.y0.div_euclid(TILE_SIZE), (seg.x1 - 1).div_euclid(TILE_SIZE), (seg.y1 - 1).div_euclid(TILE_SIZE));+ if seg.is_empty() || last == Some(span) {+ continue;+ }+ last = Some(span);+ for tc in seg.tiles() {+ set.insert(tc);+ if set.len() > limit {+ return None;+ }+ }+ }+ Some(set)+}++/// One stroke's coverage (0–255) per tile of `canvas`: the most `cov(pixel centre, a, b)` gives+/// over the path's pieces, so a stroke never paints past full. Only painted tiles are kept;+/// `None` past `limit` tiles (see [`painted_tiles`]).+fn paint_tiles(+ points: &[(f32, f32)],+ size: f32,+ canvas: Rect,+ limit: usize,+ cov: impl Fn((f32, f32), (f32, f32), (f32, f32)) -> f32,+) -> Option<BTreeMap<TileCoord, Vec<u8>>> {+ let r = size.clamp(*SIZE_RANGE.start(), *SIZE_RANGE.end()) / 2.0;+ let mut tiles: BTreeMap<TileCoord, Vec<u8>> = painted_tiles(points, size, canvas, limit)?.into_iter().map(|tc| (tc, vec![0u8; TS * TS])).collect();+ for (a, b) in segments(points, r, canvas) {+ let seg = dab_bounds(a, r).union(&dab_bounds(b, r)).intersect(&canvas);+ for tc in seg.tiles() {+ let o = tc.rect();+ let Some(buf) = tiles.get_mut(&tc) else { continue };+ let tr = o.intersect(&seg);+ for y in tr.y0..tr.y1 {+ for x in tr.x0..tr.x1 {+ let c = (cov((x as f32 + 0.5, y as f32 + 0.5), a, b).clamp(0.0, 1.0) * 255.0).round() as u8;+ if let Some(slot) = buf.get_mut((y - o.y0) as usize * TS + (x - o.x0) as usize)+ && c > *slot+ {+ *slot = c;+ }+ }+ }+ }+ }+ tiles.retain(|_, b| b.iter().any(|v| *v > 0));+ Some(tiles)+}+/// Select and Mask's Brush: the coverage one stroke of a round brush `size` px wide with-/// `hardness` (0–100) paints along `points`, clipped to `canvas`. Overlapping dabs keep the most-/// coverage any of them gives, so a stroke never paints past full. `None` when it paints nothing,-/// has non-finite points or sweeps more than [`MAX_SWEPT_AREA`].-pub fn brush_region(points: &[(f32, f32)], size: f32, hardness: f32, canvas: Rect) -> Option<Region> {+/// `hardness` (0–100) paints along `points`, clipped to `canvas`, as a GRAY8 selection holding+/// only the tiles it paints. Overlapping dabs keep the most coverage any of them gives, so a+/// stroke never paints past full. `None` when it paints nothing, has non-finite points, sweeps+/// more than [`MAX_SWEPT_AREA`] or paints more than [`MAX_PAINTED_TILES`] tiles.+pub fn brush_surface(points: &[(f32, f32)], size: f32, hardness: f32, canvas: Rect) -> Option<Surface> {if points.is_empty() || !size.is_finite() || !hardness.is_finite() || points.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) {return None;}@@ -102,48 +173,12 @@ pub fn brush_region(points: &[(f32, f32)], size: f32, hardness: f32, canvas: Rec}let r = size.clamp(*SIZE_RANGE.start(), *SIZE_RANGE.end()) / 2.0;let core = r * hardness.clamp(0.0, 100.0) / 100.0;- let bbox = points.iter().fold(Rect::EMPTY, |acc, p| acc.union(&dab_bounds(*p, r))).intersect(&canvas);- if bbox.is_empty() {- return None;- }- let bw = bbox.width() as usize;- let mut cov = vec![0.0f32; bw.checked_mul(bbox.height() as usize)?];- for (a, b) in segments(points, r, bbox) {- let seg = dab_bounds(a, r).union(&dab_bounds(b, r)).intersect(&bbox);- for y in seg.y0..seg.y1 {- for x in seg.x0..seg.x1 {- let c = soft_coverage(segment_distance((x as f32 + 0.5, y as f32 + 0.5), a, b), r, core);- if let Some(slot) = cov.get_mut((y - bbox.y0) as usize * bw + (x - bbox.x0) as usize)- && c > *slot- {- *slot = c;- }- }- }+ let tiles = paint_tiles(points, size, canvas, MAX_PAINTED_TILES, |p, a, b| soft_coverage(segment_distance(p, a, b), r, core))?;+ let mut s = Surface::new(PixelFormat::GRAY8);+ for (tc, bytes) in &tiles {+ s.write_interleaved(tc.rect(), bytes);}- let mask: Vec<u8> = cov.iter().map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8).collect();- mask.iter().any(|v| *v > 0).then_some(Region { bbox, mask })-}--/// The part of the segment `a`–`b` inside `r` (Liang–Barsky), or `None` when it misses it.-fn clip_segment(a: (f32, f32), b: (f32, f32), r: Rect) -> Option<((f32, f32), (f32, f32))> {- let (dx, dy) = (b.0 - a.0, b.1 - a.1);- let (mut t0, mut t1) = (0.0f32, 1.0f32);- for (p, q) in [(-dx, a.0 - r.x0 as f32), (dx, r.x1 as f32 - a.0), (-dy, a.1 - r.y0 as f32), (dy, r.y1 as f32 - a.1)] {- if p == 0.0 {- if q < 0.0 {- return None;- }- } else {- let t = q / p;- if p < 0.0 {- t0 = t0.max(t);- } else {- t1 = t1.min(t);- }- }- }- (t0 <= t1 && t0.is_finite() && t1.is_finite()).then_some(((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1)))+ (s.tile_count() > 0).then_some(s)}/// The stroke's path as short segments within reach of `clip`: points closer than a quarter of@@ -181,8 +216,8 @@ fn segments(points: &[(f32, f32)], r: f32, clip: Rect) -> impl Iterator<Item = (}impl EdgeBrush {- /// Rasterises `strokes` (clipped to `canvas`). `None` when they paint nothing or sweep more- /// than [`MAX_SWEPT_AREA`].+ /// Rasterises `strokes` (clipped to `canvas`), tile by tile. `None` when they paint nothing,+ /// sweep more than [`MAX_SWEPT_AREA`] or paint more than [`MAX_PAINTED_TILES`] tiles.pub fn new(strokes: &[EdgeStroke], canvas: Rect) -> Option<EdgeBrush> {let usable = |s: &&EdgeStroke| s.size.is_finite() && !s.points.is_empty() && s.points.iter().all(|p| p.0.is_finite() && p.1.is_finite());if swept_area(strokes) > MAX_SWEPT_AREA {@@ -197,61 +232,43 @@ impl EdgeBrush {if bbox.is_empty() {return None;}- let bw = bbox.width() as usize;- let mut v = vec![0i8; bw.checked_mul(bbox.height() as usize)?];- let mut cov: Vec<f32> = Vec::new();+ let mut tiles: BTreeMap<TileCoord, Vec<i8>> = BTreeMap::new();let mut max_add = 0.0f32;for s in strokes {- let sb = stroke_bounds(s);- if sb.is_empty() {- continue;- }let r = s.size.clamp(*SIZE_RANGE.start(), *SIZE_RANGE.end()) / 2.0;if s.add {max_add = max_add.max(2.0 * r);}- let sw = sb.width() as usize;- cov.clear();- cov.resize(sw * sb.height() as usize, 0.0);// The stroke's coverage: the most any of its segments gives (a single dab for one point).- for (a, b) in segments(&s.points, r, sb) {- let seg = dab_bounds(a, r).union(&dab_bounds(b, r)).intersect(&sb);- for y in seg.y0..seg.y1 {- for x in seg.x0..seg.x1 {- let c = capsule((x as f32 + 0.5, y as f32 + 0.5), a, b, r);- if let Some(slot) = cov.get_mut((y - sb.y0) as usize * sw + (x - sb.x0) as usize)- && c > *slot- {- *slot = c;- }- }- }- }+ let cov = paint_tiles(&s.points, s.size, canvas, MAX_PAINTED_TILES, |p, a, b| capsule(p, a, b, r))?;let target = if s.add { 1.0 } else { -1.0 };- for y in sb.y0..sb.y1 {- for x in sb.x0..sb.x1 {- let c = cov.get((y - sb.y0) as usize * sw + (x - sb.x0) as usize).copied().unwrap_or(0.0);- if c <= 0.0 {- continue;- }- if let Some(slot) = v.get_mut((y - bbox.y0) as usize * bw + (x - bbox.x0) as usize) {- let cur = f32::from(*slot) / 127.0;+ for (tc, c) in cov {+ let v = tiles.entry(tc).or_insert_with(|| vec![0i8; TS * TS]);+ for (slot, c) in v.iter_mut().zip(c) {+ if c > 0 {+ let (cur, c) = (f32::from(*slot) / 127.0, f32::from(c) / 255.0);*slot = ((cur + (target - cur) * c) * 127.0).round().clamp(-127.0, 127.0) as i8;}}}+ if tiles.len() > MAX_PAINTED_TILES {+ return None;+ }}- if v.iter().all(|c| *c == 0) {+ tiles.retain(|_, v| v.iter().any(|c| *c != 0));+ if tiles.is_empty() {return None;}- let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);- for (row, line) in v.chunks_exact(bw).enumerate() {- let (Some(first), Some(last)) = (line.iter().position(|c| *c > 0), line.iter().rposition(|c| *c > 0)) else { continue };- let y = bbox.y0 + row as i32;- (x0, x1, y0, y1) = (x0.min(bbox.x0 + first as i32), x1.max(bbox.x0 + last as i32 + 1), y0.min(y), y1.max(y + 1));+ let mut added = Rect::EMPTY;+ for (tc, v) in &tiles {+ let o = tc.rect();+ for (row, line) in v.as_chunks::<TS>().0.iter().enumerate() {+ let (Some(first), Some(last)) = (line.iter().position(|c| *c > 0), line.iter().rposition(|c| *c > 0)) else { continue };+ let y = o.y0 + row as i32;+ added = added.union(&Rect::new(o.x0 + first as i32, y, o.x0 + last as i32 + 1, y + 1));+ }}- let added = if x0 < x1 { Rect::new(x0, y0, x1, y1) } else { Rect::EMPTY };- Some(EdgeBrush { bbox, v, added, window: max_add.ceil().clamp(4.0, 64.0) as usize })+ Some(EdgeBrush { bbox, tiles, added, window: max_add.ceil().clamp(4.0, 64.0) as usize })}/// Where the strokes paint (added or restored).@@ -271,16 +288,32 @@ impl EdgeBrush {/// Signed coverage at document pixel `(x, y)` (zero outside the painted area).pub fn at(&self, x: i32, y: i32) -> f32 {- if !self.bbox.contains(x, y) {- return 0.0;- }- let i = (y - self.bbox.y0) as usize * self.bbox.width() as usize + (x - self.bbox.x0) as usize;- self.v.get(i).map_or(0.0, |c| f32::from(*c) / 127.0)+ let (tc, o) = (TileCoord::containing(x, y), (y.rem_euclid(TILE_SIZE) as usize) * TS + x.rem_euclid(TILE_SIZE) as usize);+ self.tiles.get(&tc).and_then(|v| v.get(o)).map_or(0.0, |c| f32::from(*c) / 127.0)}/// Signed coverage over `r` (row-major).pub fn read(&self, r: Rect) -> Vec<f32> {- (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| self.at(x, y))).collect()+ let w = r.width() as usize;+ let mut out = vec![0.0f32; w * r.height() as usize];+ for tc in r.tiles() {+ let Some(v) = self.tiles.get(&tc) else { continue };+ let (o, tr) = (tc.rect(), tc.rect().intersect(&r));+ for y in tr.y0..tr.y1 {+ let src = (y - o.y0) as usize * TS;+ let dst = (y - r.y0) as usize * w;+ let (Some(src), Some(dst)) = (+ v.get(src + (tr.x0 - o.x0) as usize..src + (tr.x1 - o.x0) as usize),+ out.get_mut(dst + (tr.x0 - r.x0) as usize..dst + (tr.x1 - r.x0) as usize),+ ) else {+ continue;+ };+ for (d, c) in dst.iter_mut().zip(src) {+ *d = f32::from(*c) / 127.0;+ }+ }+ }+ out}}@@ -345,6 +378,11 @@ mod tests {use super::*;use crate::matting::{RefineParams, refine_mask_brushed, region_reader};use crate::segment::ImageSampler;+ use crate::selection::Region;++ fn at(s: &Surface, x: i32, y: i32) -> f32 {+ s.pixel(x, y).first().copied().unwrap_or(0.0)+ }/// Strands of the subject's colour (every 4th column from x = 60) beyond the selection's/// edge at x = 40: brushing over them adds them, Alt-brushing the edge keeps it as it was.@@ -401,32 +439,33 @@ mod tests {assert!(EdgeBrush::new(&[off, nan, empty], canvas).is_none());}#[test]- fn brush_region_paints_hard_and_soft_strokes() {+ fn brush_surface_paints_hard_and_soft_strokes() {let canvas = Rect::new(0, 0, 100, 50);- let hard = brush_region(&[(10.0, 25.0), (90.0, 25.0)], 20.0, 100.0, canvas).expect("painted");- assert!(hard.at(50, 25) > 0.99 && hard.at(50, 33) > 0.99, "solid inside the radius");- assert!(hard.at(50, 36) == 0.0 && hard.at(50, 10) == 0.0, "nothing past it");+ let hard = brush_surface(&[(10.0, 25.0), (90.0, 25.0)], 20.0, 100.0, canvas).expect("painted");+ assert!(at(&hard, 50, 25) > 0.99 && at(&hard, 50, 33) > 0.99, "solid inside the radius");+ assert!(at(&hard, 50, 36) == 0.0 && at(&hard, 50, 10) == 0.0, "nothing past it");// A soft brush fades from the centre line to the rim.- let soft = brush_region(&[(10.0, 25.0), (90.0, 25.0)], 20.0, 0.0, canvas).expect("painted");- let (centre, mid, rim) = (soft.at(50, 25), soft.at(50, 30), soft.at(50, 34));+ let soft = brush_surface(&[(10.0, 25.0), (90.0, 25.0)], 20.0, 0.0, canvas).expect("painted");+ let (centre, mid, rim) = (at(&soft, 50, 25), at(&soft, 50, 30), at(&soft, 50, 34));assert!(centre > 0.95 && mid > 0.2 && mid < 0.8 && rim < 0.1, "{centre} {mid} {rim}");// A single point is one dab; clipped to the canvas.- let dab = brush_region(&[(0.0, 0.0)], 10.0, 100.0, canvas).expect("painted");- assert_eq!((dab.bbox.x0, dab.bbox.y0), (0, 0));- assert!(dab.at(1, 1) > 0.99);+ let dab = brush_surface(&[(0.0, 0.0)], 10.0, 100.0, canvas).expect("painted");+ let b = dab.content_bounds();+ assert_eq!((b.x0, b.y0), (0, 0));+ assert!(at(&dab, 1, 1) > 0.99);}#[test]- fn brush_region_paints_nothing_for_hostile_strokes() {+ fn brush_surface_paints_nothing_for_hostile_strokes() {let canvas = Rect::new(0, 0, 100, 50);- assert!(brush_region(&[], 10.0, 100.0, canvas).is_none());- assert!(brush_region(&[(f32::NAN, 1.0)], 10.0, 100.0, canvas).is_none());- assert!(brush_region(&[(1.0, 1.0)], f32::INFINITY, 100.0, canvas).is_none());- assert!(brush_region(&[(1.0, 1.0)], 10.0, f32::NAN, canvas).is_none());- assert!(brush_region(&[(-500.0, -500.0)], 10.0, 100.0, canvas).is_none(), "off the canvas");- assert!(brush_region(&[(0.0, 0.0), (1e7, 1e7)], 5000.0, 100.0, canvas).is_none(), "sweeps too much");+ assert!(brush_surface(&[], 10.0, 100.0, canvas).is_none());+ assert!(brush_surface(&[(f32::NAN, 1.0)], 10.0, 100.0, canvas).is_none());+ assert!(brush_surface(&[(1.0, 1.0)], f32::INFINITY, 100.0, canvas).is_none());+ assert!(brush_surface(&[(1.0, 1.0)], 10.0, f32::NAN, canvas).is_none());+ assert!(brush_surface(&[(-500.0, -500.0)], 10.0, 100.0, canvas).is_none(), "off the canvas");+ assert!(brush_surface(&[(0.0, 0.0), (1e7, 1e7)], 5000.0, 100.0, canvas).is_none(), "sweeps too much");// Sizes and hardness outside their ranges are clamped, not rejected.- assert!(brush_region(&[(50.0, 25.0)], 0.0, 500.0, canvas).is_some());+ assert!(brush_surface(&[(50.0, 25.0)], 0.0, 500.0, canvas).is_some());}/// A 1 px stroke zigzagging across 2 million px stays within [`MAX_SWEPT_AREA`] yet splits/// into over 100 million pieces: painting it must not collect them all first (it allocated@@ -438,9 +477,34 @@ mod tests {assert!(stroke_area(&points, 1.0) <= MAX_SWEPT_AREA);// Only the pieces within reach of the canvas are made.assert!(segments(&points, 0.5, canvas).count() < 134 * 40, "{}", segments(&points, 0.5, canvas).count());- let r = brush_region(&points, 1.0, 100.0, canvas).expect("it paints its row");- assert!(r.at(10, 32) > 0.5);+ let r = brush_surface(&points, 1.0, 100.0, canvas).expect("it paints its row");+ assert!(at(&r, 10, 32) > 0.5);let strokes = [EdgeStroke { points, size: 1.0, add: true }];assert!(EdgeBrush::new(&strokes, canvas).is_some_and(|b| b.at(10, 32) > 0.5));}++ /// A 1 px diagonal across a 100,000 px canvas sweeps about 141,000 px, well within+ /// [`MAX_SWEPT_AREA`], but its bounding box is 10 billion pixels: painting it must cost the+ /// tiles it crosses, not that box (it allocated 40 GB; the #8783 review).+ #[test]+ fn a_thin_diagonal_across_a_huge_canvas_paints_only_its_tiles() {+ let canvas = Rect::new(0, 0, 100_000, 100_000);+ let diagonal = [(0.0, 0.0), (99_999.0, 99_999.0)];+ assert!(stroke_area(&diagonal, 1.0) <= MAX_SWEPT_AREA);+ let tiles = painted_tiles(&diagonal, 1.0, canvas, MAX_PAINTED_TILES).expect("within the limit");+ assert!(tiles.len() < 1500, "{}", tiles.len());+ let s = brush_surface(&diagonal, 1.0, 100.0, canvas).expect("painted");+ assert!(s.tile_count() <= tiles.len());+ assert!(at(&s, 50_000, 50_000) > 0.5 && at(&s, 50_000, 40_000) == 0.0);+ let strokes = [EdgeStroke { points: diagonal.to_vec(), size: 1.0, add: true }];+ let b = EdgeBrush::new(&strokes, canvas).expect("painted");+ assert!(b.at(50_000, 50_000) > 0.5 && b.at(50_000, 40_000) == 0.0);+ assert!(b.read(Rect::new(49_990, 49_990, 50_010, 50_010)).iter().any(|v| *v > 0.5));+ // A zigzag crossing more tiles than the limit is refused rather than allocated.+ let zigzag: Vec<(f32, f32)> = (0..20).map(|i| (if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0)).collect();+ assert!(stroke_area(&zigzag, 1.0) <= MAX_SWEPT_AREA);+ assert!(painted_tiles(&zigzag, 1.0, canvas, MAX_PAINTED_TILES).is_none());+ assert!(brush_surface(&zigzag, 1.0, 100.0, canvas).is_none());+ assert!(EdgeBrush::new(&[EdgeStroke { points: zigzag, size: 1.0, add: true }], canvas).is_none());+ }}diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rsindex 94f744d0b..1e71a502c 100644--- a/crates/algo/src/selection.rs+++ b/crates/algo/src/selection.rs@@ -761,10 +761,13 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec<f32> {}mod distance;+mod lasso;mod marquee;pub use distance::edt;-pub use marquee::{combine_surfaces, ellipse_surface};+pub(crate) use lasso::clip_segment;+pub use lasso::{MAX_PAINTED_TILES, polygon_edge_tiles, polygon_surface};+pub use marquee::{combine_sparse, combine_surfaces, ellipse_surface};/// Grows the selection by `r` pixels.pub fn expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec<f32> {diff --git a/crates/algo/src/selection/lasso.rs b/crates/algo/src/selection/lasso.rsnew file mode 100644index 000000000..3ca4eacd5--- /dev/null+++ b/crates/algo/src/selection/lasso.rs@@ -0,0 +1,291 @@+//! Lasso shapes built straight into tiles (#8783): only the tiles an edge crosses are rasterised,+//! and every tile wholly inside the polygon shares one solid tile, so a thin lasso across a huge+//! canvas costs the tiles along its edges, not its bounding box. The bytes are those+//! [`super::polygon`] gives over the canvas.++use std::collections::BTreeSet;+use std::sync::Arc;++use photocraft_color::PixelFormat;+use photocraft_geom::{Rect, TILE_SIZE, TileCoord};+use photocraft_raster::{Surface, Tile};++use crate::photo_util::par_map;++const TS: usize = TILE_SIZE as usize;++/// Most partly covered tiles one painted shape (a lasso, a brush stroke) may hold: 2²⁸ pixels'+/// worth, 256 MB as GRAY8. A thin shape touches a whole tile wherever it passes, so this, not+/// its area, bounds what painting it allocates.+pub const MAX_PAINTED_TILES: usize = (1 << 28) / (TS * TS);++/// The part of the segment `a`–`b` inside `r` (Liang–Barsky), or `None` when it misses it.+pub(crate) fn clip_segment(a: (f32, f32), b: (f32, f32), r: Rect) -> Option<((f32, f32), (f32, f32))> {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let (mut t0, mut t1) = (0.0f32, 1.0f32);+ for (p, q) in [(-dx, a.0 - r.x0 as f32), (dx, r.x1 as f32 - a.0), (-dy, a.1 - r.y0 as f32), (dy, r.y1 as f32 - a.1)] {+ if p == 0.0 {+ if q < 0.0 {+ return None;+ }+ } else {+ let t = q / p;+ if p < 0.0 {+ t0 = t0.max(t);+ } else {+ t1 = t1.min(t);+ }+ }+ }+ (t0 <= t1 && t0.is_finite() && t1.is_finite()).then_some(((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1)))+}++/// The pixels the polygon through `points` can touch within `clip` (its bounding box, grown by a+/// pixel, as the Lasso has always rasterised it).+fn polygon_area(points: &[(f32, f32)], clip: Rect) -> Rect {+ let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);+ for p in points {+ (x0, y0, x1, y1) = (x0.min(p.0), y0.min(p.1), x1.max(p.0), y1.max(p.1));+ }+ if points.len() < 3 || !(x0 <= x1 && y0 <= y1) {+ return Rect::EMPTY;+ }+ let clamp = |v: f32| v.clamp(-1e7, 1e7) as i32;+ Rect::new(clamp(x0.floor()) - 1, clamp(y0.floor()) - 1, clamp(x1.ceil()) + 1, clamp(y1.ceil()) + 1).intersect(&clip)+}++/// The tiles of `clip` the edges of the polygon through `points` cross (with a pixel's margin),+/// in order: the only ones whose pixels can differ. `None` when there are more than `limit`.+pub fn polygon_edge_tiles(points: &[(f32, f32)], clip: Rect, limit: usize) -> Option<BTreeSet<TileCoord>> {+ let area = polygon_area(points, clip);+ let mut set = BTreeSet::new();+ if area.is_empty() {+ return Some(set);+ }+ let step = TILE_SIZE as f32 / 4.0;+ for (&a, &b) in points.iter().zip(points.iter().cycle().skip(1)) {+ let Some((a, b)) = clip_segment(a, b, area.inflate(2)) else { continue };+ let pieces = ((b.0 - a.0).hypot(b.1 - a.1) / step).ceil().clamp(1.0, 1e6) as usize;+ let at = |k: usize| {+ let t = k as f32 / pieces as f32;+ (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)+ };+ for k in 0..pieces {+ let (p, q) = (at(k), at(k + 1));+ let lo = |u: f32, v: f32| u.min(v).floor() as i32 - 1;+ let hi = |u: f32, v: f32| u.max(v).floor() as i32 + 2;+ for tc in Rect::new(lo(p.0, q.0), lo(p.1, q.1), hi(p.0, q.0), hi(p.1, q.1)).intersect(&area).tiles() {+ set.insert(tc);+ if set.len() > limit {+ return None;+ }+ }+ }+ }+ Some(set)+}++/// One polygon edge, as [`super::polygon`] keeps it.+struct Edge {+ top: f32,+ bottom: f32,+ a: (f32, f32),+ b: (f32, f32),+}++/// The anti-aliased (even-odd) polygon through `points`, cut to `clip`, as a GRAY8 selection: the+/// bytes of [`super::polygon`] over `clip`, quantised. Edge tiles are rasterised, tiles wholly+/// inside share one solid tile. `None` when the edges cross more than [`MAX_PAINTED_TILES`] tiles.+pub fn polygon_surface(points: &[(f32, f32)], clip: Rect) -> Option<Surface> {+ let mut s = Surface::new(PixelFormat::GRAY8);+ let area = polygon_area(points, clip);+ if area.is_empty() {+ return Some(s);+ }+ let edge_tiles = polygon_edge_tiles(points, clip, MAX_PAINTED_TILES)?;+ const SUB: usize = 4;+ // Sample rows as `polygon` over `clip` takes them, so the bytes match.+ let sample_y = |y: i32, k: usize| clip.y0 as f32 + (y - clip.y0) as f32 + (k as f32 + 0.5) / SUB as f32;+ let mut edges: Vec<Edge> = points+ .iter()+ .zip(points.iter().cycle().skip(1))+ .filter_map(|(&a, &b)| {+ if a.1 < b.1 {+ Some(Edge { top: a.1, bottom: b.1, a, b })+ } else if b.1 < a.1 {+ Some(Edge { top: b.1, bottom: a.1, a, b })+ } else {+ None+ }+ })+ .collect();+ edges.sort_by(|p, q| p.top.total_cmp(&q.top));+ let crossings = |e: &[&Edge], y: f32, xs: &mut Vec<f32>| {+ xs.clear();+ xs.extend(e.iter().map(|&&Edge { a, b, .. }| a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)));+ xs.sort_by(|a, b| a.total_cmp(b));+ };+ let full = s.solid_tile(&[1.0]);+ let blank = s.solid_tile(&[0.0]);+ let bands: Vec<i32> = Rect::new(area.x0, area.y0, area.x0 + 1, area.y1).tiles().map(|tc| tc.ty).collect();+ let built = par_map(bands.len(), |bi| -> Vec<(TileCoord, Arc<Tile>)> {+ let Some(&ty) = bands.get(bi) else { return Vec::new() };+ let rows = Rect::new(area.x0, ty * TILE_SIZE, area.x1, (ty + 1) * TILE_SIZE).intersect(&area);+ // In `x` order (`TileCoord` orders by `tx` first).+ let cols: Vec<TileCoord> = edge_tiles.iter().filter(|tc| tc.ty == ty).copied().collect();+ let mut out = Vec::new();+ let (first, last) = (sample_y(rows.y0, 0), sample_y(rows.y1 - 1, SUB - 1));+ let reach = edges.partition_point(|e| e.top <= last);+ let band_edges = edges.get(..reach).unwrap_or_default();+ let mut xs: Vec<f32> = Vec::new();+ // Tiles no edge crosses are wholly in or out: one sample row decides them all.+ let y_mid = sample_y(rows.y0 + rows.height() as i32 / 2, 0);+ let mid: Vec<&Edge> = band_edges.iter().filter(|e| e.top <= y_mid && e.bottom > y_mid).collect();+ crossings(&mid, y_mid, &mut xs);+ for tc in rows.tiles() {+ if cols.binary_search(&tc).is_ok() {+ continue;+ }+ let tr = tc.rect().intersect(&rows);+ let cx = (tr.x0 + tr.x1) as f32 / 2.0;+ if xs.partition_point(|x| *x <= cx) % 2 == 0 {+ continue;+ }+ if tr == tc.rect() {+ out.push((tc, Arc::clone(&full)));+ } else {+ let mut tile = Tile::clone(&blank);+ fill(&mut tile, tc, tr, u8::MAX);+ out.push((tc, Arc::new(tile)));+ }+ }+ if cols.is_empty() {+ return out;+ }+ // The edge tiles: `polygon`'s scanline, accumulated only over their columns.+ let x_of = |tc: &TileCoord| tc.rect().intersect(&rows);+ let spans: Vec<Rect> = cols.iter().map(x_of).collect();+ let mut acc = vec![0.0f32; cols.len() * TS];+ let mut tiles: Vec<Tile> = cols.iter().map(|_| Tile::clone(&blank)).collect();+ let mut pending = band_edges.iter().filter(|e| e.bottom > first).peekable();+ let mut active: Vec<&Edge> = Vec::new();+ let origin = clip.x0 as f32;+ for y in rows.y0..rows.y1 {+ acc.fill(0.0);+ for k in 0..SUB {+ let sy = sample_y(y, k);+ while let Some(e) = pending.next_if(|e| e.top <= sy) {+ active.push(e);+ }+ active.retain(|e| e.bottom > sy);+ if active.is_empty() {+ continue;+ }+ crossings(&active, sy, &mut xs);+ for pair in xs.as_chunks::<2>().0 {+ let (x0, x1) = ((pair[0] - origin).max(0.0), (pair[1] - origin).min(clip.width() as f32));+ if x1 <= x0 {+ continue;+ }+ let (c0, c1) = (clip.x0 + x0.floor() as i32, clip.x0 + x1.ceil() as i32);+ let start = spans.partition_point(|r| r.x1 <= c0);+ for (ci, r) in spans.iter().enumerate().skip(start).take_while(|(_, r)| r.x0 < c1) {+ for x in c0.max(r.x0)..c1.min(r.x1) {+ let cx = (x - clip.x0) as f32;+ let cov = (cx + 1.0).min(x1) - cx.max(x0);+ if let Some(v) = acc.get_mut(ci * TS + (x - r.x0) as usize) {+ *v += cov.max(0.0) / SUB as f32;+ }+ }+ }+ }+ }+ for ((r, tile), row) in spans.iter().zip(&mut tiles).zip(acc.as_chunks::<TS>().0) {+ let base = y.rem_euclid(TILE_SIZE) as usize * TS + r.x0.rem_euclid(TILE_SIZE) as usize;+ let Some(dst) = tile.bytes_mut().get_mut(base..base + r.width() as usize) else { continue };+ for (d, v) in dst.iter_mut().zip(row) {+ *d = (v.min(1.0).clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ }+ }+ for (tc, tile) in cols.into_iter().zip(tiles) {+ let (lo, hi) = tile.bytes().iter().fold((u8::MAX, 0u8), |(lo, hi), v| (lo.min(*v), hi.max(*v)));+ if hi > 0 {+ out.push((tc, if lo == u8::MAX { Arc::clone(&full) } else { Arc::new(tile) }));+ }+ }+ out+ });+ s.put_tiles(built.into_iter().flatten());+ Some(s)+}++/// Sets `tr` (within tile `tc`) to `v`.+fn fill(tile: &mut Tile, tc: TileCoord, tr: Rect, v: u8) {+ let o = tc.rect();+ for y in tr.y0..tr.y1 {+ let base = (y - o.y0) as usize * TS;+ if let Some(row) = tile.bytes_mut().get_mut(base + (tr.x0 - o.x0) as usize..base + (tr.x1 - o.x0) as usize) {+ row.fill(v);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The dense rasteriser over `clip`, quantised as the Lasso stores it.+ fn dense(points: &[(f32, f32)], clip: Rect) -> Surface {+ let m: Vec<u8> = super::super::polygon(points, clip, true).iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8).collect();+ let mut s = Surface::from_interleaved(PixelFormat::GRAY8, clip, &m);+ s.prune();+ s+ }++ #[test]+ fn matches_the_dense_polygon() {+ let clip = Rect::new(-40, 10, 1300, 900);+ let shapes: [&[(f32, f32)]; 6] = [+ &[(10.5, 20.25), (1200.0, 40.0), (600.0, 880.7)],+ // Whole tiles inside, edges exactly on tile boundaries.+ &[(0.0, 256.0), (768.0, 256.0), (768.0, 768.0), (0.0, 768.0)],+ // Self-intersecting (even-odd), past the clip.+ &[(-300.0, -50.0), (1500.0, 950.0), (1500.0, -50.0), (-300.0, 950.0)],+ &[(100.0, 100.0), (101.0, 100.0), (100.5, 700.0)],+ &[(5.0, 15.0), (5.0, 15.0), (5.0, 15.0)],+ &[(2000.0, 2000.0), (2100.0, 2000.0), (2000.0, 2100.0)],+ ];+ for pts in shapes {+ let s = polygon_surface(pts, clip).expect("within the tile limit");+ let d = dense(pts, clip);+ let area = clip.union(&s.tile_bounds());+ assert!(s.read_region(area) == d.read_region(area), "{pts:?}");+ }+ }++ /// A thin sliver across a 100,000 px canvas: only the tiles along it are built (the dense+ /// rasteriser allocated its 10-billion-pixel bounding box; the #8783 review).+ #[test]+ fn a_thin_sliver_across_a_huge_canvas_costs_its_edge_tiles() {+ let clip = Rect::new(0, 0, 100_000, 100_000);+ let sliver = [(0.0, 0.0), (99_999.0, 99_999.0), (0.0, 1.5)];+ let tiles = polygon_edge_tiles(&sliver, clip, MAX_PAINTED_TILES).expect("within the limit");+ assert!(tiles.len() < 2000, "{}", tiles.len());+ let s = polygon_surface(&sliver, clip).expect("within the limit");+ assert!(s.tile_count() <= tiles.len());+ assert!(s.pixel(50_000, 50_000)[0] > 0.0 && s.pixel(50_000, 40_000)[0] == 0.0);+ // A zigzag that crosses more tiles than the limit is refused.+ let zigzag: Vec<(f32, f32)> = (0..200).map(|i| (if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 500.0)).collect();+ assert!(polygon_edge_tiles(&zigzag, clip, MAX_PAINTED_TILES).is_none());+ assert!(polygon_surface(&zigzag, clip).is_none());+ }++ #[test]+ fn a_huge_polygon_shares_one_tile_inside() {+ let clip = Rect::new(0, 0, 51_200, 51_200);+ let s = polygon_surface(&[(-10.0, -10.0), (60_000.0, -10.0), (60_000.0, 60_000.0), (-10.0, 60_000.0)], clip).expect("no edge tiles");+ let shared = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect::<BTreeSet<_>>();+ assert!(s.tile_count() == 200 * 200 && shared.len() == 1, "{} tiles, {} distinct", s.tile_count(), shared.len());+ }+}diff --git a/crates/algo/src/selection/marquee.rs b/crates/algo/src/selection/marquee.rsindex 7dd861164..c4830ae13 100644--- a/crates/algo/src/selection/marquee.rs+++ b/crates/algo/src/selection/marquee.rs@@ -236,6 +236,60 @@ pub fn combine_surfaces(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f3out}+/// [`combine_surfaces`] for an `f` that keeps `a` wherever `b` reads 0 (Add, Subtract), visiting+/// only `b`'s tiles within `area`: the rest of `a` (its other tiles and its untouched value) is+/// kept as it is, so painting a thin stroke across a huge canvas costs the tiles it paints, not+/// the canvas (#8783). Falls back to [`combine_surfaces`] over `area` for other inputs.+pub fn combine_sparse(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f32) -> f32) -> Surface {+ let gray = PixelFormat::GRAY8;+ let lut: Vec<u8> = (0..=u16::MAX).map(|i| encode8(f(decode8((i >> 8) as u8), decode8(i as u8)))).collect();+ let pair = |x: u8, y: u8| lut.get(usize::from(x) << 8 | usize::from(y)).copied().unwrap_or(0);+ if a.format() != gray || b.format() != gray || b.default_bytes() != [0] || !(0..=255u8).all(|v| pair(v, 0) == v) {+ return combine_surfaces(a, b, area, f);+ }+ let da = a.default_bytes().first().copied().unwrap_or(0);+ let mut out = a.clone();+ let (full, untouched) = (out.solid_tile(&[1.0]), out.solid_tile(&[decode8(da)]));+ let coords: Vec<TileCoord> = b.tiles().map(|(c, _)| *c).filter(|c| !c.rect().intersect(&area).is_empty()).collect();+ // Each tile: `Some(tile)` to store, `None` when it reads as `a`'s untouched value.+ let built = par_map(coords.len(), |k| {+ let tc = *coords.get(k)?;+ let rect = tc.rect();+ let tr = rect.intersect(&area);+ let tb = b.tile(tc)?;+ let mut tile = Tile::clone(a.tile(tc).unwrap_or(&untouched));+ let data = tile.bytes_mut();+ let (x0, x1) = ((tr.x0 - rect.x0) as usize, (tr.x1 - rect.x0) as usize);+ for ly in (tr.y0 - rect.y0) as usize..(tr.y1 - rect.y0) as usize {+ let (s, e) = (ly * TS + x0, ly * TS + x1);+ let (Some(dst), Some(src)) = (data.get_mut(s..e), tb.bytes().get(s..e)) else { continue };+ for (d, y) in dst.iter_mut().zip(src) {+ *d = pair(*d, *y);+ }+ }+ let (lo, hi) = tile.bytes().iter().fold((u8::MAX, 0u8), |(lo, hi), v| (lo.min(*v), hi.max(*v)));+ Some((+ tc,+ if lo == da && hi == da {+ None+ } else if lo == u8::MAX {+ Some(Arc::clone(&full))+ } else {+ Some(Arc::new(tile))+ },+ ))+ });+ for (tc, tile) in built.into_iter().flatten() {+ match tile {+ Some(t) => out.put_tiles([(tc, t)]),+ // `take_tiles` only allocates for a tile that is missing; this one is there.+ None if out.tile(tc).is_some() => drop(out.take_tiles(tc.rect())),+ None => {}+ }+ }+ out+}+#[cfg(test)]mod tests {use super::*;@@ -311,4 +365,30 @@ mod tests {}}}++ /// Add and Subtract through only the new shape's tiles give the bytes of the whole-area+ /// combination, keep the old selection's other tiles shared, and keep an untouched value+ /// (a layer mask's reveal-all) outside them.+ #[test]+ fn sparse_combination_matches_the_whole_area_one() {+ let area = Rect::new(0, 0, 1100, 700);+ let mut rect = Surface::new(PixelFormat::GRAY8);+ rect.fill_rect(Rect::from_xywh(200, 100, 600, 520), &[1.0]);+ let ell = old_ellipse(Rect::from_xywh(-60, 250, 700, 500), area, true);+ let far = ellipse_surface(Rect::from_xywh(900, 20, 150, 150), area, true);+ let ops: [fn(f32, f32) -> f32; 2] = [|a, b| a.max(b), |a, b| (a - b).max(0.0)];+ for (a, b) in [(&rect, &ell), (&ell, &rect), (&ell, &ell), (&rect, &far)] {+ for f in ops {+ let sparse = combine_sparse(a, b, area, f);+ assert!(sparse.read_region(area) == old_combine(a, b, area, f).read_region(area));+ assert!(sparse.tiles().all(|(_, t)| t.bytes().iter().any(|v| *v != 0)), "no empty tiles kept");+ }+ }+ let kept = combine_sparse(&rect, &far, area, |a, b| a.max(b));+ let tc = TileCoord::new(1, 1);+ assert!(Arc::ptr_eq(kept.tile(tc).expect("kept"), rect.tile(tc).expect("there")), "untouched tiles stay shared");+ let reveal = Surface::with_default(PixelFormat::GRAY8, &[1.0]);+ let cut = combine_sparse(&reveal, &far, area, |a, b| (a - b).max(0.0));+ assert!(cut.pixel(5000, 5000)[0] == 1.0 && cut.pixel(975, 95)[0] == 0.0);+ }}diff --git a/crates/engine/src/select_mask_edits.rs b/crates/engine/src/select_mask_edits.rsindex 6506ac72e..9fd29a275 100644--- a/crates/engine/src/select_mask_edits.rs+++ b/crates/engine/src/select_mask_edits.rs@@ -8,6 +8,8 @@//! them, OK is one history step, and the UI, CLI, MCP and the control channel all drive them the//! same way. [`apply`] is pure, so the workspace's preview runs exactly what OK commits.+use std::collections::BTreeSet;+use photocraft_algo::matting;use photocraft_algo::segment::{grabcut, quick, subject};use photocraft_algo::selection::{self as sel, Region, SelectionMode, combine_region};@@ -183,22 +185,41 @@ fn mode(add: bool) -> SelectionMode {if add { SelectionMode::Add } else { SelectionMode::Subtract }}-/// The polygon through `points` (anti-aliased), over the rows and columns it spans in `canvas`.-fn polygon_region(points: &[(f32, f32)], canvas: Rect) -> Option<Region> {- let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);- for p in points {- (x0, y0, x1, y1) = (x0.min(p.0), y0.min(p.1), x1.max(p.0), y1.max(p.1));- }- if x0 > x1 || y0 > y1 {- return None;+/// Most tiles the Brush and Lasso edits may paint in all: four times what one may+/// ([`sel::MAX_PAINTED_TILES`]), 1 GiB of GRAY8 tiles. Each is rasterised a tile at a time, so+/// this, not the canvas size, bounds what they allocate (the #8783 review).+pub const MAX_EDIT_TILES: usize = 4 * sel::MAX_PAINTED_TILES;++/// Refuses Brush and Lasso edits that would paint too many tiles of `canvas`, one by one or in+/// all, before anything is painted.+pub fn check_size(edits: &[SelectionEdit], canvas: Rect) -> Result<()> {+ let mut all = BTreeSet::new();+ for e in edits {+ let tiles = match e {+ SelectionEdit::Brush { points, size, .. } => matting::painted_tiles(points, *size, canvas, sel::MAX_PAINTED_TILES),+ SelectionEdit::Lasso { points, .. } => sel::polygon_edge_tiles(points, canvas, sel::MAX_PAINTED_TILES),+ _ => continue,+ };+ all.extend(tiles.ok_or_else(|| bad("a brush or lasso edit crosses too many tiles of the canvas"))?);+ if all.len() > MAX_EDIT_TILES {+ return Err(bad("brush and lasso edits cross too many tiles of the canvas"));+ }}- let clamp = |v: f32| v.clamp(-1e7, 1e7) as i32;- let bbox = Rect::new(clamp(x0.floor()) - 1, clamp(y0.floor()) - 1, clamp(x1.ceil()) + 1, clamp(y1.ceil()) + 1).intersect(&canvas);- if bbox.is_empty() {- return None;+ Ok(())+}++/// Refuses Refine Edge Brush strokes that would paint more tiles of `canvas` than+/// [`matting::EdgeBrush`] holds.+pub fn check_strokes(strokes: &[matting::EdgeStroke], canvas: Rect) -> Result<()> {+ let refused = || EngineError::BadParams { cmd: CMD.into(), msg: "refineStrokes cross too many tiles of the canvas".into() };+ let mut all = BTreeSet::new();+ for s in strokes {+ all.extend(matting::painted_tiles(&s.points, s.size, canvas, sel::MAX_PAINTED_TILES).ok_or_else(refused)?);+ if all.len() > sel::MAX_PAINTED_TILES {+ return Err(refused());+ }}- let mask: Vec<u8> = sel::polygon(points, bbox, true).iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8).collect();- mask.iter().any(|v| *v > 0).then_some(Region { bbox, mask })+ Ok(())}/// `base` inverted over `canvas`; `None` when that leaves nothing selected. Tile by tile: the@@ -235,13 +256,22 @@ pub fn apply_one(doc: &Document, layer: Option<LayerId>, base: Option<Surface>,Some(r) => combine_region(base.as_ref(), Some(&r), m),None => base.clone(),};+ // A painted shape (tile-sparse) added or subtracted, a tile at a time.+ let paint = |shape: Option<Surface>, add: bool| match (shape.filter(|s| s.tile_count() > 0), base.as_ref()) {+ (None, _) => base.clone(),+ (Some(s), None) => add.then_some(s),+ (Some(s), Some(o)) => {+ let out = if add { sel::combine_sparse(o, &s, canvas, f32::max) } else { sel::combine_sparse(o, &s, canvas, |a, b| (a - b).max(0.0)) };+ (!out.content_bounds().is_empty()).then_some(out)+ }+ };match edit {SelectionEdit::Quick { points, size, add, sample_all_layers } => {let region = with_doc_sampler(doc, layer, *sample_all_layers, |smp, doc| quick::quick_select(smp, doc.bounds(), points, *size));combine(region, mode(*add))}- SelectionEdit::Brush { points, size, hardness, add } => combine(matting::brush_region(points, *size, *hardness, canvas), mode(*add)),- SelectionEdit::Lasso { points, add } => combine(polygon_region(points, canvas), mode(*add)),+ SelectionEdit::Brush { points, size, hardness, add } => paint(matting::brush_surface(points, *size, *hardness, canvas), *add),+ SelectionEdit::Lasso { points, add } => paint(sel::polygon_surface(points, canvas), *add),SelectionEdit::Object { area, add, sample_all_layers } => {let region = with_doc_sampler(doc, layer, *sample_all_layers, |smp, doc| match *area {ObjectArea::Rect(r) => grabcut::object_select(smp, doc.bounds(), r, 160_000),@@ -394,4 +424,40 @@ mod tests {assert!(all.sample_channel(15, 15, 0) > 0.99 && all.sample_channel(70_000, 3, 0) > 0.99);assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());}++ /// The #8783 review: a size-1 Brush edit from corner to corner of a 100,000 px canvas sweeps+ /// about 141,000 px but its bounding box is 10 billion; it, a Lasso sliver along it and their+ /// subtraction paint only the tiles they cross, and keep the selection there was.+ #[test]+ fn thin_edits_across_a_huge_canvas_paint_only_their_tiles() {+ let doc = Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8);+ let canvas = doc.bounds();+ let mut small = Surface::new(photocraft_color::PixelFormat::GRAY8);+ small.fill_rect(Rect::new(10, 60, 20, 70), &[1.0]);+ let diagonal = vec![(0.0, 0.0), (99_999.0, 99_999.0)];+ let brush = SelectionEdit::Brush { points: diagonal.clone(), size: 1.0, hardness: 100.0, add: true };+ let lasso = SelectionEdit::Lasso { points: vec![(0.0, 0.0), (99_999.0, 99_999.0), (0.0, 1.5)], add: true };+ assert!(check_size(&[brush.clone(), lasso.clone()], canvas).is_ok());+ let t = std::time::Instant::now();+ for edit in [&brush, &lasso] {+ let s = apply(&doc, None, Some(small.clone()), std::slice::from_ref(edit)).expect("painted");+ assert!(s.tile_count() < 1500, "{}", s.tile_count());+ assert!(s.sample_channel(15, 65, 0) > 0.99 && s.sample_channel(50_000, 50_000, 0) > 0.0 && s.sample_channel(50_000, 40_000, 0) == 0.0);+ }+ let erased =+ apply(&doc, None, Some(small.clone()), &[brush, SelectionEdit::Brush { points: diagonal, size: 9.0, hardness: 100.0, add: false }]).expect("kept");+ assert!(erased.sample_channel(15, 65, 0) > 0.99 && erased.sample_channel(50_000, 50_000, 0) == 0.0);+ assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());+ // A zigzag across more tiles than one edit may paint is refused before painting.+ let zigzag: Vec<(f32, f32)> = (0..20).map(|i| (if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0)).collect();+ let over = [SelectionEdit::Brush { points: zigzag.clone(), size: 1.0, hardness: 100.0, add: true }];+ assert!(check_size(&over, canvas).is_err());+ assert!(check_size(&[SelectionEdit::Lasso { points: zigzag, add: true }], canvas).is_err());+ // So are many edits that each fit but cross too many tiles in all.+ let rows: Vec<SelectionEdit> = (0..48)+ .map(|i| SelectionEdit::Brush { points: vec![(0.0, i as f32 * 2000.0), (99_999.0, i as f32 * 2000.0)], size: 1.0, hardness: 100.0, add: true })+ .collect();+ assert!(rows.iter().all(|e| check_size(std::slice::from_ref(e), canvas).is_ok()));+ assert!(check_size(&rows, canvas).is_err());+ }}diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rsindex cad2feac2..8d6366360 100644--- a/crates/engine/src/smartselect_cmds.rs+++ b/crates/engine/src/smartselect_cmds.rs@@ -422,6 +422,9 @@ fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {output = "newLayerWithMask".into();}let edits = select_mask_edits::parse(p)?;+ // Before anything is painted: a thin stroke across a huge canvas paints few pixels but many tiles.+ select_mask_edits::check_size(&edits, d.doc.bounds())?;+ select_mask_edits::check_strokes(&strokes, d.doc.bounds())?;let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| {let mask_surf = active.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref()).map(|m| &m.surface);let target_mask = p.get("target").and_then(Value::as_str) == Some("mask");@@ -1076,6 +1079,30 @@ mod tests {(0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect()}+ /// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint+ /// too many tiles of a huge canvas are refused before anything is painted, and the selection+ /// stays as it was.+ #[test]+ fn refine_edge_refuses_edits_that_cross_too_many_tiles() {+ let mut s = Session::new();+ s.add_document(+ Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8),+ None,+ );+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();+ let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected");+ let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect();+ for p in [+ json!({"edits": [{"tool": "brush", "points": zigzag, "size": 1}]}),+ json!({"edits": [{"tool": "lasso", "points": zigzag}]}),+ json!({"refineStrokes": [{"points": zigzag, "size": 1}]}),+ ] {+ let e = s.execute("select.refineEdge", p.clone()).expect_err("refused");+ assert!(e.to_string().contains("too many tiles"), "{p}: {e}");+ assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&before), "{p}: the selection is unchanged");+ }+ }+/// Select and Mask's own tools (#7069, #8148): each edit changes the selection before the/// edge is refined, at every depth, and the whole run is one history step.#[test]