Merge pull request #10528 from qvest-ssels/fix/select-mask-ants-10506

Select and Mask, Content-Aware Fill: draw the ants with the canvas's ants (#10506)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-11 00:21:08 -07:00
commit 031aa36b48
8 files changed
+611 -149

No files matched your search

+6
View File
@@ -48,6 +48,12 @@ impl Style {
Self { ppp, width, dash, phase }
}
/// How far the pattern has marched and its period, in device pixels.
#[cfg(test)]
pub(crate) fn march(&self) -> (i64, i64) {
(self.phase, 2 * self.dash)
}
/// The black runs of `[lo, hi)` along one pixel row (or column) of a band. A pixel is black
/// where `(s + phase) mod 2·dash < dash`, `s` being its position along the edge plus `off`,
/// `width` times its position across it: `x + w·y` on a horizontal edge, `y + w·x` on a
+45
View File
@@ -25,6 +25,31 @@ pub(crate) fn bounded_step(bounds: Rect, mut step: u32) -> u32 {
step
}
/// The trace step for a view of `device_zoom` device px per document px, of a mask reduced by `k`:
/// about one sample per device pixel, a power of two in 1..=64.
pub(crate) fn view_step(device_zoom: f32, k: u32) -> u32 {
(1.0 / (device_zoom * k.max(1) as f32).max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32
}
/// The part of a mask reduced by `k` to trace for the document rectangle `[x0, y0, x1, y1]` in
/// view: quantised to 256 cells of `step` so small pans keep it, and padded by that so the cut
/// edges of a trace fall outside the view.
pub(crate) fn view_region(view: [f64; 4], k: u32, step: u32) -> Rect {
let k = f64::from(k.max(1));
let q = 256 * step.clamp(1, 64) as i32;
// The view centre can be any finite number. Past ±2³⁰ there is no document to outline, and
// the padding (at most 2 · 256 · 64) can't overflow i32 from there.
let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32;
let (x0, x1) = (view[0].min(view[2]) / k, view[0].max(view[2]) / k);
let (y0, y1) = (view[1].min(view[3]) / k, view[1].max(view[3]) / k);
Rect::new(
px(x0.floor()).div_euclid(q) * q - q,
px(y0.floor()).div_euclid(q) * q - q,
(px(x1.ceil()).div_euclid(q) + 2) * q,
(px(y1.ceil()).div_euclid(q) + 2) * q,
)
}
/// Extract the boundary of `mask` (> 0.5 = selected) as merged horizontal and vertical segments.
pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {
outline_scaled(mask, bounds, 1)
@@ -210,6 +235,26 @@ mod tests {
}
}
#[test]
fn view_step_and_region_quantise_and_survive_hostile_views() {
assert_eq!(view_step(1.0, 1), 1);
assert_eq!(view_step(0.25, 1), 4);
assert_eq!(view_step(0.5, 2), 1, "a copy reduced by 2 seen at 50 % is at its own size");
assert_eq!(view_region([10.0, 20.0, 300.0, 200.0], 1, 1), Rect::new(-256, -256, 768, 512));
assert_eq!(view_region([0.0, 0.0, 1024.0, 512.0], 2, 1), Rect::new(-256, -256, 1024, 768));
for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1e9, 1e-30] {
for k in [0, 1, 3, u32::MAX] {
assert!((1..=64).contains(&view_step(zoom, k)), "zoom {zoom}, k {k}");
}
}
for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e30, -1e30] {
for step in [0, 1, 64, u32::MAX] {
let r = view_region([v, -v, v, 1e30], 1, step);
assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "{v}, {step}: {r:?}");
}
}
}
#[test]
fn empty_mask_has_no_outline() {
let m = Surface::new(PixelFormat::GRAY8);
+4 -4
View File
@@ -56,8 +56,8 @@ const BAR_H: f32 = 36.0;
const PANEL_W: f32 = 300.0;
const PREVIEW_W: f32 = 380.0;
const UNDO_LIMIT: usize = 100;
/// Outlines with more edges than this are drawn at the proxy's resolution.
const MAX_OUTLINE_EDGES: usize = 200_000;
/// Outlines with more runs than this are drawn as the fill area's bounding box.
const MAX_OUTLINE_SEGMENTS: usize = 200_000;
/// Photoshop's overlay colour as it shows (a 50 % tint of grey 200 reads 171, 204, 153).
const OVERLAY_COLOR: [u8; 3] = [142, 208, 106];
/// The `prefs.dialogs` key under which the settings are remembered.
@@ -237,8 +237,8 @@ pub struct CafWorkspace {
/// The lasso polygon being drawn and its selection mode.
lasso: Option<(usize, Vec<[f64; 2]>)>,
base: Base,
/// Fill-area outline edges (document px), or `None` when there are too many.
outline: Option<Vec<[[f32; 2]; 2]>>,
/// The fill area's outline (document px), or `None` when there are too many runs.
outline: Option<Vec<crate::outline::Segment>>,
/// Document px per proxy px, and the proxy size.
k: usize,
pw: usize,
+29 -28
View File
@@ -1,4 +1,5 @@
use super::{CMD, CafWorkspace, Color32, LayerId, MAX_CAF_POINTS, MAX_OUTLINE_EDGES, PhotocraftApp, Rect, TextureHandle, Value, json, stroke_json};
use super::{CMD, CafWorkspace, Color32, LayerId, MAX_CAF_POINTS, MAX_OUTLINE_SEGMENTS, PhotocraftApp, Rect, TextureHandle, Value, json, stroke_json};
use crate::outline::Segment;
/// What the plan (without the brush strokes) says: the window, the fill area and the sampling
/// option's area, over `rect`.
@@ -99,36 +100,36 @@ pub(super) fn compute_base(app: &PhotocraftApp, w: &CafWorkspace) -> Result<Base
Ok(Base { window: plan.window, rect: plan.rect, hole: plan.hole, base })
}
/// Unit edges between the fill area and the rest, in document px.
pub(super) fn outline(b: &Base) -> Option<Vec<[[f32; 2]; 2]>> {
let (w, h) = (b.rect.width() as usize, b.rect.height() as usize);
let (ox, oy) = (b.rect.x0 as f32, b.rect.y0 as f32);
let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && b.hole.get(y as usize * w + x as usize).copied().unwrap_or(false);
let mut out = Vec::new();
for y in 0..h as i64 {
for x in 0..w as i64 {
if !at(x, y) {
continue;
}
let (fx, fy) = (ox + x as f32, oy + y as f32);
if !at(x - 1, y) {
out.push([[fx, fy], [fx, fy + 1.0]]);
}
if !at(x + 1, y) {
out.push([[fx + 1.0, fy], [fx + 1.0, fy + 1.0]]);
}
if !at(x, y - 1) {
out.push([[fx, fy], [fx + 1.0, fy]]);
}
if !at(x, y + 1) {
out.push([[fx, fy + 1.0], [fx + 1.0, fy + 1.0]]);
}
if out.len() > MAX_OUTLINE_EDGES {
return None;
/// The fill area's edges merged into runs, as the canvas traces a selection, in document px;
/// `None` past [`MAX_OUTLINE_SEGMENTS`].
pub(super) fn outline(b: &Base) -> Option<Vec<Segment>> {
let area = super::lifecycle::bounds(b);
let w = b.rect.width() as usize;
let at = |x: i32, y: i32| b.rect.contains(x, y) && b.hole.get((y - b.rect.y0) as usize * w + (x - b.rect.x0) as usize).copied().unwrap_or(false);
let mut segs = Vec::new();
// Between rows y - 1 and y along x, then between columns x - 1 and x along y.
for horizontal in [true, false] {
let (l0, l1, t0, t1) = if horizontal { (area.y0, area.y1, area.x0, area.x1) } else { (area.x0, area.x1, area.y0, area.y1) };
for l in l0..=l1 {
let mut run = None;
for t in t0..=t1 {
let (p, q) = if horizontal { ((t, l), (t, l.saturating_sub(1))) } else { ((l, t), (l.saturating_sub(1), t)) };
let edge = t < t1 && at(p.0, p.1) != at(q.0, q.1);
match (edge, run) {
(true, None) => run = Some(t),
(false, Some(s)) => {
segs.push(if horizontal { ([s, l], [t, l]) } else { ([l, s], [l, t]) });
if segs.len() > MAX_OUTLINE_SEGMENTS {
return None;
}
run = None;
}
_ => {}
}
}
}
}
Some(out)
Some(segs)
}
/// Recompute the base after a change of the fill area, the sampling option or the document.
@@ -473,6 +473,45 @@ fn strokes_past_the_engines_limits_are_refused_at_the_brush() {
assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}");
}
/// A plan over `rect` whose fill area is the union of `parts`.
fn base_with_hole(rect: Rect, parts: &[Rect]) -> Base {
let (w, h) = (rect.width() as usize, rect.height() as usize);
let mut hole = vec![false; w * h];
for (i, cell) in hole.iter_mut().enumerate() {
let (x, y) = (rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32);
*cell = parts.iter().any(|p| p.contains(x, y));
}
Base { window: rect, rect, hole, base: vec![false; w * h] }
}
/// #10506: the fill area is outlined by merged runs, as the canvas outlines a selection, so it
/// is drawn with the canvas's ants (it was one 1-point line per pixel edge, blinking).
#[test]
fn fill_area_outline_is_merged_runs() {
let rect = Rect::new(10, 20, 210, 180);
let mut square = outline(&base_with_hole(rect, &[Rect::new(50, 60, 90, 100)])).unwrap();
square.sort();
assert_eq!(square, vec![([50, 60], [50, 100]), ([50, 60], [90, 60]), ([50, 100], [90, 100]), ([90, 60], [90, 100])]);
let mut l = outline(&base_with_hole(rect, &[Rect::new(20, 30, 40, 90), Rect::new(20, 70, 100, 90)])).unwrap();
l.sort();
assert_eq!(l, vec![([20, 30], [20, 90]), ([20, 30], [40, 30]), ([20, 90], [100, 90]), ([40, 30], [40, 70]), ([40, 70], [100, 70]), ([100, 70], [100, 90])]);
// At the plan's edge too, and nothing for no fill area.
assert_eq!(outline(&base_with_hole(rect, &[rect])).map(|s| s.len()), Some(4));
assert_eq!(outline(&base_with_hole(rect, &[])), Some(Vec::new()));
}
/// A speckled fill area past the cap falls back to its bounding box.
#[test]
fn a_speckled_fill_area_falls_back_to_its_bounds() {
let rect = Rect::new(0, 0, 1000, 1000);
let mut b = base_with_hole(rect, &[]);
for (i, cell) in b.hole.iter_mut().enumerate() {
*cell = (i % 1000).is_multiple_of(2) && (i / 1000).is_multiple_of(2);
}
assert!(outline(&b).is_none());
assert_eq!(lifecycle::bounds(&b), Rect::new(0, 0, 999, 999), "the box drawn instead");
}
fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) {
let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
let input = egui::RawInput { events: vec![ev], ..Default::default() };
+6 -9
View File
@@ -380,22 +380,19 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let pr = ERect::from_min_size(img.min, vec2((w.pw * w.k) as f32 * v.zoom, (w.ph * w.k) as f32 * v.zoom));
clip.with_clip_rect(img.intersect(area)).image(tex.id(), pr, uv, Color32::WHITE);
}
// The fill area's outline (marching ants: black dashes on white).
let phase = (ui.input(|i| i.time) * 8.0) as usize;
// The fill area's outline: marching ants, as the canvas draws them.
match &w.outline {
Some(edges) => {
for e in edges {
let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])]));
let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2);
clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE }));
}
Some(segs) if segs.is_empty() => {}
Some(segs) => {
let time = ui.input(|i| i.time);
crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen([f64::from(p[0]), f64::from(p[1])]));
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
None => {
let b = v.rect(bounds(&w.base));
clip.rect_stroke(b, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside);
}
}
ctx.request_repaint_after(std::time::Duration::from_millis(120));
if let Some((_, pts)) = &w.lasso
&& pts.len() > 1
{
+110 -105
View File
@@ -35,6 +35,7 @@ use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
use crate::canvas::ToolEvent;
use crate::outline::Segment;
use crate::select_mask_view::Mode;
use crate::theme::Tokens;
use crate::widgets;
@@ -46,10 +47,6 @@ const BAR_H: f32 = 36.0;
const TAB_H: f32 = 28.0;
const PANEL_W: f32 = 350.0;
const UNDO_LIMIT: usize = 100;
/// Marching ants with more edges than this are not drawn.
const MAX_ANT_EDGES: usize = 200_000;
/// Bound the temporary dense mask used for marching ants.
const MAX_ANT_PIXELS: usize = 4_000_000;
/// The `prefs.dialogs` key under which Remember Settings keeps the settings.
const REMEMBERED: &str = "select.refineEdge.workspace";
const CMD: &str = crate::select_mask_view::COMMAND;
@@ -354,11 +351,32 @@ struct BaseCache {
base: Option<Surface>,
}
/// Which part of the refined selection the Marching Ants view traced, and how coarsely.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct OutlineKey {
step: u32,
/// Reduced-copy px.
region: Rect,
k: u32,
}
/// What the Marching Ants view outlines: the refined selection of one preview.
struct Ants {
/// The refined selection on the reduced copy.
selection: Surface,
/// Where its outline can be (reduced-copy px): its content within the copy.
bounds: Rect,
/// Document px per reduced-copy px of the preview.
k: u32,
/// The outline for a view (reduced-copy px), traced again when the view moves past its key.
outline: Option<(OutlineKey, Vec<Segment>)>,
}
/// A computed preview, ready to upload.
struct Shown {
image: egui::ColorImage,
/// Marching ants (document px) in the Marching Ants view.
ants: Option<Vec<[[f32; 2]; 2]>>,
/// In the Marching Ants view, with the outline traced for the view the preview was asked for.
ants: Option<Ants>,
/// Reduced-copy pixels at least half selected.
selected: usize,
/// How many points of the stroke being drawn it includes ([`usize::MAX`]: every stroke is in).
@@ -380,7 +398,8 @@ struct Preview {
shown: u64,
pending: Option<Shown>,
tex: Option<TextureHandle>,
ants: Option<Vec<[[f32; 2]; 2]>>,
/// [`Shown::ants`] of the preview shown.
ants: Option<Ants>,
covers: [f32; 2],
selected: usize,
/// [`Shown::trail`] of the preview shown.
@@ -434,6 +453,8 @@ pub struct SelectMaskWorkspace {
image_tex: Option<TextureHandle>,
zoom: f32,
center: [f64; 2],
/// The document's area on screen and the device px per point, as last drawn.
view_area: Option<(ERect, f32)>,
hover: Option<[f64; 2]>,
preview: Preview,
pub error: Option<String>,
@@ -781,6 +802,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result<(), String> {
image_tex: None,
zoom: 0.0,
center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0],
view_area: None,
hover: None,
preview: Preview::default(),
error: None,
@@ -1051,6 +1073,9 @@ struct Job {
texture_limit: usize,
/// [`Shown::trail`] of this preview.
trail: usize,
/// In the Marching Ants view: the device px per document px and the document rectangle in
/// view, to trace the outline for.
ants: Option<(f32, [f64; 4])>,
}
fn job(app: &PhotocraftApp) -> Option<Job> {
@@ -1096,38 +1121,10 @@ fn job(app: &PhotocraftApp) -> Option<Job> {
Some(_) => 0,
None => usize::MAX,
},
ants: w.view_area.filter(|_| w.opts.view == Mode::MarchingAnts).map(|(area, ppp)| ant_view(View { area, zoom: w.zoom, center: w.center }, ppp)),
})
}
/// Unit edges between selected (≥ ½) and unselected pixels of `m` (`w × h`, reduced by `k`), in
/// document px; `None` past [`MAX_ANT_EDGES`].
fn ant_edges(m: &[f32], w: usize, h: usize, k: f32) -> Option<Vec<[[f32; 2]; 2]>> {
let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && m.get(y as usize * w + x as usize).is_some_and(|v| *v >= 0.5);
let mut out = Vec::new();
for y in 0..h as i64 {
for x in 0..w as i64 {
if !at(x, y) {
continue;
}
let (fx, fy) = (x as f32, y as f32);
for (n, a, b) in [
(at(x - 1, y), [fx, fy], [fx, fy + 1.0]),
(at(x + 1, y), [fx + 1.0, fy], [fx + 1.0, fy + 1.0]),
(at(x, y - 1), [fx, fy], [fx + 1.0, fy]),
(at(x, y + 1), [fx, fy + 1.0], [fx + 1.0, fy + 1.0]),
] {
if !n {
out.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]);
}
}
if out.len() > MAX_ANT_EDGES {
return None;
}
}
}
Some(out)
}
/// Count selected pixels without allocating a canvas-sized mask. Missing tiles use the surface's
/// default value, including an inverted selection whose default is selected.
fn selected_pixels(selection: Option<&Surface>, area: Rect) -> usize {
@@ -1150,65 +1147,53 @@ fn selected_pixels(selection: Option<&Surface>, area: Rect) -> usize {
count
}
/// Generate ants only when the dense temporary mask fits the preview budget.
fn preview_ants(selection: Option<&Surface>, area: Rect, k: f32) -> Option<Vec<[[f32; 2]; 2]>> {
let (w, h) = (area.width() as usize, area.height() as usize);
if w.checked_mul(h).is_none_or(|n| n > MAX_ANT_PIXELS) {
return sparse_preview_ants(selection?, area, k);
}
let coverage = photocraft_algo::selection::mask_from_surface(selection, area);
ant_edges(&coverage, w, h, k)
/// The device px per document px and the document rectangle `[x0, y0, x1, y1]` the view shows.
fn ant_view(v: View, ppp: f32) -> (f32, [f64; 4]) {
let (a, b) = (v.to_doc(v.area.min), v.to_doc(v.area.max));
(v.zoom * ppp, [a[0], a[1], b[0], b[1]])
}
/// Follow sparse selections on large canvases without scanning the empty canvas. A selected
/// default or too many stored pixels falls back to omitting ants, as for too many edges.
fn sparse_preview_ants(surface: &Surface, area: Rect, k: f32) -> Option<Vec<[[f32; 2]; 2]>> {
if surface.default_pixel().first().is_some_and(|v| *v >= 0.5) {
return None;
/// Where the outline of `selection` can be within the reduced copy `area`: all of it when the
/// default pixel is selected (an inverted selection is outlined along the canvas border).
fn trace_bounds(selection: Option<&Surface>, area: Rect) -> Rect {
match selection {
Some(s) if s.default_pixel().first().is_some_and(|v| *v > 0.5) => area,
Some(s) => s.content_bounds().intersect(&area),
None => Rect::EMPTY,
}
let mut work = 0usize;
let mut edges = Vec::new();
let mut sample = vec![0.0; surface.channels()];
for (coord, _) in surface.tiles() {
let tile = coord.rect().intersect(&area);
if tile.is_empty() {
continue;
}
work = work.checked_add((tile.width() as usize).checked_mul(tile.height() as usize)?)?;
if work > MAX_ANT_PIXELS {
return None;
}
let coverage = photocraft_algo::selection::mask_from_surface(Some(surface), tile);
for y in tile.y0..tile.y1 {
for x in tile.x0..tile.x1 {
let index = (y - tile.y0) as usize * tile.width() as usize + (x - tile.x0) as usize;
if !coverage.get(index).is_some_and(|v| *v >= 0.5) {
continue;
}
let (fx, fy) = ((x - area.x0) as f32, (y - area.y0) as f32);
for (nx, ny, a, b) in [
(x - 1, y, [fx, fy], [fx, fy + 1.0]),
(x + 1, y, [fx + 1.0, fy], [fx + 1.0, fy + 1.0]),
(x, y - 1, [fx, fy], [fx + 1.0, fy]),
(x, y + 1, [fx, fy + 1.0], [fx + 1.0, fy + 1.0]),
] {
let selected = if nx < area.x0 || nx >= area.x1 || ny < area.y0 || ny >= area.y1 {
false
} else {
surface.read_pixel(nx, ny, &mut sample);
sample.first().is_some_and(|v| *v >= 0.5)
};
if !selected {
edges.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]);
if edges.len() > MAX_ANT_EDGES {
return None;
}
}
}
}
}
}
/// The trace of a preview reduced by `k` within `bounds`, for a view (see [`ant_view`]).
fn outline_key(k: u32, bounds: Rect, (zoom, view): (f32, [f64; 4])) -> OutlineKey {
let k = k.max(1);
let step = crate::outline::view_step(zoom, k);
OutlineKey { step, region: crate::outline::view_region(view, k, step).intersect(&bounds), k }
}
fn trace(selection: &Surface, key: OutlineKey, parallel: bool) -> Vec<Segment> {
if parallel {
crate::outline::outline_scaled(selection, key.region, key.step)
} else {
// A preview job may hold Rayon's workers; the UI thread must not wait for them (#1554).
crate::outline::outline_scaled_serial(selection, key.region, key.step)
}
Some(edges)
}
/// The outline for a view, traced again only when the view's key changes.
fn ant_outline(ants: &mut Ants, view: (f32, [f64; 4]), parallel: bool) -> &[Segment] {
let key = outline_key(ants.k, ants.bounds, view);
if ants.outline.as_ref().is_none_or(|(k, _)| *k != key) {
ants.outline = Some((key, trace(&ants.selection, key, parallel)));
}
ants.outline.as_ref().map_or(&[], |(_, segs)| segs.as_slice())
}
/// Document point of outline point `p` (reduced by `k`), within `canvas`: the reduced copy's
/// last row and column may reach past it.
fn ant_point(p: [i32; 2], k: u32, canvas: Rect) -> [f64; 2] {
let k = f64::from(k.max(1));
let at = |v: i32, lo: i32, hi: i32| (f64::from(v) * k).clamp(f64::from(lo), f64::from(hi.max(lo)));
[at(p[0], canvas.x0, canvas.x1), at(p[1], canvas.y0, canvas.y1)]
}
/// The preview of `job`: the edits applied (from where the cache left off), the edge refined and
@@ -1259,8 +1244,19 @@ fn compute(job: Job, cancel: Option<&photocraft_engine::jobs::JobCtx>) -> Result
let buf = photocraft_compose::render_reduced(&shown, u32::try_from(tw).unwrap_or(1), u32::try_from(th).unwrap_or(1));
let image = crate::canvas::display_image(job.display.as_deref(), &buf);
let selected = selected_pixels(shown.selection.as_ref(), shown.bounds());
// Only the Marching Ants view keeps the refined selection; switching to it runs a new preview.
let mode = params.get("__view").and_then(|v| v.get("mode")).and_then(Value::as_str);
let ants = if mode == Some(Mode::MarchingAnts.id()) { preview_ants(shown.selection.as_ref(), shown.bounds(), k as f32) } else { None };
let area = shown.bounds();
let ants = shown.selection.filter(|_| mode == Some(Mode::MarchingAnts.id())).map(|selection| {
let bounds = trace_bounds(Some(&selection), area);
// Traced here, off the UI thread, for the view as it was: the UI traces again only after
// a pan or zoom. On the web this runs on the UI thread, where Rayon has no workers.
let outline = job.ants.map(|view| {
let key = outline_key(k, bounds, view);
(key, trace(&selection, key, true))
});
Ants { selection, bounds, k, outline }
});
let covers = [(pw as f32) * k as f32, (ph as f32) * k as f32];
Ok((Shown { image, ants, selected, trail: job.trail, covers }, cache, proxy))
}
@@ -1684,13 +1680,17 @@ fn follow_revision(app: &mut PhotocraftApp) {
w.preview.tex = None;
w.preview.pending = None;
w.preview.cache = None;
w.preview.ants = None;
w.stale();
}
}
/// Draws the document, the refined edge, the stroke being drawn and the polygon in progress.
fn paint_canvas(ui: &mut egui::Ui, ctx: &egui::Context, w: &mut SelectMaskWorkspace, t: &Tokens, painter: &egui::Painter, resp: &egui::Response, area: ERect) {
fn paint_canvas(ui: &mut egui::Ui, w: &mut SelectMaskWorkspace, t: &Tokens, painter: &egui::Painter, resp: &egui::Response, area: ERect, parallel: bool) {
let ctx = &ui.ctx().clone();
let v = View { area, zoom: w.zoom, center: w.center };
let ppp = ctx.pixels_per_point();
w.view_area = Some((area, ppp));
let clip = painter.with_clip_rect(area);
let img = v.rect(w.canvas);
let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
@@ -1707,18 +1707,18 @@ fn paint_canvas(ui: &mut egui::Ui, ctx: &egui::Context, w: &mut SelectMaskWorksp
}
(None, None) => {}
}
// Marching Ants: the refined selection's edge, black dashes on white.
if !w.hide_view
&& w.opts.view == Mode::MarchingAnts
&& let Some(edges) = &w.preview.ants
{
let phase = (ui.input(|i| i.time) * 8.0) as usize;
for e in edges {
let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])]));
let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2);
clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE }));
// Marching Ants: the refined selection's edge, drawn as the canvas draws its ants.
if !w.hide_view && w.opts.view == Mode::MarchingAnts {
let canvas = w.canvas;
if let Some(ants) = w.preview.ants.as_mut()
&& let k = ants.k
&& let segs = ant_outline(ants, ant_view(v, ppp), parallel)
&& !segs.is_empty()
{
let time = ui.input(|i| i.time);
crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen(ant_point(p, k, canvas)));
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
ctx.request_repaint_after(std::time::Duration::from_millis(120));
}
if w.preview.shown != w.preview.want && !w.pressed {
let sp = ERect::from_min_size(area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0));
@@ -1917,6 +1917,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let mut mods = egui::Modifiers::NONE;
let mut edit: Option<Value> = None;
let mut do_reset = false;
// As on the canvas: trace in parallel unless a job may hold Rayon's workers (#1554).
#[cfg(not(target_arch = "wasm32"))]
let parallel = !app.session.has_jobs() && app.distort.select_mask.as_ref().is_some_and(|w| w.preview.running.is_none());
#[cfg(target_arch = "wasm32")]
let parallel = !app.session.has_jobs();
egui::Area::new(egui::Id::unique("select-mask-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
let Some(w) = app.distort.select_mask.as_mut() else { return };
let before = (w.opts.clone(), w.sample_all);
@@ -2027,7 +2032,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
let v = View { area, zoom: w.zoom, center: w.center };
paint_canvas(ui, ctx, w, &t, &painter, &resp, area);
paint_canvas(ui, w, &t, &painter, &resp, area, parallel);
// Space, the middle button or the Hand pan. The Polygonal Lasso takes clicks: each adds a
// vertex, a double-click closes.
let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == SmTool::Hand;
@@ -789,18 +789,32 @@ fn the_reason_a_stale_workspace_closed_is_reported() {
}
}
/// The ants of `selection` over the reduced copy `area`, `k` document px per copy px.
fn shown_ants(selection: Surface, area: Rect, k: u32) -> Ants {
let bounds = trace_bounds(Some(&selection), area);
Ants { selection, bounds, k, outline: None }
}
fn ants_mut(app: &mut PhotocraftApp) -> &mut Ants {
ws_mut(app).preview.ants.as_mut().unwrap()
}
#[test]
fn sparse_large_preview_counts_coverage_without_a_dense_canvas_mask() {
fn sparse_large_preview_keeps_its_ants() {
let area = Rect::new(0, 0, 100_000, 100_000);
let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8);
selection.write_pixel(99_999, 99_999, &[1.0]);
selection.write_pixel(2, 3, &[0.5]);
selection.write_pixel(-1, -1, &[1.0]);
assert_eq!(selected_pixels(Some(&selection), area), 2);
assert_eq!(preview_ants(Some(&selection), area, 1.0).unwrap().len(), 8);
let small = Rect::new(0, 0, 10, 10);
assert_eq!(selected_pixels(Some(&selection), small), 1);
assert_eq!(preview_ants(Some(&selection), small, 1.0).unwrap().len(), 4);
// At 100 % around the far corner: the one pixel there, outlined by four lines. The old ants
// were unit edges of a canvas-sized mask, dropped past 4 MP.
let mut ants = shown_ants(selection, area, 1);
let segs = ant_outline(&mut ants, (1.0, [99_500.0, 99_500.0, 100_500.0, 100_500.0]), false);
assert_eq!(segs.len(), 4, "{segs:?}");
assert!(segs.iter().all(|(a, b)| [a, b].iter().all(|p| (99_999..=100_000).contains(&p[0]) && (99_999..=100_000).contains(&p[1]))));
let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]);
inverted.write_pixel(2, 3, &[0.0]);
@@ -1097,3 +1111,358 @@ fn the_resize_circle_stays_put_while_the_readout_follows_the_pointer() {
assert_eq!(brush_circles(&h), [(over + vec2(60.0, -60.0), size as f32 * 0.5 * zoom)], "after the drag the circle follows the pointer again");
assert!(h.query_by_label("Diameter:").is_none(), "and the readout is gone");
}
/// A selection of the rectangle `r` (reduced-copy px).
fn rect_selection(r: Rect) -> Surface {
let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8);
s.fill_rect(r, &[1.0]);
s
}
/// The Marching Ants view outlines the refined selection as the canvas does: merged runs (4 lines
/// for a rectangle, not one per pixel edge), on the document's pixel edges at the copy's scale.
#[test]
fn marching_ants_trace_merged_runs_like_the_canvas() {
let area = Rect::new(0, 0, 100, 60);
let sel = rect_selection(Rect::new(5, 5, 25, 15));
let whole = crate::outline::outline(&sel, sel.content_bounds());
let mut ants = shown_ants(sel, area, 2);
let segs = ant_outline(&mut ants, (1.0, [0.0, 0.0, 200.0, 120.0]), false).to_vec();
assert_eq!(segs, whole);
assert_eq!(segs.len(), 4, "{segs:?}");
for (a, b) in segs {
for p in [a, b].map(|p| [p[0] * 2, p[1] * 2]) {
let on_x = (p[0] == 10 || p[0] == 50) && (10..=30).contains(&p[1]);
let on_y = (p[1] == 10 || p[1] == 30) && (10..=50).contains(&p[0]);
assert!(on_x || on_y, "{p:?} lies on the document rectangle (10, 10)–(50, 30)");
}
}
}
/// Frames reuse the trace while the view stays within its quantised region; a zoom traces again.
#[test]
fn ant_outline_is_cached_per_view() {
let mut ants = shown_ants(rect_selection(Rect::new(10, 10, 90, 50)), Rect::new(0, 0, 100, 60), 1);
let first = ant_outline(&mut ants, (1.0, [0.0, 0.0, 100.0, 60.0]), false).as_ptr();
let key = ants.outline.as_ref().unwrap().0;
let panned = ant_outline(&mut ants, (1.0, [3.0, 2.0, 103.0, 62.0]), false).as_ptr();
assert_eq!(first, panned, "a small pan keeps the trace");
assert_eq!(ants.outline.as_ref().unwrap().0, key);
let zoomed = ant_outline(&mut ants, (0.25, [0.0, 0.0, 400.0, 240.0]), false).len();
assert_eq!(ants.outline.as_ref().unwrap().0.step, 4, "zoomed out to 25 %: one sample per 4 px");
assert_eq!(zoomed, 4);
}
/// The preview job traces the outline for the view it was asked for, so a new preview (one per
/// move with Real-Time Refinement) costs the UI thread no trace.
#[test]
fn the_preview_job_traces_the_outline_for_the_view() {
let mut app = app_with_selection();
open(&mut app).unwrap();
let area = ERect::from_min_size(pos2(50.0, 60.0), vec2(800.0, 500.0));
let w = ws_mut(&mut app);
(w.view_area, w.zoom, w.center) = (Some((area, 1.5)), 2.0, [80.0, 50.0]);
// The other views keep no refined selection.
ui(&mut app, json!({"waitPreview": true}));
upload(&mut app, &egui::Context::default());
assert!(ws(&app).preview.ants.is_none(), "Onion Skin");
ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true}));
upload(&mut app, &egui::Context::default());
let w = ws_mut(&mut app);
let view = ant_view(View { area, zoom: w.zoom, center: w.center }, 1.5);
let ants = w.preview.ants.as_mut().unwrap();
let traced = ants.outline.as_ref().map(|(key, segs)| (*key, segs.as_ptr())).expect("traced in the job");
assert_eq!(traced.0, outline_key(ants.k, ants.bounds, view));
assert_eq!(ant_outline(ants, view, false).as_ptr(), traced.1, "drawn without tracing again");
assert_eq!(ants.outline.as_ref().unwrap().1.len(), 4, "the 20 × 20 selection");
}
/// Until the preview at the new scale arrives, the ants keep the scale of the preview they outline.
#[test]
fn the_outline_keeps_its_previews_scale_while_high_quality_is_toggled() {
let mut app = app_sized(3300, 60);
app.session.execute("select.rect", json!({"x": 30, "y": 15, "width": 30, "height": 30})).unwrap();
open(&mut app).unwrap();
ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true}));
upload(&mut app, &egui::Context::default());
ui(&mut app, json!({"highQualityPreview": true}));
assert_eq!(ws(&app).proxy_k(), 1);
let ants = ants_mut(&mut app);
assert_eq!(ants.k, 3);
let k = ants.k as i32;
let segs = ant_outline(ants, (1.0, [0.0, 0.0, 3300.0, 60.0]), false);
let mut doc: Vec<_> = segs.iter().map(|(a, b)| ([a[0] * k, a[1] * k], [b[0] * k, b[1] * k])).collect();
doc.sort();
assert_eq!(doc, vec![([30, 15], [30, 45]), ([30, 15], [60, 15]), ([30, 45], [60, 45]), ([60, 15], [60, 45])]);
}
/// An inverted selection (selected by default) is outlined along the canvas border too, on a
/// canvas past the old ants' 4 MP limit.
#[test]
fn an_inverted_selection_outlines_the_canvas_border() {
let area = Rect::new(0, 0, 3000, 2000);
let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]);
inverted.fill_rect(Rect::new(1000, 800, 1400, 1200), &[0.0]);
let mut ants = shown_ants(inverted, area, 1);
assert_eq!(ants.bounds, area);
let segs = ant_outline(&mut ants, (0.25, [0.0, 0.0, 3000.0, 2000.0]), false);
assert_eq!(segs.len(), 8, "{segs:?}");
for border in [([0, 0], [3000, 0]), ([0, 2000], [3000, 2000]), ([0, 0], [0, 2000]), ([3000, 0], [3000, 2000])] {
assert!(segs.contains(&border), "{border:?} in {segs:?}");
}
}
/// The reduced copy covers whole blocks of `k` px, past the canvas when its size isn't a multiple
/// of `k`; the ants stay on the canvas border, not on the pasteboard beyond it.
#[test]
fn the_border_ants_stay_on_the_canvas_of_a_reduced_copy() {
let mut app = app_sized(3301, 60);
open(&mut app).unwrap();
ui(&mut app, json!({"invert": true, "view": "marchingAnts", "waitPreview": true}));
upload(&mut app, &egui::Context::default());
let canvas = ws(&app).canvas;
let ants = ants_mut(&mut app);
assert_eq!(ants.k, 3);
let k = ants.k;
let segs = ant_outline(ants, (0.5, [0.0, 0.0, 3301.0, 60.0]), false);
let points: Vec<[f64; 2]> = segs.iter().flat_map(|(a, b)| [*a, *b]).map(|p| ant_point(p, k, canvas)).collect();
assert!(points.iter().all(|p| (0.0..=3301.0).contains(&p[0]) && (0.0..=60.0).contains(&p[1])), "{points:?}");
assert!(points.iter().any(|p| p[0] == 3301.0) && points.iter().any(|p| p[1] == 60.0), "the right and bottom border: {points:?}");
}
/// A document edit while the workspace is open drops the old preview's ants with its image.
#[test]
fn a_document_edit_clears_the_old_ants() {
let mut app = app_with_selection();
open(&mut app).unwrap();
ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true}));
upload(&mut app, &egui::Context::default());
assert!(!ant_outline(ants_mut(&mut app), (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_empty());
app.session
.edit("paint", |doc, _| {
doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
follow_revision(&mut app);
assert!(ws(&app).preview.ants.is_none());
}
/// With nothing selected the Marching Ants view draws no ants, and drawing it doesn't panic.
#[test]
fn marching_ants_without_a_selection_draw_nothing() {
let empty = Surface::new(photocraft_color::PixelFormat::GRAY8);
assert!(ant_outline(&mut shown_ants(empty, Rect::new(0, 0, 100, 100), 1), (1.0, [0.0, 0.0, 100.0, 100.0]), true).is_empty());
let mut app = app_with_selection();
open(&mut app).unwrap();
ui(&mut app, json!({"clearSelection": true, "view": "marchingAnts", "waitPreview": true}));
assert_eq!(ws(&app).describe()["selectedProxyPixels"].as_u64(), Some(0));
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
show(app, &ctx);
}
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(4);
let w = h.state().distort.select_mask.as_ref().unwrap();
let outline = w.preview.ants.as_ref().and_then(|a| a.outline.as_ref());
assert!(outline.is_some_and(|(_, segs)| segs.is_empty()), "traced, and nothing to outline");
}
type GpuHarness = egui_kittest::Harness<'static, PhotocraftApp>;
/// A rendered frame: RGBA8, device pixels.
struct Frame {
w: u32,
h: u32,
px: Vec<u8>,
}
impl Frame {
fn luma(&self, x: i64, y: i64) -> Option<u8> {
if x < 0 || y < 0 || x >= i64::from(self.w) || y >= i64::from(self.h) {
return None;
}
let i = (y as usize * self.w as usize + x as usize) * 4;
let p = self.px.get(i..i + 3)?;
Some(((u16::from(p[0]) * 3 + u16::from(p[1]) * 6 + u16::from(p[2])) / 10) as u8)
}
}
/// The workspace open on a white 400 × 300 document with (100, 80)–(300, 220) selected, in the
/// Marching Ants view at 100 %, on an offscreen wgpu harness, and the frame time the workspace
/// opened at (after three frames); `None` without a GPU adapter.
fn ants_harness(ppp: f32, step_dt: f32) -> Option<(GpuHarness, f64)> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 80, "width": 200, "height": 140})).unwrap();
app.sync_views();
// `wgpu()` creates the render state and panics when no adapter is found.
let builder = std::panic::catch_unwind(|| {
egui_kittest::Harness::<PhotocraftApp>::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(ppp).with_step_dt(step_dt).wgpu()
})
.ok()?;
let mut h = builder.build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
show(app, &ctx);
}
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
// The canvas's clock runs a few frames before the dialog opens, so a clock of the dialog's
// own, started when it opens, would be out of phase with it.
h.run_steps(3);
let opened = h.ctx.input(|i| i.time);
open(h.state_mut()).unwrap();
ui(h.state_mut(), json!({"view": "marchingAnts", "waitPreview": true}));
h.run_steps(4);
let w = h.state_mut().distort.select_mask.as_mut().unwrap();
(w.zoom, w.center) = (1.0, [200.0, 150.0]);
h.run_steps(2);
Some((h, opened))
}
fn frame(h: &mut GpuHarness) -> Frame {
let img = h.render().unwrap();
Frame { w: img.width(), h: img.height(), px: img.into_raw() }
}
/// Device pixel of document point `p`.
fn device(h: &GpuHarness, ppp: f32, p: [f64; 2]) -> (i64, i64) {
let w = h.state().distort.select_mask.as_ref().unwrap();
let (area, _) = w.view_area.unwrap();
let s = View { area, zoom: w.zoom, center: w.center }.to_screen(p) * ppp;
(s.x.round() as i64, s.y.round() as i64)
}
/// Along the edge from device pixel `a` to `b` (12 px in from each end): the offsets across it
/// (±6) of the dark pixels at each step, and how many pixels of the band are grey.
fn scan(img: &Frame, a: (i64, i64), b: (i64, i64)) -> (Vec<Vec<i64>>, usize) {
let vertical = a.0 == b.0;
let (lo, hi) = if vertical { (a.1.min(b.1), a.1.max(b.1)) } else { (a.0.min(b.0), a.0.max(b.0)) };
let mut across = Vec::new();
let mut greys = 0;
for t in lo + 12..hi - 12 {
let mut dark = Vec::new();
for o in -6..=6 {
let (x, y) = if vertical { (a.0 + o, t) } else { (t, a.1 + o) };
let l = img.luma(x, y).unwrap_or(255);
if l < 64 {
dark.push(o);
}
if (24..232).contains(&l) {
greys += 1;
}
}
across.push(dark);
}
(across, greys)
}
/// #10506: the Marching Ants view draws the canvas's ants: every edge `w` device px thick, crisp
/// black and white, dashes of 4·w px. They were 1-point antialiased lines, grey and uneven.
#[test]
fn select_and_mask_ants_match_the_canvas() {
let _gpu = photocraft_testkit::gpu_lock();
for ppp in [1.0f32, 1.25] {
let Some((mut h, _)) = ants_harness(ppp, 1.0 / 60.0) else { return };
let img = frame(&mut h);
let w = ppp.ceil() as usize;
let [tl, tr, br, bl] = [[100.0, 80.0], [300.0, 80.0], [300.0, 220.0], [100.0, 220.0]].map(|p| device(&h, ppp, p));
for (name, (a, b)) in [("top", (tl, tr)), ("right", (tr, br)), ("bottom", (bl, br)), ("left", (tl, bl))] {
let (across, greys) = scan(&img, a, b);
assert_eq!(greys, 0, "@{ppp}x {name}: crisp black and white");
let max = across.iter().map(Vec::len).max().unwrap_or(0);
assert_eq!(max, w, "@{ppp}x {name}: {w} px thick");
let dark: usize = across.iter().map(Vec::len).sum();
let frac = dark as f32 / (across.len() * w) as f32;
assert!((0.45..=0.55).contains(&frac), "@{ppp}x {name}: {frac:.2} of the line is black");
let rows: std::collections::BTreeSet<i64> = across.iter().flatten().copied().collect();
for row in rows {
let mut runs = vec![0usize];
for d in &across {
match (d.contains(&row), runs.last_mut()) {
(true, Some(n)) => *n += 1,
(false, Some(0)) => {}
_ => runs.push(0),
}
}
let inner = runs.get(1..runs.len().saturating_sub(1)).unwrap_or(&[]);
assert!(inner.iter().all(|&n| n == 4 * w), "@{ppp}x {name} row {row}: dashes {runs:?}, want {} px", 4 * w);
}
}
}
}
/// #10506: the ants march along the edge. They used to swap black and white 8 times a second.
#[test]
fn select_and_mask_ants_march_rather_than_blink() {
let _gpu = photocraft_testkit::gpu_lock();
let Some((mut h, _)) = ants_harness(1.0, 0.125) else { return };
let row = |h: &mut GpuHarness| {
let img = frame(h);
let ((x0, y), (x1, _)) = (device(h, 1.0, [100.0, 80.0]), device(h, 1.0, [300.0, 80.0]));
// The darkest row of the band along the top edge (grey counts as dark here, so an
// antialiased line is still read).
let line = |dy: i64| (x0 + 12..x1 - 12).map(|x| img.luma(x, y + dy).is_some_and(|l| l < 160)).collect::<Vec<bool>>();
let best = (-2..=2).max_by_key(|dy| line(*dy).iter().filter(|b| **b).count()).unwrap();
(line(best), h.ctx.input(|i| i.time))
};
let (a, ta) = row(&mut h);
h.step();
let (b, tb) = row(&mut h);
assert!((tb - ta - 0.125).abs() < 1e-6, "frames {ta} and {tb}");
// How far the canvas's ants march between the two frames.
let ((pa, period), (pb, _)) = (crate::ants::Style::new(1.0, ta).march(), crate::ants::Style::new(1.0, tb).march());
let shift = (pb - pa).rem_euclid(period) as usize;
assert!(shift > 0, "the pattern moves");
let dark = a.iter().filter(|d| **d).count();
assert!((a.len() * 2..=a.len() * 8).contains(&(dark * 10)), "the edge has dashes: {dark} of {} px dark", a.len());
let n = b.len() - shift;
let shifted = (0..n).filter(|&i| b[i] != a[i + shift]).count();
let inverted = (0..n).filter(|&i| b[i] != a[i]).count();
assert!(shifted * 10 < n, "the dashes shift by {shift} px: {shifted} of {n} pixels don't");
assert!(inverted * 10 < n * 9, "black and white don't swap: {inverted} of {n} pixels changed");
}
/// #10506: at 100 % and 200 % the dialog's ants are the canvas's ants at the frame's time: every
/// pixel of the top edge's band is black exactly where `ants::Style::new(ppp, time)` puts a dash.
/// The dialog reads the same frame clock as the canvas, so the pattern doesn't restart when it
/// opens; and it is fixed to the screen, so the two line up.
#[test]
fn select_and_mask_ants_have_the_canvas_phase() {
let _gpu = photocraft_testkit::gpu_lock();
for ppp in [1.0f32, 2.0] {
// 0.31 s steps, so the march has a phase that isn't zero or a whole dash at the frame, nor
// zero when the dialog opens.
let Some((mut h, opened)) = ants_harness(ppp, 0.31) else { return };
// A clock restarted when the dialog opened would be off by the canvas's phase then.
let (at_open, period) = crate::ants::Style::new(ppp, opened).march();
assert!(at_open.rem_euclid(period) != 0, "@{ppp}x: phase {at_open} when the dialog opened at {opened} s");
let img = frame(&mut h);
let time = h.ctx.input(|i| i.time);
let (phase, period) = crate::ants::Style::new(ppp, time).march();
let (dash, w) = (period / 2, period / 8);
assert_eq!(w, ppp.ceil() as i64);
assert!(phase % dash != 0, "@{ppp}x: phase {phase} at {time} s");
let ((x0, ay), (x1, _)) = (device(&h, ppp, [100.0, 80.0]), device(&h, ppp, [300.0, 80.0]));
let mut wrong = Vec::new();
for y in ay - w / 2..ay - w / 2 + w {
for x in x0 + 12..x1 - 12 {
let black = (x + w * y + phase).rem_euclid(period) < dash;
let l = img.luma(x, y).unwrap_or(128);
if (l < 64) != black || (24..232).contains(&l) {
wrong.push((x, y, l));
}
}
}
assert!(wrong.is_empty(), "@{ppp}x phase {phase}: {} pixels differ from the canvas's ants, first {:?}", wrong.len(), wrong.first());
}
}