Skip to main content

emblema_core/
paint.rs

1//! How a shape is drawn.
2
3use std::borrow::Cow;
4
5use crate::canvas::{Morphology, Rect};
6use crate::color::Color;
7use emblema_geometry::dash::Dash;
8use emblema_geometry::stroke::StrokeStyle;
9use emblema_geometry::transform::{transformed_bounds, unbounded, Transform2D};
10use emblema_hal::{BlendMode, Extent2D, TileMode};
11use emblema_hal::{ColorFilter, Sampling};
12use glam::Vec2;
13
14/// A color stop in a gradient.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct GradientStop {
17    pub color: Color,
18    /// Position along the gradient, from zero to one.
19    pub offset: f32,
20}
21
22impl GradientStop {
23    pub fn new(color: Color, offset: f32) -> Self {
24        Self { color, offset }
25    }
26}
27
28/// What fills a shape.
29#[derive(Debug, Clone, PartialEq)]
30pub enum Shader {
31    Solid(Color),
32    /// A gradient along the line between two points **in user space**.
33    ///
34    /// The endpoints travel through the canvas transform with the geometry, so
35    /// a gradient rotates and scales with the shape it fills rather than
36    /// staying pinned to the screen.
37    LinearGradient {
38        start: Vec2,
39        end: Vec2,
40        stops: Vec<GradientStop>,
41        /// What fills the shape beyond the two endpoints.
42        ///
43        /// A gradient is defined by two points and a shape is rarely exactly
44        /// that long, so this is not an edge case: clamping holds the end
45        /// colors, repeating tiles the ramp, and decal leaves the outside
46        /// empty. Set with [`Paint::with_tile_mode`], the same call an image
47        /// uses.
48        tile: TileMode,
49    },
50    /// A gradient outward from a center **in user space**, reaching its last
51    /// stop at `radius`.
52    RadialGradient {
53        center: Vec2,
54        radius: f32,
55        stops: Vec<GradientStop>,
56        /// What fills the shape beyond `radius`. See [`Shader::LinearGradient`].
57        tile: TileMode,
58    },
59    /// A texture, mapped onto a rectangle **in user space**.
60    ///
61    /// The rectangle travels through the canvas transform with the geometry, so
62    /// an image rotates and scales with the shape it fills. It is the region
63    /// the image covers, not the region drawn: filling a circle with this paint
64    /// draws a circular piece of the image.
65    ///
66    /// `slot` indexes the table supplied when the recording is drawn. The
67    /// canvas names a slot rather than holding a texture because it records
68    /// without touching a device, and a backend texture is not something it can
69    /// name. Assigning slots is the caller's business for now; a registry that
70    /// did it for them is a separate piece of design.
71    Image {
72        slot: u32,
73        rect: Rect,
74        /// Scales the sampled color, for drawing an image translucently.
75        alpha: f32,
76        /// What happens outside the image, across and then down: an image
77        /// can repeat along x and clamp along y, as dart:ui's `ImageShader`
78        /// and Impeller's tiled texture contents take them. Set both with
79        /// [`Paint::with_tile_mode`], or each with [`Paint::with_tile_modes`].
80        tile: [TileMode; 2],
81        /// Which part of the image to draw, from zero to one in each axis.
82        ///
83        /// The whole image by default. Set it with [`Paint::with_source`], or
84        /// with [`Paint::with_source_pixels`] if you would rather state it in
85        /// texels and hand over the size you uploaded.
86        source: Rect,
87        /// Multiplies the sampled color. White changes nothing.
88        tint: Color,
89        /// How to read between texels. See [`Paint::with_sampling`].
90        sampling: Sampling,
91    },
92    /// A gradient around a center **in user space**, running between two angles
93    /// in radians, measured counter-clockwise from the positive X axis.
94    SweepGradient {
95        center: Vec2,
96        start_angle: f32,
97        end_angle: f32,
98        stops: Vec<GradientStop>,
99        /// What fills the directions the arc does not cover.
100        ///
101        /// A sweep of a full turn covers every direction and this changes
102        /// nothing; it is a partial sweep that has an outside.
103        tile: TileMode,
104    },
105    /// A caller's own fragment program.
106    ///
107    /// The one shader here this renderer did not write. `program` names one
108    /// registered with a context, and `uniforms` are the floats it reads --
109    /// laid out as the program's own declaration expects, which is a contract
110    /// between the caller's shader and the caller's code and not something
111    /// this renderer can check.
112    ///
113    /// At most [`RUNTIME_FLOATS`] of them, which the program reads from the
114    /// effect block at group 1, binding 1, and its first 52 also from the
115    /// material block at binding 0; the rest are dropped.
116    ///
117    /// [`RUNTIME_FLOATS`]: emblema_hal::RUNTIME_FLOATS
118    RuntimeEffect {
119        program: u32,
120        uniforms: Vec<f32>,
121        /// A texture slot the program may sample, if it declares one.
122        ///
123        /// The same table an image paint names, so a caller supplies them in
124        /// the same array beside the recording, in the order the program
125        /// declares its bindings.
126        ///
127        /// A binding the program declares and this leaves empty reads a
128        /// one-pixel opaque white texture -- what a solid fill binds, and what
129        /// keeps a pipeline's declared binding satisfied. Beyond
130        /// [`MAX_EFFECT_TEXTURES`] a caller is asking for a second descriptor
131        /// set layout, which would be one layout per program; the ceiling is
132        /// what buys a single shared one.
133        ///
134        /// [`MAX_EFFECT_TEXTURES`]: emblema_hal::MAX_EFFECT_TEXTURES
135        images: Vec<u32>,
136    },
137    /// A gradient between two circles **in user space**, reaching its first
138    /// stop on the first circle and its last on the second.
139    ///
140    /// This is the general form: a radial gradient is the case where the first
141    /// circle is a point at the second's center, and the two-point form is what
142    /// `dart:ui` reaches by giving `Gradient.radial` a focal point. It is kept
143    /// separate from [`Shader::RadialGradient`] rather than replacing it,
144    /// because the radial case folds its radius into a matrix and solves no
145    /// quadratic at all, and paying for the general solve on every ordinary
146    /// gradient would be a poor trade on the hardware this targets.
147    ///
148    /// Where no circle in the family passes through a point, nothing is drawn
149    /// there -- which is most of the plane when one circle is far outside the
150    /// other. That is a property of the two circles rather than of the tile
151    /// mode, which acts only where the parameter exists.
152    ConicalGradient {
153        start_center: Vec2,
154        start_radius: f32,
155        end_center: Vec2,
156        end_radius: f32,
157        stops: Vec<GradientStop>,
158        /// What fills the parameter outside the two circles. See
159        /// [`Shader::LinearGradient`].
160        tile: TileMode,
161    },
162}
163
164impl Shader {
165    /// How many color stops this paint carries, or zero where it carries none.
166    ///
167    /// Public because the threshold is: at or below [`MAX_STOPS`] a gradient
168    /// costs nothing beyond its material, and above it the recorder bakes a
169    /// small texture. Neither is visible in the result, so this exists for a
170    /// caller who cares about the cost rather than the picture.
171    ///
172    /// [`MAX_STOPS`]: emblema_hal::MAX_STOPS
173    pub fn stop_count(&self) -> usize {
174        match self {
175            Self::Solid(_) | Self::Image { .. } | Self::RuntimeEffect { .. } => 0,
176            Self::LinearGradient { stops, .. }
177            | Self::RadialGradient { stops, .. }
178            | Self::SweepGradient { stops, .. }
179            | Self::ConicalGradient { stops, .. } => stops.len(),
180        }
181    }
182
183    /// Whether this would draw anything at all.
184    pub fn is_visible(&self) -> bool {
185        match self {
186            Self::Solid(color) => !color.is_invisible(),
187            // What a caller's program draws is not knowable from here.
188            Self::RuntimeEffect { .. } => true,
189            Self::LinearGradient { stops, .. }
190            | Self::RadialGradient { stops, .. }
191            | Self::SweepGradient { stops, .. }
192            | Self::ConicalGradient { stops, .. } => stops.iter().any(|s| !s.color.is_invisible()),
193            // What the texture holds is unknown here, so only a zero alpha or
194            // an empty destination makes an image provably invisible.
195            Self::Image { alpha, rect, .. } => *alpha > 0.0 && !rect.is_empty(),
196        }
197    }
198
199    /// This shader with what it produces multiplied by `opacity`, which
200    /// [`Paint::opacity`] says is between zero and one.
201    ///
202    /// Folded into the colors the shader is stated in, which is exact: a
203    /// gradient interpolates straight color and premultiplies after, so a
204    /// stop's alpha scaled is the result's scaled; an image's alpha already
205    /// scales what it samples. A runtime effect is returned as it is: its
206    /// program writes the color, and upstream's `RuntimeEffectContents` does
207    /// not apply the factor either.
208    pub fn at_opacity(&self, opacity: f32) -> Shader {
209        let mut out = self.clone();
210        let scale = |c: &mut Color| *c = c.with_alpha(c.a * opacity);
211        match &mut out {
212            Self::Solid(color) => scale(color),
213            Self::Image { alpha, .. } => *alpha *= opacity,
214            Self::LinearGradient { stops, .. }
215            | Self::RadialGradient { stops, .. }
216            | Self::SweepGradient { stops, .. }
217            | Self::ConicalGradient { stops, .. } => {
218                stops.iter_mut().for_each(|s| scale(&mut s.color));
219            }
220            Self::RuntimeEffect { .. } => {}
221        }
222        out
223    }
224}
225
226/// Which part of a blurred shape survives.
227///
228/// A mask blur produces two things a picture can be made from: the shape's own
229/// coverage, and that coverage blurred. Every style here is one combination of
230/// the two, and naming them is what `dart:ui` and Skia both do -- a shadow
231/// wants the blur outside and nothing inside, a glow wants it inside, and a
232/// soft-edged solid wants the shape intact with the blur around it.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
234pub enum MaskBlurStyle {
235    /// The blurred coverage, and nothing else. Soft on both sides of the edge.
236    #[default]
237    Normal,
238    /// The shape at full strength, with the blur outside it.
239    Solid,
240    /// The blur outside the shape only. What a drop shadow behind an opaque
241    /// object is: the part that would be hidden is not drawn at all.
242    Outer,
243    /// The blur inside the shape only, which is an inner shadow or a glow
244    /// confined to what it lights.
245    Inner,
246}
247
248/// A function applied to what a paint drew, rather than to the color it
249/// computed.
250///
251/// The distinction from a color filter is what the input is. A color filter
252/// sees one color at a time and cannot know its neighbors; this sees the
253/// picture, which is what a blur needs.
254///
255/// The distinction from [`Paint::mask_blur`] is what is blurred. A mask blur
256/// blurs coverage and then fills, which is only the same picture as blurring
257/// the result when the fill does not vary -- so it takes a solid color and
258/// refuses anything else. This blurs the result, which is defined for every
259/// paint and is what `dart:ui` means by an image filter. For a solid color the
260/// two agree, and there is a test that says so.
261#[derive(Debug, Clone, PartialEq, Default)]
262pub enum ImageFilter {
263    #[default]
264    None,
265    /// Blur what was drawn, by a standard deviation per axis in the space the
266    /// caller is drawing in.
267    ///
268    /// The caller's space rather than device pixels, which is what `dart:ui`
269    /// means by a sigma and what the rest of this renderer does with one: a card
270    /// lifting under a scale blurs by more as its content grows. `scaled_by`
271    /// converts it when the layer opens. This doc said "device pixels" for as
272    /// long as one path failed to convert it, which is the state
273    /// `emblema`'s `filter_space.rs` now rules out.
274    ///
275    /// Two, because `dart:ui`'s `ImageFilter.blur` takes `sigmaX` and
276    /// `sigmaY` separately and upstream's `MakeBlur` passes both through. A
277    /// blur is two separable passes here already, one along each axis, so the
278    /// second deviation costs nothing but the field: each pass uses its own,
279    /// and a pass whose deviation is zero is skipped rather than run as an
280    /// identity that would resample for no reason.
281    ///
282    /// [`Self::blur`] is the isotropic case, which is nearly every use.
283    Blur { sigma_x: f32, sigma_y: f32 },
284    /// Move what was drawn, in device pixels, by resampling it.
285    ///
286    /// Not the same as drawing under the transform, which is what the canvas's
287    /// own stack does. This draws at the size it was written and then moves
288    /// the finished image, so magnifying gives enlarged pixels where the
289    /// transform stack would give the shape redrawn larger. That difference is
290    /// the reason `dart:ui` has both, and a caller wanting the sharp one
291    /// already has `concat`.
292    Matrix { transform: Transform2D },
293    /// Spread what was drawn, taking the largest sample within these radii in
294    /// device pixels.
295    ///
296    /// `ImageFilter.dilate`. On premultiplied color and channel by channel, so
297    /// a translucent shape spreads its coverage along with its color.
298    Dilate { radius_x: f32, radius_y: f32 },
299    /// Shrink what was drawn, taking the smallest sample within these radii in
300    /// device pixels.
301    ///
302    /// `ImageFilter.erode`, and the dual of [`Self::Dilate`]: what one does to
303    /// a shape the other does to the space around it.
304    Erode { radius_x: f32, radius_y: f32 },
305    /// Recolor what was drawn, rather than what the paint computed.
306    ///
307    /// `dart:ui`'s `ColorFilter` is itself an `ImageFilter`, and upstream's
308    /// `DlImageFilter::MakeColorFilter` is the same thing. A paint carries a
309    /// color filter of its own, so the obvious question is what this adds, and
310    /// the answer is narrower than it first looks: **it can be half of a
311    /// [`Self::Compose`], and `Paint::color_filter` cannot.** Recoloring a
312    /// blurred result, or blurring a recolored one, has no other spelling here.
313    ///
314    /// On a single draw with a solid fill it is the same picture as the paint's
315    /// own filter, and a test pins that rather than leaving it to be discovered.
316    /// A paint's image filter applies per draw -- each draw gets a layer of its
317    /// own -- so there is no arrangement of two draws under one paint for the
318    /// two to disagree about. Where they would disagree is inside a
319    /// composition, which is the case this exists for.
320    Color(ColorFilter),
321    /// Run a caller's fragment program over what was drawn.
322    ///
323    /// `dart:ui`'s `ImageFilter.shader`, and upstream's
324    /// `DlImageFilter::MakeRuntimeEffect`. The program reads its input as a
325    /// texture with an identity transform -- the same guarantee upstream
326    /// re-rasterizes to provide, and one this renderer has by construction: a
327    /// filter is a pass whose target is the size of its source, covered by a
328    /// quad, so a fragment's clip position *is* its texture coordinate. A
329    /// program written for this samples exactly as the fixture programs do.
330    ///
331    /// The uniforms are the program's own, as for a runtime effect used as a
332    /// paint: in the effect block, the first 52 also in the material block,
333    /// which a program replaces the shader of. `RUNTIME_FLOATS` is the bound
334    /// and anything past it is dropped.
335    ///
336    /// `sampling` is how the program's reads of its input fall between
337    /// texels: `dart:ui`'s `filterQuality` argument, whose default there is
338    /// `FilterQuality.none`, [`Sampling::Nearest`]. Nearest binds a sampler
339    /// that reads the nearest texel; every other mode binds the linear one,
340    /// which is Impeller's mapping, since a sampler has no bicubic and the
341    /// input has no mip levels. A program reading at its own fragment's
342    /// position reads texel centers and sees no difference; one reading
343    /// anywhere else does.
344    Runtime {
345        program: u32,
346        uniforms: Vec<f32>,
347        sampling: Sampling,
348    },
349    /// Filter with `inner`, then filter that result with `outer`.
350    ///
351    /// `ImageFilter.compose`, and the reason this type is not `Copy`: a filter
352    /// that holds filters cannot be a fixed size without a bound on the depth,
353    /// and `dart:ui` puts no bound on it.
354    ///
355    /// A caller can already nest [`Canvas::save_layer`] calls to the same
356    /// effect, and did before this existed. What this adds is that the bounds
357    /// come out right without being worked out by hand: the outer layer has to
358    /// be opened wide enough to hold whatever the inner one grew to, which
359    /// means knowing how far each filter in the chain reaches.
360    ///
361    /// [`Canvas::save_layer`]: crate::Canvas::save_layer
362    ///
363    /// # How deep one may go
364    ///
365    /// Two hundred and fifty-six levels, and past that the calls taking a filter
366    /// refuse it rather than crash. Everything that reads a composition walks it
367    /// recursively, and the depth that can be walked is a property of the stack
368    /// rather than of the picture -- a debug build managed two thousand and
369    /// forty-eight and died at three thousand and seventy-two. Each level also
370    /// costs a pass and a target, so the limit is far above any use.
371    ///
372    /// One thing no refusal here can cover: this is a chain of `Box`es, so
373    /// *dropping* a composition recurses as deeply as it nests. A filter built deep
374    /// enough overflows the stack being freed, in the caller's own code, before it
375    /// is handed to anything. Building one is what has to be avoided, not passing
376    /// it.
377    Compose {
378        outer: Box<ImageFilter>,
379        inner: Box<ImageFilter>,
380    },
381}
382
383/// How far a blur of the given deviations reaches, as an outset per target axis.
384///
385/// A function rather than a pair of numbers because the answer depends on which
386/// directions the blur will run along, and those come from the transform in
387/// force where the layer opened -- which `paint.rs` has no view of. See
388/// `BlurBasis` in `canvas.rs`.
389pub(crate) type BlurReach<'a> = &'a dyn Fn(Vec2) -> Vec2;
390
391impl ImageFilter {
392    /// A blur of the same deviation along both axes, which is nearly every use.
393    pub fn blur(sigma: f32) -> Self {
394        Self::Blur {
395            sigma_x: sigma,
396            sigma_y: sigma,
397        }
398    }
399
400    /// A blur with a deviation per axis, as `dart:ui`'s `ImageFilter.blur`
401    /// states one.
402    pub fn blur_xy(sigma_x: f32, sigma_y: f32) -> Self {
403        Self::Blur { sigma_x, sigma_y }
404    }
405
406    /// Whether a deviation describes a blur at all.
407    ///
408    /// Stated positively rather than as a negated comparison, which reads
409    /// badly on a type where two values can be incomparable: a sigma that is
410    /// not finite is not a blur, and neither is one that is zero or less.
411    pub(crate) fn blurs(sigma: f32) -> bool {
412        sigma.is_finite() && sigma > 0.0
413    }
414
415    /// This filter with its lengths converted from the caller's space to device
416    /// pixels.
417    ///
418    /// A caller's sigma is stated in the space they were drawing in, which is
419    /// what `dart:ui` means by it and what upstream honors by scaling with
420    /// `effect_transform.Basis()`. `Layer::scaled_by` does this for the fields a
421    /// `Copy` layer carries, and for a long time nothing did it for the filter
422    /// handed alongside them -- so the same `ImageFilter::Blur` meant a local
423    /// sigma through `Paint::with_image_filter`, which becomes a layer and is
424    /// scaled, and a device sigma through `Canvas::save_layer_filtered`, which
425    /// was not. One value in one type meaning two things depending on which call
426    /// received it, which is the defect this closes rather than a difference
427    /// between the two spellings.
428    ///
429    /// **The lengths scale and the rest does not**, which is not an oversight:
430    ///
431    /// - A blur's deviations and a morphology's radii are lengths in the
432    ///   caller's space. The morphology pair used to be left out, on the reading
433    ///   that its radius was device pixels here on purpose; that reading rested
434    ///   on upstream having no morphology, which was wrong, and both now scale.
435    ///   `Layer::scaled_by` does the same to the fields a `Copy` layer carries,
436    ///   so the two spellings of a dilation agree -- including which factor each
437    ///   takes. Both pairs are converted per axis, each component by the length of
438    ///   its own transformed basis vector, which is what upstream takes. A
439    ///   deviation took the single largest factor until `non-parity.md` 20 was
440    ///   closed, and `Layer::backdrop_blur` still does because it is one number
441    ///   rather than a pair.
442    /// - A matrix is not a length. It moves a finished image, and the transform
443    ///   is already in the space the image is in.
444    /// - A color filter and a caller's program carry no lengths at all.
445    ///
446    /// Matched arm by arm with no wildcard, so a variant added later fails to
447    /// compile here instead of silently not being converted. That is the whole
448    /// reason this is written out rather than done with an `if let`.
449    pub(crate) fn scaled_by(self, scale: f32, axes: Vec2) -> Self {
450        if !scale.is_finite() || scale <= 0.0 {
451            return self;
452        }
453        match self {
454            Self::Blur { sigma_x, sigma_y } => Self::Blur {
455                sigma_x: sigma_x * axes.x,
456                sigma_y: sigma_y * axes.y,
457            },
458            Self::Dilate { radius_x, radius_y } => Self::Dilate {
459                radius_x: radius_x * axes.x,
460                radius_y: radius_y * axes.y,
461            },
462            Self::Erode { radius_x, radius_y } => Self::Erode {
463                radius_x: radius_x * axes.x,
464                radius_y: radius_y * axes.y,
465            },
466            Self::Compose { outer, inner } => Self::Compose {
467                outer: Box::new(outer.scaled_by(scale, axes)),
468                inner: Box::new(inner.scaled_by(scale, axes)),
469            },
470            Self::None | Self::Matrix { .. } | Self::Color(_) | Self::Runtime { .. } => self,
471        }
472    }
473
474    /// Whether this would change anything.
475    pub fn is_identity(&self) -> bool {
476        match self {
477            Self::None => true,
478            // Stated positively rather than as a negated comparison, which
479            // reads badly on a type where two values can be incomparable: a
480            // sigma that is not finite is not a blur, and neither is one that
481            // is zero or less.
482            Self::Blur { sigma_x, sigma_y } => !Self::blurs(*sigma_x) && !Self::blurs(*sigma_y),
483            // A matrix that changes nothing is one that costs a layer for
484            // nothing, so it is worth recognizing.
485            Self::Matrix { transform } => {
486                !transform.is_finite() || *transform == Transform2D::IDENTITY
487            }
488            // Positive is a filter, however small, and this used to round first
489            // on the reasoning that a radius of a third of a pixel names no
490            // sample the filter could take. That reasoning died with the radius
491            // becoming a length in the caller's space: a third of *what* is not
492            // known here, and a local 0.2 under a scale of ten is two device
493            // texels -- a filter this would have discarded. Whether a radius
494            // rounds to nothing is decided in `Morphology::applied_radius`,
495            // where the scale has been applied.
496            Self::Dilate { radius_x, radius_y } | Self::Erode { radius_x, radius_y } => {
497                let positive = |v: f32| v.is_finite() && v > 0.0;
498                !positive(*radius_x) && !positive(*radius_y)
499            }
500            // Composing two filters that each change nothing changes nothing,
501            // and costs two layers to say so.
502            // A color filter that recolors nothing is one, which keeps a
503            // caller who builds one from a default out of a layer they did not
504            // ask to pay for. Asked of the filter rather than compared against
505            // `ColorFilter::None`, which is what this used to do: a blend in
506            // `Dst` mode returns the destination untouched and an identity
507            // matrix recolors nothing, and both paid for a pass and a resample
508            // to arrive at what they were handed. `ColorFilter::is_identity`
509            // knows all three and is the same question.
510            Self::Color(filter) => filter.is_identity(),
511            // Never. What a caller's program does is the caller's business and
512            // nothing here can read it, so the only safe answer is that it does
513            // something -- and answering otherwise would drop the pass that
514            // runs it.
515            Self::Runtime { .. } => false,
516            Self::Compose { outer, inner } => outer.is_identity() && inner.is_identity(),
517        }
518    }
519
520    /// Whether what this draws depends on how large its input is, and not
521    /// only on what is in it.
522    ///
523    /// A caller's program is told its input's size and places what it reads
524    /// against it, so the same program over a larger input is a different
525    /// picture. Every other filter here reads a fixed distance around each
526    /// texel, which a larger input does not move.
527    pub(crate) fn is_sized_by_its_input(&self) -> bool {
528        match self {
529            Self::Runtime { .. } => true,
530            Self::Compose { outer, inner } => {
531                outer.is_sized_by_its_input() || inner.is_sized_by_its_input()
532            }
533            _ => false,
534        }
535    }
536
537    /// Filter with `inner` first and then with `outer`.
538    ///
539    /// The order `dart:ui` states, which is the order the names suggest once
540    /// you picture them nested: the inner filter is the one closer to what was
541    /// drawn. A composition where either half does nothing is the other half,
542    /// since the layer it would have taken is a copy of an image.
543    pub fn compose(outer: ImageFilter, inner: ImageFilter) -> Self {
544        if inner.is_identity() {
545            return outer;
546        }
547        if outer.is_identity() {
548            return inner;
549        }
550        Self::Compose {
551            outer: Box::new(outer),
552            inner: Box::new(inner),
553        }
554    }
555
556    /// The outermost filter that is not itself a composition, and everything
557    /// that has to run before it.
558    ///
559    /// A chain is applied innermost first, so drawing one means peeling from
560    /// the other end: open a layer for the outermost, and hand the remainder
561    /// back to be drawn inside it. The remainder is a filter in its own right,
562    /// which is what lets the caller recurse without knowing how deep it is.
563    ///
564    /// Recursive on the *outer* half, and that is the whole point. A first
565    /// version took `outer` to be a leaf and returned it directly, which is
566    /// true for anything `compose` builds left to right and false the moment a
567    /// caller composes two compositions -- `compose(compose(a, b), c)` was
568    /// refused as an unimplemented filter, having been assembled entirely out
569    /// of implemented ones.
570    /// The deepest composition this will walk.
571    ///
572    /// Every function that reads a composition walks it recursively -- `peel`,
573    /// `covering`, `is_identity`, `scaled_by` -- and the passes it turns into are
574    /// built by a recursion too. So the depth that can be serviced is a property of
575    /// the stack rather than of the picture, and a limit stated here is a refusal
576    /// where the absence of one was a fatal stack overflow.
577    ///
578    /// Measured on 2026-09-24 rather than guessed: a debug build serviced a
579    /// composition two thousand and forty-eight deep and died at three thousand and
580    /// seventy-two. A release build has smaller frames and would reach further,
581    /// which is the wrong direction to calibrate from -- a limit has to hold in the
582    /// profile that fails first, and the suite is that profile.
583    ///
584    /// Two hundred and fifty-six is far below it and far above any use. `dart:ui`
585    /// callers compose two or three filters; each level here also costs a pass and
586    /// a target, so a composition this deep is already a recording of two hundred
587    /// and sixty passes over a picture nobody can see the shape of.
588    pub(crate) const MAX_NESTING: usize = 256;
589
590    /// Whether this composition nests deeper than `limit`.
591    ///
592    /// Iterative, with its own worklist, which is the point: a recursive depth
593    /// check would overflow on exactly the input it exists to refuse. Stops as soon
594    /// as the limit is passed rather than measuring the whole tree, so a
595    /// pathological filter costs the limit and not its own size.
596    ///
597    /// A composition is a tree rather than a list -- both halves can compose -- so
598    /// the walk carries a depth per node instead of counting iterations.
599    pub(crate) fn nests_deeper_than(&self, limit: usize) -> bool {
600        let mut work = vec![(self, 0usize)];
601        while let Some((filter, depth)) = work.pop() {
602            if depth > limit {
603                return true;
604            }
605            if let Self::Compose { outer, inner } = filter {
606                work.push((outer, depth + 1));
607                work.push((inner, depth + 1));
608            }
609        }
610        false
611    }
612
613    pub(crate) fn peel(&self) -> (ImageFilter, ImageFilter) {
614        match self {
615            Self::Compose { outer, inner } => {
616                let (outermost, rest) = outer.peel();
617                (outermost, Self::compose(rest, (**inner).clone()))
618            }
619            leaf => (leaf.clone(), Self::None),
620        }
621    }
622
623    /// The region of device pixels a target must cover for this filter to run
624    /// over content occupying `min`..`max`.
625    ///
626    /// Both what goes in and what comes out, which is not the same question for
627    /// every filter and is the one that matters. A blur or a dilation only
628    /// grows, so its output contains its input and the distinction is invisible
629    /// -- the case that makes it visible is a matrix, which *moves* the image.
630    /// A composition puts the inner filter's layer inside the outer one's
631    /// target, and a layer's target is clipped to its parent's, so a target
632    /// sized only for where a matrix filter put things would crop the content
633    /// before the matrix ever ran: the inner layer draws the shape where it was
634    /// written and the composite is what moves it.
635    ///
636    /// Erosion is left alone rather than shrunk. Covering more than the result
637    /// needs costs a little memory; covering less loses drawing.
638    pub(crate) fn covering(&self, min: Vec2, max: Vec2, blur: BlurReach) -> (Vec2, Vec2) {
639        match self {
640            // A color filter changes what a pixel is and never which pixels
641            // there are, so it needs exactly the region it was given. A runtime
642            // effect is the same on the side that matters here: it may read
643            // anywhere in its input, and it writes only where the pass covers.
644            Self::None | Self::Erode { .. } | Self::Color(_) | Self::Runtime { .. } => (min, max),
645            Self::Blur { sigma_x, sigma_y } => {
646                // Per axis, which is the whole reason a filter states two: a
647                // blur along one axis alone must not widen the other, or the
648                // target holding it is bigger than the picture in it.
649                //
650                // Which axes, though, is the caller's to say. A blur runs along
651                // the directions the caller's own axes point once the transform
652                // has been applied, so the outset is the bounding box of the two
653                // reaches laid along those -- and asking here with the target's
654                // axes when the blur will run along turned ones sizes a target
655                // for one blur and fills it with another. That is not a
656                // conservative error: it is short exactly where the blur went.
657                let reach = blur(Vec2::new(*sigma_x, *sigma_y));
658                (min - reach, max + reach)
659            }
660            Self::Dilate { radius_x, radius_y } => {
661                let radius = Morphology::dilate(*radius_x, *radius_y).radius;
662                let reach = Vec2::new(radius[0], radius[1]);
663                (min - reach, max + reach)
664            }
665            Self::Matrix { transform } => {
666                // A matrix that carries the content across the vanishing line
667                // moves it further than a box can state, and this is a
668                // statement about how far a filter reaches -- so it widens to
669                // everything rather than reporting a reach that is too short.
670                let (moved_min, moved_max) =
671                    transformed_bounds(*transform, min, max).unwrap_or_else(unbounded);
672                (min.min(moved_min), max.max(moved_max))
673            }
674            Self::Compose { outer, inner } => {
675                let (min, max) = inner.covering(min, max, blur);
676                outer.covering(min, max, blur)
677            }
678        }
679    }
680}
681
682/// Fill the shape, or trace its outline.
683#[derive(Debug, Clone, Copy, PartialEq, Default)]
684pub enum Style {
685    #[default]
686    Fill,
687    /// Stroke with the given width and joinery.
688    ///
689    /// The width is in the coordinate space the shape is drawn in, so it scales
690    /// with the canvas transform. A caller wanting a hairline that stays one
691    /// pixel wide under zoom divides by the current scale.
692    Stroke(StrokeStyle),
693}
694
695/// Everything about how a shape is painted.
696#[derive(Debug, Clone, PartialEq)]
697pub struct Paint {
698    pub shader: Shader,
699    pub style: Style,
700    /// Which part of the blurred shape survives. Ignored without a mask blur.
701    pub mask_blur_style: MaskBlurStyle,
702    /// A function applied to what this paint drew, after the shader and any
703    /// color filter.
704    ///
705    /// Costs a layer: what is drawn goes into a target of its own, is
706    /// filtered, and is composited back. See [`ImageFilter`] for how this
707    /// differs from a color filter and from a mask blur.
708    pub image_filter: ImageFilter,
709    /// A function applied to the color the shader produces, before blending.
710    ///
711    /// Beside the shader rather than inside it because it applies to all of
712    /// them, and after it rather than before because that is where `dart:ui`
713    /// puts a color filter and where it is useful: what is being recolored is
714    /// the result of the fill, not the inputs it was built from.
715    pub color_filter: ColorFilter,
716    /// Cut a stroke into a dash pattern before drawing it.
717    ///
718    /// On the paint rather than inside [`Style::Stroke`] for two reasons. It
719    /// keeps the geometry crate's stroke description a small copyable value,
720    /// which the tessellator wants and a pattern of arbitrary length would
721    /// end. And it says what it is: a dashed stroke is a stroke of a different
722    /// path, so this describes what happens to the path on the way in rather
723    /// than how the outline is built.
724    ///
725    /// Ignored by a fill, which has no length to measure along.
726    pub dash: Option<Dash>,
727    /// Blur the shape's coverage before filling it, in device pixels.
728    ///
729    /// What a soft shadow is made of: the same shape, softened, drawn behind
730    /// the thing casting it. Zero for none.
731    ///
732    /// `dart:ui` states this as blurring the mask and then applying the paint
733    /// through it, and that is what a shape gets. Two orders exist and they
734    /// agree only where the fill does not vary, because a blur is linear:
735    /// `blur(C·α)` is `C·blur(α)` for a constant `C` and for nothing else. A
736    /// solid color therefore takes the cheaper route and is drawn through a
737    /// blurred layer, which is that identity used; anything that varies is
738    /// drawn the way the specification says, with the fill laid across
739    /// everything the blur reaches and blurred coverage composited onto it.
740    ///
741    /// A solid fill of a convex path in the default style takes upstream's own
742    /// route instead, where no analytic shape covers it: a shadow mesh, its
743    /// falloff carried on the vertices (`docs/non-parity.md` section 7). That
744    /// approximates the Gaussian rather than being it, as upstream's does; a
745    /// concave path is blurred through the layer on both sides.
746    ///
747    /// Two things still take a solid color only, and neither is about blurring.
748    /// A glyph run tints one color by its own nature, so a gradient over one is
749    /// refused here exactly as it is when nothing is blurred. And a mesh
750    /// carries a color per vertex, which is a second thing multiplying the
751    /// coverage rather than a fill to lay down.
752    ///
753    /// The three styles that combine a blurred mask with a sharp one need the
754    /// coverage twice and are not built for a varying fill; they take a solid
755    /// color, which is every use a shadow has.
756    pub mask_blur: f32,
757    pub blend: BlendMode,
758    /// How a color carried per vertex or per sprite combines with what this
759    /// paint produced.
760    ///
761    /// `dart:ui` passes this as an argument to `drawVertices` and `drawAtlas`
762    /// rather than on the paint. It sits here instead because those are the
763    /// only two calls that can carry such a color, and an argument every other
764    /// call would have to pass and ignore is worse than a field they leave
765    /// alone. [`BlendMode::Modulate`] multiplies, which is the identity for the
766    /// white a caller who supplied no color gets.
767    ///
768    /// The paint's result is the source and the carried color the
769    /// destination, the order `dart:ui` states for both calls: so `SrcOver`
770    /// lays the paint over the color, and `Dst` keeps the color alone.
771    ///
772    /// Distinct from [`Self::blend`], which decides how the result reaches the
773    /// target. Both colors here are in the shader already, so every mode is
774    /// available to this one without an extension.
775    pub tint_blend: BlendMode,
776    /// Whether to antialias this shape's edges.
777    ///
778    /// Recorded per paint but applied per pass, because multisampling is a
779    /// property of the target rather than of a draw: a canvas that mixes the
780    /// two antialiases everything.
781    pub anti_alias: bool,
782    /// Where the shader's own space sits in the space the paint is used in:
783    /// the shader's local matrix.
784    ///
785    /// An image's rectangle, a gradient's points and radii and a sweep's
786    /// angles are stated in the shader's space, and this carries them into
787    /// the space the shape is drawn in, before the canvas transform. So a
788    /// gradient can be rotated, skewed or put in perspective independently
789    /// of the shape it fills, and an image laid down at any angle: what
790    /// `dart:ui`'s `ImageShader` and `Gradient` take as `matrix4`, and what
791    /// upstream applies as a color source's effect transform.
792    ///
793    /// Composed into the mapping each fragment is located through, so a
794    /// radial gradient under a stretch is an ellipse, as it is upstream, and
795    /// nothing about the shape changes. The identity by default. Ignored by
796    /// a solid color, which has no space, and by a runtime effect, whose
797    /// program locates itself.
798    pub shader_transform: Transform2D,
799    /// What the shader produces is multiplied by this, from zero to one: the
800    /// alpha of `dart:ui`'s paint color, which modulates whatever shader the
801    /// paint has, as upstream's opacity factor does on every color source.
802    ///
803    /// One by default. Kept apart from the shader so it survives
804    /// [`Self::with_shader`], and read through [`Self::effective_shader`], so
805    /// every route draws the same. A value outside zero to one is clamped
806    /// into it, and one that is not a number draws nothing.
807    ///
808    /// A mesh or an atlas with colors of its own is the one place the order
809    /// shows: there it fades what [`Self::tint_blend`] produced, after the
810    /// blend, as upstream's vertices and atlas contents do. Under
811    /// `Modulate` that is the same product either way.
812    pub opacity: f32,
813}
814
815impl Default for Paint {
816    fn default() -> Self {
817        Self {
818            shader: Shader::Solid(Color::BLACK),
819            style: Style::Fill,
820            image_filter: ImageFilter::None,
821            mask_blur_style: MaskBlurStyle::default(),
822            color_filter: ColorFilter::None,
823            dash: None,
824            mask_blur: 0.0,
825            blend: BlendMode::SrcOver,
826            tint_blend: BlendMode::Modulate,
827            anti_alias: true,
828            shader_transform: Transform2D::IDENTITY,
829            opacity: 1.0,
830        }
831    }
832}
833
834impl Paint {
835    /// A solid fill.
836    pub fn fill(color: Color) -> Self {
837        Self {
838            shader: Shader::Solid(color),
839            ..Default::default()
840        }
841    }
842
843    /// A fill that runs between colors along a line in user space.
844    ///
845    /// Any number of them. Up to [`MAX_STOPS`] the colors travel with the
846    /// material; beyond that the recorder tabulates them into a texture the
847    /// shader samples, which costs one small upload per distinct gradient and
848    /// is otherwise invisible. Ask [`Shader::stop_count`] if you want to know
849    /// which will happen.
850    ///
851    /// [`MAX_STOPS`]: emblema_hal::MAX_STOPS
852    pub fn linear_gradient(start: Vec2, end: Vec2, stops: Vec<GradientStop>) -> Self {
853        Self {
854            shader: Shader::LinearGradient {
855                start,
856                end,
857                stops,
858                tile: TileMode::default(),
859            },
860            ..Default::default()
861        }
862    }
863
864    /// A fill that runs outward from a center in user space.
865    ///
866    /// Any number of stops; see [`Paint::linear_gradient`].
867    pub fn radial_gradient(center: Vec2, radius: f32, stops: Vec<GradientStop>) -> Self {
868        Self {
869            shader: Shader::RadialGradient {
870                center,
871                radius,
872                stops,
873                tile: TileMode::default(),
874            },
875            ..Default::default()
876        }
877    }
878
879    /// A fill that runs around a center in user space.
880    ///
881    /// Angles are in radians from the positive X axis, increasing toward
882    /// positive Y: clockwise on screen, where Y points down, as `dart:ui` and
883    /// Skia measure them. At any number of stops; see
884    /// [`Paint::linear_gradient`].
885    pub fn sweep_gradient(
886        center: Vec2,
887        start_angle: f32,
888        end_angle: f32,
889        stops: Vec<GradientStop>,
890    ) -> Self {
891        Self {
892            shader: Shader::SweepGradient {
893                center,
894                start_angle,
895                end_angle,
896                stops,
897                tile: TileMode::default(),
898            },
899            ..Default::default()
900        }
901    }
902
903    /// A fill computed by a program the caller supplied.
904    ///
905    /// See [`Shader::RuntimeEffect`]. The program has to be registered with
906    /// the context that will draw the recording, and the index it was given is
907    /// what goes here.
908    pub fn runtime_effect(program: u32, uniforms: Vec<f32>) -> Self {
909        Self {
910            shader: Shader::RuntimeEffect {
911                program,
912                uniforms,
913                images: Vec::new(),
914            },
915            ..Default::default()
916        }
917    }
918
919    /// Give a runtime effect a texture to sample.
920    ///
921    /// Ignored by every other kind of paint, which either samples nothing or
922    /// already names what it samples. Called more than once, the slots stack up
923    /// in the order the program declares its bindings.
924    pub fn with_effect_image(mut self, slot: u32) -> Self {
925        if let Shader::RuntimeEffect { images, .. } = &mut self.shader {
926            images.push(slot);
927        }
928        self
929    }
930
931    /// Give a runtime effect every texture it samples at once.
932    ///
933    /// The order is the order the program declares its bindings, which for a
934    /// program written in WGSL is the order of the binding numbers rather than
935    /// the order of the declarations.
936    pub fn with_effect_images(mut self, slots: &[u32]) -> Self {
937        if let Shader::RuntimeEffect { images, .. } = &mut self.shader {
938            images.clear();
939            images.extend_from_slice(slots);
940        }
941        self
942    }
943
944    /// A fill that runs between two circles in user space.
945    ///
946    /// The general gradient: the first stop lands on the first circle and the
947    /// last on the second, and every stop between them on a circle
948    /// interpolated between the two. `radial_gradient` is the case where the
949    /// first circle is a point at the second's center, and is worth reaching
950    /// for when that is what you mean -- it does less work per fragment.
951    ///
952    /// Any number of stops; see [`Paint::linear_gradient`].
953    pub fn conical_gradient(
954        start_center: Vec2,
955        start_radius: f32,
956        end_center: Vec2,
957        end_radius: f32,
958        stops: Vec<GradientStop>,
959    ) -> Self {
960        Self {
961            shader: Shader::ConicalGradient {
962                start_center,
963                start_radius,
964                end_center,
965                end_radius,
966                stops,
967                tile: TileMode::default(),
968            },
969            ..Default::default()
970        }
971    }
972
973    /// How to read a texture between its texels.
974    ///
975    /// Linear by default, which is what an image drawn at any size but its own
976    /// wants. [`Sampling::Nearest`] is for the cases where blending is the
977    /// wrong answer: pixel art, and a sprite drawn at exactly its own size
978    /// where certainty that no neighbor bled in matters more than smoothness.
979    ///
980    /// Ignored by a paint with no texture.
981    pub fn with_sampling(mut self, sampling: Sampling) -> Self {
982        if let Shader::Image { sampling: at, .. } = &mut self.shader {
983            *at = sampling;
984        }
985        self
986    }
987
988    /// Keep only part of the blurred shape. See [`MaskBlurStyle`].
989    ///
990    /// Ignored unless a mask blur is set, since there is nothing to take a
991    /// part of otherwise.
992    pub fn with_mask_blur_style(mut self, style: MaskBlurStyle) -> Self {
993        self.mask_blur_style = style;
994        self
995    }
996
997    /// Filter what this paint draws, rather than the color it computes.
998    ///
999    /// Unlike a mask blur this takes any shader, because blurring a result is
1000    /// defined whatever produced it. It is the more expensive of the two: a
1001    /// layer is allocated, drawn into and composited back, where a mask blur
1002    /// of a solid color reaches the same picture the same way but is only
1003    /// offered where that equivalence holds.
1004    pub fn with_image_filter(mut self, filter: ImageFilter) -> Self {
1005        self.image_filter = filter;
1006        self
1007    }
1008
1009    /// Apply a function to the color this paint produces, before it blends.
1010    ///
1011    /// Works on any shader, which is the point: the image tint that came
1012    /// before it could only recolor an image. A gradient, a shape, a run of
1013    /// glyphs all take one now.
1014    pub fn with_color_filter(mut self, filter: ColorFilter) -> Self {
1015        self.color_filter = filter;
1016        self
1017    }
1018
1019    /// Blur the shape's coverage, for a shadow or a glow.
1020    ///
1021    /// Ignored unless finite and positive. Applies to a fill or a stroke alike
1022    /// -- what is blurred is whatever coverage the shape produces.
1023    pub fn with_mask_blur(mut self, sigma: f32) -> Self {
1024        self.mask_blur = if sigma.is_finite() && sigma > 0.0 {
1025            sigma
1026        } else {
1027            0.0
1028        };
1029        self
1030    }
1031
1032    /// Dash this paint's stroke, or clear an existing pattern with `None`.
1033    ///
1034    /// The lengths are in the space the shape is drawn in, so a pattern scales
1035    /// with the canvas transform along with the line it cuts. A pattern that
1036    /// cannot be walked -- empty, negative, or summing to zero -- draws the
1037    /// line whole rather than drawing nothing, since an undashed line leads
1038    /// back to the pattern and an absent one leads nowhere.
1039    pub fn with_dash(mut self, dash: impl Into<Option<Dash>>) -> Self {
1040        self.dash = dash.into();
1041        self
1042    }
1043
1044    /// A stroke of the given width, with default caps and joins.
1045    /// A fill that samples an image across a rectangle in user space.
1046    ///
1047    /// `slot` indexes the table supplied when the recording is drawn, and
1048    /// `rect` is the region the image covers rather than the region drawn: the
1049    /// shape being filled decides what is painted, this decides where the image
1050    /// sits under it.
1051    pub fn image(slot: u32, rect: Rect) -> Self {
1052        Self {
1053            shader: Shader::Image {
1054                slot,
1055                rect,
1056                alpha: 1.0,
1057                tile: [TileMode::default(); 2],
1058                source: Rect::new(0.0, 0.0, 1.0, 1.0),
1059                tint: Color::WHITE,
1060                sampling: Sampling::default(),
1061            },
1062            ..Default::default()
1063        }
1064    }
1065
1066    /// Place the shader's space in the paint's. See [`Paint::shader_transform`].
1067    pub fn with_shader_transform(mut self, transform: Transform2D) -> Self {
1068        self.shader_transform = transform;
1069        self
1070    }
1071
1072    /// What happens outside the paint's own extent.
1073    ///
1074    /// Means the same thing for a gradient as for an image, which is why it is
1075    /// one call rather than two: past the end of the ramp, past the radius, or
1076    /// outside the swept arc, the color either holds, or repeats, or stops.
1077    /// Ignored by a solid paint, which has no outside.
1078    pub fn with_tile_mode(mut self, tile: TileMode) -> Self {
1079        match &mut self.shader {
1080            Shader::Image { tile: current, .. } => *current = [tile; 2],
1081            Shader::LinearGradient { tile: current, .. }
1082            | Shader::RadialGradient { tile: current, .. }
1083            | Shader::SweepGradient { tile: current, .. }
1084            | Shader::ConicalGradient { tile: current, .. } => *current = tile,
1085            // Neither has an outside a tile mode could describe: a solid has
1086            // no edge, and where a caller's program stops is the caller's
1087            // arithmetic rather than this renderer's.
1088            Shader::Solid(_) | Shader::RuntimeEffect { .. } => {}
1089        }
1090        self
1091    }
1092
1093    /// What happens outside an image, one mode across and one down.
1094    ///
1095    /// A strip that repeats along its length and stops at its ends, say, which
1096    /// one mode for both axes cannot state. dart:ui's `ImageShader` takes the
1097    /// two separately, and Impeller samples each axis by its own; this is that.
1098    ///
1099    /// Ignored by paints that are not images. A gradient has one parameter to
1100    /// fold, not two coordinates, and one mode is all it has upstream as well;
1101    /// [`Paint::with_tile_mode`] is how it is set.
1102    pub fn with_tile_modes(mut self, x: TileMode, y: TileMode) -> Self {
1103        if let Shader::Image { tile, .. } = &mut self.shader {
1104            *tile = [x, y];
1105        }
1106        self
1107    }
1108
1109    /// Draw only part of the image, in coordinates from zero to one.
1110    ///
1111    /// What a sprite sheet needs, and a nine-patch border. Normalized rather
1112    /// than in texels because a canvas records without touching a device and
1113    /// has never seen the image: it holds a slot, not a texture, and cannot ask
1114    /// how large it is. The caller who uploaded it can, which is what
1115    /// [`Paint::with_source_pixels`] is for.
1116    ///
1117    /// Ignored by paints that are not images.
1118    pub fn with_source(mut self, source: Rect) -> Self {
1119        if let Shader::Image { source: at, .. } = &mut self.shader {
1120            *at = source;
1121        }
1122        self
1123    }
1124
1125    /// The same, stated in texels of an image of the given size.
1126    ///
1127    /// A degenerate size would divide by zero, so it leaves the paint alone --
1128    /// drawing the whole image, which is what the paint already said.
1129    pub fn with_source_pixels(self, source: Rect, size: Extent2D) -> Self {
1130        if size.width == 0 || size.height == 0 {
1131            return self;
1132        }
1133        let (w, h) = (size.width as f32, size.height as f32);
1134        self.with_source(Rect::new(
1135            source.left / w,
1136            source.top / h,
1137            source.right / w,
1138            source.bottom / h,
1139        ))
1140    }
1141
1142    /// Multiply an image paint's sampled color. Ignored by other paints.
1143    ///
1144    /// What turns one monochrome icon sheet into every state a control has:
1145    /// upload the shapes once as white on transparent, and tint per draw. A
1146    /// white tint is the identity, which is what an image that never mentions
1147    /// one already carries.
1148    ///
1149    /// Composes with everything else on the paint, so a tinted sprite from a
1150    /// sheet is one call for the piece and one for the color.
1151    pub fn with_tint(mut self, tint: Color) -> Self {
1152        if let Shader::Image { tint: at, .. } = &mut self.shader {
1153            *at = tint;
1154        }
1155        self
1156    }
1157
1158    /// Multiply what the shader produces. See [`Paint::opacity`].
1159    pub fn with_opacity(mut self, opacity: f32) -> Self {
1160        self.opacity = opacity;
1161        self
1162    }
1163
1164    /// The shader as the paint draws it: [`Self::opacity`] folded in. Every
1165    /// route reads the shader through this.
1166    pub fn effective_shader(&self) -> Cow<'_, Shader> {
1167        let opacity = self.effective_opacity();
1168        if opacity == 1.0 {
1169            Cow::Borrowed(&self.shader)
1170        } else {
1171            Cow::Owned(self.shader.at_opacity(opacity))
1172        }
1173    }
1174
1175    /// [`Paint::opacity`] as it is applied: held to zero to one, and zero for
1176    /// a NaN, which has no amount of fading to stand for.
1177    pub(crate) fn effective_opacity(&self) -> f32 {
1178        if self.opacity.is_nan() {
1179            0.0
1180        } else {
1181            self.opacity.clamp(0.0, 1.0)
1182        }
1183    }
1184
1185    /// Scale an image paint's sampled color. Ignored by other paints.
1186    pub fn with_image_alpha(mut self, alpha: f32) -> Self {
1187        if let Shader::Image { alpha: current, .. } = &mut self.shader {
1188            *current = alpha;
1189        }
1190        self
1191    }
1192
1193    pub fn stroke(color: Color, width: f32) -> Self {
1194        Self {
1195            shader: Shader::Solid(color),
1196            style: Style::Stroke(StrokeStyle::new(width)),
1197            ..Default::default()
1198        }
1199    }
1200
1201    pub fn with_shader(mut self, shader: Shader) -> Self {
1202        self.shader = shader;
1203        self
1204    }
1205
1206    pub fn with_style(mut self, style: Style) -> Self {
1207        self.style = style;
1208        self
1209    }
1210
1211    pub fn with_blend(mut self, blend: BlendMode) -> Self {
1212        self.blend = blend;
1213        self
1214    }
1215
1216    /// How a per-vertex or per-sprite color combines with this paint's result.
1217    ///
1218    /// Ignored by every call that carries no such color, there being nothing to
1219    /// combine.
1220    pub fn with_tint_blend(mut self, tint_blend: BlendMode) -> Self {
1221        self.tint_blend = tint_blend;
1222        self
1223    }
1224
1225    /// Whether this paint's edges are smoothed. On by default.
1226    ///
1227    /// How that is paid for depends on the shape rather than on this flag. A
1228    /// rectangle, rounded rectangle, oval or circle is drawn from a distance
1229    /// field and antialiases itself inside its own fragment shader, costing a
1230    /// pass nothing. Anything that reaches the tessellator instead -- an
1231    /// arbitrary path, a stroke, a line, a double rounded rectangle -- has only
1232    /// triangles to work with, so its pass becomes multisampled.
1233    ///
1234    /// That second case carries a requirement worth knowing before meeting it:
1235    /// a multisampled pass must clear, so the pass it lands in needs something
1236    /// to clear to. Drawn straight onto the frame, that means the canvas needs
1237    /// a background -- see [`crate::Canvas::clear`], which is where a caller
1238    /// refused for this reason should look. Drawn inside a layer it means
1239    /// nothing to the caller, the layer's target clearing to transparent on
1240    /// its own.
1241    pub fn with_anti_alias(mut self, anti_alias: bool) -> Self {
1242        self.anti_alias = anti_alias;
1243        self
1244    }
1245
1246    /// Whether drawing with this paint would change anything.
1247    ///
1248    /// A transparent fill and a zero-width stroke both draw nothing, and
1249    /// skipping them early keeps empty geometry out of the batch rather than
1250    /// tessellating it and discovering it was empty.
1251    pub fn is_visible(&self) -> bool {
1252        if !self.effective_shader().is_visible() {
1253            return false;
1254        }
1255        match &self.style {
1256            Style::Fill => true,
1257            // `can_draw` rather than `is_visible`, and the difference is a
1258            // width of zero: a hairline, which the canvas widens to a device
1259            // pixel before any geometry is built for it.
1260            Style::Stroke(stroke) => stroke.can_draw(),
1261        }
1262    }
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267    use super::*;
1268
1269    #[test]
1270    fn a_default_paint_is_an_opaque_antialiased_fill() {
1271        let paint = Paint::default();
1272        assert_eq!(paint.style, Style::Fill);
1273        assert_eq!(paint.blend, BlendMode::SrcOver);
1274        assert!(paint.anti_alias);
1275        assert!(paint.is_visible());
1276    }
1277
1278    #[test]
1279    fn a_transparent_paint_draws_nothing_whatever_its_style() {
1280        let clear = Color::WHITE.with_alpha(0.0);
1281        assert!(!Paint::fill(clear).is_visible());
1282        assert!(!Paint::stroke(clear, 4.0).is_visible());
1283
1284        // A gradient every stop of which is transparent draws nothing either.
1285        let invisible = Paint::linear_gradient(
1286            Vec2::ZERO,
1287            Vec2::new(1.0, 0.0),
1288            vec![GradientStop::new(clear, 0.0), GradientStop::new(clear, 1.0)],
1289        );
1290        assert!(!invisible.is_visible());
1291    }
1292
1293    #[test]
1294    fn a_zero_width_stroke_draws_nothing() {
1295        // Animating a width to zero should stop drawing rather than emit
1296        // degenerate geometry for the tessellator to discard.
1297        // A width of zero is a hairline rather than nothing, so the paint is
1298        // visible; a negative one still is not a stroke.
1299        assert!(Paint::stroke(Color::BLACK, 0.0).is_visible());
1300        assert!(!Paint::stroke(Color::BLACK, -1.0).is_visible());
1301        assert!(Paint::stroke(Color::BLACK, 0.5).is_visible());
1302    }
1303
1304    #[test]
1305    fn an_image_takes_a_tile_mode_per_axis_and_a_gradient_one() {
1306        let tile_of = |paint: &Paint| match paint.shader {
1307            Shader::Image { tile, .. } => tile,
1308            _ => unreachable!("an image paint"),
1309        };
1310        let rect = Rect::new(0.0, 0.0, 1.0, 1.0);
1311        assert_eq!(tile_of(&Paint::image(0, rect)), [TileMode::Clamp; 2]);
1312        let one = Paint::image(0, rect).with_tile_mode(TileMode::Mirror);
1313        assert_eq!(tile_of(&one), [TileMode::Mirror; 2]);
1314        let each = Paint::image(0, rect).with_tile_modes(TileMode::Repeat, TileMode::Decal);
1315        assert_eq!(tile_of(&each), [TileMode::Repeat, TileMode::Decal]);
1316
1317        // A gradient has one mode, and the per-axis call leaves it alone.
1318        let ramp = Paint::linear_gradient(
1319            Vec2::ZERO,
1320            Vec2::new(1.0, 0.0),
1321            vec![
1322                GradientStop::new(Color::BLACK, 0.0),
1323                GradientStop::new(Color::WHITE, 1.0),
1324            ],
1325        )
1326        .with_tile_modes(TileMode::Repeat, TileMode::Decal);
1327        assert!(matches!(
1328            ramp.shader,
1329            Shader::LinearGradient {
1330                tile: TileMode::Clamp,
1331                ..
1332            }
1333        ));
1334    }
1335}