Skip to main content

devpage_design/
shadow.rs

1//! Shadows: a box's shape blurred by a true Gaussian, as display-list
2//! commands both backends replay.
3//!
4//! Neither vello's blurred rounded rectangle — one radius for all four corners
5//! — nor any filter both backends share draws that, so the engine computes the
6//! blur itself, sampling the shape every half standard deviation, which is fine
7//! enough that the samples, drawn smoothly, are the blur at any zoom.
8//!
9//! A small shadow is one image of those samples. A large one would need too
10//! many — a 16,000-pixel box blurred by 2 has a billion — but away from its
11//! corners a blurred rounded rectangle doesn't vary along its edges, so it is
12//! drawn as pieces instead: solid where the blur can't reach, each edge's
13//! one-dimensional profile stretched along it, and each corner on its own —
14//! sampled in two dimensions, or for a corner far rounder than the blur, the
15//! exact blur of a disc's edge as a radial gradient. The pieces meet edge to
16//! edge, each added to what is under it, so no seam shows where two meet at any
17//! zoom; together, in one layer at the shadow color's opacity, they are the
18//! shadow. An ellipse that isn't a circle has no straight edges, so its shadow
19//! is tiled: solid tiles inside, sampled tiles along its edge, nothing outside.
20
21use std::collections::BTreeMap;
22use std::sync::Arc;
23
24use kurbo::{Affine, BezPath, Ellipse as KEllipse, Point, Rect, RoundedRect, Shape};
25use peniko::{Blob, Color as PColor, Gradient, ImageAlphaType, ImageData, ImageFormat};
26
27use crate::display::{Blend, Builder};
28use crate::display::{Draw, Paint};
29use crate::scene::Rgba;
30
31/// How far a blur reaches, in samples: three standard deviations at two
32/// samples a standard deviation. Past it the Gaussian is under 0.15%, less
33/// than half of one step of 255.
34const REACH: usize = 6;
35/// The most samples a shadow drawn as one image may have, and its longest side.
36pub const SINGLE: usize = 1 << 16;
37/// The longest side, in samples, of a shadow drawn as one image.
38const SINGLE_SIDE: usize = 1024;
39/// A corner at least this many standard deviations round is drawn as a disc's
40/// blurred edge, within 0.1 of 255 of the exact blur; a tighter one is sampled.
41const ROUND: f64 = 16.0;
42/// The side, in samples, of a tile of an ellipse's shadow.
43const TILE: usize = 128;
44/// How far the layer a piece is added from reaches past the piece, in scene
45/// pixels: so far that no pixel the layer's own edge crosses holds any of the
46/// piece, at any zoom out to 1/128.
47const MARGIN: f64 = 128.0;
48
49/// The shape a shadow blurs: a rounded rectangle — each corner's radius as
50/// kurbo clamps it — or an ellipse.
51#[derive(Clone, Copy)]
52pub enum Outline {
53    /// A rounded rectangle and its radii, `[top-left, top-right, bottom-right,
54    /// bottom-left]`, each as kurbo clamps it.
55    Rounded(Rect, [f64; 4]),
56    /// The ellipse that fills a rectangle; never a circle, which is
57    /// [`Rounded`](Self::Rounded).
58    Ellipse(Rect),
59}
60
61impl Outline {
62    /// A rounded rectangle with radii `[top-left, top-right, bottom-right,
63    /// bottom-left]`, or a circle as one with every radius half its side.
64    pub fn rounded(rect: Rect, radii: [f64; 4]) -> Outline {
65        let r = RoundedRect::from_rect(rect, (radii[0], radii[1], radii[2], radii[3])).radii();
66        Outline::Rounded(
67            rect,
68            [r.top_left, r.top_right, r.bottom_right, r.bottom_left],
69        )
70    }
71
72    /// The ellipse that fills `rect`: a rounded rectangle when `rect` is a
73    /// square.
74    pub fn ellipse(rect: Rect) -> Outline {
75        if rect.width() == rect.height() {
76            Outline::rounded(rect, [rect.width() / 2.0; 4])
77        } else {
78            Outline::Ellipse(rect)
79        }
80    }
81
82    /// The outline as a path, within 0.1 of it.
83    pub fn path(&self) -> BezPath {
84        match *self {
85            Outline::Rounded(r, [tl, tr, br, bl]) => {
86                RoundedRect::from_rect(r, (tl, tr, br, bl)).to_path(0.1)
87            }
88            Outline::Ellipse(r) => KEllipse::from_rect(r).to_path(0.1),
89        }
90    }
91
92    /// The outline as straight lines within `tolerance` of it. The
93    /// rasterizer would flatten a curve itself, within a quarter of a sample
94    /// — inside it, as a chord is — which moves a blurred curve's edge by as
95    /// much as 2% of its alpha.
96    fn lines(&self, tolerance: f64) -> BezPath {
97        let mut out = BezPath::new();
98        let shape = match *self {
99            Outline::Rounded(r, [tl, tr, br, bl]) => {
100                RoundedRect::from_rect(r, (tl, tr, br, bl)).to_path(tolerance / 10.0)
101            }
102            Outline::Ellipse(r) => KEllipse::from_rect(r).to_path(tolerance / 10.0),
103        };
104        kurbo::flatten(shape, tolerance, |el| out.push(el));
105        out
106    }
107
108    /// The rectangle the outline fills.
109    fn rect(&self) -> Rect {
110        match *self {
111            Outline::Rounded(r, _) | Outline::Ellipse(r) => r,
112        }
113    }
114
115    /// The signed distance from `p` to the edge, negative inside.
116    fn distance(&self, p: Point) -> f64 {
117        let r = self.rect();
118        let c = r.center();
119        let (hx, hy) = (r.width() / 2.0, r.height() / 2.0);
120        let (dx, dy) = (p.x - c.x, p.y - c.y);
121        match *self {
122            Outline::Rounded(_, [tl, tr, br, bl]) => {
123                let radius = match (dx >= 0.0, dy >= 0.0) {
124                    (false, false) => tl,
125                    (true, false) => tr,
126                    (true, true) => br,
127                    (false, true) => bl,
128                };
129                let (qx, qy) = (dx.abs() - hx + radius, dy.abs() - hy + radius);
130                qx.max(qy).min(0.0) + qx.max(0.0).hypot(qy.max(0.0)) - radius
131            }
132            Outline::Ellipse(_) => ellipse_distance(hx, hy, dx, dy),
133        }
134    }
135
136    /// Whether all of `r` is inside — for a convex shape, its four corners.
137    fn holds(&self, r: Rect) -> bool {
138        [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]
139            .iter()
140            .all(|&(x, y)| self.distance(Point::new(x, y)) <= 0.0)
141    }
142
143    /// Whether `r` certainly lies outside.
144    fn misses(&self, r: Rect) -> bool {
145        if let Outline::Ellipse(e) = *self {
146            // Scaled to a unit circle the rectangle is still one, and its
147            // point nearest the center is the center clamped into it.
148            let c = e.center();
149            let (a, b) = (e.width() / 2.0, e.height() / 2.0);
150            let nx = (c.x.clamp(r.x0, r.x1) - c.x) / a;
151            let ny = (c.y.clamp(r.y0, r.y1) - c.y) / b;
152            return nx.hypot(ny) > 1.0;
153        }
154        self.distance(r.center()) > r.width().hypot(r.height()) / 2.0
155    }
156}
157
158/// The normalized Gaussian over `-REACH..=REACH` samples, two samples a
159/// standard deviation.
160fn kernel() -> [f32; 2 * REACH + 1] {
161    let mut k = [0f32; 2 * REACH + 1];
162    for (i, w) in k.iter_mut().enumerate() {
163        let x = i as f64 - REACH as f64;
164        *w = (-x * x / 8.0).exp() as f32;
165    }
166    let total: f32 = k.iter().sum();
167    k.map(|w| w / total)
168}
169
170/// The grid a shadow is sampled on: sample `(i, j)` covers the square of side
171/// `step` whose top-left is `origin + (i, j) × step`.
172#[derive(Clone, Copy)]
173struct Grid {
174    /// The top-left of sample `(0, 0)`, in the design's coordinates.
175    origin: Point,
176    /// The side of a sample, in the design's coordinates: half the blur's
177    /// standard deviation.
178    step: f64,
179}
180
181impl Grid {
182    /// The left edge of the samples in column `i`.
183    fn x(&self, i: isize) -> f64 {
184        self.origin.x + i as f64 * self.step
185    }
186    /// The top edge of the samples in row `j`.
187    fn y(&self, j: isize) -> f64 {
188        self.origin.y + j as f64 * self.step
189    }
190    /// The rectangle the samples from `(i0, j0)` up to, not through, `(i1, j1)`
191    /// cover.
192    fn rect(&self, i0: isize, j0: isize, i1: isize, j1: isize) -> Rect {
193        Rect::new(self.x(i0), self.y(j0), self.x(i1), self.y(j1))
194    }
195    /// The transform from an image whose pixel `(0, 0)` is sample `(i, j)`.
196    fn place(&self, i: isize, j: isize) -> Affine {
197        Affine::translate((self.x(i), self.y(j))) * Affine::scale(self.step)
198    }
199}
200
201/// How much of each of the `w` × `h` unit squares the closed polygon `path`
202/// — straight lines only — covers under `to`, row by row, as an 8-bit
203/// rasterizer gives it: the exact area, to the nearest 255th. Signed area is
204/// accumulated cell by cell along each edge and summed along each row, so a
205/// sample costs the same however the shape crosses it. What lies outside the
206/// squares counts as a rasterizer clips it: left of them, wholly in the first
207/// column; right of them, not at all.
208fn coverage(path: &BezPath, to: Affine, w: usize, h: usize) -> Vec<f32> {
209    // Each row has two cells past its end, which take what lies right of it.
210    let stride = w + 2;
211    let mut acc = vec![0f64; stride * h + 2];
212    let mut cell = |p0: Point, p1: Point| {
213        if (p0.y - p1.y).abs() <= 1e-12 {
214            return;
215        }
216        let (dir, p0, p1) = if p0.y < p1.y {
217            (1.0, p0, p1)
218        } else {
219            (-1.0, p1, p0)
220        };
221        let dxdy = (p1.x - p0.x) / (p1.y - p0.y);
222        let mut x = p0.x;
223        if p0.y < 0.0 {
224            x -= p0.y * dxdy;
225        }
226        let first = p0.y.max(0.0) as usize;
227        for y in first..h.min(p1.y.ceil() as usize) {
228            let start = (y * stride) as isize;
229            let dy = ((y + 1) as f64).min(p1.y) - (y as f64).max(p0.y);
230            let xnext = x + dxdy * dy;
231            let d = dy * dir;
232            let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) };
233            let x0floor = x0.floor();
234            let x0i = x0floor as isize;
235            let x1ceil = x1.ceil();
236            let x1i = x1ceil as isize;
237            let at = start + x0i;
238            if at < 0 {
239                x = xnext;
240                continue;
241            }
242            let at = at as usize;
243            if x1i <= x0i + 1 {
244                let xmf = 0.5 * (x + xnext) - x0floor;
245                acc[at] += d - d * xmf;
246                acc[at + 1] += d * xmf;
247            } else {
248                let s = (x1 - x0).recip();
249                let x0f = x0 - x0floor;
250                let a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f);
251                let x1f = x1 - x1ceil + 1.0;
252                let am = 0.5 * s * x1f * x1f;
253                acc[at] += d * a0;
254                if x1i == x0i + 2 {
255                    acc[at + 1] += d * (1.0 - a0 - am);
256                } else {
257                    let a1 = s * (1.5 - x0f);
258                    acc[at + 1] += d * (a1 - a0);
259                    for xi in x0i + 2..x1i - 1 {
260                        acc[(start + xi) as usize] += d * s;
261                    }
262                    let a2 = a1 + (x1i - x0i - 3) as f64 * s;
263                    acc[(start + x1i - 1) as usize] += d * (1.0 - a2 - am);
264                }
265                acc[(start + x1i) as usize] += d * am;
266            }
267            x = xnext;
268        }
269    };
270    // An edge split where it crosses either side, each part moved inside.
271    let mut line = |p0: Point, p1: Point| {
272        let mut cuts = vec![0.0, 1.0];
273        for edge in [0.0, w as f64] {
274            if (p0.x - edge) * (p1.x - edge) < 0.0 {
275                cuts.push((edge - p0.x) / (p1.x - p0.x));
276            }
277        }
278        cuts.sort_by(f64::total_cmp);
279        let at = |t: f64| {
280            let p = p0.lerp(p1, t);
281            Point::new(p.x.clamp(0.0, w as f64), p.y)
282        };
283        for pair in cuts.windows(2) {
284            cell(at(pair[0]), at(pair[1]));
285        }
286    };
287    let (mut first, mut last) = (None, None);
288    for el in path.elements() {
289        match *el {
290            kurbo::PathEl::MoveTo(p) => {
291                if let (Some(a), Some(b)) = (last, first) {
292                    line(a, b);
293                }
294                let p = to * p;
295                first = Some(p);
296                last = Some(p);
297            }
298            kurbo::PathEl::LineTo(p) => {
299                let p = to * p;
300                if let Some(a) = last {
301                    line(a, p);
302                }
303                last = Some(p);
304            }
305            kurbo::PathEl::ClosePath => {
306                if let (Some(a), Some(b)) = (last, first) {
307                    line(a, b);
308                }
309                last = first;
310            }
311            _ => unreachable!("an outline flattened to lines"),
312        }
313    }
314    if let (Some(a), Some(b)) = (last, first) {
315        line(a, b);
316    }
317    let mut out = Vec::with_capacity(w * h);
318    for row in acc.chunks(stride).take(h) {
319        let mut sum = 0.0;
320        out.extend(row[..w].iter().map(|a| {
321            sum += a;
322            ((sum.abs().min(1.0) * 255.0).round() / 255.0) as f32
323        }));
324    }
325    out
326}
327
328/// The blurred shape at samples `i0..i0 + w` × `j0..j0 + h`, row by row: its
329/// coverage of each sample out to the blur's reach, blurred down each column
330/// and then across each row.
331fn blurred(path: &BezPath, grid: Grid, i0: isize, j0: isize, w: usize, h: usize) -> Vec<f32> {
332    let (cw, ch) = (w + 2 * REACH, h + 2 * REACH);
333    let to = Affine::scale(1.0 / grid.step)
334        * Affine::translate((-grid.x(i0 - REACH as isize), -grid.y(j0 - REACH as isize)));
335    let cov = coverage(path, to, cw, ch);
336    let k = kernel();
337    let mut down = vec![0f32; h * cw];
338    for y in 0..h {
339        let row = &mut down[y * cw..][..cw];
340        for (t, weight) in k.iter().enumerate() {
341            let from = &cov[(y + t) * cw..][..cw];
342            for (o, c) in row.iter_mut().zip(from) {
343                *o += weight * c;
344            }
345        }
346    }
347    let mut out = vec![0f32; w * h];
348    for y in 0..h {
349        let from = &down[y * cw..][..cw];
350        for (x, o) in out[y * w..][..w].iter_mut().enumerate() {
351            *o = k.iter().zip(&from[x..]).map(|(a, b)| a * b).sum();
352        }
353    }
354    out
355}
356
357/// The blur of the interval `lo..hi` at samples `from..from + len` of a line
358/// whose sample `0` starts at `origin`: a straight edge's profile.
359fn profile(lo: f64, hi: f64, origin: f64, step: f64, from: isize, len: usize) -> Vec<f32> {
360    let cov: Vec<f32> = (0..len + 2 * REACH)
361        .map(|n| {
362            let a = origin + (from + n as isize - REACH as isize) as f64 * step;
363            ((hi.min(a + step) - lo.max(a)) / step).clamp(0.0, 1.0) as f32
364        })
365        .collect();
366    let k = kernel();
367    (0..len)
368        .map(|i| k.iter().zip(&cov[i..]).map(|(a, b)| a * b).sum())
369        .collect()
370}
371
372/// `values`, `w` × `h`, as an image of `c` whose alpha is each value times
373/// `alpha`.
374fn image(values: &[f32], w: usize, h: usize, c: Rgba, alpha: f32) -> ImageData {
375    let pixels: Vec<u8> = values
376        .iter()
377        .flat_map(|v| [c.r, c.g, c.b, (v.clamp(0.0, 1.0) * alpha).round() as u8])
378        .collect();
379    ImageData {
380        data: Blob::new(Arc::new(pixels)),
381        format: ImageFormat::Rgba8,
382        alpha_type: ImageAlphaType::Alpha,
383        width: w as u32,
384        height: h as u32,
385    }
386}
387
388/// The normal distribution's cumulative function, to 1.5 × 10⁻⁷
389/// (Abramowitz and Stegun, 7.1.26).
390fn phi_cdf(x: f64) -> f64 {
391    let z = x.abs() / std::f64::consts::SQRT_2;
392    let t = 1.0 / (1.0 + 0.3275911 * z);
393    let poly = t
394        * (0.254829592
395            + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))));
396    let erf = 1.0 - poly * (-z * z).exp();
397    0.5 * (1.0 + if x < 0.0 { -erf } else { erf })
398}
399
400/// One piece of a large shadow: the area it covers and how it is painted.
401enum Piece {
402    /// Every sample inside the blur's reach of the shape: solid.
403    Solid(BezPath),
404    /// Where the blur varies only down: the profile of rows `j0..j1`.
405    Down(BezPath, isize, isize),
406    /// Where it varies only across: the profile of columns `i0..i1`.
407    Across(BezPath, isize, isize),
408    /// A round corner: the blurred edge of the disc centered at the point,
409    /// of the radius.
410    Disc(BezPath, Point, f64),
411    /// Samples `i0..i1` × `j0..j1`, blurred in two dimensions, cut to the
412    /// path, or else to those samples.
413    Patch(Option<BezPath>, isize, isize, isize, isize),
414}
415
416/// Adds `outline`'s shadow — blurred by a Gaussian of `std_dev` pixels and
417/// colored `c` — to `list`, and each image it paints, in order, to `images`.
418pub fn shadow(
419    outline: Outline,
420    std_dev: f64,
421    c: Rgba,
422    list: &mut Builder,
423    images: &mut Vec<ImageData>,
424) {
425    shadow_with(outline, std_dev, c, list, images, SINGLE)
426}
427
428/// [`shadow`], drawing one image when it takes no more than `single` samples.
429pub fn shadow_with(
430    outline: Outline,
431    std_dev: f64,
432    c: Rgba,
433    list: &mut Builder,
434    images: &mut Vec<ImageData>,
435    single: usize,
436) {
437    let rect = outline.rect();
438    if rect.width() <= 0.0 || rect.height() <= 0.0 {
439        return;
440    }
441    let color = PColor::from_rgba8(c.r, c.g, c.b, c.a);
442    if std_dev <= 0.0 {
443        list.draw(Draw::Fill(outline.path(), Paint::Solid(color)));
444        return;
445    }
446    let step = std_dev / 2.0;
447    let reach = REACH as f64 * step;
448    let grid = Grid {
449        origin: Point::new(rect.x0 - reach, rect.y0 - reach),
450        step,
451    };
452    let nx = ((rect.width() + 2.0 * reach) / step).ceil() as usize;
453    let ny = ((rect.height() + 2.0 * reach) / step).ceil() as usize;
454    // A hundredth of a sample.
455    let path = outline.lines(step / 100.0);
456    if nx * ny <= single && nx <= SINGLE_SIDE && ny <= SINGLE_SIDE {
457        let values = blurred(&path, grid, 0, 0, nx, ny);
458        let data = image(&values, nx, ny, c, c.a as f32);
459        images.push(data.clone());
460        list.draw(Draw::Fill(
461            grid.rect(0, 0, nx as isize, ny as isize).to_path(0.1),
462            Paint::Image(data, grid.place(0, 0)),
463        ));
464        return;
465    }
466    let (nx, ny) = (nx as isize, ny as isize);
467    let pieces = match outline {
468        Outline::Rounded(r, radii) => rounded(r, radii, std_dev, grid, nx, ny),
469        Outline::Ellipse(e) => ellipse(e, std_dev, grid, nx, ny),
470    };
471    let extent = grid.rect(0, 0, nx, ny);
472    list.push_layer(
473        Blend::Opacity(c.a as f32 / 255.0),
474        Some(extent.to_path(0.1)),
475    );
476    let opaque = Rgba { a: 255, ..c };
477    let paint_over = |clip: &BezPath| clip.bounding_box().inflate(MARGIN, MARGIN).to_path(0.1);
478    for piece in pieces {
479        let (clip, paint) = match piece {
480            Piece::Solid(clip) => (clip, Paint::Solid(color.with_alpha(1.0))),
481            Piece::Down(clip, j0, j1) => {
482                let len = (j1 - j0 + 2) as usize;
483                let values = profile(rect.y0, rect.y1, grid.origin.y, step, j0 - 1, len);
484                let data = image(&values, 1, len, opaque, 255.0);
485                images.push(data.clone());
486                let place = Affine::translate((0.0, grid.y(j0 - 1))) * Affine::scale(step);
487                (clip, Paint::Image(data, place))
488            }
489            Piece::Across(clip, i0, i1) => {
490                let len = (i1 - i0 + 2) as usize;
491                let values = profile(rect.x0, rect.x1, grid.origin.x, step, i0 - 1, len);
492                let data = image(&values, len, 1, opaque, 255.0);
493                images.push(data.clone());
494                let place = Affine::translate((grid.x(i0 - 1), 0.0)) * Affine::scale(step);
495                (clip, Paint::Image(data, place))
496            }
497            Piece::Disc(clip, center, radius) => {
498                (clip, Paint::Gradient(disc(center, radius, std_dev, c)))
499            }
500            Piece::Patch(clip, i0, j0, i1, j1) => {
501                let (w, h) = ((i1 - i0 + 2) as usize, (j1 - j0 + 2) as usize);
502                let values = blurred(&path, grid, i0 - 1, j0 - 1, w, h);
503                let data = image(&values, w, h, opaque, 255.0);
504                images.push(data.clone());
505                (
506                    clip.unwrap_or_else(|| grid.rect(i0, j0, i1, j1).to_path(0.1)),
507                    Paint::Image(data, grid.place(i0 - 1, j0 - 1)),
508                )
509            }
510        };
511        // The piece's own edge cuts it, anti-aliased, so where two meet each
512        // adds its share of the pixel; the layer reaches well past it.
513        list.push_layer(Blend::Add, Some(paint_over(&clip)));
514        list.draw(Draw::Fill(clip, paint));
515        list.pop();
516    }
517    list.pop();
518}
519
520/// The blurred edge of a disc of `radius` around `center`, as a radial
521/// gradient from where it is solid to where it is gone. A Gaussian of σ
522/// across the edge of a disc of radius R is, to within 0.1 of 255 once R is
523/// [`ROUND`] σ, the straight edge's minus φ(d)·σ/2R — the disc's curve taking
524/// a little from it.
525fn disc(center: Point, radius: f64, std_dev: f64, c: Rgba) -> Gradient {
526    let reach = REACH as f64 * std_dev / 2.0;
527    let (r0, r1) = (radius - reach, radius + reach);
528    const STOPS: usize = 49;
529    let stops: Vec<(f32, PColor)> = (0..STOPS)
530        .map(|k| {
531            let t = k as f64 / (STOPS - 1) as f64;
532            let d = (r0 + t * (r1 - r0) - radius) / std_dev;
533            let density = (-d * d / 2.0).exp() / (2.0 * std::f64::consts::PI).sqrt();
534            let v = (phi_cdf(-d) - density * std_dev / (2.0 * radius)).clamp(0.0, 1.0);
535            (
536                t as f32,
537                PColor::new([
538                    c.r as f32 / 255.0,
539                    c.g as f32 / 255.0,
540                    c.b as f32 / 255.0,
541                    v as f32,
542                ]),
543            )
544        })
545        .collect();
546    Gradient::new_two_point_radial(center, r0 as f32, center, r1 as f32)
547        .with_stops(stops.as_slice())
548}
549
550/// The pieces of a rounded rectangle's shadow over samples `0..nx` ×
551/// `0..ny`. Away from a corner's reach the blur depends on one coordinate
552/// only: down where the column lies a blur's reach inside both sides, across
553/// where the row does, and is solid where both do.
554fn rounded(
555    rect: Rect,
556    radii: [f64; 4],
557    std_dev: f64,
558    grid: Grid,
559    nx: isize,
560    ny: isize,
561) -> Vec<Piece> {
562    let reach = REACH as f64 * grid.step;
563    let (sx, sy) = (
564        |x: f64| (x - grid.origin.x) / grid.step,
565        |y: f64| (y - grid.origin.y) / grid.step,
566    );
567    let clamp_x = |v: f64| (v as isize).clamp(0, nx);
568    let clamp_y = |v: f64| (v as isize).clamp(0, ny);
569    // Where the blur no longer reaches either side.
570    let (xl, xr) = (2 * REACH as isize, clamp_x(sx(rect.x1 - reach).floor()));
571    let (yt, yb) = (2 * REACH as isize, clamp_y(sy(rect.y1 - reach).floor()));
572    let [tl, tr, br, bl] = radii;
573    let (w, h) = (rect.width(), rect.height());
574    // The straight run between each pair of corners.
575    let (top, right, bottom, left) = (w - tl - tr, h - tr - br, w - br - bl, h - tl - bl);
576    // A corner is a disc's edge when it is round enough and each side
577    // leaving it runs straight for the blur's reach — or into a corner of
578    // the same circle.
579    let disc_ok = |r: f64, a: (f64, f64), b: (f64, f64)| {
580        let run = |(len, other): (f64, f64)| len >= reach || (len <= 1e-9 && other == r);
581        r >= ROUND * std_dev && run(a) && run(b)
582    };
583    struct Corner {
584        zone: [isize; 4],
585        disc: Option<Point>,
586        radius: f64,
587    }
588    let mut corners = Vec::new();
589    for (r, at_right, at_bottom, a, b) in [
590        (tl, false, false, (top, tr), (left, bl)),
591        (tr, true, false, (top, tl), (right, br)),
592        (br, true, true, (bottom, bl), (right, tr)),
593        (bl, false, true, (bottom, br), (left, tl)),
594    ] {
595        let disc = disc_ok(r, a, b);
596        // A disc's quadrant reaches its center; a sampled corner, the blur's
597        // reach past the corner's square.
598        let inner = if disc { r } else { r + reach };
599        let (x0, x1) = if at_right {
600            let x = sx(rect.x1 - inner);
601            (clamp_x(if disc { x.round() } else { x.floor() }), nx)
602        } else {
603            let x = sx(rect.x0 + inner);
604            (0, clamp_x(if disc { x.round() } else { x.ceil() }))
605        };
606        let (y0, y1) = if at_bottom {
607            let y = sy(rect.y1 - inner);
608            (clamp_y(if disc { y.round() } else { y.floor() }), ny)
609        } else {
610            let y = sy(rect.y0 + inner);
611            (0, clamp_y(if disc { y.round() } else { y.ceil() }))
612        };
613        let center = Point::new(
614            if at_right { rect.x1 - r } else { rect.x0 + r },
615            if at_bottom { rect.y1 - r } else { rect.y0 + r },
616        );
617        corners.push(Corner {
618            zone: [x0, y0, x1, y1],
619            disc: disc.then_some(center),
620            radius: r,
621        });
622    }
623    let mut xs = vec![0, nx, xl.min(nx), xr];
624    let mut ys = vec![0, ny, yt.min(ny), yb];
625    for c in &corners {
626        xs.extend([c.zone[0], c.zone[2]]);
627        ys.extend([c.zone[1], c.zone[3]]);
628    }
629    xs.sort_unstable();
630    xs.dedup();
631    ys.sort_unstable();
632    ys.dedup();
633    let mut solid = BezPath::new();
634    let mut down: BTreeMap<(isize, isize), BezPath> = BTreeMap::new();
635    let mut across: BTreeMap<(isize, isize), BezPath> = BTreeMap::new();
636    let mut discs: BTreeMap<usize, BezPath> = BTreeMap::new();
637    let mut patches = Vec::new();
638    // A sampled corner whose zone meets no other's is one patch.
639    let meets =
640        |a: &[isize; 4], b: &[isize; 4]| a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3];
641    let whole: Vec<bool> = corners
642        .iter()
643        .enumerate()
644        .map(|(n, c)| {
645            c.disc.is_none()
646                && corners
647                    .iter()
648                    .enumerate()
649                    .all(|(m, o)| m == n || !meets(&c.zone, &o.zone))
650        })
651        .collect();
652    for (c, _) in corners.iter().zip(&whole).filter(|(_, w)| **w) {
653        let [i0, j0, i1, j1] = c.zone;
654        if i0 < i1 && j0 < j1 {
655            patches.push((i0, j0, i1, j1));
656        }
657    }
658    let add = |path: &mut BezPath, r: Rect| path.extend(r.path_elements(0.1));
659    for ys in ys.windows(2) {
660        let (j0, j1) = (ys[0], ys[1]);
661        for xs in xs.windows(2) {
662            let (i0, i1) = (xs[0], xs[1]);
663            let cell = grid.rect(i0, j0, i1, j1);
664            let within = |z: &[isize; 4]| z[0] <= i0 && i1 <= z[2] && z[1] <= j0 && j1 <= z[3];
665            if corners
666                .iter()
667                .zip(&whole)
668                .any(|(c, w)| *w && within(&c.zone))
669            {
670                // Already a patch of its own.
671            } else if corners.iter().any(|c| c.disc.is_none() && within(&c.zone)) {
672                patches.push((i0, j0, i1, j1));
673            } else if let Some(n) = corners
674                .iter()
675                .position(|c| c.disc.is_some() && within(&c.zone))
676            {
677                add(discs.entry(n).or_default(), cell);
678            } else {
679                let central_x = xl <= i0 && i1 <= xr;
680                let central_y = yt <= j0 && j1 <= yb;
681                match (central_x, central_y) {
682                    (true, true) => add(&mut solid, cell),
683                    (true, false) => add(down.entry((j0, j1)).or_default(), cell),
684                    (false, true) => add(across.entry((i0, i1)).or_default(), cell),
685                    // Never, as a corner's zone covers where neither holds;
686                    // if it did, sampling it is still exact.
687                    (false, false) => patches.push((i0, j0, i1, j1)),
688                }
689            }
690        }
691    }
692    let outline = Outline::Rounded(rect, radii);
693    let mut pieces = Vec::new();
694    if !solid.elements().is_empty() {
695        pieces.push(Piece::Solid(solid));
696    }
697    // Bands that meet are one piece, with one image: every join between two
698    // pieces inside a pixel costs a rounding in each, so a straight run has
699    // none.
700    pieces.extend(runs(down).map(|((j0, j1), p)| Piece::Down(p, j0, j1)));
701    pieces.extend(runs(across).map(|((i0, i1), p)| Piece::Across(p, i0, i1)));
702    pieces.extend(
703        discs
704            .into_iter()
705            .map(|(n, p)| Piece::Disc(p, corners[n].disc.expect("a disc"), corners[n].radius)),
706    );
707    for (i0, j0, i1, j1) in merged(patches) {
708        pieces.extend(tiles(&outline, grid, i0, j0, i1, j1));
709    }
710    pieces
711}
712
713/// Bands `(from, to)` of cells, merged where one ends as the next begins.
714fn runs(
715    bands: BTreeMap<(isize, isize), BezPath>,
716) -> impl Iterator<Item = ((isize, isize), BezPath)> {
717    let mut out: Vec<((isize, isize), BezPath)> = Vec::new();
718    for ((from, to), path) in bands {
719        match out.last_mut() {
720            Some(((_, end), run)) if *end == from => {
721                *end = to;
722                run.extend(path);
723            }
724            _ => out.push(((from, to), path)),
725        }
726    }
727    out.into_iter()
728}
729
730/// Cells `(i0, j0, i1, j1)` of a grid, none overlapping, merged into fewer
731/// rectangles: along each band first, then down where the runs line up.
732fn merged(mut cells: Vec<(isize, isize, isize, isize)>) -> Vec<(isize, isize, isize, isize)> {
733    cells.sort_unstable_by_key(|&(i0, j0, _, j1)| (j0, j1, i0));
734    let mut rows: Vec<(isize, isize, isize, isize)> = Vec::new();
735    for c in cells {
736        match rows.last_mut() {
737            Some(r) if (r.1, r.3, r.2) == (c.1, c.3, c.0) => r.2 = c.2,
738            _ => rows.push(c),
739        }
740    }
741    rows.sort_unstable_by_key(|&(i0, j0, i1, _)| (i0, i1, j0));
742    let mut out: Vec<(isize, isize, isize, isize)> = Vec::new();
743    for c in rows {
744        match out.last_mut() {
745            Some(r) if (r.0, r.2, r.3) == (c.0, c.2, c.1) => r.3 = c.3,
746            _ => out.push(c),
747        }
748    }
749    out
750}
751
752/// Samples `i0..i1` × `j0..j1` of `outline`'s shadow as tiles of at most
753/// [`TILE`] samples a side: none where the blur can't reach the shape, one
754/// solid piece where the shape fills all it reaches, and each other tile
755/// sampled.
756fn tiles(outline: &Outline, grid: Grid, i0: isize, j0: isize, i1: isize, j1: isize) -> Vec<Piece> {
757    let tile = TILE as isize;
758    if (i1 - i0) <= tile && (j1 - j0) <= tile {
759        return vec![Piece::Patch(None, i0, j0, i1, j1)];
760    }
761    // A tile's samples, its border and how far the blur reaches.
762    let reach = REACH as isize + 1;
763    let mut solid = BezPath::new();
764    let mut pieces = Vec::new();
765    let mut j = j0;
766    while j < j1 {
767        let je = (j + tile).min(j1);
768        let mut run: Option<isize> = None;
769        let mut i = i0;
770        while i < i1 {
771            let ie = (i + tile).min(i1);
772            let reached = grid.rect(i - reach, j - reach, ie + reach, je + reach);
773            let full = outline.holds(reached);
774            if full {
775                run.get_or_insert(i);
776            } else {
777                if let Some(start) = run.take() {
778                    solid.extend(grid.rect(start, j, i, je).path_elements(0.1));
779                }
780                if !outline.misses(reached) {
781                    pieces.push(Piece::Patch(None, i, j, ie, je));
782                }
783            }
784            i = ie;
785        }
786        if let Some(start) = run {
787            solid.extend(grid.rect(start, j, i1, je).path_elements(0.1));
788        }
789        j = je;
790    }
791    if !solid.elements().is_empty() {
792        pieces.insert(0, Piece::Solid(solid));
793    }
794    pieces
795}
796
797/// The signed distance from `(x, y)` to the ellipse of semi-axes `a` and `b`
798/// around the origin: from its nearest point, found by Newton's method on the
799/// angle where the offset to it is normal to the curve.
800fn ellipse_distance(a: f64, b: f64, x: f64, y: f64) -> f64 {
801    // By symmetry, in the first quadrant, where the nearest point is too.
802    let (px, py) = (x.abs(), y.abs());
803    let mut t = (a * py).atan2(b * px);
804    for _ in 0..40 {
805        let (sin, cos) = t.sin_cos();
806        let (ex, ey) = (a * cos, b * sin);
807        // f(t) = (p − e(t)) · e'(t), and its derivative.
808        let f = (px - ex) * -a * sin + (py - ey) * b * cos;
809        let df =
810            (a * a * sin * sin + b * b * cos * cos) - (px - ex) * a * cos - (py - ey) * b * sin;
811        if df.abs() < 1e-12 {
812            break;
813        }
814        let next = (t - f / df).clamp(0.0, std::f64::consts::FRAC_PI_2);
815        if (next - t).abs() < 1e-12 {
816            t = next;
817            break;
818        }
819        t = next;
820    }
821    let (sin, cos) = t.sin_cos();
822    let d = (px - a * cos).hypot(py - b * sin);
823    if (px / a).hypot(py / b) <= 1.0 { -d } else { d }
824}
825
826/// The pieces of an ellipse's shadow. Cut by rays from its center into
827/// wedges, each short enough that the ellipse stays within a hundredth of a
828/// standard deviation of its circle of curvature there, a wedge is that
829/// circle's blurred edge — or, where the ellipse curves too tightly for that,
830/// sampled; inside the wedges it is solid. An ellipse too thin to be solid
831/// anywhere is tiled instead.
832fn ellipse(e: Rect, std_dev: f64, grid: Grid, nx: isize, ny: isize) -> Vec<Piece> {
833    let outline = Outline::Ellipse(e);
834    let step = grid.step;
835    let (a, b) = (e.width() / 2.0, e.height() / 2.0);
836    let c = e.center();
837    // How far inside every sample a blur reaches is covered, and how far
838    // outside none is.
839    let inside = (REACH as f64 * step + step) * std::f64::consts::SQRT_2;
840    let outside = inside + step;
841    if a.min(b) <= 4.0 * inside {
842        return tiles(&outline, grid, 0, 0, nx, ny);
843    }
844    let at = |t: f64| Point::new(c.x + a * t.cos(), c.y + b * t.sin());
845    let normal = |t: f64| {
846        let n = kurbo::Vec2::new(b * t.cos(), a * t.sin());
847        n / n.hypot()
848    };
849    let rho = |t: f64| {
850        let (sin, cos) = t.sin_cos();
851        (a * a * sin * sin + b * b * cos * cos).powf(1.5) / (a * b)
852    };
853    let distance = |p: Point| ellipse_distance(a, b, p.x - c.x, p.y - c.y);
854    // Where the ray through the point at `t` crosses `depth` inside and
855    // `outside` outside, or `None` when no point on it lies that deep.
856    let cut = |t: f64| -> Option<(Point, Point)> {
857        let p = at(t);
858        let ray = p - c;
859        let u = ray / ray.hypot();
860        let cos = u.dot(normal(t)).max(1e-6);
861        let mut s = inside / cos;
862        while distance(p - u * s) > -inside {
863            s += step;
864            if s >= ray.hypot() {
865                return None;
866            }
867        }
868        Some((p - u * s, p + u * (outside / cos)))
869    };
870    let tolerance = std_dev / 100.0;
871    let tile = TILE as f64 * step;
872    // Whether the wedge from `t0` to `t1` is short enough.
873    let fine = |t0: f64, t1: f64| -> bool {
874        let tm = (t0 + t1) / 2.0;
875        let (p0, p1) = (at(t0), at(t1));
876        let chord = (p1 - p0).hypot();
877        let tightest = rho(t0).min(rho(t1)).min(rho(tm));
878        // The outer edge, a chord, may come no nearer than a sample.
879        if chord * chord / (8.0 * (tightest + outside)) > step {
880            return false;
881        }
882        if tightest >= ROUND * std_dev {
883            let center = at(tm) - normal(tm) * rho(tm);
884            let r = rho(tm);
885            [t0, (t0 + tm) / 2.0, (tm + t1) / 2.0, t1]
886                .iter()
887                .all(|&t| ((at(t) - center).hypot() - r).abs() <= tolerance)
888        } else {
889            chord <= tile
890        }
891    };
892    // Cut at every axis, so the curvature only grows or shrinks in a wedge,
893    // then halve each wedge until it is fine.
894    let mut ts = Vec::new();
895    let quarter = std::f64::consts::FRAC_PI_2;
896    for q in 0..4 {
897        let mut todo = vec![(q as f64 * quarter, (q + 1) as f64 * quarter, 0)];
898        let mut done = Vec::new();
899        while let Some((t0, t1, depth)) = todo.pop() {
900            if depth >= 24 || fine(t0, t1) {
901                done.push(t0);
902            } else {
903                let tm = (t0 + t1) / 2.0;
904                todo.push((tm, t1, depth + 1));
905                todo.push((t0, tm, depth + 1));
906            }
907        }
908        done.sort_by(f64::total_cmp);
909        ts.extend(done);
910    }
911    let mut cuts = Vec::with_capacity(ts.len());
912    for &t in &ts {
913        match cut(t) {
914            Some(c) => cuts.push(c),
915            None => return tiles(&outline, grid, 0, 0, nx, ny),
916        }
917    }
918    let mut pieces = Vec::new();
919    let mut solid = BezPath::new();
920    for (n, (inner, _)) in cuts.iter().enumerate() {
921        if n == 0 {
922            solid.move_to(*inner);
923        } else {
924            solid.line_to(*inner);
925        }
926    }
927    solid.close_path();
928    pieces.push(Piece::Solid(solid));
929    let tau = std::f64::consts::TAU;
930    for n in 0..ts.len() {
931        let (t0, t1) = (ts[n], if n + 1 < ts.len() { ts[n + 1] } else { tau });
932        let ((i0, o0), (i1, o1)) = (cuts[n], cuts[(n + 1) % cuts.len()]);
933        let mut wedge = BezPath::new();
934        wedge.move_to(i0);
935        wedge.line_to(i1);
936        wedge.line_to(o1);
937        wedge.line_to(o0);
938        wedge.close_path();
939        let tm = (t0 + t1) / 2.0;
940        if rho(t0).min(rho(t1)).min(rho(tm)) >= ROUND * std_dev {
941            pieces.push(Piece::Disc(wedge, at(tm) - normal(tm) * rho(tm), rho(tm)));
942        } else {
943            let bounds = wedge.bounding_box();
944            let i = |x: f64| ((x - grid.origin.x) / step).floor() as isize;
945            let j = |y: f64| ((y - grid.origin.y) / step).floor() as isize;
946            pieces.push(Piece::Patch(
947                Some(wedge),
948                i(bounds.x0),
949                j(bounds.y0),
950                i(bounds.x1) + 1,
951                j(bounds.y1) + 1,
952            ));
953        }
954    }
955    pieces
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961    use crate::compare::compare;
962    use crate::cpu::paint_area;
963    use crate::display::Frame;
964    use crate::display::List;
965
966    /// The most a shadow in pieces may differ from the same shadow as one
967    /// image, in any channel of 255, by how wide its blur is on the screen:
968    /// σ at the zoom, in device pixels. Measured over 3,000 random outlines
969    /// at 0.25×, 0.5×, 0.73×, 1×, 1.37× and 2× — what `random` makes, with
970    /// any seed. Where σ is a pixel or more, only the last bit of each
971    /// piece's 8-bit rounding is left; a narrower blur's edge is steeper than
972    /// a pixel, and vello_cpu's 8-bit gradient and layers round a disc
973    /// corner's a few hundredths of a pixel away from the sampled one.
974    fn bound(std_dev: f64, scale: f32) -> u8 {
975        match std_dev * scale as f64 {
976            s if s >= 1.0 => 4,
977            s if s >= 0.5 => 6,
978            s if s >= 0.25 => 11,
979            _ => 18,
980        }
981    }
982
983    /// Paints `outline`'s shadow at each scale as one image and in pieces,
984    /// and holds the two to the engine's tolerance — no seam — and to
985    /// [`bound`].
986    fn pieces_match_one_image(outline: Outline, std_dev: f64, case: &str, scales: &[f32]) {
987        let color = Rgba {
988            r: 20,
989            g: 30,
990            b: 40,
991            a: 200,
992        };
993        let paint = |single: usize, scale: f32| {
994            let area = Frame {
995                x: 0.0,
996                y: 0.0,
997                width: 360.0,
998                height: 220.0,
999            };
1000            let list = List::of(area, |b| {
1001                shadow_with(outline, std_dev, color, b, &mut Vec::new(), single)
1002            });
1003            let p = paint_area(&list, Rect::new(0.0, 0.0, 360.0, 220.0), scale as f64);
1004            // How many commands, and how many layers they are drawn in.
1005            let chunk = list.chunk(&Vec::new()).unwrap();
1006            let shape = (chunk.commands.len(), chunk.made.effects.len());
1007            (p.data_as_u8_slice().to_vec(), p.width() as usize, shape)
1008        };
1009        for &scale in scales {
1010            let (one, width, single_list) = paint(usize::MAX, scale);
1011            let (pieces, _, pieced_list) = paint(0, scale);
1012            assert_eq!(single_list, (1, 0), "{case}");
1013            assert!(pieced_list.1 > 1, "{case} isn't in pieces");
1014            let d = compare(&one, &pieces, width).unwrap();
1015            assert!(
1016                d.within_tolerance() && d.max <= bound(std_dev, scale),
1017                "{case}, σ {std_dev}, at {scale}: {d:?}"
1018            );
1019        }
1020    }
1021
1022    /// A shadow drawn in pieces is the shadow drawn as one image — no seam
1023    /// where pieces meet, no step at a corner — at 1× and at scales that put
1024    /// every edge between pieces part way across a pixel, for square
1025    /// corners, sampled corners, disc corners, a pill, a thin box, a thin
1026    /// ellipse, a circle, and ellipses in wedges with and without sampled
1027    /// tips; the box 1.48 pixels tall blurred by less than 2 that once
1028    /// differed by 7 at 1×; and random outlines.
1029    #[test]
1030    fn a_shadow_in_pieces_is_the_shadow_in_one() {
1031        let r = |x0, y0, x1, y1| Rect::new(x0, y0, x1, y1);
1032        let cases = [
1033            (Outline::rounded(r(30.3, 20.7, 250.1, 170.9), [0.0; 4]), 4.0),
1034            (
1035                Outline::rounded(r(30.3, 20.7, 250.1, 170.9), [3.0, 80.0, 12.0, 45.0]),
1036                4.0,
1037            ),
1038            (
1039                Outline::rounded(r(30.0, 40.0, 330.0, 120.0), [40.0; 4]),
1040                2.0,
1041            ),
1042            (Outline::rounded(r(30.0, 40.0, 330.0, 43.0), [1.0; 4]), 6.0),
1043            (Outline::ellipse(r(25.5, 30.25, 300.5, 140.75)), 3.0),
1044            (Outline::ellipse(r(25.0, 30.0, 185.0, 190.0)), 2.0),
1045            (Outline::ellipse(r(15.3, 30.6, 345.2, 190.1)), 2.0),
1046            (Outline::ellipse(r(20.0, 60.0, 340.0, 150.0)), 1.0),
1047            (
1048                Outline::rounded(
1049                    r(50.0986, 43.2465, 329.1681, 44.7226),
1050                    [0.738, 0.738, 0.738, 0.0],
1051                ),
1052                0.869,
1053            ),
1054            (
1055                Outline::rounded(r(63.287, 18.532, 289.892, 187.314), [80.0; 4]),
1056                0.584,
1057            ),
1058        ];
1059        for (n, (outline, std_dev)) in cases.into_iter().enumerate() {
1060            pieces_match_one_image(outline, std_dev, &format!("case {n}"), &[1.0, 0.73, 1.37]);
1061        }
1062        let mut seed = 0x2545_f491_4f6c_dd1du64;
1063        for n in 0..12 {
1064            let (outline, std_dev) = random(&mut seed);
1065            pieces_match_one_image(outline, std_dev, &format!("random {n}"), &[0.5, 1.0]);
1066        }
1067    }
1068
1069    /// A random outline that fits the test's 360 × 220 area with its blur, and
1070    /// one image of its shadow's samples, and its σ, from `seed`: a box with
1071    /// square, sampled, nearly-disc, pill-round or random corners — all alike
1072    /// or each its own — or an ellipse, blurred by σ from half a pixel to six.
1073    fn random(seed: &mut u64) -> (Outline, f64) {
1074        let mut next = || {
1075            *seed = seed
1076                .wrapping_mul(6364136223846793005)
1077                .wrapping_add(1442695040888963407);
1078            (*seed >> 11) as f64 / (1u64 << 53) as f64
1079        };
1080        let (aw, ah) = (360.0, 220.0);
1081        let sd = 0.5 + next() * 5.5;
1082        let reach = 3.0 * sd;
1083        // No wider than one image of samples can show, with its blur.
1084        let most = SINGLE_SIDE as f64 * sd / 2.0 - 2.0 * reach - sd - 1.0;
1085        let w = 1.0 + next() * (aw - 2.0 * reach - 20.0).min(most);
1086        let h = 1.0 + next() * (ah - 2.0 * reach - 20.0).min(most);
1087        let x0 = reach + 5.0 + next() * (aw - 2.0 * reach - 10.0 - w);
1088        let y0 = reach + 5.0 + next() * (ah - 2.0 * reach - 10.0 - h);
1089        let rect = Rect::new(x0, y0, x0 + w, y0 + h);
1090        let half = w.min(h) / 2.0;
1091        let kind = (next() * 6.0) as usize;
1092        if kind == 5 {
1093            return (Outline::ellipse(rect), sd);
1094        }
1095        let mut corners = [(0, 0.0); 4];
1096        for c in &mut corners {
1097            *c = ((next() * 5.0) as usize, next());
1098        }
1099        let alike = next() < 0.5;
1100        let radius = |(kind, u): (usize, f64)| match kind {
1101            0 => 0.0,
1102            1 => u * ROUND * sd,
1103            2 => ROUND * sd * (0.98 + 0.04 * u),
1104            3 => half,
1105            4 => half - u * 3.0 * sd,
1106            _ => u * half,
1107        };
1108        let radii = if alike {
1109            [radius(corners[0]); 4]
1110        } else {
1111            corners.map(radius)
1112        };
1113        (Outline::rounded(rect, radii), sd)
1114    }
1115}