Skip to main content

emblema_hal/
material.rs

1//! What fills a shape.
2//!
3//! A material is the paint as a backend sees it: fully resolved, in clip space,
4//! and packed into the layout the shader expects. Resolving happens above,
5//! because gradient geometry has to travel through the same transform the shape
6//! did.
7
8use crate::blend::BlendMode;
9
10/// Floats in the packed representation.
11///
12/// This was 128 bytes for a long time because that is exactly what every
13/// device guarantees as push constants, and the material traveled as one.
14/// That guarantee was also a ceiling, and the material had grown to occupy it
15/// exactly -- so the mechanism was deciding what a paint could hold, which is
16/// the wrong way round. Materials travel in a uniform buffer now, and the
17/// limit that binds is `maxUniformBufferRange`, whose guaranteed minimum is
18/// sixteen kilobytes: two orders of magnitude of room rather than none.
19///
20/// The size has not changed with the mechanism, and should not change without
21/// a material that needs it. Every float here is read by a shader that
22/// branches on the kind, and floats nobody reads are bandwidth in the one
23/// place a renderer spends it per draw.
24pub const MATERIAL_FLOATS: usize = 64;
25
26/// Enforced at compile time rather than by a test, so a material that outgrew
27/// what every device guarantees could not be built at all.
28///
29/// The bound is `maxUniformBufferRange`'s guaranteed minimum. A material is
30/// nowhere near it; the assertion is here because the previous bound was
31/// reached, and the way that was noticed was this line failing to compile.
32const _: () = assert!(
33    MATERIAL_FLOATS * 4 <= 16384,
34    "a material must fit the 16 KiB of uniform buffer range every device guarantees"
35);
36
37/// The most stops a gradient carries in the material itself.
38///
39/// Four covers the overwhelming majority of real gradients, and covers them
40/// without a texture, an upload or a binding. It is not a limit on what can be
41/// drawn: beyond this the recorder tabulates the stops into a ramp and the
42/// shader samples it instead, which is what this constant used to say was
43/// waiting on the HAL learning to sample textures. It has since learned.
44pub const MAX_STOPS: usize = 4;
45
46/// Offsets into the packed layout, matching the shader's declaration.
47///
48/// Public because it is a contract between the shader and every backend, not an
49/// internal detail. Both backends copy the packed floats straight into a
50/// uniform buffer, so a member is found by its offset here rather than by a
51/// name -- and naming the offsets in one place keeps the layout from being
52/// written out again as bare indices that quietly go stale when it grows.
53pub mod layout {
54    /// Four stop colors.
55    pub const STOPS: usize = 0;
56    /// Stop positions.
57    pub const OFFSETS: usize = 16;
58    /// Endpoints, or center plus angles.
59    pub const GEOMETRY: usize = 20;
60    /// Clip space to the paint's own space: three columns of a three-by-three,
61    /// in column order, each padded to four floats.
62    ///
63    /// Twelve floats rather than nine because that is how a `mat3x3` sits in a
64    /// uniform block, and because every member here is a four-component vector
65    /// on purpose -- it is what lets both backends copy the packed material
66    /// straight in without writing padding around anything.
67    ///
68    /// The paint's origin is inside this matrix rather than beside it in
69    /// `GEOMETRY`, which is why the first two floats there are unclaimed for
70    /// every kind that carries a mapping. See `invert_to_local`.
71    pub const TO_LOCAL: usize = 24;
72    /// Stop count, material kind, and two floats whose meaning the kind
73    /// decides -- a corner radius, a stroke width, a blur's deviation, a
74    /// gradient's tile mode, a conical gradient's separation.
75    ///
76    /// A zero stop count means the colors are in a ramp texture; see
77    /// `stop_count_code`.
78    pub const PARAMS: usize = 36;
79    /// A color filter's matrix, by column.
80    pub const FILTER: usize = 40;
81    /// The constant a color filter adds.
82    pub const FILTER_OFFSET: usize = 56;
83    /// Which color filter, if any, and in which form its matrix is stated.
84    ///
85    /// The second float holds the tint blend, the third the dither, and the
86    /// last the draw's opacity; see [`DITHER`] and [`OPACITY`]. Four unrelated
87    /// things share a slot because the slot is a four-component vector whether
88    /// or not anything fills it, and a fifth vector would cost every draw
89    /// sixteen bytes to carry three unused floats.
90    pub const FILTER_PARAMS: usize = 60;
91    /// The dither amplitude, in the target's storage units, with zero meaning
92    /// no dithering.
93    ///
94    /// Written by the backend at submission rather than by the recorder,
95    /// because the target's format is what decides it and a recording is made
96    /// without one -- which is also what keeps the color policy intact. The
97    /// shader is handed a number and still knows nothing about formats.
98    ///
99    /// It once had a flag beside it, saying whether a step was one of encoded
100    /// value or of light. Upstream's rate is a single constant on encoded
101    /// values, this took it, and the flag was never written after; the float
102    /// it held is [`OPACITY`]'s.
103    pub const DITHER: usize = 62;
104    /// What the tint blend's result is scaled by, before a color filter.
105    ///
106    /// The batch's to write, as the tint blend is: a material is a paint's
107    /// color, and this is how a draw that blends a color of its own into that
108    /// one fades. One for every other draw. See `BatchDraw::opacity`.
109    pub const OPACITY: usize = 63;
110
111    // Neither names a member of the block: the shader reads them as
112    // `filter_params.z` and `.w`, and these are where those land.
113    const _: () = assert!(DITHER == FILTER_PARAMS + 2 && OPACITY == FILTER_PARAMS + 3);
114}
115
116/// The number the shader reads for a tile mode.
117///
118/// Written once rather than at each call site: an image and a gradient must
119/// agree about what `1.0` means, and two copies of a mapping eventually do not.
120/// The stop count the shader reads, which doubles as the ramp flag.
121///
122/// Zero means the colors are in a texture rather than in this material, and
123/// the shader samples them instead of walking the stops. A sentinel rather
124/// than a flag of its own because the two are mutually exclusive by
125/// construction -- a ramp exists only when the stops outnumbered what fits, so
126/// a material with a ramp has no count worth reporting -- and because the float
127/// this frees is the one a conical gradient needs for its second center. That
128/// is the whole reason the fourth parameter slot was available to it.
129fn stop_count_code(count: usize, ramp: &Option<u32>) -> f32 {
130    match ramp {
131        Some(_) => 0.0,
132        None => count.max(1) as f32,
133    }
134}
135
136fn tile_code(tile: TileMode) -> f32 {
137    match tile {
138        TileMode::Clamp => tile::CLAMP,
139        TileMode::Repeat => tile::REPEAT,
140        TileMode::Decal => tile::DECAL,
141        TileMode::Mirror => tile::MIRROR,
142    }
143}
144
145/// Kind selector shared with the shader.
146pub mod kind {
147    pub const SOLID: f32 = 0.0;
148    pub const LINEAR: f32 = 1.0;
149    pub const RADIAL: f32 = 2.0;
150    pub const SWEEP: f32 = 3.0;
151    pub const IMAGE: f32 = 4.0;
152    pub const GLYPH: f32 = 5.0;
153    pub const BLUR: f32 = 6.0;
154    pub const ROUNDED_RECT: f32 = 7.0;
155    pub const ELLIPSE: f32 = 8.0;
156    pub const CONICAL: f32 = 9.0;
157    pub const MESH: f32 = 10.0;
158    pub const MORPHOLOGY: f32 = 11.0;
159    pub const ROUNDED_RECT_BLUR: f32 = 12.0;
160    pub const POINT_FIELD: f32 = 13.0;
161    pub const SHADOW_MESH: f32 = 14.0;
162}
163
164/// How many textures one runtime program may sample.
165///
166/// A fixed ceiling because the descriptor set layout is shared: every pipeline
167/// this renderer builds is built against one layout, so the bindings it
168/// declares are the same for a solid fill and for a caller's program. Raising
169/// this costs an image binding on every draw; removing the ceiling costs a
170/// layout per program.
171///
172/// Four covers what `dart:ui` shaders ask for in practice -- an image and a
173/// mask, an image and a gradient ramp, occasionally a third.
174pub const MAX_EFFECT_TEXTURES: usize = 4;
175
176/// How far one morphology pass reaches, in texels each way.
177///
178/// The shader's loop has to be bounded, and this is the bound. It is not a
179/// limit on the filter: a larger radius becomes more passes, since dilating
180/// twice dilates by the sum. Sixty-five samples per pixel per pass is already
181/// enough bandwidth that splitting is the cheaper answer anyway.
182pub const MORPHOLOGY_TAPS: u32 = 32;
183
184/// How many floats a runtime effect may take.
185///
186/// The whole material block, because an effect replaces the shader that would
187/// have read it as a material. A caller writing an effect declares the same
188/// std140 block and reads these as their own.
189pub const RUNTIME_FLOATS: usize = MATERIAL_FLOATS;
190
191/// How a texture is read between its texels.
192///
193/// Not two samplers. The same argument that keeps tile modes in the shader
194/// keeps this there: a sampler baked with a filter would mean one sampler per
195/// combination and a descriptor set per draw that used a different one. A
196/// linear sampler read exactly at a texel's center returns that texel and
197/// nothing else, so nearest sampling is the coordinate snapped to the nearest
198/// center before the read, which is one multiply-floor-divide and no bindings
199/// at all.
200///
201/// `dart:ui` offers four qualities. These are its first two; the other two are
202/// mipmapped and bicubic, and neither exists here to select.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
204pub enum Sampling {
205    /// Blend the texels around the coordinate. The right default: an image
206    /// drawn at any size but its own is otherwise a mess of hard edges.
207    #[default]
208    Linear,
209    /// The one texel the coordinate falls in.
210    ///
211    /// What pixel art needs, and what a sprite drawn at exactly its own size
212    /// wants in order to be certain no neighbor bled in.
213    Nearest,
214    /// A bicubic reconstruction over the sixteen texels around the coordinate.
215    ///
216    /// What `dart:ui` calls `FilterQuality.high`. Sharper than linear under
217    /// magnification, because the curve through four texels along an axis has
218    /// a slope where a straight line between two has a corner, and it costs
219    /// sixteen reads per fragment to say so.
220    ///
221    /// The particular curve is Mitchell-Netravali with `B` and `C` both a
222    /// third, which is what Skia's high quality has always meant and so what a
223    /// caller porting from Flutter is expecting. It rings slightly -- the
224    /// weights go a little negative between one and two texels out -- and that
225    /// overshoot is the sharpening, not an error in it.
226    Cubic,
227    /// A linear read of the mip level that matches how far the image is being
228    /// minified, blended with the level either side of it.
229    ///
230    /// What `dart:ui` calls `FilterQuality.medium`, and the one quality that
231    /// answers minification rather than magnification. Drawn at half its size
232    /// an image read linearly skips every other texel and aliases; read from
233    /// the level built for that size, every texel of the original contributes.
234    ///
235    /// It needs a texture that was allocated with a chain, since a level that
236    /// was never made cannot be read. On a texture without one every read lands
237    /// on the image itself and this is linear -- which is a picture that is
238    /// merely worse rather than wrong, and is what a sampler does with a level
239    /// it does not have.
240    Mipmap,
241}
242
243/// The number the shader reads for a sampling mode.
244fn sampling_code(sampling: Sampling) -> f32 {
245    match sampling {
246        Sampling::Linear => sampling::LINEAR,
247        Sampling::Nearest => sampling::NEAREST,
248        Sampling::Cubic => sampling::CUBIC,
249        Sampling::Mipmap => sampling::MIPMAP,
250    }
251}
252
253/// Sampling selector shared with the shader.
254pub mod sampling {
255    pub const LINEAR: f32 = 0.0;
256    pub const NEAREST: f32 = 1.0;
257    pub const CUBIC: f32 = 2.0;
258    pub const MIPMAP: f32 = 3.0;
259}
260
261/// Tile mode selector shared with the shader.
262///
263/// emblema's own numbering, older than [`TileMode`]'s upstream discriminants
264/// and deliberately not cast from them: `DECAL` is 2 and `MIRROR` 3 here,
265/// the other way round from the enum, and only this side is visible from
266/// the shader.
267pub mod tile {
268    pub const CLAMP: f32 = 0.0;
269    pub const REPEAT: f32 = 1.0;
270    pub const DECAL: f32 = 2.0;
271    pub const MIRROR: f32 = 3.0;
272}
273
274/// What space a color filter's matrix expects its input in.
275///
276/// A `dart:ui` color matrix is defined on straight color, which is the form a
277/// person writes a saturation or a sepia matrix in. A blend against a constant
278/// color is defined on premultiplied color, which is the form the compositing
279/// rules are stated in. Both are affine, both are one matrix here, and this is
280/// which one -- because the shader works in premultiplied color and has to know
281/// whether to undo that before applying the matrix.
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
283pub enum ColorForm {
284    /// Premultiplied, which is what the shader already has.
285    #[default]
286    Premultiplied,
287    /// Straight, which the shader divides out first and restores after.
288    Straight,
289}
290
291/// A function applied to a material's color, after the material and before the
292/// blend.
293///
294/// Only affine functions, which is less of a restriction than it sounds: a
295/// `dart:ui` color matrix is affine by definition, and every separable
296/// Porter-Duff blend against a *constant* color is affine in the other operand.
297/// So one matrix in the shader serves both, and which blend modes are offered
298/// is decided on the processor rather than in the fragment.
299#[derive(Debug, Clone, Copy, PartialEq, Default)]
300pub enum ColorFilter {
301    #[default]
302    None,
303    /// `columns[j]` scales the input's `j`th channel, and `offset` is added.
304    ///
305    /// Stored by column rather than by row -- the transpose of how `dart:ui`
306    /// writes it -- because that is what makes the shader four multiply-adds
307    /// of vectors rather than four dot products, and because a column is a
308    /// `vec4` where a row of the five-wide form is not.
309    Matrix {
310        columns: [[f32; 4]; 4],
311        offset: [f32; 4],
312        form: ColorForm,
313    },
314    /// Blend a constant color against the material's own, in a mode a matrix
315    /// cannot state.
316    ///
317    /// `dart:ui`'s `ColorFilter.mode` takes any blend mode, and most of them
318    /// are affine in the destination once the source is fixed -- those become
319    /// a [`Self::Matrix`] and cost the shader nothing beyond the multiply it
320    /// was already doing. The advanced modes are not affine: they are
321    /// piecewise, or they exchange components between channels. This is where
322    /// they go.
323    ///
324    /// It is arithmetic against a constant rather than against the frame, so
325    /// it needs no framebuffer fetch and no extension -- unlike the same mode
326    /// set on the paint, which reaches the hardware's blending unit and is
327    /// gated on one. The shader evaluates it with the same function a mesh's
328    /// per-vertex tint uses.
329    ///
330    /// `color` is premultiplied, as [`Self::blend`] leaves it and as the
331    /// specification states its operands.
332    Blend { color: [f32; 4], mode: BlendMode },
333    /// The sRGB transfer function, one direction or the other.
334    ///
335    /// The one filter `dart:ui` offers that a matrix cannot express: the curve
336    /// is piecewise, and the piece that covers almost all of the range has an
337    /// exponent in it. Approximating it as a power of 2.2 -- which is the usual
338    /// shortcut -- is wrong by about a percent in the midtones and much more
339    /// near black, where the linear segment is doing the work, so the shader
340    /// evaluates the real thing instead.
341    ///
342    /// Applied to straight color, per channel, leaving alpha alone. Gamma on a
343    /// premultiplied channel would be encoding the alpha along with the color.
344    Gamma { direction: Gamma },
345}
346
347/// Which way through the sRGB transfer function a [`ColorFilter::Gamma`] goes.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349pub enum Gamma {
350    /// Linear light in, sRGB's encoding out. `ColorFilter.linearToSrgbGamma`.
351    LinearToSrgb,
352    /// sRGB's encoding in, linear light out. `ColorFilter.srgbToLinearGamma`.
353    SrgbToLinear,
354}
355
356impl ColorFilter {
357    /// A filter from a 4x5 color matrix, in `dart:ui`'s layout but not its
358    /// units.
359    ///
360    /// Row-major and five wide: four scales and a constant per output channel,
361    /// red row first, applied to straight color with each channel from zero to
362    /// one. The constants are in the same units, zero to one, as Impeller's
363    /// are. `ColorFilter.matrix` states them in 0-255, and the engine divides
364    /// that column by 255 before Impeller sees it
365    /// (`lib/ui/painting/color_filter.cc`); a caller passing `dart:ui`'s
366    /// numbers through has to do the same.
367    pub fn matrix(rows: [f32; 20]) -> Self {
368        let mut columns = [[0.0f32; 4]; 4];
369        let mut offset = [0.0f32; 4];
370        for (out, row) in rows.chunks_exact(5).enumerate() {
371            for (channel, value) in row[..4].iter().enumerate() {
372                columns[channel][out] = *value;
373            }
374            offset[out] = row[4];
375        }
376        Self::Matrix {
377            columns,
378            offset,
379            form: ColorForm::Straight,
380        }
381    }
382
383    /// Linear light encoded into sRGB, which is `ColorFilter.linearToSrgbGamma`.
384    pub fn linear_to_srgb() -> Self {
385        Self::Gamma {
386            direction: Gamma::LinearToSrgb,
387        }
388    }
389
390    /// sRGB decoded back to linear light, which is
391    /// `ColorFilter.srgbToLinearGamma`.
392    pub fn srgb_to_linear() -> Self {
393        Self::Gamma {
394            direction: Gamma::SrgbToLinear,
395        }
396    }
397
398    /// A filter that blends a constant color against the material's own.
399    ///
400    /// The material is the destination and `color` is the source, which is the
401    /// way round `dart:ui` states `ColorFilter.mode` and the way round that
402    /// makes an icon sheet tinted by `SrcIn` mean what everyone expects.
403    ///
404    /// Most modes are affine in the destination once the source is fixed, so
405    /// each becomes a matrix and the shader needs no blending arithmetic at
406    /// all. The advanced modes are not affine -- they are piecewise, or
407    /// exchange components between channels -- so those become
408    /// [`Self::Blend`] and are evaluated per fragment against the constant, by
409    /// the same function a mesh's per-vertex tint goes through.
410    ///
411    /// Every mode is therefore a filter and none of them is refused. This used
412    /// to answer a `Result` and say in its own documentation that the advanced
413    /// modes were "refused rather than approximated", which the code below has
414    /// never done. Eighteen call sites carried an `expect` that could not fire, and
415    /// several of their messages stated the opposite of what the branch they
416    /// were on does.
417    ///
418    /// `color` is straight, like every color a caller states.
419    pub fn blend(color: [f32; 4], mode: BlendMode) -> Self {
420        use BlendMode as B;
421        let alpha = color[3];
422        // Premultiplied, because the rules below are stated for premultiplied
423        // operands and the shader's own color is premultiplied too.
424        let s = [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha];
425        let zero = [[0.0f32; 4]; 4];
426        let scaled = |k: f32| {
427            let mut m = zero;
428            for (i, column) in m.iter_mut().enumerate() {
429                column[i] = k;
430            }
431            m
432        };
433        // The destination's alpha reaches every output channel through this
434        // column alone, which is what makes the modes that multiply by it --
435        // or by one minus it -- a matrix rather than a special case.
436        let with_alpha_column = |mut m: [[f32; 4]; 4], column: [f32; 4]| {
437            for (i, value) in column.iter().enumerate() {
438                m[3][i] += *value;
439            }
440            m
441        };
442        let negated = [-s[0], -s[1], -s[2], -s[3]];
443        let (columns, offset) = match mode {
444            B::Clear => (zero, [0.0; 4]),
445            B::Src => (zero, s),
446            B::Dst => (scaled(1.0), [0.0; 4]),
447            B::SrcOver => (scaled(1.0 - alpha), s),
448            B::DstOver => (with_alpha_column(scaled(1.0), negated), s),
449            B::SrcIn => (with_alpha_column(zero, s), [0.0; 4]),
450            B::DstIn => (scaled(alpha), [0.0; 4]),
451            B::SrcOut => (with_alpha_column(zero, negated), s),
452            B::DstOut => (scaled(1.0 - alpha), [0.0; 4]),
453            B::SrcATop => (with_alpha_column(scaled(1.0 - alpha), s), [0.0; 4]),
454            B::DstATop => (with_alpha_column(scaled(alpha), negated), s),
455            B::Xor => (with_alpha_column(scaled(1.0 - alpha), negated), s),
456            B::Plus => (scaled(1.0), s),
457            B::Modulate => {
458                let mut m = zero;
459                for (i, column) in m.iter_mut().enumerate() {
460                    column[i] = s[i];
461                }
462                (m, [0.0; 4])
463            }
464            // Not affine, so not a matrix. Evaluated per fragment instead,
465            // against the same constant, by the same function a mesh's
466            // per-vertex tint goes through.
467            mode => return Self::Blend { color: s, mode },
468        };
469        Self::Matrix {
470            columns,
471            offset,
472            form: ColorForm::Premultiplied,
473        }
474    }
475
476    /// Whether this changes anything.
477    pub fn is_identity(&self) -> bool {
478        match self {
479            Self::None => true,
480            Self::Matrix {
481                columns,
482                offset,
483                form: _,
484            } => {
485                offset.iter().all(|v| *v == 0.0)
486                    && columns.iter().enumerate().all(|(j, column)| {
487                        column
488                            .iter()
489                            .enumerate()
490                            .all(|(i, v)| *v == if i == j { 1.0 } else { 0.0 })
491                    })
492            }
493            // `Dst` returns the destination untouched, which is the identity
494            // and is the only mode here that is. It cannot arrive through
495            // `blend`, which sends every affine mode to a matrix, but it can be
496            // written by hand.
497            Self::Blend { mode, .. } => *mode == BlendMode::Dst,
498            // The curve is the identity at exactly three points -- zero, one,
499            // and nowhere else on the range -- so as a function it never is.
500            Self::Gamma { .. } => false,
501        }
502    }
503
504    /// The code the shader reads to choose a path.
505    fn code(&self) -> f32 {
506        match self {
507            Self::None => filter::NONE,
508            Self::Matrix {
509                form: ColorForm::Premultiplied,
510                ..
511            } => filter::PREMULTIPLIED,
512            Self::Matrix {
513                form: ColorForm::Straight,
514                ..
515            } => filter::STRAIGHT,
516            Self::Gamma {
517                direction: Gamma::LinearToSrgb,
518            } => filter::LINEAR_TO_SRGB,
519            Self::Gamma {
520                direction: Gamma::SrgbToLinear,
521            } => filter::SRGB_TO_LINEAR,
522            Self::Blend { .. } => filter::BLEND,
523        }
524    }
525
526    pub(crate) fn pack_into(&self, out: &mut [f32; MATERIAL_FLOATS]) {
527        out[layout::FILTER_PARAMS] = self.code();
528        match self {
529            Self::Matrix {
530                columns, offset, ..
531            } => {
532                for (j, column) in columns.iter().enumerate() {
533                    out[layout::FILTER + j * 4..layout::FILTER + j * 4 + 4].copy_from_slice(column);
534                }
535                out[layout::FILTER_OFFSET..layout::FILTER_OFFSET + 4].copy_from_slice(offset);
536            }
537            // The constant goes where a matrix's offset would, which is what it
538            // is: the term that does not depend on the material. The mode goes
539            // in the first float of the matrix itself, which this filter has no
540            // use for -- sixteen floats are already reserved for every draw,
541            // and spending a fifth vector to carry one number would cost every
542            // draw that does not blend.
543            Self::Blend { color, mode } => {
544                out[layout::FILTER_OFFSET..layout::FILTER_OFFSET + 4].copy_from_slice(color);
545                out[layout::FILTER] = mode.code();
546            }
547            Self::None | Self::Gamma { .. } => {}
548        }
549    }
550}
551
552/// Filter selector shared with the shader.
553pub mod filter {
554    pub const NONE: f32 = 0.0;
555    pub const PREMULTIPLIED: f32 = 1.0;
556    pub const STRAIGHT: f32 = 2.0;
557    pub const LINEAR_TO_SRGB: f32 = 3.0;
558    pub const SRGB_TO_LINEAR: f32 = 4.0;
559    /// A blend against a constant color, for the modes a matrix cannot state.
560    pub const BLEND: f32 = 5.0;
561
562    /// Whether a code names a filter that reads straight rather than
563    /// premultiplied color.
564    ///
565    /// The shader decides this by comparison rather than by equality, and gets
566    /// the same answer, so the boundary lives here where both can cite it: a
567    /// filter added above this line is straight unless it says otherwise.
568    ///
569    /// [`BLEND`] says otherwise, which is what the sentence above anticipated.
570    /// The compositing specification states every blend on premultiplied
571    /// operands and the shader's own blend function takes them that way, so
572    /// handing it straight color would be handing it the wrong numbers.
573    pub fn is_straight(code: f32) -> bool {
574        code > PREMULTIPLIED && code < BLEND
575    }
576}
577
578/// A color stop.
579#[derive(Debug, Clone, Copy, PartialEq)]
580pub struct Stop {
581    /// Linear color with straight alpha.
582    pub color: [f32; 4],
583    /// Position along the gradient, from zero to one.
584    pub offset: f32,
585}
586
587impl Stop {
588    pub fn new(color: [f32; 4], offset: f32) -> Self {
589        Self { color, offset }
590    }
591}
592
593/// Maps a clip-space offset into a gradient's own space, in column order.
594///
595/// Clip space is anisotropic whenever the target is not square, and a transform
596/// may rotate or skew as well, so a circle in user space is an ellipse there.
597/// Radial and sweep gradients measure distance and angle, both of which that
598/// distortion changes, so they map back before measuring. A linear gradient
599/// projects onto an axis, which distortion does not affect, and so does not
600/// need this.
601pub type ToLocal = [f32; 12];
602
603/// How a shape is filled.
604#[derive(Debug, Clone, PartialEq)]
605pub enum Material {
606    Solid([f32; 4]),
607    /// Color comes from the vertices, and the result is dithered.
608    ///
609    /// Shades as opaque white, so the per-vertex color under `Modulate` -- which
610    /// is the identity against white -- is the whole result. That is the
611    /// arrangement `draw_vertices` already uses for a caller's mesh; what this
612    /// adds is that it dithers, which `Solid` must not.
613    ///
614    /// It exists for a gradient the rasterizer interpolates instead of the
615    /// fragment stage evaluating. A long run of nearly equal values is what
616    /// bands on an eight-bit target whichever stage produced it, and a route
617    /// that could not say so would drop the dither silently -- which is what
618    /// §19 of `docs/non-parity.md` records killing the first attempt at it.
619    ///
620    /// Carries no data: a section's colors ride on its vertices, and the
621    /// premultiplied alpha rides with them.
622    VertexGradient,
623    /// A gradient along an axis, starting at a point **in clip space**.
624    ///
625    /// Clip space for the start, because the fragment stage locates itself from
626    /// an interpolated clip position: the alternative, the fragment coordinate
627    /// builtin, has a different origin in each graphics API and would run the
628    /// gradient in opposite directions on the two backends.
629    ///
630    /// The axis is in the gradient's own space, and `to_local` maps a clip-space
631    /// offset into it — the same pairing radial and sweep use, and for the same
632    /// reason. Clip space is anisotropic whenever the target is not square, so
633    /// projecting onto an axis *there* weights the two axes by the target's
634    /// shape: on a target twice as wide as it is tall, a diagonal gradient runs
635    /// in the wrong direction.
636    LinearGradient {
637        /// End minus start, in the gradient's own space.
638        axis: [f32; 2],
639        to_local: ToLocal,
640        stops: Vec<Stop>,
641        /// Texture slot holding this gradient's colors, when they did not fit.
642        ///
643        /// `None` is the ordinary case: the stops travel in the material and
644        /// the shader walks them. `Some` means the recorder tabulated them into
645        /// an image instead, because there were more than [`MAX_STOPS`], and
646        /// the shader reads the color at the parameter rather than computing
647        /// it. The two must agree where both are possible, which is what makes
648        /// the choice invisible to a caller.
649        ramp: Option<u32>,
650        /// What happens beyond the two endpoints.
651        ///
652        /// The parameter a gradient is sampled by runs from zero at one end to
653        /// one at the other and is defined everywhere else too, so a shape
654        /// larger than its gradient asks a question the stops do not answer.
655        /// Clamping holds the end colors, which is the usual choice; repeating
656        /// tiles the ramp, which is what a stripe pattern is; decal draws
657        /// nothing outside, the same meaning it has for an image.
658        tile: TileMode,
659    },
660    /// A gradient outward from a center, **in clip space**, where `to_local`
661    /// carries the radius: it maps the clip-space offset so that the gradient's
662    /// edge lands at unit distance.
663    RadialGradient {
664        to_local: ToLocal,
665        stops: Vec<Stop>,
666        /// Texture slot holding this gradient's colors, when they did not fit.
667        ///
668        /// `None` is the ordinary case: the stops travel in the material and
669        /// the shader walks them. `Some` means the recorder tabulated them into
670        /// an image instead, because there were more than [`MAX_STOPS`], and
671        /// the shader reads the color at the parameter rather than computing
672        /// it. The two must agree where both are possible, which is what makes
673        /// the choice invisible to a caller.
674        ramp: Option<u32>,
675        /// What happens beyond the radius. See [`Material::LinearGradient`].
676        tile: TileMode,
677    },
678    /// A gradient around a center, **in clip space**, running from `start_angle`
679    /// to `end_angle` in radians.
680    SweepGradient {
681        to_local: ToLocal,
682        start_angle: f32,
683        end_angle: f32,
684        stops: Vec<Stop>,
685        /// Texture slot holding this gradient's colors, when they did not fit.
686        ///
687        /// `None` is the ordinary case: the stops travel in the material and
688        /// the shader walks them. `Some` means the recorder tabulated them into
689        /// an image instead, because there were more than [`MAX_STOPS`], and
690        /// the shader reads the color at the parameter rather than computing
691        /// it. The two must agree where both are possible, which is what makes
692        /// the choice invisible to a caller.
693        ramp: Option<u32>,
694        /// What happens outside the swept arc.
695        ///
696        /// Unlike the other two this can be a no-op: a sweep covering the whole
697        /// turn has no outside, and every direction lands within it.
698        tile: TileMode,
699    },
700    /// A gradient between two circles, the general form the other two are
701    /// special cases of.
702    ///
703    /// `center` is the first circle's center **in clip space**, and `to_local`
704    /// maps a clip-space offset into a space where that center is the origin
705    /// and the second circle's center lies at `(separation, 0)`. Putting the
706    /// separation on an axis costs nothing -- the rotation folds into a matrix
707    /// that has to be there anyway -- and buys the second center for one float
708    /// instead of two, which is what makes this fit at all.
709    ///
710    /// The radii are in that same space and are *not* normalized, unlike the
711    /// radial gradient's, because there are two of them and a scale can only
712    /// remove one. Carrying both plainly also means the degenerate cases need
713    /// no special handling: concentric circles are `separation == 0`, and a
714    /// cone rather than a tube is `radius_delta != 0`.
715    ConicalGradient {
716        to_local: ToLocal,
717        /// Radius of the first circle.
718        start_radius: f32,
719        /// Second radius minus the first.
720        radius_delta: f32,
721        /// Distance between the two centers.
722        separation: f32,
723        stops: Vec<Stop>,
724        /// Texture slot holding this gradient's colors, when they did not fit.
725        /// See [`Material::LinearGradient`].
726        ramp: Option<u32>,
727        /// What happens where the parameter leaves the unit interval. See
728        /// [`Material::LinearGradient`].
729        tile: TileMode,
730    },
731    /// A caller's own fragment program, with the floats it reads.
732    ///
733    /// The program is named rather than carried: registering one builds a
734    /// pipeline, which is expensive and outlives any draw, so a context holds
735    /// them and a material names which. The floats travel in the same uniform
736    /// block every other material uses, which is what lets an effect exist
737    /// without a second descriptor set.
738    Runtime {
739        program: u32,
740        uniforms: Vec<f32>,
741        /// The textures the program may sample, in the order it declares them.
742        ///
743        /// `None` in a position means the program does not read that binding,
744        /// and the backend binds its placeholder there -- a pipeline must have
745        /// every binding it declares bound, however unreachable the branch
746        /// reading it.
747        ///
748        /// The count is fixed rather than free because the descriptor set
749        /// layout every pipeline is built against has to be one layout. Four is
750        /// what that costs: three unused image bindings on a draw that samples
751        /// nothing, against a second set and a second layout for the draws that
752        /// want more than one.
753        textures: [Option<u32>; MAX_EFFECT_TEXTURES],
754    },
755    /// A texture, sampled at coordinates the vertices carry.
756    ///
757    /// Deliberately not [`Material::Image`] with a switch on where its
758    /// coordinates come from. An image mapped from clip space needs an origin,
759    /// a matrix and a source rectangle to say which part of a sheet it draws;
760    /// a mesh needs none of them, because a caller stating a coordinate per
761    /// vertex has already answered all three. What is left is small enough to
762    /// be its own thing, and keeping it separate means neither carries a field
763    /// that means nothing for it.
764    ///
765    /// This is what makes a sprite batch one draw: a hundred quads reading a
766    /// hundred different parts of one sheet differ only in their vertices.
767    Mesh {
768        /// Index into the texture table given at submission.
769        slot: u32,
770        /// Scales the sampled color, applied to premultiplied color like
771        /// [`Material::Image`]'s.
772        alpha: f32,
773        /// Straight color the sampled texel is multiplied by; white changes
774        /// nothing.
775        tint: [f32; 4],
776        /// What happens where a vertex names a coordinate outside the texture,
777        /// across and then down. See [`Material::Image`]'s.
778        tile: [TileMode; 2],
779        /// How to read between texels.
780        sampling: Sampling,
781    },
782    /// A texture, sampled through a mapping from clip space.
783    ///
784    /// `origin` and `to_local` together are an affine: a clip-space position
785    /// maps to texture coordinates as `to_local * (clip - origin)`, which lands
786    /// the image's top-left corner at zero and its bottom-right at one. The
787    /// same pair a radial gradient uses, for the same reason — clip space is
788    /// anisotropic on a non-square target, so a mapping that ignored it would
789    /// stretch every image by the aspect ratio.
790    ///
791    /// Which texture is not named here. The material is data the recorder
792    /// produces without touching the device, so it carries a slot into the
793    /// table supplied at submission instead of a backend handle.
794    Image {
795        to_local: ToLocal,
796        /// Index into the texture table given at submission.
797        slot: u32,
798        /// Scales the sampled color, for drawing an image translucently.
799        ///
800        /// Applied to premultiplied color, so it scales the whole texel rather
801        /// than only its alpha. A texture holds premultiplied color whether it
802        /// was uploaded or rendered into, and treating a sample as straight
803        /// alpha would apply the alpha twice — invisible for an opaque image,
804        /// and plain the moment one translucent image is drawn into another.
805        alpha: f32,
806        /// What happens outside the image, across and then down.
807        ///
808        /// Two because upstream has two: an image shader takes a horizontal
809        /// and a vertical mode, and its tiled texture contents fold and decal
810        /// each axis by its own. A decal along one axis only draws a band.
811        tile: [TileMode; 2],
812        /// How to read between texels.
813        sampling: Sampling,
814        /// The part of the texture to draw, as `[u0, v0, u1, v1]` from zero to
815        /// one.
816        ///
817        /// The whole texture is `[0, 0, 1, 1]`, which is what every caller
818        /// wanted until sprite sheets. Normalized rather than in texels because
819        /// a material is built by a recorder that has never seen the texture
820        /// and cannot know how large it is; the caller who uploaded it does.
821        ///
822        /// Applied after tiling rather than before, so a repeat repeats the
823        /// selected piece rather than the whole sheet -- which is the only
824        /// reading of "tile this sprite" that means anything.
825        source: [f32; 4],
826        /// Straight color the sampled texel is multiplied by; white changes
827        /// nothing.
828        ///
829        /// What turns one monochrome icon sheet into every state a control has.
830        /// A generalization of `alpha` rather than a rival to it: a tint of
831        /// `[1, 1, 1, a]` is exactly that scaling, and both are applied because
832        /// removing the narrower one would break callers for no gain.
833        ///
834        /// Straight rather than premultiplied because that is how a caller
835        /// states a color, and the shader premultiplies it before multiplying a
836        /// texel that already is -- scaling color by the tint's alpha as well,
837        /// which is what keeps the result premultiplied rather than merely
838        /// close to it.
839        tint: [f32; 4],
840    },
841    /// A rounded rectangle evaluated per fragment rather than tessellated.
842    ///
843    /// The shape an interface is mostly made of, and the one where computing
844    /// coverage beats building triangles for it. A tessellated rounded
845    /// rectangle costs vertices proportional to how round it is and has hard
846    /// edges unless the whole pass is multisampled; this is two triangles
847    /// whatever the radius, and antialiases itself from the distance field it
848    /// already computes.
849    ///
850    /// The geometry is in the shape's own space, with `to_local` mapping a
851    /// clip-space position into it -- the same pairing the gradients use, and
852    /// for the same reason: clip space is anisotropic on a target that is not
853    /// square, and a distance measured there would round the corners by
854    /// different amounts on each axis.
855    RoundedRect {
856        color: [f32; 4],
857        /// Half the width and height, in the shape's own space.
858        half_size: [f32; 2],
859        to_local: ToLocal,
860        /// Corner radius, in the shape's own space.
861        radius: f32,
862        /// The radius the outline's *outer* edge turns through, which is not
863        /// always the radius grown by half the stroke.
864        ///
865        /// An outline is the difference of two offset shapes rather than a band
866        /// around one, and the outer offset is where a join shows. Grow a
867        /// rounded corner and you get a bigger rounded corner, so this is
868        /// `radius + stroke / 2` for anything with a radius, and for anything
869        /// with a round join. A *mitered* square corner is the exception: its
870        /// offset is still square, so this is zero and the field draws the
871        /// point the join asks for.
872        ///
873        /// Carried rather than derived because the shader cannot see the join,
874        /// and because deriving it wrongly is what made a square-cornered
875        /// stroke come out with rounded corners and be refused this route
876        /// altogether.
877        outer_radius: f32,
878        /// Trace the outline at this width rather than filling, in the shape's
879        /// own space. Zero fills.
880        ///
881        /// Costs a distance field nothing: the field already says how far every
882        /// fragment is from the edge, so an outline is the band where that is
883        /// small. Tessellating one instead means building a second shape --
884        /// offset inward and outward, with the corners resolved -- which is
885        /// where a stroked outline gets its vertex count and its joins.
886        stroke: f32,
887    },
888    /// A *blurred* rounded rectangle evaluated per fragment, with no blur pass.
889    ///
890    /// The sibling of [`Self::RoundedRect`], and the reason it is worth having
891    /// is that the general route costs three passes per shape -- one for the
892    /// content and two for a separable Gaussian -- where this costs one draw in
893    /// the pass already being recorded. On a Raspberry Pi 5 three shadows that
894    /// way are 7.8 ms of a 26.8 ms frame and nine of its fourteen passes.
895    ///
896    /// The method is Raph Levien's "Blurred rounded rectangles", which is what
897    /// upstream's `SolidRRectBlurContents` evaluates too: the exact convolution
898    /// of a Gaussian with a rounded rectangle has no closed form, and this
899    /// approximates it as a product of two error functions along an axis,
900    /// corrected for the corners by measuring distance with an exponent other
901    /// than two. Every field here is a number the CPU precomputed for that
902    /// expression rather than anything a caller stated -- see
903    /// `Canvas::rrect_blur_material`, which is the only place they are derived.
904    ///
905    /// Only where every corner shares one circular radius, which is upstream's
906    /// condition too. Anything else takes the general route.
907    RoundedRectBlur {
908        color: [f32; 4],
909        to_local: ToLocal,
910        /// Half the rectangle, less `r1`, in the shape's own space.
911        adjust: [f32; 2],
912        /// The corner radius the approximation uses, which is not the caller's:
913        /// it grows with the deviation, because a blurred corner is rounder
914        /// than a sharp one.
915        r1: f32,
916        /// The exponent the corner distance is measured with. Two is a circle;
917        /// this is larger, which is what makes the blurred corner's profile
918        /// match a Gaussian's rather than a circle's.
919        exponent: f32,
920        /// One over the deviation, which is what the error function takes.
921        s_inv: f32,
922        /// The shorter side, which bounds how far the fade can reach before the
923        /// two edges of the shape meet.
924        min_edge: f32,
925        /// Normalizes the fade so that the middle of a large shape reaches full
926        /// coverage.
927        scale: f32,
928    },
929    /// An ellipse evaluated per fragment.
930    ///
931    /// Its own variant rather than a rounded rectangle with a large radius,
932    /// which gives a stadium: past half the shorter side a rounded rectangle
933    /// stops changing, where an ellipse keeps curving along both axes.
934    ///
935    /// The same geometry a rounded rectangle carries, less the radius, which
936    /// the two axes already state.
937    Ellipse {
938        color: [f32; 4],
939        /// The two semi-axes, in the shape's own space.
940        half_size: [f32; 2],
941        to_local: ToLocal,
942        /// Trace the outline at this width rather than filling. Zero fills.
943        stroke: f32,
944    },
945    /// One axis of a separable Gaussian blur of a sampled texture.
946    ///
947    /// Separable because a two-dimensional Gaussian is the product of two
948    /// one-dimensional ones, so blurring along each axis in turn gives the
949    /// same result as a square of taps at a fraction of the cost: at a radius
950    /// of sixteen that is thirty-three taps against a thousand and eighty-nine.
951    /// Two passes are the price, which is why this names an axis rather than
952    /// describing the whole blur.
953    Blur {
954        to_local: ToLocal,
955        slot: u32,
956        /// One tap's step, in the sampled texture's own coordinates.
957        ///
958        /// The axis and the texel size together: a horizontal pass over a
959        /// target `w` wide steps `(1/w, 0)`. Stated here rather than derived in
960        /// the shader because the shader does not know the size of what it is
961        /// sampling.
962        step: [f32; 2],
963        /// Standard deviation, in taps.
964        ///
965        /// The tap count follows from it -- the kernel reaches
966        /// `(sigma - 0.5) * sqrt(3)` each way, which is upstream's radius for a
967        /// given deviation -- so a caller sets how soft the result is and
968        /// nothing else.
969        sigma: f32,
970    },
971    /// One axis of a morphological filter of a finished layer.
972    ///
973    /// The largest or smallest sample within a radius, per channel, which is
974    /// what `dart:ui` calls `ImageFilter.dilate` and `ImageFilter.erode`. Like
975    /// the blur it is separable -- a rectangular structuring element is the
976    /// product of two intervals -- so two passes give the square of taps.
977    ///
978    /// Unlike the blur it is also *decomposable*: dilating by `a` and then by
979    /// `b` is dilating by `a + b` exactly, because the structuring elements add
980    /// under the Minkowski sum. A radius past what one pass can reach is
981    /// therefore split across passes rather than approximated by sampling more
982    /// sparsely. Sparse taps work for a blur, where a missed sample costs a
983    /// little smoothness, and do not work here: the result is a maximum, so a
984    /// missed sample is a scallop in the edge.
985    Morphology {
986        to_local: ToLocal,
987        slot: u32,
988        /// One tap's step, in the sampled texture's own coordinates. As
989        /// [`Self::Blur::step`].
990        step: [f32; 2],
991        /// How many texels each way this pass reaches, at most
992        /// [`MORPHOLOGY_TAPS`].
993        ///
994        /// A whole number of texels, because the structuring element is a set
995        /// of samples rather than a weighting of them and there is no meaning
996        /// to half of one.
997        radius: f32,
998        /// The largest sample in reach rather than the smallest.
999        dilate: bool,
1000    },
1001    /// Coverage sampled from an atlas, tinting one color.
1002    ///
1003    /// Distinct from [`Self::Image`] in two ways that matter. The texture is
1004    /// read as *coverage* rather than as color — one channel scaling a solid,
1005    /// which is what antialiased text is — and the coordinates come from the
1006    /// vertices rather than from a mapping in the paint, so a run of glyphs
1007    /// reading different parts of one atlas is a single draw.
1008    Glyph {
1009        /// Linear color with straight alpha, as the text is painted.
1010        color: [f32; 4],
1011        /// Index into the texture table given at submission.
1012        slot: u32,
1013    },
1014    /// Many discs of one color, evaluated from the vertices rather than the
1015    /// paint, so that a field of them is one draw.
1016    ///
1017    /// Carries no mapping and no size, which is the whole point of it. Every
1018    /// other fragment-evaluated shape here locates itself through `to_local`,
1019    /// and `to_local` holds the shape's center -- so two of them at different
1020    /// places are two materials and cannot share a draw. This one locates
1021    /// itself from the interpolated texture coordinate, which the vertices
1022    /// carry as the unit circle's corners, so any number of discs at any
1023    /// centers are one material and one draw.
1024    ///
1025    /// The edge is the same edge. `disc_coverage` in the shader differentiates
1026    /// the implicit function across the pixel rather than forming a distance,
1027    /// and a derivative of an interpolated value is as available as that of a
1028    /// computed one.
1029    PointField {
1030        /// One color for the field, premultiplied as everything here is.
1031        color: [f32; 4],
1032    },
1033    /// A blurred convex shape's shadow, drawn as a mesh whose vertices carry
1034    /// a Gaussian coefficient in their first texture coordinate.
1035    ///
1036    /// The coefficient is interpolated across each triangle and mapped per
1037    /// fragment through the Gaussian's integral, upstream's
1038    /// `IPHalfFractionToFastGaussianCDF`: zero at the mesh's outer ring, where
1039    /// the shadow has gone, one at its umbra. Interpolating the opacity
1040    /// instead would draw the falloff as straight ramps. Upstream's
1041    /// `ShadowVerticesContents`; the mesh is `emblema_geometry::shadow`'s.
1042    ShadowMesh {
1043        /// The shadow's color, straight, as a solid fill's.
1044        color: [f32; 4],
1045    },
1046}
1047
1048/// What happens outside an image's own bounds.
1049///
1050/// Numbered as upstream numbers them: the discriminants are `dart:ui`'s
1051/// `TileMode.index`, `DlTileMode` and Impeller's `Entity::TileMode`, so
1052/// `as u8` gives an embedder the upstream number, as with
1053/// [`crate::BlendMode`]. The number a shader reads is [`tile`], kept apart.
1054#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1055#[repr(u8)]
1056pub enum TileMode {
1057    /// Hold the edge pixel. The usual choice for drawing an image once.
1058    #[default]
1059    Clamp = 0,
1060    /// Repeat the image, tiling the plane.
1061    Repeat = 1,
1062    /// Repeat, reversing every other copy.
1063    ///
1064    /// What repeating is for when the two ends do not match. A ramp tiled by
1065    /// [`TileMode::Repeat`] jumps from its last color back to its first at
1066    /// every period, and that discontinuity is a visible seam; reflecting each
1067    /// alternate copy joins end to end and leaves none. The period is twice as
1068    /// long, since a copy and its reflection make one.
1069    Mirror = 2,
1070    /// Draw nothing outside the image.
1071    ///
1072    /// Distinct from clamping in the only case that matters: a shape larger
1073    /// than the image it is filled with. Clamping smears the border across the
1074    /// remainder, which reads as a rendering fault rather than as a choice.
1075    Decal = 3,
1076}
1077
1078impl Material {
1079    pub fn solid(color: [f32; 4]) -> Self {
1080        Self::Solid(color)
1081    }
1082
1083    /// How this material reads a texture, if it reads one.
1084    ///
1085    /// `None` for a material that samples nothing, which is not the same answer
1086    /// as [`Sampling::Nearest`]: one says there is no texture and the other says
1087    /// there is and it is read at a texel's center.
1088    ///
1089    /// Here because a caller above the HAL may need to know whether a draw
1090    /// interpolates between texels, and only this type knows. The test harness
1091    /// asks it to size a cross-device tolerance: a filter that forms a weighted
1092    /// sum of texels does so with weights of implementation-defined precision,
1093    /// so two devices disagree on every interpolated pixel by more than the last
1094    /// bit of one store. Deriving that from a recording rather than from the
1095    /// scene that produced it is the point -- the scene model has four separate
1096    /// places a sampled texture can come from and a comment recording four
1097    /// occasions on which enumerating them missed one.
1098    pub fn sampling(&self) -> Option<Sampling> {
1099        match self {
1100            // Samples nothing: the color arrives on the vertices.
1101            Self::VertexGradient => None,
1102            Self::Image { sampling, .. } | Self::Mesh { sampling, .. } => Some(*sampling),
1103            // Reads a texture and states no filter: a blur and a morphology
1104            // sample their own target at offsets they compute, and a glyph reads
1105            // coverage out of the atlas. What they do between texels is the
1106            // shader's, not a field's, so there is no mode to report here.
1107            Self::Blur { .. }
1108            | Self::Morphology { .. }
1109            | Self::Glyph { .. }
1110            | Self::Runtime { .. } => None,
1111            // Reads no texture at all.
1112            Self::Solid(_)
1113            | Self::LinearGradient { .. }
1114            | Self::RadialGradient { .. }
1115            | Self::SweepGradient { .. }
1116            | Self::ConicalGradient { .. }
1117            | Self::RoundedRect { .. }
1118            | Self::RoundedRectBlur { .. }
1119            | Self::Ellipse { .. }
1120            | Self::PointField { .. }
1121            | Self::ShadowMesh { .. } => None,
1122        }
1123    }
1124
1125    /// Whether this material reads between texels rather than at one.
1126    ///
1127    /// Every mode but [`Sampling::Nearest`] forms a weighted sum: linear over
1128    /// four texels, bicubic over sixteen, mipmapped over two levels of the
1129    /// first. Measured on a Raspberry Pi 5, one scene rendered twice differing
1130    /// only in this: nearest is byte for byte identical between v3d and llvmpipe
1131    /// over the whole frame, and linear reaches a delta of three across seventy
1132    /// per cent of it.
1133    /// Whether this material reads its texture at offsets it computes, rather
1134    /// than at the coordinate it was handed.
1135    ///
1136    /// True for the two filters that walk a neighborhood: a blur steps out by a
1137    /// sigma, a morphology by a radius, and neither need land on a texel center
1138    /// whatever size the texture is. So this is the one case where a material
1139    /// can say that a read interpolates without knowing the texture -- which is
1140    /// why it is a separate question from [`Self::sampling`], and why a layer
1141    /// dilated by a morphology is one of the scenes that put two devices three
1142    /// levels apart.
1143    pub fn reads_at_computed_offsets(&self) -> bool {
1144        matches!(self, Self::Blur { .. } | Self::Morphology { .. })
1145    }
1146
1147    /// The same material at `factor` of its opacity.
1148    ///
1149    /// Applied to every color a material carries, since a gradient's stops may
1150    /// differ in alpha and scaling them together is what keeps the ramp the
1151    /// same ramp. Straight alpha, so this happens before the premultiply the
1152    /// packing does rather than after it.
1153    ///
1154    /// Two variants are left alone and it is worth saying which. A blur or a
1155    /// morphology is a filter over a finished pass rather than a paint, so
1156    /// there is no color in it to dim -- and nothing asks this of one. A
1157    /// caller's program is the other: its output is whatever it computes, and
1158    /// this renderer has no uniform it may write to. That is a real limit
1159    /// wherever the caller wanted the dimming, and it is stated at the one
1160    /// place that asks for it.
1161    #[must_use]
1162    pub fn with_opacity(mut self, factor: f32) -> Self {
1163        let scale = |color: &mut [f32; 4]| color[3] *= factor;
1164        match &mut self {
1165            Self::Solid(color)
1166            | Self::RoundedRect { color, .. }
1167            | Self::RoundedRectBlur { color, .. }
1168            | Self::Ellipse { color, .. }
1169            | Self::PointField { color }
1170            | Self::ShadowMesh { color }
1171            | Self::Glyph { color, .. } => scale(color),
1172            Self::LinearGradient { stops, .. }
1173            | Self::RadialGradient { stops, .. }
1174            | Self::SweepGradient { stops, .. }
1175            | Self::ConicalGradient { stops, .. } => {
1176                for stop in stops.iter_mut() {
1177                    scale(&mut stop.color);
1178                }
1179            }
1180            Self::Mesh { alpha, .. } | Self::Image { alpha, .. } => *alpha *= factor,
1181            Self::Runtime { .. } | Self::Blur { .. } | Self::Morphology { .. } => {}
1182            // Nothing here to scale -- the alpha is premultiplied into the
1183            // vertex colors, which this cannot see. The one caller is the thin
1184            // stroke above, and a fill passes a factor of one, so the route
1185            // that uses this material never asks. A route that did would have
1186            // to bake the factor in when it builds the sections.
1187            Self::VertexGradient => {}
1188        }
1189        self
1190    }
1191
1192    /// Whether drawing with this would change anything.
1193    pub fn is_invisible(&self) -> bool {
1194        match self {
1195            Self::Solid(color) | Self::PointField { color } | Self::ShadowMesh { color } => {
1196                color[3] <= 0.0
1197            }
1198            // The colors are on the vertices, so the only honest answer is
1199            // that it might draw something.
1200            Self::VertexGradient => false,
1201            Self::LinearGradient { stops, .. }
1202            | Self::RadialGradient { stops, .. }
1203            | Self::SweepGradient { stops, .. }
1204            | Self::ConicalGradient { stops, .. } => {
1205                stops.is_empty() || stops.iter().all(|s| s.color[3] <= 0.0)
1206            }
1207            // What the texture holds is unknown here, so only a zero alpha
1208            // makes an image provably invisible.
1209            Self::Image { alpha, .. } | Self::Mesh { alpha, .. } => *alpha <= 0.0,
1210            // What a caller's program draws is unknowable from here, so the
1211            // only honest answer is that it might draw something.
1212            Self::Runtime { .. } => false,
1213            // A blur of nothing is nothing, but the pass still has to run: what
1214            // it samples is not knowable from here.
1215            Self::Blur { .. } | Self::Morphology { .. } => false,
1216            // No `half_size` to test: a blurred rectangle with no area still
1217            // draws, because the blur carries color past where the shape is.
1218            Self::RoundedRectBlur { color, .. } => color[3] <= 0.0,
1219            Self::RoundedRect {
1220                color, half_size, ..
1221            }
1222            | Self::Ellipse {
1223                color, half_size, ..
1224            } => color[3] <= 0.0 || half_size[0] <= 0.0 || half_size[1] <= 0.0,
1225            Self::Glyph { color, .. } => color[3] <= 0.0,
1226        }
1227    }
1228
1229    /// The texture slot this samples, for a backend building its bindings.
1230    ///
1231    /// Matched exhaustively rather than with a catch-all. A variant that
1232    /// samples something and is not listed here reports no slot, so the backend
1233    /// binds its placeholder and the draw comes out flat white -- a plausible
1234    /// picture rather than an error, and one nothing else would explain.
1235    /// Every texture slot this material samples, in binding order.
1236    ///
1237    /// One entry for everything but a runtime program, which may declare
1238    /// several. A backend building descriptors needs the whole tuple, since a
1239    /// set holds all of them at once; a backend asking only which slot to bind
1240    /// first has [`Self::texture_slot`].
1241    pub fn texture_slots(&self) -> [Option<u32>; MAX_EFFECT_TEXTURES] {
1242        match self {
1243            Self::Runtime { textures, .. } => *textures,
1244            other => {
1245                let mut slots = [None; MAX_EFFECT_TEXTURES];
1246                slots[0] = other.texture_slot();
1247                slots
1248            }
1249        }
1250    }
1251
1252    pub fn texture_slot(&self) -> Option<u32> {
1253        match self {
1254            Self::VertexGradient => None,
1255            Self::Image { slot, .. }
1256            | Self::Mesh { slot, .. }
1257            | Self::Glyph { slot, .. }
1258            | Self::Blur { slot, .. }
1259            | Self::Morphology { slot, .. } => Some(*slot),
1260            // A gradient names a texture only when its colors were too many to
1261            // carry, which is why this is an option rather than a slot.
1262            Self::LinearGradient { ramp, .. }
1263            | Self::RadialGradient { ramp, .. }
1264            | Self::SweepGradient { ramp, .. }
1265            | Self::ConicalGradient { ramp, .. } => *ramp,
1266            Self::Solid(_)
1267            | Self::PointField { .. }
1268            | Self::ShadowMesh { .. }
1269            | Self::RoundedRect { .. }
1270            | Self::RoundedRectBlur { .. }
1271            | Self::Ellipse { .. } => None,
1272            // Whatever a caller named, and `None` where they named nothing --
1273            // in which case the placeholder is bound and a program that
1274            // samples anyway reads opaque white.
1275            // The first of them, for the callers that still ask a material for
1276            // one slot. `texture_slots` is what a backend binding several
1277            // should ask.
1278            Self::Runtime { textures, .. } => textures[0],
1279        }
1280    }
1281
1282    /// The stops, for any material that has them.
1283    fn stops(&self) -> &[Stop] {
1284        match self {
1285            // Its stops became vertex colors when the sections were built.
1286            Self::VertexGradient => &[],
1287            Self::Solid(_)
1288            | Self::PointField { .. }
1289            | Self::ShadowMesh { .. }
1290            | Self::Image { .. }
1291            | Self::Mesh { .. }
1292            | Self::Glyph { .. }
1293            | Self::Blur { .. }
1294            | Self::Morphology { .. }
1295            | Self::RoundedRect { .. }
1296            | Self::RoundedRectBlur { .. }
1297            | Self::Ellipse { .. }
1298            | Self::Runtime { .. } => &[],
1299            Self::LinearGradient { stops, .. }
1300            | Self::RadialGradient { stops, .. }
1301            | Self::SweepGradient { stops, .. }
1302            | Self::ConicalGradient { stops, .. } => stops,
1303        }
1304    }
1305
1306    /// Pack into the layout the shader declares.
1307    ///
1308    /// Every member is a four-component vector, which is what lets this be a
1309    /// flat array of floats copied straight into a uniform buffer: the std140
1310    /// rules the shader's block is declared with place a `vec4` and an array
1311    /// of them at exactly these offsets, so no member needs padding written
1312    /// around it.
1313    ///
1314    /// Stops beyond the limit are dropped rather than resampled, and the count
1315    /// travels alongside so the shader ignores unused entries instead of
1316    /// blending toward whatever happens to be in them.
1317    /// Whether every pixel this material writes comes out fully opaque.
1318    ///
1319    /// Used to decide whether a draw may be split into several, which is only safe when
1320    /// writing a pixel twice gives what writing it once does. Under `SrcOver` that holds
1321    /// exactly when the source is opaque.
1322    ///
1323    /// **False unless shown otherwise.** A solid fill carries its alpha and a gradient's
1324    /// stops carry theirs. Everything else -- images, the analytic shapes, blurs, a
1325    /// caller's own program -- is refused outright.
1326    ///
1327    /// A tabulated gradient still answers from its stops, and that is worth saying because
1328    /// the first version of this refused one. `ramp` being `Some` means the *shader* reads
1329    /// a texture instead of walking the list, not that the list is gone: the recorder maps
1330    /// every stop into the material either way and bakes the ramp from the same list, by
1331    /// interpolating between them. Interpolating between opaque colors gives an opaque
1332    /// one, so the texels are opaque exactly when the stops are. Refusing a ramp cost the
1333    /// whole of occlusion culling's benefit on the bench's frame, whose wash is five stops
1334    /// against a `MAX_STOPS` of four.
1335    pub fn is_opaque(&self) -> bool {
1336        let stops_opaque =
1337            |stops: &[Stop]| !stops.is_empty() && stops.iter().all(|s| s.color[3] >= 1.0);
1338        match self {
1339            Material::Solid(color) => color[3] >= 1.0,
1340            Material::LinearGradient { stops, .. }
1341            | Material::RadialGradient { stops, .. }
1342            | Material::SweepGradient { stops, .. }
1343            | Material::ConicalGradient { stops, .. } => stops_opaque(stops),
1344            _ => false,
1345        }
1346    }
1347
1348    /// Whether this material's shading reads screen-space derivatives.
1349    ///
1350    /// `dpdx` and `dpdy` are computed across a two-by-two quad of fragments, using helper
1351    /// invocations outside the primitive. Whether a scissor keeps those helpers alive is
1352    /// not something either specification settles, and implementations differ: Mesa
1353    /// 26.2.3 keeps them and 25.2.8 does not. So a draw whose shading depends on them
1354    /// gives a different answer at a scissor's edge than away from it, and splitting such
1355    /// a draw by scissor changes the picture along the seam.
1356    ///
1357    /// Measured rather than reasoned about: an analytic shadow drawn once reads 217 where
1358    /// the same shadow drawn in four scissored strips reads 206, at the pixel on the
1359    /// strip boundary, on Mesa 25.2.8. See `a_scissor_does_not_change_what_a_draw_paints`.
1360    ///
1361    /// **True unless shown otherwise**, which is the only safe direction: a material
1362    /// wrongly called derivative-free leaves a seam in the frame. The two groups that are
1363    /// shown otherwise are solid fills, whose coverage comes from the rasterizer, and the
1364    /// gradients, which sample their ramp at an explicit level of zero. The rest either
1365    /// take a coverage from the gradient of a distance field -- the rounded rectangle, the
1366    /// ellipse and the rounded-rectangle blur -- or a texture level from the rate their
1367    /// coordinates change, which is every image fill, or are a caller's own program.
1368    pub fn needs_screen_derivatives(&self) -> bool {
1369        !matches!(
1370            self,
1371            Material::Solid(_)
1372                | Material::VertexGradient
1373                | Material::LinearGradient { .. }
1374                | Material::RadialGradient { .. }
1375                | Material::SweepGradient { .. }
1376                | Material::ConicalGradient { .. }
1377        )
1378    }
1379
1380    /// Whether this material asks the target for a long run of nearly equal
1381    /// values, and so wants a dither.
1382    ///
1383    /// The gradients, and nothing else -- the same set the shader used to test
1384    /// for itself. Asked here because the shader cannot be the place that knows:
1385    /// it tests the material *kind*, so a route that draws a gradient under a
1386    /// different kind silently stops dithering. §19 of `docs/non-parity.md`
1387    /// records that happening, in the reverted attempt at upstream's
1388    /// vertex-interpolated fast gradient.
1389    ///
1390    /// **False unless shown otherwise.** Dithering something with no band to
1391    /// break adds noise to a flat color.
1392    pub fn dithers(&self) -> bool {
1393        matches!(
1394            self,
1395            // The one non-gradient here, and the reason this predicate is not
1396            // simply "is a gradient": what it draws is a gradient, with the
1397            // rasterizer interpolating it instead of the fragment stage.
1398            Material::VertexGradient
1399                | Material::LinearGradient { .. }
1400                | Material::RadialGradient { .. }
1401                | Material::SweepGradient { .. }
1402                | Material::ConicalGradient { .. }
1403        )
1404    }
1405
1406    pub fn to_uniform(&self) -> [f32; MATERIAL_FLOATS] {
1407        let mut out = [0.0f32; MATERIAL_FLOATS];
1408
1409        if let Self::Solid(color) = self {
1410            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1411            out[layout::PARAMS] = 1.0;
1412            out[layout::PARAMS + 1] = kind::SOLID;
1413            return out;
1414        }
1415
1416        // Opaque white under the solid kind, which is the identity for the
1417        // `Modulate` tint that carries the vertex color. Packed here rather
1418        // than falling through, because the machinery below reads `stops` and
1419        // this material has none -- a gradient with no stops packs as
1420        // transparent black, which is the opposite of an identity.
1421        if matches!(self, Self::VertexGradient) {
1422            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(&[1.0, 1.0, 1.0, 1.0]);
1423            out[layout::PARAMS] = 1.0;
1424            out[layout::PARAMS + 1] = kind::SOLID;
1425            return out;
1426        }
1427
1428        // A glyph is a solid color plus a texture read; the coordinates come
1429        // from the vertices, so nothing about the mapping is packed here.
1430        if let Self::Glyph { color, .. } = self {
1431            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1432            out[layout::PARAMS] = 1.0;
1433            out[layout::PARAMS + 1] = kind::GLYPH;
1434            return out;
1435        }
1436
1437        // An image carries no stops and no count, and must be packed before
1438        // the gradient path below decides it has too few to interpolate.
1439        if let Self::PointField { color } = self {
1440            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1441            out[layout::PARAMS] = 1.0;
1442            out[layout::PARAMS + 1] = kind::POINT_FIELD;
1443            return out;
1444        }
1445
1446        if let Self::ShadowMesh { color } = self {
1447            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1448            out[layout::PARAMS] = 1.0;
1449            out[layout::PARAMS + 1] = kind::SHADOW_MESH;
1450            return out;
1451        }
1452
1453        if let Self::Ellipse {
1454            color,
1455            half_size,
1456            to_local,
1457            stroke,
1458        } = self
1459        {
1460            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1461            out[layout::GEOMETRY + 2] = half_size[0];
1462            out[layout::GEOMETRY + 3] = half_size[1];
1463            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1464            out[layout::PARAMS] = 1.0;
1465            out[layout::PARAMS + 1] = kind::ELLIPSE;
1466            out[layout::PARAMS + 3] = *stroke;
1467            return out;
1468        }
1469
1470        if let Self::RoundedRect {
1471            color,
1472            half_size,
1473            to_local,
1474            radius,
1475            outer_radius,
1476            stroke,
1477        } = self
1478        {
1479            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1480            out[layout::GEOMETRY + 1] = *outer_radius;
1481            out[layout::GEOMETRY + 2] = half_size[0];
1482            out[layout::GEOMETRY + 3] = half_size[1];
1483            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1484            out[layout::PARAMS] = 1.0;
1485            out[layout::PARAMS + 1] = kind::ROUNDED_RECT;
1486            out[layout::PARAMS + 2] = *radius;
1487            out[layout::PARAMS + 3] = *stroke;
1488            return out;
1489        }
1490
1491        if let Self::RoundedRectBlur {
1492            color,
1493            to_local,
1494            adjust,
1495            r1,
1496            exponent,
1497            s_inv,
1498            min_edge,
1499            scale,
1500        } = self
1501        {
1502            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(color);
1503            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1504            // The first two floats of `GEOMETRY` are unclaimed for every kind
1505            // that carries a mapping, which this does, so the two that follow
1506            // are what a rounded rectangle would have used for its half size --
1507            // and it needs none, because `adjust` already has the shape in it.
1508            out[layout::GEOMETRY] = adjust[0];
1509            out[layout::GEOMETRY + 1] = adjust[1];
1510            out[layout::GEOMETRY + 2] = *s_inv;
1511            out[layout::GEOMETRY + 3] = *min_edge;
1512            // `OFFSETS` holds stop positions for a gradient and nothing for
1513            // anything else, which is what makes it the seventh float this
1514            // needs and the only kind here that borrows it.
1515            out[layout::OFFSETS] = *scale;
1516            out[layout::PARAMS] = 1.0;
1517            out[layout::PARAMS + 1] = kind::ROUNDED_RECT_BLUR;
1518            out[layout::PARAMS + 2] = *r1;
1519            out[layout::PARAMS + 3] = *exponent;
1520            return out;
1521        }
1522
1523        if let Self::Blur {
1524            to_local,
1525            step,
1526            sigma,
1527            ..
1528        } = self
1529        {
1530            out[layout::GEOMETRY + 2] = step[0];
1531            out[layout::GEOMETRY + 3] = step[1];
1532            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1533            out[layout::PARAMS] = 1.0;
1534            out[layout::PARAMS + 1] = kind::BLUR;
1535            out[layout::PARAMS + 2] = *sigma;
1536            return out;
1537        }
1538
1539        if let Self::Morphology {
1540            to_local,
1541            step,
1542            radius,
1543            dilate,
1544            ..
1545        } = self
1546        {
1547            out[layout::GEOMETRY + 2] = step[0];
1548            out[layout::GEOMETRY + 3] = step[1];
1549            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1550            out[layout::PARAMS] = 1.0;
1551            out[layout::PARAMS + 1] = kind::MORPHOLOGY;
1552            out[layout::PARAMS + 2] = radius.clamp(0.0, MORPHOLOGY_TAPS as f32);
1553            out[layout::PARAMS + 3] = if *dilate { 1.0 } else { 0.0 };
1554            return out;
1555        }
1556
1557        if let Self::Runtime { uniforms, .. } = self {
1558            // Straight into the block, in the order the caller wrote them. No
1559            // kind is set: nothing in the shared shader will read this, and a
1560            // caller's program does not branch on one.
1561            let count = uniforms.len().min(RUNTIME_FLOATS);
1562            out[..count].copy_from_slice(&uniforms[..count]);
1563            return out;
1564        }
1565
1566        if let Self::Mesh {
1567            alpha,
1568            tint,
1569            tile,
1570            sampling,
1571            ..
1572        } = self
1573        {
1574            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(tint);
1575            out[layout::GEOMETRY] = *alpha;
1576            out[layout::GEOMETRY + 1] = tile_code(tile[0]);
1577            out[layout::GEOMETRY + 2] = tile_code(tile[1]);
1578            out[layout::PARAMS] = 1.0;
1579            out[layout::PARAMS + 1] = kind::MESH;
1580            out[layout::PARAMS + 2] = sampling_code(*sampling);
1581            return out;
1582        }
1583
1584        if let Self::Image {
1585            to_local,
1586            alpha,
1587            tile,
1588            sampling,
1589            source,
1590            tint,
1591            ..
1592        } = self
1593        {
1594            // Into the stop colors, which an image has none of. Eight floats
1595            // that would otherwise travel as zeros on every image draw.
1596            out[layout::STOPS..layout::STOPS + 4].copy_from_slice(source);
1597            out[layout::STOPS + 4..layout::STOPS + 8].copy_from_slice(tint);
1598            // The vertical mode in the slot a mapped kind leaves free. Not the
1599            // first: that is the flag a batch sets for a paint read at texture
1600            // coordinates, and it is the batch's to write.
1601            out[layout::GEOMETRY + 1] = tile_code(tile[1]);
1602            out[layout::GEOMETRY + 2] = *alpha;
1603            out[layout::GEOMETRY + 3] = tile_code(tile[0]);
1604            out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1605            out[layout::PARAMS] = 1.0;
1606            out[layout::PARAMS + 1] = kind::IMAGE;
1607            out[layout::PARAMS + 2] = sampling_code(*sampling);
1608            return out;
1609        }
1610
1611        let stops = self.stops();
1612        let count = stops.len().min(MAX_STOPS);
1613        for (i, stop) in stops.iter().take(count).enumerate() {
1614            out[layout::STOPS + i * 4..layout::STOPS + i * 4 + 4].copy_from_slice(&stop.color);
1615            out[layout::OFFSETS + i] = stop.offset;
1616        }
1617        out[layout::PARAMS] = count.max(1) as f32;
1618
1619        // A gradient with fewer than two stops has nothing to interpolate
1620        // between, so it renders as its first color rather than sending the
1621        // shader down a path that would read an entry nothing wrote.
1622        if count < 2 {
1623            out[layout::PARAMS + 1] = kind::SOLID;
1624            return out;
1625        }
1626
1627        match self {
1628            Self::Solid(_)
1629            | Self::VertexGradient
1630            | Self::PointField { .. }
1631            | Self::ShadowMesh { .. }
1632            | Self::Image { .. }
1633            | Self::Mesh { .. }
1634            | Self::Glyph { .. }
1635            | Self::Blur { .. }
1636            | Self::Morphology { .. }
1637            | Self::RoundedRect { .. }
1638            | Self::RoundedRectBlur { .. }
1639            | Self::Ellipse { .. }
1640            | Self::Runtime { .. } => {
1641                unreachable!("handled above")
1642            }
1643            Self::LinearGradient {
1644                ramp,
1645                axis,
1646                to_local,
1647                tile,
1648                ..
1649            } => {
1650                out[layout::PARAMS] = stop_count_code(count, ramp);
1651                out[layout::PARAMS + 2] = tile_code(*tile);
1652                out[layout::GEOMETRY + 2] = axis[0];
1653                out[layout::GEOMETRY + 3] = axis[1];
1654                out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1655                out[layout::PARAMS + 1] = kind::LINEAR;
1656            }
1657            Self::RadialGradient {
1658                ramp,
1659                to_local,
1660                tile,
1661                ..
1662            } => {
1663                out[layout::PARAMS] = stop_count_code(count, ramp);
1664                out[layout::PARAMS + 2] = tile_code(*tile);
1665                out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1666                out[layout::PARAMS + 1] = kind::RADIAL;
1667            }
1668            Self::SweepGradient {
1669                ramp,
1670                to_local,
1671                start_angle,
1672                end_angle,
1673                tile,
1674                ..
1675            } => {
1676                out[layout::PARAMS] = stop_count_code(count, ramp);
1677                out[layout::PARAMS + 2] = tile_code(*tile);
1678                out[layout::GEOMETRY + 2] = *start_angle;
1679                out[layout::GEOMETRY + 3] = *end_angle;
1680                out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1681                out[layout::PARAMS + 1] = kind::SWEEP;
1682            }
1683            Self::ConicalGradient {
1684                ramp,
1685                to_local,
1686                start_radius,
1687                radius_delta,
1688                separation,
1689                tile,
1690                ..
1691            } => {
1692                out[layout::PARAMS] = stop_count_code(count, ramp);
1693                out[layout::PARAMS + 2] = tile_code(*tile);
1694                out[layout::GEOMETRY + 2] = *start_radius;
1695                out[layout::GEOMETRY + 3] = *radius_delta;
1696                out[layout::TO_LOCAL..layout::TO_LOCAL + 12].copy_from_slice(to_local);
1697                out[layout::PARAMS + 1] = kind::CONICAL;
1698                out[layout::PARAMS + 3] = *separation;
1699            }
1700        }
1701        out
1702    }
1703
1704    /// The caller's program this draws with, where it uses one.
1705    ///
1706    /// `None` is every material the built-in shader draws, which is all of
1707    /// them but one.
1708    pub fn program(&self) -> Option<u32> {
1709        match self {
1710            Self::Runtime { program, .. } => Some(*program),
1711            _ => None,
1712        }
1713    }
1714
1715    /// Which of the built-in shader's material arms this draws with.
1716    ///
1717    /// A pipeline is built with the arm its draws need and no other, so a
1718    /// driver compiles a fraction of the shader for each; see
1719    /// [`ShaderVariant`]. Exhaustive on purpose: a new material has to say
1720    /// where it is drawn, and the shader has to guard its arm by the same part.
1721    pub fn variant(&self) -> MaterialVariant {
1722        match self {
1723            Self::Solid(_)
1724            | Self::VertexGradient
1725            | Self::LinearGradient { .. }
1726            | Self::RadialGradient { .. }
1727            | Self::SweepGradient { .. }
1728            | Self::ConicalGradient { .. }
1729            | Self::Glyph { .. } => MaterialVariant::Core,
1730            Self::Image { .. } => MaterialVariant::Image,
1731            Self::Mesh { .. } => MaterialVariant::Mesh,
1732            Self::RoundedRect { .. }
1733            | Self::RoundedRectBlur { .. }
1734            | Self::Ellipse { .. }
1735            | Self::PointField { .. }
1736            | Self::ShadowMesh { .. } => MaterialVariant::Shape,
1737            Self::Blur { .. } | Self::Morphology { .. } => MaterialVariant::Pass,
1738            Self::Runtime { .. } => MaterialVariant::Runtime,
1739        }
1740    }
1741}
1742
1743/// Which arm of the built-in shader a material is drawn by.
1744#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1745pub enum MaterialVariant {
1746    /// A solid color, a gradient or a glyph: what every variant carries.
1747    Core,
1748    Image,
1749    Mesh,
1750    /// Rounded rectangles, ellipses, a rounded rectangle's blur, point fields
1751    /// and shadow meshes.
1752    Shape,
1753    /// A blur or a morphology pass.
1754    Pass,
1755    /// A caller's program, which replaces the built-in fragment stage.
1756    Runtime,
1757}
1758
1759/// The parts of the built-in shader one draw needs: its material's arm, and
1760/// whether it filters its color and blends its tint by a mode other than
1761/// `Modulate`.
1762///
1763/// A backend builds a pipeline per variant. The shader holding every part cost
1764/// seconds to compile on some drivers with their caches empty -- 1.8 on a
1765/// Raspberry Pi 5's V3D, about 5 on an RK3566's Mali-G52 -- and a frame of
1766/// solid colors, gradients and text needs a variant that compiles in tens of
1767/// milliseconds.
1768#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1769pub struct ShaderVariant {
1770    pub material: MaterialVariant,
1771    pub filters: bool,
1772    pub tint_blends: bool,
1773}
1774
1775impl ShaderVariant {
1776    /// A solid color, a gradient or a glyph, unfiltered and tinted by
1777    /// `Modulate`: what most of a frame draws with, and what a backend
1778    /// prepares ahead of the first frame.
1779    pub const CORE: ShaderVariant = ShaderVariant {
1780        material: MaterialVariant::Core,
1781        filters: false,
1782        tint_blends: false,
1783    };
1784}
1785
1786#[cfg(test)]
1787mod tests {
1788
1789    /// Each axis's mode where the shader reads it: an image's across in the
1790    /// last geometry float and down in the second, a mesh's in the second and
1791    /// third. The first is the batch's flag, and neither writes it.
1792    #[test]
1793    fn an_image_and_a_mesh_pack_a_tile_mode_per_axis() {
1794        let image = Material::Image {
1795            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1796            slot: 0,
1797            alpha: 0.5,
1798            tile: [TileMode::Repeat, TileMode::Decal],
1799            sampling: Sampling::Linear,
1800            source: [0.0, 0.0, 1.0, 1.0],
1801            tint: [1.0; 4],
1802        }
1803        .to_uniform();
1804        assert_eq!(
1805            &image[layout::GEOMETRY..layout::GEOMETRY + 4],
1806            &[0.0, tile::DECAL, 0.5, tile::REPEAT]
1807        );
1808
1809        let mesh = Material::Mesh {
1810            slot: 0,
1811            alpha: 0.5,
1812            tint: [1.0; 4],
1813            tile: [TileMode::Mirror, TileMode::Repeat],
1814            sampling: Sampling::Linear,
1815        }
1816        .to_uniform();
1817        assert_eq!(
1818            &mesh[layout::GEOMETRY..layout::GEOMETRY + 3],
1819            &[0.5, tile::MIRROR, tile::REPEAT]
1820        );
1821    }
1822
1823    /// The enum carries upstream's numbers; the shader keeps its own, and
1824    /// reordering the enum to the first left the second alone.
1825    #[test]
1826    fn tile_modes_are_upstreams_numbers_and_the_shader_keeps_its_own() {
1827        assert_eq!(
1828            [
1829                TileMode::Clamp,
1830                TileMode::Repeat,
1831                TileMode::Mirror,
1832                TileMode::Decal
1833            ]
1834            .map(|t| t as u8),
1835            [0, 1, 2, 3],
1836            "dart:ui TileMode.index and Impeller's Entity::TileMode"
1837        );
1838        assert_eq!(tile_code(TileMode::Clamp), tile::CLAMP);
1839        assert_eq!(tile_code(TileMode::Repeat), tile::REPEAT);
1840        assert_eq!(tile_code(TileMode::Mirror), 3.0);
1841        assert_eq!(tile_code(TileMode::Decal), 2.0);
1842    }
1843
1844    /// `VertexGradient` packs as the identity for the tint that colors it, and
1845    /// asks for a dither where `Solid` does not.
1846    #[test]
1847    fn a_vertex_gradient_packs_as_white_and_dithers() {
1848        let packed = Material::VertexGradient.to_uniform();
1849        assert_eq!(
1850            &packed[layout::STOPS..layout::STOPS + 4],
1851            &[1.0, 1.0, 1.0, 1.0],
1852            "opaque white is the identity for a `Modulate` tint"
1853        );
1854        assert_eq!(packed[layout::PARAMS + 1], kind::SOLID);
1855        assert_eq!(packed[layout::PARAMS], 1.0);
1856
1857        assert!(Material::VertexGradient.dithers());
1858        assert!(!Material::solid([1.0; 4]).dithers());
1859    }
1860
1861    /// And answers the rest of the predicates the way its shading does: no
1862    /// texture, no derivatives, and nothing knowable about its coverage.
1863    #[test]
1864    fn a_vertex_gradient_answers_the_other_predicates() {
1865        let m = Material::VertexGradient;
1866        assert!(!m.needs_screen_derivatives(), "a vertex color reads none");
1867        assert_eq!(m.sampling(), None);
1868        assert_eq!(m.texture_slot(), None);
1869        assert!(!m.is_invisible(), "the colors are on the vertices");
1870        assert!(
1871            !m.is_opaque(),
1872            "the vertex alphas are not visible from here"
1873        );
1874    }
1875    use super::*;
1876
1877    /// What a material can say about a texture read, and what it cannot.
1878    ///
1879    /// The second half is the point. A material has never seen the texture it
1880    /// names -- `Image::source` says so in as many words -- so it can report the
1881    /// filter that is bound and never whether that filter interpolates, which
1882    /// depends on the texture's size against the size it is drawn at. Only the
1883    /// two neighborhood filters escape that, because they step out by a sigma or
1884    /// a radius whatever the size is.
1885    #[test]
1886    fn a_material_reports_its_filter_and_not_what_the_filter_does() {
1887        let image = |sampling| Material::Image {
1888            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1889            slot: 3,
1890            alpha: 1.0,
1891            tile: [TileMode::Clamp; 2],
1892            sampling,
1893            source: [0.0, 0.0, 1.0, 1.0],
1894            tint: [1.0; 4],
1895        };
1896
1897        for sampling in [
1898            Sampling::Nearest,
1899            Sampling::Linear,
1900            Sampling::Cubic,
1901            Sampling::Mipmap,
1902        ] {
1903            assert_eq!(image(sampling).sampling(), Some(sampling));
1904            assert_eq!(image(sampling).texture_slot(), Some(3));
1905            // Even a linear one: whether it lands between texels is the
1906            // caller's geometry against a size this type does not hold.
1907            assert!(
1908                !image(sampling).reads_at_computed_offsets(),
1909                "an image is read where it is drawn, not at an offset of its own"
1910            );
1911        }
1912
1913        // The one case a material can settle by itself.
1914        let morphology = Material::Morphology {
1915            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1916            slot: 0,
1917            step: [1.0, 0.0],
1918            radius: 2.0,
1919            dilate: true,
1920        };
1921        assert_eq!(
1922            morphology.sampling(),
1923            None,
1924            "it carries no filter to report"
1925        );
1926        assert!(morphology.reads_at_computed_offsets());
1927
1928        // Reads a texture, states no filter, and walks nothing: the pair of
1929        // answers is why `sampling` returning `None` cannot be read as "no
1930        // texture".
1931        let glyph = Material::Glyph {
1932            color: [1.0; 4],
1933            slot: 1,
1934        };
1935        assert_eq!(glyph.sampling(), None);
1936        assert_eq!(glyph.texture_slot(), Some(1));
1937        assert!(!glyph.reads_at_computed_offsets());
1938
1939        // Reads nothing at all.
1940        let solid = Material::solid([1.0; 4]);
1941        assert_eq!(solid.sampling(), None);
1942        assert_eq!(solid.texture_slot(), None);
1943        assert!(!solid.reads_at_computed_offsets());
1944    }
1945
1946    /// A mapping with the given two-by-two linear part and no translation.
1947    ///
1948    /// Most of these tests care that the mapping survives packing, not what it
1949    /// is, and said so in four floats before the paint's origin moved inside
1950    /// it. This keeps them saying that.
1951    fn linear_to_local(m: [f32; 4]) -> ToLocal {
1952        [
1953            m[0], m[1], 0.0, 0.0, //
1954            m[2], m[3], 0.0, 0.0, //
1955            0.0, 0.0, 1.0, 0.0,
1956        ]
1957    }
1958
1959    fn two_stops() -> Vec<Stop> {
1960        vec![
1961            Stop::new([1.0, 0.0, 0.0, 1.0], 0.0),
1962            Stop::new([0.0, 0.0, 1.0, 1.0], 1.0),
1963        ]
1964    }
1965
1966    #[test]
1967    fn a_solid_color_lands_in_the_first_stop_and_selects_the_solid_path() {
1968        let packed = Material::solid([0.25, 0.5, 0.75, 1.0]).to_uniform();
1969        assert_eq!(&packed[0..4], &[0.25, 0.5, 0.75, 1.0]);
1970        assert_eq!(packed[layout::PARAMS], 1.0, "stop count");
1971        assert_eq!(packed[layout::PARAMS + 1], kind::SOLID);
1972    }
1973
1974    #[test]
1975    fn a_linear_gradient_packs_its_stops_axis_and_count() {
1976        let packed = Material::LinearGradient {
1977            axis: [2.0, 0.0],
1978            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
1979            stops: two_stops(),
1980            tile: TileMode::Clamp,
1981            ramp: None,
1982        }
1983        .to_uniform();
1984
1985        assert_eq!(&packed[0..4], &[1.0, 0.0, 0.0, 1.0], "first stop");
1986        assert_eq!(&packed[4..8], &[0.0, 0.0, 1.0, 1.0], "second stop");
1987        assert_eq!(packed[layout::OFFSETS], 0.0);
1988        assert_eq!(packed[layout::OFFSETS + 1], 1.0);
1989        assert_eq!(
1990            &packed[layout::GEOMETRY..layout::GEOMETRY + 4],
1991            &[0.0, 0.0, 2.0, 0.0],
1992            "the axis rather than the end point, and nothing in the half the \
1993             start used to occupy before it moved inside the mapping"
1994        );
1995        assert_eq!(
1996            &packed[layout::TO_LOCAL..layout::TO_LOCAL + 12],
1997            &linear_to_local([1.0, 0.0, 0.0, 1.0])
1998        );
1999        assert_eq!(packed[layout::PARAMS + 1], kind::LINEAR);
2000    }
2001
2002    #[test]
2003    fn a_radial_gradient_packs_its_mapping() {
2004        let packed = Material::RadialGradient {
2005            to_local: linear_to_local([2.0, 0.0, 0.0, 4.0]),
2006            stops: two_stops(),
2007            tile: TileMode::Clamp,
2008            ramp: None,
2009        }
2010        .to_uniform();
2011
2012        // A radial gradient states nothing in the geometry slot at all now: its
2013        // center rode there, and rides inside the mapping instead.
2014        assert_eq!(&packed[layout::GEOMETRY..layout::GEOMETRY + 2], &[0.0, 0.0]);
2015        // The mapping is what makes a circle circular on a non-square target,
2016        // so it has to survive packing intact.
2017        assert_eq!(
2018            &packed[layout::TO_LOCAL..layout::TO_LOCAL + 12],
2019            &linear_to_local([2.0, 0.0, 0.0, 4.0])
2020        );
2021        assert_eq!(packed[layout::PARAMS + 1], kind::RADIAL);
2022    }
2023
2024    #[test]
2025    fn a_sweep_gradient_packs_its_angles_alongside_its_center() {
2026        let packed = Material::SweepGradient {
2027            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2028            start_angle: 0.5,
2029            end_angle: 2.5,
2030            stops: two_stops(),
2031            tile: TileMode::Clamp,
2032            ramp: None,
2033        }
2034        .to_uniform();
2035
2036        // Angles share the geometry slot with the center, which is why a linear
2037        // gradient's endpoints and a sweep's angles cannot both be present.
2038        assert_eq!(
2039            &packed[layout::GEOMETRY..layout::GEOMETRY + 4],
2040            &[0.0, 0.0, 0.5, 2.5]
2041        );
2042        assert_eq!(packed[layout::PARAMS + 1], kind::SWEEP);
2043    }
2044
2045    #[test]
2046    fn every_gradient_kind_falls_back_to_solid_with_one_stop() {
2047        // Interpolating needs two points. Selecting a gradient path with one
2048        // would have the shader read an entry nothing wrote.
2049        let one = vec![Stop::new([1.0, 1.0, 1.0, 1.0], 0.0)];
2050        let materials = [
2051            Material::LinearGradient {
2052                axis: [1.0 - 0.0, 0.0 - 0.0],
2053                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2054                stops: one.clone(),
2055                tile: TileMode::Clamp,
2056                ramp: None,
2057            },
2058            Material::RadialGradient {
2059                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2060                stops: one.clone(),
2061                tile: TileMode::Clamp,
2062                ramp: None,
2063            },
2064            Material::SweepGradient {
2065                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2066                start_angle: 0.0,
2067                end_angle: 1.0,
2068                stops: one,
2069                tile: TileMode::Clamp,
2070                ramp: None,
2071            },
2072        ];
2073        for material in materials {
2074            let packed = material.to_uniform();
2075            assert_eq!(packed[layout::PARAMS + 1], kind::SOLID, "{material:?}");
2076            assert_eq!(&packed[0..4], &[1.0, 1.0, 1.0, 1.0]);
2077        }
2078    }
2079
2080    #[test]
2081    fn stops_beyond_the_limit_are_dropped_rather_than_overflowing() {
2082        let stops: Vec<Stop> = (0..8)
2083            .map(|i| Stop::new([i as f32 / 8.0, 0.0, 0.0, 1.0], i as f32 / 7.0))
2084            .collect();
2085        let packed = Material::LinearGradient {
2086            axis: [1.0 - 0.0, 0.0 - 0.0],
2087            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2088            stops,
2089            tile: TileMode::Clamp,
2090            ramp: None,
2091        }
2092        .to_uniform();
2093        // The count is what stops the shader reading past what was written.
2094        assert_eq!(packed[layout::PARAMS], MAX_STOPS as f32);
2095    }
2096
2097    #[test]
2098    fn visibility_accounts_for_every_stop_of_every_kind() {
2099        assert!(Material::solid([1.0, 1.0, 1.0, 0.0]).is_invisible());
2100        assert!(!Material::solid([0.0, 0.0, 0.0, 1.0]).is_invisible());
2101
2102        let clear = vec![
2103            Stop::new([1.0, 0.0, 0.0, 0.0], 0.0),
2104            Stop::new([0.0, 0.0, 1.0, 0.0], 1.0),
2105        ];
2106        assert!(Material::RadialGradient {
2107            to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2108            stops: clear,
2109            tile: TileMode::Clamp,
2110            ramp: None,
2111        }
2112        .is_invisible());
2113
2114        let partly = vec![
2115            Stop::new([1.0, 0.0, 0.0, 0.0], 0.0),
2116            Stop::new([0.0, 0.0, 1.0, 1.0], 1.0),
2117        ];
2118        assert!(
2119            !Material::SweepGradient {
2120                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2121                start_angle: 0.0,
2122                end_angle: 1.0,
2123                stops: partly,
2124                tile: TileMode::Clamp,
2125                ramp: None,
2126            }
2127            .is_invisible(),
2128            "one visible stop is enough"
2129        );
2130    }
2131
2132    #[test]
2133    fn a_solid_color_and_every_gradient_report_the_core_variant() {
2134        // They share the core of the shader, selected by a uniform, so keying
2135        // a pipeline on the kind would create identical pipelines.
2136        assert_eq!(Material::solid([0.0; 4]).variant(), MaterialVariant::Core);
2137        for material in [
2138            Material::LinearGradient {
2139                axis: [1.0, 0.0],
2140                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2141                stops: two_stops(),
2142                tile: TileMode::Clamp,
2143                ramp: None,
2144            },
2145            Material::RadialGradient {
2146                to_local: linear_to_local([1.0, 0.0, 0.0, 1.0]),
2147                stops: two_stops(),
2148                tile: TileMode::Clamp,
2149                ramp: None,
2150            },
2151        ] {
2152            assert_eq!(material.variant(), MaterialVariant::Core);
2153        }
2154    }
2155}