Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Canvas: the CPU canvas pixel grid skips empty pixels, like the GPU canvas (#1891)

Jeremy7a5b0b5d4538
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 56cd9ed58..789391cf1 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -103,6 +103,8 @@ pub struct CanvasCache {
/// `revision`, so the Navigator never shows a stale CPU image after GPU-path edits.
pub tex_revision: u64,
pub tex_preview_key: u64,
+ /// The CPU path's pixel grid for the part of the document in view (pixel_grid.rs).
+ pub grid: Option<crate::pixel_grid::GridLines>,
}
/// An in-progress pointer gesture on the canvas.
@@ -705,7 +707,7 @@ fn texture_key(display: Option<&photocraft_engine::display_color::CanvasDisplay>
/// `app.canvases` key: CPU canvas textures are per document and display (they hold monitor
/// values); the GPU canvas state uses [`GPU_OUTPUT`].
-fn cache_key(doc: photocraft_doc::DocId, display: Option<u32>) -> (photocraft_doc::DocId, u32) {
+pub(crate) fn cache_key(doc: photocraft_doc::DocId, display: Option<u32>) -> (photocraft_doc::DocId, u32) {
(doc, display.unwrap_or(0))
}
@@ -713,7 +715,7 @@ fn cache_key(doc: photocraft_doc::DocId, display: Option<u32>) -> (photocraft_do
pub(crate) const GPU_OUTPUT: u32 = u32::MAX;
/// The document to render: the committed one, or a clone with the live adjustment preview applied.
-fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {
+pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {
if let Some(shown) = crate::type_transform::display_doc(app, idx) {
return shown;
}
@@ -883,6 +885,7 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
on_gpu: false,
tex_revision: 0,
tex_preview_key: 0,
+ grid: None,
});
if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key {
let t0 = crate::gpu_canvas::now_ms();
@@ -1040,6 +1043,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {
on_gpu: false,
tex_revision: 0,
tex_preview_key: 0,
+ grid: None,
});
let present = cache.on_gpu && gpu.has(id.0, size);
if present && cache.revision == revision && cache.preview_key == preview_key {
@@ -2203,28 +2207,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
}
- // Pixel grid at high zoom (the GPU path draws its own).
- if !on_gpu && pixel_grid && view.zoom > 5.0 {
- let vis = img_rect.intersect(rect);
- let corners = [vis.min, pos2(vis.max.x, vis.min.y), vis.max, pos2(vis.min.x, vis.max.y)];
- let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])];
- let mut x0 = docs[0][0];
- let mut y0 = docs[0][1];
- let mut x1 = x0;
- let mut y1 = y0;
- for d in docs {
- x0 = x0.min(d[0]);
- y0 = y0.min(d[1]);
- x1 = x1.max(d[0]);
- y1 = y1.max(d[1]);
- }
- let grid = Stroke::new(1.0, Color32::from_white_alpha(64));
- for x in (x0.floor() as i32)..=(x1.ceil() as i32) {
- painter.line_segment([xf.to_screen(x as f32, y0 as f32), xf.to_screen(x as f32, y1 as f32)], grid);
- }
- for y in (y0.floor() as i32)..=(y1.ceil() as i32) {
- painter.line_segment([xf.to_screen(x0 as f32, y as f32), xf.to_screen(x1 as f32, y as f32)], grid);
- }
+ // Pixel grid at high zoom, over pixels with content only (the GPU path draws its own).
+ if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) {
+ crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf));
}
// View › Show › Layer Edges: the active layer's content bounds.
diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs
index defbf1e9c..d61e259ad 100644
--- a/crates/ui-egui/src/gpu_canvas.rs
+++ b/crates/ui-egui/src/gpu_canvas.rs
@@ -1637,8 +1637,9 @@ impl CanvasCallback {
let p = &self.params;
let (origin, scale) = self.placement(ppp);
let (mode, lod) = filter_mode(scale);
- // The pixel grid shows above 500% and lightens a dark pixel by about a quarter.
- let grid = if p.pixel_grid && p.zoom > 5.0 { 0.25 } else { 0.0 };
+ // The pixel grid shows above 500% and lightens a dark pixel by about a quarter (the
+ // constants are shared with the CPU path, pixel_grid.rs).
+ let grid = if p.pixel_grid && crate::pixel_grid::shows_at(p.zoom) { crate::pixel_grid::STRENGTH } else { 0.0 };
let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 };
let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color);
// 32-bit preview: linear-light gain 2^exposure (0 = off) and 1 / gamma.
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index bc61fc2b2..e9d9f2b6a 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -102,6 +102,7 @@ pub mod panels;
pub mod parity;
pub mod patch_preview;
pub mod perspective_ui;
+pub mod pixel_grid;
pub mod plugin_ui;
pub mod point_curve;
pub mod prefs_ui;
diff --git a/crates/ui-egui/src/pixel_grid.rs b/crates/ui-egui/src/pixel_grid.rs
new file mode 100644
index 000000000..de50d1383
--- /dev/null
+++ b/crates/ui-egui/src/pixel_grid.rs
@@ -0,0 +1,301 @@
+//! The pixel grid of the CPU canvas path, matching the GPU canvas shader (`gpu_canvas.rs`):
+//! shown above 500% zoom, one device pixel wide, lightening a dark pixel by about a quarter
+//! (darkening a light one), and only over pixels that have content, never over empty checker.
+//!
+//! The shader reads each pixel's alpha as it draws. Here the same rule runs on the composite of
+//! the part of the document in view, turned into merged line segments. Both the composite and
+//! the segments are cached per document revision and per padded region, so panning inside the
+//! padding costs nothing and the work is bounded by the viewport at 500% or more, never by the
+//! document (AGENTS.md rule 8).
+
+use egui::{Color32, Painter, Stroke};
+use photocraft_doc::Document;
+use photocraft_geom::Rect as DRect;
+
+use crate::PhotocraftApp;
+use crate::canvas::ViewXform;
+
+/// The grid shows above this zoom (1.0 = 100%). Shared with the GPU canvas.
+pub const MIN_ZOOM: f32 = 5.0;
+/// Opacity of the grid line over a fully opaque dark pixel. Shared with the GPU canvas.
+pub const STRENGTH: f32 = 0.25;
+/// Light pixels get a black line this much weaker than the white one on dark pixels. The WGSL
+/// in `gpu_canvas.rs` spells the same number.
+pub const LIGHT_SCALE: f32 = 0.64;
+/// Luminance above which a pixel counts as light (same cut as the shader).
+const LIGHT_LUMA: f32 = 0.55;
+/// Luminance of the checker under a see-through pixel when deciding light or dark; between the
+/// default checker's two greys.
+const CHECKER_LUMA: f32 = 0.9;
+/// Cached regions snap to this many document pixels, so a small pan stays inside the cache.
+const REGION_SNAP: i32 = 64;
+/// Most segments kept. A document that is a fine lattice of transparent holes would otherwise
+/// produce one segment per cell; past this the grid is simply left off the remainder.
+const MAX_SEGMENTS: usize = 60_000;
+
+/// Whether the grid is drawn at `zoom`.
+pub fn shows_at(zoom: f32) -> bool {
+ zoom > MIN_ZOOM
+}
+
+/// One grid line piece in document pixels, axis-aligned, with its colour.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct GridSeg {
+ pub from: [i32; 2],
+ pub to: [i32; 2],
+ pub color: Color32,
+}
+
+/// The grid of a document region, valid for one revision and preview.
+pub struct GridLines {
+ revision: u64,
+ preview_key: u64,
+ region: DRect,
+ segs: Vec<GridSeg>,
+}
+
+/// The line colour over a pixel with straight-alpha `rgba` (0..1), or `None` where there is
+/// nothing to draw on: transparent pixels show checker, which stays clean.
+pub fn cell_color(rgba: [f32; 4]) -> Option<Color32> {
+ let a = rgba[3];
+ if a.is_nan() || a <= 0.0 {
+ return None;
+ }
+ let a = a.min(1.0);
+ let luma = 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2];
+ let shown = luma * a + CHECKER_LUMA * (1.0 - a);
+ let light = shown > LIGHT_LUMA;
+ let strength = STRENGTH * a * if light { LIGHT_SCALE } else { 1.0 };
+ let alpha = (strength * 255.0).round() as u8;
+ if alpha == 0 {
+ return None;
+ }
+ Some(if light { Color32::from_black_alpha(alpha) } else { Color32::from_white_alpha(alpha) })
+}
+
+/// Merge consecutive cells of equal colour along one line into `emit(start, end, colour)` runs.
+fn runs(len: i32, color_at: impl Fn(i32) -> Option<Color32>, mut emit: impl FnMut(i32, i32, Color32)) {
+ let mut open: Option<(i32, Color32)> = None;
+ for i in 0..len {
+ let c = color_at(i);
+ match (open, c) {
+ (Some((_, oc)), Some(c)) if oc == c => {}
+ _ => {
+ if let Some((s, oc)) = open {
+ emit(s, i, oc);
+ }
+ open = c.map(|c| (i, c));
+ }
+ }
+ }
+ if let Some((s, oc)) = open {
+ emit(s, len, oc);
+ }
+}
+
+/// The grid segments for the straight-alpha `px` covering `rect` (row-major). Each pixel owns
+/// its left and top edge, as in the shader, so the document's right and bottom edges carry no
+/// line. Runs of equal colour merge, so an opaque region costs one segment per line.
+pub fn segments(px: &[[f32; 4]], rect: DRect) -> Vec<GridSeg> {
+ let (w, h) = (rect.width() as i32, rect.height() as i32);
+ let mut out = Vec::new();
+ if w == 0 || h == 0 || px.len() < w as usize * h as usize {
+ return out;
+ }
+ let at = |x: i32, y: i32| px.get(y as usize * w as usize + x as usize).and_then(|p| cell_color(*p));
+ for x in 0..w {
+ if out.len() >= MAX_SEGMENTS {
+ return out;
+ }
+ runs(h, |y| at(x, y), |s, e, color| out.push(GridSeg { from: [rect.x0 + x, rect.y0 + s], to: [rect.x0 + x, rect.y0 + e], color }));
+ }
+ for y in 0..h {
+ if out.len() >= MAX_SEGMENTS {
+ return out;
+ }
+ runs(w, |x| at(x, y), |s, e, color| out.push(GridSeg { from: [rect.x0 + s, rect.y0 + y], to: [rect.x0 + e, rect.y0 + y], color }));
+ }
+ out.truncate(MAX_SEGMENTS);
+ out
+}
+
+/// The part of the document to cache for a view showing `visible`: that area within `bounds`,
+/// grown outward to multiples of [`REGION_SNAP`].
+pub fn cache_region(visible: DRect, bounds: DRect) -> DRect {
+ let v = visible.intersect(&bounds);
+ if v.is_empty() {
+ return DRect::EMPTY;
+ }
+ let down = |n: i32| n.div_euclid(REGION_SNAP) * REGION_SNAP;
+ let up = |n: i32| down(n.saturating_add(REGION_SNAP - 1));
+ DRect::new(down(v.x0), down(v.y0), up(v.x1), up(v.y1)).intersect(&bounds)
+}
+
+impl GridLines {
+ fn build(doc: &Document, revision: u64, preview_key: u64, region: DRect) -> Self {
+ let segs = if region.is_empty() { Vec::new() } else { segments(&photocraft_compose::render(doc, region).px, region) };
+ Self { revision, preview_key, region, segs }
+ }
+
+ /// Whether this still holds the grid of `need` at the given revision and preview.
+ fn covers(&self, revision: u64, preview_key: u64, need: &DRect) -> bool {
+ self.revision == revision && self.preview_key == preview_key && self.region.contains_rect(need)
+ }
+}
+
+/// Draw the grid of document `idx` over the CPU-composited canvas. `visible` is the document
+/// area in view (document pixels); `output` the display the canvas is drawn for.
+pub fn paint(app: &mut PhotocraftApp, painter: &Painter, xf: &ViewXform, idx: usize, output: Option<u32>, visible: DRect) {
+ let Some((id, revision)) = app.session.documents().get(idx).map(|st| (st.doc.id, st.revision)) else { return };
+ let (doc, preview_key) = crate::canvas::display_doc(app, idx);
+ let need = visible.intersect(&doc.bounds());
+ if need.is_empty() {
+ return;
+ }
+ let Some(cache) = app.canvases.get_mut(&crate::canvas::cache_key(id, output)) else { return };
+ if !cache.grid.as_ref().is_some_and(|g| g.covers(revision, preview_key, &need)) {
+ cache.grid = Some(GridLines::build(&doc, revision, preview_key, cache_region(visible, doc.bounds())));
+ }
+ let Some(grid) = &cache.grid else { return };
+ for s in &grid.segs {
+ let (a, b) = (xf.to_screen(s.from[0] as f32, s.from[1] as f32), xf.to_screen(s.to[0] as f32, s.to[1] as f32));
+ painter.line_segment([a, b], Stroke::new(1.0, s.color));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const OPAQUE_DARK: [f32; 4] = [0.1, 0.1, 0.1, 1.0];
+ const OPAQUE_LIGHT: [f32; 4] = [0.9, 0.9, 0.9, 1.0];
+
+ #[test]
+ fn grid_starts_above_five_hundred_percent() {
+ assert!(!shows_at(5.0));
+ assert!(!shows_at(1.0));
+ assert!(shows_at(5.01));
+ assert!(shows_at(128.0));
+ }
+
+ #[test]
+ fn transparent_pixels_get_no_line() {
+ assert_eq!(cell_color([0.0, 0.0, 0.0, 0.0]), None);
+ assert_eq!(cell_color([1.0, 1.0, 1.0, 0.0]), None);
+ assert_eq!(cell_color([0.5, 0.5, 0.5, f32::NAN]), None);
+ // Almost invisible pixels round to no line rather than a faint speck.
+ assert_eq!(cell_color([0.0, 0.0, 0.0, 0.001]), None);
+ }
+
+ #[test]
+ fn dark_pixels_get_a_quarter_white_and_light_ones_less_black() {
+ assert_eq!(cell_color(OPAQUE_DARK), Some(Color32::from_white_alpha(64)));
+ assert_eq!(cell_color(OPAQUE_LIGHT), Some(Color32::from_black_alpha(41)));
+ }
+
+ #[test]
+ fn line_strength_follows_alpha_like_the_shader() {
+ // Half-clear black over the checker reads dark (0.45): a white line at half strength.
+ assert_eq!(cell_color([0.0, 0.0, 0.0, 0.5]), Some(Color32::from_white_alpha(32)));
+ // Half-clear white reads light (0.95): a black line at half the light-pixel strength.
+ assert_eq!(cell_color([1.0, 1.0, 1.0, 0.5]), Some(Color32::from_black_alpha(20)));
+ let full = cell_color([0.0, 0.0, 0.0, 1.0]);
+ assert_eq!(full, Some(Color32::from_white_alpha(64)));
+ }
+
+ #[test]
+ fn out_of_range_values_do_not_panic() {
+ // NaN colour with a valid alpha reads as dark; alpha past 1 is clamped.
+ assert_eq!(cell_color([f32::INFINITY, f32::NEG_INFINITY, f32::NAN, 5.0]), Some(Color32::from_white_alpha(64)));
+ assert_eq!(cell_color([0.0; 4]), None);
+ }
+
+ fn grid(w: u32, h: u32, f: impl Fn(u32, u32) -> [f32; 4]) -> Vec<[f32; 4]> {
+ (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect()
+ }
+
+ #[test]
+ fn opaque_region_is_one_segment_per_line() {
+ let rect = DRect::from_xywh(0, 0, 6, 4);
+ let segs = segments(&grid(6, 4, |_, _| OPAQUE_DARK), rect);
+ assert_eq!(segs.len(), 6 + 4);
+ let white = Color32::from_white_alpha(64);
+ assert!(segs.contains(&GridSeg { from: [0, 0], to: [0, 4], color: white }));
+ assert!(segs.contains(&GridSeg { from: [5, 0], to: [5, 4], color: white }));
+ assert!(segs.contains(&GridSeg { from: [0, 3], to: [6, 3], color: white }));
+ // No closing line on the right or bottom edge of the region.
+ assert!(!segs.iter().any(|s| s.from[0] == 6 || s.from[1] == 4));
+ }
+
+ #[test]
+ fn empty_region_draws_nothing() {
+ let rect = DRect::from_xywh(0, 0, 8, 8);
+ assert!(segments(&grid(8, 8, |_, _| [0.0; 4]), rect).is_empty());
+ }
+
+ #[test]
+ fn a_lone_pixel_owns_its_left_and_top_edges() {
+ let rect = DRect::from_xywh(10, 20, 5, 5);
+ let px = grid(5, 5, |x, y| if (x, y) == (2, 3) { OPAQUE_DARK } else { [0.0; 4] });
+ let segs = segments(&px, rect);
+ let white = Color32::from_white_alpha(64);
+ assert_eq!(segs.len(), 2);
+ assert!(segs.contains(&GridSeg { from: [12, 23], to: [12, 24], color: white }));
+ assert!(segs.contains(&GridSeg { from: [12, 23], to: [13, 23], color: white }));
+ }
+
+ #[test]
+ fn lines_stop_where_the_pixels_do() {
+ // Left half opaque, right half transparent: vertical lines only on the left half and
+ // the horizontal ones only as long as the opaque part.
+ let rect = DRect::from_xywh(0, 0, 8, 2);
+ let px = grid(8, 2, |x, _| if x < 4 { OPAQUE_DARK } else { [0.0; 4] });
+ let segs = segments(&px, rect);
+ assert_eq!(segs.len(), 4 + 2);
+ assert!(segs.iter().all(|s| s.to[0] <= 4));
+ assert!(segs.contains(&GridSeg { from: [0, 1], to: [4, 1], color: Color32::from_white_alpha(64) }));
+ }
+
+ #[test]
+ fn runs_split_where_the_colour_changes() {
+ let rect = DRect::from_xywh(0, 0, 1, 4);
+ let px = vec![OPAQUE_DARK, OPAQUE_DARK, OPAQUE_LIGHT, OPAQUE_LIGHT];
+ let segs: Vec<_> = segments(&px, rect).into_iter().filter(|s| s.from[0] == s.to[0]).collect();
+ assert_eq!(segs.len(), 2);
+ assert!(segs.contains(&GridSeg { from: [0, 0], to: [0, 2], color: Color32::from_white_alpha(64) }));
+ assert!(segs.contains(&GridSeg { from: [0, 2], to: [0, 4], color: Color32::from_black_alpha(41) }));
+ }
+
+ #[test]
+ fn a_checkered_lattice_is_capped() {
+ let n = 400u32;
+ let rect = DRect::from_xywh(0, 0, n, n);
+ let px = grid(n, n, |x, y| if (x + y) % 2 == 0 { OPAQUE_DARK } else { [0.0; 4] });
+ assert_eq!(segments(&px, rect).len(), MAX_SEGMENTS);
+ }
+
+ #[test]
+ fn short_or_empty_buffers_are_ignored() {
+ assert!(segments(&[], DRect::from_xywh(0, 0, 4, 4)).is_empty());
+ assert!(segments(&[OPAQUE_DARK; 3], DRect::from_xywh(0, 0, 4, 4)).is_empty());
+ assert!(segments(&[], DRect::EMPTY).is_empty());
+ }
+
+ #[test]
+ fn cache_region_snaps_outward_and_stays_in_the_document() {
+ let bounds = DRect::new(0, 0, 1000, 500);
+ assert_eq!(cache_region(DRect::new(70, 10, 130, 90), bounds), DRect::new(64, 0, 192, 128));
+ assert_eq!(cache_region(DRect::new(-50, -50, 2000, 2000), bounds), bounds);
+ assert_eq!(cache_region(DRect::new(900, 400, 1200, 700), bounds), DRect::new(896, 384, 1000, 500));
+ assert!(cache_region(DRect::new(2000, 2000, 2100, 2100), bounds).is_empty());
+ }
+
+ #[test]
+ fn cached_grid_serves_a_pan_inside_its_region_only() {
+ let g = GridLines { revision: 3, preview_key: 7, region: DRect::new(64, 0, 192, 128), segs: Vec::new() };
+ assert!(g.covers(3, 7, &DRect::new(70, 10, 130, 90)));
+ assert!(!g.covers(4, 7, &DRect::new(70, 10, 130, 90)));
+ assert!(!g.covers(3, 8, &DRect::new(70, 10, 130, 90)));
+ assert!(!g.covers(3, 7, &DRect::new(60, 10, 130, 90)));
+ }
+}
diff --git a/crates/ui-egui/tests/checker_canvas.rs b/crates/ui-egui/tests/checker_canvas.rs
index 45892dc99..1480a7ceb 100644
--- a/crates/ui-egui/tests/checker_canvas.rs
+++ b/crates/ui-egui/tests/checker_canvas.rs
@@ -3,7 +3,7 @@
//! 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.
+//! is available. The CPU canvas (no wgpu handed to the app) has its own pixel grid tests at the end.
use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::control::{ControlRequest, handle};
@@ -15,11 +15,16 @@ const LIGHT: u8 = 255;
const DARK: u8 = 204;
fn harness() -> Option<Harness> {
+ harness_with(true)
+}
+
+/// The app with the GPU canvas (`gpu`), or without it: the CPU fallback path.
+fn harness_with(gpu: bool) -> Option<Harness> {
let built = std::panic::catch_unwind(|| {
egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 800.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
- if let Some(rs) = cc.wgpu_render_state.as_ref() {
+ if let Some(rs) = cc.wgpu_render_state.as_ref().filter(|_| gpu) {
app.set_wgpu(rs.clone());
}
app
@@ -82,6 +87,11 @@ impl Shot {
/// 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)
+}
+
+/// [`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() {
@@ -97,14 +107,15 @@ fn render(h: &mut Harness, zoom: f32, doc: u32, black: bool, grid: bool) -> (Sho
}
control(h, "ui.set", json!({"zoom": zoom, "center": [doc as f32 / 2.0, doc as f32 / 2.0]}));
h.run_steps(3);
- assert!(h.state().perf.gpu, "zoom {zoom}: expected the GPU canvas");
+ 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());
let img = Shot { w: 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);
// Black fill is 0 (64 on a grid line), the pasteboard is 39.
- let on_doc = |p: [u8; 4]| if black { p[0] < 12 || (58..=70).contains(&p[0]) } else { is_checker_grey(p) };
+ // (Two CPU grid lines crossing blend twice: about 112.)
+ let on_doc = |p: [u8; 4]| if black { p[0] < 12 || (58..=70).contains(&p[0]) || (105..=120).contains(&p[0]) } else { is_checker_grey(p) };
let (x0, w) = longest_run((0..width).map(|x| on_doc(img.at(x, cy))));
let (y0, hgt) = longest_run((0..height).map(|y| on_doc(img.at(cx, y))));
let doc_px = (doc as f32 * zoom).round() as i64;
@@ -191,3 +202,37 @@ fn pixel_grid_is_not_drawn_over_empty_checker() {
}
}
}
+
+#[test]
+fn cpu_pixel_grid_shows_above_500_percent_over_content() {
+ let Some(mut h) = harness_with(false) else { return };
+ h.run_steps(4);
+ let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true, 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 y = y0 + (zoom * 3.5) as u32;
+ let lit = lit_columns(&img, x0, y, (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:?}");
+ let v = img.at(x0 + lit[2], y)[0];
+ assert!((60..=68).contains(&v), "zoom {zoom}: a grid line over black is {v}, want about 64");
+ }
+}
+
+#[test]
+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.
+ 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);
+ assert_eq!((x0, y0), (x1, y1), "zoom {zoom}: the document moved");
+ for y in y0..y0 + 64 {
+ for x in x0..x0 + 64 {
+ assert_eq!(with.at(x, y), without.at(x, y), "zoom {zoom}: the grid changed empty checker at ({x}, {y})");
+ }
+ }
+ }
+}