diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 51cdfd436e..f9d84bd713 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -266,6 +266,186 @@ fn rectangular_area(hole: &[bool], source: &[bool]) -> bool { hole.iter().zip(source).all(|(h, s)| *h || *s) } +/// The variant specs of `opts`: mirror, the rotation set, the scaled pair. +fn variant_specs(opts: &FillOptions) -> Vec<(f32, f32, bool)> { + let mut specs: Vec<(f32, f32, bool)> = Vec::new(); + if opts.mirror { + specs.push((0.0, 1.0, true)); + } + for ° in &opts.rotations { + specs.push((deg, 1.0, false)); + } + if opts.scale { + specs.push((0.0, 0.8, false)); + specs.push((0.0, 1.25, false)); + } + specs +} + +/// The variants of `src` for `specs`, or none when none are asked for or their mosaic would not fit +/// in the budget. The mosaic gap follows `params`, so they are built again for every attempt. +fn mosaic_variants(src: Src, specs: &[(f32, f32, bool)], params: &CompleteParams, ctl: &Interrupt) -> Result, Cancelled> { + if specs.is_empty() { + return Ok(Vec::new()); + } + let gap = 2 * params.patch_radius + 2; + let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(src.w, src.h, deg, scale)).collect(); + if mosaic_size(src.w, src.h, gap, &dims).is_none() { + return Ok(Vec::new()); + } + let mut extra = Vec::new(); + for &(deg, scale, mirror) in specs { + extra.push(variant(src, deg, scale, mirror, ctl)?); + } + Ok(extra) +} + +/// The roles of the window's pixels: the hole, what may be copied from, and the rest of the image. +fn window_roles(hole: &[bool], ok: &[bool]) -> Vec { + par::map(hole.len(), true, |s| { + if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + } + }) +} + +/// The mosaic of the window and its variants: identity at the left, the variants in a column to its +/// right, gaps that are no image. `None` when the mosaic spans more than the budget (the variants +/// then go unused, as they did before they were built). +#[allow(clippy::too_many_arguments)] +fn mosaic_pixels( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + extra: &[Variant], + params: &CompleteParams, +) -> Option<(usize, usize, Vec, Vec)> { + let gap = 2 * params.patch_radius + 2; + if extra.is_empty() { + return None; + } + let (mw, mh) = mosaic_size(w, h, gap, &extra.iter().map(|v| (v.w, v.h)).collect::>())?; + let mut mimg = vec![0.0f32; mw * mh * ch]; + let mut roles = vec![Px::Void; mw * mh]; + for y in 0..h { + for x in 0..w { + let (s, d) = (y * w + x, y * mw + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); + roles[d] = if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + }; + } + } + let mut oy = 0; + for v in extra { + for y in 0..v.h { + for x in 0..v.w { + let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); + if v.ok[s] { + roles[d] = Px::Source; + } + } + } + oy += v.h + gap; + } + Some((mw, mh, mimg, roles)) +} + +/// One completion attempt: the variant mosaic to run it on, or the plain window when no variant was +/// asked for or the mosaic would not fit the budget. +struct Attempt { + /// The mosaic's dimensions (the window's own when there is no mosaic). + mw: usize, + mh: usize, + /// The mosaic pixels; empty when the attempt runs on the window itself. + mosaic: Vec, + /// The roles of the attempt's pixels (the window's own when there is no mosaic). + roles: Vec, +} + +/// Build one attempt: variants first (their pixels are expensive, so the mosaic budget is settled +/// on their dimensions before any variant is built), then the mosaic or the plain window's roles. +/// The mosaic gap follows `params`, so an attempt is built for every patch radius. +#[allow(clippy::too_many_arguments)] +fn fill_attempt( + w: usize, + h: usize, + ch: usize, + pixels: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &CompleteParams, + ctl: &Interrupt, +) -> Result { + let src = Src { w, h, ch, img: pixels, ok }; + let extra = mosaic_variants(src, specs, params, ctl)?; + ctl.check()?; + match mosaic_pixels(w, h, ch, pixels, hole, ok, &extra, params) { + Some((mw, mh, mosaic, roles)) => Ok(Attempt { mw, mh, mosaic, roles }), + // No variant was asked for, or its mosaic would not fit the budget: complete the window. + None => Ok(Attempt { mw: w, mh: h, mosaic: Vec::new(), roles: window_roles(hole, ok) }), + } +} + +/// The window's own pixels out of a finished mosaic (its left region, the variants and the gaps +/// beside it are no answer). +fn window_from_mosaic(w: usize, h: usize, ch: usize, mw: usize, mosaic: &[f32]) -> Vec { + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + for x in 0..w { + let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); + out[d..d + ch].copy_from_slice(&mosaic[s..s + ch]); + } + } + out +} + +/// The measured fill of #14191, asked again with today's radius when the 11x11 patch leaves no +/// donor: an 11x11 window needs room inside the buffer, and a hole can also use up every window of +/// a bigger one. Without that second attempt the fill would answer with the smooth membrane where +/// today's 7x7 patch still copies pieces; #14191 measures a 600x400 document and keeps every other +/// case on today's behaviour. +#[allow(clippy::too_many_arguments)] +fn fill_retry( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &Interrupt, +) -> Result>, Cancelled> { + let measured = params.patch_radius; + for radius in [measured, CompleteParams::default().patch_radius] { + params.patch_radius = radius; + let attempt = fill_attempt(w, h, ch, img, hole, ok, specs, params, ctl)?; + if attempt.mosaic.is_empty() { + if let Some(f) = complete_masked(w, h, ch, img, &attempt.roles, params, inner)? { + return Ok(Some(f)); + } + } else if let Some(f) = complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, params, inner)? { + return Ok(Some(window_from_mosaic(w, h, ch, attempt.mw, &f))); + } + } + Ok(None) +} + #[allow(clippy::too_many_arguments)] fn fill_cow( w: usize, @@ -287,110 +467,72 @@ fn fill_cow( if structure_measured(opts) && rectangular_area(hole, source) { params.patch_radius = MEASURED_STRUCTURE_PATCH_RADIUS; } - let gap = 2 * params.patch_radius + 2; let ok: Vec = par::map(w * h, true, |i| !hole[i] && source[i]); - let src = Src { w, h, ch, img: &img, ok: &ok }; - // Variants: the identity (which holds the hole) first, then the adaptations. Their pixels are - // expensive, so the mosaic budget is settled on their dimensions before any variant is built; - // when the variants would not fit, the image itself is completed without them. - let mut specs: Vec<(f32, f32, bool)> = Vec::new(); - if opts.mirror { - specs.push((0.0, 1.0, true)); - } - for ° in &opts.rotations { - specs.push((deg, 1.0, false)); - } - if opts.scale { - specs.push((0.0, 0.8, false)); - specs.push((0.0, 1.25, false)); - } - let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(w, h, deg, scale)).collect(); - let size = if specs.is_empty() { None } else { mosaic_size(w, h, gap, &dims) }; - let mut extra: Vec = Vec::new(); - if size.is_some() { - for &(deg, scale, mirror) in &specs { - extra.push(variant(src, deg, scale, mirror, ctl)?); - } - } - let role = |s: usize| { - if hole[s] { - Px::Hole - } else if ok[s] { - Px::Source - } else { - Px::Known - } - }; - // Mosaic: identity at the left, variants in a column to its right, gaps that are no image. - // Without variants it is the image itself; so it is when the variants would not fit - // (`size` above is then None and `extra` is empty). - let (mw, mh, mosaic, roles): (usize, usize, Option>, Vec) = if let Some((mw, mh)) = size { - let mut mimg = vec![0.0f32; mw * mh * ch]; - let mut roles = vec![Px::Void; mw * mh]; - for y in 0..h { - for x in 0..w { - let (s, d) = (y * w + x, y * mw + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); - roles[d] = role(s); - } - } - let mut oy = 0; - for v in &extra { - ctl.check()?; - for y in 0..v.h { - for x in 0..v.w { - let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); - if v.ok[s] { - roles[d] = Px::Source; - } - } - } - oy += v.h + gap; - } - (mw, mh, Some(mimg), roles) - } else { - (w, h, None, par::map(w * h, true, role)) - }; - drop((extra, ok)); - ctl.check()?; + let specs = variant_specs(opts); // The completion is nearly all the work. let cancel = || ctl.cancelled(); let progress = |f: f32| ctl.progress(f * 0.99); let inner = photocraft_raster::Interrupt::new(&cancel, &progress); - let out = match mosaic { - // Without variants the image itself is completed (it changes only in the hole). - None => { - let filled: Result, Cow<[f32]>> = match img { - Cow::Owned(v) => complete_masked_owned(w, h, ch, v, &roles, ¶ms, &inner)?.map_err(Cow::Owned), - Cow::Borrowed(b) => complete_masked(w, h, ch, b, &roles, ¶ms, &inner)?.ok_or(Cow::Borrowed(b)), - }; - match filled { + // One completion for every option set but the measured one: it fills the caller's buffer in + // place when it owns one. The measured set may be asked a second time (see `fill_retry`). + if params.patch_radius != MEASURED_STRUCTURE_PATCH_RADIUS { + let mut pixels = img.into_owned(); + let attempt = fill_attempt(w, h, ch, &pixels, hole, &ok, &specs, ¶ms, ctl)?; + ctl.check()?; + let out = if attempt.mosaic.is_empty() { + match complete_masked_owned(w, h, ch, pixels, &attempt.roles, ¶ms, &inner)? { Ok(f) => f, - Err(img) => membrane_fill_with(w, h, ch, &img, hole, ctl)?, + // Nothing to copy from: the membrane, as today. + Err(v) => membrane_fill_with(w, h, ch, &v, hole, ctl)?, } - } - Some(mimg) => match complete_masked(mw, mh, ch, &mimg, &roles, ¶ms, &inner)? { - Some(f) => { - let mut out = img.into_owned(); - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); - out[d..d + ch].copy_from_slice(&f[s..s + ch]); + } else { + match complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, ¶ms, &inner)? { + Some(f) => { + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + let (s, d) = ((y * attempt.mw + x) * ch, (y * w + x) * ch); + pixels[d..d + ch].copy_from_slice(&f[s..s + ch]); + } } } + pixels } - out + None => membrane_fill_with(w, h, ch, &pixels, hole, ctl)?, } - None => membrane_fill_with(w, h, ch, &img, hole, ctl)?, - }, - }; + }; + ctl.check()?; + ctl.progress(1.0); + return Ok(out); + } + let out = fill_cow_measured(w, h, ch, img.as_ref(), hole, &ok, &specs, &mut params, &inner, ctl)?; ctl.check()?; ctl.progress(1.0); Ok(out) } +/// The measured fill (#14191): the window is read where it stands, so both attempts see the same +/// pixels; the answer is a new buffer, as in [`fill_with`] (measured fills come from the command's +/// own copy of the sampling window). +#[allow(clippy::too_many_arguments)] +fn fill_cow_measured( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &photocraft_raster::Interrupt, +) -> Result, Cancelled> { + match fill_retry(w, h, ch, img, hole, ok, specs, params, inner, ctl)? { + Some(f) => Ok(f), + // Nothing to copy from at either radius: the membrane, as today. + None => membrane_fill_with(w, h, ch, img, hole, ctl), + } +} /// Box mean of radius `r` over a `w × h` plane (edge-clamped), by summed areas. fn box_mean(w: usize, h: usize, v: &[f32], r: usize) -> Vec { let w1 = w + 1; diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 30ff8111ae..895e9f5d02 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -348,3 +348,125 @@ fn auto_fill_whose_area_differs_from_rectangular_keeps_todays_patch_radius() { let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); assert_eq!(moved, 0, "{moved} channel values differ from today's radius-3 fill"); } + +/// A small buffer that carries the measured option set and the Rectangular area, so the patch +/// radius is the only thing under test: vertical stripes (period 4) in two far-apart colours, with +/// the hole the 1 px border of the buffer. An off-centre 2 x 2 hole leaves no 7 x 7 donor either on +/// a buffer this small (every 7 x 7 window takes a hole pixel), so it proves nothing here. +fn small_stripes(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = (0..n * n).map(|i| (i % n).min(i / n) < 1 || (i % n).max(i / n) > n - 2).collect(); + (img, hole) +} + +/// The completion of the same roles with a given patch radius: `None` when that radius leaves no +/// donor to copy from, which is what sends the fill to the membrane. +fn completion(n: usize, img: &[f32], hole: &[bool], params: &CompleteParams) -> Option> { + let roles: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); + complete_masked(n, n, 3, img, &roles, params, &Interrupt::NONE).unwrap() +} + +/// The smallest side that still holds a fully interior 11 x 11 donor window. +const PATCH_SIDE: usize = MEASURED_STRUCTURE_PATCH_RADIUS * 2 + 1; + +/// Review round 2, real: on a buffer narrower than the 11 x 11 patch there is no window centre for +/// radius 5 at all, so the measured fill found no donor and answered with the smooth membrane where +/// today's radius 3 still copies pieces (#14191 measures 600 x 400 and keeps every other case on +/// today's behaviour, and its "no regression" bullet covers this). Measured at b2764ca1c: on the +/// 9 x 9 buffer the radius-3 completion fills the border hole with 96 channel values differing from +/// the membrane; the radius-5 completion has no donor, so the fill returned the membrane in all 243 +/// channel values of that buffer. The fill now gets today's radius-3 answer there again. +#[test] +fn measured_fill_on_a_small_image_keeps_todays_patch_radius() { + for n in [PATCH_SIDE - 2, PATCH_SIDE - 1] { + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "n {n}: the measured configuration"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "n {n}: today's radius"); + let today = completion(n, &img, &hole, ¶ms).unwrap_or_else(|| panic!("n {n}: today's radius-3 fill has no donor either")); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let like_membrane = out.iter().zip(&membrane).filter(|(a, b)| *a == *b).count(); + assert_eq!( + moved, + 0, + "n {n}: {moved} of {} channel values differ from today's radius-3 fill; {like_membrane} of them equal the membrane fill", + img.len() + ); + } +} + +/// The other side of that border: when an 11 x 11 donor window does exist, the measured fill uses +/// it, also on a small buffer (18 x 18 with a 1 px border hole: 178 channel values differ from +/// today's radius-3 completion there). Guard test, passes before and after the change. +#[test] +fn measured_fill_uses_the_11x11_patch_when_a_window_fits() { + let n = 18; + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + let with_patch = completion(n, &img, &hole, &wide).expect("n 18: an 11 x 11 donor window must exist beside a 1 px border hole"); + let today = completion(n, &img, &hole, &CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }) + .expect("n 18: today's fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let from_patch = out.iter().zip(&with_patch).filter(|(a, b)| a != b).count(); + let from_today = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(from_patch, 0, "the measured fill is not the 11 x 11 completion ({from_patch} channel values differ)"); + assert_ne!(from_today, 0, "the 11 x 11 completion is the same as today's ({from_today} differ): the patch was never used"); +} + +/// The membrane fallback stays where it already is today: a buffer with no room even for the +/// default 7 x 7 patch has no donor at either radius, so the new radius never reaches it. +/// Guard test, passes before and after the change. +#[test] +fn measured_fill_without_room_for_todays_patch_still_falls_back_to_the_membrane() { + for n in 4..7 { + let (img, hole) = small_stripes(n); + let opts = FillOptions { color_adaptation: Adapt::NONE, ..FillOptions::default() }; + let source: Vec = hole.iter().map(|h| !h).collect(); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, ¶ms).is_none(), "n {n}: no donor at today's radius either"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let moved = out.iter().zip(&membrane).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "n {n}: {moved} channel values differ from the membrane fill"); + } +} + +/// The same buffer as [`small_stripes`] with an 8 x 8 hole in the middle instead of the border: at +/// 18 x 18 there are 11 x 11 windows (their centres are x and y 5 to 12), but the hole covers every +/// one of them, while a 7 x 7 window still fits in the 8-wide strips left and right of it. +fn stripes_hole_blocking_the_wide_windows(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = + (0..n * n).map(|i| matches!(i % n, x if x >= n / 2 - 1 && x <= n / 2 + 6) && matches!(i / n, y if y >= n / 2 - 1 && y <= n / 2 + 6)).collect(); + (img, hole) +} + +/// The other way radius 5 can leave no donor: a buffer with room for 11 x 11 windows, and a hole +/// that uses up all of them. #14191 measured a hole four patches across in a 400 x 400 window, so a +/// fill that completes today with the default radius has to complete the same way here, before the +/// membrane fallback. +#[test] +fn measured_fill_falls_back_to_todays_radius_when_the_hole_leaves_no_room_for_the_patch() { + let n = 18; + let (img, hole) = stripes_hole_blocking_the_wide_windows(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "the measured configuration"); + assert_eq!(hole.iter().filter(|h| **h).count(), 64, "an 8 x 8 hole"); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, &wide).is_none(), "radius 5 must leave no donor here, that is the case under test"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "today's radius"); + let today = completion(n, &img, &hole, ¶ms).expect("today's radius-3 fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "{moved} of {} channel values differ from today's radius-3 fill", img.len()); +}