diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index c31a883a197..8493f2c1e84 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -941,49 +941,79 @@ pub struct ColorMatcher { } #[derive(Clone, Debug)] -enum ColorBvh { - Empty, - Leaf(Vec<[f32; 4]>), - Node { min: [f32; 4], max: [f32; 4], left: Box, right: Box }, +struct ColorBvh { + points: Vec<[f32; 4]>, + nodes: Vec, +} + +#[derive(Clone, Debug)] +enum ColorNode { + Leaf { start: usize, end: usize }, + Branch { min: [f32; 4], max: [f32; 4], left: usize, right: usize }, } impl ColorBvh { - fn build(mut points: Vec<[f32; 4]>) -> Self { - if points.is_empty() { - return ColorBvh::Empty; + fn build(mut points: Vec<[f32; 4]>) -> Result { + let capacity = Self::node_count(points.len()); + let mut nodes = Self::reserve_nodes(capacity)?; + if !points.is_empty() { + Self::build_nodes(&mut points, 0, &mut nodes); } + Ok(Self { points, nodes }) + } + + fn node_count(len: usize) -> usize { + if len == 0 { + 0 + } else if len <= 16 { + 1 + } else { + 1 + Self::node_count(len / 2) + Self::node_count(len - len / 2) + } + } + + fn reserve_nodes(capacity: usize) -> Result, &'static str> { + let mut nodes = Vec::new(); + nodes.try_reserve_exact(capacity).map_err(|_| "not enough memory to index selection colours")?; + Ok(nodes) + } + + // Reserve the exact node count before recursion so pushes cannot allocate. + fn build_nodes(points: &mut [[f32; 4]], start: usize, nodes: &mut Vec) -> usize { if points.len() <= 16 { - return ColorBvh::Leaf(points); + let index = nodes.len(); + nodes.push(ColorNode::Leaf { start, end: start + points.len() }); + return index; } let (mut min, mut max) = ([f32::MAX; 4], [f32::MIN; 4]); - for p in &points { + for p in points.iter() { for c in 0..4 { min[c] = min[c].min(p[c]); max[c] = max[c].max(p[c]); } } - let mut best_axis = 0; - let mut max_spread = -1.0; - for c in 0..4 { - let spread = max[c] - min[c]; - if spread > max_spread { - max_spread = spread; - best_axis = c; + let mut axis = 0; + for c in 1..4 { + if max[c] - min[c] > max[axis] - min[axis] { + axis = c; } } let mid = points.len() / 2; - points.select_nth_unstable_by(mid, |a, b| a[best_axis].total_cmp(&b[best_axis])); - let right_pts = points.split_off(mid); - let left = ColorBvh::build(points); - let right = ColorBvh::build(right_pts); - ColorBvh::Node { min, max, left: Box::new(left), right: Box::new(right) } + points.select_nth_unstable_by(mid, |a, b| a[axis].total_cmp(&b[axis])); + let (left_points, right_points) = points.split_at_mut(mid); + let left = Self::build_nodes(left_points, start, nodes); + let right = Self::build_nodes(right_points, start + mid, nodes); + let index = nodes.len(); + nodes.push(ColorNode::Branch { min, max, left, right }); + index } - fn matches(&self, q: &[f32; 4], tol: f32) -> bool { - match self { - ColorBvh::Empty => false, - ColorBvh::Leaf(pts) => pts.iter().any(|p| (0..4).all(|c| (q[c] - p[c]).abs() <= tol + 1e-6)), - ColorBvh::Node { min, max, left, right } => { + fn matches_node(&self, index: usize, q: &[f32; 4], tol: f32) -> bool { + match self.nodes.get(index) { + Some(ColorNode::Leaf { start, end }) => { + self.points.get(*start..*end).is_some_and(|pts| pts.iter().any(|p| (0..4).all(|c| (q[c] - p[c]).abs() <= tol + 1e-6))) + } + Some(ColorNode::Branch { min, max, left, right }) => { for c in 0..4 { let d = if q[c] < min[c] { min[c] - q[c] @@ -996,15 +1026,39 @@ impl ColorBvh { return false; } } - left.matches(q, tol) || right.matches(q, tol) + self.matches_node(*left, q, tol) || self.matches_node(*right, q, tol) } + None => false, } } + + fn matches(&self, q: &[f32; 4], tol: f32) -> bool { + self.nodes.len().checked_sub(1).is_some_and(|root| self.matches_node(root, q, tol)) + } } +/// Bytes of memory the index is charged per distinct colour: the dedupe set entry and its +/// table slack, the colour in the point list, and its share of the tree nodes. It is an +/// approximate average, not a worst case: while the set rehashes or the point list doubles, +/// the peak runs to roughly 70–90 bytes per colour. +const COLOR_INDEX_BYTES: usize = 64; + +/// The most memory the index may be charged. It scales with the distinct colours rather than the +/// canvas, so a noisy 24 MP photo, or a float document where every pixel is its own colour, +/// still builds; it only keeps the index within the sampled pixels' own budget. On 32-bit +/// (the web build) 1 GiB still admits every distinct colour of a 24 MP photo. +const COLOR_INDEX_BUDGET: usize = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; + impl ColorMatcher { /// Creates a color matcher from selected RGBA colors and an $L_\\infty$ tolerance in $[0, 1]$. - pub fn new(selected_colors: impl IntoIterator, tol: f32) -> Self { + pub fn new(selected_colors: impl IntoIterator, tol: f32) -> Result { + Self::with_budget(selected_colors, tol, COLOR_INDEX_BUDGET) + } + + // Bound the index by `budget` bytes, charged at `COLOR_INDEX_BYTES` per distinct colour, and + // fail without altering the selection. + fn with_budget(selected_colors: impl IntoIterator, tol: f32, budget: usize) -> Result { + let limit = budget / COLOR_INDEX_BYTES; let mut has_transparent = false; let mut seen = std::collections::HashSet::new(); let mut opaque_or_semi = Vec::new(); @@ -1014,22 +1068,31 @@ impl ColorMatcher { has_transparent |= c[3] == 0.0; let norm = |x: f32| if x == 0.0 { 0.0f32.to_bits() } else { x.to_bits() }; let key = [norm(c[0]), norm(c[1]), norm(c[2]), norm(c[3])]; - if seen.insert(key) { + if !seen.contains(&key) { + if seen.len() >= limit { + return Err("the selection contains too many distinct colours to match; select a smaller area"); + } + seen.try_reserve(1).map_err(|_| "not enough memory to index selection colours")?; + opaque_or_semi.try_reserve(1).map_err(|_| "not enough memory to index selection colours")?; + seen.insert(key); opaque_or_semi.push(c); } } + drop(seen); opaque_or_semi.sort_unstable_by(|a, b| { a[0].total_cmp(&b[0]).then_with(|| a[1].total_cmp(&b[1])).then_with(|| a[2].total_cmp(&b[2])).then_with(|| a[3].total_cmp(&b[3])) }); opaque_or_semi.dedup_by(|a, b| a == b); + // The tree keeps this list; give back the slack its doubling left. + opaque_or_semi.shrink_to_fit(); - Self { has_transparent, tree: ColorBvh::build(opaque_or_semi), tol: tol.max(0.0) } + Ok(Self { has_transparent, tree: ColorBvh::build(opaque_or_semi)?, tol: tol.max(0.0) }) } /// Returns `true` if no colors (including transparent pixels) were provided. #[inline] pub fn is_empty(&self) -> bool { - !self.has_transparent && matches!(self.tree, ColorBvh::Empty) + !self.has_transparent && self.tree.nodes.is_empty() } /// Returns `true` if `q` falls within `tol` of any selected color. diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 6976776af14..4e7bdcbe069 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -2,7 +2,7 @@ fn color_matcher_bvh_and_transparency() { let red = [1.0, 0.0, 0.0, 1.0]; let blue = [0.0, 0.0, 1.0, 1.0]; - let matcher = ColorMatcher::new([red, blue], 10.0 / 255.0); + let matcher = ColorMatcher::new([red, blue], 10.0 / 255.0).unwrap(); assert!(!matcher.is_empty()); assert!(matcher.matches([0.98, 0.02, 0.0, 1.0])); @@ -14,13 +14,13 @@ fn color_matcher_bvh_and_transparency() { assert!(!matcher.matches([0.5, 0.0, 0.5, 1.0])); assert!(!matcher.matches([0.0, 0.0, 0.0, 0.0])); - let matcher_trans = ColorMatcher::new([red, [0.0, 0.0, 0.0, 0.0]], 10.0 / 255.0); + let matcher_trans = ColorMatcher::new([red, [0.0, 0.0, 0.0, 0.0]], 10.0 / 255.0).unwrap(); assert!(matcher_trans.matches([0.0, 0.0, 0.0, 0.0])); assert!(matcher_trans.matches([0.5, 0.2, 0.1, 0.0])); assert!(matcher_trans.matches([0.98, 0.0, 0.0, 1.0])); assert!(!matcher_trans.matches([0.0, 1.0, 0.0, 1.0])); - let empty = ColorMatcher::new([], 10.0 / 255.0); + let empty = ColorMatcher::new([], 10.0 / 255.0).unwrap(); assert!(empty.is_empty()); assert!(!empty.matches(red)); @@ -28,7 +28,7 @@ fn color_matcher_bvh_and_transparency() { let faint = [0.0, 0.0, 0.0, 1e-6]; assert!(!matcher_trans.matches([0.5, 0.2, 0.1, 1e-6])); assert!(matcher_trans.matches(faint)); - let matcher_faint = ColorMatcher::new([faint], 10.0 / 255.0); + let matcher_faint = ColorMatcher::new([faint], 10.0 / 255.0).unwrap(); assert!(matcher_faint.matches([0.0, 0.0, 0.0, 0.0])); assert!(!matcher_faint.matches([0.5, 0.0, 0.0, 0.0])); } @@ -37,7 +37,7 @@ fn color_matcher_bvh_and_transparency() { fn color_matcher_preserves_distinct_faint_32f_colors_at_zero_tolerance() { let zero = [0.0, 0.0, 0.0, 0.0]; let faint = [0.0, 0.0, 0.0, 8e-6]; - let matcher = ColorMatcher::new([zero, faint], 0.0); + let matcher = ColorMatcher::new([zero, faint], 0.0).unwrap(); assert!(matcher.matches(zero)); assert!(matcher.matches(faint)); assert!(!matcher.matches([0.0, 0.0, 0.0, 2e-5])); @@ -48,7 +48,7 @@ fn color_matcher_coalesces_exact_repeated_colors() { let red = [1.0, 0.0, 0.0, 1.0]; let transparent = [0.0, 0.0, 0.0, 0.0]; let colors = std::iter::repeat_n(red, 10_000).chain(std::iter::repeat_n(transparent, 10_000)); - let matcher = ColorMatcher::new(colors, 0.0); + let matcher = ColorMatcher::new(colors, 0.0).unwrap(); assert!(matcher.matches(red)); assert!(matcher.matches(transparent)); assert!(!matcher.matches([0.0, 1.0, 0.0, 1.0])); @@ -64,8 +64,8 @@ fn color_matcher_splits_colors_that_are_all_nearly_equal() { [c, 0.25, 0.75, 1.0] }) .collect(); - let matcher = ColorMatcher::new(selected.iter().copied(), 0.0); - assert!(matches!(matcher.tree, ColorBvh::Node { .. }), "more than 16 colours must not share one leaf"); + let matcher = ColorMatcher::new(selected.iter().copied(), 0.0).unwrap(); + assert!(matcher.tree.nodes.iter().any(|node| matches!(node, ColorNode::Branch { .. })), "more than 16 colours must not share one leaf"); for p in &selected { assert!(matcher.matches(*p)); } @@ -82,7 +82,7 @@ fn color_matcher_tree_matches_brute_force() { }) .collect(); let tol = 0.05; - let matcher = ColorMatcher::new(selected.iter().copied(), tol); + let matcher = ColorMatcher::new(selected.iter().copied(), tol).unwrap(); for i in 0..2000 { let t = i as f32 / 1999.0; let q = [(t * 3.0).fract(), (t * 5.0).fract(), (t * 11.0).fract(), if i % 7 == 0 { 0.0 } else { 1.0 }]; @@ -747,6 +747,45 @@ fn combine_region_matches_combine() { assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); } +#[test] +fn color_matcher_bounds_tightly_clustered_leaves() { + let colors: Vec<_> = (0..1000).map(|i| [i as f32 * 1e-10, 0.0, 0.0, 1.0]).collect(); + let matcher = ColorMatcher::new(colors.iter().copied(), 0.0).unwrap(); + for node in &matcher.tree.nodes { + if let ColorNode::Leaf { start, end } = node { + assert!(end - start <= 16); + } + } + assert!(matcher.matches(colors[999])); + assert!(!matcher.matches([0.1, 0.0, 0.0, 1.0])); +} + +#[test] +fn color_matcher_budget_fires_at_the_distinct_color_it_is_sized_for() { + let colors: Vec<_> = (0..5).map(|i| [i as f32 / 8.0, 0.0, 0.0, 1.0]).collect(); + // Room for exactly `n` distinct colours: the n-th still fits, the (n + 1)-th does not. + for n in 1..=5 { + let budget = n * COLOR_INDEX_BYTES; + assert!(ColorMatcher::with_budget(colors[..n].iter().copied(), 0.0, budget).is_ok(), "{n} colours in {budget} bytes"); + if n < 5 { + assert!(ColorMatcher::with_budget(colors[..=n].iter().copied(), 0.0, budget).is_err(), "{} colours in {budget} bytes", n + 1); + } + } + // A budget short of one colour's charge admits none, and duplicates are never charged. + assert!(ColorMatcher::with_budget([colors[0]], 0.0, COLOR_INDEX_BYTES - 1).is_err()); + let repeated = std::iter::repeat_n(colors[0], 1000); + assert!(ColorMatcher::with_budget(repeated, 0.0, COLOR_INDEX_BYTES).is_ok()); +} + +#[test] +fn color_matcher_default_budget_admits_a_noisy_float_canvas() { + // Every pixel of a 2000x1000 float canvas is its own colour: past the old 1M-colour cap. + let colors = (0..2_000_000u32).map(|i| [i as f32 * 1e-7, (i % 1013) as f32 * 1e-3, 0.5, 1.0]); + let matcher = ColorMatcher::new(colors, 0.0).unwrap(); + assert!(matcher.matches([1_999_999.0 * 1e-7, (1_999_999 % 1013) as f32 * 1e-3, 0.5, 1.0])); + assert!(!matcher.matches([0.9, 0.9, 0.9, 1.0])); +} + #[test] fn polygon_window_keeps_full_canvas_fractional_coverage() { for canvas in [Rect::new(0, 0, 110_000, 12), Rect::new(-123, -7, 109_877, 5)] { @@ -779,3 +818,12 @@ fn feather_leaves_everything_beyond_its_reach_at_zero() { assert!(out[reach + 1..].iter().all(|v| *v == 0.0), "radius {radius}: nonzero past reach {reach}"); } } + +#[test] +fn color_matcher_tree_reservation_failure_is_reported() { + assert!(ColorBvh::reserve_nodes(usize::MAX).is_err()); + for n in 0..1024 { + let tree = ColorBvh::build(vec![[0.0; 4]; n]).unwrap(); + assert_eq!(tree.nodes.len(), ColorBvh::node_count(n)); + } +} diff --git a/crates/engine/src/allocation.rs b/crates/engine/src/allocation.rs index 5d58cfae88d..bf5dc177f63 100644 --- a/crates/engine/src/allocation.rs +++ b/crates/engine/src/allocation.rs @@ -27,6 +27,18 @@ pub(crate) fn capacity(len: usize, purpose: &str) -> Result> { Ok(out) } +/// `Vec::push` that reports an allocation failure instead of aborting; each call is one +/// attempt for the test failpoints. +pub(crate) fn try_push(out: &mut Vec, value: T, purpose: &str) -> Result<()> { + #[cfg(test)] + if failpoint_hits() { + return Err(error(purpose, "not enough memory")); + } + out.try_reserve(1).map_err(|_| error(purpose, "the buffer could not grow"))?; + out.push(value); + Ok(()) +} + /// Check an operation boundary where downstream encoders/decoders allocate internally. /// The test-only failpoint lets command tests prove their transaction boundary. pub(crate) fn checkpoint(purpose: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 83317e26455..927beba121f 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -70,7 +70,11 @@ fn sample_pixels(s: &Session, all_layers: bool, window: Option) -> Result< surf.read_rgba_into(area, &mut px); Ok((area, px)) } - _ => Ok((area, photocraft_compose::render(&d.doc, area).into_px())), + _ => { + // The composite allocates inside compose; report a failure at its boundary. + crate::allocation::checkpoint("sampling pixels for a selection")?; + Ok((area, photocraft_compose::render(&d.doc, area).into_px())) + } } } @@ -540,21 +544,31 @@ fn crop_mask(m: &[f32], pw: usize, pad: usize, w: usize, h: usize) -> Vec { out } +/// Pushes a pixel onto the grow frontier, reporting an allocation failure instead of aborting. +fn try_push(stack: &mut Vec, i: usize) -> Result<()> { + crate::allocation::try_push(stack, i, "growing a selection") +} + /// Grow (contiguous) / Similar (anywhere): pixels whose colour lies within /// tolerance of any selected pixel (indexed via ColorMatcher BVH). fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result { let tol = f(p, "tolerance", 32.0) / 255.0; let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", false), None)?; let (_, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc); - let matcher = sel::ColorMatcher::new(px.iter().zip(&m).filter_map(|(q, v)| (*v >= 0.5).then_some(*q)), tol); + let matcher = + sel::ColorMatcher::new(px.iter().zip(&m).filter_map(|(q, v)| (*v >= 0.5).then_some(*q)), tol).map_err(|message| EngineError::Other(message.into()))?; if matcher.is_empty() { return Err(EngineError::Other("selection is empty".into())); } let (w, h) = (area.width() as usize, area.height() as usize); - let mut out: Vec = m.iter().map(|v| if *v >= 0.5 { 1.0 } else { 0.0 }).collect(); + let mut out = crate::allocation::filled(m.len(), 0.0f32, "growing a selection")?; + for (o, v) in out.iter_mut().zip(&m) { + *o = if *v >= 0.5 { 1.0 } else { 0.0 }; + } if contiguous { - // Frontier stack: only push selected pixels adjacent to at least one unselected pixel - let mut stack = Vec::new(); + // Frontier stack: only push selected pixels adjacent to at least one unselected pixel. + // Every push goes through `try_push` so a canvas-sized stack fails instead of aborting. + let mut stack: Vec = Vec::new(); for y in 0..h { for x in 0..w { let i = y * w + x; @@ -564,7 +578,7 @@ fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result { let has_unselected_neighbor = (x > 0 && out[i - 1] == 0.0) || (x + 1 < w && out[i + 1] == 0.0) || (y > 0 && out[i - w] == 0.0) || (y + 1 < h && out[i + w] == 0.0); if has_unselected_neighbor { - stack.push(i); + try_push(&mut stack, i)?; } } } @@ -574,7 +588,7 @@ fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result { for j in n.into_iter().flatten() { if out[j] == 0.0 && matcher.matches(px[j]) { out[j] = 1.0; - stack.push(j); + try_push(&mut stack, j)?; } } } diff --git a/crates/engine/src/cmd/selection_cmds/tests.rs b/crates/engine/src/cmd/selection_cmds/tests.rs index e0e93bcd57e..b4e3e2999d4 100644 --- a/crates/engine/src/cmd/selection_cmds/tests.rs +++ b/crates/engine/src/cmd/selection_cmds/tests.rs @@ -79,6 +79,20 @@ fn selection_sampling_allocation_failure_keeps_the_selection() { assert_eq!(s.active().unwrap().history.entries(), history); } +#[test] +fn selection_sampling_all_layers_reports_a_failed_composite_and_keeps_the_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 4, "height": 4})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + // Sample All Layers renders the composite: the failure is reported there, before the mask. + crate::allocation::fail_next_for_test(); + let err = s.execute("select.similar", json!({"sampleAllLayers": true})).unwrap_err().to_string(); + assert!(err.contains("not enough memory for sampling pixels for a selection"), "{err}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().history.entries(), history); +} + #[test] fn modify_rejects_oversized_canvases_before_reading_the_mask() { let mut s = Session::new(); @@ -674,6 +688,36 @@ fn grow_and_similar_multi_color_does_not_select_intermediate_hull() { assert_eq!(coverage(&s, 30, 10), 0.0, "disconnected blue rect must not be grown"); } +#[test] +fn grow_and_similar_report_a_failed_mask_allocation_and_keep_the_selection() { + for cmd in ["select.grow", "select.similar"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("select.rect", json!({"x": 6, "y": 6, "width": 4, "height": 4})).unwrap(); + // The first fallible allocation samples the layer; the second is the canvas-sized result. + crate::allocation::fail_after_for_test(1); + let err = s.execute(cmd, json!({"tolerance": 5})).unwrap_err().to_string(); + assert!(err.contains("not enough memory for growing a selection"), "{cmd}: {err}"); + assert_eq!(coverage(&s, 7, 7), 1.0, "{cmd}: the selection must be untouched"); + assert_eq!(coverage(&s, 20, 20), 0.0, "{cmd}: the selection must be untouched"); + } +} + +#[test] +fn grow_reports_a_failed_frontier_push_mid_traversal_and_keeps_the_selection() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("select.rect", json!({"x": 6, "y": 6, "width": 4, "height": 4})).unwrap(); + // Two buffer allocations (sample, result), then the 12 ring pixels of the 4x4 selection seed the + // frontier; three more clean pushes happen while flood-filling outwards before the next one fails. + crate::allocation::fail_after_for_test(2 + 12 + 3); + let err = s.execute("select.grow", json!({"tolerance": 5})).unwrap_err().to_string(); + assert!(err.contains("not enough memory for growing a selection"), "{err}"); + assert_eq!(coverage(&s, 7, 7), 1.0, "the selection must be untouched"); + assert_eq!(coverage(&s, 20, 20), 0.0, "the flood fill must not have been committed"); + assert_eq!(coverage(&s, 11, 7), 0.0, "the flood fill must not have been committed"); +} + #[test] fn lasso_polygon() { let mut s = session();