Skip to main content

emblema_core/
canvas.rs

1//! The recording surface.
2//!
3//! A canvas is where drawing is expressed. It holds a transform stack and
4//! accumulates shapes into a batch, which is what a backend is eventually
5//! handed. Recording is separate from submitting so that a whole frame can be
6//! described before any of it reaches the GPU — that separation is what lets
7//! draws be batched into one pass rather than submitted one at a time.
8
9use crate::paint::{GradientStop, ImageFilter, MaskBlurStyle, Paint, Shader, Style};
10use crate::ramp::Ramp;
11use crate::vertices::{Sprite, VertexMode, Vertices};
12use crate::Color;
13use emblema_geometry::stroke::{LineCap, LineJoin, StrokeStyle};
14use emblema_geometry::transform::{
15    invert_to_local, max_scale, preserves_axis_alignment, to_local_columns, transformed_bounds,
16    unbounded, viewport_projection, Transform2D,
17};
18use emblema_geometry::{FillRule, Path, PathBuilder, Rect as GeometryRect};
19use emblema_hal::{
20    Batch, BlendMode, ClipState, ColorFilter, Error, Extent2D, Material, PassDescriptor,
21    PassViewport, Result, Sampling, Scissor, Stop, TileMode, Vertex, MAX_STOPS, MORPHOLOGY_TAPS,
22};
23use emblema_renderer::{Paint as RenderPaint, Renderer, TOLERANCE};
24use emblema_text::{Atlas, PositionedGlyph};
25use glam::{Affine2, Mat2, Vec2};
26
27/// A rectangle in user coordinates.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct Rect {
30    pub left: f32,
31    pub top: f32,
32    pub right: f32,
33    pub bottom: f32,
34}
35
36impl Rect {
37    pub fn new(left: f32, top: f32, right: f32, bottom: f32) -> Self {
38        Self {
39            left,
40            top,
41            right,
42            bottom,
43        }
44    }
45
46    pub fn from_size(width: f32, height: f32) -> Self {
47        Self::new(0.0, 0.0, width, height)
48    }
49
50    pub fn width(&self) -> f32 {
51        self.right - self.left
52    }
53
54    pub fn height(&self) -> f32 {
55        self.bottom - self.top
56    }
57
58    pub fn is_empty(&self) -> bool {
59        self.width() <= 0.0 || self.height() <= 0.0
60    }
61
62    /// The same rectangle, grown by `reach` on every side.
63    ///
64    /// What a blur needs from the bounds of what it blurs: the result spreads
65    /// outward, so a target sized to the content alone cuts the halo off square
66    /// at the edge -- the failure looking exactly like a shadow with a straight
67    /// side. Written once because it was written out twice, four lines at a
68    /// time, and a third place needs it with one side extended further.
69    pub fn outset(self, reach: f32) -> Self {
70        Self::new(
71            self.left - reach,
72            self.top - reach,
73            self.right + reach,
74            self.bottom + reach,
75        )
76    }
77
78    fn to_path(self) -> Path {
79        let mut b = PathBuilder::new();
80        b.move_to(Vec2::new(self.left, self.top))
81            .line_to(Vec2::new(self.right, self.top))
82            .line_to(Vec2::new(self.right, self.bottom))
83            .line_to(Vec2::new(self.left, self.bottom))
84            .close();
85        // A rectangle is a rounded one whose corners are not rounded, and
86        // recording it as such is what lets a blurred rectangle be evaluated
87        // rather than blurred. Not a special case in the expression that draws
88        // it: a corner radius of zero is where that approximation is at its
89        // most accurate, since there is no corner to approximate.
90        b.as_rounded_rect(
91            GeometryRect::new(
92                Vec2::new(self.left, self.top),
93                Vec2::new(self.right, self.bottom),
94            ),
95            0.0,
96        );
97        b.build()
98    }
99
100    /// This rectangle with its corners rounded to `radius`.
101    ///
102    /// The radius is clamped to half the shorter side. Larger is not an error
103    /// worth refusing -- a caller asking for a fully rounded end usually says
104    /// so by passing something enormous -- and left unclamped the corner arcs
105    /// would overlap and the outline would cross itself, which fills as
106    /// something nobody asked for. Clamped, the shape degenerates to a stadium
107    /// and then a circle, which is what asking for a huge radius means.
108    ///
109    /// A radius at or below zero gives the plain rectangle, so a caller can
110    /// pass a radius that happens to be zero without special-casing it.
111    pub fn to_rounded_path(self, radius: f32) -> Path {
112        if self.is_empty() {
113            return Path::default();
114        }
115        // NaN is checked before clamping rather than after, because `f32::min`
116        // ignores a NaN operand: clamping first turns it into half the shorter
117        // side, so arithmetic that went wrong would come back as a large
118        // rounded rectangle instead of as the plain one asked for.
119        //
120        // An infinite radius is not rejected with it. It clamps like any other
121        // large number, because a caller who writes one means the roundest
122        // shape available rather than none at all, and answering with a square
123        // would be the opposite of what was asked.
124        if radius.is_nan() || radius <= 0.0 {
125            return self.to_path();
126        }
127        let mut path = PathBuilder::new();
128        self.add_rounded_contour(&mut path, radius);
129        // Recorded beside the drawing rather than inferred later, so a route
130        // that wants the shape rather than the outline can have it -- a mask
131        // blur on this is evaluated in the fragment stage and needs a rect and
132        // a radius, which eight cubics cannot give back.
133        path.as_rounded_rect(
134            GeometryRect::new(
135                Vec2::new(self.left, self.top),
136                Vec2::new(self.right, self.bottom),
137            ),
138            radius.min(self.width() / 2.0).min(self.height() / 2.0),
139        );
140        path.build()
141    }
142
143    /// This rectangle with each corner rounded to its own pair of radii.
144    ///
145    /// The eight numbers `dart:ui`'s `RRect` carries, in upstream's order:
146    /// top-left, top-right, bottom-left, bottom-right, each an x radius and a
147    /// y radius. [`Self::to_rounded_path`] is this with all four the same and
148    /// circular, and goes through the same code.
149    pub fn to_rounded_path_with_radii(self, radii: RoundingRadii) -> Path {
150        if self.is_empty() {
151            return Path::default();
152        }
153        let radii = self.fitted_radii(radii);
154        if radii.iter().flatten().all(|v| *v <= 0.0) {
155            return self.to_path();
156        }
157        let mut path = PathBuilder::new();
158        self.add_rounded_contour_with_radii(&mut path, radii);
159        path.build()
160    }
161
162    /// Add this rectangle's rounded outline to a path already being built.
163    ///
164    /// [`Self::to_rounded_path_with_radii`] is this and nothing else when the
165    /// path holds one contour. It is public for the case that one cannot
166    /// serve: a shape made of two of these -- the ring `drawDRRect` fills, or a
167    /// caller's own compound outline -- needs both contours in one path, and a
168    /// path built from two paths is not something this crate offers.
169    ///
170    /// The radii are fitted on the way in, so a
171    /// caller passing radii that overrun a side gets the same scaling
172    /// `drawRRect` would apply rather than an outline that crosses itself.
173    pub fn add_rounded_outline(self, path: &mut PathBuilder, radii: RoundingRadii) {
174        if self.is_empty() {
175            return;
176        }
177        let radii = self.fitted_radii(radii);
178        self.add_rounded_contour_with_radii(path, radii);
179    }
180
181    /// The radii this rectangle can actually carry, made finite and made to fit.
182    ///
183    /// The fitting is `dart:ui`'s rule: find the edge whose two radii overrun
184    /// it worst, and scale *every* radius by that one ratio. Scaling only the
185    /// offending pair would also keep the outline from crossing itself, and
186    /// would change the shape's proportions -- the difference between a rounded
187    /// rectangle whose corners all got smaller and one that came back with a
188    /// lopsided pair nobody asked for.
189    ///
190    /// It is applied to the radii as given, which is the part that has to be
191    /// resisted tidying. Holding each radius to the side it runs along first
192    /// looks like a harmless guard and is not: it changes the ratios the rule
193    /// then works from, so a circular radius larger than the rectangle comes
194    /// back elliptical -- half the width across and half the height down,
195    /// instead of the round end the caller asked for.
196    ///
197    /// Which leaves the two values the rule cannot divide by. NaN and anything
198    /// at or below zero become zero, so a corner whose arithmetic went wrong is
199    /// square rather than enormous. An infinity becomes the longer side, which
200    /// is not arbitrary: once a uniform radius is large enough to bind, the
201    /// result stops depending on how large it was -- the ratio shrinks exactly
202    /// as fast as the radius grows -- so any sufficiently large stand-in gives
203    /// the same shape a huge finite radius gives, which is what an infinite one
204    /// has always meant here.
205    fn fitted_radii(self, radii: RoundingRadii) -> RoundingRadii {
206        let (w, h) = (self.width(), self.height());
207        let mut r = radii;
208        for corner in r.iter_mut() {
209            for value in corner.iter_mut() {
210                *value = if value.is_nan() || *value <= 0.0 {
211                    0.0
212                } else if value.is_infinite() {
213                    w.max(h)
214                } else {
215                    *value
216                };
217            }
218        }
219        let [tl, tr, bl, br] = r;
220        // Each edge against the two radii that meet along it. A sum of zero
221        // cannot bind, and is skipped rather than divided by.
222        let mut scale = 1.0f32;
223        for (side, sum) in [
224            (w, tl[0] + tr[0]),
225            (h, tr[1] + br[1]),
226            (w, bl[0] + br[0]),
227            (h, tl[1] + bl[1]),
228        ] {
229            if sum > side {
230                scale = scale.min(side / sum);
231            }
232        }
233        if scale < 1.0 {
234            for corner in r.iter_mut() {
235                for value in corner.iter_mut() {
236                    *value *= scale;
237                }
238            }
239        }
240        r
241    }
242
243    /// Append this rectangle's rounded outline to a builder, as one contour.
244    ///
245    /// Separate from [`Self::to_rounded_path`] because a shape made of two of
246    /// these -- a ring between an outer rectangle and an inner one -- needs
247    /// both in one path, and a path built from two paths is not something this
248    /// crate offers.
249    fn add_rounded_contour(self, path: &mut PathBuilder, radius: f32) {
250        let radii = self.fitted_radii([[radius; 2]; 4]);
251        self.add_rounded_contour_with_radii(path, radii);
252    }
253
254    /// The same, for radii that have already been fitted by `fitted_radii`.
255    fn add_rounded_contour_with_radii(self, path: &mut PathBuilder, radii: RoundingRadii) {
256        let [tl, tr, bl, br] = radii;
257        // The same constant that makes four cubics a circle. A corner here is a
258        // quarter *ellipse* rather than a quarter circle, and the constant
259        // carries over unchanged: an ellipse is a circle scaled along each axis
260        // independently, and scaling a cubic's control points by the same
261        // factors scales the curve they describe.
262        let k = |v: f32| KAPPA * v;
263        let (l, t, r, b) = (self.left, self.top, self.right, self.bottom);
264        path.move_to(Vec2::new(l + tl[0], t))
265            .line_to(Vec2::new(r - tr[0], t))
266            .cubic_to(
267                Vec2::new(r - tr[0] + k(tr[0]), t),
268                Vec2::new(r, t + tr[1] - k(tr[1])),
269                Vec2::new(r, t + tr[1]),
270            )
271            .line_to(Vec2::new(r, b - br[1]))
272            .cubic_to(
273                Vec2::new(r, b - br[1] + k(br[1])),
274                Vec2::new(r - br[0] + k(br[0]), b),
275                Vec2::new(r - br[0], b),
276            )
277            .line_to(Vec2::new(l + bl[0], b))
278            .cubic_to(
279                Vec2::new(l + bl[0] - k(bl[0]), b),
280                Vec2::new(l, b - bl[1] + k(bl[1])),
281                Vec2::new(l, b - bl[1]),
282            )
283            .line_to(Vec2::new(l, t + tl[1]))
284            .cubic_to(
285                Vec2::new(l, t + tl[1] - k(tl[1])),
286                Vec2::new(l + tl[0] - k(tl[0]), t),
287                Vec2::new(l + tl[0], t),
288            )
289            .close();
290    }
291}
292
293/// The single radius these corners all are, if they are all the same one.
294///
295/// `None` for anything the fragment-evaluated route cannot describe: a corner
296/// that differs from another, or one whose two radii differ from each other.
297fn uniform_circular_radius(radii: RoundingRadii) -> Option<f32> {
298    let radius = radii[0][0];
299    radii
300        .iter()
301        .flatten()
302        .all(|v| *v == radius)
303        .then_some(radius)
304}
305
306/// A rounded rectangle's four corners, each with an x and a y radius.
307///
308/// In upstream's order -- top-left, top-right, bottom-left, bottom-right --
309/// rather than in the order the outline is traced, so that a caller porting
310/// from `RoundingRadii` or from `dart:ui`'s `RRect` can copy the four across
311/// without reordering them. The tracing order is the contour's business.
312pub type RoundingRadii = [[f32; 2]; 4];
313
314/// The outline of a rounded superellipse in `rect` with the given radii.
315///
316/// Here rather than on `Rect` beside `to_rounded_path_with_radii`, because a
317/// superellipse is not a rounded rectangle with a different corner and putting
318/// it there would suggest the two are interchangeable. They take the same four
319/// numbers and draw measurably different shapes.
320fn rsuperellipse_path(rect: Rect, radii: RoundingRadii) -> Path {
321    use emblema_geometry::superellipse::{CornerRadii, RoundSuperellipse};
322    let bounds = GeometryRect::new(
323        Vec2::new(rect.left, rect.top),
324        Vec2::new(rect.right, rect.bottom),
325    );
326    RoundSuperellipse::new(
327        bounds,
328        CornerRadii {
329            top_left: Vec2::new(radii[0][0], radii[0][1]),
330            top_right: Vec2::new(radii[1][0], radii[1][1]),
331            bottom_left: Vec2::new(radii[2][0], radii[2][1]),
332            bottom_right: Vec2::new(radii[3][0], radii[3][1]),
333        },
334    )
335    .to_path()
336}
337
338/// Where a pass's texture slot gets its content.
339///
340/// A recording is produced without touching a device, so it can name neither a
341/// texture nor an allocation. It names either an image the caller will supply
342/// or an earlier pass in the same recording, and whoever executes it resolves
343/// both.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum TextureSource {
346    /// The caller's image at this index in the table given at draw time.
347    Image(u32),
348    /// The output of the pass at this index in [`Recording::passes`].
349    Layer(usize),
350    /// The baked gradient at this index in [`Recording::ramps`].
351    ///
352    /// Unlike the other two this names something the recorder made rather than
353    /// something it was given or rendered, so it is uploaded at submission and
354    /// discarded with the frame.
355    Ramp(usize),
356}
357
358/// One target's worth of drawing.
359///
360/// Cloneable so that a finished recording can be drawn into another one: the
361/// passes are taken as they are, and the recording being drawn keeps its own
362/// copy for a caller who draws it more than once.
363#[derive(Clone)]
364pub struct Pass {
365    pub batch: Batch,
366    pub descriptor: PassDescriptor,
367    /// What each texture slot this pass samples refers to, in slot order.
368    pub sources: Vec<TextureSource>,
369    /// The size of the target this pass renders into.
370    ///
371    /// Per pass rather than per recording, because a layer given bounds
372    /// renders into a target the size of those bounds. The root pass always
373    /// carries the recording's extent, since that is the caller's surface.
374    pub extent: Extent2D,
375}
376
377/// How a run of points is joined up.
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
379pub enum PointMode {
380    /// Each point on its own, drawn as the stroke's cap.
381    #[default]
382    Points,
383    /// Each pair a segment, and an odd point at the end drawn as nothing.
384    Lines,
385    /// One open run through all of them.
386    Polygon,
387}
388
389/// A finished recording, ready to submit.
390///
391/// More than one pass where the recording used layers. A layer is drawn into a
392/// target of its own and then composited back, which cannot happen in the same
393/// pass that samples it: reading an attachment being written needs machinery
394/// this does not have, and the separation is what makes group opacity mean
395/// "make this subtree, then fade it" rather than "fade each shape in it".
396pub struct Recording {
397    /// Layers first, each before whatever samples it; the root target last.
398    ///
399    /// The order falls out of how they are recorded rather than being sorted:
400    /// a layer is finished when it is restored, which is necessarily before the
401    /// draw that composites it.
402    pub passes: Vec<Pass>,
403    /// The size of the caller's surface, which is what the root pass renders
404    /// at. A layer pass may be smaller; see [`Pass::extent`].
405    pub extent: Extent2D,
406    /// Gradients whose colors were too many to carry in a material, tabulated.
407    ///
408    /// Recorded here rather than per pass because a slot table is per pass and
409    /// this is not: the same gradient drawn into a layer and again over it is
410    /// one ramp named twice.
411    pub ramps: Vec<Ramp>,
412}
413
414impl Recording {
415    pub fn draw_count(&self) -> usize {
416        self.passes.iter().map(|p| p.batch.draw_count()).sum()
417    }
418
419    pub fn is_empty(&self) -> bool {
420        self.passes.iter().all(|p| p.batch.is_empty())
421    }
422
423    /// The pass drawn into the caller's surface.
424    pub fn root(&self) -> &Pass {
425        self.passes.last().expect("a recording always has a root")
426    }
427
428    /// How many offscreen targets executing this needs.
429    pub fn layer_count(&self) -> usize {
430        self.passes.len() - 1
431    }
432}
433
434/// The target a pass renders into, placed within the frame.
435///
436/// A layer with bounds renders into a target the size of those bounds rather
437/// than the size of the frame, which is most of the point of giving bounds: a
438/// layer covering a tenth of the frame costs a tenth of the memory and a tenth
439/// of the fill. Everything that turns a device position into a clip position
440/// has to know where that target sits, which is what `origin` carries.
441#[derive(Debug, Clone, Copy)]
442struct Target {
443    /// Where this target's top-left corner sits in the frame, in device pixels.
444    /// Whole pixels, so that the composite samples texel centers exactly.
445    origin: Vec2,
446    extent: Extent2D,
447}
448
449impl Target {
450    fn frame(extent: Extent2D) -> Self {
451        Self {
452            origin: Vec2::ZERO,
453            extent,
454        }
455    }
456
457    /// Device position to clip position for this target.
458    ///
459    /// Affine, and stays so: a viewport is a scale, a flip and an offset. It is
460    /// lifted here because everything it composes with may not be.
461    fn projection(&self) -> Transform2D {
462        (viewport_projection(self.extent.width, self.extent.height)
463            * Affine2::from_translation(-self.origin))
464        .into()
465    }
466
467    /// The whole target, in the device space the projection expects.
468    fn path(&self) -> Path {
469        Rect::new(
470            self.origin.x,
471            self.origin.y,
472            self.origin.x + self.extent.width as f32,
473            self.origin.y + self.extent.height as f32,
474        )
475        .to_path()
476    }
477}
478
479/// One stencil clip in force, kept so it can be made again.
480///
481/// A stencil clip is a *draw*: it steps the stencil forward where the shape
482/// covers, and every content draw after it tests against what that draw left.
483/// A pass cut starts a new pass, whose stencil attachment begins cleared -- so
484/// unless the narrowing draws are made again, every draw after the cut tests a
485/// buffer nothing wrote and lands nowhere.
486///
487/// Kept as the shape rather than as the draw, because the shape is what
488/// `clip_path` needs to make one and the draw lives in a batch that the cut has
489/// already taken away.
490#[derive(Debug, Clone)]
491struct StencilClip {
492    path: Path,
493    /// The transform the shape was stated in. `clip_out_rect` builds its
494    /// contours in device pixels and passes the identity; `clip_path` passes
495    /// whatever was in force.
496    transform: Transform2D,
497    /// The scissor in force when it was made, which narrows the narrowing.
498    scissor: Option<Scissor>,
499}
500
501/// Transform and clip, saved together.
502///
503/// One stack rather than two: a `save` and its `restore` bracket a subtree, and
504/// letting the two pieces of state unwind independently would mean a caller
505/// could balance one while leaving the other adrift.
506#[derive(Debug)]
507struct SavedState {
508    transform: Transform2D,
509    clip: Option<Scissor>,
510    clip_bounds: Rect,
511    depth: u32,
512    /// How many stencil clips were in force, so `restore` can drop the ones
513    /// this save added. Redundant with `depth` and kept beside it for the same
514    /// reason the bounds are kept beside the scissor: one of them is the truth
515    /// the device holds and the other is what would be needed to rebuild it.
516    clips: usize,
517    /// Set where this save opened a layer, holding what the layer displaced.
518    layer: Option<LayerFrame>,
519}
520
521/// A layer in progress: the parent's recording, set aside until it returns.
522#[derive(Debug)]
523struct LayerFrame {
524    batch: Batch,
525    sources: Vec<TextureSource>,
526    /// The stencil clips in force on the parent, set aside with its batch.
527    ///
528    /// A layer starts unclipped -- the composite that returns it is subject to
529    /// the parent's clip instead -- so it needs a list of its own, and the
530    /// parent's has to come back when it does. Held here rather than as a
531    /// length in `SavedState`, because unlike every other save this one does
532    /// not *extend* the list it found.
533    clips: Vec<StencilClip>,
534    paint: Layer,
535    /// An image filter to run over the finished layer, if one was asked for.
536    ///
537    /// Beside the layer rather than inside it, because [`Layer`] is `Copy` and
538    /// small and is copied at every `save_layer`, while a filter can hold a
539    /// composition or a program's sixty-four uniform floats. The fields on the
540    /// layer cover the four kinds that fit in one; this covers the rest, and
541    /// the two orders a composition can take.
542    filter: Option<ImageFilter>,
543    /// The target the parent was drawing into, restored when the layer closes.
544    parent: Target,
545    /// Whether the parent's own batch had asked for antialiasing yet.
546    ///
547    /// Displaced with the batch and for the same reason: the sample count
548    /// describes a pass, and a layer's draws belong to the layer's pass. A
549    /// parent that has drawn nothing needing multisampling does not start
550    /// needing it because something inside a layer did.
551    anti_alias: bool,
552    /// Whether the parent's batch began by redrawing the whole target.
553    ///
554    /// Displaced with the batch, like `anti_alias` and for the same reason: a
555    /// layer's own batch starts empty and is seeded by nothing, while the parent's
556    /// may have been cut before the layer opened.
557    seeded_by_redraw: bool,
558    /// The directions this layer's blur runs along.
559    ///
560    /// Taken from the transform in force when the layer opened, for the same
561    /// reason its sigma is: the transform that decides them may be gone by the
562    /// time the layer is composited, and both halves of a blur -- how far it
563    /// reaches and which way -- have to be settled together or a target is
564    /// sized for one blur and filled by another.
565    blur_basis: BlurBasis,
566}
567
568/// The two directions a blur runs along, in device pixels.
569///
570/// A blur is two separable passes, and which directions they take is the whole
571/// of the difference between a blur that turns with the caller's transform and
572/// one that does not. `dart:ui` states a deviation per axis in the space the
573/// caller was drawing in; if that space is turned relative to the target, the
574/// passes have to turn with it or a horizontal smear stays horizontal on
575/// screen while the thing it is smearing rotates underneath.
576///
577/// **This is not how upstream does it, and the difference is worth stating.**
578/// `GaussianBlurFilterContents` removes the rotation instead: it re-renders its
579/// input into what its own comment calls "un-rotated local space", scaled by
580/// the transform but not turned by it, blurs along that space's own axes, and
581/// applies the rotation to the *result*. Its reason is quality rather than
582/// correctness -- the comment says the un-rotated space "is a requirement for
583/// text to be rendered correctly", because taps landing on texel centers is
584/// what keeps a glyph sharp.
585///
586/// That arrangement is not available here. A layer is a recorded pass with a
587/// device-space target, a device-space scissor and a stencil buffer to match,
588/// so its content cannot be drawn into a space of its own choosing after the
589/// fact. What *is* available is the pass's `step`, which was already a free
590/// two-vector rather than an axis flag -- the shader walks its taps along
591/// whatever direction it is given. So the passes turn instead of the space.
592///
593/// The two are the same Gaussian. A blur with deviations along orthogonal
594/// directions is separable along exactly those directions, so the picture is
595/// upstream's; what differs is that a tap here lands between texels and is
596/// resolved by the sampler, which costs a little sharpness that upstream's
597/// arrangement does not.
598#[derive(Debug, Clone, Copy, PartialEq)]
599struct BlurBasis {
600    /// Unit vectors in device space, in the order the deviations are stated.
601    directions: [Vec2; 2],
602}
603
604impl BlurBasis {
605    /// The target's own axes, which is what every blur used before this and
606    /// what a transform this cannot decompose still gets.
607    const AXES: Self = Self {
608        directions: [Vec2::X, Vec2::Y],
609    };
610
611    /// Where the caller's axes point once the transform has been applied.
612    ///
613    /// Refused rather than approximated in two cases. A transform with
614    /// perspective has no single basis -- the directions would differ per
615    /// fragment, which a pass walking a constant step cannot express. And a
616    /// transform whose image axes are not perpendicular, which is a shear,
617    /// leaves a Gaussian that two separable passes cannot state at all:
618    /// separability is a property of orthogonal directions, and running the
619    /// passes along oblique ones would not be a wrong blur so much as not a
620    /// blur. Upstream is no better off here -- its `ExtractScale` takes the
621    /// lengths of the image axes and drops the shear entirely.
622    fn of(transform: Transform2D) -> Self {
623        let Some(affine) = transform.to_affine() else {
624            return Self::AXES;
625        };
626        let (x, y) = (affine.matrix2.x_axis, affine.matrix2.y_axis);
627        let (lx, ly) = (x.length(), y.length());
628        if !lx.is_finite() || !ly.is_finite() || lx <= 0.0 || ly <= 0.0 {
629            return Self::AXES;
630        }
631        let directions = [x / lx, y / ly];
632        // The cosine of the angle between them, both being unit vectors. A
633        // thousandth is well inside what a rotation composed with a scale
634        // produces and well outside anything a shear does.
635        if directions[0].dot(directions[1]).abs() > 1e-3 {
636            return Self::AXES;
637        }
638        Self { directions }
639    }
640
641    /// Whether these are the target's own axes, which several things below can
642    /// take shortcuts for.
643    fn is_axis_aligned(&self) -> bool {
644        *self == Self::AXES
645    }
646
647    /// How far past its content a blur along these directions carries, as an
648    /// outset on each of the target's axes.
649    ///
650    /// The bounding box of the two reaches laid along the two directions,
651    /// which for the target's own axes is the pair of reaches unchanged.
652    fn reach(&self, sigma: Vec2) -> Vec2 {
653        self.box_of(Vec2::new(blur_reach(sigma.x), blur_reach(sigma.y)))
654    }
655
656    /// The target-axis bounding box of two distances laid along these directions.
657    ///
658    /// Shared with the morphology reach rather than written twice, because the
659    /// two have to agree with the passes to the pixel: a pass walks `u` and `v`
660    /// and whatever room is reserved has to contain where that walk ends. It was
661    /// written twice for a while, and the morphology copy did not turn -- so a
662    /// rotated dilation ran along the caller's axes and was clipped by an outset
663    /// laid along the target's.
664    fn box_of(&self, along: Vec2) -> Vec2 {
665        let [u, v] = self.directions;
666        Vec2::new(
667            u.x.abs() * along.x + v.x.abs() * along.y,
668            u.y.abs() * along.x + v.y.abs() * along.y,
669        )
670    }
671}
672
673/// Spreading or shrinking a finished layer, one axis at a time.
674///
675/// The pair `dart:ui` calls `ImageFilter.dilate` and `ImageFilter.erode`: each
676/// output pixel takes the largest, or the smallest, of the input within a
677/// rectangle around it. The rectangle is why the radii are per axis and why the
678/// filter is separable at all.
679#[derive(Debug, Clone, Copy, PartialEq)]
680pub struct Morphology {
681    /// How far the structuring element reaches along each axis, in device
682    /// pixels.
683    pub radius: [f32; 2],
684    /// Take the largest sample in reach rather than the smallest.
685    pub dilate: bool,
686}
687
688impl Morphology {
689    /// Spread the layer: each pixel becomes the largest within the radii.
690    pub fn dilate(x: f32, y: f32) -> Self {
691        Self {
692            radius: Self::sane(x, y),
693            dilate: true,
694        }
695    }
696
697    /// Shrink the layer: each pixel becomes the smallest within the radii.
698    pub fn erode(x: f32, y: f32) -> Self {
699        Self {
700            radius: Self::sane(x, y),
701            dilate: false,
702        }
703    }
704
705    /// Not negative, and finite.
706    ///
707    /// No longer rounded here, and the reason is the whole of the change that
708    /// made the radius a local length. A structuring element is a set of sample
709    /// positions and there is no half of one to keep -- but the positions are
710    /// *device* texels, and this runs on the caller's number before any
711    /// transform has been applied to it. Rounding a local length rounds the
712    /// wrong quantity: at a scale of three, a radius of 1.5 rounded here becomes
713    /// two and then six, where the sample positions it is naming are four and a
714    /// half. `applied_radius` rounds instead, where the device radius is known.
715    fn sane(x: f32, y: f32) -> [f32; 2] {
716        let one = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
717        [one(x), one(y)]
718    }
719
720    /// Whether this would leave every pixel where it was.
721    pub fn is_identity(&self) -> bool {
722        self.radius == [0.0, 0.0]
723    }
724
725    /// The radius worth applying on a target this size, per axis.
726    ///
727    /// A window reaching `extent` texels along an axis already spans the whole
728    /// of it, so every output pixel is the extreme over the entire row or
729    /// column and a wider one cannot change a single pixel. Dilating takes the
730    /// largest sample and eroding the smallest; either way the taps a larger
731    /// radius adds are all outside the image, and whatever the sampler returns
732    /// there is already in the window. So this clamp is picture-preserving
733    /// rather than a limit on the filter, which is what makes it safe to apply
734    /// without the caller having asked.
735    ///
736    /// **Why it has to exist.** `sane` bounds the radius below and
737    /// rejects what is not finite, and nothing bounded it above -- so the pass
738    /// loop, which emits one pass per [`MORPHOLOGY_TAPS`] texels, turned a
739    /// caller's float into that many passes. A radius of a million asked for
740    /// sixty-two thousand of them and a radius of `1e20` exhausted memory,
741    /// through the documented constructor and with no unsafe input anywhere:
742    /// the value is finite, positive and whole. That is a recording's size made
743    /// proportional to a scalar, which is the defect this closes.
744    ///
745    /// Non-finite gives zero, on the same terms as `sane` and for the same
746    /// reason a non-finite sigma gives no blur. Checked before the `min` rather
747    /// than after, because [`f32::min`] returns the other operand when one side
748    /// is NaN -- the trap `Layer::with_blur_xy` and `Rect::outset` both name,
749    /// and the one that would turn a NaN radius into a full-width dilation.
750    /// It also has to be handled here rather than left to the loop: the loop's
751    /// condition is false for NaN, so NaN was already harmless, but infinity
752    /// entered it and never left, since subtracting the taps from infinity
753    /// leaves infinity.
754    pub fn applied_radius(&self, extent: Extent2D) -> [f32; 2] {
755        let one = |radius: f32, along: u32| {
756            if radius.is_finite() {
757                // Rounded here rather than at construction, because this is the
758                // first point at which the number is in device texels: the
759                // caller states a local length and `Layer::scaled_by` converts
760                // it. A structuring element is a set of sample positions and
761                // there is no half of one, so the rounding still happens -- just
762                // where the positions are.
763                radius.max(0.0).min(along as f32).round()
764            } else {
765                0.0
766            }
767        };
768        [
769            one(self.radius[0], extent.width),
770            one(self.radius[1], extent.height),
771        ]
772    }
773}
774
775/// What a mask blur is blurring: a shape, or a run of glyphs.
776///
777/// An enum rather than a closure because every style draws its content two or
778/// three times and a closure taking `&mut Canvas` cannot be called twice while
779/// the canvas is borrowed. Two variants is also the whole set: a mask blur
780/// needs the content's coverage times one solid color, which a mesh's per-vertex
781/// colors rule out and an image's texels rule out.
782#[derive(Clone, Copy)]
783enum Masked<'a> {
784    Path(&'a Path),
785    /// A mesh carrying no per-vertex colors, so the paint supplies the color
786    /// the way it does for a path. One that carries them is refused before it
787    /// reaches here: see `draw_vertices`.
788    Mesh(&'a Vertices),
789    Glyphs {
790        glyphs: &'a [PositionedGlyph],
791        atlas: &'a Atlas,
792        slot: u32,
793    },
794}
795
796/// How a layer is composited back onto what was underneath it.
797///
798/// A separate type from [`Paint`] rather than a reuse of it, because only two
799/// of a paint's parts mean anything here — there is no shape to fill and no
800/// geometry to stroke — and a caller handed a `Paint` would reasonably expect
801/// its shader to matter.
802#[derive(Debug, Clone, Copy, PartialEq)]
803pub struct Layer {
804    /// Blur the group before compositing it, with this standard deviation per
805    /// axis in device pixels.
806    ///
807    /// Zero on both for no blur, which is the default and costs nothing: the
808    /// extra passes are only recorded where a caller asked for one, and an
809    /// axis whose deviation is zero costs no pass of its own.
810    ///
811    /// Two deviations rather than one because `dart:ui`'s `ImageFilter.blur`
812    /// states `sigmaX` and `sigmaY` separately, and because the blur is two
813    /// separable passes here regardless -- so the second is a field rather
814    /// than a mechanism. [`Self::with_blur`] sets both.
815    ///
816    /// On the group rather than on a paint, because a blur is a function of a
817    /// finished image and a paint describes one shape. Blurring each shape and
818    /// compositing the results is a different picture from blurring the
819    /// composite, and the second is what a shadow or a frosted panel means.
820    pub blur: Vec2,
821    /// Scales the whole layer on the way back. This is what makes group opacity
822    /// differ from per-shape opacity: two overlapping half-transparent shapes
823    /// in a layer show one blended edge, where the same shapes drawn directly
824    /// show where they cross.
825    pub alpha: f32,
826    /// How the finished layer meets what was underneath it.
827    pub blend: BlendMode,
828    /// Transform the finished layer on the way back, in device pixels.
829    ///
830    /// Distinct from transforming what goes into it, which the canvas's own
831    /// transform already does. This resamples the finished image: magnifying
832    /// through it gives the layer's own pixels enlarged, where drawing the
833    /// same shapes under a larger transform would give them redrawn at the
834    /// larger size. That difference is the whole of what a matrix image filter
835    /// means -- a caller wanting the sharp one already has the transform
836    /// stack.
837    ///
838    /// It resamples what the layer *captured*, and a layer captures no more
839    /// than its target holds. So a matrix moves an image and cannot recover
840    /// what fell outside the layer to begin with: a shape drawn past the edge
841    /// of the frame is gone before this runs, where upstream sizes the layer
842    /// through the filter and brings it back. `docs/non-parity.md` §12 has the
843    /// case and what fixing it would cost.
844    ///
845    /// `None` composites the layer where it was drawn, which is what every
846    /// layer did before this existed.
847    pub matrix: Option<Transform2D>,
848    /// Blur what is already on the target before the layer draws over it.
849    ///
850    /// This is the other blur, and the difference is which image is filtered.
851    /// [`Self::blur`] softens the layer's own content, which is what a shadow
852    /// is. This softens what is *behind* it and hands the result to the layer
853    /// as its starting content, which is what frosted glass is: a panel that
854    /// obscures rather than one that is itself indistinct.
855    ///
856    /// Zero for none, and it costs nothing when zero. When it is not zero it
857    /// costs a copy of the target and two blur passes over it, because reading
858    /// what a pass is writing is not something this renderer can do -- see the
859    /// architecture note on cutting a pass.
860    ///
861    /// # Bounds stop being an optimization
862    ///
863    /// For every other layer, [`Canvas::save_layer_bounds`] only says where the
864    /// content is, and the picture is the same either way. For this one the
865    /// bounds are the region that gets filtered: a frosted panel is a bounded
866    /// layer, and the same layer without bounds blurs the whole frame and
867    /// composites the whole frame back. Both are meaningful and they are
868    /// different pictures, so state the bounds when you mean a panel.
869    pub backdrop_blur: f32,
870    /// Which captured backdrop this layer filters, if it shares one.
871    ///
872    /// `dart:ui`'s `pushBackdropFilter` takes a `backdropId` and says what it
873    /// means: "when the first backdrop filter with a given id is processed
874    /// during rasterization, the state of the backdrop is recorded and cached.
875    /// All subsequent backdrop filters with the same identifier will apply
876    /// their filter to the cached backdrop." So it is a different picture, not
877    /// only a faster one -- overlapping panels sharing an id each filter what
878    /// was behind all of them, rather than each filtering the one before it.
879    ///
880    /// That is the case it exists for. A list of frosted rows over one
881    /// background wants each row to show the background, and without the id
882    /// the second row shows the first row's blur blurred again. With it, the
883    /// capture happens once and each row filters it: the picture the caller
884    /// meant, and one pass cut instead of one per row.
885    ///
886    /// An id keys a captured image and nothing more. A layer naming one from
887    /// inside another layer still filters what the id captured rather than its
888    /// own target's content, which is upstream's reading and is the point of
889    /// the case it tests with each panel wrapped in a save layer of its own.
890    ///
891    /// `None` captures afresh, which is what every layer did before this
892    /// existed and is right whenever the backdrops genuinely differ.
893    pub backdrop_id: Option<i64>,
894    /// Spread or shrink the group before compositing it. See [`Morphology`].
895    ///
896    /// On the group for the same reason [`Self::blur`] is: a maximum over a
897    /// window is a function of a finished image. Dilating each shape and then
898    /// compositing is a different picture from dilating the composite wherever
899    /// two shapes overlap.
900    ///
901    /// `None` for no morphology, which is the default and costs nothing.
902    pub morphology: Option<Morphology>,
903    /// Recolor the finished group on its way back.
904    ///
905    /// What `dart:ui` means by the `colorFilter` on the paint `saveLayer`
906    /// takes, and the same distinction group opacity has: filtering each shape
907    /// and compositing the results differs from filtering the composite
908    /// wherever two of them overlap, because a filter is not linear in general.
909    ///
910    /// It is also the only way to filter what a caller's own fragment program
911    /// drew. A runtime effect is a whole pipeline rather than a material this
912    /// renderer's shader evaluates, so there is nowhere in it to apply a
913    /// matrix -- the filter has to act on the image the program produced.
914    pub color_filter: ColorFilter,
915}
916
917impl Default for Layer {
918    fn default() -> Self {
919        Self {
920            blur: Vec2::ZERO,
921            alpha: 1.0,
922            blend: BlendMode::SrcOver,
923            matrix: None,
924            backdrop_blur: 0.0,
925            backdrop_id: None,
926            morphology: None,
927            color_filter: ColorFilter::None,
928        }
929    }
930}
931
932impl Layer {
933    /// Transform the finished layer on the way back. See [`Self::matrix`].
934    ///
935    /// Takes an affine or a projective transform, the same as `concat`. A layer
936    /// moved by one of these is a finished image being placed, so perspective
937    /// here gives the image seen at an angle rather than the content redrawn at
938    /// one -- which is the whole distinction this filter exists to make, and it
939    /// survives the widening unchanged.
940    pub fn with_matrix(mut self, matrix: impl Into<Transform2D>) -> Self {
941        self.matrix = Some(matrix.into());
942        self
943    }
944
945    pub fn opacity(alpha: f32) -> Self {
946        Self {
947            alpha,
948            ..Self::default()
949        }
950    }
951
952    pub fn with_blend(mut self, blend: BlendMode) -> Self {
953        self.blend = blend;
954        self
955    }
956
957    /// Recolor the finished group on its way back. See [`Self::color_filter`].
958    pub fn with_color_filter(mut self, filter: ColorFilter) -> Self {
959        self.color_filter = filter;
960        self
961    }
962
963    /// Spread or shrink the finished group. See [`Morphology`].
964    ///
965    /// A morphology that would move nothing becomes `None`, on the same
966    /// reasoning as a blur of zero: a caller animating a radius down to nothing
967    /// should get the unfiltered thing at the end, not two passes that copy the
968    /// image twice to say so.
969    pub fn with_morphology(mut self, morphology: Morphology) -> Self {
970        self.morphology = if morphology.is_identity() {
971            None
972        } else {
973            Some(morphology)
974        };
975        self
976    }
977
978    /// How far past the content this layer's filters reach, per axis, in device
979    /// pixels.
980    ///
981    /// A blur carries color outward and so does a dilation; an erosion only
982    /// eats inward and needs no room. The two can be asked for together, so
983    /// this is their sum rather than whichever is larger -- the passes run one
984    /// after the other, and the second reaches out from where the first put
985    /// things.
986    /// The same layer with its lengths converted into device pixels.
987    ///
988    /// A sigma reaches the caller in the space they were drawing in and every
989    /// pass that acts on it works on a target, so one of the two has to move.
990    /// This is that move, and it happens once at `save_layer` rather than at
991    /// each use -- the transform that decides it is the one in force when the
992    /// layer is opened, and it may be gone by the time the layer is composited.
993    ///
994    /// **Every length stated per axis takes the axis factors, and the one stated
995    /// as a single number is converted elsewhere.** A blur's deviations and a
996    /// morphology's radii are pairs, and each component takes the length of its
997    /// own transformed basis vector -- which is what upstream's `ExtractScale`
998    /// and `TransformDirection` take.
999    ///
1000    /// `backdrop_blur` is deliberately *not* converted here, and the reason is
1001    /// that it cannot be. It is one number, so a caller states a blur that is
1002    /// round in their own space -- and a round blur under an anisotropic scale is
1003    /// an oval in device space, which one number cannot hold. Multiplying it by a
1004    /// single factor here is what used to happen and is what made a frosted panel
1005    /// stay round under `scale(2, 3)` while the same deviations on the layer
1006    /// itself stretched. So the field stays in the caller's space and
1007    /// `open_layer` converts it per axis at the point it becomes an
1008    /// `ImageFilter::Blur`, which has two components to put the answer in.
1009    ///
1010    /// Nothing between here and there reads it as a length: the two other uses
1011    /// are `> 0.0` tests asking whether a backdrop is wanted at all.
1012    fn scaled_by(self, scale: f32, axes: Vec2) -> Self {
1013        if !scale.is_finite() || scale <= 0.0 {
1014            return self;
1015        }
1016        Self {
1017            blur: self.blur * axes,
1018            backdrop_blur: self.backdrop_blur,
1019            // A morphology radius is a length in the caller's space too, and was
1020            // the one filter left out of this conversion -- on the stated
1021            // grounds that upstream had no morphology to be in parity with,
1022            // which was wrong. See `non-parity.md` 17.
1023            morphology: self.morphology.map(|m| Morphology {
1024                radius: [m.radius[0] * axes.x, m.radius[1] * axes.y],
1025                ..m
1026            }),
1027            ..self
1028        }
1029    }
1030
1031    fn reach(&self, basis: BlurBasis) -> Vec2 {
1032        let blur = basis.reach(self.blur);
1033        match self.morphology {
1034            // Turned with the same basis the passes walk. An axis-aligned outset
1035            // would be the right box only while the directions are the axes, and
1036            // a rotated dilation would lose its corners to the scissor.
1037            Some(m) if m.dilate => blur + basis.box_of(Vec2::new(m.radius[0], m.radius[1])),
1038            _ => blur,
1039        }
1040    }
1041
1042    /// Blur the finished group, with `sigma` in device pixels.
1043    ///
1044    /// Anything at or below zero, or not a number, means no blur rather than an
1045    /// error: a caller animating a shadow's softness to nothing should get the
1046    /// sharp thing, not a refusal at the end of the animation.
1047    /// Blur the backdrop this layer is drawn over.
1048    ///
1049    /// Ignored unless finite and positive, on the same terms as
1050    /// [`Self::with_blur`]: a sigma that is not a length describes no blur.
1051    pub fn with_backdrop_blur(mut self, sigma: f32) -> Self {
1052        self.backdrop_blur = if sigma.is_finite() && sigma > 0.0 {
1053            sigma
1054        } else {
1055            0.0
1056        };
1057        self
1058    }
1059
1060    /// Share one captured backdrop with every layer naming the same `id`.
1061    ///
1062    /// See [`Self::backdrop_id`] for what is shared and why it changes the
1063    /// picture rather than only the cost. The id is the caller's, and means
1064    /// nothing beyond identity: any two values that differ keep their
1065    /// backdrops apart.
1066    ///
1067    /// The id outlives the target it captured. A layer naming one from inside
1068    /// another layer is seeded with the captured image placed where that
1069    /// layer's target sits within it, which is the same arithmetic a bounded
1070    /// layer is already seeded by.
1071    pub fn with_backdrop_id(mut self, id: i64) -> Self {
1072        self.backdrop_id = Some(id);
1073        self
1074    }
1075
1076    pub fn with_blur(self, sigma: f32) -> Self {
1077        self.with_blur_xy(sigma, sigma)
1078    }
1079
1080    /// Blur the finished group by a deviation per axis, in device pixels.
1081    ///
1082    /// Two, because `dart:ui`'s `ImageFilter.blur` states `sigmaX` and
1083    /// `sigmaY` separately. A blur here is two separable passes already, one
1084    /// along each axis, so each simply uses its own -- and a pass whose
1085    /// deviation is zero is skipped rather than run, which is what keeps a
1086    /// blur along one axis from resampling the other for nothing.
1087    pub fn with_blur_xy(mut self, sigma_x: f32, sigma_y: f32) -> Self {
1088        // Clamped to upstream's `kMaxSigma`, and clamped *after* the check
1089        // rather than before it: `f32::min` returns the other operand when one
1090        // is NaN, so clamping first turns a NaN into five hundred and asks for
1091        // the widest blur there is. The same trap is named at `Rect::outset`,
1092        // which is where this was learned the first time.
1093        let one = |sigma: f32| {
1094            if sigma.is_finite() && sigma > 0.0 {
1095                sigma.min(MAX_SIGMA)
1096            } else {
1097                0.0
1098            }
1099        };
1100        self.blur = Vec2::new(one(sigma_x), one(sigma_y));
1101        self
1102    }
1103}
1104
1105/// Records drawing commands for one frame.
1106pub struct Canvas {
1107    renderer: Renderer,
1108    batch: Batch,
1109    transform: Transform2D,
1110    /// The region drawing is confined to, or `None` for the whole target.
1111    ///
1112    /// Kept in device pixels rather than user space because that is what it
1113    /// means: a clip is fixed at the moment it is applied, and a later
1114    /// transform moves the shapes drawn inside it without moving the clip.
1115    clip: Option<Scissor>,
1116    /// A rectangle around everything the clip still admits, in device pixels.
1117    ///
1118    /// Kept beside the scissor rather than derived from it, because a path
1119    /// clip narrows what may be drawn without narrowing the scissor at all --
1120    /// it goes to the stencil instead. A caller asking what is still reachable
1121    /// wants both accounted for, and only this has seen both.
1122    clip_bounds: Rect,
1123    /// How many clips of a shape a scissor cannot express are in force.
1124    ///
1125    /// Content draws where the stencil holds this, which is true only where
1126    /// every one of those clips admitted the pixel.
1127    depth: u32,
1128    /// Those clips, in the order they were built. See [`StencilClip`].
1129    clips: Vec<StencilClip>,
1130    stack: Vec<SavedState>,
1131    /// What the batch being recorded samples, in slot order.
1132    sources: Vec<TextureSource>,
1133    /// Layers already finished, in the order they were restored.
1134    ///
1135    /// A layer is restored before anything can composite it, so this order is
1136    /// already an order the passes can be executed in.
1137    finished: Vec<Pass>,
1138    extent: Extent2D,
1139    /// The target being recorded into: the frame, or a bounded layer's.
1140    target: Target,
1141    background: Option<Color>,
1142    /// Set once anything asks for antialiasing.
1143    ///
1144    /// Multisampling is a property of the pass, so it cannot vary per shape.
1145    /// Turning it on for the whole frame when any shape wants it is the
1146    /// behavior that surprises least; the alternative silently ignores the
1147    /// request on some shapes.
1148    anti_alias: bool,
1149    /// Whether the batch now open begins by redrawing the whole target.
1150    ///
1151    /// It does when a pass was cut: what follows the cut is a full-target `Src`
1152    /// blit of the pass just finished, unclipped and unstencilled, so every pixel
1153    /// is written before anything else in the batch. A pass like that can be given
1154    /// a clear color it will never show -- and a clear is what a multisampled pass
1155    /// requires here, the alternative being a resolved-to-multisample load that
1156    /// this technique has no reverse of.
1157    ///
1158    /// Tracked rather than inferred from `background` being absent, because a
1159    /// caller that never set a background is compositing onto whatever the surface
1160    /// already holds, and clearing *that* pass would erase it.
1161    seeded_by_redraw: bool,
1162    /// Whether to leave hidden pixels in the draws that write them.
1163    ///
1164    /// Culling them is pixel-identical by construction, and the way to check that claim
1165    /// is to render the same scene both ways and compare. Nothing but a test should want
1166    /// this, which is why it is reachable only through a hidden method.
1167    keep_hidden_draws: bool,
1168    samples: u32,
1169    /// Gradients tabulated because their stops did not fit in a material.
1170    ///
1171    /// Across the whole recording rather than per pass, so the same gradient
1172    /// drawn into a layer and again over it is baked once.
1173    ramps: Vec<Ramp>,
1174    /// Backdrops captured once and filtered by every layer naming the same id.
1175    ///
1176    /// A `Canvas` records one frame and `finish` consumes it, so this lives
1177    /// exactly as long as the ids are meaningful and there is nothing to
1178    /// clear. Upstream's `Canvas` is reused across frames and empties its
1179    /// `backdrop_data_` at the end of each one.
1180    backdrops: std::collections::HashMap<i64, BackdropShare>,
1181}
1182
1183/// A backdrop ready to be laid under a layer's own content.
1184///
1185/// Three things rather than a pass index, because a seed is a draw and a draw
1186/// needs a mapping: which pass holds the filtered image, which target that pass
1187/// is an image *of* -- they differ when a bounded layer seeds from its parent
1188/// -- and the matrix the filter asked for, which is the one filter that moves
1189/// the image rather than recomputing it where it stands.
1190#[derive(Clone, Copy)]
1191struct Backdrop {
1192    pass: usize,
1193    of: Target,
1194    /// `None` for every filter but a matrix, which is what it means for the
1195    /// image to be read where it was written.
1196    moved_by: Option<Affine2>,
1197}
1198
1199/// One captured backdrop, and what has already been made of it.
1200///
1201/// The capture is a pass index, which is all a backdrop needs to be here: a
1202/// pass is the unit a later pass samples, so sharing one is sharing the index
1203/// rather than managing a texture. Upstream carries a `std::shared_ptr<Texture>`
1204/// in the same slot, and a second one for the filtered result, because its
1205/// filters produce snapshots rather than passes.
1206struct BackdropShare {
1207    /// The target the capture is an image of, which need not be the one a
1208    /// later layer naming the id is drawn into.
1209    ///
1210    /// An id keys a captured image and nothing else, so a layer opened inside
1211    /// some other layer still filters what the id captured. That is upstream's
1212    /// reading and it is exercised there:
1213    /// `CanRenderMultipleBackdropBlurWithSingleBackdropIdDifferentLayers` wraps
1214    /// every panel but the first in a save layer of its own and expects all six
1215    /// to show the same ground. Seeding needs no case for it -- a filtered pass
1216    /// is drawn into a rectangle *of* its source, which is already how a
1217    /// bounded layer is seeded from a full-target capture.
1218    captured_from: Target,
1219    /// The pass holding the backdrop as it was when the id was first used.
1220    captured: usize,
1221    /// Filters already run over `captured`, and where each landed.
1222    ///
1223    /// A filter is a function of its input, so the same filter over the same
1224    /// capture is the same image and there is no reason to compute it twice.
1225    /// This is upstream's `all_filters_equal` and `shared_filter_snapshot`,
1226    /// with the restriction lifted: upstream shares one snapshot only when
1227    /// *every* filter on the id is equal, which a list of rows that blur by
1228    /// different amounts fails outright. Keyed per filter, two amounts share
1229    /// what they have in common -- the capture -- and each still gets its own.
1230    ///
1231    /// A list rather than a map because a shared backdrop has a handful of
1232    /// distinct filters at most, and `ImageFilter` holds a program's uniforms.
1233    filtered: Vec<(ImageFilter, usize)>,
1234}
1235
1236impl Canvas {
1237    /// Start recording for a target of the given size.
1238    pub fn new(extent: Extent2D) -> Self {
1239        let mut renderer = Renderer::new();
1240        renderer.begin_frame(extent, TOLERANCE);
1241        Self {
1242            renderer,
1243            batch: Batch::new(),
1244            transform: Transform2D::IDENTITY,
1245            clip: None,
1246            // The whole target to start with, which is what an unclipped
1247            // canvas may reach.
1248            clip_bounds: Rect::new(0.0, 0.0, extent.width as f32, extent.height as f32),
1249            depth: 0,
1250            clips: Vec::new(),
1251            stack: Vec::new(),
1252            sources: Vec::new(),
1253            finished: Vec::new(),
1254            extent,
1255            target: Target::frame(extent),
1256            background: None,
1257            anti_alias: false,
1258            seeded_by_redraw: false,
1259            keep_hidden_draws: false,
1260            samples: 4,
1261            ramps: Vec::new(),
1262            backdrops: std::collections::HashMap::new(),
1263        }
1264    }
1265
1266    /// Sample count to use when anything is antialiased.
1267    pub fn with_samples(mut self, samples: u32) -> Self {
1268        self.samples = samples.max(1);
1269        self
1270    }
1271
1272    pub fn extent(&self) -> Extent2D {
1273        self.extent
1274    }
1275
1276    /// Fill the whole target before drawing anything else.
1277    ///
1278    /// Required, not merely usual, if the frame itself draws an antialiased
1279    /// shape that is not analytic. Such a shape renders through a multisample
1280    /// buffer, and there is no way to seed that buffer with what the target
1281    /// already held -- so a multisampled pass has to clear, and a canvas with
1282    /// no background gives its root pass nothing to clear to. Drawing one is
1283    /// refused rather than quietly discarding whatever was on the surface.
1284    ///
1285    /// The frame itself, and not the picture: a sample count describes one
1286    /// pass. The same shape drawn inside a layer needs the layer's pass
1287    /// multisampled and leaves the frame alone, since what the frame does with
1288    /// a finished layer is draw one image quad. So a shadow, which is a layer
1289    /// underneath, needs no background at all.
1290    ///
1291    /// [`Paint::with_anti_alias`] is the other end of the choice.
1292    pub fn clear(&mut self, color: Color) -> &mut Self {
1293        self.background = Some(color);
1294        self
1295    }
1296
1297    /// Current transform, mapping user coordinates to device pixels.
1298    pub fn transform(&self) -> Transform2D {
1299        self.transform
1300    }
1301
1302    /// The region drawing is currently confined to, in device pixels.
1303    ///
1304    /// `None` is the whole target.
1305    pub fn clip(&self) -> Option<Scissor> {
1306        self.clip
1307    }
1308
1309    /// The region drawing may still reach, in device pixels.
1310    ///
1311    /// Conservative: it is a rectangle around the clip rather than the clip
1312    /// itself, so a path clip reports its bounding box and a rotated
1313    /// rectangle reports the axis-aligned box around it. That is what makes it
1314    /// useful for the thing it is for -- deciding not to draw something --
1315    /// since a caller may skip anything outside it and must not assume
1316    /// everything inside it is visible.
1317    pub fn destination_clip_bounds(&self) -> Rect {
1318        self.clip_bounds
1319    }
1320
1321    /// The same region in the coordinates the caller is currently drawing in.
1322    ///
1323    /// The device bounds carried back through the transform, which under a
1324    /// rotation gives the box around the rotated box and so grows a little
1325    /// each time. Conservative in the same direction as everything else here:
1326    /// too large is a missed optimization, too small is a missing shape.
1327    ///
1328    /// A transform that cannot be inverted has collapsed the plane, and
1329    /// nothing drawn through it reaches anything; the empty rectangle says so.
1330    pub fn local_clip_bounds(&self) -> Rect {
1331        let Some(inverse) = self.transform.inverse() else {
1332            return Rect::new(0.0, 0.0, 0.0, 0.0);
1333        };
1334        // Two different ways this can have no answer, and they take opposite
1335        // ones. A transform that has collapsed leaves nothing reachable, which
1336        // the check above answers with an empty rectangle. A transform whose
1337        // inverse carries the clip across the vanishing line leaves *more*
1338        // reachable than a box can say -- and since this rectangle is a promise
1339        // about what lies outside it, the safe failure there is everything.
1340        let (min, max) = transformed_bounds(
1341            inverse,
1342            Vec2::new(self.clip_bounds.left, self.clip_bounds.top),
1343            Vec2::new(self.clip_bounds.right, self.clip_bounds.bottom),
1344        )
1345        .unwrap_or_else(unbounded);
1346        Rect::new(min.x, min.y, max.x, max.y)
1347    }
1348
1349    /// Narrow the tracked bounds to a rectangle already in device space.
1350    fn narrow_bounds(&mut self, min: Vec2, max: Vec2) {
1351        let current = self.clip_bounds;
1352        self.clip_bounds = Rect::new(
1353            current.left.max(min.x),
1354            current.top.max(min.y),
1355            current.right.min(max.x),
1356            current.bottom.min(max.y),
1357        );
1358        // An intersection that crossed over is empty rather than inside out,
1359        // which every consumer of a rectangle here would otherwise have to
1360        // check for itself.
1361        if self.clip_bounds.right < self.clip_bounds.left
1362            || self.clip_bounds.bottom < self.clip_bounds.top
1363        {
1364            self.clip_bounds = Rect::new(
1365                self.clip_bounds.left,
1366                self.clip_bounds.top,
1367                self.clip_bounds.left,
1368                self.clip_bounds.top,
1369            );
1370        }
1371    }
1372
1373    /// Narrow the clip to a rectangle in user space.
1374    ///
1375    /// Intersects with the clip already in force rather than replacing it,
1376    /// which is what makes the clip stack compose: a subtree can only ever
1377    /// narrow what its parent allowed. The rectangle goes through the current
1378    /// transform, so it moves with the coordinate system the caller set up.
1379    ///
1380    /// # Rotation
1381    ///
1382    /// Returns [`Error::Unsupported`] when the current transform rotates or
1383    /// skews by anything other than a quarter turn, because the result is then
1384    /// a rotated quadrilateral and this clip is a rectangle. Refusing is the
1385    /// point: the tempting alternative is to use the rotated shape's bounding
1386    /// box, which admits pixels the caller asked to remove, and produces a
1387    /// picture that is wrong in a way that looks like a rendering bug rather
1388    /// than like a clip that was never applied. Arbitrary clip shapes need a
1389    /// stencil pass, which is a separate piece of machinery.
1390    pub fn clip_rect(&mut self, rect: Rect) -> Result<&mut Self> {
1391        // Under a transform that keeps rectangles rectangular, this is exactly
1392        // a scissor, which costs nothing and is exact. Under anything else the
1393        // result is a rotated quadrilateral, and taking its bounding box would
1394        // admit pixels the caller asked to remove -- so it goes through the
1395        // stencil like any other shape. That the fast path survives is the
1396        // point: a scissor stays the right answer for an axis-aligned clip even
1397        // now that the general one exists.
1398        if !preserves_axis_alignment(self.transform) {
1399            return self.clip_path(&rect.to_path());
1400        }
1401        let Some((min, max)) = transformed_bounds(
1402            self.transform,
1403            Vec2::new(rect.left, rect.top),
1404            Vec2::new(rect.right, rect.bottom),
1405        ) else {
1406            // Unreachable through the check above, which has already refused
1407            // anything but an affine -- and written as a fallback rather than
1408            // an assertion because the two are coupled only by argument, and
1409            // the stencil path is the right answer either way.
1410            return self.clip_path(&rect.to_path());
1411        };
1412        let narrowed = Scissor::from_device_bounds(
1413            (min - self.target.origin).into(),
1414            (max - self.target.origin).into(),
1415            self.target.extent,
1416        );
1417        self.clip = Some(match self.clip {
1418            Some(existing) => existing.intersect(narrowed),
1419            None => narrowed,
1420        });
1421        self.narrow_bounds(min, max);
1422        Ok(self)
1423    }
1424
1425    /// Narrow the clip to everything *outside* a rectangle in user space.
1426    ///
1427    /// `dart:ui` spells this `clipRect` with `ClipOp.difference`, and it is the
1428    /// only clip that operation applies to there -- `clipPath` and `clipRRect`
1429    /// intersect and take no operation.
1430    ///
1431    /// Never a scissor, whatever the transform: the complement of a rectangle
1432    /// is not one, and a scissor is. So this goes through the stencil like an
1433    /// arbitrary shape, and the shape it narrows by is the target with the
1434    /// rectangle taken out of it -- two contours filled by the even-odd rule,
1435    /// which is what makes the second a hole in the first rather than a second
1436    /// region drawn over it. `draw_drrect` builds a ring the same way.
1437    ///
1438    /// Both contours are built in device coordinates and filled through the
1439    /// identity, rather than in user space through the transform. The reason is
1440    /// the target: it is a device rectangle, and expressing it in user space
1441    /// would mean inverting a transform that may not be invertible. The
1442    /// rectangle's own corners go through the transform here instead, so a
1443    /// rotation gives the quadrilateral it should rather than a box around one.
1444    pub fn clip_out_rect(&mut self, rect: Rect) -> Result<&mut Self> {
1445        if self.clip.is_some_and(Scissor::is_empty) {
1446            return Ok(self);
1447        }
1448        let mut builder = PathBuilder::new().with_fill_rule(FillRule::EvenOdd);
1449        // The whole target, which is what "outside the rectangle" is measured
1450        // against.
1451        let target = Rect::new(
1452            self.target.origin.x,
1453            self.target.origin.y,
1454            self.target.origin.x + self.target.extent.width as f32,
1455            self.target.origin.y + self.target.extent.height as f32,
1456        );
1457        builder
1458            .move_to(Vec2::new(target.left, target.top))
1459            .line_to(Vec2::new(target.right, target.top))
1460            .line_to(Vec2::new(target.right, target.bottom))
1461            .line_to(Vec2::new(target.left, target.bottom))
1462            .close();
1463        // The rectangle's corners under the transform, in the order that keeps
1464        // the contour simple. A degenerate one encloses no area and takes
1465        // nothing out, which is the right answer for a clip that removes an
1466        // empty rectangle.
1467        let corners = [
1468            Vec2::new(rect.left, rect.top),
1469            Vec2::new(rect.right, rect.top),
1470            Vec2::new(rect.right, rect.bottom),
1471            Vec2::new(rect.left, rect.bottom),
1472        ]
1473        .map(|corner| self.transform.project_point2(corner));
1474        // A corner that is not a number describes no rectangle, so there is
1475        // nothing to take out and the clip is left as it was. Under a transform
1476        // carrying perspective this is also what catches a corner past the
1477        // vanishing line, where the divide reports an infinity rather than a
1478        // wrong finite answer -- and where the four corners would no longer
1479        // describe the region even if they were finite.
1480        if !corners.iter().all(|corner| corner.is_finite()) {
1481            return Ok(self);
1482        }
1483        builder.move_to(corners[0]);
1484        for corner in &corners[1..] {
1485            builder.line_to(*corner);
1486        }
1487        builder.close();
1488
1489        let paint = RenderPaint {
1490            material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1491            filter: ColorFilter::None,
1492            blend: BlendMode::Src,
1493            clip: self.clip,
1494            stencil: ClipState::narrow(self.depth),
1495        };
1496        let path = builder.build();
1497        self.renderer
1498            .fill_into(&mut self.batch, &path, Affine2::IDENTITY, &paint)?;
1499        self.depth += 1;
1500        self.clips.push(StencilClip {
1501            path,
1502            transform: Transform2D::IDENTITY,
1503            scissor: paint.clip,
1504        });
1505        // The tracked bounds are left alone, and that is not an oversight.
1506        // Removing a rectangle from the middle of a region leaves its bounding
1507        // box exactly where it was, and removing one from the edge leaves a box
1508        // that is too large -- which is the safe direction, since these bounds
1509        // decide how much a caller draws and how large a layer is allocated.
1510        Ok(self)
1511    }
1512
1513    /// Narrow the clip to an arbitrary path in user space.
1514    ///
1515    /// Intersects with the clip already in force, like [`Self::clip_rect`], and
1516    /// like it the path travels through the current transform. The shape is
1517    /// recorded into the batch as a draw that writes only the stencil, so it
1518    /// costs one draw where a rectangular clip costs none.
1519    ///
1520    /// The path is filled by the same tessellator that fills a drawn shape, so
1521    /// it obeys the same fill rule and produces the same edges. That matters
1522    /// for more than consistency: the tessellation is a set of non-overlapping
1523    /// triangles, which is what lets the stencil step forward by one rather
1524    /// than needing the parity trick an overlapping fan would.
1525    pub fn clip_path(&mut self, path: &Path) -> Result<&mut Self> {
1526        if self.clip.is_some_and(Scissor::is_empty) {
1527            // Already clipped to nothing; narrowing further changes nothing and
1528            // the draw would be dropped anyway.
1529            return Ok(self);
1530        }
1531        let paint = RenderPaint {
1532            // Masked off entirely by a clip draw, but a material is still
1533            // needed to build one. White says plainly that nothing here is a
1534            // color decision.
1535            material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1536            filter: ColorFilter::None,
1537            blend: BlendMode::Src,
1538            clip: self.clip,
1539            stencil: ClipState::narrow(self.depth),
1540        };
1541        self.renderer
1542            .fill_into(&mut self.batch, path, self.transform, &paint)?;
1543        self.depth += 1;
1544        self.clips.push(StencilClip {
1545            path: path.clone(),
1546            transform: self.transform,
1547            scissor: paint.clip,
1548        });
1549        // A path clip narrows what may be drawn without touching the scissor,
1550        // so the tracked rectangle is the only place it is accounted for. Its
1551        // bounding box rather than the path: this rectangle is a promise about
1552        // what is *outside* it, and a box around a shape keeps that promise.
1553        let bounds = path.bounds();
1554        // A clip whose bounds cannot be computed narrows nothing here. The
1555        // stencil still confines it exactly; what is lost is only the tracked
1556        // rectangle used to skip work, and leaving it wide is the direction
1557        // that costs time rather than pixels.
1558        if let Some((min, max)) = transformed_bounds(self.transform, bounds.min, bounds.max) {
1559            self.narrow_bounds(min, max);
1560        }
1561        Ok(self)
1562    }
1563
1564    /// Save the transform and clip so a later `restore` can return to them.
1565    pub fn save(&mut self) -> &mut Self {
1566        self.stack.push(SavedState {
1567            transform: self.transform,
1568            clip: self.clip,
1569            clip_bounds: self.clip_bounds,
1570            depth: self.depth,
1571            clips: self.clips.len(),
1572            layer: None,
1573        });
1574        self
1575    }
1576
1577    /// Begin drawing into a layer of its own, composited back on `restore`.
1578    ///
1579    /// Everything recorded until the matching restore goes into a separate
1580    /// target and arrives as one image, which is what makes an alpha here apply
1581    /// to the group rather than to each shape in it.
1582    ///
1583    /// The layer starts unclipped and at the identity for clipping purposes,
1584    /// while keeping the current transform. It does not need to inherit the
1585    /// clip because the draw that composites it is subject to it: content the
1586    /// clip excludes is discarded once rather than prevented from being drawn,
1587    /// which costs some work in the layer and keeps a stencil clip from having
1588    /// to be rebuilt in a second target.
1589    pub fn save_layer(&mut self, layer: Layer) -> &mut Self {
1590        // A layer that captures a backdrop is handed to the bounded path with
1591        // no bounds, which narrows it to the clip in force. That path scales
1592        // the layer itself, so this one hands it over unscaled.
1593        //
1594        // A shared key goes that way too. What the key shares is the capture
1595        // and the filtered image over it, both of which stay the parent's size
1596        // because they have to serve every group naming it; the layer's own
1597        // target is bound by the clip like any other.
1598        if layer.backdrop_blur > 0.0 && layer.matrix.is_none() {
1599            let (min, max) = unbounded();
1600            // Cannot fail: only a backdrop *filter* can refuse, and this
1601            // passes none -- the blur rides on the layer.
1602            let _ = self.save_layer_device_bounds_running(layer, min, max, None, None);
1603            return self;
1604        }
1605        // The other entry to `open_layer` converts the sigmas where it computes
1606        // its reach; this one has no bounds to reach past and so converts them
1607        // here. Both are the same conversion at the same moment -- the layer is
1608        // opened under the transform the caller drew in, which is the one its
1609        // sigma is stated against.
1610        let layer = layer.scaled_by(max_scale_of(self.transform), axis_scales_of(self.transform));
1611        let widened = self.matrix_preimage(&layer);
1612        let pending = self.open_layer(layer, None, None, None).unwrap_or(None);
1613        if let Some(target) = widened {
1614            self.aim_at(target);
1615        }
1616        self.seed_backdrop(pending);
1617        self
1618    }
1619
1620    /// The region a layer must record over when a matrix will move its result.
1621    ///
1622    /// A layer's target is the parent's, and a draw outside it is scissored
1623    /// away -- which is right for every layer except one whose matrix brings
1624    /// content in from outside. `dart:ui`'s matrix image filter is exactly
1625    /// that, and upstream's `MatrixImageFilterDoesntCullWhenTranslatedFromOffscreen`
1626    /// draws a circle three hundred points to the left of the frame and
1627    /// translates it back.
1628    ///
1629    /// What has to be recorded over is the *pre-image*: the region that, once
1630    /// the matrix has moved it, lands where the parent can see it. Union with
1631    /// the parent, because a matrix that moves some content in leaves the rest
1632    /// where it was.
1633    ///
1634    /// **Opening wide costs no memory, and that is what makes this safe.** The
1635    /// pass's extent comes from the narrowed target in `finish_layer`, which is
1636    /// the content's own bounds -- so a minifying matrix, whose inverse is a
1637    /// magnifying one, widens the region a draw may land in without allocating
1638    /// for a region no draw reached. What is allocated stays bounded by what
1639    /// the caller drew.
1640    fn matrix_preimage(&self, layer: &Layer) -> Option<Target> {
1641        let matrix = layer.matrix?;
1642        let parent = self.target;
1643        let (min, max) = (
1644            parent.origin,
1645            parent.origin + Vec2::new(parent.extent.width as f32, parent.extent.height as f32),
1646        );
1647        let (back_min, back_max) = transformed_bounds(matrix.inverse()?, min, max)?;
1648        let left = min.x.min(back_min.x).floor();
1649        let top = min.y.min(back_min.y).floor();
1650        let right = max.x.max(back_max.x).ceil();
1651        let bottom = max.y.max(back_max.y).ceil();
1652        // A matrix that folds the plane or carries the region across the
1653        // vanishing line has no region to report, and one that widens past what
1654        // an extent can hold is not a picture anybody asked for.
1655        //
1656        // The second half of that sentence was not implemented, and `as u32`
1657        // **saturates**: a finite width of `3.4e38` passed the finiteness test
1658        // and came out of the cast as `u32::MAX`. A layer whose extent is four
1659        // billion texels then clamps a morphology radius to four billion and
1660        // emits one pass per thirty-two texels of it -- a hundred and
1661        // thirty-four million passes, which is a recording measured in
1662        // gigabytes. Found by `hostile_api`, whose case is in that test's
1663        // regressions file; it reached the gate as the OOM killer rather than
1664        // as a failure.
1665        let (width, height) = (right - left, bottom - top);
1666        let holdable = |side: f32| side.is_finite() && side > 0.0 && side <= MAX_TARGET_SIDE;
1667        if !(holdable(width) && holdable(height)) {
1668            return None;
1669        }
1670        Some(Target {
1671            origin: Vec2::new(left, top),
1672            extent: Extent2D::new(width as u32, height as u32),
1673        })
1674    }
1675
1676    /// Push the layer frame, and cut the backdrop out if one was asked for.
1677    ///
1678    /// Returns what the layer's target must be seeded with once its size is
1679    /// settled, which is why this is separate from the seeding: a bounded layer
1680    /// does not know its own target until after the frame exists, and the seed
1681    /// has to land in the target the content will draw into.
1682    fn open_layer(
1683        &mut self,
1684        layer: Layer,
1685        filter: Option<ImageFilter>,
1686        backdrop: Option<&ImageFilter>,
1687        region: Option<Target>,
1688    ) -> Result<Option<Backdrop>> {
1689        let parent = self.target;
1690        // Where the backdrop's filter writes, which is the target the layer is
1691        // about to take rather than the parent it is captured from. `None` is
1692        // the caller that has not worked one out yet, and gets the parent.
1693        let region = region.unwrap_or(parent);
1694        // The layer's own sigma is the `Copy`-friendly spelling of the same
1695        // thing, so it becomes a filter here and there is one path below.
1696        //
1697        // And this is where it is converted into device pixels, because this is
1698        // the first place with two components to convert it into. `Layer::scaled_by`
1699        // leaves it alone for that reason: the caller stated one number, meaning a
1700        // blur round in their space, and under a transform whose axes scale
1701        // differently that is an oval. A filter handed over by the caller is
1702        // already converted -- `save_layer_filtered` and the backdrop entry points
1703        // run it through `ImageFilter::scaled_by` -- so only this arm converts.
1704        let axes = axis_scales_of(self.transform);
1705        let asked = match backdrop {
1706            Some(filter) => filter.clone(),
1707            None if layer.backdrop_blur > 0.0 => ImageFilter::Blur {
1708                sigma_x: layer.backdrop_blur * axes.x,
1709                sigma_y: layer.backdrop_blur * axes.y,
1710            },
1711            None => ImageFilter::None,
1712        };
1713        let filtered = if asked.is_identity() {
1714            None
1715        } else {
1716            // The frame is pushed whether or not this succeeds: a layer that
1717            // fails to filter its backdrop still has to be a layer, or the
1718            // `restore` the caller has already written closes something else.
1719            match self.backdrop_pass(layer.backdrop_id, parent, region, &asked) {
1720                Ok(pending) => Some(pending),
1721                Err(e) => {
1722                    self.push_layer_frame(layer, filter);
1723                    return Err(e);
1724                }
1725            }
1726        };
1727        self.push_layer_frame(layer, filter);
1728        Ok(filtered)
1729    }
1730
1731    /// The pass a backdrop-filtered layer starts from, and what it is an image
1732    /// of.
1733    ///
1734    /// Without an id this is the whole of what a backdrop filter was: cut the
1735    /// target's content out into a pass, and filter that. With one, both halves
1736    /// are shared with whatever named the id before -- the capture always, so
1737    /// that the second layer filters what was behind the first rather than the
1738    /// first's own result, and the filtered pass as well when the filter
1739    /// matches one already run over that capture.
1740    ///
1741    /// The second element is the target the pass covers, which is `parent` for
1742    /// a fresh capture and whatever the id captured for a shared one. Seeding
1743    /// needs it to place the image, and the two can differ; see
1744    /// [`BackdropShare::captured_from`].
1745    ///
1746    /// The cut happens before the filter can refuse, which is the order the
1747    /// no-id path always had. A refusal therefore leaves the capture recorded,
1748    /// which is right: the backdrop was captured, and the next layer naming the
1749    /// id should filter that same image whether or not this one could.
1750    fn backdrop_pass(
1751        &mut self,
1752        id: Option<i64>,
1753        parent: Target,
1754        region: Target,
1755        filter: &ImageFilter,
1756    ) -> Result<Backdrop> {
1757        // A matrix is peeled off here rather than run as a pass. Every other
1758        // filter reads its input where the fragment is and writes there, so it
1759        // is a pass over a target the size of what it was handed; a matrix
1760        // moves the image instead, and a pass for it would need a target sized
1761        // for where the content went. It does not need one: what a backdrop is
1762        // seeded into is the layer's own target, already allocated and the same
1763        // size whatever the matrix says, and the seed is a draw with a mapping
1764        // -- so the matrix goes into that mapping and no pass is spent.
1765        //
1766        // Only at the top. Inside a composition the matrix is between two
1767        // filters that do run as passes, so its result is what the outer one
1768        // reads and there is no seed to fold it into; that stays refused, in
1769        // `filter_passes`.
1770        let (filter, moved_by) = match filter {
1771            ImageFilter::Matrix { transform } => {
1772                let Some(affine) = transform.to_affine() else {
1773                    return Err(Error::Unsupported(
1774                        "a projective matrix is not available as a backdrop filter; \
1775                         it maps the image through a division this seed does not do",
1776                    ));
1777                };
1778                if affine.matrix2.determinant() == 0.0 {
1779                    return Err(Error::Unsupported(
1780                        "a singular matrix is not available as a backdrop filter; \
1781                         it collapses the image and nothing says what it read",
1782                    ));
1783                }
1784                (&ImageFilter::None, Some(affine))
1785            }
1786            other => (other, None),
1787        };
1788        let Some(id) = id else {
1789            // The capture is the pass being cut, so it is the parent's size
1790            // whatever happens next. What the filter *writes* need not be: its
1791            // passes read the whole capture and only have to cover the region
1792            // the layer will hold, which is where the seed reads from.
1793            let cut = self.cut_pass();
1794            let pass = self.filter_passes(cut, region, filter, BlurBasis::of(self.transform))?;
1795            return Ok(Backdrop {
1796                pass,
1797                // Unless the filter had nothing to do -- a matrix backdrop
1798                // moves the capture rather than recomputing it, and hands the
1799                // cut straight back, which is the parent's region and not this
1800                // one.
1801                of: if pass == cut { parent } else { region },
1802                moved_by,
1803            });
1804        };
1805
1806        // Read out by value first: what follows needs `&mut self`, and the
1807        // three things wanted from the entry are all `Copy`.
1808        let existing = self.backdrops.get(&id).map(|share| {
1809            let already = share
1810                .filtered
1811                .iter()
1812                .find(|(known, _)| known == filter)
1813                .map(|(_, pass)| *pass);
1814            (share.captured_from, share.captured, already)
1815        });
1816
1817        let (over, captured) = match existing {
1818            // A filter is a function of its input, so the same filter over the
1819            // same capture is the same image and there is nothing to compute.
1820            Some((from, _, Some(pass))) => {
1821                return Ok(Backdrop {
1822                    pass,
1823                    of: from,
1824                    moved_by,
1825                })
1826            }
1827            Some((from, captured, None)) => (from, captured),
1828            None => {
1829                let cut = self.cut_pass();
1830                self.backdrops.insert(
1831                    id,
1832                    BackdropShare {
1833                        captured_from: parent,
1834                        captured: cut,
1835                        filtered: Vec::new(),
1836                    },
1837                );
1838                (parent, cut)
1839            }
1840        };
1841
1842        let pass = self.filter_passes(captured, over, filter, BlurBasis::of(self.transform))?;
1843        if let Some(share) = self.backdrops.get_mut(&id) {
1844            share.filtered.push((filter.clone(), pass));
1845        }
1846        Ok(Backdrop {
1847            pass,
1848            of: over,
1849            moved_by,
1850        })
1851    }
1852
1853    /// End the current target's pass here, and answer which pass now holds it.
1854    ///
1855    /// The architecture's rule is that a pass cannot sample the attachment it
1856    /// is writing, which is exactly what a backdrop filter asks for. So the
1857    /// pass stops: everything drawn into this target so far becomes a pass of
1858    /// its own, and what follows begins by drawing that pass back in.
1859    ///
1860    /// The redraw is the cost, one full-target copy per backdrop filter, and it
1861    /// is not avoidable without the machinery the rule exists for the absence
1862    /// of. It is a `Src` blit covering the whole target, so it reproduces what
1863    /// was cut exactly rather than compositing with it.
1864    fn cut_pass(&mut self) -> usize {
1865        let target = self.target;
1866        let mut batch = std::mem::take(&mut self.batch);
1867        let sources = std::mem::take(&mut self.sources);
1868        // The clear belongs to the half that starts from nothing. A layer's
1869        // target clears to transparent and the frame's to its background; after
1870        // the cut neither clears again, since the redraw below covers every
1871        // pixel with `Src`.
1872        let clear = if self.in_layer() {
1873            Some([0.0; 4])
1874        } else {
1875            self.background
1876                .take()
1877                .map(|c| c.to_array())
1878                .or_else(|| self.seeded_by_redraw.then_some([0.0; 4]))
1879        };
1880        // Stop each draw writing pixels a later opaque draw replaces. Pixel-identical
1881        // and order-preserving -- see `Batch::cull_occluded`, which has the argument --
1882        // and done here rather than in the backends because it is a property of the
1883        // finished pass rather than of either API.
1884        if !self.keep_hidden_draws {
1885            batch.cull_occluded(target.extent);
1886        }
1887        self.finished.push(Pass {
1888            batch,
1889            descriptor: PassDescriptor {
1890                clear,
1891                samples: self.pass_samples(),
1892                viewport: None,
1893            },
1894            sources,
1895            extent: target.extent,
1896        });
1897        // The batch that continues is empty, so it inherits nothing: what
1898        // follows the cut is a full-target `Src` blit, which no sample count
1899        // changes, plus whatever is drawn next. A draw that wants
1900        // multisampling will say so again.
1901        self.anti_alias = false;
1902        let index = self.finished.len() - 1;
1903        self.draw_whole_pass(index, target, target, BlendMode::Src, None);
1904        self.seeded_by_redraw = true;
1905        self.rebuild_stencil_clips();
1906        index
1907    }
1908
1909    /// Make the stencil clips again, in the batch that follows a cut.
1910    ///
1911    /// A stencil clip is a draw and a pass owns its stencil attachment, so
1912    /// cutting the pass throws the clip state away: the redraw restores the
1913    /// color and nothing restores the stencil, leaving every content draw after
1914    /// the cut testing for a depth no pixel holds. Which is to say it draws
1915    /// nothing, silently and everywhere.
1916    ///
1917    /// The narrowings are made again in the order they were made the first
1918    /// time, at the depths they were made at -- which they still are, since
1919    /// `clips` holds exactly those in force and each was made at its own index.
1920    /// A failure to build one is dropped rather than propagated: the shape
1921    /// tessellated once already to get here, and there is no result to fail
1922    /// into halfway through a cut.
1923    fn rebuild_stencil_clips(&mut self) {
1924        for depth in 0..self.clips.len() {
1925            let clip = self.clips[depth].clone();
1926            let paint = RenderPaint {
1927                material: Material::solid([1.0, 1.0, 1.0, 1.0]),
1928                filter: ColorFilter::None,
1929                blend: BlendMode::Src,
1930                clip: clip.scissor,
1931                stencil: ClipState::narrow(depth as u32),
1932            };
1933            let _ = self
1934                .renderer
1935                .fill_into(&mut self.batch, &clip.path, clip.transform, &paint);
1936        }
1937    }
1938
1939    /// Whether a layer is open, which decides what a cut pass clears to.
1940    fn in_layer(&self) -> bool {
1941        self.stack.iter().any(|state| state.layer.is_some())
1942    }
1943
1944    /// Draw a finished pass, sized for `source`, across the whole of `into`.
1945    ///
1946    /// `into` is a rectangle of `source`: the same target when a pass is being
1947    /// redrawn after a cut, and a sub-rectangle of it when a bounded layer is
1948    /// seeded with a backdrop. The mapping is the inverse of the one a layer
1949    /// composite uses, and reduces to the full-texture mapping when the two are
1950    /// the same size, which is what makes the unbounded case share this code.
1951    fn draw_whole_pass(
1952        &mut self,
1953        pass: usize,
1954        source: Target,
1955        into: Target,
1956        blend: BlendMode,
1957        moved_by: Option<Affine2>,
1958    ) {
1959        let slot = self.slot_for(TextureSource::Layer(pass));
1960        let offset = into.origin - source.origin;
1961        let (iw, ih) = (into.extent.width as f32, into.extent.height as f32);
1962        let (sw, sh) = (source.extent.width as f32, source.extent.height as f32);
1963        // Stated in the direction the shader reads it -- clip space to the
1964        // texture -- because the sizes are known and there is no placement to
1965        // invert. The anchor rides inside it like every other paint's.
1966        let anchor = Vec2::new(-1.0 - 2.0 * offset.x / iw, 1.0 + 2.0 * offset.y / ih);
1967        let scale = Mat2::from_diagonal(Vec2::new(0.5 * iw / sw, -0.5 * ih / sh));
1968        let clip_to_texture = Affine2::from_mat2(scale) * Affine2::from_translation(-anchor);
1969        // A matrix moves the image, so the fragment at a device point reads
1970        // where that point came *from*: the mapping gains the inverse, stated
1971        // in device pixels, between the texture coordinates and the device
1972        // position they name. `texels` is that position from a normalized
1973        // coordinate and `normalized` is its inverse, so with no matrix the
1974        // three cancel and this is the mapping above unchanged.
1975        let clip_to_texture = match moved_by {
1976            None => clip_to_texture,
1977            Some(matrix) => {
1978                let texels = Affine2::from_translation(source.origin)
1979                    * Affine2::from_scale(Vec2::new(sw, sh));
1980                let normalized = texels.inverse();
1981                normalized * matrix.inverse() * texels * clip_to_texture
1982            }
1983        };
1984        let material = Material::Image {
1985            to_local: to_local_columns(Transform2D::from(clip_to_texture)),
1986            slot,
1987            alpha: 1.0,
1988            // Clamped when the image stays where it was, which is every case
1989            // but one: the mapping then covers exactly the texture and there is
1990            // nothing outside it to decide about. A matrix leaves parts of the
1991            // target naming no texel, and those have to come out transparent so
1992            // what is underneath shows -- smearing the edge across them is what
1993            // a clamp would do and is not what a filter that moved an image
1994            // says about where the image is not.
1995            tile: [if moved_by.is_some() {
1996                TileMode::Decal
1997            } else {
1998                TileMode::Clamp
1999            }; 2],
2000            // A layer is composited at its own size, so a texel lands on a
2001            // pixel and the filter has nothing to blend. Linear anyway, which
2002            // is what a target scaled by a resize would want.
2003            sampling: Sampling::Linear,
2004            source: [0.0, 0.0, 1.0, 1.0],
2005            tint: [1.0, 1.0, 1.0, 1.0],
2006        };
2007        let paint = RenderPaint {
2008            material,
2009            filter: ColorFilter::None,
2010            blend,
2011            // Neither clipped nor stencilled: this is the target's own content
2012            // being restored or seeded, not something the caller drew, and a
2013            // clip in force belongs to what comes after it.
2014            clip: None,
2015            stencil: ClipState::UNCLIPPED,
2016        };
2017        let whole = into.path();
2018        let _ = self
2019            .renderer
2020            .fill_into(&mut self.batch, &whole, Affine2::IDENTITY, &paint);
2021    }
2022
2023    /// Put the filtered backdrop under the layer's own content.
2024    ///
2025    /// `Src`, because it is the layer's starting image rather than something
2026    /// composited onto it, and the layer's target was cleared to transparent.
2027    fn seed_backdrop(&mut self, pending: Option<Backdrop>) {
2028        let Some(Backdrop {
2029            pass,
2030            of: parent,
2031            moved_by,
2032        }) = pending
2033        else {
2034            return;
2035        };
2036        let into = self.target;
2037        self.draw_whole_pass(pass, parent, into, BlendMode::Src, moved_by);
2038    }
2039
2040    fn push_layer_frame(&mut self, layer: Layer, filter: Option<ImageFilter>) {
2041        self.stack.push(SavedState {
2042            transform: self.transform,
2043            clip: self.clip,
2044            clip_bounds: self.clip_bounds,
2045            depth: self.depth,
2046            clips: self.clips.len(),
2047            layer: Some(LayerFrame {
2048                batch: std::mem::take(&mut self.batch),
2049                sources: std::mem::take(&mut self.sources),
2050                clips: std::mem::take(&mut self.clips),
2051                paint: layer,
2052                filter,
2053                parent: self.target,
2054                anti_alias: std::mem::take(&mut self.anti_alias),
2055                seeded_by_redraw: std::mem::take(&mut self.seeded_by_redraw),
2056                blur_basis: BlurBasis::of(self.transform),
2057            }),
2058        });
2059        self.clip = None;
2060        self.depth = 0;
2061    }
2062
2063    /// Open a layer that only needs to cover `bounds`.
2064    ///
2065    /// `bounds` is in the current user space, and is the caller's promise that
2066    /// nothing drawn in the layer matters outside it. The layer gets a target
2067    /// the size of that region rather than the size of the frame, which is the
2068    /// whole reason to state it: a layer over a tenth of the frame then costs a
2069    /// tenth of the memory and a tenth of the fill, and a frame that opens
2070    /// several stops being dominated by full-frame allocations it does not use.
2071    ///
2072    /// The promise is enforced by construction rather than trusted. Content
2073    /// outside the region is clipped away by the target's own edges, so a
2074    /// caller who understates the bounds sees the drawing cut off — visible and
2075    /// attributable, rather than reading stale memory.
2076    ///
2077    /// The region is taken to device pixels and rounded outward to whole ones,
2078    /// so a fractional bound never costs coverage at the edge, and is narrowed
2079    /// to what the enclosing target can show, since a layer larger than that
2080    /// renders pixels nothing can sample. A region that comes out empty falls
2081    /// back to a full-size layer, that being a case where a smaller target
2082    /// would be a guess and guessing wrong loses drawing.
2083    ///
2084    /// A layer that filters its backdrop is the exception to all of this: for
2085    /// it the bounds are not an optimization but the region filtered, so
2086    /// omitting them filters the whole target rather than merely allocating
2087    /// more of one. See [`Layer::backdrop_blur`].
2088    ///
2089    /// Under a rotation the region becomes a quadrilateral, and the target is
2090    /// the box around it. That covers more than the caller promised, which is
2091    /// the safe direction: a target is an allocation rather than a clip the
2092    /// caller can observe, so over-covering costs a little memory where
2093    /// under-covering would lose drawing. This is the opposite of what
2094    /// [`Self::clip_rect`] does with the same box, and for the same reason —
2095    /// there the box would admit pixels the caller asked to remove.
2096    pub fn save_layer_bounds(&mut self, layer: Layer, bounds: Rect) -> &mut Self {
2097        let (min, max) = transformed_bounds(
2098            self.transform,
2099            Vec2::new(bounds.left, bounds.top),
2100            Vec2::new(bounds.right, bounds.bottom),
2101        )
2102        .unwrap_or_else(unbounded);
2103        self.save_layer_device_bounds(layer, min, max)
2104    }
2105
2106    /// A layer filtered as a whole by any image filter.
2107    ///
2108    /// [`Layer`]'s own fields carry the four kinds that fit in a `Copy` struct
2109    /// -- a blur, a morphology, a matrix and a color filter -- and apply them
2110    /// in one fixed order. This takes an [`ImageFilter`], which adds the two
2111    /// they cannot say: a caller's fragment program, and a composition in
2112    /// whichever order the caller wrote it.
2113    ///
2114    /// The same operation `dart:ui` spells as an `imageFilter` on the paint
2115    /// handed to `saveLayer`, and the group counterpart of what
2116    /// `Paint::with_image_filter` already does for one draw.
2117    ///
2118    /// Refuses a matrix, which is a redirection rather than an absence: a
2119    /// group's finished image is moved by `Layer::with_matrix`, which states
2120    /// the same thing and is what `peel` turns this filter into everywhere
2121    /// else. Refused here rather than at `restore`, because a `restore` has no
2122    /// result to fail into and by then the caller has drawn into the layer.
2123    ///
2124    /// A *backdrop's* matrix is not refused; see `backdrop_pass`. The two are
2125    /// different questions -- a group's own image is composited by machinery
2126    /// that already takes a matrix, and a backdrop's is seeded by a draw that
2127    /// now does.
2128    pub fn save_layer_filtered(
2129        &mut self,
2130        layer: Layer,
2131        bounds: Option<Rect>,
2132        filter: &ImageFilter,
2133    ) -> Result<&mut Self> {
2134        if matches!(filter, ImageFilter::Matrix { .. }) {
2135            return Err(Error::Unsupported(
2136                "a matrix filters a group through `Layer::with_matrix`, which \
2137                 states where the finished image goes",
2138            ));
2139        }
2140        // Refused here for the reason the depth is a constant at all: everything
2141        // that reads a composition walks it recursively, and a composition deep
2142        // enough took the process down rather than returning an error. See
2143        // `ImageFilter::MAX_NESTING`.
2144        if filter.nests_deeper_than(ImageFilter::MAX_NESTING) {
2145            return Err(Error::Unsupported(
2146                "this image filter composes more filters than can be walked",
2147            ));
2148        }
2149        let (min, max) = match bounds {
2150            Some(bounds) => transformed_bounds(
2151                self.transform,
2152                Vec2::new(bounds.left, bounds.top),
2153                Vec2::new(bounds.right, bounds.bottom),
2154            )
2155            .unwrap_or_else(unbounded),
2156            None => unbounded(),
2157        };
2158        self.save_layer_device_bounds_running(layer, min, max, Some(filter.clone()), None)
2159    }
2160
2161    /// A layer over a backdrop filtered by any image filter.
2162    ///
2163    /// [`Layer::backdrop_blur`] is the same operation with the one filter a
2164    /// `Copy` layer can hold, and is the spelling to reach for when a blur is
2165    /// what is wanted. This takes the rest: a color filter, a morphology, a
2166    /// caller's fragment program, or a composition of them -- which is what
2167    /// `SceneBuilder.pushBackdropFilter` accepts and what upstream's
2168    /// `SaveLayer` takes a `DlImageFilter` for.
2169    ///
2170    /// The bounds are the filtered region rather than an optimization, for the
2171    /// reason [`Layer::backdrop_blur`] gives: a frosted panel is a bounded
2172    /// layer, and the same layer unbounded filters the whole frame. Both are
2173    /// meaningful and they are different pictures.
2174    ///
2175    /// Refuses a matrix, which is the one kind that moves the image rather than
2176    /// recomputing it in place. See `filter_passes`.
2177    pub fn save_layer_backdrop(
2178        &mut self,
2179        layer: Layer,
2180        bounds: Option<Rect>,
2181        backdrop: &ImageFilter,
2182    ) -> Result<&mut Self> {
2183        // The same refusal `save_layer_filtered` makes, and for the same reason:
2184        // a backdrop's filter is read by the same recursive walks.
2185        if backdrop.nests_deeper_than(ImageFilter::MAX_NESTING) {
2186            return Err(Error::Unsupported(
2187                "this image filter composes more filters than can be walked",
2188            ));
2189        }
2190        let (min, max) = match bounds {
2191            Some(bounds) => transformed_bounds(
2192                self.transform,
2193                Vec2::new(bounds.left, bounds.top),
2194                Vec2::new(bounds.right, bounds.bottom),
2195            )
2196            .unwrap_or_else(unbounded),
2197            None => unbounded(),
2198        };
2199        self.save_layer_device_bounds_running(layer, min, max, None, Some(backdrop))
2200    }
2201
2202    /// A bounded layer whose region is already in device pixels.
2203    ///
2204    /// The same thing [`Self::save_layer_bounds`] does, minus the transform.
2205    /// Every filter's reach is a length in device pixels, so a caller that has
2206    /// already worked out where a filtered result will land -- which composing
2207    /// two filters requires, since the inner one's growth has to fit inside the
2208    /// outer one's target -- has device coordinates in hand and would only be
2209    /// mapping them backward to have them mapped forward again. Under a scale
2210    /// the round trip is not the identity: a reach of eight device pixels
2211    /// divided by the scale and multiplied by it again is eight only if nothing
2212    /// rounds, and the bounds are floored and ceiled at the end.
2213    fn save_layer_device_bounds(&mut self, layer: Layer, min: Vec2, max: Vec2) -> &mut Self {
2214        // Cannot fail: only a backdrop filter can refuse, and this passes none.
2215        let _ = self.save_layer_device_bounds_running(layer, min, max, None, None);
2216        self
2217    }
2218
2219    /// The same, with a caller's program to run over the finished layer.
2220    ///
2221    /// Separate rather than a defaulted argument because every caller but the
2222    /// three filtered draws passes `None`, and a parameter that is almost
2223    /// always one value reads as though it were sometimes the other.
2224    fn save_layer_device_bounds_running(
2225        &mut self,
2226        layer: Layer,
2227        min: Vec2,
2228        max: Vec2,
2229        filter: Option<ImageFilter>,
2230        backdrop: Option<&ImageFilter>,
2231    ) -> Result<&mut Self> {
2232        // A caller's sigma is in the space they were drawing in, which is what
2233        // `dart:ui` means by it and what upstream honors -- its
2234        // `GaussianBlurFilterContents` scales by `effect_transform.Basis()`,
2235        // and the backdrop path hands it `transform.Basis()`. Everything below
2236        // this line works in device pixels: the reach is applied to bounds
2237        // already transformed, and the passes that do the blurring run on a
2238        // target. So the conversion happens once, here, where the transform
2239        // that decides it is still the one the caller drew under.
2240        let basis = BlurBasis::of(self.transform);
2241        let scale = max_scale_of(self.transform);
2242        let axes = axis_scales_of(self.transform);
2243        let layer = layer.scaled_by(scale, axes);
2244        // And the filters beside it, which this line did not touch for as long as
2245        // it has existed. The comment above said the conversion happens once here
2246        // and it happened to the layer only, so `save_layer_filtered` with a blur
2247        // took a device sigma while the same filter through
2248        // `Paint::with_image_filter` -- which becomes a layer -- took a local one.
2249        let filter = filter.map(|filter| filter.scaled_by(scale, axes));
2250        let backdrop = backdrop
2251            .cloned()
2252            .map(|filter| filter.scaled_by(scale, axes));
2253        let backdrop = backdrop.as_ref();
2254        let reach = layer.reach(basis);
2255        // A layer opened under a clip cannot draw outside it, and neither can
2256        // the draw that composites it, so an unbounded one does not need a
2257        // target the size of its parent. A frosted panel is the case that
2258        // pays: the clip is the panel and the parent is the frame, and the
2259        // capture, the blur's passes and the intermediate were all frame-sized
2260        // for a panel a fortieth of the area.
2261        //
2262        // Only where a backdrop is being captured, and only for a layer that
2263        // shares no key and has no matrix. Each of those wants a region this
2264        // does not know how to compute: a shared capture has to cover every
2265        // group naming the id -- which is upstream's coverage union and is not
2266        // this -- a matrix records its pre-image, which is where the content
2267        // will come *from* rather than where the clip is, and a destructive
2268        // group naming the id -- which is upstream's coverage union and is not
2269        // this -- and a matrix records its pre-image, which is where the
2270        // content will come *from* rather than where the clip is.
2271        //
2272        // A destructive mode is not excluded, and the difference from
2273        // `narrowed` is the whole of why. That one shrinks to the layer's
2274        // *content*, which such a mode reaches past -- it writes where the
2275        // source drew nothing. This shrinks to the clip, which is the region
2276        // the composite can touch at all, so there is nothing outside it left
2277        // to affect.
2278        let captures_backdrop = backdrop.is_some() || layer.backdrop_blur > 0.0;
2279        let (min, max) = if captures_backdrop && layer.matrix.is_none() {
2280            let clip = self.clip_bounds;
2281            (
2282                Vec2::new(min.x.max(clip.left), min.y.max(clip.top)),
2283                Vec2::new(max.x.min(clip.right), max.y.min(clip.bottom)),
2284            )
2285        } else {
2286            (min, max)
2287        };
2288        // A filter given to the layer as a whole reaches past what it is handed
2289        // too, and by how much only the filter knows. Asked here rather than
2290        // left to the narrowing below, because the narrowing only runs for a
2291        // layer that was *not* given bounds: a caller who states bounds gets
2292        // the target those bounds describe, and a filter's spread has to be
2293        // added to it or the spread is cut off at the bound.
2294        //
2295        // Missing this made the two spellings of a layer blur disagree. A sigma
2296        // on the layer went through `reach` above and spread ten pixels past a
2297        // stated bound; the same blur handed over as the layer's filter stopped
2298        // dead at it. They are the same picture and the same comment two
2299        // functions up says so.
2300        let filter_reach = filter.as_ref().map(|filter| {
2301            let unit = Vec2::ZERO;
2302            let (min, max) = filter.covering(unit, unit, &|sigma| basis.reach(sigma));
2303            (-min).max(max)
2304        });
2305        // A blur reaches past what it was given. The caller states where the
2306        // content is, which is the question they can answer; how far a blur
2307        // carries it is this renderer's arithmetic, and a target sized to the
2308        // content alone would cut the halo off square at the bound -- the
2309        // failure looking exactly like a shadow with a straight edge.
2310        //
2311        // The kernel's own radius, `ceil((sigma - 0.5) * sqrt(3))`, which is
2312        // where the shader stops taking taps -- so the target covers every
2313        // texel the blur will actually read and no more. Nearer one and three
2314        // quarter deviations than three: the truncation is upstream's
2315        // `kKernelRadiusPerSigma`, and `blur_reach` is the one place it is
2316        // stated.
2317        let (min, max) = (min - reach, max + reach);
2318        // After the layer's own blur and morphology, because that is the order
2319        // `finish_layer` applies them in: the filter sees what those produced.
2320        let (min, max) = match filter_reach {
2321            Some(spread) => (min - spread, max + spread),
2322            None => (min, max),
2323        };
2324        let parent = self.target;
2325        let left = min.x.floor().max(parent.origin.x);
2326        let top = min.y.floor().max(parent.origin.y);
2327        let right = max
2328            .x
2329            .ceil()
2330            .min(parent.origin.x + parent.extent.width as f32);
2331        let bottom = max
2332            .y
2333            .ceil()
2334            .min(parent.origin.y + parent.extent.height as f32);
2335        // Worked out before the layer is opened, because opening it is what
2336        // builds the backdrop's passes and those want to know where they are
2337        // writing. The layer is still opened without *seeding*: the seed has to
2338        // land in the target the content will draw into, so it waits until that
2339        // target is the one aimed at.
2340        let narrowed = (right > left && bottom > top).then(|| Target {
2341            origin: Vec2::new(left, top),
2342            extent: Extent2D::new((right - left) as u32, (bottom - top) as u32),
2343        });
2344        let pending = self.open_layer(layer, filter, backdrop, narrowed)?;
2345        let Some(target) = narrowed else {
2346            // Nothing survived the clamp, so the layer keeps the full-size
2347            // target it was opened with and the backdrop is seeded across that.
2348            self.seed_backdrop(pending);
2349            return Ok(self);
2350        };
2351        self.aim_at(target);
2352        self.seed_backdrop(pending);
2353        Ok(self)
2354    }
2355
2356    /// How many layers are open, for a caller checking its own balance.
2357    pub fn layer_depth(&self) -> usize {
2358        self.stack.iter().filter(|s| s.layer.is_some()).count()
2359    }
2360
2361    /// The slot a source occupies in the pass being recorded, adding it if new.
2362    ///
2363    /// Slots are per pass rather than global, because each pass carries its own
2364    /// table. Deduplicating means a recording that draws the same image twenty
2365    /// times binds one texture rather than twenty.
2366    /// The slot holding this gradient's colors, when they cannot be carried.
2367    ///
2368    /// `None` for the ordinary case, which keeps the stops in push constants
2369    /// and costs no texture, no upload and no binding. Only a gradient with
2370    /// more stops than a material can hold pays for a ramp, and it pays once
2371    /// per distinct gradient rather than once per draw.
2372    fn ramp_for(&mut self, stops: &[GradientStop]) -> Option<u32> {
2373        (stops.len() > MAX_STOPS).then(|| self.ramp_slot(stops))
2374    }
2375
2376    /// Tabulate a gradient's colors and return the slot holding them.
2377    ///
2378    /// Called only where the stops outnumber what a material can carry. The
2379    /// ramp is deduplicated across the recording by its contents, because the
2380    /// same gradient drawn twice is one texture, and a frame that paints a
2381    /// hundred list rows with one theme gradient should upload it once.
2382    fn ramp_slot(&mut self, stops: &[GradientStop]) -> u32 {
2383        let ramp = Ramp::bake(stops);
2384        let index = match self.ramps.iter().position(|r| *r == ramp) {
2385            Some(index) => index,
2386            None => {
2387                self.ramps.push(ramp);
2388                self.ramps.len() - 1
2389            }
2390        };
2391        self.slot_for(TextureSource::Ramp(index))
2392    }
2393
2394    fn slot_for(&mut self, source: TextureSource) -> u32 {
2395        if let Some(index) = self.sources.iter().position(|s| *s == source) {
2396            return index as u32;
2397        }
2398        self.sources.push(source);
2399        (self.sources.len() - 1) as u32
2400    }
2401
2402    /// Return to the most recently saved transform and clip.
2403    ///
2404    /// Restoring without a matching save leaves both alone rather than
2405    /// panicking: an unbalanced pair is a caller bug, but taking down a frame
2406    /// loop for it is worse than continuing with what is already correct.
2407    pub fn restore(&mut self) -> &mut Self {
2408        let Some(previous) = self.stack.pop() else {
2409            return self;
2410        };
2411        self.transform = previous.transform;
2412        self.clip = previous.clip;
2413        self.clip_bounds = previous.clip_bounds;
2414
2415        if let Some(frame) = previous.layer {
2416            // The clip and stencil are restored before the composite is
2417            // recorded, so the layer arrives subject to what was in force when
2418            // it was opened rather than to whatever it did inside itself.
2419            self.depth = previous.depth;
2420            self.clips = frame.clips.clone();
2421            self.finish_layer(frame);
2422            return self;
2423        }
2424
2425        // Everything this save added to the list goes with it. The widening
2426        // draws below undo the same clips on the device; this is the record of
2427        // them a later pass cut would rebuild from.
2428        self.clips.truncate(previous.clips);
2429
2430        // A scissor is state the recorder holds, so restoring it is an
2431        // assignment. A stencil clip lives in a buffer on the device, so
2432        // restoring it is a draw: one covering the whole target per level being
2433        // left, each stepping back the pixels that reached that level.
2434        //
2435        // Deliberately unscissored. The step back lands exactly where the
2436        // matching narrowing landed, because that is where the stencil holds
2437        // the value being tested for -- so it needs no help from a scissor, and
2438        // asking it to agree with one that has already been restored to
2439        // something else would be a way to get it wrong.
2440        if self.depth > previous.depth {
2441            // Stated in device pixels, so it goes through the identity rather
2442            // than whatever transform happens to be in force.
2443            let whole = self.target.path();
2444            while self.depth > previous.depth {
2445                let paint = RenderPaint {
2446                    material: Material::solid([1.0, 1.0, 1.0, 1.0]),
2447                    filter: ColorFilter::None,
2448                    blend: BlendMode::Src,
2449                    clip: None,
2450                    stencil: ClipState::widen(self.depth),
2451                };
2452                let _ = self
2453                    .renderer
2454                    .fill_into(&mut self.batch, &whole, Affine2::IDENTITY, &paint);
2455                self.depth -= 1;
2456            }
2457        }
2458        self
2459    }
2460
2461    /// How many saves are outstanding, for a caller checking its own balance.
2462    pub fn save_depth(&self) -> usize {
2463        self.stack.len()
2464    }
2465
2466    pub fn translate(&mut self, x: f32, y: f32) -> &mut Self {
2467        self.concat(Affine2::from_translation(Vec2::new(x, y)))
2468    }
2469
2470    pub fn scale(&mut self, x: f32, y: f32) -> &mut Self {
2471        self.concat(Affine2::from_scale(Vec2::new(x, y)))
2472    }
2473
2474    /// Rotate by an angle in radians.
2475    pub fn rotate(&mut self, radians: f32) -> &mut Self {
2476        self.concat(Affine2::from_angle(radians))
2477    }
2478
2479    /// Apply an arbitrary transform on top of the current one.
2480    ///
2481    /// Takes anything that is a transform of the plane, which is an `Affine2`
2482    /// for almost every caller and a [`Transform2D`] for one that wants
2483    /// perspective. Widened rather than replaced: nobody should have to build a
2484    /// three-by-three to move something ten pixels to the right.
2485    pub fn concat(&mut self, transform: impl Into<Transform2D>) -> &mut Self {
2486        self.transform = self.transform * transform.into();
2487        self
2488    }
2489
2490    /// Apply a `dart:ui` four-by-four, which is column-major and sixteen long.
2491    ///
2492    /// The entry point for perspective, and the one `dart:ui` states: its
2493    /// `Canvas.transform` takes a matrix of this shape. Named apart from
2494    /// [`Self::transform`], which reports the current one and cannot share a
2495    /// name with a method that changes it.
2496    ///
2497    /// The reduction to a three-by-three is exact rather than a narrowing.
2498    /// Everything drawn here lies on the plane where `z` is zero, and a
2499    /// four-by-four applied to such a point never reads its `z` column; the `z`
2500    /// row yields a depth with nothing to do here. What is left -- rows and
2501    /// columns zero, one and three -- is the whole of what the matrix means on
2502    /// the plane. A caller whose matrix depends on `z` is getting the part of
2503    /// it that acts on what they are drawing, which is all of it.
2504    pub fn concat_4x4(&mut self, matrix: &[f32; 16]) -> &mut Self {
2505        self.concat(Transform2D::from_column_major_4x4(matrix))
2506    }
2507
2508    pub fn draw_path(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
2509        if !paint.is_visible() || path.is_empty() {
2510            return Ok(self);
2511        }
2512        // Before the mask blur, so the two compose in the order they are
2513        // defined in: an image filter acts on what was drawn, and what was
2514        // drawn is whatever the mask blur produced.
2515        if !paint.image_filter.is_identity() {
2516            return self.draw_filtered(path, paint);
2517        }
2518        // A rounded rectangle that still knows it is one can have its mask blur
2519        // evaluated rather than run as passes. This is where a shadow arrives:
2520        // `draw_shadow` takes a path, as `dart:ui`'s `drawShadow` does, so
2521        // without the shape traveling with the outline every shadow would take
2522        // the general route however round it is.
2523        if let Some((bounds, radius)) = path.as_rounded_rect() {
2524            let rect = Rect::new(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y);
2525            if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(rect, radius, paint)
2526            {
2527                return self.draw_analytic(rect.outset(pad), material, &drawn);
2528            }
2529        }
2530        // A color filter is normally arithmetic in this renderer's own fragment
2531        // shader, which a runtime effect replaces outright -- there is nowhere
2532        // in a caller's program to put the matrix, and the program is what runs.
2533        // Left alone, the filter was accepted and silently did nothing, which
2534        // is the shape of failure this codebase least wants: no error, no
2535        // effect, and a caller with no way to tell.
2536        //
2537        // So the filter is applied to the image the program drew instead, which
2538        // is what it means anyway. It costs a layer, which is what every other
2539        // filter that acts on a finished image already costs.
2540        if matches!(paint.shader, Shader::RuntimeEffect { .. }) && !paint.color_filter.is_identity()
2541        {
2542            return self.draw_effect_filtered(path, paint);
2543        }
2544        if paint.mask_blur > 0.0 {
2545            if let Some(drawn) = self.shadow_mesh_blur(path, paint) {
2546                return drawn.map(|()| self);
2547            }
2548            return self.draw_masked(Masked::Path(path), paint);
2549        }
2550        if paint.anti_alias {
2551            self.anti_alias = true;
2552        }
2553
2554        // A clip narrowed to nothing means this shape cannot reach any pixel.
2555        // Tessellating it to find that out is wasted work, and it is a normal
2556        // state rather than an error: a subtree scrolled out of view is clipped
2557        // away every frame it stays there.
2558        if self.clip.is_some_and(Scissor::is_empty) {
2559            return Ok(self);
2560        }
2561
2562        // Upstream tries its vertex-interpolated gradient first, and so does
2563        // this: `LinearGradientContents::Render` calls `CanApplyFastGradient`
2564        // before reaching the uniform walk. Here rather than in `draw_rect`
2565        // because everything above has to run first -- a mask blur or a
2566        // runtime-effect filter takes its own route, and the first attempt at
2567        // this path intercepted earlier and drew a masked shape sharp and
2568        // unmasked. §19 of `docs/non-parity.md` records that.
2569        //
2570        // The shape has to be a rectangle recorded as one, which `draw_rect`
2571        // and a zero-radius `draw_rrect` do and an arbitrary path with four
2572        // corners does not: the predicate needs the rectangle's edges, and a
2573        // path that happens to trace them has not said they are edges.
2574        if matches!(paint.style, Style::Fill) {
2575            if let Some((rect, 0.0)) = path.as_rounded_rect() {
2576                let rect = Rect::new(rect.min.x, rect.min.y, rect.max.x, rect.max.y);
2577                // Only where the gradient is in the rectangle's own space:
2578                // the sections run along the rectangle's edges.
2579                let sections = (paint.shader_transform == Transform2D::IDENTITY)
2580                    .then(|| fast_gradient_sections(rect, &paint.effective_shader()))
2581                    .flatten();
2582                if let Some(sections) = sections {
2583                    return self.draw_gradient_sections(&sections, paint);
2584                }
2585            }
2586        }
2587
2588        // Resolved before the clip is read, since it may add a slot to this
2589        // pass's table.
2590        let material = self.material_for(paint);
2591        // A stroke too thin to cover a pixel is widened to one and dimmed to
2592        // pay for it. See `thin_stroke`; this is the tessellated route, where
2593        // the quantization it exists for is at its worst -- coverage comes
2594        // from a multisample buffer, so a sub-pixel line has four coverages
2595        // available to it and one of them is none.
2596        let (style, coverage) = match &paint.style {
2597            Style::Stroke(stroke) => {
2598                let (width, coverage) =
2599                    thin_stroke(self.transform, stroke.width, Zero::IsAHairline);
2600                (Style::Stroke(stroke.with_width(width)), coverage)
2601            }
2602            other => (*other, 1.0),
2603        };
2604        let render_paint = RenderPaint {
2605            material: material.with_opacity(coverage),
2606            filter: paint.color_filter,
2607            blend: paint.blend,
2608            clip: self.clip,
2609            stencil: ClipState::content(self.depth),
2610        };
2611        match &style {
2612            Style::Fill => {
2613                self.renderer
2614                    .fill_into(&mut self.batch, path, self.transform, &render_paint)?
2615            }
2616            Style::Stroke(stroke) => self.renderer.stroke_into(
2617                &mut self.batch,
2618                path,
2619                stroke,
2620                paint.dash.as_ref(),
2621                self.transform,
2622                &render_paint,
2623            )?,
2624        }
2625        Ok(self)
2626    }
2627
2628    /// Draw a gradient as one quad per pair of stops, letting the rasterizer
2629    /// interpolate between them.
2630    ///
2631    /// The material shades opaque white and the vertex colors carry the result
2632    /// under `Modulate`, which is the identity against white -- the arrangement
2633    /// `draw_vertices` already uses for a caller's mesh. What `VertexGradient`
2634    /// adds over `Solid` is that it dithers, which is the whole of why it is a
2635    /// material of its own: a long run of nearly equal values bands on an
2636    /// eight-bit target whichever stage produced it.
2637    ///
2638    /// One push per section rather than one for all of them, so each quad's six
2639    /// indices address its own four vertices -- which is also what lets
2640    /// `BatchDraw::covered` recognize a section, and what makes the batch's own
2641    /// merging decide whether they coalesce.
2642    fn draw_gradient_sections(
2643        &mut self,
2644        sections: &[GradientSection],
2645        paint: &Paint,
2646    ) -> Result<&mut Self> {
2647        let to_clip = self.target.projection() * self.transform;
2648        for section in sections {
2649            let vertices: Vec<Vertex> = section
2650                .corners
2651                .iter()
2652                .zip(&section.colors)
2653                .map(|(position, color)| {
2654                    let clip = to_clip.project_homogeneous(*position);
2655                    Vertex::projected([clip.x, clip.y, clip.z], [0.0, 0.0]).with_color(*color)
2656                })
2657                .collect();
2658            self.batch.push_mesh_tinted(
2659                &vertices,
2660                // Two triangles sharing the diagonal from corner zero to corner
2661                // two, which is the winding `fan_fill` emits for a quad and what
2662                // `BatchDraw::covered` matches against.
2663                &[0, 1, 2, 0, 2, 3],
2664                Material::VertexGradient,
2665                paint.color_filter,
2666                paint.blend,
2667                self.clip,
2668                ClipState::content(self.depth),
2669                paint.tint_blend,
2670                // The section colors carry the paint's opacity already.
2671                1.0,
2672                // The color comes from the vertices, not from a coordinate, so
2673                // there is nothing for the material to read a position for.
2674                false,
2675            )?;
2676        }
2677        Ok(self)
2678    }
2679
2680    /// Resolve a paint's shader against the current transform.
2681    ///
2682    /// Gradient endpoints go through the same mapping the geometry does, so a
2683    /// gradient rotates and scales with its shape rather than staying fixed to
2684    /// the screen. Doing it here rather than in the fragment stage means the
2685    /// shader receives clip-space endpoints and needs no transform of its own.
2686    ///
2687    /// The paint's [`Paint::shader_transform`] comes first, from the shader's
2688    /// space into the canvas's, so it is folded into the same one mapping and
2689    /// costs the fragment stage nothing.
2690    fn material_for(&mut self, paint: &Paint) -> Material {
2691        let to_clip = self.target.projection() * self.transform * paint.shader_transform;
2692        self.material_from(&paint.effective_shader(), to_clip)
2693    }
2694
2695    /// The same, for a draw whose fragments locate themselves some other way.
2696    ///
2697    /// A mesh that states a coordinate per vertex has already put each one in
2698    /// the caller's own space, so the mapping the fragment stage applies must
2699    /// not carry the geometry's transform as well -- it would be applied twice,
2700    /// once by the vertices and once by the mapping. Passing the identity here
2701    /// leaves exactly the paint's own part: the translation that measures from
2702    /// a gradient's start, the rotation that orients a sweep, and nothing else.
2703    ///
2704    /// The shader then runs the same arithmetic on `(uv, 1)` that it runs on a
2705    /// clip position, which is why there is one path in it rather than two.
2706    ///
2707    /// The shader's own transform stays: the coordinates are in the space
2708    /// the paint is used in, and it carries the shader's space into that.
2709    fn material_at_texture_coords(&mut self, paint: &Paint) -> Material {
2710        self.material_from(&paint.effective_shader(), paint.shader_transform)
2711    }
2712
2713    fn material_from(&mut self, shader: &Shader, to_clip: Transform2D) -> Material {
2714        let stops_of = |stops: &[crate::paint::GradientStop]| -> Vec<Stop> {
2715            stops
2716                .iter()
2717                .map(|s| Stop::new(s.color.to_array(), s.offset))
2718                .collect()
2719        };
2720
2721        match shader {
2722            Shader::Solid(color) => Material::solid(color.to_array()),
2723            // Passed through untouched. Every other material here is resolved
2724            // -- geometry carried into clip space, a radius folded into a
2725            // matrix -- because this renderer's own shader expects it that
2726            // way. A caller's program expects whatever the caller wrote, and
2727            // there is nothing here that could resolve it correctly.
2728            Shader::RuntimeEffect {
2729                program,
2730                uniforms,
2731                images,
2732            } => Material::Runtime {
2733                program: *program,
2734                uniforms: uniforms.clone(),
2735                // Through this pass's own table, like every other texture: a
2736                // layer occupies a slot too, so a caller's index and the
2737                // pass's are not the same number once one is opened.
2738                textures: {
2739                    let mut bound = [None; emblema_hal::MAX_EFFECT_TEXTURES];
2740                    // Past the ceiling the extra names are dropped rather than
2741                    // refused: a program cannot declare a binding the layout
2742                    // does not have, so a caller naming more textures than that
2743                    // has named some the program could not read either.
2744                    for (slot, into) in images.iter().zip(bound.iter_mut()) {
2745                        *into = Some(self.slot_for(TextureSource::Image(*slot)));
2746                    }
2747                    bound
2748                },
2749            },
2750            Shader::Image {
2751                slot,
2752                rect,
2753                alpha,
2754                tile,
2755                source,
2756                tint,
2757                sampling,
2758            } => {
2759                // Texture coordinates run from zero to one across the
2760                // destination rectangle, so the mapping is: undo the transform
2761                // that took user space to clip space, then scale by the
2762                // rectangle's own size. Composing the two here means the shader
2763                // receives one matrix and does no inversion of its own.
2764                //
2765                // Built forwards and inverted once: the unit square of texture
2766                // coordinates is scaled by the rectangle's size, placed at its
2767                // corner, and carried to clip space by the transform in force.
2768                // A degenerate transform has no inverse to take, and the
2769                // identity stands in for it -- unobservable, because the
2770                // geometry went through the same matrix and has no area.
2771                let placement = to_clip
2772                    * Affine2::from_translation(Vec2::new(rect.left, rect.top))
2773                    * Affine2::from_scale(Vec2::new(
2774                        rect.right - rect.left,
2775                        rect.bottom - rect.top,
2776                    ));
2777                Material::Image {
2778                    to_local: invert_to_local(placement),
2779                    sampling: *sampling,
2780                    // The caller's index goes through this pass's own table,
2781                    // because a layer occupies a slot too and the two number
2782                    // independently. A recording that never uses a layer maps
2783                    // them one to one, which is why this is invisible until it
2784                    // is not.
2785                    slot: self.slot_for(TextureSource::Image(*slot)),
2786                    alpha: *alpha,
2787                    source: [source.left, source.top, source.right, source.bottom],
2788                    tint: tint.to_array(),
2789                    tile: *tile,
2790                }
2791            }
2792            Shader::LinearGradient {
2793                start,
2794                end,
2795                stops,
2796                tile,
2797            } => {
2798                let axis = *end - *start;
2799                if !axis.is_finite() || !start.is_finite() {
2800                    return Material::Solid([0.0; 4]);
2801                }
2802                let ramp_slot = self.ramp_for(stops);
2803                Material::LinearGradient {
2804                    axis: [axis.x, axis.y],
2805                    // Maps a clip-space position back into the space the axis is
2806                    // stated in, which is the caller's, measured from the
2807                    // gradient's start. Without it the target's aspect ratio
2808                    // leaks into the gradient's direction.
2809                    to_local: invert_to_local(to_clip * Affine2::from_translation(*start)),
2810                    stops: stops_of(stops),
2811                    tile: *tile,
2812                    ramp: ramp_slot,
2813                }
2814            }
2815            Shader::RadialGradient {
2816                center,
2817                radius,
2818                stops,
2819                tile,
2820            } => {
2821                // Folding the center and the radius into the mapping means the
2822                // shader measures against unit distance from the origin and
2823                // never sees either.
2824                let placement = to_clip
2825                    * Affine2::from_translation(*center)
2826                    * Affine2::from_scale(Vec2::splat(*radius));
2827                if !placement.is_finite() {
2828                    return Material::Solid([0.0; 4]);
2829                }
2830                // A radius of nothing folds to a singular mapping, and the
2831                // inversion below answers a singular matrix with the identity.
2832                // That is the right answer for an inversion and the wrong one
2833                // here: it invents a radius of one clip unit, so a gradient the
2834                // caller asked to have no extent comes out spanning half the
2835                // target and changing with the target's size.
2836                //
2837                // What it should be is the limit of the real thing. As the
2838                // radius shrinks, every point but the center runs off the end
2839                // of the ramp -- so under clamp it settles on the last stop,
2840                // and under decal it leaves, because past the end is where
2841                // decal draws nothing. Repeat and mirror have no limit at all,
2842                // the parameter oscillating faster and faster, and they take
2843                // the same answer as clamp because a stable color is worth
2844                // more than an arbitrary one that shimmers.
2845                //
2846                // The limit rather than a refusal, on the same reasoning that
2847                // makes a mask blur of zero the sharp shape: a caller animating
2848                // a radius down to nothing should arrive somewhere, not have
2849                // the gradient disappear at the last frame.
2850                if !radius.is_finite() || *radius <= 0.0 {
2851                    if matches!(tile, TileMode::Decal) {
2852                        return Material::Solid([0.0; 4]);
2853                    }
2854                    let last = stops
2855                        .iter()
2856                        .max_by(|a, b| a.offset.total_cmp(&b.offset))
2857                        .map(|s| s.color.to_array())
2858                        .unwrap_or([0.0; 4]);
2859                    return Material::solid(last);
2860                }
2861                let ramp_slot = self.ramp_for(stops);
2862                Material::RadialGradient {
2863                    to_local: invert_to_local(placement),
2864                    stops: stops_of(stops),
2865                    tile: *tile,
2866                    ramp: ramp_slot,
2867                }
2868            }
2869            Shader::ConicalGradient {
2870                start_center,
2871                start_radius,
2872                end_center,
2873                end_radius,
2874                stops,
2875                tile,
2876            } => {
2877                let axis = *end_center - *start_center;
2878                // The shader is told where the second center is with one float
2879                // instead of two, which is only possible if it already knows
2880                // the direction. Rotating the gradient's space so the axis
2881                // runs along +X is how it comes to know it, and the rotation
2882                // costs nothing: it folds into a matrix that has to be built
2883                // and inverted regardless.
2884                //
2885                // A zero axis leaves the angle undefined and the rotation
2886                // arbitrary, which is correct rather than merely harmless --
2887                // two concentric circles have no direction to preserve, and
2888                // every rotation is the right one.
2889                let angle = if axis == Vec2::ZERO {
2890                    0.0
2891                } else {
2892                    axis.y.atan2(axis.x)
2893                };
2894                let oriented =
2895                    to_clip * Affine2::from_translation(*start_center) * Affine2::from_angle(angle);
2896                if !oriented.is_finite() || !start_radius.is_finite() || !end_radius.is_finite() {
2897                    return Material::Solid([0.0; 4]);
2898                }
2899                let ramp_slot = self.ramp_for(stops);
2900                Material::ConicalGradient {
2901                    to_local: invert_to_local(oriented),
2902                    // In the gradient's own space, which this rotation and the
2903                    // canvas transform's inverse together make into user space
2904                    // -- so both radii are the ones the caller stated, and
2905                    // neither is folded into the matrix the way a radial
2906                    // gradient's single radius is. A scale can normalize one
2907                    // radius; it cannot normalize two.
2908                    start_radius: *start_radius,
2909                    radius_delta: *end_radius - *start_radius,
2910                    separation: axis.length(),
2911                    stops: stops_of(stops),
2912                    tile: *tile,
2913                    ramp: ramp_slot,
2914                }
2915            }
2916            Shader::SweepGradient {
2917                center,
2918                start_angle,
2919                end_angle,
2920                stops,
2921                tile,
2922            } => {
2923                let placement = to_clip * Affine2::from_translation(*center);
2924                if !placement.is_finite() || !start_angle.is_finite() || !end_angle.is_finite() {
2925                    return Material::Solid([0.0; 4]);
2926                }
2927                let ramp_slot = self.ramp_for(stops);
2928                Material::SweepGradient {
2929                    to_local: invert_to_local(placement),
2930                    start_angle: *start_angle,
2931                    end_angle: *end_angle,
2932                    stops: stops_of(stops),
2933                    tile: *tile,
2934                    ramp: ramp_slot,
2935                }
2936            }
2937        }
2938    }
2939
2940    /// Draw a shape through a blurred layer, which is what a mask blur is.
2941    ///
2942    /// Blurring coverage and then filling equals filling and then blurring
2943    /// exactly when the fill is constant, since a blur is linear. That identity
2944    /// is the whole implementation: a bounded layer, blurred, with the shape
2945    /// drawn into it. It also means the machinery is one already tested rather
2946    /// than a second blur written beside the first.
2947    ///
2948    /// The bounds are the shape's, widened by how far the blur reaches. A
2949    /// caller doing this by hand has to know that reach, which is exactly the
2950    /// part that is easy to get wrong and shows as a shadow with a straight
2951    /// edge where it was cut off.
2952    /// Draw into a layer, filter it, and composite it back.
2953    ///
2954    /// The same machinery a mask blur uses, without the restriction: a mask
2955    /// blur is only the same picture as this when the fill does not vary, and
2956    /// so takes a solid color, while filtering a result is defined whatever
2957    /// produced it. What is paid for that is a target of its own.
2958    /// The layer that applies one filter, where that filter is a leaf.
2959    ///
2960    /// `None` for the two that are not: `is_identity` keeps `None` out, and
2961    /// `peel` recurses through a composition's outer half until it reaches
2962    /// something that is not one -- so neither can arrive here. They were
2963    /// reachable when peeling took that half to be a leaf, and composing two
2964    /// compositions was then refused as unimplemented, having been assembled
2965    /// out of nothing but implemented filters.
2966    fn filter_layer(&self, filter: &ImageFilter) -> Option<(Layer, Option<ImageFilter>)> {
2967        if let ImageFilter::Runtime { program, uniforms } = filter {
2968            // The layer itself is plain: what makes it a filter is the pass run
2969            // over it at restore, which needs the program and cannot get it
2970            // from a `Copy` layer.
2971            return Some((
2972                Layer::opacity(1.0),
2973                Some(ImageFilter::Runtime {
2974                    program: *program,
2975                    uniforms: uniforms.clone(),
2976                }),
2977            ));
2978        }
2979        Some((
2980            match *filter {
2981                ImageFilter::Blur { sigma_x, sigma_y } => {
2982                    Layer::opacity(1.0).with_blur_xy(sigma_x, sigma_y)
2983                }
2984                ImageFilter::Matrix { transform } => Layer::opacity(1.0).with_matrix(transform),
2985                ImageFilter::Dilate { radius_x, radius_y } => {
2986                    Layer::opacity(1.0).with_morphology(Morphology::dilate(radius_x, radius_y))
2987                }
2988                ImageFilter::Erode { radius_x, radius_y } => {
2989                    Layer::opacity(1.0).with_morphology(Morphology::erode(radius_x, radius_y))
2990                }
2991                ImageFilter::Color(filter) => Layer::opacity(1.0).with_color_filter(filter),
2992                ImageFilter::Runtime { .. } => unreachable!("handled above"),
2993                ImageFilter::None | ImageFilter::Compose { .. } => return None,
2994            },
2995            None,
2996        ))
2997    }
2998
2999    /// A glyph run drawn into a layer, and the layer filtered.
3000    ///
3001    /// The third of these, after the shape and the mesh, and the same shape as
3002    /// both. The bounds come from the run's own boxes, since a run has neither
3003    /// a path nor vertices to take them from.
3004    fn draw_glyphs_filtered(
3005        &mut self,
3006        glyphs: &[PositionedGlyph],
3007        atlas: &Atlas,
3008        atlas_slot: u32,
3009        paint: &Paint,
3010    ) -> Result<&mut Self> {
3011        if paint
3012            .image_filter
3013            .nests_deeper_than(ImageFilter::MAX_NESTING)
3014        {
3015            return Err(Error::Unsupported(
3016                "this image filter composes more filters than can be walked",
3017            ));
3018        }
3019        let (outermost, rest) = paint.image_filter.peel();
3020        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3021            return Err(Error::Unsupported("this image filter is not implemented"));
3022        };
3023        let (mut min, mut max) = (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3024        for glyph in glyphs {
3025            let corner = Vec2::from(glyph.position);
3026            min = min.min(corner);
3027            max = max.max(corner + Vec2::from(glyph.size));
3028        }
3029        if !min.is_finite() || !max.is_finite() {
3030            return Err(Error::Unsupported(
3031                "a glyph in this run is not at a finite position",
3032            ));
3033        }
3034        let (min, max) = transformed_bounds(self.transform, min, max).unwrap_or_else(unbounded);
3035        let basis = BlurBasis::of(self.transform);
3036        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3037        let _ = self.save_layer_device_bounds_running(
3038            layer.with_blend(paint.blend),
3039            min,
3040            max,
3041            runtime,
3042            None,
3043        );
3044        let inner = paint
3045            .clone()
3046            .with_image_filter(rest)
3047            .with_blend(BlendMode::SrcOver);
3048        let failure = self.draw_glyphs(glyphs, atlas, atlas_slot, &inner).err();
3049        self.restore();
3050        match failure {
3051            Some(e) => Err(e),
3052            None => Ok(self),
3053        }
3054    }
3055
3056    /// A mesh drawn into a layer, and the layer filtered.
3057    ///
3058    /// The path version's twin, and separate rather than shared because the two
3059    /// differ in the only two places that matter -- where the bounds come from,
3060    /// and which draw call the remainder of the chain is handed back to. The
3061    /// peeling, the region arithmetic and the blend placement are the same and
3062    /// are described there.
3063    fn draw_vertices_filtered(&mut self, mesh: &Vertices, paint: &Paint) -> Result<&mut Self> {
3064        if paint
3065            .image_filter
3066            .nests_deeper_than(ImageFilter::MAX_NESTING)
3067        {
3068            return Err(Error::Unsupported(
3069                "this image filter composes more filters than can be walked",
3070            ));
3071        }
3072        let (outermost, rest) = paint.image_filter.peel();
3073        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3074            return Err(Error::Unsupported("this image filter is not implemented"));
3075        };
3076        // From the vertices themselves. A mesh has no path to take bounds from,
3077        // and the positions are in the same coordinates a path's points would
3078        // be, so the transform below is the one that applies to either.
3079        let positions = mesh.positions();
3080        let (mut min, mut max) = (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3081        for point in positions {
3082            min = min.min(*point);
3083            max = max.max(*point);
3084        }
3085        if !min.is_finite() || !max.is_finite() {
3086            return Err(Error::Unsupported("a mesh position is not a finite number"));
3087        }
3088        let (min, max) = transformed_bounds(self.transform, min, max).unwrap_or_else(unbounded);
3089        let basis = BlurBasis::of(self.transform);
3090        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3091        let _ = self.save_layer_device_bounds_running(
3092            layer.with_blend(paint.blend),
3093            min,
3094            max,
3095            runtime,
3096            None,
3097        );
3098        let inner = paint
3099            .clone()
3100            .with_image_filter(rest)
3101            .with_blend(BlendMode::SrcOver);
3102        let failure = self.draw_vertices(mesh, &inner).err();
3103        self.restore();
3104        match failure {
3105            Some(e) => Err(e),
3106            None => Ok(self),
3107        }
3108    }
3109
3110    /// A caller's program drawn into a layer, and the layer recolored.
3111    ///
3112    /// The bounds are the path's own, widened by a stroke where there is one.
3113    /// Nothing here reaches past that: a color filter moves colors rather than
3114    /// pixels, so the region it can affect is the region that was drawn.
3115    fn draw_effect_filtered(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
3116        let bounds = self.filter_bounds(path, paint);
3117        let (min, max) = transformed_bounds(
3118            self.transform,
3119            Vec2::new(bounds.left, bounds.top),
3120            Vec2::new(bounds.right, bounds.bottom),
3121        )
3122        .unwrap_or_else(unbounded);
3123        self.save_layer_device_bounds(
3124            Layer::opacity(1.0)
3125                .with_color_filter(paint.color_filter)
3126                // The blend belongs to the composite, not to the draw inside.
3127                // That is what `saveLayer` means by taking a paint, and it is
3128                // the only placement that gives the right answer for a blend
3129                // reading its destination: inside the layer the destination is
3130                // transparent black, so a mode like `Multiply` applied there
3131                // would come out empty and then be composited over the frame it
3132                // was supposed to darken.
3133                .with_blend(paint.blend),
3134            min,
3135            max,
3136        );
3137        // Without the filter, or this would open a layer inside itself forever,
3138        // and over an empty layer rather than through the caller's blend, which
3139        // the composite above now carries.
3140        let inner = paint
3141            .clone()
3142            .with_color_filter(ColorFilter::None)
3143            .with_blend(BlendMode::SrcOver);
3144        let failure = self.draw_path(path, &inner).err();
3145        self.restore();
3146        match failure {
3147            Some(e) => Err(e),
3148            None => Ok(self),
3149        }
3150    }
3151
3152    fn draw_filtered(&mut self, path: &Path, paint: &Paint) -> Result<&mut Self> {
3153        // One filter is peeled off here and the rest is handed back to
3154        // `draw_path`, which lands in this method again if anything is left.
3155        // A chain of filters is a stack of layers, and this builds the stack
3156        // one frame at a time rather than all at once -- which keeps the
3157        // single-filter case exactly what it was, with the remainder `None`.
3158        if paint
3159            .image_filter
3160            .nests_deeper_than(ImageFilter::MAX_NESTING)
3161        {
3162            return Err(Error::Unsupported(
3163                "this image filter composes more filters than can be walked",
3164            ));
3165        }
3166        let (outermost, rest) = paint.image_filter.peel();
3167        let Some((layer, runtime)) = self.filter_layer(&outermost) else {
3168            return Err(Error::Unsupported("this image filter is not implemented"));
3169        };
3170        let bounds = self.filter_bounds(path, paint);
3171        // In device pixels, because that is where a filter's reach is measured.
3172        // The outer layer has to cover everything the rest of the chain needs,
3173        // both what goes into it and what comes out -- a layer's target is
3174        // clipped to its parent's, so a target sized for the result alone would
3175        // crop the content before the inner filter ever ran.
3176        let (min, max) = transformed_bounds(
3177            self.transform,
3178            Vec2::new(bounds.left, bounds.top),
3179            Vec2::new(bounds.right, bounds.bottom),
3180        )
3181        .unwrap_or_else(unbounded);
3182        let basis = BlurBasis::of(self.transform);
3183        let (min, max) = rest.covering(min, max, &|sigma| basis.reach(sigma));
3184        // The caller's blend rides the outermost composite. Left on the draw
3185        // inside, it was applied against the layer's own transparent black --
3186        // so a mode that reads its destination found nothing there, and the
3187        // result was composited over the frame it was meant to combine with.
3188        // `Plus` over a cyan ground gave the source unchanged instead of the
3189        // sum, for every image filter, since filters were added.
3190        //
3191        // Only the outermost, which is why the inner paint is neutral: peeling
3192        // a chain opens a layer per link, and a blend carried down would be
3193        // applied once per link rather than once.
3194        let _ = self.save_layer_device_bounds_running(
3195            layer.with_blend(paint.blend),
3196            min,
3197            max,
3198            runtime,
3199            None,
3200        );
3201        // The mask blur, if there is one, is left on: it applies to the drawing
3202        // this filter is filtering.
3203        let inner = paint
3204            .clone()
3205            .with_image_filter(rest)
3206            .with_blend(BlendMode::SrcOver);
3207        let failure = self.draw_path(path, &inner).err();
3208        self.restore();
3209        match failure {
3210            Some(e) => Err(e),
3211            None => Ok(self),
3212        }
3213    }
3214
3215    /// A path's bounds, widened by however far a stroke reaches past it.
3216    ///
3217    /// How far a blur reaches is deliberately not added: opening a bounded
3218    /// layer with a blur already widens the region by that, and the layer is
3219    /// the right place for it, since it knows its own sigma.
3220    ///
3221    /// The stroke's own reach was untested for a while, because that blur
3222    /// widening covers any stroke whose half-width is under the blur's own
3223    /// reach, and every test had one. It takes a wide stroke and a small blur to tell the two
3224    /// apart, and there is one now.
3225    fn filter_bounds(&self, path: &Path, paint: &Paint) -> Rect {
3226        let bounds = path.bounds();
3227        let reach = match &paint.style {
3228            // The width the stroke is drawn at, which for a sub-pixel one is
3229            // wider than the width it asked for. A bound taken from the asked
3230            // width would cut the widening off at the edge of the layer.
3231            Style::Stroke(stroke) if stroke.width.is_finite() => {
3232                thin_stroke(self.transform, stroke.width, Zero::IsAHairline).0 / 2.0
3233            }
3234            _ => 0.0,
3235        };
3236        Rect::new(
3237            bounds.min.x - reach,
3238            bounds.min.y - reach,
3239            bounds.max.x + reach,
3240            bounds.max.y + reach,
3241        )
3242    }
3243
3244    /// What a mask blur is blurring.
3245    ///
3246    /// A mask blur draws its content two or three times -- once into a blurred
3247    /// layer, sometimes again at full sharpness to combine with it -- and every
3248    /// style needs the same content each time. Naming the content rather than
3249    /// passing a path is what lets a glyph run take the same four styles a
3250    /// shape does, which matters because a text shadow is a mask blur over a
3251    /// run and is how the common case of shadowed text is drawn.
3252    fn draw_mask_content(&mut self, content: Masked<'_>, paint: &Paint) -> Result<&mut Self> {
3253        match content {
3254            Masked::Path(path) => self.draw_path(path, paint),
3255            Masked::Mesh(mesh) => self.draw_vertices(mesh, paint),
3256            Masked::Glyphs {
3257                glyphs,
3258                atlas,
3259                slot,
3260            } => self.draw_glyphs(glyphs, atlas, slot, paint),
3261        }
3262    }
3263
3264    /// The bounds of what a mask blur is blurring, in the canvas's own units.
3265    fn mask_bounds(&self, content: Masked<'_>, paint: &Paint) -> Rect {
3266        match content {
3267            Masked::Path(path) => self.filter_bounds(path, paint),
3268            Masked::Mesh(mesh) => {
3269                let (mut min, mut max) =
3270                    (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3271                for position in mesh.positions() {
3272                    min = min.min(*position);
3273                    max = max.max(*position);
3274                }
3275                Rect::new(min.x, min.y, max.x, max.y)
3276            }
3277            Masked::Glyphs { glyphs, .. } => {
3278                let (mut min, mut max) =
3279                    (Vec2::splat(f32::INFINITY), Vec2::splat(f32::NEG_INFINITY));
3280                for glyph in glyphs {
3281                    let corner = Vec2::from(glyph.position);
3282                    min = min.min(corner);
3283                    max = max.max(corner + Vec2::from(glyph.size));
3284                }
3285                Rect::new(min.x, min.y, max.x, max.y)
3286            }
3287        }
3288    }
3289
3290    /// A mask blur over a fill that varies, built the way `dart:ui` states it.
3291    ///
3292    /// The path below draws the paint through a blurred layer, which is the
3293    /// same picture only where the fill does not vary. This is the other order
3294    /// and the one a mask filter actually means: blur the shape's coverage,
3295    /// then fill through it. It needs no machinery that was not already here --
3296    /// the fill goes down across everything the blur reaches, the coverage is
3297    /// blurred in a layer of its own, and `DstIn` composites the second onto
3298    /// the first as a mask.
3299    ///
3300    /// Only a path. A glyph run reaches this call too, and a run tints one
3301    /// color by its own nature rather than by anything to do with blurring, so
3302    /// a gradient over one is refused here exactly as it is refused when
3303    /// nothing is blurred at all.
3304    fn draw_masked_through_coverage(
3305        &mut self,
3306        content: Masked<'_>,
3307        paint: &Paint,
3308    ) -> Result<&mut Self> {
3309        let bounds = self.mask_bounds(content, paint);
3310        // Wide enough for whichever blur this content's route will draw.
3311        let held = bounds.outset(self.mask_blur_reach(content, paint));
3312        // White, because what is wanted from the shape here is its coverage
3313        // rather than its color: the fill supplies the color and this supplies
3314        // where it lands.
3315        let coverage = Paint::fill(Color::WHITE).with_anti_alias(paint.anti_alias);
3316        // This one floods the held region with the caller's paint, so it has to
3317        // be a *fill* whatever the caller asked for. Left as the caller's own
3318        // style it drew the outline of the held rectangle when the caller was
3319        // stroking, and the mask below then cut that away to nothing -- the
3320        // rectangle's border is nowhere near the shape. A stroked shape with a
3321        // fill that varies came out empty, on both backends.
3322        //
3323        // Only the flood needs it. Handing the coverage the caller's style as
3324        // well changes no pixel of any plate here, so something other than this
3325        // line is already giving the mask the band rather than the region, and
3326        // a line that changes nothing does not go in with a comment saying it
3327        // does.
3328        let fill = paint
3329            .clone()
3330            .with_mask_blur(0.0)
3331            .with_blend(BlendMode::SrcOver)
3332            .with_style(Style::Fill);
3333
3334        self.save_layer_bounds(Layer::opacity(1.0).with_blend(paint.blend), held);
3335        // Across everything the blur reaches, not across the shape: a blurred
3336        // mask is wider than what it was made from, and a fill stopping at the
3337        // shape's own edge would cut the halo off square.
3338        let failure = self.draw_rect(held, &fill).err().or_else(|| {
3339            if paint.mask_blur_style == MaskBlurStyle::Normal {
3340                // The blurred coverage is the whole mask, so the layer that
3341                // carries it can be the layer that blurs it.
3342                let mask = Layer::opacity(1.0)
3343                    .with_blur(paint.mask_blur)
3344                    .with_blend(BlendMode::DstIn);
3345                self.save_layer_bounds(mask, held);
3346                let inner = self.draw_mask_content(content, &coverage).err();
3347                self.restore();
3348                return inner;
3349            }
3350            // The other three combine the blurred coverage with the sharp one,
3351            // and the combination is not itself blurred -- so this layer
3352            // carries no blur, and the blur happens inside it on the operand
3353            // that wants it.
3354            self.save_layer_bounds(Layer::opacity(1.0).with_blend(BlendMode::DstIn), held);
3355            let inner = self.draw_mask_styles(
3356                content,
3357                &coverage,
3358                paint.mask_blur,
3359                paint.mask_blur_style,
3360                bounds,
3361            );
3362            self.restore();
3363            inner
3364        });
3365        self.restore();
3366        match failure {
3367            Some(e) => Err(e),
3368            None => Ok(self),
3369        }
3370    }
3371
3372    fn draw_masked(&mut self, content: Masked<'_>, paint: &Paint) -> Result<&mut Self> {
3373        if !matches!(paint.shader, Shader::Solid(_)) {
3374            if !matches!(content, Masked::Glyphs { .. }) {
3375                return self.draw_masked_through_coverage(content, paint);
3376            }
3377            // A glyph run, and it is the only thing left here. A run tints one
3378            // color by its own nature rather than by anything to do with
3379            // blurring, so a varying fill over one is refused exactly as it is
3380            // refused when nothing is blurred at all.
3381            //
3382            // See `Paint::mask_blur`: drawing the paint through a blurred layer
3383            // is the other order, and for anything that varies the two are
3384            // different pictures. Drawing one while the caller asked for the
3385            // other is the substitution this renderer refuses
3386            // elsewhere.
3387            return Err(Error::Unsupported(
3388                "a mask blur over a glyph run takes a solid color; \
3389                 draw into a blurred layer for anything else",
3390            ));
3391        }
3392        let bounds = self.mask_bounds(content, paint);
3393        // Without the mask, or this would open a layer inside itself forever --
3394        // and with the caller's blend taken off, because it belongs to the
3395        // composite that puts the finished mask on the frame rather than to a
3396        // draw inside a layer that starts empty. Left on, a mode reading its
3397        // destination found transparent black there, and `Plus` over a cyan
3398        // ground gave the source unchanged instead of the sum.
3399        //
3400        // The style's own blends below are a different thing and stay: they
3401        // combine the shape with its blur *within* the layer, which is exactly
3402        // where a destination-reading mode is supposed to look.
3403        let inner = paint
3404            .clone()
3405            .with_mask_blur(0.0)
3406            .with_blend(BlendMode::SrcOver);
3407
3408        // The blurred coverage alone is the whole picture for the default
3409        // style, so it needs one layer and no second draw.
3410        if paint.mask_blur_style == MaskBlurStyle::Normal {
3411            self.save_layer_bounds(
3412                Layer::opacity(1.0)
3413                    .with_blur(paint.mask_blur)
3414                    .with_blend(paint.blend),
3415                bounds,
3416            );
3417            // The result is discarded to end the borrow before restoring, and
3418            // taken up again after: the layer has to be closed whether the
3419            // draw inside it succeeded or not, or every later draw lands in a
3420            // layer nobody composites.
3421            let failure = self.draw_mask_content(content, &inner).err();
3422            self.restore();
3423            return match failure {
3424                Some(e) => Err(e),
3425                None => Ok(self),
3426            };
3427        }
3428
3429        // Every other style combines the blurred coverage with the shape's
3430        // own. That combination is the same whether what is being combined is
3431        // color or coverage, so it lives in `draw_mask_styles` and both routes
3432        // through here call it.
3433        // Wide enough for whichever blur this content's route will draw.
3434        let held = bounds.outset(self.mask_blur_reach(content, paint));
3435        self.save_layer_bounds(Layer::opacity(1.0).with_blend(paint.blend), held);
3436        let failure = self.draw_mask_styles(
3437            content,
3438            &inner,
3439            paint.mask_blur,
3440            paint.mask_blur_style,
3441            bounds,
3442        );
3443        self.restore();
3444        match failure {
3445            Some(e) => Err(e),
3446            None => Ok(self),
3447        }
3448    }
3449
3450    /// How far past its bounds a mask blur on this content will draw.
3451    ///
3452    /// The two routes reach different distances and the layer holding them has
3453    /// to fit whichever is used: a sampled blur stops at `blur_reach`, about
3454    /// 1.73 deviations, and an evaluated one carries to `pad_for_sigma`, about
3455    /// 2.5. Sized for the first, an evaluated blur is cut off square; sized for
3456    /// the second regardless, every *sampled* blur pays for a transient about
3457    /// twice the area to hold a halo it will never draw.
3458    ///
3459    /// So it asks which route the content will take, rather than taking the
3460    /// larger of the two and calling it safe.
3461    fn mask_blur_reach(&mut self, content: Masked<'_>, paint: &Paint) -> f32 {
3462        let sampled = blur_reach(paint.mask_blur);
3463        let probe = paint.clone().with_mask_blur_style(MaskBlurStyle::Normal);
3464        match self.analytic_style_blur(content, &probe, paint.mask_blur) {
3465            Some((_, _, pad)) => sampled.max(pad),
3466            None => sampled,
3467        }
3468    }
3469
3470    /// The evaluated blur for a style's blurred ingredient, where one applies.
3471    ///
3472    /// The styles other than `Normal` combine a blurred shape with its sharp
3473    /// self, and the blurred half is the same thing `Normal` draws — so where
3474    /// `Normal` would be evaluated rather than sampled, this half can be too.
3475    /// `inner` is the paint with the blur already taken off, which is what the
3476    /// styles draw with, so the deviation is handed back in.
3477    ///
3478    /// Returns the rectangle the draw covers as well as the material, because
3479    /// the caller has to widen its layer to hold it: an evaluated blur reaches
3480    /// `pad_for_sigma`, which is further than the `blur_reach` a sampled one is
3481    /// truncated at, and a layer sized for the sampled reach cuts it.
3482    fn analytic_style_blur(
3483        &mut self,
3484        content: Masked<'_>,
3485        inner: &Paint,
3486        sigma: f32,
3487    ) -> Option<(Rect, Material, f32)> {
3488        let Masked::Path(path) = content else {
3489            return None;
3490        };
3491        let (bounds, radius) = path.as_rounded_rect()?;
3492        let rect = Rect::new(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y);
3493        // Asked for as `Normal`, whatever style the caller wants: the blurred
3494        // half *is* the normal blur, and the style is the rule for combining it
3495        // with the sharp shape rather than a property of the blur. Left as the
3496        // caller's, the eligibility check refuses it -- which is right when the
3497        // question is "may this whole draw be one expression" and wrong here.
3498        let asked = inner
3499            .clone()
3500            .with_mask_blur(sigma)
3501            .with_mask_blur_style(MaskBlurStyle::Normal);
3502        let (material, pad) = self.analytic_rrect_blur(rect, radius, &asked)?;
3503        Some((rect, material, pad))
3504    }
3505
3506    /// Combine a shape's blurred coverage with its sharp own, per style.
3507    ///
3508    /// Draws into whatever layer the caller has already opened, and that layer
3509    /// is not optional: drawn straight onto the target, a blend that reads the
3510    /// destination would reach what was already there rather than only what
3511    /// this is building.
3512    ///
3513    /// What is being combined is the caller's business. Given the paint the
3514    /// shape is filled with, this composes colors and is the whole picture;
3515    /// given white, it composes coverage, and the caller masks a varying fill
3516    /// through the result. The rules are identical either way, which is why
3517    /// there is one of these rather than two.
3518    ///
3519    /// Which of the two operands is drawn first is not a matter of taste. A
3520    /// blend only runs where its source produces a fragment, and the shape
3521    /// produces none outside itself -- so a rule that has to *remove*
3522    /// something outside the shape cannot be written with the shape as the
3523    /// source. The blurred layer composites as a quad over the whole region, so
3524    /// it is the operand that can act everywhere, and the two rules needing
3525    /// that are the two where the shape goes down first.
3526    fn draw_mask_styles(
3527        &mut self,
3528        content: Masked<'_>,
3529        inner: &Paint,
3530        sigma: f32,
3531        style: MaskBlurStyle,
3532        bounds: Rect,
3533    ) -> Option<Error> {
3534        // Not itself blurred, so nothing widens it on its behalf.
3535        let blurred = Layer::opacity(1.0).with_blur(sigma);
3536        match style {
3537            // Blur first, then the shape over it. `SrcOver` leaves the blur
3538            // where the shape is not, and `DstOut` takes the shape out of it
3539            // -- both of which want the destination untouched outside the
3540            // shape, which is what a source that draws nothing there gives.
3541            MaskBlurStyle::Solid | MaskBlurStyle::Outer => {
3542                let blend = match style {
3543                    MaskBlurStyle::Solid => BlendMode::SrcOver,
3544                    _ => BlendMode::DstOut,
3545                };
3546                // The blurred half, evaluated where it can be. These two
3547                // styles draw it first with the layer's own blend, so nothing
3548                // has to be relaxed to allow it -- unlike `Inner`, whose blur
3549                // is composited with `DstIn` and needs coverage this cannot
3550                // give from a quad.
3551                let first = match self.analytic_style_blur(content, inner, sigma) {
3552                    Some((rect, material, pad)) => {
3553                        self.draw_analytic(rect.outset(pad), material, inner).err()
3554                    }
3555                    None => {
3556                        self.save_layer_bounds(blurred, bounds);
3557                        let failed = self.draw_mask_content(content, inner).err();
3558                        self.restore();
3559                        failed
3560                    }
3561                };
3562                first.or_else(|| {
3563                    self.draw_mask_content(content, &inner.clone().with_blend(blend))
3564                        .err()
3565                })
3566            }
3567            // The shape first, and the blur composited onto it with `DstIn`.
3568            // The other order is the obvious one and is wrong: outside the
3569            // shape there is no fragment for `DstIn` to run on, so the blur
3570            // survives exactly where this style is supposed to discard it.
3571            // Compositing a layer covers the whole region, so putting the
3572            // blur on that side is what makes the rule act everywhere.
3573            MaskBlurStyle::Inner => {
3574                let first = self.draw_mask_content(content, inner).err();
3575                if first.is_some() {
3576                    return first;
3577                }
3578                // `DstIn` is the one blend the analytic route refuses
3579                // everywhere else, because it changes the destination where the
3580                // source drew nothing and a quad is smaller than the region a
3581                // layer composite covers. That argument does not reach here,
3582                // and the reason is specific rather than a relaxation: the only
3583                // thing in this layer is the sharp shape drawn a line above,
3584                // the shape is a fill and so lies within `rect`, and the quad
3585                // is `rect` grown by the blur's reach. Everything the blend
3586                // could have to zero is under the quad; outside it the layer is
3587                // still transparent, where zeroing and leaving alone are the
3588                // same. So the eligibility is asked about the blur -- with
3589                // `SrcOver`, since that is what the question means -- and the
3590                // blend is put on at the draw.
3591                match self.analytic_style_blur(content, inner, sigma) {
3592                    Some((rect, material, pad)) => {
3593                        let composite = inner.clone().with_blend(BlendMode::DstIn);
3594                        self.draw_analytic(rect.outset(pad), material, &composite)
3595                            .err()
3596                    }
3597                    None => {
3598                        self.save_layer_bounds(blurred.with_blend(BlendMode::DstIn), bounds);
3599                        let second = self.draw_mask_content(content, inner).err();
3600                        self.restore();
3601                        second
3602                    }
3603                }
3604            }
3605            MaskBlurStyle::Normal => unreachable!("handled by the caller"),
3606        }
3607    }
3608
3609    /// Fill or stroke a rectangle.
3610    ///
3611    /// **A fill is tessellated.** It used to take the same distance field a rounded
3612    /// rectangle does, with no corner to round, on the reasoning that a shape
3613    /// computing its own coverage spares the pass multisampling. That was measured
3614    /// backwards on 2026-09-30: the field is the dearer route by about thirty per
3615    /// cent. On the `stacked interface` frame, tessellated at four samples against
3616    /// analytic at one -- 16.077 ms against 24.508 on a Pi 5, 66.100 against 93.981
3617    /// on a VisionFive 2, 1.786 against 2.758 on x86-64. Three architectures, one
3618    /// direction. `docs/on-a-board.md` has the conditions, the control and the
3619    /// arithmetic.
3620    ///
3621    /// The arithmetic the old comment had wrong: multisampling shades once per pixel
3622    /// and pays in attachment bandwidth and a resolve -- 1.23x on V3D, 2.62x on
3623    /// PowerVR, not 4x -- while the field costs an evaluation per fragment across a
3624    /// quad, and for a rectangle that field evaluates to a constant.
3625    ///
3626    /// It is also what upstream does. `FillRectGeometry::GetPositionBuffer`, read at
3627    /// `flutter/flutter` master on 2026-10-01, emits a four-vertex triangle strip
3628    /// under `Mode::kNormal`; there is no fragment-evaluated rectangle fill there at
3629    /// all. So the flip closes a divergence rather than opening one, and the edge a
3630    /// rectangle gets here is now the edge upstream gives it.
3631    ///
3632    /// **A stroke stays on the field.** What was measured is a fill, the stroke route
3633    /// is careful about a corner the field would otherwise round -- see
3634    /// `analytic_rrect` -- and nothing here has measured what that costs.
3635    pub fn draw_rect(&mut self, rect: Rect, paint: &Paint) -> Result<&mut Self> {
3636        if rect.is_empty() {
3637            return Ok(self);
3638        }
3639        if matches!(paint.style, Style::Stroke(_)) {
3640            if let Some((material, to_local)) = self.analytic_rrect(rect, 0.0, paint) {
3641                return self.draw_analytic_local(rect, material, paint, to_local);
3642            }
3643        }
3644        let path = rect.to_path();
3645        self.draw_path(&path, paint)
3646    }
3647
3648    /// Fill or stroke a rectangle with rounded corners.
3649    ///
3650    /// The shape an interface is mostly made of, and the reason it is here
3651    /// rather than left to the caller: building it from arcs by hand is a dozen
3652    /// lines that have to get the corner tangents right, and getting them
3653    /// slightly wrong shows as a corner that is subtly not round.
3654    ///
3655    /// **A fill is tessellated once the pass is multisampled**, and takes the
3656    /// field until then. What the field buys is a pass left at one sample, and
3657    /// since `draw_rect` started tessellating its fills on 2026-10-01 most frames
3658    /// give that up early: one antialiased rectangle multisamples the pass. From
3659    /// there on the field is evaluated across a whole quad for an edge four
3660    /// samples would have given anyway, and at equal sample counts it was already
3661    /// measured as the dearer route -- see `docs/architecture.md`.
3662    ///
3663    /// Measured 2026-11-12 on a Pi 5, interleaved, four runs a side: the cards
3664    /// of `full frame, mixed content`, drawn over a multisampled ground, cost
3665    /// 0.64 ms from the field and 0.29 tessellated, and the frame 14.46 against
3666    /// 14.10. `docs/on-a-board.md` has the frames. Upstream tessellates the fill
3667    /// too: `Canvas::DrawRoundRect` sends it to `RoundRectGeometry`, a
3668    /// tessellated strip, unless `--impeller-use-sdfs` is passed, which it is
3669    /// not by default.
3670    ///
3671    /// Before anything has multisampled the pass, the field stays. Tessellating
3672    /// there would turn multisampling on for the whole pass, which is what the
3673    /// field exists to avoid, and would make a frame drawn with no background
3674    /// into a multisampled pass with nothing to clear to, which the backends
3675    /// refuse.
3676    ///
3677    /// **A stroke stays on the field**, as `draw_rect`'s does, and for the
3678    /// reason given there. Both routes need what `analytic_rrect` admits -- a
3679    /// solid paint that asked for antialiasing -- and anything else goes to
3680    /// `draw_path`.
3681    pub fn draw_rrect(&mut self, rect: Rect, radius: f32, paint: &Paint) -> Result<&mut Self> {
3682        if rect.is_empty() {
3683            return Ok(self);
3684        }
3685        // Before the sharp field, because that one refuses a mask blur and this
3686        // is what answers it: the blur is folded into the expression rather
3687        // than run as passes around the draw.
3688        if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(rect, radius, paint) {
3689            return self.draw_analytic(rect.outset(pad), material, &drawn);
3690        }
3691        if matches!(paint.style, Style::Stroke(_)) || self.pass_samples() == 1 {
3692            if let Some((material, to_local)) = self.analytic_rrect(rect, radius, paint) {
3693                return self.draw_analytic_local(rect, material, paint, to_local);
3694            }
3695        }
3696        let path = rect.to_rounded_path(radius);
3697        self.draw_path(&path, paint)
3698    }
3699
3700    /// A rounded rectangle whose corners need not match.
3701    ///
3702    /// The eight numbers `dart:ui`'s `RRect` carries, in the order upstream's
3703    /// `RoundingRadii` carries them: top-left, top-right, bottom-left,
3704    /// bottom-right, each an x radius and a y radius. Radii that overrun the
3705    /// side they share are fitted by `dart:ui`'s rule -- see
3706    /// [`Rect::to_rounded_path_with_radii`].
3707    ///
3708    /// Tessellated, always. The fragment-evaluated route [`Self::draw_rrect`]
3709    /// can take -- for a stroke, or a fill in a pass not yet multisampled -- is
3710    /// a signed distance to a shape with one circular radius, and eight numbers
3711    /// is a different function rather than that one with more arguments. So a
3712    /// corner that differs from its neighbors is tessellated where a uniform
3713    /// one might not be. A multisampled fill is tessellated either way, so
3714    /// there the two calls cost the same.
3715    pub fn draw_rrect_with_radii(
3716        &mut self,
3717        rect: Rect,
3718        radii: RoundingRadii,
3719        paint: &Paint,
3720    ) -> Result<&mut Self> {
3721        if rect.is_empty() {
3722            return Ok(self);
3723        }
3724        // A caller who spells a uniform shape this way still gets the route
3725        // `draw_rrect` picks, which matters because the general call is the one
3726        // a `dart:ui` port reaches for and most of what it is handed is uniform.
3727        if let Some(radius) = uniform_circular_radius(radii) {
3728            return self.draw_rrect(rect, radius, paint);
3729        }
3730        let path = rect.to_rounded_path_with_radii(radii);
3731        self.draw_path(&path, paint)
3732    }
3733
3734    /// Draw Flutter's rounded superellipse -- the iOS-style squircle.
3735    ///
3736    /// `dart:ui`'s `drawRSuperellipse`. The corners are not arcs of one curve:
3737    /// each is a superellipse arc, a circular arc across the diagonal, and a
3738    /// second superellipse arc, with the superellipse's degree read from a
3739    /// fitted table on the ratio of side to radius. See
3740    /// [`emblema_geometry::superellipse`] for what that means and for what
3741    /// checks the transcription of the table.
3742    ///
3743    /// Tessellated rather than evaluated in the fragment stage. A rounded
3744    /// rectangle of a single radius takes the analytic route because there is
3745    /// a closed form to evaluate; this shape has none, which is the same
3746    /// reason it took so long to arrive.
3747    pub fn draw_rsuperellipse(
3748        &mut self,
3749        rect: Rect,
3750        radii: RoundingRadii,
3751        paint: &Paint,
3752    ) -> Result<&mut Self> {
3753        if rect.is_empty() {
3754            return Ok(self);
3755        }
3756        self.draw_path(&rsuperellipse_path(rect, radii), paint)
3757    }
3758
3759    /// Clip to Flutter's rounded superellipse.
3760    ///
3761    /// `dart:ui`'s `clipRSuperellipse`, and the same shape
3762    /// [`Canvas::draw_rsuperellipse`] draws.
3763    pub fn clip_rsuperellipse(&mut self, rect: Rect, radii: RoundingRadii) -> Result<&mut Self> {
3764        self.clip_path(&rsuperellipse_path(rect, radii))
3765    }
3766
3767    /// How far past the shape a blurred rounded rectangle has to draw.
3768    ///
3769    /// Wider than `blur_reach`, and deliberately: that is where a *sampled*
3770    /// Gaussian's kernel is truncated, and this expression has no kernel to
3771    /// truncate. It is evaluated everywhere and falls off smoothly, so what
3772    /// bounds it is where the falloff stops being visible rather than where the
3773    /// taps stop. Upstream's `PadForSigma`, whose comment records that three
3774    /// deviations was tried and left a cutoff on large blurs.
3775    fn pad_for_sigma(sigma: f32) -> f32 {
3776        sigma * (sigma / 47.6 + 2.5).min(3.5)
3777    }
3778
3779    /// The gate above, with the one substitution upstream makes, and the paint
3780    /// to draw the result with.
3781    ///
3782    /// Three shapes reach the evaluated blur -- a rounded-rectangle path,
3783    /// `draw_rrect` and `draw_circle` -- and all three share this. The fourth
3784    /// caller of [`Self::analytic_rrect_blur`] deliberately does not: it is
3785    /// building the blurred *ingredient* of a style that combines it with the
3786    /// sharp shape inside a layer, and a substitution good for a whole draw is
3787    /// not good for one operand of a combination.
3788    fn analytic_rrect_blur_draw(
3789        &mut self,
3790        rect: Rect,
3791        radius: f32,
3792        paint: &Paint,
3793    ) -> Option<(Material, f32, Paint)> {
3794        let drawn = Self::erasing_blur_paint(paint);
3795        let (material, pad) = self.analytic_rrect_blur(rect, radius, &drawn)?;
3796        Some((material, pad, drawn))
3797    }
3798
3799    /// `Clear` on a blurred shape, expressed as a mode that respects coverage.
3800    ///
3801    /// The gate below refuses a mode that writes where its source is
3802    /// transparent, and it is right to: the field is evaluated across a quad
3803    /// larger than the shape, so such a mode erases what is behind it in the
3804    /// gap. `Clear` is the one mode that can be admitted anyway, because on a
3805    /// coverage it is not what its factors say. Clearing by an amount `c` is
3806    /// `dst * (1 - c)`, which is `DstOut` against a white source -- and white
3807    /// is exact rather than approximate, since `Clear` discards the source
3808    /// color by definition and cannot care which one it had.
3809    ///
3810    /// This is upstream's own special case, in upstream's own one place.
3811    /// `SolidRRectLikeBlurContents::Render` checks for `BlendMode::kClear`,
3812    /// forces the color to white, and sets a flag that turns the pipeline's
3813    /// blend into a reverse subtraction -- destination factor `One`, source
3814    /// factor `DestinationColor`, so `dst - src * dst`. The arithmetic is the
3815    /// same; upstream reaches it by subtraction because its fragment writes
3816    /// coverage directly, and this reaches it by naming the mode that already
3817    /// means it.
3818    ///
3819    /// Only `Clear`. Upstream does not generalize this and neither does this:
3820    /// the other six modes that ignore coverage have no such reading and stay
3821    /// on the route that gets them wrong, which is `docs/non-parity.md`
3822    /// section 15.
3823    fn erasing_blur_paint(paint: &Paint) -> Paint {
3824        if paint.blend != BlendMode::Clear {
3825            return paint.clone();
3826        }
3827        paint
3828            .clone()
3829            .with_shader(Shader::Solid(Color::WHITE))
3830            .with_blend(BlendMode::DstOut)
3831            // Dropped rather than carried, because it provably cannot matter:
3832            // a color filter transforms the source color and `Clear` discards
3833            // it. Carried into the substitution it would stop being a no-op
3834            // and start changing how much is erased.
3835            .with_color_filter(ColorFilter::None)
3836    }
3837
3838    /// Draw a blurred rounded rectangle without a blur pass, if this one can be.
3839    ///
3840    /// The route upstream takes for the same shape, and the reason it is worth
3841    /// taking is that the general one costs three passes per shape where this
3842    /// costs one draw in the pass already open.
3843    ///
3844    /// `analytic_stroke` cannot answer this one, and the difference is the
3845    /// point: it refuses a mask blur outright, because a sharp distance field
3846    /// on an oversized quad cannot be put inside a layer and blurred. That is
3847    /// exactly the refusal this route lifts, by folding the blur into the field
3848    /// rather than wrapping the draw in one. Its other refusals do carry over
3849    /// and are restated here.
3850    /// Returns the material and how far past the rectangle it must be drawn,
3851    /// both in the shape's own space.
3852    fn analytic_rrect_blur(
3853        &mut self,
3854        rect: Rect,
3855        radius: f32,
3856        paint: &Paint,
3857    ) -> Option<(Material, f32)> {
3858        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
3859            return None;
3860        }
3861        // This emits a fragment across the whole padded quad, which is much
3862        // larger than the shape, so a mode that touches the destination where
3863        // the source is transparent would erase what is behind it in the gap.
3864        if !paint.blend.respects_coverage() {
3865            return None;
3866        }
3867        // An image filter wants a layer around the draw, and a quad larger than
3868        // its shape is the wrong thing to put in one.
3869        if !paint.image_filter.is_identity() {
3870            return None;
3871        }
3872        // A fill only. A blurred *stroke* is the blur of a band rather than of
3873        // the shape: a different picture, and not one this expression states.
3874        // A dash is refused with it, since there is no stroke to dash.
3875        if !matches!(paint.style, Style::Fill) {
3876            return None;
3877        }
3878        // The blurred coverage itself. The other three styles are that
3879        // combined with the sharp shape, which the general route assembles out
3880        // of two draws and this cannot say in one.
3881        if paint.mask_blur_style != MaskBlurStyle::Normal {
3882            return None;
3883        }
3884        let shader = paint.effective_shader();
3885        let Shader::Solid(color) = &*shader else {
3886            return None;
3887        };
3888        if radius.is_nan() || radius < 0.0 {
3889            return None;
3890        }
3891        // `is_finite` first, so a sigma that is not a number is refused rather
3892        // than compared: every comparison against NaN is false, so a bare
3893        // `<= 0.0` would let it through.
3894        if !paint.mask_blur.is_finite() || paint.mask_blur <= 0.0 {
3895            return None;
3896        }
3897        // The deviation is in device pixels -- see `non-parity.md` on a shadow's
3898        // elevation -- and everything below is in the shape's own space, so it
3899        // has to be carried across. Getting this wrong is invisible at the
3900        // identity and doubles the blur's tail on a canvas scaled by two.
3901        let affine = self.transform.to_affine()?;
3902        let sx = affine.matrix2.x_axis.length();
3903        let sy = affine.matrix2.y_axis.length();
3904        if !sx.is_finite() || !sy.is_finite() || sx <= 0.0 || sy <= 0.0 {
3905            return None;
3906        }
3907        // One deviation cannot describe a blur that is wider along one axis
3908        // than the other, and this expression carries exactly one. A transform
3909        // that scales the axes differently goes to the general route, which
3910        // blurs in device space and does not care.
3911        if (sx - sy).abs() > 1e-3 * sx.max(sy) {
3912            return None;
3913        }
3914        // Stated in the shape's own space already, so there is nothing to
3915        // convert. It used to be `paint.mask_blur / sx`, which is what a
3916        // device-space sigma needed and what made a blur refuse to grow with
3917        // the transform.
3918        let sigma = paint.mask_blur;
3919
3920        let radius = radius.min(rect.width() / 2.0).min(rect.height() / 2.0);
3921        let material = self.rrect_blur_material(rect, radius, sigma, *color)?;
3922        Some((material, Self::pad_for_sigma(sigma)))
3923    }
3924
3925    /// A blurred convex fill drawn as a shadow mesh, if this one can be.
3926    ///
3927    /// Upstream's route for every mask-blurred fill it has no analytic shape
3928    /// for -- an oval that is not a circle, a rounded rectangle with unequal
3929    /// corners, any other convex path -- and the one `drawShadow` takes for
3930    /// them: `Canvas::AttemptDrawBlurredPathSource`, a mesh from
3931    /// `ShadowPathGeometry` drawn through `ShadowVerticesContents`. A concave
3932    /// path, or one of more than one contour, has no mesh and is blurred the
3933    /// general way, as upstream blurs it.
3934    ///
3935    /// The same eligibility as the analytic rounded rectangle's, for the same
3936    /// reasons, and one difference: a mesh is built per axis, so a transform
3937    /// that scales the axes differently is no reason to refuse.
3938    ///
3939    /// `None` when this route does not apply; otherwise the draw's result.
3940    fn shadow_mesh_blur(&mut self, path: &Path, paint: &Paint) -> Option<Result<()>> {
3941        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
3942            return None;
3943        }
3944        // The mesh reaches past the shape, so a mode that writes where its
3945        // source is transparent would erase what is behind the falloff.
3946        if !paint.blend.respects_coverage() {
3947            return None;
3948        }
3949        if !paint.image_filter.is_identity()
3950            || !matches!(paint.style, Style::Fill)
3951            || paint.mask_blur_style != MaskBlurStyle::Normal
3952        {
3953            return None;
3954        }
3955        if !paint.mask_blur.is_finite() || paint.mask_blur <= 0.0 {
3956            return None;
3957        }
3958        let shader = paint.effective_shader();
3959        let Shader::Solid(color) = &*shader else {
3960            return None;
3961        };
3962        let affine = self.transform.to_affine()?;
3963        let scale = Vec2::new(
3964            affine.matrix2.x_axis.length(),
3965            affine.matrix2.y_axis.length(),
3966        );
3967        let reach = emblema_geometry::shadow_reach(paint.mask_blur, scale.x.max(scale.y));
3968        let mesh = emblema_geometry::ambient_shadow_mesh(path, scale, reach)?;
3969        if mesh.is_empty() {
3970            return Some(Ok(()));
3971        }
3972        let to_clip = self.target.projection() * self.transform;
3973        let vertices: Vec<Vertex> = mesh
3974            .positions
3975            .iter()
3976            .zip(&mesh.gaussians)
3977            .map(|(p, g)| {
3978                let clip = to_clip.project_homogeneous(*p);
3979                Vertex::projected([clip.x, clip.y, clip.z], [*g, 0.0])
3980            })
3981            .collect();
3982        Some(self.batch.push_mesh(
3983            &vertices,
3984            &mesh.indices,
3985            Material::ShadowMesh {
3986                color: color.to_array(),
3987            },
3988            paint.color_filter,
3989            paint.blend,
3990            self.clip,
3991            ClipState::content(self.depth),
3992        ))
3993    }
3994
3995    /// The material for a blurred rounded rectangle drawn without a blur pass.
3996    ///
3997    /// Raph Levien's approximation, transcribed from upstream's
3998    /// `SolidRRectLikeBlurContents::PopulateFragContext`, which evaluates the
3999    /// same method. Every line is arithmetic the shader would otherwise repeat
4000    /// per fragment, and none of it is this renderer's invention -- the
4001    /// constants are upstream's, and where one looks arbitrary it is because
4002    /// it was fitted rather than derived.
4003    ///
4004    /// `rect` and `radius` are in the shape's own space, `sigma` in device
4005    /// pixels, as everywhere else here.
4006    fn rrect_blur_material(
4007        &self,
4008        rect: Rect,
4009        radius: f32,
4010        sigma: f32,
4011        color: Color,
4012    ) -> Option<Material> {
4013        // Below one, the approximation is sharper than the pixel grid can show
4014        // and the error function saturates; upstream floors it in the same
4015        // place. The root of two is the conversion between the deviation this
4016        // renderer states and the one the expression below is written in.
4017        let sigma = (sigma * std::f32::consts::SQRT_2).max(1.0);
4018        let mut size = Vec2::new(rect.width(), rect.height());
4019        if !size.x.is_finite() || !size.y.is_finite() || !sigma.is_finite() {
4020            return None;
4021        }
4022        if size.x <= 0.0 || size.y <= 0.0 {
4023            return None;
4024        }
4025        let min_edge = size.x.min(size.y);
4026        let r_max = 0.5 * min_edge;
4027
4028        // Two corner radii rather than the caller's one: a blurred corner is
4029        // rounder than the shape's, and how much rounder depends on the
4030        // deviation. Their ratio becomes the exponent, so a sharp corner under
4031        // a wide blur is measured with a larger exponent than a round one.
4032        let r0 = radius.hypot(sigma * 1.15).min(r_max);
4033        let r1 = radius.hypot(sigma * 2.0).min(r_max);
4034        let exponent = 2.0 * r1 / r0;
4035        let s_inv = 1.0 / sigma;
4036
4037        // Pull the long end in. A rectangle much longer than it is wide blurs
4038        // to something the axis-wise expression makes too eccentric, and this
4039        // shortens the long axis by an amount that vanishes as either side
4040        // grows past the deviation -- which is why it is a pair of Gaussians
4041        // of the sides rather than a ratio.
4042        let falloff = |v: f32| (-(v * s_inv * 0.5).powi(2)).exp();
4043        let delta = 1.25 * sigma * (falloff(size.x) - falloff(size.y));
4044        // Whichever axis is longer is the one shortened, which is a deliberate
4045        // departure from upstream and the only one in this expression.
4046        // Upstream writes `rSize += NegPos(delta)`, which is
4047        // `{min(delta, 0), max(delta, 0)}` -- so it shortens x when x is the
4048        // long axis and *lengthens* y when y is, leaving the same rectangle
4049        // blurred to two different widths depending on which way it is turned.
4050        // Its own comment says "pull in long end", which is what this does in
4051        // both orientations. See `non-parity.md`.
4052        size.x += delta.min(0.0);
4053        size.y += (-delta).min(0.0);
4054
4055        let adjust = size * 0.5 - Vec2::splat(r1);
4056        // Normalizes the fade, so the middle of a shape large against its blur
4057        // reaches full coverage rather than something near it.
4058        let scale = 0.5 * erf7(s_inv * 0.5 * (size.x.max(size.y) - 0.5 * radius));
4059
4060        let center = Vec2::new(
4061            (rect.left + rect.right) / 2.0,
4062            (rect.top + rect.bottom) / 2.0,
4063        );
4064        let to_clip = self.target.projection() * self.transform;
4065        let material = Material::RoundedRectBlur {
4066            color: color.to_array(),
4067            to_local: invert_to_local(to_clip * Affine2::from_translation(center)),
4068            adjust: [adjust.x, adjust.y],
4069            r1,
4070            exponent,
4071            s_inv,
4072            min_edge,
4073            scale,
4074        };
4075        // A field that is not a number puts NaN through every fragment, and a
4076        // NaN coverage is a shape that vanishes or a frame that does. Upstream
4077        // checks the same eight and declines the same way.
4078        [adjust.x, adjust.y, r1, exponent, s_inv, min_edge, scale]
4079            .iter()
4080            .all(|v| v.is_finite())
4081            .then_some(material)
4082    }
4083
4084    /// A paint for the fragment-evaluated rounded rectangle, where one applies.
4085    ///
4086    /// A solid-colored fill or stroke that asked for antialiasing. The material
4087    /// carries a stroke width and an outer radius, and the bench times the stroked
4088    /// case as `stroked field`.
4089    ///
4090    /// Refused: a gradient or an image, which would need its own mapping and this
4091    /// one at once -- the case the push-constant budget was sized against; an
4092    /// aliased fill, which asks for the hard edges the tessellated path gives; and
4093    /// a square-cornered stroked rectangle, for the reason stated where the body
4094    /// declines it.
4095    /// The material, and the clip-to-local mapping it would otherwise carry.
4096    ///
4097    /// Returned beside the material rather than inside it so that two of this
4098    /// shape in different places compare equal and the batch merges them; the
4099    /// mapping rides on the vertices instead. See `Renderer::fill_into_local`.
4100    fn analytic_rrect(
4101        &self,
4102        rect: Rect,
4103        radius: f32,
4104        paint: &Paint,
4105    ) -> Option<(Material, [f32; 12])> {
4106        // Invisible and fully-clipped shapes are rejected before the path is
4107        // built, and this route has to reject them too. It bypasses
4108        // `draw_path`, which is where those checks live -- so an alpha of zero
4109        // went from recording nothing to recording a quad the fragment stage
4110        // discards a pixel at a time.
4111        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
4112            return None;
4113        }
4114        // A stroked rectangle with square corners is the one shape this route
4115        // draws differently, and it took a plate sending a rectangle through
4116        // `draw_rect` to notice. A distance field's stroke is the band a fixed
4117        // distance either side of the outline, and at a vertex that band's
4118        // outer edge is an arc -- so the corners come out *rounded*, where
4119        // `dart:ui`'s default join is a miter and the tessellated route gives
4120        // the sharp corner it asks for. Measured on a nine-wide stroke, one
4121        // route draws the corner pixel and the other does not: a difference of
4122        // two hundred and fifty-three out of two hundred and fifty-five.
4123        //
4124        // With a radius the outline has no vertex, so there is no join to get
4125        // wrong and the arc is what the shape is. Only the square-cornered case
4126        // is refused, and only where the caller asked for something other than
4127        // the round join the field would give them anyway.
4128        // A bevel cuts the corner off, which is neither the arc a round join
4129        // gives nor the point a miter does, and no offset of this shape is that
4130        // -- so it is the one join still sent to the tessellator. The other two
4131        // are the outer offset with and without a radius, which is what
4132        // `outer_radius` carries below.
4133        let mitered = match &paint.style {
4134            Style::Stroke(style) if style.width > 0.0 => {
4135                if style.join == LineJoin::Bevel {
4136                    return None;
4137                }
4138                style.join == LineJoin::Miter
4139            }
4140            _ => false,
4141        };
4142        // Widened and dimmed on the same terms the tessellated route is, so
4143        // that which route a shape takes stays invisible. See `thin_stroke`.
4144        let (stroke, coverage) =
4145            thin_stroke(self.transform, analytic_stroke(paint)?, Zero::IsNotAStroke);
4146        let shader = paint.effective_shader();
4147        let Shader::Solid(color) = &*shader else {
4148            return None;
4149        };
4150        // A radius of zero is a plain rectangle, which this field describes as
4151        // well as any other: with no corner to round, the expression is the
4152        // distance to the nearer edge. NaN is not a radius and falls back.
4153        if radius.is_nan() || radius < 0.0 {
4154            return None;
4155        }
4156        let to_clip = self.target.projection() * self.transform;
4157        let center = Vec2::new(
4158            (rect.left + rect.right) / 2.0,
4159            (rect.top + rect.bottom) / 2.0,
4160        );
4161        let clip_to_local = invert_to_local(to_clip * Affine2::from_translation(center));
4162        Some((
4163            Material::RoundedRect {
4164                color: dimmed(*color, coverage),
4165                half_size: [rect.width() / 2.0, rect.height() / 2.0],
4166                // Identity, because the mapping travels on the vertices instead
4167                // -- `clip_to_local` below, applied by `fill_into_local`. It maps a
4168                // clip-space position back into the shape's own space, measured
4169                // from its center, so the distance is measured where the radius
4170                // means what the caller said; measuring in clip space would round
4171                // the corners by different amounts on each axis of a target that is
4172                // not square. Keeping it out of the material is what lets two of
4173                // this shape in different places merge into one draw.
4174                to_local: to_local_columns(Transform2D::IDENTITY),
4175                radius: radius.min(rect.width() / 2.0).min(rect.height() / 2.0),
4176                // A mitered square corner offsets to a square corner, which is a
4177                // radius of nothing. Everything else grows by half the stroke:
4178                // a rounded corner because that is what offsetting an arc does, and
4179                // a round join because the arc is what it asks for.
4180                outer_radius: if mitered && radius <= 0.0 {
4181                    0.0
4182                } else {
4183                    radius.min(rect.width() / 2.0).min(rect.height() / 2.0) + stroke / 2.0
4184                },
4185                stroke,
4186            },
4187            clip_to_local,
4188        ))
4189    }
4190
4191    /// Draw the quad a fragment-evaluated shape is painted onto.
4192    ///
4193    /// Outset by a pixel, because the coverage ramp runs half a pixel either
4194    /// side of the edge: a quad ending exactly at the shape would clip the
4195    /// outer half of its own antialiasing and leave a hard edge on a shape
4196    /// drawn to be soft. Outsetting costs a ring of fragments that compute a
4197    /// coverage of zero.
4198    fn draw_analytic(
4199        &mut self,
4200        rect: Rect,
4201        material: Material,
4202        paint: &Paint,
4203    ) -> Result<&mut Self> {
4204        // A pixel for the coverage ramp, plus half the stroke where one is
4205        // traced: an outline straddles the edge, so it reaches outward by half
4206        // its width beyond the shape it belongs to.
4207        let reach = 1.0
4208            + thin_stroke(
4209                self.transform,
4210                analytic_stroke(paint).unwrap_or(0.0),
4211                Zero::IsNotAStroke,
4212            )
4213            .0 / 2.0;
4214        let outset = Rect::new(
4215            rect.left - reach,
4216            rect.top - reach,
4217            rect.right + reach,
4218            rect.bottom + reach,
4219        );
4220        let render_paint = RenderPaint {
4221            material,
4222            filter: paint.color_filter,
4223            blend: paint.blend,
4224            clip: self.clip,
4225            stencil: ClipState::content(self.depth),
4226        };
4227        self.renderer.fill_into(
4228            &mut self.batch,
4229            &outset.to_path(),
4230            self.transform,
4231            &render_paint,
4232        )?;
4233        Ok(self)
4234    }
4235
4236    /// [`Self::draw_analytic`], with the shape's own space carried on the
4237    /// vertices instead of in the material.
4238    ///
4239    /// Separate rather than an `Option` on the one above, because the two say
4240    /// different things: a material that maps clip space itself is one shape's
4241    /// worth of draw, and one that reads `uv` merges with every other placement
4242    /// of the same shape. Only the rounded rectangle takes this route so far --
4243    /// the ellipse and the blurred rectangle still carry their mapping.
4244    fn draw_analytic_local(
4245        &mut self,
4246        rect: Rect,
4247        material: Material,
4248        paint: &Paint,
4249        clip_to_local: [f32; 12],
4250    ) -> Result<&mut Self> {
4251        let reach = 1.0
4252            + thin_stroke(
4253                self.transform,
4254                analytic_stroke(paint).unwrap_or(0.0),
4255                Zero::IsNotAStroke,
4256            )
4257            .0 / 2.0;
4258        let outset = Rect::new(
4259            rect.left - reach,
4260            rect.top - reach,
4261            rect.right + reach,
4262            rect.bottom + reach,
4263        );
4264        let render_paint = RenderPaint {
4265            material,
4266            filter: paint.color_filter,
4267            blend: paint.blend,
4268            clip: self.clip,
4269            stencil: ClipState::content(self.depth),
4270        };
4271        self.renderer.fill_into_local(
4272            &mut self.batch,
4273            &outset.to_path(),
4274            self.transform,
4275            &render_paint,
4276            clip_to_local,
4277        )?;
4278        Ok(self)
4279    }
4280
4281    /// The shadow an object at `elevation` casts, under one light.
4282    ///
4283    /// The rule rather than the picture, which is why this is a call and not a
4284    /// blurred draw a caller assembles: the whole point of an elevation is
4285    /// that everything at the same height casts a consistent shadow, and
4286    /// consistency is what a rule spread across call sites loses first.
4287    ///
4288    /// The model is a single light above and behind the viewer, which is what
4289    /// Impeller uses and what makes a raised object's shadow fall downward on
4290    /// screen. Three things follow from the elevation and nothing else: the
4291    /// shadow is offset downward by it, blurred in proportion to it, and drawn
4292    /// at a quarter of the stated color's alpha before that alpha is adjusted
4293    /// for the color's own luminance.
4294    ///
4295    /// `elevation` is in device pixels, whatever the transform: the shadow
4296    /// falls that far straight down the screen, as upstream's does. Upstream
4297    /// is handed it in logical pixels and multiplies by a device pixel ratio
4298    /// first (`occluder_z = dpr * elevation`), which is a framework concept
4299    /// rather than a rendering one; a caller who has one should apply it here.
4300    ///
4301    /// `transparent_occluder` is accepted and unused, which is what upstream
4302    /// does with it -- `DlDispatcherBase::drawShadow` takes the flag and its
4303    /// drawing code never reads it. It stays on the signature because
4304    /// `dart:ui` has it, and a caller porting a call should not have to find
4305    /// out that one argument went missing.
4306    pub fn draw_shadow(
4307        &mut self,
4308        path: &Path,
4309        color: Color,
4310        elevation: f32,
4311        _transparent_occluder: bool,
4312    ) -> Result<&mut Self> {
4313        if !elevation.is_finite() || elevation <= 0.0 || color.is_invisible() {
4314            // Nothing at ground level: an object resting on the surface casts
4315            // no shadow, which is the same answer as an invisible one.
4316            return Ok(self);
4317        }
4318
4319        let shade = tonal_shadow_color(color);
4320        let affine = self.transform.to_affine();
4321        // The y axis's stretch, not the larger of the two: upstream divides by
4322        // `GetCurrentTransform().GetScale().y`, the length of the transformed
4323        // y basis vector. Without a basis to read -- perspective -- the single
4324        // factor stands in.
4325        let scale_y = affine
4326            .map(|a| a.matrix2.y_axis.length())
4327            .filter(|s| s.is_finite() && *s > 0.0)
4328            .unwrap_or_else(|| {
4329                let s = max_scale_of(self.transform);
4330                if s.is_finite() && s > 0.0 {
4331                    s
4332                } else {
4333                    1.0
4334                }
4335            });
4336        // Elevation gives a kernel radius, which the blur takes as a
4337        // deviation only after converting. Skipping the conversion is the
4338        // larger half of what made a shadow here twice as soft as upstream's.
4339        //
4340        // Divided by the y scale first and converted after, in upstream's
4341        // order: `Radius{kLightRadius * occluder_z / scale.y}` and then
4342        // `Radius::operator Sigma`. A mask blur's sigma is stated in the space
4343        // the drawing is in and grows with the transform, so a shadow whose
4344        // softness comes from an *elevation* rather than from a length would
4345        // grow with it too -- and upstream's does not. The division cancels
4346        // the multiplication the filter applies, leaving a shadow's softness
4347        // fixed in device pixels however large the caster is drawn;
4348        // `a_shadows_softness_is_fixed_in_device_pixels` is the test. This
4349        // used to convert first and divide after, which divides the
4350        // conversion's half pixel by the scale too: a shadow a quarter of a
4351        // pixel sharper than upstream's at a scale of two.
4352        let sigma = sigma_for_radius(LIGHT_RADIUS * elevation / scale_y);
4353        // Straight down the screen by `elevation` device pixels: upstream's
4354        // `PreConcat(MakeTranslation(0, occluder_z))`, which puts the
4355        // translation before the current transform. There is no pre-concat
4356        // here, so the device offset goes back through the transform's linear
4357        // part, inverted, and is applied as an ordinary translation in local
4358        // units. A plain `translate(0, elevation)` moved it `scale` times as
4359        // far, and under a rotation along the rotated axis.
4360        let device_down = Vec2::new(0.0, elevation);
4361        let down = affine
4362            .map(|a| a.matrix2)
4363            .filter(|m| m.determinant().abs() > f32::EPSILON)
4364            .map(|m| m.inverse() * device_down)
4365            .filter(|v| v.is_finite())
4366            .unwrap_or(Vec2::new(0.0, elevation / scale_y));
4367        let paint = Paint::fill(shade).with_mask_blur(sigma);
4368
4369        // The whole shadow, whatever the occluder is, which is what upstream
4370        // draws: `DlDispatcherBase::drawShadow` takes `transparent_occluder`
4371        // and its drawing code never reads it.
4372        //
4373        // This used to punch the caster's outline out of the shadow for an
4374        // opaque one, on the grounds that the part a caster covers is spent.
4375        // The grounds were sound and the result was not worth them. An opaque
4376        // caster drawn over its own shadow is the arrangement the flag
4377        // describes, and there the two are the same picture -- measured at
4378        // zero of sixty-five thousand bytes differing -- while the punch cost a
4379        // layer, so every shadow was five passes where four will do. A
4380        // deviation that produces identical pixels more slowly has nothing to
4381        // recommend it.
4382        self.save();
4383        self.translate(down.x, down.y);
4384        let failure = self.draw_path(path, &paint).err();
4385        self.restore();
4386        match failure {
4387            Some(e) => Err(e),
4388            None => Ok(self),
4389        }
4390    }
4391
4392    /// Fill or stroke a circle.
4393    ///
4394    /// An antialiased solid fill goes through the same distance field a rounded
4395    /// rectangle does, because it is one: a square whose corner radius is half
4396    /// its side has no straight edge left, and the field reduces exactly to the
4397    /// distance from the center less the radius. So a circle costs two
4398    /// triangles and needs no shader of its own, where four cubics flattened to
4399    /// a tolerance cost vertices in proportion to how large it is drawn.
4400    pub fn draw_circle(&mut self, center: Vec2, radius: f32, paint: &Paint) -> Result<&mut Self> {
4401        // NaN named rather than caught by a negated comparison, which reads as
4402        // a typo and which clippy objects to on exactly those grounds.
4403        if radius.is_nan() || radius <= 0.0 {
4404            return Ok(self);
4405        }
4406        let bounds = Rect::new(
4407            center.x - radius,
4408            center.y - radius,
4409            center.x + radius,
4410            center.y + radius,
4411        );
4412        // A circle is a rounded rectangle whose corners are half its side, which
4413        // is how the line below already treats it and how upstream states it:
4414        // `DrawOval` on a square sends `RRectBlurShape(rect, width * 0.5)`.
4415        if let Some((material, pad, drawn)) = self.analytic_rrect_blur_draw(bounds, radius, paint) {
4416            return self.draw_analytic(bounds.outset(pad), material, &drawn);
4417        }
4418        if let Some((material, to_local)) = self.analytic_rrect(bounds, radius, paint) {
4419            return self.draw_analytic_local(bounds, material, paint, to_local);
4420        }
4421        let path = circle_path(center, radius);
4422        self.draw_path(&path, paint)
4423    }
4424
4425    /// Fill or stroke an ellipse inscribed in `bounds`.
4426    ///
4427    /// A circle where the bounds are square, and the shape a rounded rectangle
4428    /// cannot become: past half its shorter side a rounded rectangle stops
4429    /// changing, giving a stadium, where an ellipse keeps curving on both axes.
4430    ///
4431    /// An antialiased solid fill is evaluated per fragment like the other
4432    /// shapes here. Everything else is tessellated from four cubics, which
4433    /// approximate an ellipse exactly as well as they approximate a circle --
4434    /// which is to say closely, and not exactly.
4435    pub fn draw_oval(&mut self, bounds: Rect, paint: &Paint) -> Result<&mut Self> {
4436        if bounds.is_empty() {
4437            return Ok(self);
4438        }
4439        if let Some(material) = self.analytic_ellipse(bounds, paint) {
4440            return self.draw_analytic(bounds, material, paint);
4441        }
4442        let path = oval_path(bounds);
4443        self.draw_path(&path, paint)
4444    }
4445
4446    /// A paint for the fragment-evaluated ellipse, where one applies.
4447    ///
4448    /// The same conditions the rounded rectangle answers to, and for the same
4449    /// reasons.
4450    fn analytic_ellipse(&self, bounds: Rect, paint: &Paint) -> Option<Material> {
4451        if !paint.is_visible() || self.clip.is_some_and(Scissor::is_empty) {
4452            return None;
4453        }
4454        let (stroke, coverage) =
4455            thin_stroke(self.transform, analytic_stroke(paint)?, Zero::IsNotAStroke);
4456        let shader = paint.effective_shader();
4457        let Shader::Solid(color) = &*shader else {
4458            return None;
4459        };
4460        let to_clip = self.target.projection() * self.transform;
4461        let center = Vec2::new(
4462            (bounds.left + bounds.right) / 2.0,
4463            (bounds.top + bounds.bottom) / 2.0,
4464        );
4465        Some(Material::Ellipse {
4466            color: dimmed(*color, coverage),
4467            half_size: [bounds.width() / 2.0, bounds.height() / 2.0],
4468            to_local: invert_to_local(to_clip * Affine2::from_translation(center)),
4469            stroke,
4470        })
4471    }
4472
4473    /// Draw a run of positioned glyphs from one atlas, as a single draw.
4474    ///
4475    /// `atlas_slot` indexes the image table supplied at draw time, and each
4476    /// glyph names where in that atlas its coverage sits. A run is one draw
4477    /// however many glyphs it holds, because the coordinates travel on the
4478    /// vertices rather than in the paint — which is the reason vertices carry
4479    /// them at all, text being the highest draw-count content there is.
4480    ///
4481    /// The paint's color is the text color; its shader is otherwise ignored,
4482    /// since the atlas supplies coverage rather than color. Gradient-filled
4483    /// text needs the run drawn into a layer and the gradient drawn through it,
4484    /// which is a thing a caller can already build out of what is here.
4485    pub fn draw_glyphs(
4486        &mut self,
4487        glyphs: &[PositionedGlyph],
4488        atlas: &Atlas,
4489        atlas_slot: u32,
4490        paint: &Paint,
4491    ) -> Result<&mut Self> {
4492        if glyphs.is_empty() || !paint.is_visible() {
4493            return Ok(self);
4494        }
4495        if self.clip.is_some_and(Scissor::is_empty) {
4496            return Ok(self);
4497        }
4498        // A run does not go through `draw_path` either, so it has to notice
4499        // these itself -- and did not, which made it the third call to accept a
4500        // filter and quietly draw without one.
4501        if !paint.image_filter.is_identity() {
4502            return self.draw_glyphs_filtered(glyphs, atlas, atlas_slot, paint);
4503        }
4504        if paint.mask_blur > 0.0 {
4505            // The same four styles a shape gets, over the run instead. A run is
4506            // coverage times one solid color, which is exactly the case where
4507            // blurring the coverage and blurring the result agree -- so unlike
4508            // a mesh, there is nothing here to refuse. This is how a text
4509            // shadow is drawn.
4510            return self.draw_masked(
4511                Masked::Glyphs {
4512                    glyphs,
4513                    atlas,
4514                    slot: atlas_slot,
4515                },
4516                paint,
4517            );
4518        }
4519
4520        let color = match &*paint.effective_shader() {
4521            Shader::Solid(color) => color.to_array(),
4522            // A run tints one color, so anything else has no meaning here. The
4523            // first stop of a gradient is a guess at what was meant, and a
4524            // guess drawn is worse than a refusal read.
4525            _ => {
4526                return Err(Error::Unsupported(
4527                    "glyphs take a solid color; fill a layer through a gradient instead",
4528                ))
4529            }
4530        };
4531
4532        let to_clip = self.target.projection() * self.transform;
4533        let mut vertices = Vec::with_capacity(glyphs.len() * 4);
4534        let mut indices = Vec::with_capacity(glyphs.len() * 6);
4535        for glyph in glyphs {
4536            let Some(rect) = atlas.get(glyph.key) else {
4537                // A glyph nobody added would sample whatever texel happens to
4538                // sit at the origin, which draws a plausible smudge. Refusing
4539                // names the glyph instead.
4540                return Err(Error::Unsupported(
4541                    "a glyph in this run is not in the atlas",
4542                ));
4543            };
4544            if rect.width == 0 || rect.height == 0 {
4545                // A space occupies no texels and needs no quad, but it still
4546                // traveled through the run rather than being the caller's to
4547                // filter out.
4548                continue;
4549            }
4550
4551            let [u0, v0, u1, v1] = rect.uv(atlas.size());
4552            let [x, y] = glyph.position;
4553            let [w, h] = glyph.size;
4554            let corners = [
4555                ([x, y], [u0, v0]),
4556                ([x + w, y], [u1, v0]),
4557                ([x + w, y + h], [u1, v1]),
4558                ([x, y + h], [u0, v1]),
4559            ];
4560            let base = vertices.len() as u32;
4561            for ([px, py], uv) in corners {
4562                // Homogeneous, so the atlas coordinate beside it is
4563                // interpolated perspective-correctly rather than swimming
4564                // across the quad.
4565                let clip = to_clip.project_homogeneous(Vec2::new(px, py));
4566                vertices.push(Vertex::projected([clip.x, clip.y, clip.z], uv));
4567            }
4568            indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
4569        }
4570        if indices.is_empty() {
4571            return Ok(self);
4572        }
4573
4574        let slot = self.slot_for(TextureSource::Image(atlas_slot));
4575        self.batch.push_mesh(
4576            &vertices,
4577            &indices,
4578            Material::Glyph { color, slot },
4579            paint.color_filter,
4580            paint.blend,
4581            self.clip,
4582            ClipState::content(self.depth),
4583        )?;
4584        Ok(self)
4585    }
4586
4587    /// Draw a mesh of triangles the caller supplied.
4588    ///
4589    /// The one drawing call whose geometry does not come from tessellating a
4590    /// shape, which is why it is also the one that can produce triangles this
4591    /// renderer would never have made: overlapping, degenerate, wound either
4592    /// way. None of that is checked beyond what [`Vertices`] checks at
4593    /// construction, because a mesh is a caller saying what to draw rather
4594    /// than what to draw *around*, and second-guessing it would defeat the
4595    /// point.
4596    ///
4597    /// Not antialiased. Coverage here comes from the rasterizer's own rule
4598    /// rather than from a distance field or a tessellated feather, and the
4599    /// interior edges of a mesh are seams between triangles that must not be
4600    /// feathered at all -- a mesh whose triangles each faded at their borders
4601    /// would show a lattice of its own construction.
4602    ///
4603    /// Texture coordinates, where the mesh carries them, require an image
4604    /// paint: they say where in a texture each vertex reads, and a paint with
4605    /// no texture leaves them meaning nothing. The reverse is allowed -- an
4606    /// image paint with no coordinates maps by position, the same as on any
4607    /// other shape.
4608    pub fn draw_vertices(&mut self, mesh: &Vertices, paint: &Paint) -> Result<&mut Self> {
4609        if mesh.is_empty() || !paint.is_visible() {
4610            return Ok(self);
4611        }
4612        if self.clip.is_some_and(Scissor::is_empty) {
4613            return Ok(self);
4614        }
4615        // The same routing `draw_path` does, and it has to be repeated here
4616        // because a mesh does not go through `draw_path` at all. Left out, an
4617        // image filter on a mesh -- or on an atlas, which is a mesh by the time
4618        // it arrives -- was accepted and silently dropped.
4619        if !paint.image_filter.is_identity() {
4620            return self.draw_vertices_filtered(mesh, paint);
4621        }
4622        if paint.mask_blur > 0.0 {
4623            // A mask blur blurs coverage and then fills through it, so the fill
4624            // has to have a value everywhere the blurred coverage reaches --
4625            // including outside the shape, where the halo is. A paint has one
4626            // there, whether it is a color or a gradient, because a paint is a
4627            // function of position. Per-vertex colors do not: they are defined
4628            // on the mesh's own triangles and nowhere else, and the halo has
4629            // nothing to take its color from.
4630            //
4631            // So the refusal is about where the color comes from rather than
4632            // about meshes. A mesh built from positions alone is filled by the
4633            // paint exactly as a path is, and takes the same route.
4634            if mesh.colors().is_empty() {
4635                return self.draw_masked(Masked::Mesh(mesh), paint);
4636            }
4637            // Refused rather than dropped, and rather than approximated:
4638            // extrapolating vertex colors into the halo would be inventing a
4639            // picture, which is the substitution this renderer refuses.
4640            return Err(Error::Unsupported(
4641                "a mask blur over a mesh with per-vertex colors has no color for \
4642                 its halo; draw the mesh into a blurred layer instead",
4643            ));
4644        }
4645
4646        let textured = !mesh.texture_coords().is_empty();
4647        // An image mesh has a material of its own, which samples the sheet at
4648        // the interpolated coordinate. Every other shader reads its coordinate
4649        // from the fragment's position, and the flag passed to the batch below
4650        // is what redirects it to the vertices instead -- so the material is
4651        // the ordinary one and nothing here has to know which kind it is.
4652        //
4653        // This used to refuse anything but an image, and the refusal said the
4654        // coordinates needed an image paint to read. `dart:ui` reads whatever
4655        // color source the paint carries at a mesh's coordinates, image or not.
4656        //
4657        // It then refused a caller's program alone, on the reasoning that a
4658        // program replaces this renderer's fragment shader outright and so has
4659        // nowhere for a per-vertex coordinate to arrive. That was wrong, and
4660        // wrong about this renderer rather than about upstream: a program
4661        // replaces the *fragment* stage, and the vertex stage it runs behind is
4662        // this renderer's own whatever the fragment does. That stage hands on
4663        // `uv` beside `clip`, and a program declaring the same `VertexOutput`
4664        // -- which one has to, to be a pipeline here at all -- receives both.
4665        //
4666        // So a program reads the mesh's coordinate by reading `in.uv`, and
4667        // chooses, where every built-in shader is told which to use by the flag
4668        // below. `effect_mesh_uv.wgsl` is the fixture that proves it: the
4669        // sibling of `effect.wgsl` differing in one line.
4670        let at_coords = textured && !matches!(paint.shader, Shader::Image { .. });
4671        // A mesh with colors of its own blends the paint's result into them,
4672        // and upstream fades what that blend produced by the paint's alpha:
4673        // `AtlasContents` and the vertices contents both scale their output,
4674        // not their texture. So the material is the paint at full strength
4675        // and the opacity rides on the draw, applied after the blend. Under
4676        // `Modulate` the two orders are one product; under `SrcOver` a sprite
4677        // faded first lets its color show through, which upstream's does not.
4678        //
4679        // Not a caller's program: its fragment stage is its own, and reads
4680        // neither the blend nor this. A mesh without colors blends with none,
4681        // and its paint fades as every other draw's does.
4682        let opacity = paint.effective_opacity();
4683        let fades_after = !mesh.colors().is_empty()
4684            && !matches!(paint.shader, Shader::RuntimeEffect { .. })
4685            && opacity < 1.0;
4686        let full;
4687        let (paint, opacity) = if fades_after {
4688            full = paint.clone().with_opacity(1.0);
4689            (&full, opacity)
4690        } else {
4691            (paint, 1.0)
4692        };
4693        let material = match (&paint.shader, textured) {
4694            (Shader::Image { .. }, true) => self.mesh_material(paint)?,
4695            _ if at_coords => self.material_at_texture_coords(paint),
4696            _ => self.material_for(paint),
4697        };
4698
4699        let to_clip = self.target.projection() * self.transform;
4700        let coords = mesh.texture_coords();
4701        let colors = mesh.colors();
4702        let vertices: Vec<Vertex> = mesh
4703            .positions()
4704            .iter()
4705            .enumerate()
4706            .map(|(i, position)| {
4707                let clip = to_clip.project_homogeneous(*position);
4708                let uv = coords.get(i).copied().unwrap_or(Vec2::ZERO);
4709                let vertex = Vertex::projected([clip.x, clip.y, clip.z], [uv.x, uv.y]);
4710                match colors.get(i) {
4711                    // Premultiplied here rather than in the shader, because
4712                    // what the rasterizer interpolates between two vertices is
4713                    // what gets multiplied in, and interpolating straight color
4714                    // across an edge whose alpha varies gives a color neither
4715                    // end asked for.
4716                    Some(color) => vertex.with_color(premultiplied(*color)),
4717                    None => vertex,
4718                }
4719            })
4720            .collect();
4721
4722        self.batch.push_mesh_tinted(
4723            &vertices,
4724            mesh.indices(),
4725            material,
4726            paint.color_filter,
4727            paint.blend,
4728            self.clip,
4729            ClipState::content(self.depth),
4730            paint.tint_blend,
4731            opacity,
4732            // Where the coordinates say something the material cannot work out
4733            // for itself. An image mesh is excluded because it already reads
4734            // them, through a material of its own; everything else -- a
4735            // gradient, a caller's program -- derives its coordinate from the
4736            // fragment's position unless told otherwise, and this is the
4737            // telling. The material above was built to match.
4738            at_coords,
4739        )?;
4740        Ok(self)
4741    }
4742
4743    /// Draw many pieces of one sheet, each with its own transform, in one draw.
4744    ///
4745    /// This is `draw_vertices` with the mesh built for you, and building it is
4746    /// the part worth not getting wrong: each sprite is a quad running from
4747    /// the origin to its source's size, placed by its transform, with the
4748    /// source rectangle divided by the sheet's size to become the
4749    /// coordinates its corners read. A caller assembling that themselves has
4750    /// four chances per sprite to transpose an axis.
4751    ///
4752    /// One draw for the whole batch: a hundred sprites from one sheet differ
4753    /// only in their vertices, so they have no reason to be a hundred draws.
4754    /// Anything that would split them -- a different sheet, a different paint
4755    /// -- is a second call.
4756    ///
4757    /// A loop over [`Self::draw_vertices`] would end up as one draw too, since
4758    /// a batch merges adjacent draws that differ in nothing. What this saves
4759    /// is the per-sprite arithmetic rather than the draw calls.
4760    ///
4761    /// `sheet` is the size of the uploaded texture in texels, which the paint
4762    /// does not carry: a recording is built without touching a device and has
4763    /// never seen how large the texture is.
4764    ///
4765    /// Each sprite's [`Sprite::color`] goes to its four corners and combines
4766    /// with what the sheet gives there by the paint's
4767    /// [`Paint::tint_blend`], as `dart:ui`'s colors and blend mode do: the
4768    /// sprite the source, its color the destination. [`Paint::opacity`]
4769    /// fades what that produced, as upstream's atlas fades by the paint's
4770    /// alpha, not the sprite before it meets its color.
4771    pub fn draw_atlas(
4772        &mut self,
4773        sprites: &[Sprite],
4774        sheet: Extent2D,
4775        paint: &Paint,
4776    ) -> Result<&mut Self> {
4777        if sprites.is_empty() || !paint.is_visible() {
4778            return Ok(self);
4779        }
4780        if sheet.width == 0 || sheet.height == 0 {
4781            return Err(Error::Unsupported(
4782                "a sprite sheet with no texels has nothing to read",
4783            ));
4784        }
4785        if !sprites.iter().all(|s| s.source.is_finite()) {
4786            return Err(Error::Unsupported(
4787                "a sprite's source rectangle is not a finite number",
4788            ));
4789        }
4790
4791        let texels = Vec2::new(sheet.width as f32, sheet.height as f32);
4792        let mut positions = Vec::with_capacity(sprites.len() * 4);
4793        let mut coords = Vec::with_capacity(sprites.len() * 4);
4794        let mut colors = Vec::with_capacity(sprites.len() * 4);
4795        let mut indices = Vec::with_capacity(sprites.len() * 6);
4796        for sprite in sprites {
4797            let source = &sprite.source;
4798            let size = Vec2::new(source.width, source.height);
4799            let origin = Vec2::new(source.x, source.y);
4800            // Corners in the same order for both, so a coordinate and the
4801            // position it belongs to are written by one step of the loop and
4802            // cannot come apart.
4803            let corners = [
4804                Vec2::ZERO,
4805                Vec2::new(size.x, 0.0),
4806                size,
4807                Vec2::new(0.0, size.y),
4808            ];
4809            let base = positions.len() as u32;
4810            for corner in corners {
4811                positions.push(sprite.transform.transform_point2(corner));
4812                coords.push((origin + corner) / texels);
4813                // The same color at all four corners: a sprite is tinted as a
4814                // whole, and a gradient across one is a mesh rather than a
4815                // sprite.
4816                colors.push(sprite.color);
4817            }
4818            indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
4819        }
4820
4821        let mesh = Vertices::full(VertexMode::Triangles, positions, coords, colors, indices)?;
4822        self.draw_vertices(&mesh, paint)
4823    }
4824
4825    /// The material for a mesh reading a texture at its own coordinates.
4826    ///
4827    /// Separate from [`Self::material_for`] because an image drawn on a shape
4828    /// and an image drawn on a mesh are different materials rather than one
4829    /// material in two modes -- the mapping, and the source rectangle that
4830    /// selects part of a sheet, are both things the vertices have already
4831    /// said. A caller wanting one sprite from a sheet states its texels in the
4832    /// coordinates.
4833    fn mesh_material(&mut self, paint: &Paint) -> Result<Material> {
4834        // The same as a source rectangle, below: the coordinates already say
4835        // where the image lands.
4836        if paint.shader_transform != Transform2D::IDENTITY {
4837            return Err(Error::Unsupported(
4838                "a textured mesh states its own coordinates; put the shader transform in them",
4839            ));
4840        }
4841        let shader = paint.effective_shader();
4842        let Shader::Image {
4843            slot,
4844            alpha,
4845            tile,
4846            tint,
4847            source,
4848            sampling,
4849            ..
4850        } = &*shader
4851        else {
4852            return Err(Error::Unsupported("a mesh material needs an image paint"));
4853        };
4854        // A source rectangle and a per-vertex coordinate are two answers to
4855        // the same question, and applying one on top of the other would mean a
4856        // coordinate of one landed at the rectangle's far edge rather than at
4857        // the texture's. Refused rather than ignored: a caller who set it
4858        // meant something by it, and the mesh is where they say it instead.
4859        if *source != Rect::new(0.0, 0.0, 1.0, 1.0) {
4860            return Err(Error::Unsupported(
4861                "a textured mesh states its own coordinates; put the source rectangle in them",
4862            ));
4863        }
4864        let table_slot = self.slot_for(TextureSource::Image(*slot));
4865        Ok(Material::Mesh {
4866            slot: table_slot,
4867            alpha: *alpha,
4868            tint: tint.to_array(),
4869            tile: *tile,
4870            sampling: *sampling,
4871        })
4872    }
4873
4874    /// Draw a run of points, joined as the mode says.
4875    ///
4876    /// A point is a segment of no length, which is what decides how it looks:
4877    /// the stroke's cap is the whole of the shape. A round cap gives a dot the
4878    /// width across, a square cap a square of that side, and a butt cap --
4879    /// which adds nothing to either end of a segment -- gives nothing at all.
4880    /// That is not a special case being handled; it is the only reading of a
4881    /// zero-length segment that stays consistent with how every other stroke
4882    /// is drawn.
4883    ///
4884    /// Takes the stroke's width even from a paint asking to fill, since there
4885    /// is no interior to fill and a point with no width is not a shape.
4886    pub fn draw_points(
4887        &mut self,
4888        mode: PointMode,
4889        points: &[Vec2],
4890        paint: &Paint,
4891    ) -> Result<&mut Self> {
4892        let stroke = match &paint.style {
4893            Style::Stroke(stroke) => *stroke,
4894            Style::Fill => StrokeStyle::default(),
4895        };
4896        // Negative only, which is upstream's guard -- `PointFieldGeometry`
4897        // refuses `radius_ < 0.0` and widens everything else. A width of zero is
4898        // a point one pixel across, the same reading a zero-width stroke gets.
4899        if !stroke.width.is_finite() || stroke.width < 0.0 {
4900            return Ok(self);
4901        }
4902
4903        match mode {
4904            // One draw for the whole field, which is what upstream's
4905            // `PointFieldGeometry` produces and what this used to fail to.
4906            //
4907            // It used to be a draw per point, and the reason is worth keeping
4908            // because it is not the obvious one. The other two modes below
4909            // issue a call per segment and still come out as one draw: a batch
4910            // merges draws that share a material, and consecutive segments do.
4911            // A point did not, because the analytic circle it went through
4912            // carries its center in `to_local` -- so two points at two places
4913            // were two materials, and no number of them could merge.
4914            //
4915            // `Material::PointField` is the same field with the center taken
4916            // off the paint and put on the vertices, as the unit circle's
4917            // corners in the texture coordinate. Every point is then the same
4918            // material and the field is one draw, with the edge each of them
4919            // had: the shader differentiates the implicit function across the
4920            // pixel rather than forming a distance, and a derivative of an
4921            // interpolated value is as good as one of a computed value.
4922            PointMode::Points => {
4923                let radius = point_radius(self.transform, stroke.width);
4924                if !matches!(stroke.cap, LineCap::Round | LineCap::Square) {
4925                    // A butt cap extends a segment by nothing, and nothing is
4926                    // what a segment of no length becomes.
4927                    return Ok(self);
4928                }
4929                let round = matches!(stroke.cap, LineCap::Round);
4930                // A mask blur or an image filter wants a layer around the
4931                // draw, which is machinery the per-point route already reaches
4932                // through `draw_circle` and this one skips entirely. Two tests
4933                // that walk every call taking a paint caught exactly that: the
4934                // field accepted a blur and drew what it draws without one.
4935                //
4936                // The condition is the same one `analytic_stroke` states for
4937                // the same reason, and it is worth keeping the shape of that
4938                // rule rather than a list: every route that needs a layer has
4939                // to decline here.
4940                if paint.mask_blur > 0.0 || !paint.image_filter.is_identity() {
4941                    return self.draw_points_individually(points, &stroke, paint);
4942                }
4943                let material = self.material_for(paint);
4944                let Material::Solid(color) = material else {
4945                    // A field takes one color, which is what a point field is.
4946                    // Anything else keeps the old route, where each point is
4947                    // its own shape and can carry its own mapping.
4948                    return self.draw_points_individually(points, &stroke, paint);
4949                };
4950
4951                // A round cap's quad is a pixel wider than the disc, for the
4952                // reason `draw_analytic` outsets its own: the coverage ramp
4953                // runs half a pixel either side of the edge, and a quad ending
4954                // exactly on the circle clips the outer half of its own
4955                // antialiasing. Measured without it, ninety-two pixels of the
4956                // frame differed from the same dots drawn one at a time, at
4957                // the four places the circle meets its quad.
4958                //
4959                // The texture coordinate is scaled to match, so that the unit
4960                // circle still falls where the disc's edge is rather than at
4961                // the corner of the widened quad. A square cap is the quad
4962                // itself and takes neither: its coordinates are zero, where
4963                // the field is saturated, so it covers what it is given.
4964                let (extent, coord) = if round {
4965                    (radius + 1.0, (radius + 1.0) / radius.max(1e-6))
4966                } else {
4967                    (radius, 0.0)
4968                };
4969                let to_clip = self.target.projection() * self.transform;
4970                let mut vertices: Vec<Vertex> = Vec::with_capacity(points.len() * 4);
4971                let mut indices: Vec<u32> = Vec::with_capacity(points.len() * 6);
4972                for point in points {
4973                    if !point.is_finite() {
4974                        continue;
4975                    }
4976                    let base = vertices.len() as u32;
4977                    for (dx, dy) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
4978                        let at = Vec2::new(point.x + dx * extent, point.y + dy * extent);
4979                        let clip = to_clip.project_homogeneous(at);
4980                        vertices.push(Vertex::projected(
4981                            [clip.x, clip.y, clip.z],
4982                            [dx * coord, dy * coord],
4983                        ));
4984                    }
4985                    indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
4986                }
4987                if indices.is_empty() {
4988                    return Ok(self);
4989                }
4990                self.batch.push_mesh_tinted(
4991                    &vertices,
4992                    &indices,
4993                    Material::PointField { color },
4994                    paint.color_filter,
4995                    paint.blend,
4996                    self.clip,
4997                    ClipState::content(self.depth),
4998                    paint.tint_blend,
4999                    1.0,
5000                    false,
5001                )?;
5002            }
5003            PointMode::Lines => {
5004                for pair in points.chunks_exact(2) {
5005                    self.draw_line(pair[0], pair[1], paint)?;
5006                }
5007            }
5008            PointMode::Polygon => {
5009                if points.len() >= 2 {
5010                    let mut b = PathBuilder::new();
5011                    b.move_to(points[0]);
5012                    for point in &points[1..] {
5013                        b.line_to(*point);
5014                    }
5015                    self.draw_path(&b.build(), paint)?;
5016                }
5017            }
5018        }
5019        Ok(self)
5020    }
5021
5022    /// The field drawn a point at a time, for a paint a field cannot carry.
5023    ///
5024    /// A point field is one color by construction -- the material holds one --
5025    /// so a gradient or an image paint still goes through the shape each point
5026    /// has, and costs a draw each. That is the old behavior kept for the case
5027    /// it was right for rather than a fallback nobody exercises: `dart:ui`
5028    /// allows any paint on `drawPoints`, and a caller who asks for a gradient
5029    /// across a field should get one.
5030    fn draw_points_individually(
5031        &mut self,
5032        points: &[Vec2],
5033        stroke: &StrokeStyle,
5034        paint: &Paint,
5035    ) -> Result<&mut Self> {
5036        // Widened on the same terms the field route is, so which route a point
5037        // takes stays invisible -- this one is reached for a mask blur, an image
5038        // filter or a shader, none of which changes how small a point may be.
5039        let radius = point_radius(self.transform, stroke.width);
5040        // Filled rather than stroked: what is being drawn is the cap itself,
5041        // and asking the stroker for a segment of no length is asking it for a
5042        // direction that does not exist.
5043        let dot = paint.clone().with_style(Style::Fill);
5044        for point in points {
5045            if !point.is_finite() {
5046                continue;
5047            }
5048            match stroke.cap {
5049                LineCap::Round => {
5050                    self.draw_circle(*point, radius, &dot)?;
5051                }
5052                LineCap::Square => {
5053                    self.draw_rect(
5054                        Rect::new(
5055                            point.x - radius,
5056                            point.y - radius,
5057                            point.x + radius,
5058                            point.y + radius,
5059                        ),
5060                        &dot,
5061                    )?;
5062                }
5063                LineCap::Butt => {}
5064            }
5065        }
5066        Ok(self)
5067    }
5068
5069    /// Draw a finished recording into this one.
5070    ///
5071    /// `dart:ui` calls this `drawPicture`, and it is a smaller thing here than
5072    /// there, which is worth saying plainly. An `SkPicture` is a command list,
5073    /// so replaying one under a new transform re-runs the commands and
5074    /// re-tessellates at the new scale. A [`Recording`] is already tessellated:
5075    /// its paths were flattened at a tolerance taken from the transform in force
5076    /// when they were recorded, and its vertices are in clip space. Magnified,
5077    /// it shows the polygon it was flattened to.
5078    ///
5079    /// So this composes scenes at about the scale they were recorded at. It is
5080    /// not the reuse optimization the same call is elsewhere, and a caller who
5081    /// wants that should re-record.
5082    ///
5083    /// What it costs is a layer, because that is what it is: the recording's
5084    /// passes are taken as they are and its root becomes an image this canvas
5085    /// samples. Nothing is re-recorded and no geometry is touched, which is
5086    /// what makes it cheap and also what makes it unable to re-tessellate.
5087    ///
5088    /// # Slots
5089    ///
5090    /// A recording naming a caller's image by index keeps that index. The two
5091    /// recordings are submitted with one image table, so an index means the
5092    /// same thing in both -- a caller composing recordings that disagree about
5093    /// what image three is has to renumber before recording, which is a thing
5094    /// they can see and this call cannot.
5095    ///
5096    /// Its layers and its baked gradients are renumbered, since those name
5097    /// positions in lists this recording is appending to.
5098    pub fn draw_recording(&mut self, recording: &Recording, paint: &Paint) -> Result<&mut Self> {
5099        if recording.is_empty() || !paint.is_visible() {
5100            return Ok(self);
5101        }
5102        if self.clip.is_some_and(Scissor::is_empty) {
5103            return Ok(self);
5104        }
5105
5106        // Where the passes and ramps being appended will land. Taken before
5107        // anything is pushed, because every index inside the recording is
5108        // relative to lists that start here.
5109        let pass_offset = self.finished.len();
5110        let ramp_offset = self.ramps.len();
5111        self.ramps.extend(recording.ramps.iter().cloned());
5112
5113        for pass in &recording.passes {
5114            let mut pass = pass.clone();
5115            for source in &mut pass.sources {
5116                *source = match *source {
5117                    // A layer names a pass by position in the recording it came
5118                    // from, and that recording's passes are now further along.
5119                    TextureSource::Layer(index) => TextureSource::Layer(index + pass_offset),
5120                    TextureSource::Ramp(index) => TextureSource::Ramp(index + ramp_offset),
5121                    // The caller's own table, which both recordings share.
5122                    TextureSource::Image(index) => TextureSource::Image(index),
5123                };
5124            }
5125            self.finished.push(pass);
5126        }
5127
5128        // The recording's root is the image this canvas now samples, and every
5129        // other pass it brought is a layer feeding that one.
5130        let root = self.finished.len() - 1;
5131        let slot = self.slot_for(TextureSource::Layer(root));
5132
5133        // The recording rendered at its own extent, and it lands here at that
5134        // size with its top-left at the origin of the current transform. A
5135        // recording is a picture rather than a shape, so it has no bounds of
5136        // its own to place -- where it goes is what the transform says.
5137        let extent = recording.extent;
5138        let placement = Rect::new(0.0, 0.0, extent.width as f32, extent.height as f32);
5139        // The mapping from a fragment's clip position back to a texel of the
5140        // recording, which is the same pair a layer composite builds -- except
5141        // that a layer sits at a known place in its parent and a recording is
5142        // placed by the transform, so the mapping is built from that instead.
5143        //
5144        // Clip space runs from -1 to 1 and upward, so the axes are halved and Y
5145        // is negated. Inverting the transform is what carries a fragment back
5146        // into the recording's own coordinates; a transform that folds the
5147        // plane has no inverse, and the geometry collapses with it, so both
5148        // halves go together and nothing is drawn.
5149        let to_clip = self.target.projection() * self.transform;
5150        if to_clip.determinant().abs() <= f32::EPSILON {
5151            return Ok(self);
5152        }
5153        // The recording's texture spans its own extent from the origin, so
5154        // that rectangle carried through the transform is the placement, and
5155        // the mapping the shader wants is its inverse.
5156        let picture_to_clip =
5157            to_clip * Affine2::from_scale(Vec2::new(extent.width as f32, extent.height as f32));
5158        if !picture_to_clip.is_finite() {
5159            return Ok(self);
5160        }
5161        let material = Material::Image {
5162            to_local: invert_to_local(picture_to_clip),
5163            slot,
5164            alpha: 1.0,
5165            tile: [TileMode::Clamp; 2],
5166            // At its own size a texel lands on a pixel, and under a transform
5167            // the recording is resampled -- which is what a picture drawn
5168            // scaled means, and the same answer a matrix image filter gives.
5169            sampling: Sampling::Linear,
5170            source: [0.0, 0.0, 1.0, 1.0],
5171            tint: [1.0, 1.0, 1.0, 1.0],
5172        };
5173        let render_paint = RenderPaint {
5174            material,
5175            filter: paint.color_filter,
5176            blend: paint.blend,
5177            clip: self.clip,
5178            stencil: ClipState::content(self.depth),
5179        };
5180        self.renderer.fill_into(
5181            &mut self.batch,
5182            &placement.to_path(),
5183            self.transform,
5184            &render_paint,
5185        )?;
5186        Ok(self)
5187    }
5188
5189    /// Fill the ring between two rounded rectangles.
5190    ///
5191    /// One path of two contours filled by the even-odd rule, which is what
5192    /// makes the inner one a hole rather than a second ring drawn on top. A
5193    /// caller could assemble this, and the reason not to leave them to it is
5194    /// the rule: two contours wound the same way fill solid under the nonzero
5195    /// rule and hollow under even-odd, and which one a border needs is not
5196    /// something to rediscover per call site.
5197    pub fn draw_drrect(
5198        &mut self,
5199        outer: Rect,
5200        outer_radius: f32,
5201        inner: Rect,
5202        inner_radius: f32,
5203        paint: &Paint,
5204    ) -> Result<&mut Self> {
5205        if outer.is_empty() {
5206            return Ok(self);
5207        }
5208        self.draw_drrect_with_radii(
5209            outer,
5210            [[outer_radius; 2]; 4],
5211            inner,
5212            [[inner_radius; 2]; 4],
5213            paint,
5214        )
5215    }
5216
5217    /// A ring between two rounded rectangles whose corners need not match.
5218    ///
5219    /// [`Self::draw_drrect`] with the eight numbers each, and the same shape:
5220    /// two contours filled even-odd, which is what makes the inner one a hole.
5221    /// Each rectangle's radii are fitted to it on its own, since a ring is two
5222    /// rounded rectangles and not one shape with a thickness.
5223    pub fn draw_drrect_with_radii(
5224        &mut self,
5225        outer: Rect,
5226        outer_radii: RoundingRadii,
5227        inner: Rect,
5228        inner_radii: RoundingRadii,
5229        paint: &Paint,
5230    ) -> Result<&mut Self> {
5231        if outer.is_empty() {
5232            return Ok(self);
5233        }
5234        let mut b = PathBuilder::new().with_fill_rule(FillRule::EvenOdd);
5235        outer.add_rounded_contour_with_radii(&mut b, outer.fitted_radii(outer_radii));
5236        if !inner.is_empty() {
5237            inner.add_rounded_contour_with_radii(&mut b, inner.fitted_radii(inner_radii));
5238        }
5239        self.draw_path(&b.build(), paint)
5240    }
5241
5242    /// Fill everything the clip still admits.
5243    ///
5244    /// `dart:ui` calls this `drawPaint`. What it fills is the clip rather than
5245    /// the target, which is why it is a call and not a rectangle a caller
5246    /// writes: the rectangle they would need is the clip's bounds carried back
5247    /// through the current transform, and getting that wrong is invisible
5248    /// until a transform is in force.
5249    ///
5250    /// The bounds are conservative, so this may cover more than the clip
5251    /// admits -- and the clip then removes the excess, which is what makes a
5252    /// superset the safe direction to be wrong in.
5253    pub fn draw_paint(&mut self, paint: &Paint) -> Result<&mut Self> {
5254        let bounds = self.local_clip_bounds();
5255        if bounds.is_empty() {
5256            return Ok(self);
5257        }
5258        self.draw_rect(bounds, paint)
5259    }
5260
5261    /// Fill everything the clip admits with one color.
5262    ///
5263    /// `dart:ui` calls this `drawColor`. Distinct from [`Self::clear`], which
5264    /// replaces the whole target and ignores the clip: this is a draw, so it
5265    /// blends and it obeys what is in force.
5266    pub fn draw_color(&mut self, color: Color, blend: BlendMode) -> Result<&mut Self> {
5267        self.draw_paint(&Paint::fill(color).with_blend(blend))
5268    }
5269
5270    /// Draw an image stretched by its middle, keeping its corners.
5271    ///
5272    /// `dart:ui` calls this `drawImageNine`, and it is the shape every
5273    /// resizable panel with a border is made of. `center` is the part of the
5274    /// image, in texels, that may stretch; what surrounds it is divided into
5275    /// eight pieces that stretch along one axis or neither.
5276    ///
5277    /// A caller could write the nine draws. The reason not to leave them to it
5278    /// is the rule rather than the arithmetic: which pieces stretch in which
5279    /// direction is the whole of what a nine-patch means, and nine call sites
5280    /// are nine chances to stretch a corner.
5281    ///
5282    /// The paint supplies the blend, the filters, its opacity and whether the
5283    /// edges are antialiased; its shader is replaced, since each of the nine
5284    /// pieces needs its own. The opacity fades each piece, which is the same
5285    /// picture as fading the whole: the pieces tile the destination without
5286    /// overlapping. Upstream's `NinePatchConverter` draws nine image
5287    /// rectangles with the one paint, alpha included, and no layer.
5288    ///
5289    /// A center reaching an edge leaves pieces of no width or height, and
5290    /// those are skipped rather than drawn empty. A center outside the image
5291    /// entirely is refused, since there is no reading of it that leaves nine
5292    /// pieces.
5293    pub fn draw_image_nine(
5294        &mut self,
5295        slot: u32,
5296        size: Extent2D,
5297        center: Rect,
5298        into: Rect,
5299        paint: &Paint,
5300    ) -> Result<&mut Self> {
5301        if size.width == 0 || size.height == 0 || into.is_empty() {
5302            return Ok(self);
5303        }
5304        let (w, h) = (size.width as f32, size.height as f32);
5305        if center.left < 0.0
5306            || center.top < 0.0
5307            || center.right > w
5308            || center.bottom > h
5309            || center.right < center.left
5310            || center.bottom < center.top
5311        {
5312            return Err(Error::Unsupported(
5313                "a nine-patch center must lie within the image it divides",
5314            ));
5315        }
5316        if paint.mask_blur > 0.0 {
5317            // A nine-patch is nine quads, and each is drawn on its own. A mask
5318            // blur asked for here would soften each of them separately -- nine
5319            // haloes with seams between them rather than one softened patch --
5320            // which is not what was asked for and is not worth guessing at.
5321            //
5322            // Refused deliberately, because it used to be refused by accident:
5323            // the pieces are drawn with an image paint, and a mask blur over
5324            // anything that varied was refused wholesale further down. That is
5325            // no longer true, so the reason has to live where it applies.
5326            return Err(Error::Unsupported(
5327                "a mask blur over a nine-patch; its pieces are drawn separately \
5328                 and would each be softened on their own",
5329            ));
5330        }
5331
5332        // The three spans along each axis, in texels and then in the
5333        // destination. The outer two keep their size and the middle takes
5334        // whatever is left, which is the whole of the rule.
5335        let source_x = [0.0, center.left, center.right, w];
5336        let source_y = [0.0, center.top, center.bottom, h];
5337        let left_keep = center.left;
5338        let right_keep = w - center.right;
5339        let top_keep = center.top;
5340        let bottom_keep = h - center.bottom;
5341        // A destination too small to hold both fixed edges would give the
5342        // middle a negative size, so the edges are scaled down together rather
5343        // than one of them overrunning the other.
5344        let squeeze_x = ((into.right - into.left) / (left_keep + right_keep)).min(1.0);
5345        let squeeze_y = ((into.bottom - into.top) / (top_keep + bottom_keep)).min(1.0);
5346        let dest_x = [
5347            into.left,
5348            into.left + left_keep * squeeze_x,
5349            into.right - right_keep * squeeze_x,
5350            into.right,
5351        ];
5352        let dest_y = [
5353            into.top,
5354            into.top + top_keep * squeeze_y,
5355            into.bottom - bottom_keep * squeeze_y,
5356            into.bottom,
5357        ];
5358
5359        // One mesh rather than nine draws, which is what this used to be.
5360        //
5361        // Each patch reads a different part of the image into a different
5362        // place, and the obvious way to say that is a shader per patch with
5363        // its own source rectangle -- nine paints, nine draws. Carrying the
5364        // coordinates on the vertices instead says the same thing in one
5365        // draw, which is how `draw_atlas` has always done it, and a nine-patch
5366        // is the same shape of work: several quads out of one sheet.
5367        //
5368        // What made the nine separate is that a per-draw source rectangle also
5369        // *clamps* to itself, so a patch could not sample its neighbor. Merged
5370        // naively that clamping goes and the seams bleed -- measured, twelve
5371        // hundred pixels of a hundred-and-twenty-eight-square frame, by as
5372        // much as a hundred and seventy levels, which on the one primitive
5373        // whose whole purpose is stretching without artifacts is not a
5374        // trade worth making.
5375        //
5376        // The half-texel inset below is what buys it back. A linear sample
5377        // reaches exactly half a texel past its coordinate, so pulling each
5378        // patch's edge in by that much removes the reach across the boundary
5379        // rather than compensating for it. With it the merged draw is
5380        // byte-identical to the nine: zero pixels differ, at the same worst
5381        // case of zero. The sampling is this call's own rather than the
5382        // caller's, and is linear, which is what makes half a texel the right
5383        // number rather than a guess.
5384        let (half_u, half_v) = (0.5 / w, 0.5 / h);
5385        let mut positions = Vec::with_capacity(36);
5386        let mut coords = Vec::with_capacity(36);
5387        let mut indices = Vec::with_capacity(54);
5388        for row in 0..3 {
5389            for column in 0..3 {
5390                let source = Rect::new(
5391                    source_x[column] / w,
5392                    source_y[row] / h,
5393                    source_x[column + 1] / w,
5394                    source_y[row + 1] / h,
5395                );
5396                let destination = Rect::new(
5397                    dest_x[column],
5398                    dest_y[row],
5399                    dest_x[column + 1],
5400                    dest_y[row + 1],
5401                );
5402                if source.is_empty() || destination.is_empty() {
5403                    continue;
5404                }
5405                // Inset toward the middle, and never past it: a patch one texel
5406                // across has nothing to give up, and an inset that crossed
5407                // would turn the quad inside out.
5408                let mid_u = (source.left + source.right) * 0.5;
5409                let mid_v = (source.top + source.bottom) * 0.5;
5410                let u0 = (source.left + half_u).min(mid_u);
5411                let u1 = (source.right - half_u).max(mid_u);
5412                let v0 = (source.top + half_v).min(mid_v);
5413                let v1 = (source.bottom - half_v).max(mid_v);
5414
5415                let base = positions.len() as u32;
5416                positions.extend([
5417                    Vec2::new(destination.left, destination.top),
5418                    Vec2::new(destination.right, destination.top),
5419                    Vec2::new(destination.right, destination.bottom),
5420                    Vec2::new(destination.left, destination.bottom),
5421                ]);
5422                coords.extend([
5423                    Vec2::new(u0, v0),
5424                    Vec2::new(u1, v0),
5425                    Vec2::new(u1, v1),
5426                    Vec2::new(u0, v1),
5427                ]);
5428                indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
5429            }
5430        }
5431        if positions.is_empty() {
5432            return Ok(self);
5433        }
5434
5435        let mesh = crate::vertices::Vertices::indexed(
5436            crate::vertices::VertexMode::Triangles,
5437            positions,
5438            coords,
5439            indices,
5440        )?;
5441        // The paint supplies everything but the shader -- its blend, its
5442        // filters, whether it antialiases -- and the shader is the sheet, read
5443        // by the coordinates the vertices carry.
5444        // The paint's own shader is replaced, and its transform with it.
5445        let painted = paint
5446            .clone()
5447            .with_shader(Shader::Image {
5448                slot,
5449                rect: into,
5450                alpha: 1.0,
5451                tile: [TileMode::Clamp; 2],
5452                source: Rect::new(0.0, 0.0, 1.0, 1.0),
5453                tint: Color::WHITE,
5454                sampling: Sampling::Linear,
5455            })
5456            .with_shader_transform(Transform2D::IDENTITY);
5457        self.draw_vertices(&mesh, &painted)
5458    }
5459
5460    /// A line, and for a hairline one snapped to a pixel.
5461    ///
5462    /// The snap is the third part of upstream's minimum-size rule and the one
5463    /// that decides whether a hairline *looks* like one. A line one pixel wide
5464    /// whose center sits on a pixel boundary covers half of each of the two rows
5465    /// it straddles, so it draws gray and two pixels soft; the same line centered
5466    /// in a row covers it and draws black and one pixel crisp. Upstream moves it:
5467    /// `LineGeometry::GetPositionBuffer` carries the endpoints into device space,
5468    /// drops the transform, and rounds the constant coordinate to a half with
5469    /// `RoundToHalf` -- which is a pixel's middle.
5470    ///
5471    /// Gated exactly as upstream gates it, on `width_ == 0.f` and
5472    /// `IsTranslationScaleOnly`. A width the caller stated is a width to respect,
5473    /// and under a rotation or a shear no axis-aligned line stays one.
5474    ///
5475    /// Narrower than upstream in one way, which is deliberate: a paint wanting a
5476    /// layer keeps the ordinary path. A mask blur's sigma is stated in user space
5477    /// and this draws in device space, so the two would disagree under a scale --
5478    /// and a snap is worth half a pixel, not a wrong blur.
5479    pub fn draw_line(&mut self, from: Vec2, to: Vec2, paint: &Paint) -> Result<&mut Self> {
5480        if let Some((p0, p1)) = self.hairline_snap(from, to, paint) {
5481            let mut b = PathBuilder::new();
5482            b.move_to(p0).line_to(p1);
5483            let path = b.build();
5484            // Drawn in device space, so the widening reads a basis of one and
5485            // gives exactly the pixel the snap aligned it to.
5486            let held = self.transform;
5487            self.transform = Transform2D::IDENTITY;
5488            let drawn = self.draw_path(&path, paint).map(|_| ());
5489            self.transform = held;
5490            drawn?;
5491            return Ok(self);
5492        }
5493        let mut b = PathBuilder::new();
5494        b.move_to(from).line_to(to);
5495        let path = b.build();
5496        self.draw_path(&path, paint)
5497    }
5498
5499    /// The device-space endpoints of a hairline worth snapping, or `None`.
5500    ///
5501    /// `None` covers every case that keeps the ordinary path: a stated width, a
5502    /// transform that is not a translation and a scale, a paint that wants a
5503    /// layer, and a line that is not axis-aligned once transformed.
5504    fn hairline_snap(&self, from: Vec2, to: Vec2, paint: &Paint) -> Option<(Vec2, Vec2)> {
5505        let Style::Stroke(stroke) = &paint.style else {
5506            return None;
5507        };
5508        if stroke.width != 0.0 {
5509            return None;
5510        }
5511        if paint.mask_blur > 0.0 || !paint.image_filter.is_identity() {
5512            return None;
5513        }
5514        // A solid color only, and this is the guard that matters most. Every
5515        // other shader is *mapped* by the transform -- a gradient's stops are
5516        // stated in the space the draw was recorded in, an image's source
5517        // rectangle likewise -- and this draw hands the batch an identity
5518        // transform, so the mapping would be taken without the scale. Measured
5519        // while writing this: a hairline under a doubling read its gradient at
5520        // sixteen per cent where the same line a pixel wide read it at four.
5521        //
5522        // Such a hairline keeps the ordinary path and stays half a pixel off
5523        // center, which is the right way round: a snap is worth half a pixel,
5524        // and a shader read in the wrong place is worth nothing.
5525        if !matches!(paint.shader, Shader::Solid(_)) {
5526            return None;
5527        }
5528        let affine = self.transform.to_affine()?;
5529        // A translation and a scale, which is what leaves an axis-aligned line
5530        // axis-aligned. Read off the matrix rather than tracked, so a caller who
5531        // arrived here through `concat` is judged on what they actually have.
5532        let m = affine.matrix2;
5533        if m.x_axis.y != 0.0 || m.y_axis.x != 0.0 {
5534            return None;
5535        }
5536        let (p0, p1) = (affine.transform_point2(from), affine.transform_point2(to));
5537        if !p0.is_finite() || !p1.is_finite() {
5538            return None;
5539        }
5540        // A pixel's middle, which is where a one-pixel line has to sit to cover
5541        // one pixel. Upstream's `RoundToHalf`.
5542        let to_half = |v: f32| v.floor() + 0.5;
5543        // Vertical first, matching upstream's order, and either branch leaves
5544        // the other coordinate alone -- the line's length is the caller's.
5545        if (p0.x - p1.x).abs() < CLOSE_ENOUGH {
5546            let x = to_half(p0.x);
5547            return Some((Vec2::new(x, p0.y), Vec2::new(x, p1.y)));
5548        }
5549        if (p0.y - p1.y).abs() < CLOSE_ENOUGH {
5550            let y = to_half(p0.y);
5551            return Some((Vec2::new(p0.x, y), Vec2::new(p1.x, y)));
5552        }
5553        None
5554    }
5555
5556    /// Close a layer: file its pass, and composite it onto the parent.
5557    /// The device-space rectangle a finished layer's draws actually cover.
5558    ///
5559    /// Read off the geometry rather than accumulated draw by draw, because the
5560    /// geometry is what gets rasterized. Anything covering the whole target --
5561    /// a `clear`, a fill the size of the frame -- has a quad that says so, so
5562    /// the cases upstream has to name as "unbounded content" need no special
5563    /// case here: their coverage comes out as the whole target and nothing is
5564    /// narrowed.
5565    ///
5566    /// Vertices are homogeneous clip positions for `target`, so this is the
5567    /// inverse of the projection they went through:
5568    /// `viewport_projection` maps a device offset `d` to `2d/extent - 1` in x
5569    /// and `1 - 2d/extent` in y.
5570    ///
5571    /// `None` where there is no geometry, and where any vertex sits at or past
5572    /// the vanishing line -- the first has nothing to bound, and the second has
5573    /// no finite bound to give.
5574    fn covered(batch: &Batch, target: Target) -> Option<Rect> {
5575        let (w, h) = (target.extent.width as f32, target.extent.height as f32);
5576        let (mut left, mut top) = (f32::INFINITY, f32::INFINITY);
5577        let (mut right, mut bottom) = (f32::NEG_INFINITY, f32::NEG_INFINITY);
5578        for vertex in batch.vertices() {
5579            let [x, y, w_clip] = vertex.position;
5580            // The rasterizer divides by this, so a vertex on the vanishing line
5581            // has no device position at all and one just past it has a position
5582            // on the wrong side. Neither can be bounded, and the honest answer
5583            // is to narrow nothing.
5584            if !w_clip.is_finite() || w_clip.abs() <= 1e-6 || !x.is_finite() || !y.is_finite() {
5585                return None;
5586            }
5587            let dx = (x / w_clip + 1.0) * 0.5 * w;
5588            let dy = (1.0 - y / w_clip) * 0.5 * h;
5589            left = left.min(dx);
5590            right = right.max(dx);
5591            top = top.min(dy);
5592            bottom = bottom.max(dy);
5593        }
5594        if !(right > left && bottom > top) {
5595            return None;
5596        }
5597        Some(Rect::new(
5598            target.origin.x + left,
5599            target.origin.y + top,
5600            target.origin.x + right,
5601            target.origin.y + bottom,
5602        ))
5603    }
5604
5605    /// The target a layer's content would fit in, if it is worth narrowing to.
5606    ///
5607    /// `None` keeps the target the layer was opened with, which is the whole
5608    /// parent. That is the answer whenever the content covers it anyway, and
5609    /// whenever the arithmetic cannot be trusted to cover everything the pass
5610    /// will draw.
5611    fn narrowed(
5612        &self,
5613        batch: &Batch,
5614        filter: Option<&ImageFilter>,
5615        paint: Layer,
5616        basis: BlurBasis,
5617        layer: Target,
5618    ) -> Option<Target> {
5619        // A layer composited with a mode that changes the destination where the
5620        // source drew nothing has to cover everything it might affect, not just
5621        // what it covered. `DstIn` is the one that shows it: narrowed to its
5622        // content, it stops taking the alpha out of everything outside that,
5623        // and a mask leaves the rest of the picture opaque.
5624        //
5625        // The same condition upstream spells `flood_output_coverage` in
5626        // `ComputeSaveLayerCoverage`, over the same nine modes.
5627        if paint.blend.is_destructive() {
5628            return None;
5629        }
5630        let content = Self::covered(batch, layer)?;
5631        // The same expansion the caller-bounded path makes, and for the same
5632        // reason: the content is where the draws are, and how far the layer's
5633        // own blur carries them past that is this renderer's arithmetic.
5634        let reach = paint.reach(basis);
5635        let (min, max) = (
5636            Vec2::new(content.left - reach.x, content.top - reach.y),
5637            Vec2::new(content.right + reach.x, content.bottom + reach.y),
5638        );
5639        // A filter given to the layer as a whole reaches past what it is
5640        // handed, and by how much is the filter's own arithmetic rather than
5641        // anything this can assume: a composition asks both halves, a matrix
5642        // carrying content across the vanishing line widens to everything, and
5643        // a color filter needs exactly what it was given. `covering` is the
5644        // same question a draw carrying an image filter already asks before it
5645        // opens its own layer.
5646        //
5647        // After the layer's own blur and morphology, because that is the order
5648        // `finish_layer` applies them in: the filter sees what those produced.
5649        let (min, max) = match filter {
5650            Some(filter) => filter.covering(min, max, &|sigma| basis.reach(sigma)),
5651            None => (min, max),
5652        };
5653        let left = min.x.floor().max(layer.origin.x);
5654        let top = min.y.floor().max(layer.origin.y);
5655        let right = max.x.ceil().min(layer.origin.x + layer.extent.width as f32);
5656        let bottom = max
5657            .y
5658            .ceil()
5659            .min(layer.origin.y + layer.extent.height as f32);
5660        if !(right > left && bottom > top) {
5661            return None;
5662        }
5663        let narrowed = Target {
5664            origin: Vec2::new(left, top),
5665            extent: Extent2D::new((right - left) as u32, (bottom - top) as u32),
5666        };
5667        // Nothing gained, and a viewport that offsets by zero into a target of
5668        // the same size is a slower way to spell what it already was.
5669        if narrowed.extent == layer.extent {
5670            return None;
5671        }
5672        Some(narrowed)
5673    }
5674
5675    fn finish_layer(&mut self, frame: LayerFrame) {
5676        // Read before the frame is taken apart below, and only these two are
5677        // needed: whether a whole-layer filter is in play, and the layer's own
5678        // blur and morphology, which decide how far past its content the pass
5679        // will draw.
5680        let (filter, paint) = (frame.filter.clone(), frame.paint);
5681        let mut batch = std::mem::replace(&mut self.batch, frame.batch);
5682        let sources = std::mem::replace(&mut self.sources, frame.sources);
5683
5684        // A layer clears to transparent rather than to the frame's background:
5685        // it is composited over what is already there, so anywhere it drew
5686        // nothing must contribute nothing. Clearing to the background instead
5687        // would paint an opaque rectangle over the parent.
5688        let opened = self.target;
5689        // What the layer's draws turned out to cover. A layer opened with no
5690        // bounds was given the whole parent, because nothing was known then
5691        // about where its content would land; now the content is recorded and
5692        // its own geometry says. Narrowing here rather than at `save_layer` is
5693        // what makes the derived bound possible at all.
5694        //
5695        // The geometry is *not* rewritten to suit the smaller target -- it is
5696        // in clip space, and so are the materials, and a radial gradient's
5697        // center among them. The pass keeps the space it was recorded against
5698        // and carries a viewport that lands it on the narrowed target, which
5699        // crops instead of scaling. See `PassViewport`.
5700        let layer = match self.narrowed(&batch, filter.as_ref(), paint, frame.blur_basis, opened) {
5701            Some(narrowed) => {
5702                let (dx, dy) = (
5703                    (narrowed.origin.x - opened.origin.x) as u32,
5704                    (narrowed.origin.y - opened.origin.y) as u32,
5705                );
5706                // The one recorded thing the move reaches: a scissor is in
5707                // target pixels where the geometry is in clip space.
5708                batch.rebase_scissors(dx, dy, narrowed.extent);
5709                narrowed
5710            }
5711            None => opened,
5712        };
5713        let viewport = (layer.extent != opened.extent).then(|| PassViewport {
5714            offset: [
5715                layer.origin.x - opened.origin.x,
5716                layer.origin.y - opened.origin.y,
5717            ]
5718            .map(|v| -v),
5719            extent: opened.extent,
5720        });
5721        self.aim_at(frame.parent);
5722
5723        if !self.keep_hidden_draws {
5724            batch.cull_occluded(layer.extent);
5725        }
5726        self.finished.push(Pass {
5727            batch,
5728            descriptor: PassDescriptor {
5729                clear: Some([0.0; 4]),
5730                samples: self.pass_samples(),
5731                viewport,
5732            },
5733            sources,
5734            extent: layer.extent,
5735        });
5736        // After the pass above, which is the one the layer's own draws went
5737        // into, and before the composite below, which is an image quad that
5738        // multisampling cannot change.
5739        self.anti_alias = frame.anti_alias;
5740        self.seeded_by_redraw = frame.seeded_by_redraw;
5741        let mut index = self.finished.len() - 1;
5742        if frame.paint.blur.max_element() > 0.0 {
5743            index = self.blur_passes(index, layer, frame.paint.blur, frame.blur_basis);
5744        }
5745        // After the blur, because that is the order the reach above assumes
5746        // when a layer asks for both: the blur softens the content and the
5747        // morphology then works on what the blur produced.
5748        if let Some(morphology) = frame.paint.morphology {
5749            index = self.morphology_passes(index, layer, morphology, frame.blur_basis);
5750        }
5751        // Last, so a filter given to the layer as a whole sees whatever the
5752        // layer's own fields produced rather than the other way round. That is
5753        // the order a composition states: the outermost filter is peeled first
5754        // and becomes this layer, and anything inner was applied by the draw
5755        // inside it.
5756        //
5757        // The failure is swallowed rather than returned, and it is the one
5758        // place in this file that does so: `restore` has no result, and the
5759        // only filter that can refuse here is a matrix, which the two callers
5760        // that can supply one already refuse before opening the layer. So this
5761        // is unreachable rather than ignored.
5762        if let Some(filter) = frame.filter.clone() {
5763            if let Ok(filtered) = self.filter_passes(index, layer, &filter, frame.blur_basis) {
5764                index = filtered;
5765            }
5766        }
5767        let slot = self.slot_for(TextureSource::Layer(index));
5768
5769        // Where the layer sits in the parent's clip space, and how much of that
5770        // space one unit of the layer's texture spans. Clip space runs from -1
5771        // to 1 and upward, so the axes are halved and Y is negated; the ratio
5772        // of the two extents is what makes a layer smaller than its parent
5773        // sample across its own full width rather than a fraction of it.
5774        //
5775        // For a full-size layer this comes out to the identity mapping between
5776        // the target and the image — origin at the top-left of clip space,
5777        // axes halved — which is what it was before bounds existed.
5778        let parent = frame.parent;
5779        let offset = layer.origin - parent.origin;
5780        let anchor = Vec2::new(
5781            -1.0 + 2.0 * offset.x / parent.extent.width as f32,
5782            1.0 - 2.0 * offset.y / parent.extent.height as f32,
5783        );
5784        let scale = Mat2::from_diagonal(Vec2::new(
5785            0.5 * parent.extent.width as f32 / layer.extent.width as f32,
5786            -0.5 * parent.extent.height as f32 / layer.extent.height as f32,
5787        ));
5788        // Stated in the direction the shader reads it: a fragment's clip
5789        // position to the texel it samples, with the anchor inside the matrix
5790        // rather than packed beside it.
5791        let clip_to_texture = Affine2::from_mat2(scale) * Affine2::from_translation(-anchor);
5792        // A layer asking to be transformed on the way back needs both halves
5793        // moved, and moving only the geometry is the mistake worth naming: the
5794        // mapping below carries a fragment's clip position to a texel, so
5795        // geometry moved without it shows the layer through a window that
5796        // moved rather than showing a layer that moved.
5797        // A matrix that folds the plane has no inverse, so there is no mapping
5798        // saying which texel a fragment reads -- and no geometry either, since
5799        // the rectangle collapses to a line. Both halves are dropped together:
5800        // dropping only the mapping leaves a layer drawn through a singular
5801        // matrix, which is nothing at all, and the fallback would be invisible.
5802        //
5803        // The matrix is stated in device pixels and the mapping is in clip
5804        // space, so it is conjugated into clip space and composed ahead of the
5805        // mapping in inverse. Both are resolved here, once, rather than tested
5806        // in one place and taken in another -- the geometry below moves by the
5807        // first and the mapping by the second, and a pair either exists or
5808        // neither half does.
5809        let projection = self.target.projection();
5810        let placement = frame.paint.matrix.and_then(|matrix| {
5811            let in_clip = projection * matrix * projection.inverse()?;
5812            in_clip.is_finite().then_some(())?;
5813            Some((matrix, in_clip.inverse()?))
5814        });
5815        let clip_to_texture = Transform2D::from(clip_to_texture);
5816        let clip_to_texture = match placement {
5817            None => clip_to_texture,
5818            Some((_, undo)) => clip_to_texture * undo,
5819        };
5820        let material = Material::Image {
5821            to_local: to_local_columns(clip_to_texture),
5822            slot,
5823            alpha: frame.paint.alpha,
5824            tile: [TileMode::Clamp; 2],
5825            // A layer composites at its own size, so nothing is between texels
5826            // to choose between.
5827            sampling: Sampling::Linear,
5828            source: [0.0, 0.0, 1.0, 1.0],
5829            tint: [1.0, 1.0, 1.0, 1.0],
5830        };
5831        let paint = RenderPaint {
5832            material,
5833            filter: frame.paint.color_filter,
5834            blend: frame.paint.blend,
5835            clip: self.clip,
5836            stencil: ClipState::content(self.depth),
5837        };
5838        // Exactly the layer's own rectangle, stated in device pixels and drawn
5839        // through the identity: a layer's contents are already where they
5840        // belong, the transform having been applied to the shapes inside it
5841        // rather than again to the finished image. Covering more than the layer
5842        // would sample outside it, which the clamped sampler answers by
5843        // smearing the edge texels across the rest of the frame.
5844        let whole = layer.path();
5845        let _ = self.renderer.fill_into(
5846            &mut self.batch,
5847            &whole,
5848            placement.map_or(Transform2D::IDENTITY, |(matrix, _)| matrix),
5849            &paint,
5850        );
5851    }
5852
5853    /// Run an image filter over a pass, and answer which pass now holds it.
5854    ///
5855    /// The one place that knows how each kind of filter becomes passes, so a
5856    /// caller with an `ImageFilter` and a pass does not have to. A composition
5857    /// is its inner half then its outer, which is what composing means and is
5858    /// the order `peel` takes them apart in.
5859    ///
5860    /// A matrix does not become a pass. Every other kind reads its input where
5861    /// the fragment is and writes there; a matrix *moves* the image, so as a
5862    /// pass it would need a target sized for where the content went rather than
5863    /// where it was. A backdrop's matrix never gets here -- `backdrop_pass`
5864    /// peels it off and folds it into the seed, which draws into a target that
5865    /// was already the right size -- so what reaches this arm is a matrix
5866    /// somewhere inside a composition, where the seed is not what reads it, and
5867    /// that is refused rather than approximated.
5868    fn filter_passes(
5869        &mut self,
5870        source: usize,
5871        target: Target,
5872        filter: &ImageFilter,
5873        basis: BlurBasis,
5874    ) -> Result<usize> {
5875        Ok(match filter {
5876            ImageFilter::None => source,
5877            ImageFilter::Blur { sigma_x, sigma_y } => {
5878                self.blur_passes(source, target, Vec2::new(*sigma_x, *sigma_y), basis)
5879            }
5880            ImageFilter::Dilate { radius_x, radius_y } => self.morphology_passes(
5881                source,
5882                target,
5883                Morphology::dilate(*radius_x, *radius_y),
5884                basis,
5885            ),
5886            ImageFilter::Erode { radius_x, radius_y } => self.morphology_passes(
5887                source,
5888                target,
5889                Morphology::erode(*radius_x, *radius_y),
5890                basis,
5891            ),
5892            ImageFilter::Runtime { program, uniforms } => {
5893                self.runtime_pass(source, target, *program, uniforms)
5894            }
5895            ImageFilter::Color(recolor) => self.recolor_pass(source, target, *recolor),
5896            ImageFilter::Compose { outer, inner } => {
5897                let inner = self.filter_passes(source, target, inner, basis)?;
5898                self.filter_passes(inner, target, outer, basis)?
5899            }
5900            ImageFilter::Matrix { .. } => {
5901                return Err(Error::Unsupported(
5902                    "a matrix inside a composition is not available as a filter; it \
5903                     moves the image rather than recomputing it in place, and only \
5904                     the outermost one folds into a backdrop's seed",
5905                ))
5906            }
5907        })
5908    }
5909
5910    /// A color filter run over a pass, and the pass it landed at.
5911    ///
5912    /// The image material with the filter on the paint rather than on the
5913    /// material, which is where a color filter lives: it acts on whatever the
5914    /// fragment computed, and here what the fragment computed is the texel.
5915    fn recolor_pass(&mut self, source: usize, target: Target, recolor: ColorFilter) -> usize {
5916        let to_local = to_local_columns(Transform2D::from(
5917            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
5918                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
5919        ));
5920        self.filter_pass_recolored(
5921            source,
5922            target,
5923            Material::Image {
5924                to_local,
5925                slot: 0,
5926                alpha: 1.0,
5927                tile: [TileMode::Clamp; 2],
5928                sampling: Sampling::Linear,
5929                source: [0.0, 0.0, 1.0, 1.0],
5930                tint: [1.0, 1.0, 1.0, 1.0],
5931            },
5932            recolor,
5933        )
5934    }
5935
5936    /// A caller's program run over a finished layer, and the pass it landed at.
5937    ///
5938    /// The whole of what a runtime image filter is, and it is short for the
5939    /// reason recorded on [`ImageFilter::Runtime`]: a filter pass covers a
5940    /// target the size of its source, so a fragment's clip position is already
5941    /// its texture coordinate and the program needs no mapping handed to it.
5942    /// Upstream re-rasterizes its input to arrange the same thing.
5943    ///
5944    /// Slot zero, because `filter_pass` gives the pass one source and that
5945    /// source is the layer being filtered. A program declaring the binding
5946    /// every draw already fills reads it and nothing further is bound.
5947    fn runtime_pass(
5948        &mut self,
5949        source: usize,
5950        target: Target,
5951        program: u32,
5952        uniforms: &[f32],
5953    ) -> usize {
5954        let mut textures = [None; emblema_hal::MAX_EFFECT_TEXTURES];
5955        textures[0] = Some(0);
5956        self.filter_pass(
5957            source,
5958            target,
5959            Material::Runtime {
5960                program,
5961                uniforms: uniforms.to_vec(),
5962                textures,
5963            },
5964        )
5965    }
5966
5967    /// One pass covering `target`, drawing `material` over all of it, and the
5968    /// index it landed at.
5969    ///
5970    /// What every image filter is made of. The material carries the mapping
5971    /// from the quad's clip position to the sampled texture's coordinates --
5972    /// the same pair a layer composite uses at zero offset, since a filter's
5973    /// target is the same size as its source -- and the filtering itself. The
5974    /// composite that follows is untouched, and still applies the layer's alpha
5975    /// and blend: keeping the filter passes pure means neither has to know
5976    /// about compositing.
5977    fn filter_pass(&mut self, source: usize, target: Target, material: Material) -> usize {
5978        self.filter_pass_recolored(source, target, material, ColorFilter::None)
5979    }
5980
5981    /// The same, with a color filter applied to what the material produced.
5982    fn filter_pass_recolored(
5983        &mut self,
5984        source: usize,
5985        target: Target,
5986        material: Material,
5987        recolor: ColorFilter,
5988    ) -> usize {
5989        // A pass of its own, so its slot table starts empty and the one slot it
5990        // uses is the pass it samples.
5991        let mut batch = Batch::new();
5992        let sources = vec![TextureSource::Layer(source)];
5993        let paint = RenderPaint {
5994            material,
5995            filter: recolor,
5996            // Replaces rather than blends: the target is cleared and this
5997            // covers all of it, so anything else would blend against the clear
5998            // for no reason.
5999            blend: BlendMode::Src,
6000            clip: None,
6001            stencil: ClipState::UNCLIPPED,
6002        };
6003        let quad = target.path();
6004        // The canvas's own renderer, aimed at the filter target for the one
6005        // draw and put back afterward. A fresh `Renderer` here would build a
6006        // pair of tessellators per pass per filtered layer per frame, for a
6007        // quad -- and would be the kind of allocation that never shows up in a
6008        // profile as itself.
6009        self.renderer.set_viewport(target.origin, target.extent);
6010        let _ = self
6011            .renderer
6012            .fill_into(&mut batch, &quad, Affine2::IDENTITY, &paint);
6013        self.renderer
6014            .set_viewport(self.target.origin, self.target.extent);
6015
6016        self.finished.push(Pass {
6017            batch,
6018            descriptor: PassDescriptor {
6019                clear: Some([0.0; 4]),
6020                // One sample: this reads a resolved image and writes another,
6021                // so multisampling it would resolve twice for no difference.
6022                samples: 1,
6023                viewport: None,
6024            },
6025            sources,
6026            extent: target.extent,
6027        });
6028        self.finished.len() - 1
6029    }
6030
6031    /// Spread or shrink a finished layer, and answer which pass holds the
6032    /// result.
6033    ///
6034    /// One pass per axis where the radius fits the shader's tap budget, and
6035    /// more where it does not. Splitting is exact rather than an
6036    /// approximation: dilating by `a` and then by `b` dilates by `a + b`,
6037    /// because the structuring elements add, and the same holds for erosion.
6038    /// So a radius of eighty runs as thirty-two, thirty-two and sixteen, and
6039    /// the picture is the one a single pass of eighty would have given.
6040    ///
6041    /// An axis with no radius contributes no passes at all. A dilation of ten
6042    /// horizontally and none vertically is one pass, not two, and the second
6043    /// would only have copied the image.
6044    fn morphology_passes(
6045        &mut self,
6046        source: usize,
6047        target: Target,
6048        morphology: Morphology,
6049        basis: BlurBasis,
6050    ) -> usize {
6051        // A filter pass covers the whole target, so its mapping is the fixed
6052        // one from clip space to the unit square and carries no transform of
6053        // the caller's at all. That is what keeps `step` -- a constant offset
6054        // between taps, in texels -- meaning the same thing at every fragment,
6055        // which a mapping with perspective would not.
6056        let to_local = to_local_columns(Transform2D::from(
6057            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6058                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6059        ));
6060        // Clamped to what the target can tell apart. The loop below emits a
6061        // pass per `MORPHOLOGY_TAPS` texels of radius, so without this a
6062        // caller's float decides how many passes a recording holds --
6063        // `Morphology::applied_radius` has the arithmetic and the case that
6064        // found it.
6065        let radius = morphology.applied_radius(target.extent);
6066        // Along the caller's axes once the transform has turned them, not the
6067        // target's -- the same arrangement and the same arithmetic as
6068        // `blur_passes`, for the same reason `non-parity.md` 14 gives: a layer's
6069        // content cannot be re-rendered into a space of its own choosing after
6070        // the fact, so the passes turn instead of the space. A unit device
6071        // direction moves `d.x` texels across and `d.y` down, so in normalized
6072        // coordinates it is `d` divided componentwise by the extent, which
6073        // reduces to the pair of axis steps this used to state whenever the
6074        // directions are the axes.
6075        //
6076        // A dilation is a maximum over a set of sample positions, and turning
6077        // the set is what makes a rotated square dilate to a square rather than
6078        // to one standing on the screen's axes.
6079        let (w, h) = (target.extent.width as f32, target.extent.height as f32);
6080        let [u, v] = basis.directions;
6081        let axes = [
6082            ([u.x / w, u.y / h], radius[0]),
6083            ([v.x / w, v.y / h], radius[1]),
6084        ];
6085
6086        let mut sampled = source;
6087        for (step, radius) in axes {
6088            let mut left = radius;
6089            while left > 0.0 {
6090                let taken = left.min(MORPHOLOGY_TAPS as f32);
6091                left -= taken;
6092                let material = Material::Morphology {
6093                    to_local,
6094                    slot: 0,
6095                    step,
6096                    radius: taken,
6097                    dilate: morphology.dilate,
6098                };
6099                sampled = self.filter_pass(sampled, target, material);
6100            }
6101        }
6102        sampled
6103    }
6104
6105    /// Blur a finished layer, and answer which pass now holds the result.
6106    ///
6107    /// Two passes, one per axis, because a two-dimensional Gaussian is the
6108    /// product of two one-dimensional ones: the same picture as a square of
6109    /// taps, at a fraction of the work. Each renders a quad covering its whole
6110    /// target and samples the pass before it.
6111    ///
6112    /// Both are the size of the layer, so a bounded layer's blur costs what the
6113    /// bound says and not what the frame is. The composite that follows is
6114    /// unchanged, and still applies the layer's alpha and blend -- keeping the
6115    /// blur passes pure means neither has to know about compositing.
6116    /// Halve a pass into a target of half its size, by sampling it.
6117    ///
6118    /// A linear sample taken at the center of a two-by-two block averages
6119    /// exactly those four texels, so halving with the sampler *is* a box
6120    /// filter and needs no kernel of its own. That is the whole reason the
6121    /// reduction below is a chain of halvings rather than one jump to the
6122    /// final size: a single bilinear tap spanning an eight-by-eight block
6123    /// reads four of its sixty-four texels and calls the rest absent, which is
6124    /// how a downsample turns a smooth image into a crawling one.
6125    fn halve_pass(&mut self, source: usize, into: Target) -> usize {
6126        // Clip space to the unit square, the same fixed mapping a blur pass
6127        // uses: a filter covers its whole target and samples the whole of what
6128        // it was given, whatever the two sizes are.
6129        let to_local = to_local_columns(Transform2D::from(
6130            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6131                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6132        ));
6133        self.filter_pass(
6134            source,
6135            into,
6136            Material::Image {
6137                to_local,
6138                slot: 0,
6139                alpha: 1.0,
6140                tile: [TileMode::Clamp; 2],
6141                sampling: Sampling::Linear,
6142                source: [0.0, 0.0, 1.0, 1.0],
6143                tint: [1.0, 1.0, 1.0, 1.0],
6144            },
6145        )
6146    }
6147
6148    /// How far to shrink a target before blurring it, as a power of two.
6149    ///
6150    /// The taps are one per texel while the radius fits in the budget and
6151    /// spread apart once it does not, which keeps a wide blur wide but samples
6152    /// it more and more coarsely -- past a deviation of about nineteen the gaps
6153    /// between taps open and a smooth ramp starts to show them. Upstream
6154    /// answers this by blurring a smaller copy, so the taps stay one per texel
6155    /// and it is the *image* that loses detail rather than the kernel. For a
6156    /// blur this wide that detail was leaving anyway.
6157    ///
6158    /// A power of two so that every step is an exact halving, which is what
6159    /// makes the sampler a box filter above.
6160    fn blur_downsample(sigma: f32, extent: u32) -> u32 {
6161        // A sigma that is not a length asks for no reduction. `with_blur_xy`
6162        // refuses one, but `Layer::blur` is a public field and a struct literal
6163        // carries whatever it likes past that -- and an infinite sigma makes the
6164        // condition below true however far the reduction goes, leaving the extent
6165        // as the loop's only stop.
6166        if !sigma.is_finite() || sigma <= 0.0 {
6167            return 1;
6168        }
6169        let mut scale = 1u32;
6170        // Stopped once the axis would round to nothing. The extent is floored
6171        // at one texel where it is built, so this is not what keeps a target
6172        // from having no pixels -- it is what keeps the reduction from spending
6173        // passes halving a single texel into itself, which a deviation of a few
6174        // hundred against a small layer will otherwise ask for.
6175        //
6176        // Written as `scale <= extent / 2` rather than `extent / (scale * 2) >= 1`,
6177        // which says the same thing and computes `scale * 2`. That product
6178        // overflows once `scale` reaches two to the thirty-first, which a layer
6179        // whose bounds make the extent that large reaches -- and the overflow was
6180        // not the worse half: in release the multiply wraps to zero and the
6181        // division that followed it panicked instead, so both profiles died on the
6182        // same input. Found by a generated sequence of canvas calls.
6183        while blur_radius(sigma / scale as f32) > BLUR_MAX_TAPS && scale <= extent / 2 {
6184            scale *= 2;
6185        }
6186        scale
6187    }
6188
6189    fn blur_passes(
6190        &mut self,
6191        source: usize,
6192        target: Target,
6193        sigma: Vec2,
6194        basis: BlurBasis,
6195    ) -> usize {
6196        // Clip space spans two units and runs upward, so this is the mapping
6197        // that turns a full-target quad's clip position into the texture
6198        // coordinates of the pass it samples -- the same pair a layer
6199        // composite uses at zero offset, since these targets are the same size.
6200        // A filter pass covers the whole target, so its mapping is the fixed
6201        // one from clip space to the unit square and carries no transform of
6202        // the caller's at all. That is what keeps `step` -- a constant offset
6203        // between taps, in texels -- meaning the same thing at every fragment,
6204        // which a mapping with perspective would not.
6205        let to_local = to_local_columns(Transform2D::from(
6206            Affine2::from_mat2(Mat2::from_diagonal(Vec2::new(0.5, -0.5)))
6207                * Affine2::from_translation(Vec2::new(1.0, -1.0)),
6208        ));
6209        // Past the tap budget the image is shrunk rather than the taps spread,
6210        // which is upstream's answer and keeps the taps one per texel. Halved
6211        // repeatedly, so each step is an exact box filter; the deviation shrinks
6212        // with the image, and the composite that puts the layer back scales it
6213        // up again -- it maps clip space to a normalized coordinate, so it does
6214        // not care what resolution answers.
6215        // Per axis, because the deviations are. An axis blurred hard needs its
6216        // reduction and an axis blurred not at all must not be reduced with it
6217        // -- shrinking and enlarging a sharp axis for the sake of the other one
6218        // would soften it, which is the whole difference between a directional
6219        // blur and a soft smear.
6220        //
6221        // Only where the passes run along the target's own axes, though. Turned
6222        // off them, reducing one axis and not the other would shear the
6223        // directions the steps are stated in: two perpendicular directions in a
6224        // stretched image are no longer perpendicular, and separability is
6225        // exactly the property that would be lost. So a turned blur reduces both
6226        // axes together, which is a similarity and leaves the angle alone.
6227        let scale = if basis.is_axis_aligned() {
6228            [
6229                Self::blur_downsample(sigma.x, target.extent.width),
6230                Self::blur_downsample(sigma.y, target.extent.height),
6231            ]
6232        } else {
6233            let smallest = target.extent.width.min(target.extent.height);
6234            let together = Self::blur_downsample(sigma.x, smallest)
6235                .max(Self::blur_downsample(sigma.y, smallest));
6236            [together, together]
6237        };
6238        let reduced = |by: [u32; 2]| Target {
6239            origin: target.origin,
6240            extent: Extent2D::new(
6241                (target.extent.width / by[0]).max(1),
6242                (target.extent.height / by[1]).max(1),
6243            ),
6244        };
6245        let blurred = reduced(scale);
6246        let sigma = Vec2::new(sigma.x / scale[0] as f32, sigma.y / scale[1] as f32);
6247
6248        let mut source = source;
6249        let mut step_scale = [1u32; 2];
6250        while step_scale[0] < scale[0] || step_scale[1] < scale[1] {
6251            // Each iteration halves whichever axes are still above their own
6252            // target, so every step remains at most a halving per axis and
6253            // therefore an exact box filter, which is the property the
6254            // reduction rests on.
6255            for axis in 0..2 {
6256                if step_scale[axis] < scale[axis] {
6257                    step_scale[axis] *= 2;
6258                }
6259            }
6260            source = self.halve_pass(source, reduced(step_scale));
6261        }
6262
6263        // A step of one texel along each axis, in the sampled texture's own
6264        // coordinates. The shader cannot derive this: it does not know the size
6265        // of what it is sampling.
6266        //
6267        // A unit device direction moves `d.x` texels across and `d.y` down, so
6268        // in normalized coordinates it is `d` divided componentwise by the
6269        // extent. That reduces to the pair of axis steps this used to state when
6270        // the directions are the axes, and it is the whole of what makes a blur
6271        // turn with its caller.
6272        let (w, h) = (blurred.extent.width as f32, blurred.extent.height as f32);
6273        let [u, v] = basis.directions;
6274        let steps = [(sigma.x, [u.x / w, u.y / h]), (sigma.y, [v.x / w, v.y / h])];
6275
6276        let mut sampled = source;
6277        for (sigma, step) in steps {
6278            // Skipped rather than run with a deviation of zero. A zero-sigma
6279            // pass is the identity in arithmetic and a resample in fact, and a
6280            // blur stated along one axis is exactly the case where the other
6281            // pass must leave the image alone.
6282            if !ImageFilter::blurs(sigma) {
6283                continue;
6284            }
6285            sampled = self.filter_pass(
6286                sampled,
6287                blurred,
6288                Material::Blur {
6289                    to_local,
6290                    slot: 0,
6291                    step,
6292                    sigma,
6293                },
6294            );
6295        }
6296        sampled
6297    }
6298
6299    /// Point both the canvas and its renderer at a target.
6300    ///
6301    /// Together rather than separately: the canvas derives a paint's mapping
6302    /// from the target and the renderer derives the geometry's, and the two
6303    /// have to agree or a shape lands in one place while its gradient runs
6304    /// through another.
6305    fn aim_at(&mut self, target: Target) {
6306        self.target = target;
6307        self.renderer.set_viewport(target.origin, target.extent);
6308    }
6309
6310    /// The sample count a pass renders at.
6311    fn pass_samples(&self) -> u32 {
6312        // One sample unless something asked for antialiasing, because
6313        // multisampling costs bandwidth and a frame of solid rectangles gains
6314        // nothing from it.
6315        if self.anti_alias {
6316            self.samples
6317        } else {
6318            1
6319        }
6320    }
6321
6322    /// Leave in the parts of each draw a later opaque draw would cover.
6323    ///
6324    /// `Batch::cull_occluded` claims to be pixel-identical. The only way to check a
6325    /// claim like that is to render the same recording with it and without it and
6326    /// compare the results, which needs a way to turn it off.
6327    ///
6328    /// Hidden because it is not a choice a caller should make: it asks for the same
6329    /// picture at more cost. Alongside `Tessellator::fill_general`, which exists for the
6330    /// same reason.
6331    #[doc(hidden)]
6332    pub fn keep_hidden_draws(&mut self) -> &mut Self {
6333        self.keep_hidden_draws = true;
6334        self
6335    }
6336
6337    /// Finish recording.
6338    pub fn finish(mut self) -> Recording {
6339        // A layer left open is a caller mistake, and the useful recovery is to
6340        // composite it anyway: the alternative is silently dropping everything
6341        // drawn since the unbalanced `save_layer`, which looks like a rendering
6342        // fault rather than like the missing `restore` it is.
6343        while self.stack.iter().any(|s| s.layer.is_some()) {
6344            self.restore();
6345        }
6346
6347        let samples = self.pass_samples();
6348        if !self.keep_hidden_draws {
6349            let extent = self.extent;
6350            self.batch.cull_occluded(extent);
6351        }
6352        let root = Pass {
6353            batch: self.batch,
6354            descriptor: PassDescriptor {
6355                clear: self
6356                    .background
6357                    .map(|c| c.to_array())
6358                    .or_else(|| self.seeded_by_redraw.then_some([0.0; 4])),
6359                samples,
6360                // The root pass renders into the caller's surface, which is the
6361                // space its geometry was recorded against.
6362                viewport: None,
6363            },
6364            sources: self.sources,
6365            extent: self.extent,
6366        };
6367        let mut passes = self.finished;
6368        passes.push(root);
6369        Recording {
6370            passes,
6371            extent: self.extent,
6372            ramps: self.ramps,
6373        }
6374    }
6375}
6376
6377/// How much a transform magnifies, for converting a length into device pixels.
6378///
6379/// The larger of the two basis lengths, which is what upstream's
6380/// `GetMaxBasisLengthXY` gives and what `thin_stroke` already uses for the same
6381/// kind of conversion. A projective transform has no single answer -- it
6382/// magnifies differently at every point -- so it converts by its affine part,
6383/// which is exact wherever the perspective is mild and is the same reading the
6384/// stroke widening takes.
6385fn max_scale_of(transform: Transform2D) -> f32 {
6386    match transform.to_affine() {
6387        Some(affine) => max_scale(&affine),
6388        None => 1.0,
6389    }
6390}
6391
6392/// How far each of the caller's own axes is stretched, separately.
6393///
6394/// `max_scale_of` answers the same question with one number, which is the right
6395/// answer for a length that has no axis -- a stroke's width, a tessellation
6396/// tolerance -- and the wrong one for a pair of lengths that do. Under
6397/// `scale(2, 5)` it reports five for both, so a radius stated per axis comes out
6398/// five times too long on one of them.
6399///
6400/// The lengths of the transformed basis vectors, which is what upstream's
6401/// `ExtractScale` takes. A rotation therefore contributes nothing to either,
6402/// which is correct: it turns the axes rather than stretching them, and
6403/// `BlurBasis` is what carries the turn.
6404///
6405/// Falls back to the single factor where there is no basis to read -- a
6406/// transform with perspective has no constant one -- so the axis-free answer is
6407/// what a filter gets exactly where a per-axis answer would be invented.
6408fn axis_scales_of(transform: Transform2D) -> Vec2 {
6409    let Some(affine) = transform.to_affine() else {
6410        return Vec2::splat(max_scale_of(transform));
6411    };
6412    let lengths = Vec2::new(
6413        affine.matrix2.x_axis.length(),
6414        affine.matrix2.y_axis.length(),
6415    );
6416    if !lengths.x.is_finite() || !lengths.y.is_finite() || lengths.min_element() <= 0.0 {
6417        return Vec2::splat(max_scale_of(transform));
6418    }
6419    lengths
6420}
6421
6422/// The constant that makes four cubics approximate a circle.
6423const KAPPA: f32 = 0.552_284_8;
6424
6425/// The smallest a stroke is drawn, in device pixels.
6426///
6427/// Upstream's `kMinStrokeSize`, and the same value for the same reason: a
6428/// stroke narrower than a pixel has no way to cover one, so it either lands on
6429/// a sample or misses it. Widening to exactly one and paying for the width in
6430/// alpha is what makes a thin line fade instead of flicker.
6431const MIN_STROKE_PIXELS: f32 = 1.0;
6432
6433/// The width a stroke is drawn at, and the alpha that pays for the difference.
6434///
6435/// A stroke narrower than a device pixel cannot be drawn at the width it asks
6436/// for. Multisampling quantizes it: at four samples the only coverages a
6437/// sub-pixel line can have are none, a quarter, a half and three quarters, so
6438/// a line a fifth of a pixel wide draws at a quarter or vanishes outright
6439/// depending on where it falls. Measured here before this existed, a stroke of
6440/// 0.18 device pixels and one of 0.3 drew identically, and one of 0.15 drew
6441/// nothing at all.
6442///
6443/// So the geometry is widened to a whole pixel and the alpha is scaled down to
6444/// pay for it, which is what upstream does — `ComputePixelHalfWidth` takes
6445/// `max(width, kMinStrokeSize / max_basis)` and `ComputeStrokeAlphaCoverage`
6446/// returns `clamp(scaled_width * 2, 0, 1)`, a factor its own comment calls
6447/// eyeballed from Skia. Both are carried rather than improved on: the whole
6448/// point is that a Flutter app's hairlines look here as they look there, and a
6449/// different constant would be a different picture at every sub-pixel width.
6450///
6451/// **Zero is a hairline**, which is upstream's reading and `dart:ui`'s
6452/// documented one: "Defaults to 0.0, which correspond to a hairline width".
6453/// Upstream spells it as an explicit exception rather than letting it fall out
6454/// of the arithmetic — `ComputeStrokeAlphaCoverage` opens with
6455/// `if (scaled_stroke_width == 0.0 || scaled_stroke_width >= kMinStrokeSize)
6456/// return 1.0`, so zero takes the widening to a whole pixel and pays nothing in
6457/// alpha for it.
6458///
6459/// This renderer read zero as no stroke until 2026-09-17, on the reasoning that
6460/// a caller animating a width to nothing should dim continuously rather than
6461/// jump back to full at the end. That reasoning is sound and it is not
6462/// upstream's: the jump is in upstream on purpose, and zero is the *default*
6463/// value of `Paint.strokeWidth` rather than an edge a caller has to ask for --
6464/// so a Flutter app that strokes without setting a width drew a hairline there
6465/// and nothing here. Parity wins, and the discontinuity comes with it.
6466///
6467/// Which zero means which is what [`Zero`] carries. The analytic route spells a
6468/// *fill* as a stroke width of zero, and widening that one would put a
6469/// one-pixel outline around every filled shape, so the distinction cannot be
6470/// left to the number.
6471///
6472/// A projective transform is left alone too. The widening asks how much a
6473/// transform stretches, which for a homography is a different answer at every
6474/// point; upstream guards the same case with `HasPerspective2D`.
6475fn thin_stroke(transform: Transform2D, width: f32, zero: Zero) -> (f32, f32) {
6476    let Some(affine) = transform.to_affine() else {
6477        return (width, 1.0);
6478    };
6479    if !width.is_finite() || width < 0.0 {
6480        return (width, 1.0);
6481    }
6482    if width == 0.0 && zero == Zero::IsNotAStroke {
6483        return (width, 1.0);
6484    }
6485    let basis = max_scale(&affine);
6486    if !basis.is_finite() || basis <= 0.0 {
6487        return (width, 1.0);
6488    }
6489    let scaled = basis * width;
6490    if scaled >= MIN_STROKE_PIXELS {
6491        return (width, 1.0);
6492    }
6493    // Upstream's exception, and the reason it is one: the dimming below would
6494    // take a width of zero to an alpha of zero, which is a hairline nobody can
6495    // see rather than the thinnest line the device can draw.
6496    let coverage = match scaled == 0.0 {
6497        true => 1.0,
6498        false => (scaled * 2.0).clamp(0.0, 1.0),
6499    };
6500    (MIN_STROKE_PIXELS / basis, coverage)
6501}
6502
6503/// The radius a point is drawn at, which for a small one is wider than asked.
6504///
6505/// The same problem `thin_stroke` solves and a different constant, both taken
6506/// from upstream. A point smaller than a pixel lands on a sample or misses it,
6507/// so `PointFieldGeometry` widens the *radius* to `0.5f / max_basis` --
6508/// `std::max(radius_, min_size)`, half a pixel, so the point comes out one pixel
6509/// across. A stroke's constant is a whole pixel because a stroke width spans the
6510/// line rather than reaching from its middle.
6511///
6512/// Nothing is dimmed to pay for it, which is upstream's rule and not an omission
6513/// here: a stroke fades as it thins and a point does not. A point is a disc
6514/// whose area falls away as the square of its radius, so dimming it as well
6515/// would take it to nothing twice over, and a field of them is a scatter plot
6516/// whose small marks are the ones a reader has to see.
6517///
6518/// A projective transform is left alone, as it is for a stroke: the stretch a
6519/// homography applies is a different answer at every point.
6520fn point_radius(transform: Transform2D, width: f32) -> f32 {
6521    let radius = width / 2.0;
6522    let Some(affine) = transform.to_affine() else {
6523        return radius;
6524    };
6525    if !radius.is_finite() || radius < 0.0 {
6526        return radius;
6527    }
6528    let basis = max_scale(&affine);
6529    if !basis.is_finite() || basis <= 0.0 {
6530        return radius;
6531    }
6532    radius.max(MIN_POINT_RADIUS_PIXELS / basis)
6533}
6534
6535/// When two coordinates are the same coordinate, for deciding axis alignment.
6536///
6537/// Upstream's `kEhCloseEnough`, and the same value. A line off vertical by less
6538/// than this covers the same pixels a vertical one does, so treating it as
6539/// vertical moves nothing a reader could see.
6540const CLOSE_ENOUGH: f32 = 1e-3;
6541
6542/// Half a device pixel, so the smallest point drawn covers one.
6543///
6544/// Upstream's `min_size` in `PointFieldGeometry::GetPositionBuffer`, which is
6545/// `0.5f / max_basis` rather than [`MIN_STROKE_PIXELS`] over it, for the reason
6546/// [`point_radius`] gives: this one is a radius.
6547const MIN_POINT_RADIUS_PIXELS: f32 = 0.5;
6548
6549/// What a stroke width of zero means at a call site, which is not always the
6550/// same thing.
6551///
6552/// A caller asking for a zero-width stroke wants a hairline. The analytic route
6553/// reaches [`thin_stroke`] through `analytic_stroke`, which reports a *fill* as
6554/// a width of zero -- and a fill widened to a pixel would grow an outline it
6555/// never asked for. So the two are told apart here rather than by the number,
6556/// which they share.
6557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6558enum Zero {
6559    /// A stroke of no width, which draws the thinnest line the device can.
6560    IsAHairline,
6561    /// Not a stroke at all, so there is no width to widen.
6562    IsNotAStroke,
6563}
6564
6565/// A color at `factor` of its opacity.
6566///
6567/// The analytic route's materials carry one color rather than a material this
6568/// can be asked of, so the two spellings of the same dimming sit beside each
6569/// other: [`Material::with_opacity`] and this.
6570fn dimmed(color: crate::Color, factor: f32) -> [f32; 4] {
6571    let mut c = color.to_array();
6572    c[3] *= factor;
6573    c
6574}
6575
6576/// The stroke width a paint implies for a fragment-evaluated shape, if one can
6577/// be drawn that way at all.
6578///
6579/// `Some(0.0)` fills, `Some(w)` traces an outline, and `None` means this paint
6580/// has to be tessellated: without antialiasing there is nothing a distance
6581/// field offers that triangles do not, and a width that is not finite and
6582/// positive is not a stroke.
6583///
6584/// The joins and caps a stroke style also carries are ignored rather than
6585/// refused. These shapes are closed curves with no corners to join and no ends
6586/// to cap, so every setting produces the same outline -- which is why a stroked
6587/// one can take this path at all.
6588fn analytic_stroke(paint: &Paint) -> Option<f32> {
6589    if !paint.anti_alias {
6590        return None;
6591    }
6592    // The shape is drawn on a quad larger than itself and emits a fragment
6593    // everywhere on it, so a mode that discards the destination where the
6594    // source is transparent would erase what is behind it in the gap between
6595    // the two -- and in the corner of a rounded rectangle that gap is most of
6596    // the corner. Tessellating covers only the shape and has no such gap.
6597    if !paint.blend.respects_coverage() {
6598        return None;
6599    }
6600    // A distance field describes a continuous outline and has no notion of a
6601    // position along it, so a dashed stroke cannot be expressed this way at
6602    // all. Falling back to tessellation is what makes the dash appear; without
6603    // this the rounded rectangle and the circle would draw a solid outline and
6604    // silently ignore the pattern, which is the shape of bug the analytic path
6605    // is most able to hide -- the result looks like a stroke, because it is
6606    // one.
6607    if paint.dash.as_ref().is_some_and(|dash| dash.is_usable()) {
6608        return None;
6609    }
6610    // A mask blur is a layer around the draw, and a distance field evaluated on
6611    // a quad is not a shape that can be put inside one and blurred: the quad is
6612    // larger than the shape and the layer would blur its edges too.
6613    if paint.mask_blur > 0.0 {
6614        return None;
6615    }
6616    // An image filter is a layer around the draw for the same reason, and this
6617    // guard was missing when image filters were added -- so a blurred or moved
6618    // circle drew as though neither had been asked for. Nothing failed: the
6619    // shape was still a shape, and only a test comparing where it landed said
6620    // otherwise. Every route that needs a layer has to be refused here, which
6621    // is worth stating as the rule rather than as three cases.
6622    if !paint.image_filter.is_identity() {
6623        return None;
6624    }
6625    match &paint.style {
6626        Style::Fill => Some(0.0),
6627        Style::Stroke(stroke) => {
6628            let width = stroke.width;
6629            (width.is_finite() && width > 0.0).then_some(width)
6630        }
6631    }
6632}
6633
6634/// An ellipse inscribed in a rectangle, as four cubics.
6635///
6636/// The same construction a circle uses, with a different radius on each axis:
6637/// the constant that makes a cubic approximate a quarter turn does not care
6638/// which, since it scales with the axis it belongs to.
6639fn oval_path(bounds: Rect) -> Path {
6640    let (cx, cy) = (
6641        (bounds.left + bounds.right) / 2.0,
6642        (bounds.top + bounds.bottom) / 2.0,
6643    );
6644    let (rx, ry) = (bounds.width() / 2.0, bounds.height() / 2.0);
6645    let (kx, ky) = (KAPPA * rx, KAPPA * ry);
6646    let mut b = PathBuilder::new();
6647    b.move_to(Vec2::new(cx + rx, cy))
6648        .cubic_to(
6649            Vec2::new(cx + rx, cy + ky),
6650            Vec2::new(cx + kx, cy + ry),
6651            Vec2::new(cx, cy + ry),
6652        )
6653        .cubic_to(
6654            Vec2::new(cx - kx, cy + ry),
6655            Vec2::new(cx - rx, cy + ky),
6656            Vec2::new(cx - rx, cy),
6657        )
6658        .cubic_to(
6659            Vec2::new(cx - rx, cy - ky),
6660            Vec2::new(cx - kx, cy - ry),
6661            Vec2::new(cx, cy - ry),
6662        )
6663        .cubic_to(
6664            Vec2::new(cx + kx, cy - ry),
6665            Vec2::new(cx + rx, cy - ky),
6666            Vec2::new(cx + rx, cy),
6667        )
6668        .close();
6669    b.build()
6670}
6671
6672fn circle_path(center: Vec2, radius: f32) -> Path {
6673    let (cx, cy) = (center.x, center.y);
6674    let r = radius;
6675    let k = KAPPA * r;
6676    let mut b = PathBuilder::new();
6677    // Recorded for the same reason a rounded rectangle's is: a shadow arrives
6678    // as a path, and a circle is the one oval the blurred-rectangle expression
6679    // describes exactly -- corners of half the side, on a square.
6680    b.as_rounded_rect(
6681        GeometryRect::new(Vec2::new(cx - r, cy - r), Vec2::new(cx + r, cy + r)),
6682        r,
6683    );
6684    b.move_to(Vec2::new(cx + r, cy))
6685        .cubic_to(
6686            Vec2::new(cx + r, cy + k),
6687            Vec2::new(cx + k, cy + r),
6688            Vec2::new(cx, cy + r),
6689        )
6690        .cubic_to(
6691            Vec2::new(cx - k, cy + r),
6692            Vec2::new(cx - r, cy + k),
6693            Vec2::new(cx - r, cy),
6694        )
6695        .cubic_to(
6696            Vec2::new(cx - r, cy - k),
6697            Vec2::new(cx - k, cy - r),
6698            Vec2::new(cx, cy - r),
6699        )
6700        .cubic_to(
6701            Vec2::new(cx + k, cy - r),
6702            Vec2::new(cx + r, cy - k),
6703            Vec2::new(cx + r, cy),
6704        )
6705        .close();
6706    b.build()
6707}
6708
6709/// How far a shadow's blur reaches per unit of elevation, as a kernel radius.
6710///
6711/// The light's radius over its height, which is the ratio that decides how
6712/// quickly a shadow softens as its caster rises. Upstream writes it
6713/// `constexpr Scalar kLightRadius = 800 / 600;` in the dispatcher that draws
6714/// the shadow, and those are integer literals: the division happens in `int`
6715/// and the constant is one, not the one and a third the comment beside it
6716/// describes.
6717///
6718/// One is what this uses, because parity is against what upstream does rather
6719/// than against what it appears to have meant. This did carry the ratio the
6720/// comment states, and combined with reading the result as a deviation instead
6721/// of a radius it made every shadow here about twice as soft as the same
6722/// elevation gives upstream.
6723///
6724/// Note that `DlCanvas` has a second pair of these, `kShadowLightRadius` over
6725/// `kShadowLightHeight`, which are `DlScalar` and so do divide to one and a
6726/// third. Those size the shadow's *bounds*; this one draws it. Reading the
6727/// wrong pair is easy and gives a shadow a third too wide.
6728const LIGHT_RADIUS: f32 = 1.0;
6729
6730/// Kernel radius per deviation, for turning one into the other.
6731///
6732/// The square root of three, matching upstream's `kKernelRadiusPerSigma`. A
6733/// shadow's elevation gives a radius, and the blur takes a deviation, so the
6734/// conversion is not optional -- and upstream's is affine rather than a plain
6735/// scale, adding half a pixel so that a radius shrinking to nothing still
6736/// leaves a deviation the blur can act on.
6737const KERNEL_RADIUS_PER_SIGMA: f32 = 1.732_050_8;
6738
6739/// The deviation upstream blurs a shadow of this radius by.
6740///
6741/// `Radius::operator Sigma` in `impeller/geometry/sigma.cc`, which is
6742/// `radius / kKernelRadiusPerSigma + 0.5` for a positive radius and zero
6743/// otherwise.
6744fn sigma_for_radius(radius: f32) -> f32 {
6745    if radius > 0.0 {
6746        radius / KERNEL_RADIUS_PER_SIGMA + 0.5
6747    } else {
6748        0.0
6749    }
6750}
6751
6752/// What fraction of the stated color's alpha a shadow starts from.
6753///
6754/// A quarter, matching Impeller. A shadow is a suggestion of occlusion rather
6755/// than an absence of light, and at full alpha it reads as a hole. This is what
6756/// the tonal remap below begins with rather than the alpha a shadow ends up
6757/// drawn at -- for anything but a gray it raises the alpha again.
6758const SHADOW_ALPHA: f32 = 0.25;
6759
6760/// A shadow's color, tonally adjusted the way upstream adjusts it.
6761///
6762/// Ported from `DlDispatcherBase::drawShadow`, which says it ports
6763/// `SkShadowUtils::ComputeTonalColors`. The rule is that a colored shadow does
6764/// not read as a gray one tinted: a saturated shadow needs more alpha and less
6765/// saturation than the number a caller gave it, or it looks like a colored
6766/// object lying on the surface rather than an absence of light.
6767///
6768/// The arithmetic runs on **sRGB-encoded** components rather than on light,
6769/// because upstream's do: its pipeline holds encoded values throughout, so the
6770/// luminance this keys on is a luminance of encoded numbers. Computing it on
6771/// linear light would be the same formula answering a different question, and
6772/// would part company with upstream by more than the remap is worth.
6773///
6774/// It is the identity for a black shadow, which is nearly every shadow: at zero
6775/// luminance the color term falls out and the alpha is left at the quarter
6776/// above. What it changes is a colored one, and by a lot -- a fully saturated
6777/// red at full alpha comes out at better than twice the alpha and about
6778/// five eighths of the red.
6779fn tonal_shadow_color(color: Color) -> Color {
6780    let [r, g, b, a] = color.to_srgb();
6781    let alpha = a * SHADOW_ALPHA;
6782
6783    let luminance = (r.min(g).min(b) + r.max(g).max(b)) * 0.5;
6784
6785    let alpha_adjust = (2.6 + (-2.666_67 + 1.066_67 * alpha) * alpha) * alpha;
6786    let color_alpha = (3.544_762 + (-4.891_428 + 2.346_6 * luminance) * luminance) * luminance;
6787    let color_alpha = (alpha_adjust * color_alpha).clamp(0.0, 1.0);
6788
6789    let grayscale_alpha = (alpha * (1.0 - 0.4 * luminance)).clamp(0.0, 1.0);
6790
6791    let color_scale = color_alpha * (1.0 - grayscale_alpha);
6792    let tonal_alpha = color_scale + grayscale_alpha;
6793    // Guarded because a fully transparent shadow leaves both terms at zero, and
6794    // the ratio below is the only place that could divide by it.
6795    let unpremul_scale = if tonal_alpha != 0.0 {
6796        color_scale / tonal_alpha
6797    } else {
6798        0.0
6799    };
6800
6801    Color::srgb(
6802        unpremul_scale * r,
6803        unpremul_scale * g,
6804        unpremul_scale * b,
6805        tonal_alpha,
6806    )
6807}
6808
6809/// How far past its content a blur of this deviation reaches.
6810///
6811/// `(sigma - 0.5) * sqrt(3)`, which is upstream's `CalculateBlurRadius` and is
6812/// also where the shader stops taking taps -- so a target sized by this covers
6813/// everything the blur will actually read, and no more. It was three
6814/// deviations, which covered more of the curve than upstream does and made
6815/// every blur here wider than the same request gives it.
6816///
6817/// Shared rather than written twice. A bounded layer sizes its target with it,
6818/// and a mask blur style that combines the blurred coverage with the shape's
6819/// own has to size the layer holding both by the same rule -- which it did not
6820/// at first, and the halo was cut off square at the shape's own bounds.
6821/// The widest deviation a blur is asked for, matching upstream's `kMaxSigma`.
6822///
6823/// Not a limitation so much as the end of the useful range: at five hundred a
6824/// blur of anything smaller than a wall is a flat wash, and the reduction that
6825/// keeps the taps affordable has long since taken the image down to a handful
6826/// of texels.
6827pub(crate) const MAX_SIGMA: f32 = 500.0;
6828
6829/// The most taps a blur takes each way from center.
6830///
6831/// Must match `max_taps` in the blur shader, which is where the budget is
6832/// actually spent; this is the copy that decides when to shrink the image
6833/// instead of spreading the taps across it.
6834/// The largest side a recorded target may have, in texels.
6835///
6836/// Not a device limit -- this side of the renderer has no device -- but a
6837/// bound on what a *recording* may describe. Every current part reports a
6838/// maximum texture side of 16,384 or less, so a target twice that is already
6839/// past anything that could be rendered, and the number's job is to be
6840/// obviously larger than a real surface while small enough that a filter
6841/// emitting a pass per `MORPHOLOGY_TAPS` texels of radius stays countable.
6842///
6843/// It exists because `f32 as u32` saturates rather than wrapping or refusing:
6844/// without a ceiling a finite width of `3.4e38` becomes an extent of
6845/// `u32::MAX`, and a morphology over that asks for a hundred and thirty-four
6846/// million passes.
6847pub(crate) const MAX_TARGET_SIDE: f32 = 32_768.0;
6848
6849pub(crate) const BLUR_MAX_TAPS: f32 = 32.0;
6850
6851/// The kernel radius a deviation gives, in texels of whatever it is blurring.
6852///
6853/// Upstream's `CalculateBlurRadius`, which is `Radius(Sigma(sigma))`. Shared
6854/// so that the rule deciding how far a blur reaches, the rule sizing a target
6855/// to hold it, and the rule deciding whether it needs shrinking first cannot
6856/// drift apart -- they are the same question asked by three callers.
6857/// The error function, to about seven digits.
6858///
6859/// The same rational approximation the shader evaluates, and it has to be the
6860/// same one: `scale` is computed here and the fade there, so two different
6861/// approximations would normalize the shape against a curve it is not drawn
6862/// with. Upstream keeps a copy on each side for the same reason.
6863pub(crate) fn erf7(value: f32) -> f32 {
6864    let x = value * std::f32::consts::FRAC_2_SQRT_PI;
6865    let xx = x * x;
6866    let series = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx);
6867    series / (1.0 + series * series).sqrt()
6868}
6869
6870pub(crate) fn blur_radius(sigma: f32) -> f32 {
6871    ((sigma - 0.5) * KERNEL_RADIUS_PER_SIGMA).max(0.0)
6872}
6873
6874pub(crate) fn blur_reach(sigma: f32) -> f32 {
6875    if sigma > 0.0 {
6876        blur_radius(sigma).ceil()
6877    } else {
6878        0.0
6879    }
6880}
6881
6882/// A color in the form a vertex carries one.
6883///
6884/// Premultiplied, because a vertex color is interpolated across a triangle and
6885/// straight color interpolated between differing alphas is wrong at every point
6886/// between the ends.
6887/// The largest number of sections a vertex-interpolated gradient will emit.
6888///
6889/// Sections are geometry, so stop count is not bounded here the way the paint
6890/// block's four are -- but it is not unbounded either: each section is four
6891/// vertices and six indices, and past some count the fragment walk is cheaper
6892/// than the vertices. The shader route is always available, so the cap is a
6893/// fallback rather than a refusal.
6894const MAX_GRADIENT_SECTIONS: usize = 64;
6895
6896/// Whether this gradient can be drawn by interpolating across vertices instead
6897/// of evaluating per fragment, and the sections to draw if so.
6898///
6899/// Upstream's `CanApplyFastGradient` asks three things, and so does this: the
6900/// gradient is axis-aligned, its endpoints land on the edges of the rectangle
6901/// being covered, and the geometry is a rectangle at all. When they hold, the
6902/// parameter runs exactly zero to one across the shape, so one quad per pair of
6903/// stops with the stop colors on its corners is the same picture the fragment
6904/// walk produces -- see §19 of `docs/non-parity.md` for the measured agreement.
6905///
6906/// Axis-aligned means the two endpoints share a coordinate: an x for a vertical
6907/// wash, a y for a horizontal one. Landing on the edges is the strict half.
6908///
6909/// **`Clamp` only, and the reasoning that admitted every tile mode was wrong.**
6910/// It said that endpoints on the edges make the mode irrelevant, the parameter
6911/// never leaving `[0, 1]` inside the shape. That holds only while the edges fall
6912/// between pixels. Give the rectangle a fractional edge and the rasterizer
6913/// covers pixels whose centers lie just outside the gradient's span, so the
6914/// fragment walk's parameter does leave the interval -- and `Repeat` wraps it to
6915/// the far end, which is a whole stop's difference rather than a rounding one.
6916/// Sections cannot wrap: their vertices carry the end colors and interpolation
6917/// stays between them.
6918///
6919/// Measured by `gradient_routes.rs` on lavapipe at Mesa 26.2.3: a vertical
6920/// gradient on a rectangle whose edges sit at `y = 38.5003` and `62.5003`,
6921/// tiling by `Repeat`, differs between the two routes by **56 of 255** -- the
6922/// full range of the only channel its stops move. `Clamp` is what the two agree
6923/// on, because clamping is what interpolation already does.
6924///
6925/// Returned in rectangle space. The caller transforms the corners, which is
6926/// what keeps this independent of the transform: a rotated or skewed rectangle
6927/// is still a rectangle in its own space, and the gradient still runs along one
6928/// of its axes.
6929/// One quad of a vertex-interpolated gradient: the corners in the rectangle's
6930/// own space, and the premultiplied color at each.
6931///
6932/// Wound top-left, top-right, bottom-right, bottom-left, which is what
6933/// `draw_gradient_sections` indexes against.
6934struct GradientSection {
6935    corners: [Vec2; 4],
6936    colors: [[f32; 4]; 4],
6937}
6938
6939fn fast_gradient_sections(rect: Rect, shader: &Shader) -> Option<Vec<GradientSection>> {
6940    let Shader::LinearGradient {
6941        start,
6942        end,
6943        stops,
6944        tile,
6945    } = shader
6946    else {
6947        return None;
6948    };
6949    // See the note above: only clamping agrees with what sections do at an edge.
6950    if *tile != TileMode::Clamp {
6951        return None;
6952    }
6953    if stops.len() < 2 || stops.len() > MAX_GRADIENT_SECTIONS + 1 {
6954        return None;
6955    }
6956    // Non-decreasing and inside the unit interval. A stop list that is neither
6957    // is the shader route's to interpret, not this one's to guess at.
6958    if stops.first()?.offset != 0.0 || stops.last()?.offset != 1.0 {
6959        return None;
6960    }
6961    if stops.windows(2).any(|w| w[1].offset < w[0].offset) {
6962        return None;
6963    }
6964    // One alpha across the list, and this is not a conservatism -- it is the
6965    // one case where the two routes do not produce the same picture.
6966    //
6967    // A gradient is interpolated in *straight* color, which is what `dart:ui`
6968    // and Skia do: the fragment walk interpolates the stops and premultiplies
6969    // the result. A vertex color cannot work that way. What the rasterizer
6970    // interpolates is what gets multiplied in, so the colors have to be
6971    // premultiplied before they reach it -- and premultiplying then
6972    // interpolating is not interpolating then premultiplying unless alpha is
6973    // constant. Measured at 58 of 255 between the two routes on a two-stop
6974    // gradient from alpha one to alpha a tenth.
6975    //
6976    // Uniform alpha is the ordinary case -- a wash is opaque, and a fading one
6977    // is usually a layer's opacity rather than the gradient's -- so the route
6978    // keeps the gradients it was built for and gives up the ones it would get
6979    // wrong.
6980    let alpha = stops[0].color.to_array()[3];
6981    if stops.iter().any(|s| s.color.to_array()[3] != alpha) {
6982        return None;
6983    }
6984
6985    // Which axis varies, and the two coordinates it runs between.
6986    let horizontal = start.y == end.y && start.x != end.x;
6987    let vertical = start.x == end.x && start.y != end.y;
6988    let (from, to) = if horizontal {
6989        (start.x, end.x)
6990    } else if vertical {
6991        (start.y, end.y)
6992    } else {
6993        return None;
6994    };
6995
6996    // The endpoints are the shape's own edges, in either order. Exact, because
6997    // anything else leaves a parameter outside `[0, 1]` somewhere in the shape
6998    // and the tile mode starts to matter.
6999    let (low, high) = if horizontal {
7000        (rect.left, rect.right)
7001    } else {
7002        (rect.top, rect.bottom)
7003    };
7004    if (from.min(to), from.max(to)) != (low, high) {
7005        return None;
7006    }
7007
7008    let mut sections = Vec::with_capacity(stops.len() - 1);
7009    for pair in stops.windows(2) {
7010        let (a, b) = (&pair[0], &pair[1]);
7011        // A zero-width section contributes nothing and would be a degenerate
7012        // quad; a repeated offset is how a caller asks for a hard edge, and
7013        // skipping it is what produces one.
7014        if a.offset == b.offset {
7015            continue;
7016        }
7017        let at = |t: f32| from + (to - from) * t;
7018        let (p, q) = (at(a.offset), at(b.offset));
7019        let (ca, cb) = (premultiplied(a.color), premultiplied(b.color));
7020        // Wound the same way for both orientations -- top-left, top-right,
7021        // bottom-right, bottom-left of the section -- so the colors differ
7022        // instead of the corners. Which corners sit at the section's start
7023        // depends on which axis varies: along x it is the first and last, along
7024        // y the first two.
7025        let (corners, colors) = if horizontal {
7026            (
7027                [
7028                    Vec2::new(p, rect.top),
7029                    Vec2::new(q, rect.top),
7030                    Vec2::new(q, rect.bottom),
7031                    Vec2::new(p, rect.bottom),
7032                ],
7033                [ca, cb, cb, ca],
7034            )
7035        } else {
7036            (
7037                [
7038                    Vec2::new(rect.left, p),
7039                    Vec2::new(rect.right, p),
7040                    Vec2::new(rect.right, q),
7041                    Vec2::new(rect.left, q),
7042                ],
7043                [ca, ca, cb, cb],
7044            )
7045        };
7046        sections.push(GradientSection { corners, colors });
7047    }
7048    (!sections.is_empty()).then_some(sections)
7049}
7050
7051fn premultiplied(color: Color) -> [f32; 4] {
7052    let [r, g, b, a] = color.to_array();
7053    [r * a, g * a, b * a, a]
7054}
7055
7056#[cfg(test)]
7057mod tests {
7058    use super::*;
7059
7060    fn canvas() -> Canvas {
7061        Canvas::new(Extent2D::new(128, 128))
7062    }
7063
7064    /// A backdrop layer opened under a clip is the size of the clip.
7065    ///
7066    /// It used to be the size of the parent, whatever the clip said, so a
7067    /// frosted panel a fortieth of the frame's area recorded a frame-sized
7068    /// target. The clip binds the layer's content and the draw that composites
7069    /// it alike, so there is nothing outside it for the layer to hold.
7070    ///
7071    /// The extents are asserted rather than the pixels because the pixels do
7072    /// not change: the sibling test below is what says they do not.
7073    #[test]
7074    fn a_backdrop_layer_under_a_clip_is_no_larger_than_the_clip() {
7075        let mut canvas = canvas();
7076        canvas.clear(Color::srgb(0.2, 0.3, 0.4, 1.0));
7077        canvas
7078            .draw_rect(
7079                Rect::new(0.0, 0.0, 128.0, 128.0),
7080                &Paint::fill(Color::srgb(0.9, 0.2, 0.2, 1.0)),
7081            )
7082            .expect("the ground");
7083        canvas.save();
7084        canvas
7085            .clip_rect(Rect::new(40.0, 40.0, 80.0, 80.0))
7086            .expect("the clip");
7087        canvas.save_layer(Layer::opacity(1.0).with_backdrop_blur(4.0));
7088        canvas
7089            .draw_rect(
7090                Rect::new(40.0, 40.0, 80.0, 80.0),
7091                &Paint::fill(Color::srgb(1.0, 0.6, 0.0, 0.6)),
7092            )
7093            .expect("the panel");
7094        canvas.restore();
7095        canvas.restore();
7096
7097        let recording = canvas.finish();
7098        let frame = recording.extent;
7099        let narrowed: Vec<_> = recording
7100            .passes
7101            .iter()
7102            .map(|pass| pass.extent)
7103            .filter(|extent| *extent != frame)
7104            .collect();
7105        // The layer's own target and both passes of the backdrop's blur. What
7106        // stays frame-sized is the pass being captured and the one the frame
7107        // ends in, and neither is allocated for this layer.
7108        assert_eq!(
7109            narrowed.len(),
7110            3,
7111            "three passes should be sized to the clip, and {} are: {:?}",
7112            narrowed.len(),
7113            recording
7114                .passes
7115                .iter()
7116                .map(|pass| pass.extent)
7117                .collect::<Vec<_>>()
7118        );
7119        for extent in narrowed {
7120            assert!(
7121                extent.width <= 48 && extent.height <= 48,
7122                "a pass came out {}x{} for a clip forty pixels across",
7123                extent.width,
7124                extent.height
7125            );
7126        }
7127    }
7128
7129    /// A layer sharing a backdrop key is narrowed too, and its capture is not.
7130    ///
7131    /// These two are separate regions and were once excluded together. The
7132    /// layer's own target is bound by the clip exactly as an unshared one is.
7133    /// What the key shares is the capture and the filtered image over it, and
7134    /// those have to cover every group naming the key -- so they stay the
7135    /// parent's size, and a second group somewhere else reads the same pass.
7136    #[test]
7137    fn a_shared_backdrop_layer_is_narrowed_while_its_capture_is_not() {
7138        let mut canvas = canvas();
7139        canvas.clear(Color::srgb(0.2, 0.3, 0.4, 1.0));
7140        let panel = |canvas: &mut Canvas, clip: Rect| {
7141            canvas.save();
7142            canvas.clip_rect(clip).expect("the clip");
7143            canvas.save_layer(
7144                Layer::opacity(1.0)
7145                    .with_backdrop_blur(4.0)
7146                    .with_backdrop_id(7),
7147            );
7148            canvas
7149                .draw_rect(clip, &Paint::fill(Color::srgb(1.0, 0.6, 0.0, 0.6)))
7150                .expect("the panel");
7151            canvas.restore();
7152            canvas.restore();
7153        };
7154        // Opposite corners, so nothing can pass by covering one with the other.
7155        panel(&mut canvas, Rect::new(8.0, 8.0, 48.0, 48.0));
7156        panel(&mut canvas, Rect::new(80.0, 80.0, 120.0, 120.0));
7157
7158        let recording = canvas.finish();
7159        let frame = recording.extent;
7160        let extents: Vec<_> = recording.passes.iter().map(|pass| pass.extent).collect();
7161        let narrowed: Vec<_> = extents.iter().filter(|e| **e != frame).collect();
7162        // One target per panel, and nothing else: the capture and the two
7163        // passes its blur takes are shared, and all three cover the parent.
7164        assert_eq!(
7165            narrowed.len(),
7166            2,
7167            "one narrowed target per panel and no more, in {extents:?}"
7168        );
7169        for extent in narrowed {
7170            assert!(
7171                extent.width <= 40 && extent.height <= 40,
7172                "a panel target came out {}x{} for a clip forty pixels across",
7173                extent.width,
7174                extent.height
7175            );
7176        }
7177        // The second panel pays for its own target and nothing else: the cut,
7178        // and the two passes of the blur over it, are taken once between them.
7179        // Six in all -- the cut, the blur's two, a target each, and the pass
7180        // the frame ends in, which holds both composites.
7181        assert_eq!(
7182            extents.len(),
7183            6,
7184            "a cut, two blur passes, a target each, and the frame's own, in \
7185             {extents:?}"
7186        );
7187    }
7188
7189    /// And it draws what stating the clip as the layer's bounds would.
7190    ///
7191    /// The narrowing above is an optimization, so the thing to check is that it
7192    /// is only that. A caller who writes the bounds out has always taken the
7193    /// bounded path; a caller who relies on the clip now takes it too, and the
7194    /// two recordings have to describe the same picture.
7195    #[test]
7196    fn narrowing_to_the_clip_records_what_stating_it_would() {
7197        let build = |bounded: bool| {
7198            let mut canvas = canvas();
7199            canvas.clear(Color::srgb(0.1, 0.1, 0.1, 1.0));
7200            canvas
7201                .draw_rect(
7202                    Rect::new(0.0, 20.0, 128.0, 60.0),
7203                    &Paint::fill(Color::srgb(0.9, 0.4, 0.1, 1.0)),
7204                )
7205                .expect("the ground");
7206            let clip = Rect::new(24.0, 34.0, 104.0, 94.0);
7207            canvas.save();
7208            canvas.clip_rect(clip).expect("the clip");
7209            let layer = Layer::opacity(1.0).with_backdrop_blur(6.0);
7210            if bounded {
7211                canvas.save_layer_bounds(layer, clip);
7212            } else {
7213                canvas.save_layer(layer);
7214            }
7215            canvas.restore();
7216            canvas.restore();
7217            canvas.finish()
7218        };
7219        let from_clip = build(false);
7220        let from_bounds = build(true);
7221        assert_eq!(from_clip.passes.len(), from_bounds.passes.len());
7222        for (a, b) in from_clip.passes.iter().zip(from_bounds.passes.iter()) {
7223            assert_eq!(a.extent, b.extent, "the two spellings size a pass alike");
7224            assert_eq!(
7225                a.batch.vertices(),
7226                b.batch.vertices(),
7227                "the two spellings record the same geometry"
7228            );
7229        }
7230    }
7231
7232    /// How far a blur reaches, which four comments in this tree got wrong.
7233    ///
7234    /// The kernel is truncated at `(sigma - 0.5) * sqrt(3)` -- upstream's
7235    /// `kKernelRadiusPerSigma` -- and every layer sized to hold a blur asks
7236    /// `blur_reach` for it. Nothing pinned the arithmetic, so the prose drifted
7237    /// to "three deviations" in four places and stayed there: a test written
7238    /// against that phrase expected 88 where the renderer gives 68, and the
7239    /// phrase was wrong rather than the renderer.
7240    ///
7241    /// Pinned here because the number is not free to change. It decides how
7242    /// wide a halo is, so moving it moves every blurred picture away from
7243    /// upstream's -- and it decides a target's size, so getting it *smaller*
7244    /// cuts the halo off square, which reads as a shadow with a straight edge
7245    /// rather than as arithmetic.
7246    #[test]
7247    fn a_blur_reaches_the_radius_its_kernel_is_truncated_at() {
7248        // Sqrt three per deviation, less the half pixel upstream subtracts, and
7249        // rounded out to a whole texel because a target is whole texels.
7250        assert_eq!(blur_reach(8.0), 13.0, "ceil(7.5 * sqrt(3))");
7251        assert_eq!(blur_reach(2.0), 3.0, "ceil(1.5 * sqrt(3))");
7252
7253        // Not three deviations, which is what the prose used to say. Stated as
7254        // its own assertion because the two agree closely enough at small sigma
7255        // that a spot check would not tell them apart.
7256        assert!(
7257            blur_reach(50.0) < 3.0 * 50.0,
7258            "the kernel is truncated nearer one and three quarter deviations \
7259             than three"
7260        );
7261
7262        // A sigma that describes no blur reaches nowhere, and a layer asking
7263        // for one gets no widening rather than half a pixel of it.
7264        assert_eq!(blur_reach(0.0), 0.0);
7265        assert_eq!(blur_reach(0.5), 0.0, "the half pixel is subtracted first");
7266        assert_eq!(blur_reach(-1.0), 0.0);
7267
7268        // And it never shrinks as the blur widens, which is what makes a target
7269        // sized from it safe.
7270        let mut previous = 0.0;
7271        for tenth in 0..600 {
7272            let reach = blur_reach(tenth as f32 / 10.0);
7273            assert!(
7274                reach >= previous,
7275                "reach fell at sigma {}",
7276                tenth as f32 / 10.0
7277            );
7278            previous = reach;
7279        }
7280    }
7281
7282    #[test]
7283    fn drawing_accumulates_into_one_batch() {
7284        let mut canvas = canvas();
7285        let paint = Paint::fill(Color::WHITE);
7286        canvas
7287            .draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &paint)
7288            .unwrap();
7289        canvas
7290            .draw_rect(Rect::new(20.0, 20.0, 30.0, 30.0), &paint)
7291            .unwrap();
7292
7293        // Two shapes, one batch: describing the frame before submitting is what
7294        // lets them share a pass.
7295        //
7296        // And one *draw*, which is stronger and newer. Both take the analytic
7297        // route, and that route carries the shape's own space on its vertices
7298        // rather than in its material, so two rectangles of a size differing
7299        // only in where they sit are the same material and merge. It was two
7300        // until then, with the placement inside the material making every
7301        // instance unequal to every other.
7302        let recording = canvas.finish();
7303        assert_eq!(recording.draw_count(), 1);
7304    }
7305
7306    #[test]
7307    fn an_invisible_paint_records_nothing() {
7308        let mut canvas = canvas();
7309        let invisible = Paint::fill(Color::WHITE.with_alpha(0.0));
7310        canvas
7311            .draw_rect(Rect::new(0.0, 0.0, 10.0, 10.0), &invisible)
7312            .unwrap();
7313        canvas
7314            .draw_circle(Vec2::new(5.0, 5.0), 4.0, &invisible)
7315            .unwrap();
7316
7317        // Rejecting early keeps empty geometry out of the batch rather than
7318        // tessellating it and discovering it was empty.
7319        assert!(canvas.finish().is_empty());
7320    }
7321
7322    #[test]
7323    fn outsetting_grows_every_side_and_negating_it_shrinks_back() {
7324        let rect = Rect::new(10.0, 20.0, 40.0, 60.0);
7325        let grown = rect.outset(5.0);
7326        assert_eq!(
7327            (grown.left, grown.top, grown.right, grown.bottom),
7328            (5.0, 15.0, 45.0, 65.0)
7329        );
7330        // Symmetric, which is what lets a caller undo one: a blur's reach is
7331        // the same in both directions and a target sized by it has to be too.
7332        let back = grown.outset(-5.0);
7333        assert_eq!(
7334            (back.left, back.top, back.right, back.bottom),
7335            (rect.left, rect.top, rect.right, rect.bottom)
7336        );
7337    }
7338
7339    #[test]
7340    fn degenerate_shapes_record_nothing() {
7341        let mut canvas = canvas();
7342        let paint = Paint::fill(Color::WHITE);
7343        canvas
7344            .draw_rect(Rect::new(10.0, 10.0, 10.0, 20.0), &paint)
7345            .unwrap();
7346        canvas.draw_circle(Vec2::ZERO, 0.0, &paint).unwrap();
7347        assert!(canvas.finish().is_empty());
7348    }
7349
7350    #[test]
7351    fn save_and_restore_return_the_previous_transform() {
7352        let mut canvas = canvas();
7353        canvas.translate(10.0, 20.0);
7354        let outer = canvas.transform();
7355
7356        canvas.save();
7357        canvas.scale(3.0, 3.0).rotate(0.5);
7358        assert_ne!(canvas.transform(), outer);
7359
7360        canvas.restore();
7361        assert_eq!(canvas.transform(), outer);
7362        assert_eq!(canvas.save_depth(), 0);
7363    }
7364
7365    #[test]
7366    fn saves_nest() {
7367        let mut canvas = canvas();
7368        let identity = canvas.transform();
7369        canvas.save();
7370        canvas.translate(5.0, 0.0);
7371        canvas.save();
7372        canvas.translate(5.0, 0.0);
7373        assert_eq!(canvas.save_depth(), 2);
7374
7375        canvas.restore();
7376        assert_eq!(
7377            canvas.transform(),
7378            Transform2D::from(Affine2::from_translation(Vec2::new(5.0, 0.0)))
7379        );
7380        canvas.restore();
7381        assert_eq!(canvas.transform(), identity);
7382    }
7383
7384    #[test]
7385    fn restoring_too_often_leaves_the_transform_alone() {
7386        let mut canvas = canvas();
7387        canvas.translate(7.0, 3.0);
7388        let current = canvas.transform();
7389        // An unbalanced restore is a caller bug, but taking down a frame loop
7390        // for it is worse than continuing with a transform that is still right.
7391        canvas.restore().restore().restore();
7392        assert_eq!(canvas.transform(), current);
7393    }
7394
7395    #[test]
7396    fn transforms_compose_in_the_order_applied() {
7397        let mut canvas = canvas();
7398        canvas.translate(10.0, 0.0).scale(2.0, 2.0);
7399        // Scale then translate, or translate then scale, place a point very
7400        // differently; the later call applies in the frame the earlier set up.
7401        let mapped = canvas.transform().project_point2(Vec2::new(1.0, 0.0));
7402        assert!((mapped - Vec2::new(12.0, 0.0)).length() < 1e-5);
7403    }
7404
7405    #[test]
7406    fn antialiasing_is_off_unless_something_asks_for_it() {
7407        let mut canvas = canvas();
7408        let aliased = Paint::fill(Color::WHITE).with_anti_alias(false);
7409        canvas
7410            .draw_rect(Rect::from_size(10.0, 10.0), &aliased)
7411            .unwrap();
7412        // Multisampling costs bandwidth, and a frame of solid rectangles gains
7413        // nothing from it.
7414        assert_eq!(canvas.finish().root().descriptor.samples, 1);
7415    }
7416
7417    #[test]
7418    fn one_antialiased_shape_antialiases_the_frame() {
7419        let mut canvas = canvas();
7420        canvas
7421            .draw_rect(
7422                Rect::from_size(10.0, 10.0),
7423                &Paint::fill(Color::WHITE).with_anti_alias(false),
7424            )
7425            .unwrap();
7426        // A path, because it has to be tessellated. A circle or a rounded
7427        // rectangle would antialias itself from a distance field and would
7428        // rightly leave the pass alone -- which the test below is about.
7429        let mut triangle = PathBuilder::new();
7430        triangle
7431            .move_to(Vec2::new(20.0, 20.0))
7432            .line_to(Vec2::new(40.0, 20.0))
7433            .line_to(Vec2::new(20.0, 40.0))
7434            .close();
7435        canvas
7436            .draw_path(&triangle.build(), &Paint::fill(Color::WHITE))
7437            .unwrap();
7438
7439        // Sampling is a property of the pass, so it cannot vary per shape.
7440        // Honoring the request for the frame beats silently ignoring it.
7441        assert!(canvas.finish().root().descriptor.samples > 1);
7442    }
7443
7444    #[test]
7445    fn a_shape_that_antialiases_itself_leaves_the_pass_alone() {
7446        // The saving that comes with the distance field, and the reason it is
7447        // worth having beyond the vertex count: a frame whose only antialiased
7448        // shapes compute their own coverage does not have to multisample, which
7449        // is four times the fill and four times the bandwidth for an edge it
7450        // was already going to get right.
7451        let mut canvas = canvas();
7452        canvas
7453            .draw_circle(Vec2::splat(20.0), 8.0, &Paint::fill(Color::WHITE))
7454            .unwrap();
7455        canvas
7456            .draw_rrect(
7457                Rect::new(30.0, 30.0, 60.0, 50.0),
7458                6.0,
7459                &Paint::fill(Color::WHITE),
7460            )
7461            .unwrap();
7462        assert_eq!(
7463            canvas.finish().root().descriptor.samples,
7464            1,
7465            "an analytic shape should not multisample the pass"
7466        );
7467    }
7468
7469    /// A black shadow is untouched by the tonal remap; a colored one is not.
7470    ///
7471    /// Both halves matter. The remap exists for colored shadows, and if it
7472    /// moved a black one it would change nearly every shadow anybody draws --
7473    /// so the identity is the safety property and the change is the feature.
7474    ///
7475    /// The figures are upstream's formula evaluated by hand rather than
7476    /// recorded from this implementation, which is the only way a test of a
7477    /// port can fail when the port is wrong.
7478    #[test]
7479    fn a_colored_shadow_is_tonally_adjusted_and_a_black_one_is_not() {
7480        // Black: at zero luminance the color term vanishes and the alpha is
7481        // left at the quarter it started from.
7482        let black = super::tonal_shadow_color(Color::srgb(0.0, 0.0, 0.0, 1.0));
7483        let [r, g, b, a] = black.to_srgb();
7484        assert_eq!([r, g, b], [0.0, 0.0, 0.0], "a black shadow gained color");
7485        assert!(
7486            (a - 0.25).abs() < 1e-6,
7487            "a black shadow should keep the quarter alpha, got {a}"
7488        );
7489
7490        // Saturated red at full alpha. Luminance is a half, so:
7491        //   alpha_adjust    = (2.6 + (-2.66667 + 1.06667*0.25)*0.25)*0.25 = 0.5
7492        //   color_alpha     = (3.544762 + (-4.891428 + 2.3466*0.5)*0.5)*0.5
7493        //                   = 0.842849, times alpha_adjust  = 0.421424
7494        //   grayscale_alpha = 0.25 * (1 - 0.4*0.5)           = 0.2
7495        //   color_scale     = 0.421424 * 0.8                 = 0.337140
7496        //   tonal_alpha     = 0.537140
7497        //   unpremul_scale  = 0.337140 / 0.537140            = 0.627650
7498        let red = super::tonal_shadow_color(Color::srgb(1.0, 0.0, 0.0, 1.0));
7499        let [r, g, b, a] = red.to_srgb();
7500        assert!(
7501            (a - 0.537_140).abs() < 1e-4,
7502            "the tonal alpha for a red shadow is {a}, not 0.53714"
7503        );
7504        assert!(
7505            (r - 0.627_650).abs() < 1e-4,
7506            "the tonal red for a red shadow is {r}, not 0.62765"
7507        );
7508        assert_eq!([g, b], [0.0, 0.0], "a red shadow gained other channels");
7509
7510        // And it is emphatically not what taking a quarter of the alpha gives,
7511        // which is what this used to do.
7512        assert!(
7513            a > 0.5,
7514            "the remap left the alpha near the naive quarter: {a}"
7515        );
7516
7517        // A mid-tone, which is the case that says *which space* this runs in.
7518        // Neither of the colors above can: zero and one are fixed points of the
7519        // transfer function, so a saturated primary is the same number encoded
7520        // or linear and the two readings agree by accident. Here they do not --
7521        // the same formula on linear light gives (0.137, 0.032, 0.004) at an
7522        // alpha of 0.410, against upstream's (0.345, 0.173, 0.058) at 0.506.
7523        let midtone = super::tonal_shadow_color(Color::srgb(0.6, 0.3, 0.1, 1.0));
7524        let [r, g, b, a] = midtone.to_srgb();
7525        for (got, want, name) in [
7526            (a, 0.506_265, "alpha"),
7527            (r, 0.345_193, "red"),
7528            (g, 0.172_596, "green"),
7529            (b, 0.057_532, "blue"),
7530        ] {
7531            assert!(
7532                (got - want).abs() < 1e-4,
7533                "the tonal {name} for a mid-tone shadow is {got}, not {want} -- \
7534                 which is what running the remap on light rather than on encoded \
7535                 values would give"
7536            );
7537        }
7538    }
7539
7540    #[test]
7541    fn clearing_sets_the_background_rather_than_recording_a_draw() {
7542        let mut canvas = canvas();
7543        canvas.clear(Color::rgba8(20, 30, 40, 255));
7544        let recording = canvas.finish();
7545        // A clear is a pass property; recording it as a full-target rectangle
7546        // would cost a draw and defeat the load operation.
7547        assert!(recording.is_empty());
7548        assert!(recording.root().descriptor.clear.is_some());
7549    }
7550
7551    /// A morphology radius cannot decide how many passes a recording holds.
7552    ///
7553    /// The loop emits a pass per `MORPHOLOGY_TAPS` texels, so before the clamp a
7554    /// radius of a million gave sixty-two thousand passes and `1e20` exhausted
7555    /// memory -- through `Morphology::dilate`, whose sanitizing rejects only what
7556    /// is negative or not finite. Nothing about that input was malformed.
7557    #[test]
7558    fn a_huge_morphology_radius_is_bounded_by_what_the_target_can_show() {
7559        // The morphology materials a radius produces, in order. Compared rather
7560        // than counted, because the clamp's justification is that a wider window
7561        // cannot change a pixel -- and identical materials over identical passes
7562        // is that claim in a form a machine can check without a device. It says
7563        // the two requests are not merely the same size but the same recording,
7564        // and the shader is a function of what it is handed.
7565        let filters = |radius: f32| {
7566            let mut canvas = canvas();
7567            canvas.clear(Color::BLACK);
7568            canvas.save_layer(
7569                Layer::opacity(1.0).with_morphology(Morphology::dilate(radius, radius)),
7570            );
7571            canvas
7572                .draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE))
7573                .expect("a rectangle is a rectangle");
7574            canvas.restore();
7575            let recording = canvas.finish();
7576            let morphology: Vec<Material> = recording
7577                .passes
7578                .iter()
7579                .flat_map(|pass| pass.batch.draws())
7580                .filter(|draw| matches!(draw.material, Material::Morphology { .. }))
7581                .map(|draw| draw.material.clone())
7582                .collect();
7583            (recording.passes.len(), morphology)
7584        };
7585
7586        // A 128-square target, so each axis saturates at 128 texels: four passes
7587        // an axis at thirty-two taps each, plus the root and the composite.
7588        let (passes, saturated) = filters(128.0);
7589        assert!(passes < 16, "{passes} passes to saturate a 128 square");
7590        assert_eq!(saturated.len(), 8, "{saturated:?}");
7591        for radius in [1e3f32, 1e6, 1e20, f32::MAX] {
7592            let (grew, wider) = filters(radius);
7593            assert_eq!(
7594                grew, passes,
7595                "a radius of {radius:e} cost more passes than saturating the target"
7596            );
7597            assert_eq!(
7598                wider, saturated,
7599                "a radius of {radius:e} asked for a different filter than saturating the target"
7600            );
7601        }
7602    }
7603
7604    /// Infinity terminates, which it did not before.
7605    ///
7606    /// `Morphology::dilate` maps it to zero, so this reaches the loop the only way
7607    /// left: the fields are public, so a struct literal skips the constructor.
7608    /// Subtracting the taps from infinity leaves infinity, so the loop never ended
7609    /// and each turn of it allocated a pass.
7610    #[test]
7611    fn a_non_finite_morphology_radius_is_no_filter_rather_than_no_end() {
7612        for radius in [f32::INFINITY, f32::NEG_INFINITY, f32::NAN] {
7613            let morphology = Morphology {
7614                radius: [radius, radius],
7615                dilate: true,
7616            };
7617            assert_eq!(
7618                morphology.applied_radius(Extent2D::new(128, 128)),
7619                [0.0, 0.0],
7620                "a radius of {radius} survived as something to apply"
7621            );
7622            let mut canvas = canvas();
7623            canvas.clear(Color::BLACK);
7624            canvas.save_layer(Layer {
7625                morphology: Some(morphology),
7626                ..Layer::opacity(1.0)
7627            });
7628            canvas.restore();
7629            // Reaching here at all is the assertion.
7630            assert!(!canvas.finish().passes.is_empty());
7631        }
7632    }
7633
7634    /// The clamp is per axis, and is the extent of that axis.
7635    #[test]
7636    fn the_applied_radius_is_clamped_to_each_axis_separately() {
7637        let morphology = Morphology {
7638            radius: [1e9, 7.0],
7639            dilate: false,
7640        };
7641        assert_eq!(
7642            morphology.applied_radius(Extent2D::new(64, 256)),
7643            [64.0, 7.0],
7644            "the clamp took the wrong axis or clamped what did not need it"
7645        );
7646        // Negative is refused rather than reflected, as `sane` does.
7647        let negative = Morphology {
7648            radius: [-5.0, -0.0],
7649            dilate: true,
7650        };
7651        assert_eq!(negative.applied_radius(Extent2D::new(64, 64)), [0.0, 0.0]);
7652    }
7653
7654    /// A blur's reduction terminates whatever the sigma and the extent.
7655    ///
7656    /// The reduction doubles a divisor until the kernel fits the tap budget or
7657    /// the axis runs out. An infinite sigma never satisfies the first, so the
7658    /// extent is the only stop -- and against a very large extent the divisor
7659    /// reached two to the thirty-first, where the old condition's `scale * 2`
7660    /// overflowed. Release was worse rather than better: the product wrapped to
7661    /// zero and the division panicked.
7662    ///
7663    /// A struct literal is how a non-finite sigma gets here at all, since
7664    /// `Layer::with_blur_xy` maps one to zero. `Layer::blur` is a public field.
7665    ///
7666    /// Found by `a_sequence_of_any_operations_records_something_addressable`,
7667    /// which generated a layer with an infinite blur inside bounds of `-1e20`.
7668    #[test]
7669    fn the_blur_reduction_terminates_for_any_sigma_and_extent() {
7670        // Reaching the end of this at all is most of the assertion.
7671        for extent in [0u32, 1, 2, 3, 128, u32::MAX / 2, u32::MAX - 1, u32::MAX] {
7672            for sigma in [
7673                f32::INFINITY,
7674                f32::NEG_INFINITY,
7675                f32::NAN,
7676                -1.0,
7677                0.0,
7678                1e30,
7679                f32::MAX,
7680                500.0,
7681                8.0,
7682            ] {
7683                let scale = Canvas::blur_downsample(sigma, extent);
7684                assert!(
7685                    scale.is_power_of_two(),
7686                    "sigma {sigma:e} over {extent} gave a divisor of {scale}, which \
7687                     is not a power of two, so the halvings are not exact"
7688                );
7689                assert!(
7690                    scale == 1 || scale <= extent,
7691                    "sigma {sigma:e} reduced a {extent}-texel axis by {scale}, which \
7692                     is more than the axis has"
7693                );
7694            }
7695        }
7696
7697        // A sigma that is not a length reduces nothing, on the same terms as
7698        // `with_blur_xy` refusing it and `Morphology::applied_radius` refusing a
7699        // non-finite radius.
7700        for sigma in [f32::INFINITY, f32::NAN, -1.0, 0.0] {
7701            assert_eq!(
7702                Canvas::blur_downsample(sigma, u32::MAX),
7703                1,
7704                "a sigma of {sigma} asked for a reduction"
7705            );
7706        }
7707
7708        // And a real one still reduces, so the guard above did not turn the
7709        // reduction off for everything.
7710        assert!(
7711            Canvas::blur_downsample(500.0, 4096) > 1,
7712            "a wide blur on a large target stopped reducing, which is what the tap \
7713             budget exists to avoid"
7714        );
7715    }
7716
7717    /// Which route a rounded rectangle took is read off what it recorded:
7718    /// the field is one quad, the tessellated outline is many vertices.
7719    fn draw_rounded(canvas: &mut Canvas, paint: &Paint) {
7720        canvas
7721            .draw_rrect(Rect::new(10.3, 12.7, 90.1, 70.6), 12.0, paint)
7722            .expect("a rounded rectangle");
7723    }
7724
7725    /// A canvas whose pass is already multisampled: a background, and a fill
7726    /// `draw_rect` tessellates with antialiasing, placed off the pixel grid.
7727    fn multisampled() -> Canvas {
7728        let mut canvas = canvas();
7729        canvas.clear(Color::BLACK);
7730        canvas
7731            .draw_rect(
7732                Rect::new(100.5, 100.5, 120.5, 120.5),
7733                &Paint::fill(Color::WHITE),
7734            )
7735            .expect("a rectangle");
7736        canvas
7737    }
7738
7739    fn root_pass(canvas: Canvas) -> (u32, usize) {
7740        let recording = canvas.finish();
7741        let pass = recording.passes.last().expect("a root pass");
7742        (pass.descriptor.samples, pass.batch.vertices().len())
7743    }
7744
7745    /// A fill is tessellated once the pass is multisampled, and takes the field
7746    /// before that. See `draw_rrect` for the measurement.
7747    #[test]
7748    fn a_rounded_fill_is_tessellated_once_the_pass_is_multisampled() {
7749        let paint = Paint::fill(Color::WHITE);
7750        let (_, rectangle) = root_pass(multisampled());
7751
7752        let mut after = multisampled();
7753        draw_rounded(&mut after, &paint);
7754        let (samples, vertices) = root_pass(after);
7755        assert_eq!(samples, 4);
7756        assert!(
7757            vertices - rectangle > 4,
7758            "tessellated, so more than a quad: {}",
7759            vertices - rectangle
7760        );
7761
7762        // Nothing has multisampled the pass, so the field keeps it at one
7763        // sample, background or not.
7764        let mut first = canvas();
7765        first.clear(Color::BLACK);
7766        draw_rounded(&mut first, &paint);
7767        assert_eq!(root_pass(first), (1, 4));
7768        let mut over_the_surface = canvas();
7769        draw_rounded(&mut over_the_surface, &paint);
7770        assert_eq!(root_pass(over_the_surface), (1, 4));
7771    }
7772
7773    /// A stroke keeps the field in a pass that is already multisampled.
7774    #[test]
7775    fn a_rounded_stroke_keeps_the_field_in_a_multisampled_pass() {
7776        let (_, rectangle) = root_pass(multisampled());
7777        let mut canvas = multisampled();
7778        draw_rounded(&mut canvas, &Paint::stroke(Color::WHITE, 3.0));
7779        let (samples, vertices) = root_pass(canvas);
7780        assert_eq!(samples, 4);
7781        assert_eq!(vertices - rectangle, 4, "one quad from the field");
7782    }
7783}