Merge pull request #15656 from aiongg/test-speed-15639-15640

Tests: land #15639, #15640 and #15643 on current main
This commit is contained in:
aiongg authored and GitHub committed 2026-11-18 15:37:09 -05:00
commit 542e23daf4
14 files changed
+274 -162

No files matched your search

@@ -36,12 +36,14 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() {
let Some(rs) = render_state() else { return };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.set_wgpu(rs);
app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap();
// Half the 1024 × 768 canvas these views were first written for (see `check_blend_viewport`): `a` still runs off
// the right edge and `b` still lies apart from it.
app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap();
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
let ctx = app.ctx().clone();
let a = DRect::new(724, 200, 1324, 500);
let b = DRect::new(0, 200, 300, 500);
let a = DRect::new(362, 100, 662, 250);
let b = DRect::new(0, 100, 150, 250);
assert!(ensure_gpu(&mut app, &ctx, 0, a, None));
app.ui.view.pattern_preview = true;
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply));
@@ -136,7 +138,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
let Some(rs) = render_state() else { return };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.set_wgpu(rs);
app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap();
// Every view and count below is half of the 1024 × 768 fixture first used: the clip to the view
// (`blend_preview::clip_damage`) and the catch-up (`blend_preview::uncovered`) are rectangle arithmetic with no
// size threshold, and the canvas stays far below the background redraw's (that case is
// `blend_hover_during_background_redraw_restores_committed_pixels`). The whole-canvas pixel checks cost a quarter.
app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap();
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
if cpu_fallback {
@@ -150,7 +156,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
layers.push(photocraft_doc::LayerId(other));
}
let ctx = app.ctx().clone();
let visible = DRect::new(256, 256, 512, 512);
let visible = DRect::new(128, 128, 256, 256);
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
assert!(app.redraws.is_empty(), "small fixture must finish synchronously");
if cpu_fallback {
@@ -161,23 +167,23 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
let original = gpu.read_texels(id.0).unwrap();
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply));
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 256 * 256, app.perf.gpu_info);
assert_eq!(app.perf.last_refresh_px, 256 * 256, "hover must not recomposite offscreen pixels of a full-canvas layer");
println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 128 * 128, app.perf.gpu_info);
assert_eq!(app.perf.last_refresh_px, 128 * 128, "hover must not recomposite offscreen pixels of a full-canvas layer");
assert_visible_pixels(&mut app, visible);
app.perf.last_refresh_px = 0;
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture");
let zoomed_out = DRect::new(128, 128, 640, 640);
let zoomed_out = DRect::new(64, 64, 320, 320);
assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None));
assert_eq!(app.perf.last_refresh_px, 512 * 512, "zooming out catches up the larger visible area");
let panned = DRect::new(640, 256, 896, 512);
assert_eq!(app.perf.last_refresh_px, 256 * 256, "zooming out catches up the larger visible area");
let panned = DRect::new(320, 128, 448, 256);
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
assert_eq!(app.perf.last_refresh_px, 256 * 256, "newly exposed pixels must catch up without a mode change");
assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change");
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen));
assert!(ensure_gpu(&mut app, &ctx, 0, panned, None));
assert_eq!(app.perf.last_refresh_px, 256 * 256);
assert_eq!(app.perf.last_refresh_px, 128 * 128);
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
assert_eq!(app.perf.last_refresh_px, 256 * 256, "returning view must show the current mode");
assert_eq!(app.perf.last_refresh_px, 128 * 128, "returning view must show the current mode");
assert_visible_pixels(&mut app, visible);
assert_visible_pixels(&mut app, panned);
crate::blend_preview::hover(&mut app, &layers, None);
@@ -189,7 +195,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
assert!(ensure_gpu(&mut app, &ctx, 0, visible, None));
let bounds = app.session.active().unwrap().doc.bounds();
assert_visible_pixels(&mut app, bounds);
app.run("file.new", json!({"width":1024,"height":768,"background":"white"})).unwrap();
app.run("file.new", json!({"width":512,"height":384,"background":"white"})).unwrap();
assert!(ensure_gpu(&mut app, &ctx, 1, visible, None));
app.session.set_active(0);
app.sync_views();
@@ -125,7 +125,11 @@ fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) {
fn check_mips(gpu: &GpuCanvas) {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for (w, h) in [(1791, 1083), (513, 1), (1, 513)] {
// 767 × 431 is a single tile (`DEFAULT_TILE`) with odd sides down the chain (767, 383, 191, 95 and 431,
// 215, 107, 53), and its levels 1 and 2 are over `WHOLE_MIP_SIDE` (128), so the patch below redraws two
// levels by their damage (`mip_damage`) before the chain is redrawn whole: the paths 1791 × 1083 took, at
// a sixth of the pixels. The larger driver case stays in `partial_updates_match_a_full_rebuild_at_every_mip_level`.
for (w, h) in [(767, 431), (513, 1), (1, 513)] {
let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]);
// Reusing the key also covers replacing textures after a size or depth change.
gpu.upload_buffer_full(1, &full, depth);
@@ -97,8 +97,9 @@ fn drag(h: &mut Harness<'_, Box<PhotocraftApp>>, from: Pos2, to: Pos2) {
h.run_steps(1);
h.drag_at(from);
h.run_steps(1);
for i in 1..=6 {
h.hover_at(from + (to - from) * (i as f32 / 6.0));
// Three moves give the gesture several previews before its one commit, which is what the history check needs.
for i in 1..=3 {
h.hover_at(from + (to - from) * (i as f32 / 3.0));
h.run_steps(1);
}
h.drop_at(to);
@@ -137,8 +138,21 @@ fn sliders(h: &Harness<'_, Box<PhotocraftApp>>) -> Vec<Rect> {
#[test]
fn every_adjustment_layer_edits_through_properties() {
for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("gray", 8), ("cmyk", 8), ("lab", 16)] {
for kind in ALL_KINDS {
let mut h = app_harness(kind, mode, depth);
// One app per document setting, not one per kind: each kind deletes the previous kind's layer and adds its
// own over the same two-tone background, so its editor opens on the stack a fresh app had (the Properties
// session is per layer, `PropertiesAdjust::new`). Every kind still runs in every mode and depth: the
// composite of each adjustment differs per mode and depth, and no other test runs all of them.
let mut h = app_harness(ALL_KINDS[0], mode, depth);
for (i, kind) in ALL_KINDS.into_iter().enumerate() {
if i > 0 {
let (previous, _) = layer(&h);
h.state_mut().run("layer.delete", json!({"layer": previous.0})).unwrap();
h.state_mut().run(&format!("layer.newAdjustmentLayer.{kind}"), json!({})).unwrap();
// The Properties panel shows the new layer's editor on the next frame; the second leaves its widgets
// laid out for the queries below.
h.run_steps(2);
}
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 2, "{kind} {mode}: the background and this kind's layer");
let (_, before) = layer(&h);
let steps = history_len(&h);
let slider = sliders(&h).first().copied();
+7 -1
View File
@@ -59,6 +59,12 @@ fn the_wheel_over_a_field_steps_it_without_a_click() {
assert_eq!(view(&h), before, "the canvas didn't move");
}
/// Frames a wheel event gets to play out (0.25 s each, the harness's default step). egui's wheel smoothing reaches
/// 90 % in 0.1 s and takes the rest under one point at once, so the smoothed tail of a notch (about 50 points) ends
/// within three frames even at a 0.1 s step; four leave one to spare: the view after
/// them is the one the old forty left.
const TAIL_STEPS: usize = 4;
/// How far a wheel of `delta` lines with `modifiers` over the canvas moves the view, a Smoothing
/// field focused or not, once egui's smoothed scroll has run out. The field isn't stepped.
fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f32, [f32; 2]) {
@@ -78,7 +84,7 @@ fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f3
phase: egui::TouchPhase::Move,
modifiers,
});
h.run_steps(40);
h.run_steps(TAIL_STEPS);
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("10")), "focus {focus}: the field wasn't stepped");
let after = view(&h);
(after.0 / before.0, [after.1[0] - before.1[0], after.1[1] - before.1[1]])
+5 -6
View File
@@ -84,16 +84,17 @@ const GUIDE: egui::CursorIcon = egui::CursorIcon::ResizeHorizontal;
#[test]
fn command_over_a_guide_takes_it_where_command_is_the_move_tool() {
let takes = |tool, latched| (tool, false, latched, true);
// One tool per family (`canvas::tools::family`): whether the guides take ⌘ is decided by family
// (`rulers::moves_with_command`, `tools::takes_command_stand_in`), and the painting family refuses a ⌘ press the
// same way for all its tools (`PaintTool::takes`). Within it, one tool per kind of pointer (`cursor_policy`): the
// Brush's tip with its centre mark, the Clone Stamp's and Quick Selection's tips without one, the Paint Bucket's
// click-tool pointer. The Eraser, Dodge, Spot Healing Brush and Smudge are more Brush-like tips.
let rows = [
takes(Tool::Brush, false),
takes(Tool::Eraser, false),
takes(Tool::Gradient, false),
takes(Tool::PaintBucket, false),
takes(Tool::CloneStamp, false),
takes(Tool::Eyedropper, false),
takes(Tool::Dodge, false),
takes(Tool::SpotHealing, false),
takes(Tool::Smudge, false),
takes(Tool::QuickSelection, false),
takes(Tool::RectMarquee, false),
takes(Tool::Lasso, false),
@@ -102,10 +103,8 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() {
takes(Tool::Frame, false),
takes(Tool::Artboard, false),
takes(Tool::Brush, true),
takes(Tool::Eraser, true),
takes(Tool::RectMarquee, true),
(Tool::Brush, true, false, false),
(Tool::Eraser, true, false, false),
(Tool::Frame, true, false, false),
(Tool::Pen, false, false, false),
(Tool::Hand, false, false, false),
+4 -2
View File
@@ -347,8 +347,10 @@ const CTRL_ALT: Modifiers = Modifiers { alt: true, ctrl: true, shift: false, mac
/// The tools that keep ⌘ for themselves leave the layer alone.
#[test]
fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() {
let moves =
[Tool::Brush, Tool::Eraser, Tool::Gradient, Tool::CloneStamp, Tool::Eyedropper, Tool::Move, Tool::RectMarquee, Tool::EllipseMarquee, Tool::Lasso];
// The Eraser is left out: it is in the Brush's family (`canvas::tools::family`), which refuses a ⌘ press the same
// way for every tool (`PaintTool::takes`); the Elliptical Marquee is the Rectangular one's marquee pass with
// another shape (`selection.rs`, `MarqueeKind`).
let moves = [Tool::Brush, Tool::Gradient, Tool::CloneStamp, Tool::Eyedropper, Tool::Move, Tool::RectMarquee, Tool::Lasso];
for tool in moves {
let mut h = harness(tool);
let id = with_layer(&mut h);
+8 -3
View File
@@ -261,9 +261,14 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() {
h.hover_at(p);
h.run_steps(2);
let d0 = doc_at(&h, p);
// Frames after each notch (0.25 s each, the harness's default step): a notch lands within two (egui's wheel
// smoothing reaches 90 % in 0.1 s and takes the rest under one point at once), and the old clamp pulled the zoom
// back on every frame, so three show it: the zoom and centre
// after them are the ones the old thirty left.
const NOTCH_STEPS: usize = 3;
for _ in 0..14 {
wheel(&h, 1.0, Modifiers::ALT);
h.run_steps(30);
h.run_steps(NOTCH_STEPS);
}
assert_eq!(zoom(&h), max_zoom(), "a notch past the limit lands on it exactly");
let d1 = doc_at(&h, p);
@@ -271,13 +276,13 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() {
let c = h.state().ui.views[0].center;
for _ in 0..4 {
wheel(&h, 1.0, Modifiers::ALT);
h.run_steps(30);
h.run_steps(NOTCH_STEPS);
}
assert_eq!(zoom(&h), max_zoom());
assert_eq!(h.state().ui.views[0].center, c, "at the limit the image doesn't move");
// One notch back: 12800 / 1.1, still around the pointer.
wheel(&h, -1.0, Modifiers::ALT);
h.run_steps(30);
h.run_steps(NOTCH_STEPS);
assert!((zoom(&h) - max_zoom() / 1.1).abs() < 1e-2, "{}", zoom(&h));
let d2 = doc_at(&h, p);
assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}");
@@ -51,13 +51,25 @@ fn sequence(letter: char, steps: usize) -> Vec<Tool> {
.collect()
}
/// [`shift_press`] with two frames instead of three: the runtime takes the key in the first and the app picks the
/// tool it fired in the second (`shortcut_dispatch::pick_tool`); the third only drew the toolbar again.
fn quick_shift_press(h: &mut Harness<'static, Box<PhotocraftApp>>, key: Key) {
h.input_mut().events.extend([
egui::Event::ModifiersChanged(Modifiers::SHIFT),
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT },
egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT },
egui::Event::ModifiersChanged(Modifiers::NONE),
]);
h.run_steps(2);
}
#[test]
fn from_every_tool_shift_letter_lands_on_the_next_tool_in_toolbar_order() {
let mut h = app();
for (letter, group) in groups() {
for (i, from) in group.iter().enumerate() {
h.state_mut().ui.tool = *from;
shift_press(&mut h, key_for(letter));
quick_shift_press(&mut h, key_for(letter));
let want = group[(i + 1) % group.len()];
assert_eq!(h.state().ui.tool, want, "Shift+{letter} from {from:?}");
}
@@ -2028,7 +2028,11 @@ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() {
let scaled = Affine { m: [1.5, 0.0, 0.0, 0.75, 300.0, 300.0] };
let rotated = Affine { m: [1.2 * 0.94, 1.2 * 0.342, -1.2 * 0.342, 1.2 * 0.94, 300.0, 300.0] };
for ppp in [1.0, 2.0] {
for zoom in [0.25f32, 0.5, 1.0, 2.0] {
// The ends of the range only: the frame's handles and their grab area are screen-space parts of the
// framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and the snap reach is a screen distance,
// so the zoom only scales the view, with no step in between. 25 % and 200 % at 1x and 2x span 12.5 % to
// 200 % in points, which holds 50 % and 100 %.
for zoom in [0.25f32, 2.0] {
for (name, tf) in [("plain", None), ("scaled", Some(scaled)), ("rotated", Some(rotated))] {
let mut app = new_app();
assert!(app.ui.extras.snap, "snapping is on by default");
@@ -229,40 +229,46 @@ fn clipped_target_preview_composites_on_the_gpu_like_the_command() {
let Some((device, queue, mut comp)) = gpu() else { return };
let (tol_gpu, tol_cmd) = (2.0 / 255.0, 2.5 / 255.0);
let mut worst = 0.0f32;
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for selection in [false, true] {
let (doc, target) = clipped_document(mode, depth, selection);
for kind in photocraft_ui_egui::adjust_editors::KINDS {
let params = sample(kind);
let preview = match preview_document(&doc, target, kind, &params) {
Ok(p) => p,
Err(e) => {
// Only grayscale kinds that make colour keep the CPU proxy preview.
assert_eq!(mode, ColorMode::Grayscale, "{kind}: {e}");
assert!(GRAY_COLOUR.contains(&kind), "{kind} {mode:?}: unexpected preview error: {e}");
continue;
}
};
assert!(preview.layer(PREVIEW_LAYER).is_some());
assert!(preview.layer(target).unwrap().is_group(), "the clipped target is isolated");
let what = format!("{kind} {mode:?} {depth:?} selection {selection}");
let b = preview.bounds();
let skip = if matches!(kind, "threshold" | "posterize") && depth != SampleType::U8 { (b.width() * b.height()) as usize / 100 } else { 0 };
let on_gpu = render_to_vec(&mut comp, &device, &queue, &preview, b).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let on_cpu = photocraft_compose::render(&preview, b).into_px();
let d = max_diff(&on_gpu, &on_cpu, skip);
assert!(d <= tol_gpu, "{what}: GPU vs CPU {:.2}/255", d * 255.0);
let mut s = photocraft_engine::Session::new();
s.add_document(doc.clone(), None);
s.select_layer(target).unwrap();
s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap();
let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px();
let d = max_diff(&on_gpu, &cmd, skip);
worst = worst.max(d);
assert!(d <= tol_cmd, "{what}: GPU preview vs command {:.2}/255", d * 255.0);
// Each kind runs once per mode at one (depth, selection) pair, rather than kind x depth x selection: this test's
// own case is the isolating group, which `base_document` builds before it knows the kind (`with_settings` only
// swaps the preview layer's adjustment), and the GPU planner applies a clipped adjustment through the same
// `atop_any` / `adjust` passes whatever the group around it (`crates/gpu/src/plan/planner.rs`). The kind x depth x
// selection x mode matrix of those passes is `preview_layer_composites_on_the_gpu_like_the_command`. Cycling the
// pairs over the kinds still runs every depth with and without a selection in both modes (in Grayscale among the
// kinds that keep gray, too).
const PAIRS: [(SampleType, bool); 6] =
[(SampleType::U8, false), (SampleType::U16, true), (SampleType::F32, false), (SampleType::U8, true), (SampleType::U16, false), (SampleType::F32, true)];
for (mode, offset) in [(ColorMode::Rgb, 0), (ColorMode::Grayscale, 3)] {
for (i, kind) in photocraft_ui_egui::adjust_editors::KINDS.into_iter().enumerate() {
let (depth, selection) = PAIRS[(i + offset) % PAIRS.len()];
let (doc, target) = clipped_document(mode, depth, selection);
let params = sample(kind);
let preview = match preview_document(&doc, target, kind, &params) {
Ok(p) => p,
Err(e) => {
// Only grayscale kinds that make colour keep the CPU proxy preview.
assert_eq!(mode, ColorMode::Grayscale, "{kind}: {e}");
assert!(GRAY_COLOUR.contains(&kind), "{kind} {mode:?}: unexpected preview error: {e}");
continue;
}
}
};
assert!(preview.layer(PREVIEW_LAYER).is_some());
assert!(preview.layer(target).unwrap().is_group(), "the clipped target is isolated");
let what = format!("{kind} {mode:?} {depth:?} selection {selection}");
let b = preview.bounds();
let skip = if matches!(kind, "threshold" | "posterize") && depth != SampleType::U8 { (b.width() * b.height()) as usize / 100 } else { 0 };
let on_gpu = render_to_vec(&mut comp, &device, &queue, &preview, b).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let on_cpu = photocraft_compose::render(&preview, b).into_px();
let d = max_diff(&on_gpu, &on_cpu, skip);
assert!(d <= tol_gpu, "{what}: GPU vs CPU {:.2}/255", d * 255.0);
let mut s = photocraft_engine::Session::new();
s.add_document(doc.clone(), None);
s.select_layer(target).unwrap();
s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap();
let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px();
let d = max_diff(&on_gpu, &cmd, skip);
worst = worst.max(d);
assert!(d <= tol_cmd, "{what}: GPU preview vs command {:.2}/255", d * 255.0);
}
}
eprintln!("worst clipped-target GPU preview vs command: {:.3}/255", worst * 255.0);
@@ -108,12 +108,13 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() {
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut h) = harness() else { return };
h.run_steps(4);
for (width, height, zoom, center, degrees, factor) in [
(400, 240, 1.0, [160.0, 90.0], 45.0, 1),
(400, 240, 1.0, [160.0, 90.0], -45.0, 1),
(400, 240, 1.0, [160.0, 90.0], 90.0, 1),
(3000, 1800, 0.12, [1350.0, 825.0], 45.0, 2),
] {
// The canvas places a size-changing preview by its size alone (`canvas/gpu_picture.rs`: `growth` and
// `preview_bounds` from `preview_size`): 45° grows both sides, 90° grows one and shrinks the other, and the large
// document runs the reduced proxy. -45° gives 45°'s size, so it repeated the same placement; the direction of
// the rotation itself is the engine's (its `image.rotation.arbitrary` tests with `"direction": "ccw"`).
for (width, height, zoom, center, degrees, factor) in
[(400, 240, 1.0, [160.0, 90.0], 45.0, 1), (400, 240, 1.0, [160.0, 90.0], 90.0, 1), (3000, 1800, 0.12, [1350.0, 825.0], 45.0, 2)]
{
setup(&mut h, width, height, zoom, center);
assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor);
let id = open(&mut h);
@@ -289,15 +289,31 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() {
}
}
/// The depths [`pixel_grid_is_solid_and_visible_at_scale`] runs at. Both canvases draw the grid with the same
/// `PixelGrid` over a CPU composite (`PhotoComposite`: compose's f32 render, `canvas/raster_source.rs` `read`; see
/// `grid_prep` and "The grid is drawn over the picture" in `canvas/document_display.rs`), and the fills 0 and 1 are
/// exact at every depth, so the grid reads the same pixels at 8, 16 and 32 bits. Depth reaches only the picture under
/// it, which the `inside` assertion reads: on the GPU canvas its texture (`Rgba8Unorm` for 8-bit, `Rgba16Float` for
/// 16/32-bit, see `canvas_16f.rs`). So every canvas and scale runs 8-bit, and the GPU canvas adds 16-bit at 1x and
/// 32-bit at 2x.
fn grid_depths(gpu: bool, ppp: f32) -> Vec<photocraft_color::SampleType> {
use photocraft_color::SampleType;
match (gpu, ppp > 1.0) {
(true, false) => vec![SampleType::U8, SampleType::U16],
(true, true) => vec![SampleType::U8, SampleType::F32],
(false, _) => vec![SampleType::U8],
}
}
fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) {
let _gpu = photocraft_testkit::gpu_lock();
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_color::{ColorMode, PixelFormat};
use photocraft_doc::{Document, Layer, LayerContent, Size};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
let Some(mut h) = harness_with_scale(gpu, ppp) else { return };
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for depth in grid_depths(gpu, ppp) {
for v in [0.0, 1.0] {
let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth);
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true));
@@ -8,7 +8,7 @@
//!
//! They drive the real app offscreen on wgpu with real egui pointer events (press, then a series
//! of moves past the click distance), render the frame mid-drag and look at the pixels along the
//! preview's edges on white and on black documents. They also check the preview follows every
//! preview's edges on a mid-grey document, for both colours of the ants. They also check the preview follows every
//! move (each move's frame shows the new outline) and that the animated ants keep frames coming
//! while the pointer is held still. Skips when no GPU adapter exists (like `live_stroke_canvas.rs`).
@@ -169,11 +169,17 @@ fn coverage_along(img: &Image, ppp: f32, pts: &[Pos2], test: impl Fn(u8) -> bool
hits as f32 / samples.max(1) as f32
}
/// Ink that contrasts with `background`: dark on white, light on black. The 1 px ants are half
/// antialiasing where the curve crosses pixel columns, so a quarter of the luma range suffices.
fn ink(background: &str) -> impl Fn(u8) -> bool {
let white = background == "white";
move |l| if white { l < 192 } else { l > 63 }
/// The document the marquee tests drag over: the grey halfway between the ants' two colours (luma 102 and 255 in the
/// default theme), so both contrast with it.
const GREY: &str = "#b3b3b3";
/// An ink's name and whether a luma shows it.
type Ink = (&'static str, fn(u8) -> bool);
/// The two inks of the ants over [`GREY`] (luma 179): darker and lighter. The 1 px ants are half antialiasing where
/// the curve crosses pixel columns (luma 140 and 217 there), so the thresholds sit just past the grey either way.
fn inks() -> [Ink; 2] {
[("dark", |l| l < 150), ("light", |l| l > 208)]
}
/// The four edges of the document rectangle `[x0, y0]`–`[x1, y1]` on screen.
@@ -186,22 +192,34 @@ fn edges(h: &Harness, a: [f32; 2], b: [f32; 2]) -> [(Pos2, Pos2); 4] {
#[test]
fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() {
let _gpu = photocraft_testkit::gpu_lock();
for ppp in [1.0, 2.0] {
let Some(mut h) = harness(ppp) else { return };
// One mid-grey document instead of a white and a black one: the ants are a band of the marquee colour with dashes
// of the halo colour, fixed colours that never depend on the pixels under them (the framework's `marching_ants`,
// which the marquee tool paints through `ToolContext::marching_ants`). White on white (#253) hid the light ants
// and black would hide the dark ones; over grey the test sees both inks at once, so an outline missing either
// colour fails here as it failed on one of the two documents. (The name is the one CI's slow-test order lists.)
// One harness for both scales: the app derives its scale from the window's native one every frame
// (`prefs_ui/appearance.rs` `interface_zoom`), so the 2x pass sets that, as a move to a HiDPI display does.
let Some(mut h) = harness(1.0) else { return };
h.run_steps(4);
for ppp in [1.0f32, 2.0] {
if let Some(root) = h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT) {
root.native_pixels_per_point = Some(ppp);
}
h.run_steps(4);
assert_eq!(h.ctx.pixels_per_point(), ppp, "the harness runs at {ppp}x");
for tool in ["rectMarquee", "ellipseMarquee"] {
for bg in ["white", "black"] {
setup(&mut h, bg, tool);
let (a, b) = ([100.0, 80.0], [300.0, 220.0]);
let before = render(&mut h);
drag_to(&mut h, a, b);
let img = render(&mut h);
setup(&mut h, GREY, tool);
let (a, b) = ([100.0, 80.0], [300.0, 220.0]);
let before = render(&mut h);
drag_to(&mut h, a, b);
let img = render(&mut h);
for (ink, test) in inks() {
if tool == "rectMarquee" {
for (i, (p, q)) in edges(&h, a, b).into_iter().enumerate() {
let was = coverage(&before, ppp, p, q, ink(bg));
let now = coverage(&img, ppp, p, q, ink(bg));
// Ants: half the dashes contrast with the pixels under them.
assert!(was < 0.05 && now > 0.3, "{tool} on {bg} @{ppp}x, edge {i}: {was:.2} → {now:.2} contrasting");
let was = coverage(&before, ppp, p, q, test);
let now = coverage(&img, ppp, p, q, test);
// Ants: half the dashes are each ink.
assert!(was < 0.05 && now > 0.3, "{tool} @{ppp}x, edge {i}: {was:.2} → {now:.2} {ink}");
}
} else {
// The ellipse touches its box at the edge midpoints. Walk the curve around
@@ -220,21 +238,24 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() {
screen(&h, (cx as f64 + rx as f64 * t.cos()) as f32, (cy as f64 + ry as f64 * t.sin()) as f32)
})
.collect();
let now = coverage_along(&img, ppp, &pts, ink(bg));
assert!(now > 0.3, "{tool} on {bg} @{ppp}x at ({mx}, {my}): {now:.2} contrasting");
let was = coverage_along(&before, ppp, &pts, test);
let now = coverage_along(&img, ppp, &pts, test);
assert!(was < 0.05 && now > 0.3, "{tool} @{ppp}x at ({mx}, {my}): {was:.2} → {now:.2} {ink}");
}
}
// Each move's frame shows the outline where the pointer is now (no stale frame).
pointer_move(&mut h, 340.0, 250.0);
let img = render(&mut h);
if tool == "rectMarquee" {
let [top, right, ..] = edges(&h, a, [340.0, 250.0]);
assert!(coverage(&img, ppp, top.0, top.1, ink(bg)) > 0.3, "{tool} {bg} @{ppp}x: top edge follows the pointer");
assert!(coverage(&img, ppp, right.0, right.1, ink(bg)) > 0.3, "{tool} {bg} @{ppp}x: right edge follows the pointer");
}
button(&mut h, 340.0, 250.0, false);
h.run_steps(2);
}
// Each move's frame shows the outline where the pointer is now (no stale frame).
pointer_move(&mut h, 340.0, 250.0);
let img = render(&mut h);
if tool == "rectMarquee" {
let [top, right, ..] = edges(&h, a, [340.0, 250.0]);
for (ink, test) in inks() {
assert!(coverage(&img, ppp, top.0, top.1, test) > 0.3, "{tool} @{ppp}x: top edge follows the pointer ({ink})");
assert!(coverage(&img, ppp, right.0, right.1, test) > 0.3, "{tool} @{ppp}x: right edge follows the pointer ({ink})");
}
}
button(&mut h, 340.0, 250.0, false);
h.run_steps(2);
}
}
}
@@ -19,10 +19,15 @@ type Pixels = Vec<[u8; 4]>;
fn raw_pointer_brush_and_mixer_pixels_appear_in_the_input_frame() {
use photocraft_ui_egui::state::Tool;
let _gpu = photocraft_testkit::gpu_lock();
// One harness for every case: each case closes what the last one left open and sets its own tool, view flip,
// brush and colours, so a fresh harness per case only repeated the wgpu setup.
let Some(mut h) = harness() else { return };
for flip in [false, true] {
for tool in [Tool::Brush, Tool::MixerBrush] {
let Some(mut h) = harness() else { return };
let app = h.state_mut();
while app.session.active().is_some() {
app.run("file.close", json!({"discard": true})).unwrap();
}
app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap();
app.run("edit.fill", json!({"color":"#2040df"})).unwrap();
app.run("tools.setColors", json!({"foreground":"#ef2000"})).unwrap();
@@ -202,11 +207,14 @@ fn the_canvas_shows_the_committed_stroke_part(part: usize) {
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut h) = harness() else { return };
h.run_steps(4);
// Every zoom once, with every smoothing amount among them, rather than zoom x smoothing: the canvas branches on
// the zoom (reduced, 1:1 and magnified pictures) and only on whether smoothing is on (a held pointer repeats its
// point while smoothing catches up, `canvas/strokes.rs`); that the live stroke equals the commit at
// every zoom and smoothing amount is the engine's `live_stroke_equals_the_commit_at_every_zoom_with_smoothing`
// (`brush_cmds/tests.rs`). The zoom 4, smoothing 0.1 case is the base the cases after it change one thing of.
let mut cases = Vec::new();
for zoom in [0.5, 1.0, 4.0, 12.0] {
for smoothing in [0.0, 0.1, 0.5] {
cases.push(Case { zoom, smoothing, hardness: 0.0, depth: 8, pressure: false, flip: false });
}
for (zoom, smoothing) in [(0.5, 0.5), (1.0, 0.0), (4.0, 0.1), (12.0, 0.0)] {
cases.push(Case { zoom, smoothing, hardness: 0.0, depth: 8, pressure: false, flip: false });
}
cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 1.0, depth: 8, pressure: false, flip: false });
cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 16, pressure: false, flip: false });
@@ -214,7 +222,8 @@ fn the_canvas_shows_the_committed_stroke_part(part: usize) {
cases.push(Case { zoom: 4.0, smoothing: 0.1, hardness: 0.0, depth: 8, pressure: false, flip: true });
cases.push(Case { zoom: 12.0, smoothing: 0.5, hardness: 0.0, depth: 16, pressure: true, flip: true });
let mut gpu_seen = false;
for c in cases.into_iter().skip(part).step_by(4) {
// One step per `_part_N` test, so every case runs in exactly one of them.
for c in cases.into_iter().skip(part).step_by(3) {
let (before, drawing, done, gpu) = frames(&mut h, c);
gpu_seen |= gpu;
// The stroke is on screen while drawing (not a blank canvas compared with a blank one)…
@@ -248,60 +257,67 @@ fn the_canvas_shows_the_committed_stroke_part_2() {
fn live_tool_camera_navigation_is_visible_in_the_input_frame() {
use photocraft_ui_egui::state::Tool;
let _gpu = photocraft_testkit::gpu_lock();
// Brush only: no stroke is drawn, and the canvas has no branch on the live tool before a press. Since the canvas
// moved onto the framework it always runs the tools, then shows the picture with the camera of this pass
// (`canvas/document_display.rs` `show`: "The tools run after the controls … and before the picture"); the Mixer
// Brush's own paths (`canvas/paint_tool.rs`, `canvas/strokes.rs`) start at a press, which
// `raw_pointer_brush_and_mixer_pixels_appear_in_the_input_frame` covers. The flip (CPU or GPU picture) and the
// input (pinch zoom or wheel pan) do reach different code, so they stay, on one harness.
let tool = Tool::Brush;
let Some(mut h) = harness() else { return };
for flip in [false, true] {
for tool in [Tool::Brush, Tool::MixerBrush] {
for zoom in [false, true] {
let Some(mut h) = harness() else { return };
let app = h.state_mut();
app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap();
app.run("paint.stroke", json!({"points":[[40,40],[240,160]],"size":30,"hardness":1.0,"color":"#2050df"})).unwrap();
app.run("prefs.set", json!({"values":{"tools.overscroll":true,"general.animatedZoom":false,"general.zoomWithScrollWheel":false}})).unwrap();
app.ui.tool = tool;
app.ui.view.flip_horizontal = flip;
app.sync_views();
h.run_steps(4);
control(&mut h, "ui.set", json!({"zoom":1.0,"center":[150,100]}));
let at = h.state().last_canvas_rect.center() + egui::vec2(30.0, 10.0);
h.hover_at(at);
h.run_steps(2);
let before = h.state().ui.views[0].clone();
h.input_mut().events.push(if zoom {
egui::Event::Zoom(1.25)
} else {
egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(30.0, 20.0),
modifiers: egui::Modifiers::NONE,
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
}
});
h.step();
let moved = h.state().ui.views[0].clone();
assert!(if zoom { moved.zoom != before.zoom } else { moved.center != before.center }, "navigation was applied");
let immediate = h.render().unwrap();
let rect = h.state().last_canvas_rect.shrink(8.0);
h.step();
let settled = h.render().unwrap();
if tool == Tool::MixerBrush
&& flip
&& zoom
&& let Ok(path) = std::env::var("PHOTOCRAFT_NAV_SNAPSHOT")
{
settled.save(path).unwrap();
}
assert_eq!(h.state().ui.views[0].zoom, moved.zoom);
assert_eq!(h.state().ui.views[0].center, moved.center);
let mut diff = 0;
for y in rect.top() as u32..rect.bottom() as u32 {
for x in rect.left() as u32..rect.right() as u32 {
for (a, b) in immediate.get_pixel(x, y).0.into_iter().zip(settled.get_pixel(x, y).0) {
diff = diff.max(a.abs_diff(b));
}
}
}
assert!(diff <= 1, "{tool:?} flip={flip} zoom={zoom}: canvas changes {diff}/255 one frame after navigation");
for zoom in [false, true] {
let app = h.state_mut();
while app.session.active().is_some() {
app.run("file.close", json!({"discard": true})).unwrap();
}
app.run("file.new", json!({"width":300,"height":200,"background":"white"})).unwrap();
app.run("paint.stroke", json!({"points":[[40,40],[240,160]],"size":30,"hardness":1.0,"color":"#2050df"})).unwrap();
app.run("prefs.set", json!({"values":{"tools.overscroll":true,"general.animatedZoom":false,"general.zoomWithScrollWheel":false}})).unwrap();
app.ui.tool = tool;
app.ui.view.flip_horizontal = flip;
app.sync_views();
h.run_steps(4);
control(&mut h, "ui.set", json!({"zoom":1.0,"center":[150,100]}));
let at = h.state().last_canvas_rect.center() + egui::vec2(30.0, 10.0);
h.hover_at(at);
h.run_steps(2);
let before = h.state().ui.views[0].clone();
h.input_mut().events.push(if zoom {
egui::Event::Zoom(1.25)
} else {
egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(30.0, 20.0),
modifiers: egui::Modifiers::NONE,
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
}
});
h.step();
let moved = h.state().ui.views[0].clone();
assert!(if zoom { moved.zoom != before.zoom } else { moved.center != before.center }, "navigation was applied");
let immediate = h.render().unwrap();
let rect = h.state().last_canvas_rect.shrink(8.0);
h.step();
let settled = h.render().unwrap();
if flip
&& zoom
&& let Ok(path) = std::env::var("PHOTOCRAFT_NAV_SNAPSHOT")
{
settled.save(path).unwrap();
}
assert_eq!(h.state().ui.views[0].zoom, moved.zoom);
assert_eq!(h.state().ui.views[0].center, moved.center);
let mut diff = 0;
for y in rect.top() as u32..rect.bottom() as u32 {
for x in rect.left() as u32..rect.right() as u32 {
for (a, b) in immediate.get_pixel(x, y).0.into_iter().zip(settled.get_pixel(x, y).0) {
diff = diff.max(a.abs_diff(b));
}
}
}
assert!(diff <= 1, "{tool:?} flip={flip} zoom={zoom}: canvas changes {diff}/255 one frame after navigation");
}
}
}