diff --git a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs index e3297baeee4..ec81aeb9956 100644 --- a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs @@ -36,24 +36,23 @@ 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); - // 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(); + // One view crosses the right edge; the other sits apart from it. The + // intervening pixels still have to be refreshed when Pattern Preview opens. + app.run("file.new", json!({"width":256,"height":192,"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(362, 100, 662, 250); - let b = DRect::new(0, 100, 150, 250); + let a = DRect::new(181, 50, 331, 125); + let b = DRect::new(0, 50, 75, 125); 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)); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, b); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); app.ui.view.pattern_preview = false; for mode in [BlendMode::Multiply, BlendMode::Screen] { @@ -64,16 +63,16 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together"); - assert_visible_pixels(&mut app, visible.intersect(&bounds)); + assert_visible_pixels(&mut app, &[visible.intersect(&bounds)]); } } // Enabling periodic display during an existing hover must catch up the unseen gap too. app.ui.view.pattern_preview = true; assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } #[test] @@ -96,12 +95,12 @@ fn blend_hover_during_background_redraw_restores_committed_pixels() { let panned = DRect::new(2048, 1024, 2304, 1280); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); - assert_visible_pixels(&mut app, panned); + assert_visible_pixels(&mut app, &[panned]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } fn settle_redraw(app: &mut PhotocraftApp) { @@ -115,19 +114,33 @@ fn settle_redraw(app: &mut PhotocraftApp) { } } -fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) { +fn assert_visible_pixels(app: &mut PhotocraftApp, regions: &[DRect]) { let (doc, _) = display_doc(app, 0); let gpu = app.gpu.clone().unwrap(); - let reference = doc.id.0 ^ (1u64 << 60); let (display, _) = canvas_display(app, &doc, None); - gpu.upload_composite(reference, &doc, display.as_deref()); - let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap(); - let (_, _, want) = gpu.read_texels(reference).unwrap(); - for y in visible.y0..visible.y1 { - for x in visible.x0..visible.x1 { - let index = y as usize * size[0] as usize + x as usize; - for channel in 0..4 { - assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}"); + let format = eframe::wgpu::TextureFormat::Rgba8Unorm; + // Prepare the CPU reference while the GPU can still be drawing. Each requested + // region is compared to the same captured canvas texture. + let references: Vec<_> = regions + .iter() + .map(|®ion| { + assert!(doc.bounds().contains_rect(®ion)); + let reference = photocraft_compose::render(&doc, region); + (region, gpu_canvas::display_texels(format, display.as_deref(), &reference)) + }) + .collect(); + let (actual_format, size, shown) = gpu.read_texels(doc.id.0).expect("read visible canvas"); + assert_eq!(actual_format, format); + assert_eq!(size, [doc.size.width, doc.size.height]); + for (region, expected) in references { + let expected = expected.as_chunks::<4>().0; + for y in region.y0..region.y1 { + for x in region.x0..region.x1 { + let actual = shown[y as usize * size[0] as usize + x as usize]; + let index = ((y - region.y0) as usize) * region.width() as usize + (x - region.x0) as usize; + for (channel, (actual, expected)) in actual.into_iter().zip(expected[index]).enumerate() { + assert!((actual - f32::from(expected) / 255.0).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel {channel}"); + } } } } @@ -138,11 +151,9 @@ 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); - // 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(); + // View clipping and catch-up use rectangles at any size. The visible, + // expanded and disjoint views below still require different refreshes. + app.run("file.new", json!({"width":256,"height":192,"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 { @@ -156,7 +167,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(128, 128, 256, 256); + let visible = DRect::new(64, 64, 128, 128); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); if cpu_fallback { @@ -167,25 +178,24 @@ 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, 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); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 64 * 64, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "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(64, 64, 320, 320); + let zoomed_out = DRect::new(32, 32, 160, 160); assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None)); - 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_eq!(app.perf.last_refresh_px, 128 * 128, "zooming out catches up the larger visible area"); + let panned = DRect::new(160, 64, 224, 128); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change"); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "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, 128 * 128); + assert_eq!(app.perf.last_refresh_px, 64 * 64); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - 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); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "returning view must show the current mode"); + assert_visible_pixels(&mut app, &[visible, panned]); crate::blend_preview::hover(&mut app, &layers, None); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels"); @@ -194,11 +204,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap(); 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":512,"height":384,"background":"white"})).unwrap(); + assert_visible_pixels(&mut app, &[bounds]); + app.run("file.new", json!({"width":256,"height":192,"background":"white"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 1, visible, None)); app.session.set_active(0); app.sync_views(); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } diff --git a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs index 33dca070fe4..851a1ee455e 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs @@ -14,37 +14,48 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec> { let tile = &doc.tiles[0]; let (device, queue) = (&gpu.rs.device, &gpu.rs.queue); let bpp = texel_bytes(doc.format) as usize; - (0..tile.levels.len()) + // Each level starts after a whole number of padded rows, so each copy offset has + // room for its own texels and meets the copy alignment for both canvas formats. + let mut size = 0; + let levels: Vec<_> = (0..tile.levels.len()) .map(|level| { let (w, h) = ((doc.size[0] >> level).max(1), (doc.size[1] >> level).max(1)); let row = (w as usize * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize); - let buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("mip_test_readback"), - size: (row * h as usize) as u64, - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - let mut encoder = device.create_command_encoder(&Default::default()); - encoder.copy_texture_to_buffer( - wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyBufferInfo { - buffer: &buffer, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, - }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - queue.submit([encoder.finish()]); - buffer.slice(..).map_async(wgpu::MapMode::Read, |result| result.unwrap()); - assert!(gpu.health.wait(device, None)); - let data = buffer.slice(..).get_mapped_range().unwrap(); - let mut pixels = Vec::new(); - for y in 0..h as usize { - for x in 0..w as usize { - let offset = y * row + x * bpp; - pixels.push(texel_to_f32(doc.format, &data[offset..offset + bpp])); - } - } - pixels + let offset = size; + size += row * h as usize; + (w, h, row, offset) + }) + .collect(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mip_test_readback"), + size: size as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + for (level, &(w, h, row, offset)) in levels.iter().enumerate() { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: offset as u64, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + } + let submission = queue.submit([encoder.finish()]); + let slice = buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |result| result.expect("map mip readback")); + assert!(gpu.health.wait_idle(device, Some(submission))); + let data = slice.get_mapped_range().expect("read mip snapshot"); + levels + .into_iter() + .map(|(w, h, row, offset)| { + data[offset..offset + row * h as usize] + .chunks_exact(row) + .flat_map(|line| line[..w as usize * bpp].chunks_exact(bpp)) + .map(|texel| texel_to_f32(doc.format, texel)) + .collect() }) .collect() } @@ -124,40 +135,44 @@ 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] { - // 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); - for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { - for pixel in pixels { - assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { - assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - } + use SampleType::{F32, U8, U16}; + // 519 is odd and still gives two damage-redrawn levels above WHOLE_MIP_SIDE + // (259 and 129), followed by whole levels. Both stored formats use this path + // on each backend, and the thin horizontal and vertical cases reach 1 × 1. + // U16 and F32 use the same float texture and mip pipeline for these values. + let depths_and_sizes: &[(SampleType, u32, u32)] = if photocraft_testkit::full_sweep() { + &[(U8, 767, 431), (U8, 513, 1), (U8, 1, 513), (U16, 767, 431), (U16, 513, 1), (U16, 1, 513), (F32, 767, 431), (F32, 513, 1), (F32, 1, 513)] + } else { + &[(U8, 519, 267), (U16, 519, 267), (F32, 1, 513), (U8, 513, 1)] + }; + for &(depth, w, h) in depths_and_sizes { + 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); + for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { + for pixel in pixels { + assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); + for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { + assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); } } - let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); - let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); - assert!(gpu.upload_buffer_rect(1, &changed)); - for y in patch.y0..patch.y1 { - for x in patch.x0..patch.x1 { - full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; - } + } + let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); + let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); + assert!(gpu.upload_buffer_rect(1, &changed)); + for y in patch.y0..patch.y1 { + for x in patch.x0..patch.x1 { + full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; } - gpu.upload_buffer_full(2, &full, depth); - let partial = read_mips(gpu, 1); - let rebuilt = read_mips(gpu, 2); - for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { - for (a, b) in actual.iter().zip(expected) { - assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); - for (a, b) in a.iter().zip(b) { - assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); - } + } + gpu.upload_buffer_full(2, &full, depth); + let partial = read_mips(gpu, 1); + let rebuilt = read_mips(gpu, 2); + for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { + for (a, b) in actual.iter().zip(expected) { + assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); + for (a, b) in a.iter().zip(b) { + assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); } } } @@ -177,7 +192,17 @@ fn partial_updates_match_a_full_rebuild_at_every_mip_level() { return; }; let gpu = GpuCanvas::new(&rs); - for (depth, w, h) in [(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] { + let adapter = rs.adapter.get_info(); + // Keep the allocation/layout sweep on physical Vulkan devices, where the + // scissor regression was observed, and in the full sweep. Software adapters + // still exercise both texture formats, whole and partial redraws, and both dabs. + let sizes: &[(SampleType, u32, u32)] = + if photocraft_testkit::full_sweep() || (adapter.backend == wgpu::Backend::Vulkan && adapter.device_type != wgpu::DeviceType::Cpu) { + &[(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] + } else { + &[(SampleType::U8, 255, 255), (SampleType::F32, 519, 267)] + }; + for &(depth, w, h) in sizes { let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.0; 4]); for (i, px) in full.px.iter_mut().enumerate() { let (x, y) = (i as u32 % w, i as u32 / w); @@ -232,8 +257,9 @@ fn background_compositor_switch_preserves_pixels(gpu: &GpuCanvas) { } let second = gpu.refresh(key, &doc, Some(damage), None); assert_eq!(second.kind, "gpu-rect", "{:?}", second.fallback); - let actual = read_mips(gpu, key).remove(0); + let (_, _, actual) = gpu.read_texels(key).expect("read updated canvas"); let expected = photocraft_compose::render(&doc, doc.bounds()); + assert_eq!(actual.len(), expected.px.len()); for (got, want) in actual.iter().zip(expected.px.iter()) { for (g, w) in got.iter().zip(want.iter()) { assert!((g - w).abs() < 0.02, "{got:?} != {want:?}"); diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index f5890874b7f..050549e99cc 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -90,12 +90,14 @@ fn button(h: &mut Harness, at: Pos2, pressed: bool) { h.step(); } -/// The rendered frame's RGB at document point `(x, y)`. -fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { - let p = screen(h, x, y); +/// Sample all points in the same rendered frame. +fn rgb_at(h: &mut Harness, points: [[f64; 2]; N]) -> [[u8; 3]; N] { + let points = points.map(|[x, y]| screen(h, x, y)); let img = h.render().expect("render"); - let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); - [px[0], px[1], px[2]] + points.map(|p| { + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] + }) } fn is_red(c: [u8; 3]) -> bool { @@ -110,11 +112,12 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness(gpu_canvas) else { return }; setup(&mut h); - assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + let [before] = rgb_at(&mut h, [[150.5, 150.5]]); + assert!(is_red(before), "the layer shows before the transform"); control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); assert!(h.state().ui.transform.is_some(), "Free Transform is open"); - let inside = rgb_at(&mut h, 150.5, 150.5); + let [inside] = rgb_at(&mut h, [[150.5, 150.5]]); assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the @@ -125,12 +128,11 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { for i in 1..=6 { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, vacated] = rgb_at(&mut h, [[230.5, 130.5], [120.5, 130.5]]); assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); - let vacated = rgb_at(&mut h, 120.5, 130.5); assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); button(&mut h, to, false); - let released = rgb_at(&mut h, 230.5, 130.5); + let [released] = rgb_at(&mut h, [[230.5, 130.5]]); assert!(is_red(released), "the moved square still shows after the release: {released:?}"); } @@ -158,14 +160,14 @@ fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } button(&mut h, to, false); - assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square"); + let [before] = rgb_at(&mut h, [[230.5, 130.5]]); + assert!(is_red(before), "the box moved the square"); h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.step(); assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform"); - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, back] = rgb_at(&mut h, [[230.5, 130.5], [150.5, 130.5]]); assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}"); - let back = rgb_at(&mut h, 150.5, 130.5); assert!(is_red(back), "the square is back in its place: {back:?}"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs index f8f56bb371d..43790c4a406 100644 --- a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs @@ -162,15 +162,22 @@ fn pm(p: &[f32; 4]) -> [f32; 4] { [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] } -fn diffs(a: &[[f32; 4]], b: &[[f32; 4]]) -> Vec { - a.iter().zip(b).map(|(x, y)| (0..4).map(|c| (pm(x)[c] - pm(y)[c]).abs()).fold(0.0, f32::max)).collect() -} - /// Largest difference, ignoring up to `skip` outliers. fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 { - let mut d = diffs(a, b); - d.sort_by(|x, y| y.total_cmp(x)); - d.get(skip).copied().unwrap_or(0.0) + assert_eq!(a.len(), b.len()); + let diffs = a.iter().zip(b).map(|(x, y)| { + let (x, y) = (pm(x), pm(y)); + x.into_iter().zip(y).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) + }); + if skip == 0 { + diffs.fold(0.0, f32::max) + } else { + let mut diffs = diffs.collect::>(); + if skip >= diffs.len() { + return 0.0; + } + *diffs.select_nth_unstable_by(skip, |x, y| y.total_cmp(x)).1 + } } #[test] @@ -181,11 +188,18 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { // command's CPU result (adds the command's rounding to the layer depth). let (tol_gpu, tol_cmd) = (2.0 / 255.0, 2.5 / 255.0); let mut worst = 0.0f32; + let full_sweep = photocraft_testkit::full_sweep(); for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (depth_index, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { for selection in [false, true] { let (doc, target) = document(mode, depth, selection); - for kind in photocraft_ui_egui::adjust_editors::KINDS { + for (kind_index, kind) in photocraft_ui_egui::adjust_editors::KINDS.into_iter().enumerate() { + // Keep every shader at every mode and depth, sampling both mask + // paths. The CPU test preview_composite_matches_the_destructive_command + // already compares all combinations; the full GPU sweep keeps them too. + if !full_sweep && selection != (kind_index + depth_index).is_multiple_of(2) { + continue; + } let params = sample(kind); let preview = match preview_document(&doc, target, kind, ¶ms) { Ok(p) => p, @@ -209,7 +223,7 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { 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(); + s.execute(&format!("image.adjustments.{kind}"), params).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); @@ -284,7 +298,7 @@ fn proxy_preview_composites_on_the_gpu() { let (doc, target) = document(ColorMode::Rgb, SampleType::U8, selection); let proxy = proxy_base(&base_document(&doc, target).unwrap(), 2); // Render the full document too, so both share the compositor's resident textures. - render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).unwrap(); + comp.render(&device, &queue, &doc, doc.bounds(), |_, _| {}).unwrap(); for kind in photocraft_ui_egui::adjust_editors::KINDS { let p = proxy_with_settings(&proxy, kind, &sample(kind)).unwrap(); let on_gpu = render_to_vec(&mut comp, &device, &queue, &p, p.bounds()).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs index 97ad7528ac3..88d506e0107 100644 --- a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs +++ b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs @@ -39,22 +39,29 @@ fn harness() -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) -> Value { +fn request(h: &mut Harness, method: &str, params: Value) -> Value { let ctx = h.ctx.clone(); let (req, _rx) = ControlRequest::new(method, params); let Reply::Done(value) = handle(h.state_mut(), &ctx, &req) else { panic!("{method} did not finish") }; assert_eq!(value["ok"], true, "{method}: {value}"); - h.run_steps(4); value["result"].clone() } +fn control(h: &mut Harness, method: &str, params: Value) -> Value { + let result = request(h, method, params); + h.run_steps(4); + result +} + fn setup(h: &mut Harness, width: u32, height: u32, zoom: f32, center: [f32; 2]) { + // Settle once after the document is filled and positioned. The fixture does not + // need a canvas frame for the old tab, the empty editor or the temporary white fill. while h.state().session.active().is_some() { - control(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); + request(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); } - control(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); - control(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); - control(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); + request(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); + request(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); + request(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); control(h, "ui.set", json!({"zoom":zoom,"center":center})); assert!(h.state().perf.gpu, "the fixture must use the GPU canvas"); } @@ -129,18 +136,18 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { setup(&mut h, width, height, zoom, center); assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor); let id = open_previewing(&mut h); - let source = blue(&mut h, &format!("{width}x{height}-{degrees}-zero")).0; - assert!(source > 5_000, "the unrotated blue image must be visible outside the dialog"); angle(&mut h, &id, degrees); h.get_by_label("Preview").click(); h.run_steps(4); assert!(!preview_on(&h)); - assert!(blue(&mut h, &format!("{width}x{height}-{degrees}-off")).0 > 5_000, "Preview off shows the original image"); + let (original, original_top, original_bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-off")); + assert!(original > 5_000, "Preview off shows the original image"); h.get_by_label("Preview").click(); h.run_steps(4); assert!(preview_on(&h)); let (count, top, bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-on")); assert!(count > 5_000, "{width}x{height}, {degrees}°, factor {factor}: rotated blue pixels disappeared ({count} remain)"); + assert!(bottom - top > original_bottom - original_top, "{degrees}°: the rotated preview should be taller"); let rect = photocraft_ui_egui::canvas::active_view(h.state()).expect("a shown view").rect; let expected_y = rect.center().y + (height as f32 / 2.0 - center[1]) * zoom; let actual_y = (top + bottom) as f32 / 2.0; diff --git a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs index fcdd436f7d1..8193a546e6d 100644 --- a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs +++ b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs @@ -227,9 +227,10 @@ fn screens(cases: Vec>) -> Option> { } harness.run_steps(6); let img = harness.render().expect("render"); - let out = std::env::temp_dir().join(name); - let _ = img.save(&out); - eprintln!("screen: {}", out.display()); + if let Some(dir) = std::env::var_os("PHOTOCRAFT_CANVAS_16F_EVIDENCE_DIR") { + std::fs::create_dir_all(&dir).expect("evidence directory"); + img.save(std::path::Path::new(&dir).join(name)).expect("save UI frame"); + } shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() }); if let Some((doc, setup, name)) = cases.next() { harness.state_mut().session.open_document(doc, None); @@ -252,7 +253,9 @@ fn screen_levels(img: &Screen, y: u32, x0: u32, x1: u32) -> (usize, i32) { fn sixteen_bit_gradient_on_screen() { let _gpu = gpu_lock(); // A 16-bit ramp drawn by the app's canvas: smooth, monotonic, no visible steps. - let doc = gradient(SampleType::U16, 2048, 1024, 0.0, 1.0); + // The document still fits down to the same viewport and has more source levels than + // the screen can display. The extra source pixels aren't needed to spot banding. + let doc = gradient(SampleType::U16, 1024, 512, 0.0, 1.0); let Some(img) = screen(doc, &[], "photocraft-canvas-16f-gradient.png") else { return }; let (n, step) = screen_levels(&img, img.h / 2, 150, 600); assert!(n > 100 && step <= 3, "{n} levels, max step {step}"); @@ -263,7 +266,7 @@ fn thirty_two_bit_preview_exposes_values_above_one() { let _gpu = gpu_lock(); // A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit // canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth. - let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0); + let doc = gradient(SampleType::F32, 1024, 512, 0.0, 1.0 / 16.0); // Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0 // at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8). let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32); diff --git a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs index e3708e45920..ae99576baa8 100644 --- a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs @@ -1,13 +1,17 @@ -//! The transparency checker is made of 8 screen pixel cells (the Medium preference) at every zoom, +//! The transparency checker is made of 8 screen point cells (the Medium preference) at every zoom, //! anchored to the document's top-left corner so the pattern moves with the image. The pixel grid shows above 500% zoom, //! over pixels with content only, never over empty checker. //! //! These tests render the real app offscreen and read pixels back. They skip when no GPU adapter //! is available. The CPU canvas (no wgpu handed to the app) has its own pixel grid tests at the end. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, Size}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; use photocraft_ui_egui::PhotocraftApp; -use photocraft_ui_egui::control::{ControlRequest, handle}; -use serde_json::{Value, json}; +use photocraft_ui_egui::control::{ControlRequest, Reply, handle}; +use serde_json::json; type Harness = egui_kittest::Harness<'static, Box>; @@ -24,8 +28,18 @@ fn harness_with(gpu: bool) -> Option { } fn harness_with_scale(gpu: bool, ppp: f32) -> Option { + // At 2× the same document pixels take half as many points. Keep the samples + // inside the viewport without reading back a 2800 × 1600 frame. + let size = if ppp > 1.0 { + egui::vec2(820.0, 570.0) + } else if photocraft_testkit::full_sweep() { + // The full sweep also samples a 730 px wide document at 1×. + egui::vec2(1400.0, 800.0) + } else { + egui::vec2(900.0, 640.0) + }; let built = std::panic::catch_unwind(|| { - egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 800.0)).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { + egui_kittest::Harness::builder().with_size(size).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if let Some(rs) = cc.wgpu_render_state.as_ref().filter(|_| gpu) { @@ -43,10 +57,11 @@ fn harness_with_scale(gpu: bool, ppp: f32) -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) { +fn set_view(h: &mut Harness, zoom: f32, center: [f32; 2]) { let ctx = h.ctx.clone(); - let (req, _rx) = ControlRequest::new(method, params); - handle(h.state_mut(), &ctx, &req); + let (req, _rx) = ControlRequest::new("ui.set", json!({"zoom": zoom, "center": center})); + let Reply::Done(reply) = handle(h.state_mut(), &ctx, &req) else { panic!("setting the view did not finish") }; + assert_eq!(reply["ok"], true, "{reply}"); h.run_steps(4); } @@ -87,30 +102,23 @@ impl Shot { } } -/// Opens a `doc` px square document at `zoom` (transparent, or filled black when `black`), renders -/// it with the pixel grid on or off, and returns the screenshot with the document's left and top -/// screen edge and its width in screen pixels. -fn render(h: &mut Harness, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - render_on(h, true, zoom, doc, black, grid) +fn open_document(h: &mut Harness, doc: u32, black: bool, grid: bool) { + let app = h.state_mut(); + while app.session.active().is_some() { + app.run("file.close", json!({"discard": true})).expect("close"); + } + let background = if black { "white" } else { "transparent" }; + app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); + if black { + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + } + app.sync_views(); + app.ui.view.show.pixel_grid = grid; } -/// [`render`] on the GPU canvas (`gpu`) or the CPU canvas. -fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - let background = if black { "white" } else { "transparent" }; - app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); - if black { - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - } - app.sync_views(); - app.ui.view.show.pixel_grid = grid; - } - control(h, "ui.set", json!({"zoom": zoom, "center": [doc as f32 / 2.0, doc as f32 / 2.0]})); - h.run_steps(3); +/// Zooms the current document and returns the screenshot and the document's physical-pixel bounds. +fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool) -> (Shot, u32, u32, u32) { + set_view(h, zoom, [doc as f32 / 2.0; 2]); assert_eq!(h.state().perf.gpu, gpu, "zoom {zoom}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); let rendered = h.render().expect("render"); let (width, height) = (rendered.width(), rendered.height()); @@ -122,7 +130,8 @@ fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: return (img, origin.x.round() as u32, origin.y.round() as u32, (doc as f32 * zoom).round() as u32); } let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); + let center = r.center() * h.ctx.pixels_per_point(); + let (cx, cy) = (center.x as u32, center.y as u32); let (x0, w) = longest_run((0..width).map(|x| is_checker_grey(img.at(x, cy)))); let (y0, hgt) = longest_run((0..height).map(|y| is_checker_grey(img.at(cx, y)))); let doc_px = (doc as f32 * zoom).round() as i64; @@ -135,14 +144,33 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // The 8 px cell never changes with the zoom. - for (zoom, doc) in [(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] { - let (img, x0, y0, _) = render(&mut h, zoom, doc, false, false); - let n = ((doc as f32 * zoom) / 8.0) as u32; + // The checker draws in screen points, independent of the document zoom. + // Sample reduced, 1:1, fractional and magnified views, including 2× displays. + let zooms_1x: &[(f32, u32)] = if photocraft_testkit::full_sweep() { + &[(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] + } else { + &[(0.5, 64), (1.0, 64), (1.1, 64)] + }; + let zooms_2x = [(8.0, 32), (32.0, 12)]; + let cases = zooms_1x.iter().map(|&(zoom, doc)| (1.0, zoom, doc)).chain(zooms_2x.into_iter().map(|(zoom, doc)| (2.0, zoom, doc))); + let mut current_size = 0; + for (ppp, zoom, doc) in cases { + if h.ctx.pixels_per_point() != ppp { + h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT).expect("root viewport").native_pixels_per_point = Some(ppp); + h.run_steps(4); + } + assert_eq!(h.ctx.pixels_per_point(), ppp); + if current_size != doc { + open_document(&mut h, doc, false, false); + current_size = doc; + } + let (img, x0, y0, _) = render_on(&mut h, true, zoom, doc, false); + let cell = (8.0 * ppp) as u32; + let n = (doc as f32 * zoom) as u32 / cell; assert!(n >= 2, "zoom {zoom}: test needs at least two cells"); for row in 0..n.min(4) { for col in 0..n.min(6) { - let (sx, sy) = (x0 + col * 8 + 4, y0 + row * 8 + 4); + let (sx, sy) = (x0 + col * cell + cell / 2, y0 + row * cell + cell / 2); let got = img.at(sx, sy); let want = if (col + row) % 2 == 0 { LIGHT } else { DARK }; assert!( @@ -152,8 +180,8 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { } } // Crisp: every pixel of the row is exactly one of the two greys, no blended edges. - let y = y0 + 4; - for x in x0..x0 + (n * 8).min(48) { + let y = y0 + cell / 2; + for x in x0..x0 + n.min(6) * cell { let v = img.at(x, y)[0]; assert!(v == LIGHT || v == DARK, "zoom {zoom}: blended pixel {v} at ({x}, {y})"); } @@ -170,10 +198,11 @@ fn pixel_grid_shows_above_500_percent_and_lightens_a_dark_pixel_by_about_a_quart let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render(&mut h, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, true, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, true); let lit = lit_columns(&img, x0, y0 + (zoom * 3.5) as u32, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "zoom {zoom}: grid columns {lit:?}"); assert!(lit.windows(2).all(|p| p[1] - p[0] == zoom as u32), "zoom {zoom}: spacing of {lit:?}"); @@ -187,8 +216,9 @@ fn pixel_grid_is_not_drawn_over_empty_checker() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); + open_document(&mut h, 24, false, true); for zoom in [8.0f32, 16.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 24, false, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, false); for y in y0..y0 + 64 { for x in x0..x0 + 64 { let v = img.at(x, y)[0]; @@ -204,10 +234,11 @@ fn cpu_pixel_grid_shows_above_500_percent_over_content() { for ppp in [1.0, 2.0] { let Some(mut h) = harness_with_scale(false, ppp) else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render_on(&mut h, false, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, false, zoom, 24, true); let y = y0 + (zoom * 3.5) as u32; let lit = lit_columns(&img, x0, y, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "scale {ppp}, zoom {zoom}: one physical pixel per line, columns {lit:?}"); @@ -224,9 +255,12 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { let Some(mut h) = harness_with(false) else { return }; h.run_steps(4); // The CPU checker has soft cell edges of its own, so compare with and without the grid. + open_document(&mut h, 24, false, false); for zoom in [8.0f32, 16.0] { - let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false, false); - let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false, true); + h.state_mut().ui.view.show.pixel_grid = false; + let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false); + h.state_mut().ui.view.show.pixel_grid = true; + let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false); assert_eq!((x0, y0), (x1, y1), "zoom {zoom}: the document moved"); for y in y0..y0 + 64 { for x in x0..x0 + 64 { @@ -236,56 +270,48 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { } } -/// The pixel grid over a flat `grey` document at 800%: the largest difference, in 8-bit levels, -/// between a grid line and the pixel interior beside it. -fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("file.new", json!({"width": 48, "height": 48, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": format!("#{grey:02x}{grey:02x}{grey:02x}")})).expect("fill"); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - } - control(h, "ui.set", json!({"zoom": 8.0, "center": [24.0, 24.0]})); - h.run_steps(3); - assert!(h.state().perf.gpu, "expected the GPU canvas"); - let rendered = h.render().expect("render"); - let img = Shot { w: rendered.width(), px: rendered.into_raw() }; - let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); - // The median of an 8 px block is a pixel interior whichever line the block straddles. - let mut block: Vec = (0..64).map(|i| img.at(cx + i % 8, cy + i / 8)[0] as i32).collect(); - block.sort_unstable(); - let interior = block[32]; - // Walk out to the document edge: the pasteboard is far darker than any grid line. - let near = |x: u32, y: u32| (img.at(x, y)[0] as i32 - interior).abs() < 50; - let x0 = (0..=cx).rev().take_while(|x| near(*x, cy)).last().unwrap_or(cx); - let y0 = (0..=cy).rev().take_while(|y| near(cx, *y)).last().unwrap_or(cy); - // Pixel (col, row) owns the grid line on its left and top edge, 8 screen px apart. - let y = y0 + 8 * 3 + 4; - (2..6).map(|col| (img.at(x0 + 8 * col, y)[0] as i32 - img.at(x0 + 8 * col + 4, y)[0] as i32).abs()).max().unwrap_or(0) -} - #[test] fn pixel_grid_does_not_flip_colour_across_mid_tones() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white - // line to a full black one. Both now give a faint line, so neighbouring cells match. - for grey in [0x87u8, 0x90] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c <= 14, "grey {grey:#04x}: grid line differs from its pixel by {c} levels, want a faint line"); + // Put both sides of the old luma cutoff and the stronger dark/light lines in one frame. + // Sample inside each swatch so an edge between swatches cannot pass as a grid line. + let greys = [0x87u8, 0x90, 0x60, 0xd0, 0xff]; + let mut doc = Document::new("grid midtones", Size::new(40, 16), ColorMode::Rgb, SampleType::U8); + let mut surface = Surface::new(doc.pixel_format()); + for (i, grey) in greys.into_iter().enumerate() { + let x = i as i32 * 8; + let v = f32::from(grey) / 255.0; + surface.fill_rect(Rect::new(x, 0, x + 8, 16), &[v, v, v, 1.0]); } - // The fade must not remove the grid where it is needed: dark and light pixels keep a clear - // line (white over 0x60, black over 0xd0 and white; black itself is in the unit tests, as the - // dark pasteboard defeats this walk to the document edge). - for grey in [0x60u8, 0xd0, 0xff] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {c} levels"); + doc.layers.push(Layer::new("swatches", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + set_view(&mut h, 8.0, [20.0, 8.0]); + assert!(h.state().perf.gpu); + let img = h.render().expect("render swatches"); + let center = h.state().last_canvas_rect.center(); + let x0 = (center.x - 20.0 * 8.0).round() as u32; + let y = (center.y + 3.5 * 8.0).round() as u32; + for (i, grey) in greys.into_iter().enumerate() { + let x = x0 + i as u32 * 64; + let contrast = (2..6) + .map(|col| { + let edge = x + 8 * col; + let inside = img.get_pixel(edge + 4, y)[0]; + assert!(inside.abs_diff(grey) <= 1, "wrong swatch at {edge}: {inside} vs {grey}"); + (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, y)[0].abs_diff(inside)).max().expect("grid line") + }) + .max() + .expect("swatch columns"); + if i < 2 { + assert!(contrast <= 14, "grey {grey:#04x}: grid line differs from its pixel by {contrast} levels, want a faint line"); + } else { + assert!(contrast >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {contrast} levels"); + } } } @@ -296,8 +322,7 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() { /// 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 { - use photocraft_color::SampleType; +fn grid_depths(gpu: bool, ppp: f32) -> Vec { match (gpu, ppp > 1.0) { (true, false) => vec![SampleType::U8, SampleType::U16], (true, true) => vec![SampleType::U8, SampleType::F32], @@ -307,36 +332,49 @@ fn grid_depths(gpu: bool, ppp: f32) -> Vec { fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) { let _gpu = photocraft_testkit::gpu_lock(); - 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 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)); - surface.fill_rect(Rect::new(0, 0, 32, 16), &[v, v, v, 1.0]); - doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); - let app = h.state_mut(); - app.session.add_document(doc, None); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - for zoom in [7.119, 8.0, 22.825] { - control(&mut h, "ui.set", json!({"zoom": zoom, "center": [16.0, 8.0]})); - assert_eq!(h.state().perf.gpu, gpu); - let img = h.render().expect("render opaque grid"); - let center = h.state().last_canvas_rect.center() * ppp; - let x0 = center.x - 16.0 * zoom; - let y = (center.y + 3.25 * zoom).floor() as u32; + 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)); + // Both neutral fills take the same grid draw path, with opposite line contrast. + // Separate rows let them share one readback at each depth and zoom. + surface.fill_rect(Rect::new(0, 0, 32, 8), &[0.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(0, 8, 32, 16), &[1.0; 4]); + doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + // Keep the 500% cutoff at each scale. Across the two scales, sample both + // fractional and integer grid alignment, including the largest zoom. + let visible_zooms: &[f32] = if photocraft_testkit::full_sweep() { + &[7.119, 8.0, 22.825] + } else if ppp == 1.0 { + &[7.119] + } else { + &[8.0, 22.825] + }; + for zoom in (depth == SampleType::U8).then_some(5.0).into_iter().chain(visible_zooms.iter().copied()) { + set_view(&mut h, zoom, [16.0, 8.0]); + assert_eq!(h.state().perf.gpu, gpu); + assert_eq!(h.ctx.pixels_per_point(), ppp); + let img = h.render().expect("render opaque grid"); + let center = h.state().last_canvas_rect.center() * ppp; + let x0 = center.x - 16.0 * zoom; + for (v, dy) in [(0, -2.75), (255, 3.25)] { + let y = (center.y + dy * zoom).floor() as u32; for x in 2..30 { let edge = (x0 + x as f32 * zoom).floor() as u32; for sy in y..y + 3 { let inside = img.get_pixel((x0 + (x as f32 + 0.5) * zoom).floor() as u32, sy)[0]; - assert_eq!(inside, (v * 255.0) as u8); + assert_eq!(inside, v); let contrast = (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, sy)[0].abs_diff(inside)).max().expect("line"); - assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + if zoom == 5.0 { + assert_eq!(contrast, 0, "grid visible at 500%, {gpu:?}/{depth:?}, scale {ppp}, fill {v}"); + } else { + assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + } } } } diff --git a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs index 208dac9e950..03030efc629 100644 --- a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs @@ -197,17 +197,22 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { // 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. + // Both shapes paint through the same scale-aware marching-ants painter. + // Sample the rectangle at 1× and the curve at 2× by default; the full + // sweep also covers each shape at the other scale. + let full_sweep = photocraft_testkit::full_sweep(); let Some(mut h) = harness(1.0) else { return }; h.run_steps(4); - for ppp in [1.0f32, 2.0] { + for (ppp, primary) in [(1.0f32, "rectMarquee"), (2.0, "ellipseMarquee")] { 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"] { + if tool != primary && !full_sweep { + continue; + } setup(&mut h, GREY, tool); let (a, b) = ([100.0, 80.0], [300.0, 220.0]); let before = render(&mut h); @@ -246,8 +251,8 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { } // 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 img = render(&mut h); 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})"); diff --git a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs index 1556fb0e04c..bf92a75c034 100644 --- a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs @@ -141,7 +141,6 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The smoothing tool option syncs on the first frame with the Brush: set it after. h.state_mut().session.tools.brush.smoothing.amount = c.smoothing; let canvas = |h: &mut Harness| { - h.run_steps(3); let r = h.state().last_canvas_rect.shrink(4.0); let img = h.render().expect("render"); let mut px = Vec::new(); @@ -152,10 +151,13 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { } px }; + h.run_steps(3); let before = canvas(h); let pressure = |t: f64| if c.pressure { 0.3 + 0.7 * t } else { 1.0 }; control(h, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100, "pressure": pressure(0.0)}]})); - let n = 14; + // Keep the whole curved path and both ends of the pressure ramp. The full + // sweep also exercises the original denser sequence of pointer events. + let n = if photocraft_testkit::full_sweep() { 14 } else { 8 }; let mut last = (100.0, 100.0); for i in 1..=n { let t = f64::from(i) / f64::from(n); @@ -168,11 +170,12 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The pointer stays held at its last point, as a mouse held still repeats its position. let held = |h: &mut Harness| { control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]})); - canvas(h) + h.run_steps(3); }; - let drawing = settled(h, held); + let drawing = settled(h, held, canvas); let gpu = h.state().perf.gpu && !c.flip; control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]})); + h.run_steps(3); let done = canvas(h); (before, drawing, done, gpu) } @@ -180,22 +183,28 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { /// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own /// thread and a frame waits only a few real ms for it, so on a slow machine its newest step /// arrives late, and only a later pointer event shows it; release would then paint the rest. -/// `picture` holds the pointer still and takes a picture, with short real waits between them, -/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove -/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails -/// instead of hanging or comparing an unsettled picture. -fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { +/// Keep feeding the held pointer until the stroke is idle and three pictures in a row match. +/// A busy stroke can't be stable, so advance those frames without a GPU readback. +fn settled(h: &mut Harness, held: impl Fn(&mut Harness), picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { const TRIES: usize = 80; - let mut last = picture(h); + let mut last = None; let mut unchanged = 0; - for _ in 0..TRIES { - std::thread::sleep(std::time::Duration::from_millis(25)); - let next = picture(h); - unchanged = if next == last { unchanged + 1 } else { 0 }; - last = next; - if unchanged >= 2 && !h.state().live_stroke_busy() { - return last; + for attempt in 0..=TRIES { + if attempt != 0 { + std::thread::sleep(std::time::Duration::from_millis(25)); } + held(h); + if h.state().live_stroke_busy() { + last = None; + unchanged = 0; + continue; + } + let next = picture(h); + unchanged = if last.as_ref() == Some(&next) { unchanged + 1 } else { 0 }; + if unchanged >= 2 { + return next; + } + last = Some(next); } panic!("the live stroke did not settle before release"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs index c661370ea64..3ff626b86ce 100644 --- a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs @@ -86,26 +86,20 @@ fn assert_document_size_is_physical(gpu: bool) { let Some(mut h) = harness(gpu) else { return }; h.run_steps(4); const DOC: u32 = 60; + let app = h.state_mut(); + app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + app.sync_views(); // A fractional and an integer UI scale: the canvas sees the scale only as `pixels_per_point` (device px per doc px // = zoom x ppp), and its sampling branches on that product being below 1, whole (or 2 and up) or fractional // (`gpu_canvas::callback::filter_mode`). 125% gives 1.25 and 2.5 at the two zooms, as 150% would; 200% gives 2 and // 4, covering 100%'s 1 and 2, where a dropped ppp could not show anyway (#15652). for ui_scale in ["125", "200"] { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); - app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - app.sync_views(); - } + h.state_mut().run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); h.run_steps(6); assert_eq!(h.state().perf.gpu, gpu, "UI Scale {ui_scale}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); for zoom in [1.0f32, 2.0] { control(&mut h, "ui.set", json!({"zoom": zoom, "center": [DOC as f32 / 2.0, DOC as f32 / 2.0]})); - h.run_steps(4); let (w, hgt) = document_physical_size(&mut h); let want = (DOC as f32 * zoom).round() as i64; assert!(