diff --git a/crates/render/src/backdrop.rs b/crates/render/src/backdrop.rs index 97aec946b..fc7c946bd 100644 --- a/crates/render/src/backdrop.rs +++ b/crates/render/src/backdrop.rs @@ -117,6 +117,22 @@ pub(crate) fn replace(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, clip: Opti fx::overlap_rows(dst, at, src, |dp, sp, r, c0| { let Some((m, (mx, my))) = clip else { return dp.copy_from_slice(sp) }; let (mw, mh, my) = (i64::from(m.width()), i64::from(m.height()), r + i64::from(my)); + // Most rows of a clip lie wholly inside it (or outside): copied (or kept) in one piece. + let cols = (dp.len() / 4) as i64; + let first = c0 + i64::from(mx); + if my >= 0 + && my < mh + && first >= 0 + && first + cols <= mw + && let Some(row) = m.data().get((my * mw + first) as usize..(my * mw + first + cols) as usize) + { + if row.iter().all(|k| *k == 255) { + return dp.copy_from_slice(sp); + } + if row.iter().all(|k| *k == 0) { + return; + } + } for (c, (d, s)) in (c0..).zip(dp.chunks_exact_mut(4).zip(sp.chunks_exact(4))) { let mx = c + i64::from(mx); let k = if mx >= 0 && my >= 0 && mx < mw && my < mh { u32::from(m.data().get((my * mw + mx) as usize).copied().unwrap_or(0)) } else { 0 }; diff --git a/crates/render/src/clip_cover_tests.rs b/crates/render/src/clip_cover_tests.rs new file mode 100644 index 000000000..8e4deebe1 --- /dev/null +++ b/crates/render/src/clip_cover_tests.rs @@ -0,0 +1,119 @@ +//! A clipping frame that takes in the whole pixmap cuts nothing off there: its children draw +//! without a layer, a mask or a copy back, and look the same. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, NodeId, NodeKind}; +use figcraft_geom::Affine; + +use crate::draw::{NO_COVER_SHORTCUTS, clip_covers}; +use crate::retained_tests::assert_same; +use crate::{Options, Pixmap, View, render_view_single}; + +fn white() -> Options { + Options { background: Some(Color::WHITE), ..Default::default() } +} + +/// A screen (clipping) > a list (clipping) > a card (rounded, clipping) > a picture (rounded, +/// clipping) > a shape; the document, its page and the shape. +fn card() -> (Document, NodeId, NodeId) { + let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())]; + let mut d = Document::new("clips"); + let page = d.first_page().unwrap(); + let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap(); + fill(&mut d, screen, "F4F6F5"); + let list = d.create(screen, NodeKind::Frame, "List", 24.0, 261.0, 342.0, 312.0).unwrap(); + let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap(); + fill(&mut d, card, "FFFFFF"); + d.get_mut(card).unwrap().corners.radii = [20.0; 4]; + let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap(); + fill(&mut d, picture, "CFE3DA"); + d.get_mut(picture).unwrap().corners.radii = [14.0; 4]; + let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap(); + fill(&mut d, shape, "7FAE9C"); + (d, page, shape) +} + +/// A `width` × `height` view at `scale` with the shape in the middle. +fn close_up(d: &Document, shape: NodeId, scale: f64, width: u32, height: u32) -> View { + let b = crate::draw::paint_bounds(d, shape).unwrap(); + let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + View { origin: (cx - f64::from(width) / scale / 2.0, cy - f64::from(height) / scale / 2.0), scale, width, height } +} + +/// The view rendered with and without the shortcut for clips that cut nothing. +fn both(d: &Document, page: NodeId, v: &View) -> (Pixmap, Pixmap) { + let new = render_view_single(d, page, v, &white()).unwrap(); + NO_COVER_SHORTCUTS.with(|f| f.set(true)); + let old = render_view_single(d, page, v, &white()); + NO_COVER_SHORTCUTS.with(|f| f.set(false)); + (new, old.unwrap()) +} + +#[test] +fn views_inside_and_across_clipping_frames_look_the_same() { + let (d, page, shape) = card(); + let views = [ + // Inside the card and its picture; across the picture's round corner; across the card's + // edge and the list's; the whole screen; on fractional pixels. + close_up(&d, shape, 38.66, 300, 200), + View { origin: (504.0, 440.0), scale: 9.0, width: 300, height: 260 }, + View { origin: (480.0, 440.0), scale: 6.0, width: 400, height: 300 }, + View { origin: (460.0, -10.0), scale: 0.5, width: 220, height: 440 }, + View { origin: (500.37, 381.21), scale: 3.3, width: 300, height: 260 }, + ]; + for v in &views { + let (new, old) = both(&d, page, v); + assert_same(&new, &old, &format!("{:?} at {}", v.origin, v.scale)); + } +} + +#[test] +fn a_rotated_frame_clips_as_it_did() { + let mut d = Document::new("rotated"); + let page = d.first_page().unwrap(); + let f = d.create(page, NodeKind::Frame, "F", 100.0, 100.0, 300.0, 200.0).unwrap(); + d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::from_hex("FFE0B0").unwrap())]; + d.get_mut(f).unwrap().transform = figcraft_geom::set_rotation_about_center(d.node(f).unwrap().transform, 300.0, 200.0, 25.0); + let c = d.create(f, NodeKind::Rectangle, "C", -40.0, 40.0, 420.0, 60.0).unwrap(); + d.get_mut(c).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())]; + // The frame's middle (inside it whole), and its corner (cut by two edges). + for v in + [View { origin: (220.0, 170.0), scale: 4.0, width: 200, height: 160 }, View { origin: (60.0, 60.0), scale: 2.0, width: 300, height: 300 }] + { + let (new, old) = both(&d, page, &v); + assert_same(&new, &old, &format!("{:?}", v.origin)); + } +} + +#[test] +fn a_pixmap_in_a_round_corner_is_not_taken_in() { + let mut d = Document::new("corner"); + let page = d.first_page().unwrap(); + let f = d.create(page, NodeKind::Frame, "F", 0.0, 0.0, 200.0, 100.0).unwrap(); + d.get_mut(f).unwrap().corners.radii = [40.0, 0.0, 0.0, 0.0]; + let at = |d: &Document, x: f64, y: f64| clip_covers(d.node(f).unwrap(), Affine::translate((-x, -y)), (10, 10)); + assert!(at(&d, 100.0, 40.0), "the middle"); + assert!(at(&d, 190.0, 0.0), "a square corner, up to the edges"); + assert!(!at(&d, 195.0, 0.0), "across the right edge"); + assert!(!at(&d, 2.0, 2.0), "outside the arc of the round corner"); + assert!(at(&d, 20.0, 20.0), "inside the arc"); + assert!(!at(&d, 5.0, 20.0), "across the arc"); + // A smoothed corner turns further along its edges: its whole square counts as cut off. + d.get_mut(f).unwrap().corners.smoothing = 0.6; + assert!(!at(&d, 20.0, 20.0), "smoothed: the corner's square is left out"); + assert!(at(&d, 100.0, 40.0), "smoothed: the middle"); +} + +#[test] +fn a_view_inside_clipping_frames_holds_no_layer_for_them() { + let (d, page, shape) = card(); + let v = close_up(&d, shape, 38.66, 600, 300); + let held = || crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&d, page, &v, &Options::default())).1; + // The view lies inside the screen, the list, the card and the picture: none of their clips + // cuts it. Each held a copy of the view while its children drew. + assert_eq!(held(), 0, "no layer for a clip that cuts nothing"); + NO_COVER_SHORTCUTS.with(|f| f.set(true)); + let before = held(); + NO_COVER_SHORTCUTS.with(|f| f.set(false)); + assert!(before >= u64::from(v.width) * u64::from(v.height) * 4, "as it was: {before} bytes held"); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index de0a05fc6..0772fcaa2 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -611,6 +611,12 @@ pub(crate) const MAX_REACH: f64 = 1e12; /// result (drop shadows from the blurred layer, a backdrop blurred with it), so the largest of /// those reaches comes on top. Each reach counts up to [`MAX_REACH`], so the sum stays finite. pub fn effect_margin(n: &Node) -> f64 { + margin_of(n, true) +} + +/// [`effect_margin`], with or without what drop shadows reach (`drops`): shadows cast from the +/// layer's outline ([`shadow::outline_caster`]) read none of its pixels. +fn margin_of(n: &Node, drops: bool) -> f64 { let visible = || n.effects.iter().filter(|e| e.visible); let finite = |m: f64| if m.is_finite() { m.clamp(0.0, MAX_REACH) } else { 0.0 }; let layer: f64 = visible() @@ -624,7 +630,9 @@ pub fn effect_margin(n: &Node) -> f64 { let others = visible() .map(|e| match &e.kind { EffectKind::BackgroundBlur { .. } | EffectKind::Glass(_) => e.backdrop_radius() * 2.0, - EffectKind::DropShadow(s) => s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs(), + EffectKind::DropShadow(s) if drops => { + s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs() + } // Inner shadows cast from around a layer's pixels (groups, image fills with alpha; any // image counts here): a layer cut off at the view would cast one from the cut. EffectKind::InnerShadow(s) @@ -772,6 +780,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u // Isolated layer covering the node's paint bounds, clipped to the visible area + margin. Its // origin can be negative (inside the margin); the size counts from there, or a layer starting // above or left of the pixmap came out short by the margin (a band missing at its far edge). + // Drop shadows cast from the layer's outline need none of its pixels: the layer then ends + // where the pixmap does (plus what its other effects read), however far the shadows reach. + let cast_outline = if ctx.lod || backdrop::has_effects(n) { None } else { shadow::outline_caster(ctx.doc, n) }; + let view = match &cast_outline { + Some(_) => { + let m = (margin_of(n, false) * ctx.scale).min(MAX_EFFECT_MARGIN_PX); + Rect::new(0.0, 0.0, f64::from(pw), f64::from(ph)).inflate(m, m) + } + None => view, + }; let vis = dev.intersect(view); let (x0, y0) = (vis.x0.floor(), vis.y0.floor()); let (w, h) = (vis.x1.ceil() - x0, vis.y1.ceil() - y0); @@ -843,7 +861,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u layer_effects(ctx, &mut layer, n, id, lxf); } // Drop shadows go under the layer, in effect-list order. - { + if let Some(outlines) = &cast_outline { + let cover = shadow::hiding_cover(ctx.doc, n); + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::DropShadow(s) = &e.kind + && let Some((sh, at)) = shadow::outline_drop_shadow(outlines, cover.as_deref().unwrap_or(outlines), s, xf, ctx.scale, (pw, ph)) + { + composite(pix, at, &sh, op, s.blend); + } + } + } else { // Kept apart, the backdrop isn't in the layer yet: the shadows are cast from the content // with the layer effects it will get (a copy only when it gets some). let layer_fx = @@ -1187,6 +1214,12 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept let (pw, ph) = (pix.width(), pix.height()); let dev = device_rect(xf, n.local_rect()); let Some(ir) = int_rect(dev, (pw, ph)) else { return }; + // A clip that takes in the whole pixmap cuts nothing off here (a frame larger than the view, + // or than the band or patch of it being drawn): the children draw as they are. + if clip_covers(n, xf, (pw, ph)) { + draw_children(ctx, pix, n, xf, depth); + return; + } let Some(_held) = crate::layer_budget::Held::take(ir.width(), ir.height(), 1) else { return }; let (lx, ly) = (ir.x(), ir.y()); // The layer starts as what lies under it and goes back in its place through the clip: @@ -1195,7 +1228,7 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept let Some(mut layer) = pix.clone_rect(ir) else { return }; let lxf = Affine::translate((-f64::from(lx), -f64::from(ly))) * xf; let square_aligned = n.corners.uniform() == Some(0.0) && is_axis_aligned(xf); - let rect_clip = square_aligned && on_whole_pixels(dev); + let rect_clip = square_aligned && on_whole_pixels(dev, (pw, ph)); // The clip (a rectangular one on whole pixels is the layer's own box) is known before the // children draw, so their backdrops are clipped the way the layer will be. An axis-aligned // square frame with fractional edges gets an anti-aliased mask of its box so its edge pixels @@ -1246,8 +1279,70 @@ fn fract_ok(_v: f64) -> bool { true } -/// Whether all four edges of the device rectangle `r` lie on whole pixels, up to the float noise -/// `snap_px` forgives. -fn on_whole_pixels(r: Rect) -> bool { - [r.x0, r.y0, r.x1, r.y1].into_iter().all(|v| (snap_px(v) - v.round()).abs() < 1e-9) +#[cfg(test)] +thread_local! { + /// Tests: no clip or shadow is skipped for taking in the whole pixmap ([`clip_covers`]). + pub(crate) static NO_COVER_SHORTCUTS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether the edges of the device rectangle `r` that cross a `size` pixmap lie on whole pixels, +/// up to the float noise `snap_px` forgives. An edge at or past the pixmap's own cuts no pixel +/// of it in part, wherever it lies. +fn on_whole_pixels(r: Rect, size: (u32, u32)) -> bool { + let whole = |v: f64| (snap_px(v) - v.round()).abs() < 1e-9; + let (w, h) = (f64::from(size.0), f64::from(size.1)); + (r.x0 <= 0.0 || whole(r.x0)) && (r.y0 <= 0.0 || whole(r.y0)) && (r.x1 >= w || whole(r.x1)) && (r.y1 >= h || whole(r.y1)) +} + +/// Whether the box of frame `n` (its rounded corners cut off), drawn at `xf`, takes in every +/// pixel of a `size` pixmap: its clip then cuts nothing there. Errs towards `false`: smoothed +/// corners count as cut off square. +pub(crate) fn clip_covers(n: &Node, xf: Affine, size: (u32, u32)) -> bool { + #[cfg(test)] + if NO_COVER_SHORTCUTS.with(std::cell::Cell::get) { + return false; + } + let (w, h) = (n.width, n.height); + let det = xf.determinant(); + if !(det.is_finite() && det.abs() > 1e-12 && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return false; + } + let max_r = w.min(h) / 2.0; + let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 }; + // Top-left, top-right, bottom-right, bottom-left: the corner and its radius. + let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r }); + let corners = [(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])]; + let inside = |p: figcraft_geom::Point| { + if !(p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) { + return false; + } + corners.iter().all(|(cx, cy, r)| { + let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs()); + let zone = r * (1.0 + smooth); + // Outside the corner's square, or (a round corner) within its arc. + dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r) + }) + }; + let inv = xf.inverse(); + let (pw, ph) = (f64::from(size.0), f64::from(size.1)); + [(0.0, 0.0), (pw, 0.0), (pw, ph), (0.0, ph)].into_iter().all(|p| inside(inv * figcraft_geom::Point::new(p.0, p.1))) +} + +/// Whether point `p` (local) lies in the box of `n`, its rounded corners cut off. Errs towards +/// `false`: smoothed corners count as cut off square. +pub(crate) fn in_box(n: &Node, p: figcraft_geom::Point) -> bool { + let (w, h) = (n.width, n.height); + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 && p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) { + return false; + } + let max_r = w.min(h) / 2.0; + let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 }; + // Top-left, top-right, bottom-right, bottom-left: the corner and its radius. + let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r }); + [(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])].iter().all(|(cx, cy, r)| { + let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs()); + let zone = r * (1.0 + smooth); + // Outside the corner's square, or (a round corner) within its arc. + dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r) + }) } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index fd5f3764c..78de1a0d9 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -242,6 +242,90 @@ pub fn tint(p: &mut Pixmap, color: [f32; 4]) { } } +/// What [`tint`] makes of each alpha: the premultiplied pixel of `color` at that coverage. +pub fn tints(color: [f32; 4]) -> [[u8; 4]; 256] { + let [r, g, b, a] = color; + let mut out = [[0u8; 4]; 256]; + for (i, px) in out.iter_mut().enumerate() { + let alpha = i as f32 / 255.0 * a; + let q = |c: f32| (c * alpha * 255.0).round().clamp(0.0, 255.0) as u8; + *px = [q(r), q(g), q(b), (alpha * 255.0).round().clamp(0.0, 255.0) as u8]; + } + out +} + +/// `dst` from the alpha of `src`, tinted (see [`tints`]): `dst`'s pixel (0, 0) is `src`'s pixel +/// `at`; past `src`'s edges is empty. +pub fn copy_alpha(src: &Pixmap, dst: &mut Pixmap, at: (i32, i32), tints: &[[u8; 4]; 256]) { + let (sw, sh, dw) = (i64::from(src.width()), i64::from(src.height()), dst.width() as usize); + let s = src.data().as_chunks::<4>().0; + for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw.max(1)).enumerate() { + let sy = y as i64 + i64::from(at.1); + for (x, px) in row.iter_mut().enumerate() { + let sx = x as i64 + i64::from(at.0); + let a = if (0..sw).contains(&sx) && (0..sh).contains(&sy) { s.get((sy * sw + sx) as usize).map_or(0, |p| p[3]) } else { 0 }; + *px = tints.get(usize::from(a)).copied().unwrap_or_default(); + } + } +} + +/// Steps between two samples of [`enlarge_alpha`] (a power of two: weights are whole numbers). +const LERP_STEPS: i64 = 256; + +/// Where on a line of `len` samples position `at` lies: the sample before it and how far on to +/// the next it is, in [`LERP_STEPS`]; `None` further than a sample past either end. +fn lerp_at(at: f64, len: usize) -> Option<(i64, u32)> { + // Rounded to a step first: positions a float's noise apart then weigh the same. + let steps = (at * LERP_STEPS as f64).round(); + if !(steps.is_finite() && steps >= -(LERP_STEPS as f64) && steps <= (len as f64) * LERP_STEPS as f64) { + return None; + } + let steps = steps as i64; + Some((steps.div_euclid(LERP_STEPS), steps.rem_euclid(LERP_STEPS) as u32)) +} + +/// `dst` from the alpha of `src` drawn larger, between its samples (bilinear), tinted (see +/// [`tints`]): `dst`'s pixel (0, 0) lies at position `at` among `src`'s pixel centres and each +/// pixel on is `step` of a `src` pixel further. Past `src`'s edges is empty. +pub fn enlarge_alpha(src: &Pixmap, dst: &mut Pixmap, at: (f64, f64), step: f64, tints: &[[u8; 4]; 256]) { + let (sw, sh, dw) = (src.width() as usize, src.height() as usize, dst.width() as usize); + if sw == 0 || sh == 0 || dw == 0 { + return; + } + let s = src.data().as_chunks::<4>().0; + let cols: Vec> = (0..dw).map(|x| lerp_at(at.0 + x as f64 * step, sw)).collect(); + // One row of `src` between its samples, for every column of `dst`, in 1/256ths of 255. + let line = |y: i64, out: &mut [u32]| { + let row = usize::try_from(y).ok().filter(|y| *y < sh).and_then(|y| s.get(y * sw..(y + 1) * sw)); + let a = |x: i64| row.and_then(|r| usize::try_from(x).ok().and_then(|x| r.get(x))).map_or(0, |p| u32::from(p[3])); + for (o, c) in out.iter_mut().zip(&cols) { + *o = c.map_or(0, |(x, t)| a(x) * (LERP_STEPS as u32 - t) + a(x + 1) * t); + } + }; + let (mut top, mut bottom) = (vec![0u32; dw], vec![0u32; dw]); + let mut held: Option = None; + for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw).enumerate() { + let Some((sy, t)) = lerp_at(at.1 + y as f64 * step, sh) else { + row.fill([0; 4]); + continue; + }; + if held != Some(sy) { + if held == Some(sy - 1) { + std::mem::swap(&mut top, &mut bottom); + } else { + line(sy, &mut top); + } + line(sy + 1, &mut bottom); + held = Some(sy); + } + let half = (LERP_STEPS * LERP_STEPS / 2) as u32; + for ((px, a), b) in row.iter_mut().zip(&top).zip(&bottom) { + let v = (a * (LERP_STEPS as u32 - t) + b * t + half) / (LERP_STEPS * LERP_STEPS) as u32; + *px = tints.get(v.min(255) as usize).copied().unwrap_or_default(); + } + } +} + /// Invert the alpha (premultiplied white with alpha 1-a): used for inner shadows. pub fn invert_alpha(p: &mut Pixmap) { for px in p.data_mut().as_chunks_mut::<4>().0 { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 495b19507..9656f25c5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -675,6 +675,8 @@ mod boolean_radius_tests; #[cfg(test)] mod bounds_memo_tests; #[cfg(test)] +mod clip_cover_tests; +#[cfg(test)] mod dots_tests; #[cfg(test)] mod effect_order_tests; @@ -709,6 +711,8 @@ mod magnified_image_tests; #[cfg(test)] mod mask_bounds_tests; #[cfg(test)] +mod outline_shadow_tests; +#[cfg(test)] mod paint_behaviour_tests; #[cfg(test)] mod pan_bench_tests; @@ -734,3 +738,5 @@ mod stroke_reach_tests; mod tests; #[cfg(test)] mod width_tests; +#[cfg(test)] +mod zoom_bench_tests; diff --git a/crates/render/src/outline_shadow_tests.rs b/crates/render/src/outline_shadow_tests.rs new file mode 100644 index 000000000..d803c636f --- /dev/null +++ b/crates/render/src/outline_shadow_tests.rs @@ -0,0 +1,212 @@ +//! Drop shadows cast from a layer's outline ([`crate::shadow::outline_caster`]) look as the ones +//! cast from its pixels do, in every piece a view is rendered in, and cost what shows of them. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{EffectKind, NodeId, Shadow}; + +use crate::shadow::FROM_PIXELS; +use crate::zoom_bench_tests::{Card, SCALE, card, close_up}; +use crate::{Options, Pixmap, View, render_band, render_view_single}; + +fn white() -> Options { + Options { background: Some(Color::WHITE), ..Default::default() } +} + +/// The view rendered with shadows cast from outlines, and from pixels (as they all were). +fn both(c: &Card, v: &View) -> (Pixmap, Pixmap) { + let new = render_view_single(&c.doc, c.page, v, &white()).unwrap(); + FROM_PIXELS.with(|f| f.set(true)); + let old = render_view_single(&c.doc, c.page, v, &white()); + FROM_PIXELS.with(|f| f.set(false)); + (new, old.unwrap()) +} + +/// The largest difference of a channel between two renders of view `v`, under the card: where +/// only its shadow paints. (The card's own edges differ a little with where a layer's pixmap +/// ends, whatever casts the shadow: curves are flattened from where the pixmap cuts them.) +fn furthest(v: &View, a: &Pixmap, b: &Pixmap) -> u8 { + let from = (((CARD_BOTTOM - v.origin.1) * v.scale).ceil() as usize + 2) * v.width as usize * 4; + assert!(from < a.data().len(), "the view shows what is under the card"); + a.data().iter().zip(b.data()).skip(from).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0) +} + +/// The card's bottom edge on the page. +const CARD_BOTTOM: f64 = 465.0; + +fn shadow_of(c: &mut Card, f: impl FnOnce(&mut Shadow)) { + for e in &mut c.doc.get_mut(c.card).unwrap().effects { + if let EffectKind::DropShadow(s) = &mut e.kind { + f(s); + return; + } + } +} + +/// The card's bottom-left corner and the shadow under it, `scale` device pixels a unit. +fn corner(scale: f64) -> View { + View { origin: (480.0, 440.0), scale, width: (50.0 * scale) as u32, height: (40.0 * scale) as u32 } +} + +fn darkest(p: &Pixmap) -> u8 { + p.data().as_chunks::<4>().0.iter().map(|c| c[0]).min().unwrap_or(255) +} + +#[test] +fn a_shadow_blurred_little_is_the_one_cast_from_the_layers_pixels() { + let mut c = card(true); + // A blur of 3 device pixels: drawn at full resolution, a dark shadow so it shows. + shadow_of(&mut c, |s| (s.radius, s.color) = (6.0, Color { a: 0.8, ..Color::BLACK })); + for scale in [1.0, 1.37] { + let (new, old) = both(&c, &corner(scale)); + assert!(darkest(&new) < 120, "a shadow shows at {scale}"); + assert_eq!(furthest(&corner(scale), &new, &old), 0, "at {scale}"); + } +} + +#[test] +fn a_shadow_blurred_widely_looks_as_the_one_cast_from_the_layers_pixels() { + for (spread, offset, behind) in [(0.0, (0.0, 4.0), false), (3.0, (2.5, 4.0), false), (-2.0, (0.0, 6.0), false), (0.0, (0.0, 4.0), true)] { + let mut c = card(true); + shadow_of(&mut c, |s| { + (s.spread, s.offset, s.show_behind, s.color) = (spread, offset, behind, Color { a: 0.8, ..Color::BLACK }); + }); + // A frame's shadow spreads from its outline when it clips (from its pixels otherwise). + c.doc.get_mut(c.card).unwrap().clip = spread != 0.0; + if behind { + // What shows of a shadow behind its layer: through a see-through picture, not the card. + let n = c.doc.get_mut(c.card).unwrap(); + n.fills = vec![Paint::solid(Color::WHITE)]; + } + // Blurs of 16 to 309 device pixels: drawn 4 to 64 times smaller. + for scale in [4.0, 9.3, SCALE] { + let v = if scale == SCALE { View { origin: (488.0, 452.0), scale, width: 700, height: 900 } } else { corner(scale) }; + let (new, old) = both(&c, &v); + assert!(darkest(&new) < 200, "a shadow shows at {scale}"); + let d = furthest(&v, &new, &old); + assert!(d <= 4, "spread {spread}, offset {offset:?}, behind {behind}, at {scale}: {d} apart"); + } + } +} + +#[test] +fn bands_and_one_piece_draw_the_same_wide_shadow() { + let mut c = card(true); + shadow_of(&mut c, |s| s.color = Color { a: 0.8, ..Color::BLACK }); + for scale in [9.3, SCALE] { + let v = View { origin: (488.3, 452.7), scale, width: 640, height: 600 }; + let whole = render_view_single(&c.doc, c.page, &v, &white()).unwrap(); + let mut bands = Pixmap::new(v.width, v.height).unwrap(); + for y0 in (0..v.height).step_by(75) { + let part = render_band(&c.doc, c.page, &v, &white(), y0, 75, 0).unwrap(); + crate::put_band(&mut bands, y0, &part); + } + assert_eq!(furthest(&v, &bands, &whole), 0, "at {scale}"); + } +} + +#[test] +fn a_layer_with_a_shadow_holds_no_more_than_the_view() { + let c = card(true); + let v = close_up(&c, 1200, 800); + let view_bytes = u64::from(v.width) * u64::from(v.height) * 4; + let (pix, peak) = crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&c.doc, c.page, &v, &Options::default())); + assert!(pix.is_some()); + // The card's layer, and the clips inside and around it: each the view at most. Cast from the + // layer's pixels, the layer alone was the view and 1,392 pixels more each way. + assert!(peak <= view_bytes * 6, "{} MB held for a view of {} MB", peak >> 20, view_bytes >> 20); +} + +#[test] +fn layers_that_are_not_their_outline_cast_from_their_pixels() { + let caster = |f: fn(&mut Card) -> NodeId| { + let mut c = card(true); + let id = f(&mut c); + crate::shadow::outline_caster(&c.doc, c.doc.node(id).unwrap()).is_some() + }; + assert!(caster(|c| c.card), "an opaque frame whose children stay inside it"); + assert!(caster(|c| { + c.doc.get_mut(c.card).unwrap().clip = true; + c.card + })); + assert!(!caster(|c| { + c.doc.get_mut(c.card).unwrap().fills = vec![Paint::solid(Color { a: 0.5, ..Color::WHITE })]; + c.card + })); + // A child past the card's edge, or in the corner its rounding cuts off, casts a shadow too. + assert!(!caster(|c| { + let picture = c.doc.node(c.shape).unwrap().parent.unwrap(); + c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((300.0, 12.0)); + c.card + })); + assert!(!caster(|c| { + shadow_of(c, |s| s.spread = 2.0); + c.card + })); + assert!(!caster(|c| { + let picture = c.doc.node(c.shape).unwrap().parent.unwrap(); + c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0)); + c.card + })); + assert!(caster(|c| { + let picture = c.doc.node(c.shape).unwrap().parent.unwrap(); + c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0)); + c.doc.get_mut(c.card).unwrap().clip = true; + c.card + })); + assert!(!caster(|c| { + c.doc + .get_mut(c.card) + .unwrap() + .effects + .push(figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(2.0)), visible: true }); + c.card + })); +} + +/// A rectangle with a dark shadow of `radius` and `spread`, drawn through `transform`. +fn slab(transform: figcraft_geom::Affine, size: (f64, f64), radius: f64, spread: f64) -> (figcraft_doc::Document, NodeId) { + let mut d = figcraft_doc::Document::new("slab"); + let page = d.first_page().unwrap(); + let r = d.create(page, figcraft_doc::NodeKind::Rectangle, "Slab", 0.0, 0.0, size.0, size.1).unwrap(); + let n = d.get_mut(r).unwrap(); + n.transform = transform; + n.fills = vec![Paint::solid(Color::WHITE)]; + n.effects.push(figcraft_doc::Effect { + kind: EffectKind::DropShadow(Shadow { radius, spread, offset: (0.0, 0.0), color: Color::BLACK, ..Shadow::default() }), + visible: true, + }); + (d, page) +} + +/// A spread grows the outline in the layer's own units: stretched six times one way and squeezed +/// as much the other, it reaches six times as far that way, not as far as the scale of an area +/// (here 1) says. +#[test] +fn a_spread_reaches_as_far_as_the_layer_is_stretched() { + let stretched = figcraft_geom::Affine::translate((120.0, 60.0)) * figcraft_geom::Affine::scale_non_uniform(6.0, 1.0 / 6.0); + let (d, page) = slab(stretched, (20.0, 240.0), 0.0, 10.0); + let v = View { origin: (0.0, 0.0), scale: 1.0, width: 360, height: 160 }; + let new = render_view_single(&d, page, &v, &white()).unwrap(); + FROM_PIXELS.with(|f| f.set(true)); + let old = render_view_single(&d, page, &v, &white()).unwrap(); + FROM_PIXELS.with(|f| f.set(false)); + // Black 50 pixels left of the slab (its spread is 60 there), in both. + let at = |p: &Pixmap, x: usize, y: usize| p.data()[(y * 360 + x) * 4]; + assert_eq!((at(&new, 70, 80), at(&old, 70, 80)), (0, 0), "the shadow 50 pixels out"); + let apart = new.data().iter().zip(old.data()).filter(|(a, b)| a.abs_diff(**b) > 8).count(); + assert!(apart < 400, "{apart} channels apart"); +} + +/// A shadow across a view as wide as a pixmap gets is drawn: the pixmap it is blurred in is a +/// blur's reach wider still. +#[test] +fn a_shadow_shows_across_the_widest_view() { + let (d, page) = slab(figcraft_geom::Affine::translate((-100.0, 4.0)), (17_000.0, 10.0), 6.0, 0.0); + let v = View { origin: (0.0, 0.0), scale: 1.0, width: 16_384, height: 30 }; + let pix = render_view_single(&d, page, &v, &white()).unwrap(); + // Two rows under the slab (white without a shadow), at both ends and in the middle. + for x in [10usize, 8_000, 16_370] { + let red = pix.data()[(16 * 16_384 + x) * 4]; + assert!(red < 245, "a shadow under the slab at {x}: {red}"); + } +} diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index cf08b4b99..2d8bbdce3 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use figcraft_doc::{Document, EffectKind, NodeId, NodeKind}; use figcraft_geom::Rect; -use tiny_skia::{IntRect, Pixmap, PixmapPaint, Transform}; +use tiny_skia::Pixmap; use crate::{Options, View, draw, render_view}; @@ -721,14 +721,17 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> // The same pixel grid as the frame: origin (px + offset) / scale. let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh }; let part = crate::render_part(doc, page, &sub, opts)?; - let inner = IntRect::from_xywh( - i32::try_from(d.x0 - ox).ok()?, - i32::try_from(d.y0 - oy).ok()?, - u32::try_from(d.x1 - d.x0).ok()?, - u32::try_from(d.y1 - d.y0).ok()?, - )?; - let inner = part.clone_rect(inner)?; - let copy = PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() }; - pix.draw_pixmap(i32::try_from(d.x0).ok()?, i32::try_from(d.y0).ok()?, inner.as_ref(), ©, Transform::identity(), None); + // The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the + // copy took longer than rendering a simple part). + let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?); + let (cols, rows) = (usize::try_from(d.x1 - d.x0).ok()?, usize::try_from(d.y1 - d.y0).ok()?); + let (at_x, at_y) = (usize::try_from(d.x0).ok()?, usize::try_from(d.y0).ok()?); + let (src_w, dst_w) = (part.width() as usize, pix.width() as usize); + let dst = pix.data_mut(); + for (r, row) in part.data().chunks_exact(src_w.max(1) * 4).skip(skip_y).take(rows).enumerate() { + let from = row.get(skip_x * 4..(skip_x + cols) * 4)?; + let start = ((at_y + r) * dst_w + at_x) * 4; + dst.get_mut(start..start + cols * 4)?.copy_from_slice(from); + } Some(()) } diff --git a/crates/render/src/shadow.rs b/crates/render/src/shadow.rs index 7ed7c4d65..068f79407 100644 --- a/crates/render/src/shadow.rs +++ b/crates/render/src/shadow.rs @@ -61,10 +61,15 @@ pub fn inner_from_pixels(doc: &Document, n: &Node) -> bool { } fn outlines(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool) -> Option> { + outlines_with(doc, n, fill_counts, false) +} + +/// [`outlines`]; `kids_within`: the caller knows the children paint nothing outside the outline. +fn outlines_with(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool, kids_within: bool) -> Option> { let has_fill = n.fills.iter().any(fill_counts); let is_bool = matches!(n.kind, NodeKind::BooleanOp { .. }); let is_text = matches!(n.kind, NodeKind::Text(_)); - let kids = !is_bool && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible)); + let kids = !is_bool && !kids_within && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible)); if matches!(n.kind, NodeKind::Group | NodeKind::Page { .. }) || (kids && !(n.kind.is_frame_like() && n.clip && has_fill)) || (is_text && n.has_visible_stroke()) @@ -286,3 +291,150 @@ fn inner_from(mut big: Pixmap, pad: u32, cover: &Pixmap, scale: f64, s: &Shadow) fx::tint(&mut out, color4(s.color)); Some(out) } + +/// Whether `p` paints every pixel it covers at full alpha: a visible, opaque solid colour. +fn opaque(p: &Paint) -> bool { + p.visible && p.opacity >= 1.0 && p.blend == figcraft_color::BlendMode::Normal && matches!(&p.kind, PaintKind::Solid { color } if color.a >= 1.0) +} + +/// The outlines node `n`'s drop shadows are cast from when its pixels are those outlines, filled: +/// a shape or a clipping frame whose paints are opaque colours and that has no effect that moves +/// its pixels. Such a shadow needs none of the layer's pixels, so it is drawn only where it +/// shows and blurred at the resolution its radius needs ([`outline_drop_shadow`]), not from a +/// copy of the layer reaching past the view. `None`: the shadows come from the layer's pixels. +pub fn outline_caster(doc: &Document, n: &Node) -> Option> { + #[cfg(test)] + if FROM_PIXELS.with(std::cell::Cell::get) { + return None; + } + let shape = + n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Polygon { .. } | NodeKind::Star { .. }); + let plain = n.effects.iter().filter(|e| e.visible).all(|e| matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_))); + let fills = n.fills.iter().any(opaque); + let strokes = !n.has_visible_stroke() || n.strokes.iter().filter(|s| s.visible).all(opaque); + if !(shape && plain && fills && strokes && figcraft_doc::geometry::is_closed(n)) { + return None; + } + // A frame that doesn't clip is its outline too while its children stay inside it. Its + // shadows spread as its pixels do (see the module docs), not as an outline: those stay. + let within = n.kind.is_frame_like() && !n.clip && drop_shadows(n).all(|s| s.spread == 0.0) && children_within(doc, n); + outlines_with(doc, n, |f| f.visible && f.opacity > 0.0, within) +} + +/// Whether everything the children of frame `n` paint (effects and all) lies inside its box, its +/// rounded corners cut off: they then add nothing to the pixels its fill covers. +fn children_within(doc: &Document, n: &Node) -> bool { + let world = doc.world_transform(n.id); + let det = world.determinant(); + if !(det.is_finite() && det.abs() > 1e-12) { + return false; + } + let to_local = world.inverse(); + n.children.iter().filter(|c| doc.node(**c).is_some_and(|c| c.visible)).all(|c| { + crate::draw::paint_bounds(doc, *c).is_some_and(|b| { + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] + .into_iter() + .all(|p| crate::draw::in_box(n, to_local * figcraft_geom::Point::new(p.0, p.1))) + }) + }) +} + +#[cfg(test)] +thread_local! { + /// Tests: every drop shadow is cast from its layer's pixels, as before [`outline_caster`]. + pub(crate) static FROM_PIXELS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Shadows blurred by less than this many device pixels (standard deviation) are drawn at full +/// resolution, as they always were. +const FULL_RES_SIGMA: f64 = 8.0; +/// The most a shadow is drawn smaller by before its blur: a blur of 4 to 8 small pixels. +const MAX_SMALLER: u32 = 256; + +/// The longest side of a pixmap. +const MAX_SIDE: u32 = 16_384; +/// What the pixmap a shadow is blurred in may have more than [`MAX_SIDE`] a side: the blur's +/// reach both ways at full resolution (under [`FULL_RES_SIGMA`]: 34 pixels) and a pixel's slack. +/// Drawn smaller, it is far under the limit. +const BLUR_ROOM: u32 = 128; + +/// A whole pixel range `[lo, hi)` as `(start, length)`; `None` when empty or longer than `most`. +fn span(lo: f64, hi: f64, most: u32) -> Option<(i32, u32)> { + if !(lo.is_finite() && hi.is_finite() && hi > lo && lo.abs() < 1e9 && hi.abs() < 1e9) { + return None; + } + let len = (hi - lo) as u32; + (1..=most).contains(&len).then_some((lo as i32, len)) +} + +/// The most `xf` stretches a length, in any direction (its largest singular value): how far a +/// distance in local units can reach on the pixmap. +fn stretch(xf: Affine) -> f64 { + let c = xf.as_coeffs(); + let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3]; + let det = c[0] * c[3] - c[1] * c[2]; + ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt() +} + +/// The drop shadow `s` cast by `outlines` (local space, drawn at `xf` into a `size` pixmap), where +/// it shows on that pixmap: the shadow's pixels and where their top-left goes. Unless it shows +/// behind the layer, it is hidden behind `cover`. +/// +/// A shadow blurred widely is drawn `k` times smaller, blurred there and scaled back up: a wide +/// blur has no detail a pixel across. The small pixels line up with the shape, not with the +/// pixmap, so every render of a view (a band, a patch, the whole of it) draws the same shadow. +pub fn outline_drop_shadow( + outlines: &[Outline], + cover: &[Outline], + s: &Shadow, + xf: Affine, + scale: f64, + size: (u32, u32), +) -> Option<(Pixmap, (i32, i32))> { + let spread = if s.spread.is_finite() { s.spread } else { 0.0 }; + let sigma = (s.radius / 2.0 * scale).min(fx::MAX_SIGMA); + let sigma = if sigma.is_finite() && sigma > 0.3 { sigma } else { 0.0 }; + // As from the layer's pixels: without a spread the offset is whole pixels. + let (dx, dy) = (s.offset.0 * scale, s.offset.1 * scale); + let (dx, dy) = if spread != 0.0 && dx.is_finite() && dy.is_finite() { (dx, dy) } else { (f64::from(whole_px(dx)), f64::from(whole_px(dy))) }; + let cast = Affine::translate((dx, dy)) * xf; + // Where the shadow can show: its outlines, spread and blurred, on the pixmap. + let reach = (sigma * 4.0).ceil() + 2.0; + // A spread grows the outline in local units: on the pixmap, as far as the transform + // stretches them the most (it need not scale both ways alike). + let px = stretch(xf); + let grown = if px.is_finite() { (spread.abs() * px * SPREAD_MITER_LIMIT).min(MAX_SPREAD_PX) } else { 0.0 }; + let shape = + outlines.iter().map(|(p, _)| figcraft_geom::transform_rect_bbox(cast, figcraft_geom::Shape::bounding_box(p))).reduce(|a, b| a.union(b))?; + let shows = shape.inflate(grown + reach, grown + reach).intersect(figcraft_geom::Rect::new(0.0, 0.0, f64::from(size.0), f64::from(size.1))); + let (x0, w) = span(shows.x0.floor(), shows.x1.ceil(), MAX_SIDE)?; + let (y0, h) = span(shows.y0.floor(), shows.y1.ceil(), MAX_SIDE)?; + let smaller = if sigma >= FULL_RES_SIGMA { (2f64.powi((sigma / 4.0).log2().floor() as i32) as u32).clamp(1, MAX_SMALLER) } else { 1 }; + let k = f64::from(smaller); + // The small pixmap's pixels are `k` device pixels a side, counted from the shape's origin + // (the pixmap's own pixels when nothing is drawn smaller): those the shadow's area and + // what blurs into it take in. + let c = cast.as_coeffs(); + let (ax, ay) = if smaller > 1 { (c[4], c[5]) } else { (0.0, 0.0) }; + let (i0, lw) = + span(((f64::from(x0) - reach - ax) / k).floor() - 1.0, ((f64::from(x0) + f64::from(w) + reach - ax) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?; + let (j0, lh) = + span(((f64::from(y0) - reach - ay) / k).floor() - 1.0, ((f64::from(y0) + f64::from(h) + reach - ay) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?; + let small = Affine::new([c[0] / k, c[1] / k, c[2] / k, c[3] / k, (c[4] - ax) / k - f64::from(i0), (c[5] - ay) / k - f64::from(j0)]); + let mut low = spread_alpha(outlines, spread, small, lw, lh)?; + fx::blur(&mut low, sigma / k); + let mut out = Pixmap::new(w, h)?; + let tints = fx::tints(color4(s.color)); + if smaller > 1 { + // Device pixel centre → small pixel centres. + let at = |v: i32, a: f64, first: i32| (f64::from(v) + 0.5 - a) / k - 0.5 - f64::from(first); + fx::enlarge_alpha(&low, &mut out, (at(x0, ax, i0), at(y0, ay, j0)), 1.0 / k, &tints); + } else { + fx::copy_alpha(&low, &mut out, (x0 - i0, y0 - j0), &tints); + } + if !s.show_behind { + let hides = spread_alpha(cover, 0.0, Affine::translate((-f64::from(x0), -f64::from(y0))) * xf, w, h)?; + fx::mask_by(&mut out, &hides, true); + } + Some((out, (x0, y0))) +} diff --git a/crates/render/src/zoom_bench_tests.rs b/crates/render/src/zoom_bench_tests.rs new file mode 100644 index 000000000..d7e914376 --- /dev/null +++ b/crates/render/src/zoom_bench_tests.rs @@ -0,0 +1,126 @@ +//! Timings of a shadowed card seen close up: a small shape inside a rounded picture inside a +//! rounded card with a drop shadow, inside two stacks and a screen, at 1,933% on a 2× display +//! (38.66 device pixels a unit, 4112 × 2292 device pixels). The mobile app template's trail card, +//! where the browser took 16.6 s for one render and 2 s for each frame of an edit. +//! +//! Run in release, on one thread as the browser does: +//! `RAYON_NUM_THREADS=1 cargo test --release -p figcraft-render --lib zoomed_card_timings -- --ignored --nocapture`. + +use std::sync::Arc; +use std::time::Instant; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow}; + +use crate::{Begun, Options, Retained, View, Work, render_view_single}; + +/// Device pixels a document unit: 1,933% at a pixel ratio of 2. +pub(crate) const SCALE: f64 = 38.66; + +pub(crate) struct Card { + pub doc: Document, + pub page: NodeId, + pub card: NodeId, + /// The shape in the card's picture. + pub shape: NodeId, +} + +/// The card: screen (clipping) > content > list > card (rounded, white, a drop shadow; like +/// the two stacks around it, not clipping) > picture (rounded, clipping) > shape. +pub(crate) fn card(shadow: bool) -> Card { + let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())]; + let mut d = Document::new("zoomed card"); + let page = d.first_page().unwrap(); + let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap(); + fill(&mut d, screen, "F4F6F5"); + let content = d.create(screen, NodeKind::Frame, "Content", 0.0, 81.0, 390.0, 763.0).unwrap(); + let list = d.create(content, NodeKind::Frame, "List", 24.0, 180.0, 342.0, 312.0).unwrap(); + let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap(); + fill(&mut d, card, "FFFFFF"); + let n = d.get_mut(card).unwrap(); + n.corners.radii = [20.0; 4]; + if shadow { + n.effects.push(Effect { + kind: EffectKind::DropShadow(Shadow { offset: (0.0, 4.0), radius: 16.0, color: Color { a: 0.08, ..Color::BLACK }, ..Shadow::default() }), + visible: true, + }); + } + for stack in [content, list, card] { + d.get_mut(stack).unwrap().clip = false; + } + let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap(); + fill(&mut d, picture, "CFE3DA"); + d.get_mut(picture).unwrap().corners.radii = [14.0; 4]; + let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap(); + fill(&mut d, shape, "7FAE9C"); + Card { doc: d, page, card, shape } +} + +/// The view the canvas has after zooming to the shape: the shape in the middle. +pub(crate) fn close_up(c: &Card, width: u32, height: u32) -> View { + let b = crate::draw::paint_bounds(&c.doc, c.shape).unwrap(); + let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + View { origin: (cx - f64::from(width) / SCALE / 2.0, cy - f64::from(height) / SCALE / 2.0), scale: SCALE, width, height } +} + +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +/// A full render drawn in the browser's bands: (all of it, the slowest band), in milliseconds. +fn banded(c: &Card, v: &View) -> (f64, f64) { + let doc = Arc::new(c.doc.clone()); + let mut r = Retained::default(); + let band_h = (v.height + 1).div_ceil(8).max(64); + let t = Instant::now(); + let mut slowest = 0.0f64; + match r.begin(&doc, c.page, v, &Options::default(), band_h).unwrap() { + Begun::Done(..) => {} + Begun::Steps(mut steps) => loop { + let b = Instant::now(); + let done = steps.step(); + slowest = slowest.max(ms(b)); + if done { + break; + } + }, + } + (ms(t), slowest) +} + +/// Mean milliseconds of a canvas frame after an edit of the shape, and what the last one took. +fn edits(c: &Card, v: &View) -> (f64, Work) { + const RUNS: u32 = 6; + let mut r = Retained::default(); + let mut doc = Arc::new(c.doc.clone()); + let _ = r.render(&doc, c.page, v, &Options::default()); + let mut work = Work::Reused; + let t = Instant::now(); + for i in 1..=RUNS { + let mut next = (*doc).clone(); + next.get_mut(c.shape).unwrap().height = 49.0 - f64::from(i); + doc = Arc::new(next); + work = r.render(&doc, c.page, v, &Options::default()).unwrap().2; + } + (ms(t) / f64::from(RUNS), work) +} + +#[test] +#[ignore = "timing: run in release with --ignored --nocapture"] +fn zoomed_card_timings() { + println!("zoomed card timings ({} build, 4112 × 2292 px, ms)", if cfg!(debug_assertions) { "debug" } else { "release" }); + println!("| render | shadow | no shadow |\n|---|---:|---:|"); + let (with, without) = (card(true), card(false)); + let v = close_up(&with, 4112, 2292); + let piece = |c: &Card| { + let t = Instant::now(); + assert!(render_view_single(&c.doc, c.page, &v, &Options::default()).is_some()); + ms(t) + }; + println!("| the view in one piece | {:.0} | {:.0} |", piece(&with), piece(&without)); + let (a, b) = (banded(&with, &v), banded(&without, &v)); + println!("| the view in 8 bands | {:.0} | {:.0} |", a.0, b.0); + println!("| the slowest band | {:.0} | {:.0} |", a.1, b.1); + let (a, b) = (edits(&with, &v), edits(&without, &v)); + println!("| a frame after an edit of the shape | {:.0} ({:?}) | {:.0} ({:?}) |", a.0, a.1, b.0, b.1); +} diff --git a/docs/gaps.md b/docs/gaps.md index fb6e45153..f976603f3 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; gap 7: the browser build compiles the rasteriser for speed; gap 7: a moved point redraws its vector around it only; gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; gap 7: drop shadows of opaque shapes are cast from their outline, where they show, at the resolution their blur needs; gap 7: a clipping frame that takes in the whole pixmap costs no layer, mask or copy; gap 7: a patch goes into the kept canvas image row by row; gap 7: the browser build compiles the rasteriser for speed; gap 7: a moved point redraws its vector around it only; gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -304,6 +304,30 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe filled twelve-tooth zigzag that fills the view (`a_moved_point_redraws_the_vector_around_it_only`). Dashes, width profiles, brushes, gradients and images, effects, masks and open filled paths depend on the whole outline: those vectors are drawn again whole. +- **Landed (2026-11-24):** a patch goes into the kept image row by row. A re-rendered area was + cut out of its render into a pixmap of its own and that drawn onto the kept image: two more + passes over it, which for simple content took far longer than rendering it. A 4.7 megapixel + patch of two flat fills (a 4112 × 2292 view, release, one thread): 16.9 → 2.8 ms a frame. +- **Landed (2026-11-24):** a clipping frame that takes in the whole pixmap costs no layer, mask + or copy there. Close up, the view (or the band or patch of it being drawn) lies inside its + clipping frames; each still copied the pixmap, filled a mask for it and put the copy back + through the mask pixel by pixel, because a frame with an edge off screen on a fraction of a + pixel never took the whole-pixel path. A clip that takes in the whole pixmap now draws its + children as they are, edges at or past the pixmap's count as whole, and rows of a mask that are + all in or all out are copied or kept in one piece. A view inside four nested clipping frames + at 1,933% on a 2× display (4112 × 2292 device pixels, release, one thread): 119 → 87 ms, a band + of it 18 → 12 ms. +- **Landed (2026-11-24):** a drop shadow of a shape or frame with opaque paints is cast from its + outline: drawn only where it shows on the pixmap, and a blur of 8 device pixels or more is drawn + smaller, blurred and scaled back up, on a grid that follows the shape (bands, patches and whole + views draw the same shadow). A frame that doesn't clip counts while its children stay inside its + box. The shadow was blurred at full resolution from a copy of the layer that reached past the + pixmap by the shadow's reach (1,392 pixels each way for a 16 px blur at 1,933% on a 2× display), + once for every band of a full render: 17.4 s for one render of the mobile app template's trail + card in the browser (0.18.1, 4112 × 2292 device pixels). `zoomed_card_timings` (release, one + thread, that view): 8 bands 4,576 → 152 ms, the slowest band 598 → 21 ms. Layers that aren't + their outline (see-through fills, groups, children past the box, layer blurs) cast from their + pixels as before, and are as slow close up; an edit inside the card still redraws all of it. - **Landed (2026-10-29):** the browser draws a zoom's full render a band at a time (`Retained::begin`, `Steps`; at least a band a frame and at most eight bands, so a frame draws a part of the render where it drew the whole of it: 0.7–1.4 s where the render took 3.7–4.0 s in the measurement of @@ -640,6 +664,9 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | 2026-11-24 | minor | Gap 7: after an edit the browser converts and uploads only the redrawn areas of the canvas image to its texture, not all of it. Numbers unchanged | | 2026-11-24 | minor | Gap 7: a point moved in the vector editor redraws the segments that moved and their neighbours, not the vector's whole box (a full render of the view when the vector fills it). Numbers unchanged | | 2026-11-24 | minor | Gap 7: the browser build compiles tiny-skia, tiny-skia-path and figcraft-render at opt-level 3 (the rest stays at "z" for the size gate): a full render of a close-up view took 117 ms where it took 296 ms in a 0.18.1 build; the bundle grows by about 0.2 MB. Numbers unchanged | +| 2026-11-24 | minor | Gap 7: a re-rendered area is copied into the kept canvas image row by row, not cut out and drawn (16.9 → 2.8 ms a frame for a 4.7 megapixel patch of flat fills, one thread). Numbers unchanged | +| 2026-11-24 | minor | Gap 7: a clipping frame that takes in the whole pixmap draws its children without a layer, a mask or a copy back; frame edges past the pixmap count as on whole pixels (119 → 87 ms for a view inside four nested clipping frames close up, one thread). Numbers unchanged | +| 2026-11-24 | minor | Gap 7: a drop shadow of a shape or frame with opaque paints is cast from its outline, drawn where it shows and blurred at the resolution its radius needs (`zoomed_card_timings`: 4,576 → 152 ms for a card close up, 8 bands, one thread). Numbers unchanged | | 2026-11-19 | minor | Gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`; a block is as tall as its lines and keeps its text plain code, #2237); the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. | | 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index b8096f3ff..674ee0350 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -51,6 +51,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| | 2026-11-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. | +| 2026-11-24 | minor | M8: drop shadows of opaque shapes and frames are cast from their outline, drawn where they show and blurred at the resolution their radius needs: a card with a 16 px shadow at 1,933% on a 2× display renders in 152 ms (8 bands, one thread) where it took 4,576 ms. Tests: `outline_shadow_tests`; timings: `zoomed_card_timings`. Numbers unchanged | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | patch | M10, #1343 (also #1422, #2233): Windows: the window no longer draws below a hidden caption. FigCraft draws its own title bar on Windows and opens undecorated windows, but winit 0.30 still gives them `WS_CAPTION` and `WS_BORDER`; on some systems the desktop compositor reserves that caption, so the content was drawn about 30 px low (a black band above it) while clicks kept the client coordinates and landed above what was drawn. A per-frame step (`apps/figcraft/src/window_frame.rs`, safe `winsafe` calls, Windows only) clears `WS_CAPTION` and `WS_BORDER` from every FigCraft window, the main one and the others, keeping the sizing border and window buttons so edge resizing and snap work, and writes only when a style changed (winit puts them back on maximize and restore). The same fix as DesignCraft #2139 and PhotoCraft #2401; the maximize-to-work-area trim from DesignCraft is left for a later change. Not run on a Windows machine that shows the offset: the style math and the per-frame hook are tested, the window itself needs a live check. Tests: `window_frame_tests`. Numbers unchanged |