Skip to main content

emblema_hal/
blend.rs

1//! How a draw combines with what a target already holds.
2//!
3//! Two families live here, and they differ in kind rather than degree.
4//!
5//! The Porter-Duff modes decide *where* each side survives, and are expressible
6//! with fixed-function blend factors: they work on every device with no
7//! extension and no capability gate, which is why they came first. A renderer
8//! unable to composite without an extension would be unusable on the hardware
9//! least likely to have one.
10//!
11//! The separable modes — multiply, screen, overlay and the rest — mix the two
12//! sides *arithmetically*, channel by channel. No combination of blend factors
13//! expresses that, so they need an advanced-blend extension and are
14//! capability-gated. Their formulas are fixed by the specification, which is
15//! what makes them testable against a computed expectation rather than against
16//! a recorded picture.
17//!
18//! The non-separable modes — hue, saturation, color and luminosity — need the
19//! same extension and differ again in kind: each output channel depends on all
20//! three input channels, because they are stated in terms of a color's hue,
21//! saturation and luminosity rather than of its components. They are checked
22//! against what they are named for rather than against values: whether hue kept
23//! the backdrop's luminosity, whether saturation took the source's.
24//!
25//! Every mode assumes **premultiplied** color, which is what the render target
26//! holds. The factors differ from the straight-alpha forms: source-over is
27//! `ONE` rather than `SRC_ALPHA`, because the source has already been scaled.
28
29/// A factor a blend equation multiplies one side by.
30///
31/// Portable rather than each backend naming its own, so the Porter-Duff table
32/// below exists once instead of once per backend, where the two copies would
33/// drift.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum BlendFactor {
36    Zero,
37    One,
38    SrcAlpha,
39    OneMinusSrcAlpha,
40    DstAlpha,
41    OneMinusDstAlpha,
42    DstColor,
43}
44
45/// The factors for one blend mode.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct BlendFactors {
48    pub src: BlendFactor,
49    pub dst: BlendFactor,
50}
51
52impl BlendFactors {
53    const fn new(src: BlendFactor, dst: BlendFactor) -> Self {
54        Self { src, dst }
55    }
56}
57
58/// How a draw combines with what a target already holds.
59///
60/// Three families: the Porter-Duff set, which decides which of the source and
61/// destination survive and where; the separable modes, which mix the two
62/// arithmetically channel by channel; and the non-separable modes, which
63/// exchange whole attributes of a color. Only the first works everywhere.
64///
65/// Numbered as upstream numbers them: the discriminants are Impeller's
66/// `BlendMode` and `dart:ui`'s `BlendMode.index`, which agree with each other
67/// and with Skia's `SkBlendMode`. A caller holding one of those numbers --
68/// an embedder decoding a `Paint`, a port reading a serialized display list
69/// -- converts with a table it can check against this one rather than a
70/// match it has to keep in step by hand, and `as u8` gives the number back.
71///
72/// The number a shader reads is [`Self::code`], not this. The two are kept
73/// apart on purpose; see there.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
75#[repr(u8)]
76pub enum BlendMode {
77    /// Leave nothing behind. Neither source nor destination survives.
78    Clear = 0,
79    /// Replace the destination outright, alpha included.
80    ///
81    /// Not the same as [`Self::SrcOver`] with an opaque source: this overwrites
82    /// destination alpha too, which decides whether a layer composites
83    /// correctly when it is itself drawn onto something else.
84    Src = 1,
85    /// Keep the destination and discard the source.
86    Dst = 2,
87    /// Source over destination: the default for drawing one thing on another.
88    #[default]
89    SrcOver = 3,
90    /// Destination over source, as though the source were drawn underneath.
91    DstOver = 4,
92    /// Source, clipped to where the destination is.
93    SrcIn = 5,
94    /// Destination, clipped to where the source is.
95    DstIn = 6,
96    /// Source, clipped to where the destination is not.
97    SrcOut = 7,
98    /// Destination, clipped to where the source is not.
99    DstOut = 8,
100    /// Source drawn on top, but only within the destination's shape.
101    SrcATop = 9,
102    /// Destination drawn on top, but only within the source's shape.
103    DstATop = 10,
104    /// Whichever of the two is not overlapped by the other.
105    Xor = 11,
106    /// The two added together, saturating.
107    ///
108    /// Used for light accumulation, where overlapping contributions should
109    /// brighten rather than replace.
110    Plus = 12,
111    /// The two multiplied together.
112    Modulate = 13,
113
114    // Everything below mixes the two sides arithmetically and requires
115    // advanced blending. The formulas are the separable ones from the
116    // compositing specification, applied per channel to unpremultiplied color.
117    /// The inverse of multiplying the inverses, which always lightens.
118    Screen = 14,
119    /// Multiply or screen depending on the destination, so the destination
120    /// decides the contrast.
121    Overlay = 15,
122    /// The darker of the two, per channel.
123    Darken = 16,
124    /// The lighter of the two, per channel.
125    Lighten = 17,
126    /// Brighten the destination in proportion to the source.
127    ColorDodge = 18,
128    /// Darken the destination in proportion to the inverse of the source.
129    ColorBurn = 19,
130    /// Overlay with the roles reversed, so the source decides the contrast.
131    HardLight = 20,
132    /// A gentler hard-light, without the hard transition at the midpoint.
133    SoftLight = 21,
134    /// The absolute difference, which inverts where the two agree.
135    Difference = 22,
136    /// Like difference, but with a softer response near the midpoint.
137    Exclusion = 23,
138    /// Multiply the two, which always darkens.
139    ///
140    /// Last of the separable modes rather than first, because that is where
141    /// upstream numbers it (`impeller/geometry/color.h`).
142    Multiply = 24,
143
144    // Everything below is non-separable: each output channel depends on all
145    // three input channels, because these are stated in terms of a color's
146    // hue, saturation and luminosity rather than of its components.
147    /// The source's hue, with the backdrop's saturation and luminosity.
148    Hue = 25,
149    /// The source's saturation, with the backdrop's hue and luminosity.
150    Saturation = 26,
151    /// The source's hue and saturation, with the backdrop's luminosity.
152    Color = 27,
153    /// The source's luminosity, with the backdrop's hue and saturation.
154    Luminosity = 28,
155}
156
157impl BlendMode {
158    /// Whether this mode changes the destination where the source is absent.
159    ///
160    /// The modes for which "the source drew nothing here" is not the same as
161    /// "leave this pixel alone": `DstIn` zeroes what the source did not cover,
162    /// `Clear` zeroes everything, `Src` replaces it. A layer composited with
163    /// one of these has to cover everything it might affect rather than only
164    /// what it drew, so it is the test for whether a layer's target may be
165    /// narrowed to its content.
166    ///
167    /// The same nine upstream lists in `Entity::IsBlendModeDestructive`, and
168    /// the reason to match it exactly is that this decides a target's size:
169    /// a mode missing here is a layer that silently stops masking what it
170    /// used to.
171    pub fn is_destructive(self) -> bool {
172        matches!(
173            self,
174            Self::Clear
175                | Self::Src
176                | Self::SrcIn
177                | Self::DstIn
178                | Self::SrcOut
179                | Self::DstOut
180                | Self::DstATop
181                | Self::Xor
182                | Self::Modulate
183        )
184    }
185
186    /// The modes every device can do, with no extension.
187    pub const PORTER_DUFF: &'static [Self] = &[
188        Self::Clear,
189        Self::Src,
190        Self::Dst,
191        Self::SrcOver,
192        Self::DstOver,
193        Self::SrcIn,
194        Self::DstIn,
195        Self::SrcOut,
196        Self::DstOut,
197        Self::SrcATop,
198        Self::DstATop,
199        Self::Xor,
200        Self::Plus,
201        Self::Modulate,
202    ];
203
204    /// The modes that need advanced blending.
205    pub const ADVANCED: &'static [Self] = &[
206        Self::Screen,
207        Self::Overlay,
208        Self::Darken,
209        Self::Lighten,
210        Self::ColorDodge,
211        Self::ColorBurn,
212        Self::HardLight,
213        Self::SoftLight,
214        Self::Difference,
215        Self::Exclusion,
216        Self::Multiply,
217        Self::Hue,
218        Self::Saturation,
219        Self::Color,
220        Self::Luminosity,
221    ];
222
223    /// Every mode, for exhaustive tests and reporting.
224    ///
225    /// Deliberately *not* what a backend iterates to decide what it supports —
226    /// that is what [`Self::is_advanced`] and the capability flag are for.
227    pub const ALL: &'static [Self] = &[
228        Self::Clear,
229        Self::Src,
230        Self::Dst,
231        Self::SrcOver,
232        Self::DstOver,
233        Self::SrcIn,
234        Self::DstIn,
235        Self::SrcOut,
236        Self::DstOut,
237        Self::SrcATop,
238        Self::DstATop,
239        Self::Xor,
240        Self::Plus,
241        Self::Modulate,
242        Self::Screen,
243        Self::Overlay,
244        Self::Darken,
245        Self::Lighten,
246        Self::ColorDodge,
247        Self::ColorBurn,
248        Self::HardLight,
249        Self::SoftLight,
250        Self::Difference,
251        Self::Exclusion,
252        Self::Multiply,
253        Self::Hue,
254        Self::Saturation,
255        Self::Color,
256        Self::Luminosity,
257    ];
258
259    /// The number a shader reads to identify this mode.
260    ///
261    /// Spelled out rather than cast from the discriminant, because this number
262    /// is written into a uniform buffer that a shader decodes, and the two
263    /// must agree where only one of them is visible from the shader. It is
264    /// emblema's own numbering and predates the upstream discriminants: it
265    /// still counts `Multiply` as 14, which moving the variant did not change
266    /// and does not need to.
267    pub const fn code(self) -> f32 {
268        match self {
269            Self::Clear => 0.0,
270            Self::Src => 1.0,
271            Self::Dst => 2.0,
272            Self::SrcOver => 3.0,
273            Self::DstOver => 4.0,
274            Self::SrcIn => 5.0,
275            Self::DstIn => 6.0,
276            Self::SrcOut => 7.0,
277            Self::DstOut => 8.0,
278            Self::SrcATop => 9.0,
279            Self::DstATop => 10.0,
280            Self::Xor => 11.0,
281            Self::Plus => 12.0,
282            Self::Modulate => 13.0,
283            Self::Multiply => 14.0,
284            Self::Screen => 15.0,
285            Self::Overlay => 16.0,
286            Self::Darken => 17.0,
287            Self::Lighten => 18.0,
288            Self::ColorDodge => 19.0,
289            Self::ColorBurn => 20.0,
290            Self::HardLight => 21.0,
291            Self::SoftLight => 22.0,
292            Self::Difference => 23.0,
293            Self::Exclusion => 24.0,
294            Self::Hue => 25.0,
295            Self::Saturation => 26.0,
296            Self::Color => 27.0,
297            Self::Luminosity => 28.0,
298        }
299    }
300
301    /// Whether this mode needs advanced blending.
302    ///
303    /// Callers check [`crate::Capabilities::advanced_blend`] before using one, and a
304    /// backend without it refuses rather than substituting something that looks
305    /// close: a silently wrong blend mode is a picture nobody can debug from.
306    pub const fn is_advanced(self) -> bool {
307        !matches!(
308            self,
309            Self::Clear
310                | Self::Src
311                | Self::Dst
312                | Self::SrcOver
313                | Self::DstOver
314                | Self::SrcIn
315                | Self::DstIn
316                | Self::SrcOut
317                | Self::DstOut
318                | Self::SrcATop
319                | Self::DstATop
320                | Self::Xor
321                | Self::Plus
322                | Self::Modulate
323        )
324    }
325
326    /// The factors this mode blends with, assuming premultiplied color.
327    ///
328    /// `None` for an advanced mode: those are not expressible as factors at
329    /// all, which is exactly why they need an extension. Returning an
330    /// option rather than a plausible pair keeps a backend from silently
331    /// rendering the wrong thing.
332    pub const fn factors(self) -> Option<BlendFactors> {
333        use BlendFactor::*;
334        Some(match self {
335            Self::Clear => BlendFactors::new(Zero, Zero),
336            Self::Src => BlendFactors::new(One, Zero),
337            Self::Dst => BlendFactors::new(Zero, One),
338            Self::SrcOver => BlendFactors::new(One, OneMinusSrcAlpha),
339            Self::DstOver => BlendFactors::new(OneMinusDstAlpha, One),
340            Self::SrcIn => BlendFactors::new(DstAlpha, Zero),
341            Self::DstIn => BlendFactors::new(Zero, SrcAlpha),
342            Self::SrcOut => BlendFactors::new(OneMinusDstAlpha, Zero),
343            Self::DstOut => BlendFactors::new(Zero, OneMinusSrcAlpha),
344            Self::SrcATop => BlendFactors::new(DstAlpha, OneMinusSrcAlpha),
345            Self::DstATop => BlendFactors::new(OneMinusDstAlpha, SrcAlpha),
346            Self::Xor => BlendFactors::new(OneMinusDstAlpha, OneMinusSrcAlpha),
347            Self::Plus => BlendFactors::new(One, One),
348            Self::Modulate => BlendFactors::new(DstColor, Zero),
349            _ => return None,
350        })
351    }
352
353    /// Whether the destination contributes to the result.
354    ///
355    /// A mode that ignores it can skip loading the target on a tiler, which is
356    /// a bandwidth saving rather than a correctness one.
357    pub const fn reads_destination(self) -> bool {
358        match self.factors() {
359            Some(factors) => {
360                !matches!(factors.dst, BlendFactor::Zero)
361                    || matches!(
362                        factors.src,
363                        BlendFactor::DstAlpha
364                            | BlendFactor::OneMinusDstAlpha
365                            | BlendFactor::DstColor
366                    )
367            }
368            // Every advanced mode is a function of both sides by definition.
369            None => true,
370        }
371    }
372
373    /// Whether a source scaled by coverage composites as though the shape were
374    /// partly there.
375    ///
376    /// This is what decides whether a shape may be antialiased by computing
377    /// coverage in the fragment stage rather than by multisampling. Such a
378    /// shape is drawn on a quad larger than itself and emits a fragment
379    /// everywhere on it, including where coverage is nothing — so the mode has
380    /// to leave the destination alone for a fully transparent source, or the
381    /// quad erases what is behind it in the gap between the two.
382    ///
383    /// Which is exactly the destination factor being `One` or
384    /// `OneMinusSrcAlpha`: the source term vanishes with the alpha whatever its
385    /// own factor is, so only the destination's own weight is left. Every
386    /// advanced mode qualifies as well — their equations carry a
387    /// `(1 - source alpha)` on the destination by construction, and reduce to
388    /// it when the source contributes nothing.
389    ///
390    /// The same condition happens to be what makes the partly covered edge
391    /// correct rather than merely harmless. Weighting a premultiplied source by
392    /// coverage and compositing gives the same answer as mixing the unweighted
393    /// result into the destination by coverage, which is what multisampling
394    /// would have produced.
395    pub const fn respects_coverage(self) -> bool {
396        match self.factors() {
397            Some(factors) => matches!(
398                factors.dst,
399                BlendFactor::One | BlendFactor::OneMinusSrcAlpha
400            ),
401            None => true,
402        }
403    }
404
405    /// Whether this simply writes the source, so blending can be switched off.
406    pub const fn is_plain_write(self) -> bool {
407        matches!(self, Self::Src)
408    }
409
410    pub const fn name(self) -> &'static str {
411        match self {
412            Self::Clear => "clear",
413            Self::Src => "src",
414            Self::Dst => "dst",
415            Self::SrcOver => "src-over",
416            Self::DstOver => "dst-over",
417            Self::SrcIn => "src-in",
418            Self::DstIn => "dst-in",
419            Self::SrcOut => "src-out",
420            Self::DstOut => "dst-out",
421            Self::SrcATop => "src-atop",
422            Self::DstATop => "dst-atop",
423            Self::Xor => "xor",
424            Self::Plus => "plus",
425            Self::Modulate => "modulate",
426            Self::Multiply => "multiply",
427            Self::Screen => "screen",
428            Self::Overlay => "overlay",
429            Self::Darken => "darken",
430            Self::Lighten => "lighten",
431            Self::ColorDodge => "color-dodge",
432            Self::ColorBurn => "color-burn",
433            Self::HardLight => "hard-light",
434            Self::SoftLight => "soft-light",
435            Self::Difference => "difference",
436            Self::Exclusion => "exclusion",
437            Self::Hue => "hue",
438            Self::Saturation => "saturation",
439            Self::Color => "color",
440            Self::Luminosity => "luminosity",
441        }
442    }
443}
444
445impl std::fmt::Display for BlendMode {
446    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
447        f.write_str(self.name())
448    }
449}
450
451/// The separable blend function `B(Cb, Cs)`, on one unpremultiplied channel.
452///
453/// This is the compositing specification's definition transcribed directly.
454/// It exists so there is exactly one statement of what each mode means: the
455/// conformance tests check the hardware against it, and any future software
456/// path evaluates it. Nothing here is a second implementation of the backend
457/// mapping — that maps an enum to an extension's blend op and shares no code
458/// with this, which is what makes checking one against the other meaningful.
459///
460/// Returns `None` for a mode that is not separable-advanced.
461pub fn separable_blend(mode: BlendMode, backdrop: f32, source: f32) -> Option<f32> {
462    let (cb, cs) = (backdrop, source);
463    let multiply = |a: f32, b: f32| a * b;
464    let screen = |a: f32, b: f32| a + b - a * b;
465    // Hard-light is its own function *and* the body of overlay with the two
466    // sides exchanged, so it is written once and called twice.
467    let hard_light = |cb: f32, cs: f32| {
468        if cs <= 0.5 {
469            multiply(cb, 2.0 * cs)
470        } else {
471            screen(cb, 2.0 * cs - 1.0)
472        }
473    };
474    Some(match mode {
475        BlendMode::Multiply => multiply(cb, cs),
476        BlendMode::Screen => screen(cb, cs),
477        BlendMode::Overlay => hard_light(cs, cb),
478        BlendMode::Darken => cb.min(cs),
479        BlendMode::Lighten => cb.max(cs),
480        BlendMode::ColorDodge => {
481            // The order of these three cases is load-bearing: a black backdrop
482            // stays black even under a full-strength source, and only then does
483            // a full-strength source saturate. Swapping them makes the corner
484            // where both hold produce white instead of black.
485            if cb <= 0.0 {
486                0.0
487            } else if cs >= 1.0 {
488                1.0
489            } else {
490                (cb / (1.0 - cs)).min(1.0)
491            }
492        }
493        BlendMode::ColorBurn => {
494            if cb >= 1.0 {
495                1.0
496            } else if cs <= 0.0 {
497                0.0
498            } else {
499                1.0 - ((1.0 - cb) / cs).min(1.0)
500            }
501        }
502        BlendMode::HardLight => hard_light(cb, cs),
503        BlendMode::SoftLight => {
504            if cs <= 0.5 {
505                cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
506            } else {
507                // The specification's D(Cb): a cubic below a quarter, a square
508                // root above it, chosen so the two meet with equal slope.
509                let d = if cb <= 0.25 {
510                    ((16.0 * cb - 12.0) * cb + 4.0) * cb
511                } else {
512                    cb.sqrt()
513                };
514                cb + (2.0 * cs - 1.0) * (d - cb)
515            }
516        }
517        BlendMode::Difference => (cs - cb).abs(),
518        BlendMode::Exclusion => cs + cb - 2.0 * cs * cb,
519        _ => return None,
520    })
521}
522
523/// The non-separable blend function, on unpremultiplied color.
524///
525/// These are stated in terms of a color's luminosity and saturation rather than
526/// of its components, so each output channel depends on all three inputs — the
527/// reason they cannot go through [`separable_blend`] and the reason they are a
528/// separate family rather than four more entries in the same table.
529///
530/// The helpers below are the specification's, transcribed directly. The one
531/// that repays reading is the clip: setting a luminosity can push a channel
532/// outside zero to one, and clipping each channel independently would change
533/// the hue that the whole operation exists to preserve. Scaling the color
534/// toward its own luminosity instead brings it back into range along a line
535/// that holds hue fixed.
536///
537/// Returns `None` for a mode that is not non-separable-advanced.
538pub fn nonseparable_blend(
539    mode: BlendMode,
540    backdrop: [f32; 3],
541    source: [f32; 3],
542) -> Option<[f32; 3]> {
543    // The specification's coefficients, which weight green far above blue
544    // because the eye does. Not the same as any of the standard luma matrices,
545    // and deliberately so: this is what the compositing specification says.
546    fn lum(c: [f32; 3]) -> f32 {
547        0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
548    }
549
550    fn clip_color(mut c: [f32; 3]) -> [f32; 3] {
551        let l = lum(c);
552        let n = c[0].min(c[1]).min(c[2]);
553        let x = c[0].max(c[1]).max(c[2]);
554        if n < 0.0 {
555            // Guarded because a color whose luminosity equals its darkest
556            // channel is already flat, and the scale would divide by zero.
557            let span = l - n;
558            if span > 0.0 {
559                for channel in &mut c {
560                    *channel = l + (*channel - l) * l / span;
561                }
562            }
563        }
564        if x > 1.0 {
565            let span = x - l;
566            if span > 0.0 {
567                for channel in &mut c {
568                    *channel = l + (*channel - l) * (1.0 - l) / span;
569                }
570            }
571        }
572        c
573    }
574
575    fn set_lum(mut c: [f32; 3], l: f32) -> [f32; 3] {
576        let d = l - lum(c);
577        for channel in &mut c {
578            *channel += d;
579        }
580        clip_color(c)
581    }
582
583    fn sat(c: [f32; 3]) -> f32 {
584        c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
585    }
586
587    /// Rescale a color to a given saturation, keeping which channel is which.
588    ///
589    /// Written by index rather than by sorting the components, because the
590    /// result has to go back where it came from: the middle channel of the
591    /// input stays the middle channel of the output.
592    fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
593        let mut order = [0usize, 1, 2];
594        order.sort_by(|a, b| {
595            c[*a]
596                .partial_cmp(&c[*b])
597                .unwrap_or(std::cmp::Ordering::Equal)
598        });
599        let (low, mid, high) = (order[0], order[1], order[2]);
600        let mut out = [0.0f32; 3];
601        if c[high] > c[low] {
602            out[mid] = (c[mid] - c[low]) * s / (c[high] - c[low]);
603            out[high] = s;
604        }
605        // A flat color has no saturation to scale, so it stays flat at zero
606        // rather than being given one arbitrarily.
607        out[low] = 0.0;
608        out
609    }
610
611    let (cb, cs) = (backdrop, source);
612    Some(match mode {
613        BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
614        BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
615        BlendMode::Color => set_lum(cs, lum(cb)),
616        BlendMode::Luminosity => set_lum(cb, lum(cs)),
617        _ => return None,
618    })
619}
620
621/// An advanced mode applied to premultiplied colors, giving premultiplied color.
622///
623/// The blend function itself is defined on unpremultiplied channels, so this
624/// un-premultiplies, blends, and recombines using the specification's
625/// composite: the blended color applies only where the two sides overlap, and
626/// each side survives alone where the other is absent.
627pub fn blend_advanced(mode: BlendMode, source: [f32; 4], backdrop: [f32; 4]) -> Option<[f32; 4]> {
628    let (a_s, a_b) = (source[3], backdrop[3]);
629    let mut out = [0.0f32; 4];
630    out[3] = a_s + a_b - a_s * a_b;
631
632    // Dividing by a zero alpha would give a NaN that then propagates through a
633    // term the same alpha multiplies away, so the color under a fully
634    // transparent side is taken as zero rather than computed.
635    //
636    // Clamped for a second reason, stated separately because it is a different
637    // one: the formulas below are defined on channels between zero and one and
638    // not outside, so a component describing a color the sRGB primaries cannot
639    // hold has to be brought to the triangle's edge before a mode is evaluated.
640    // The shader states the same domain at the same place, because these two
641    // exist to be checked against each other and a domain named in one and not
642    // the other is how they begin to disagree.
643    let straight = |c: [f32; 4], a: f32| {
644        if a > 0.0 {
645            [
646                (c[0] / a).clamp(0.0, 1.0),
647                (c[1] / a).clamp(0.0, 1.0),
648                (c[2] / a).clamp(0.0, 1.0),
649            ]
650        } else {
651            [0.0; 3]
652        }
653    };
654    let cs = straight(source, a_s);
655    let cb = straight(backdrop, a_b);
656
657    // The whole-color family first. A non-separable mode has no per-channel
658    // form, and trying the separable table first would have it fall through to
659    // a `None` that reads as "not an advanced mode at all".
660    let blended = match nonseparable_blend(mode, cb, cs) {
661        Some(blended) => blended,
662        None => {
663            let mut per_channel = [0.0f32; 3];
664            for (channel, slot) in per_channel.iter_mut().enumerate() {
665                *slot = separable_blend(mode, cb[channel], cs[channel])?;
666            }
667            per_channel
668        }
669    };
670
671    for channel in 0..3 {
672        out[channel] = a_s * (1.0 - a_b) * cs[channel]
673            + a_s * a_b * blended[channel]
674            + (1.0 - a_s) * a_b * cb[channel];
675    }
676    Some(out)
677}
678
679#[cfg(test)]
680mod coverage_tests {
681    use super::*;
682
683    #[test]
684    fn a_mode_respects_coverage_when_a_transparent_source_changes_nothing() {
685        // Worked out from the factors rather than listed, so a mode added later
686        // is classified rather than forgotten. These are the answers that
687        // classification has to produce.
688        for mode in [
689            BlendMode::SrcOver,
690            BlendMode::DstOver,
691            BlendMode::Dst,
692            BlendMode::Plus,
693            BlendMode::Xor,
694            BlendMode::SrcATop,
695            BlendMode::DstOut,
696        ] {
697            assert!(mode.respects_coverage(), "{} should", mode.name());
698        }
699        // These discard the destination where the source is transparent, so a
700        // quad larger than its shape would erase what is behind it.
701        for mode in [
702            BlendMode::Clear,
703            BlendMode::Src,
704            BlendMode::SrcIn,
705            BlendMode::DstIn,
706            BlendMode::SrcOut,
707            BlendMode::DstATop,
708            BlendMode::Modulate,
709        ] {
710            assert!(!mode.respects_coverage(), "{} should not", mode.name());
711        }
712    }
713
714    #[test]
715    fn every_advanced_mode_respects_coverage() {
716        // Their equations carry a (1 - source alpha) on the destination by
717        // construction, so a transparent source leaves it whole.
718        for mode in BlendMode::ALL {
719            if mode.is_advanced() {
720                assert!(mode.respects_coverage(), "{} should", mode.name());
721            }
722        }
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729
730    /// Evaluate a factor against premultiplied source and destination.
731    fn value(factor: BlendFactor, src: [f32; 4], dst: [f32; 4], channel: usize) -> f32 {
732        match factor {
733            BlendFactor::Zero => 0.0,
734            BlendFactor::One => 1.0,
735            BlendFactor::SrcAlpha => src[3],
736            BlendFactor::OneMinusSrcAlpha => 1.0 - src[3],
737            BlendFactor::DstAlpha => dst[3],
738            BlendFactor::OneMinusDstAlpha => 1.0 - dst[3],
739            BlendFactor::DstColor => dst[channel],
740        }
741    }
742
743    /// The blend equation, as the hardware applies it.
744    fn blend(mode: BlendMode, src: [f32; 4], dst: [f32; 4]) -> [f32; 4] {
745        let f = mode.factors().expect("Porter-Duff mode");
746        let mut out = [0.0f32; 4];
747        for channel in 0..4 {
748            out[channel] = (src[channel] * value(f.src, src, dst, channel)
749                + dst[channel] * value(f.dst, src, dst, channel))
750            .clamp(0.0, 1.0);
751        }
752        out
753    }
754
755    fn close(a: [f32; 4], b: [f32; 4]) -> bool {
756        a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-5)
757    }
758
759    // Premultiplied half-opaque red and opaque blue.
760    const SRC: [f32; 4] = [0.5, 0.0, 0.0, 0.5];
761    const DST: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
762
763    #[test]
764    fn clear_leaves_nothing() {
765        assert!(close(blend(BlendMode::Clear, SRC, DST), [0.0; 4]));
766    }
767
768    #[test]
769    fn src_and_dst_each_keep_one_side_entirely() {
770        assert!(close(blend(BlendMode::Src, SRC, DST), SRC));
771        assert!(close(blend(BlendMode::Dst, SRC, DST), DST));
772    }
773
774    #[test]
775    fn source_over_and_destination_over_are_mirror_images() {
776        // Half-opaque red over opaque blue: half the blue survives.
777        assert!(close(
778            blend(BlendMode::SrcOver, SRC, DST),
779            [0.5, 0.0, 0.5, 1.0]
780        ));
781        // The other way round, the destination is opaque so nothing shows
782        // through and the source is entirely hidden.
783        assert!(close(blend(BlendMode::DstOver, SRC, DST), DST));
784    }
785
786    #[test]
787    fn the_in_modes_clip_one_side_to_the_other() {
788        // Source clipped to an opaque destination is the source unchanged.
789        assert!(close(blend(BlendMode::SrcIn, SRC, DST), SRC));
790        // Destination clipped to a half-opaque source keeps half of it.
791        assert!(close(
792            blend(BlendMode::DstIn, SRC, DST),
793            [0.0, 0.0, 0.5, 0.5]
794        ));
795    }
796
797    #[test]
798    fn the_out_modes_are_the_complement_of_the_in_modes() {
799        // The destination is opaque, so there is nowhere the source is outside
800        // it: source-out leaves nothing.
801        assert!(close(blend(BlendMode::SrcOut, SRC, DST), [0.0; 4]));
802        // Half the destination lies outside a half-opaque source.
803        assert!(close(
804            blend(BlendMode::DstOut, SRC, DST),
805            [0.0, 0.0, 0.5, 0.5]
806        ));
807    }
808
809    #[test]
810    fn atop_keeps_the_shape_of_the_side_it_is_named_for() {
811        // Source atop destination has the destination's shape: alpha stays at
812        // the destination's, which is what distinguishes it from source-over.
813        let result = blend(BlendMode::SrcATop, SRC, DST);
814        assert!((result[3] - DST[3]).abs() < 1e-5, "alpha should follow dst");
815        assert!(close(result, [0.5, 0.0, 0.5, 1.0]));
816    }
817
818    #[test]
819    fn xor_keeps_only_what_the_other_side_does_not_cover() {
820        // An opaque destination covers everything, so only the part of the
821        // destination outside the half-opaque source survives.
822        assert!(close(blend(BlendMode::Xor, SRC, DST), [0.0, 0.0, 0.5, 0.5]));
823    }
824
825    #[test]
826    fn plus_accumulates_and_saturates() {
827        let sum = blend(BlendMode::Plus, SRC, DST);
828        assert!(close(sum, [0.5, 0.0, 1.0, 1.0]));
829        // Saturating rather than wrapping: two bright sources must not go dark.
830        let bright = blend(BlendMode::Plus, [0.8, 0.8, 0.8, 1.0], [0.8, 0.8, 0.8, 1.0]);
831        assert!(close(bright, [1.0, 1.0, 1.0, 1.0]));
832    }
833
834    #[test]
835    fn modulate_multiplies_the_two() {
836        let result = blend(
837            BlendMode::Modulate,
838            [0.5, 1.0, 0.5, 1.0],
839            [0.5, 0.5, 1.0, 1.0],
840        );
841        assert!(close(result, [0.25, 0.5, 0.5, 1.0]));
842    }
843
844    #[test]
845    fn only_src_can_skip_blending_entirely() {
846        // Everything else needs the hardware to combine two sides, so treating
847        // another mode as a plain write would silently drop the destination.
848        for mode in BlendMode::PORTER_DUFF {
849            assert_eq!(
850                mode.is_plain_write(),
851                *mode == BlendMode::Src,
852                "{mode} misreported whether it is a plain write"
853            );
854        }
855    }
856
857    #[test]
858    fn modes_that_ignore_the_destination_are_identified() {
859        // A mode that never reads the target can skip loading it on a tiler.
860        for mode in [BlendMode::Clear, BlendMode::Src] {
861            assert!(!mode.reads_destination(), "{mode}");
862        }
863        for mode in [
864            BlendMode::SrcOver,
865            BlendMode::DstOver,
866            BlendMode::SrcIn,
867            BlendMode::Modulate,
868            BlendMode::Xor,
869        ] {
870            assert!(mode.reads_destination(), "{mode}");
871        }
872    }
873
874    #[test]
875    fn the_separable_modes_hit_their_defining_fixed_points() {
876        // Each identity below is what the mode is *for*, so getting one wrong
877        // means the transcription is wrong regardless of what the hardware does.
878        let cases: &[(BlendMode, f32, f32, f32)] = &[
879            (BlendMode::Multiply, 0.5, 0.5, 0.25),
880            (BlendMode::Screen, 0.5, 0.5, 0.75),
881            (BlendMode::Darken, 0.2, 0.8, 0.2),
882            (BlendMode::Lighten, 0.2, 0.8, 0.8),
883            (BlendMode::Difference, 0.2, 0.8, 0.6),
884            (BlendMode::Exclusion, 0.5, 0.5, 0.5),
885            // Half-strength hard-light and overlay are both the identity on the
886            // side that decides the contrast.
887            (BlendMode::HardLight, 0.3, 0.5, 0.3),
888            (BlendMode::Overlay, 0.5, 0.3, 0.3),
889            // Half-strength soft-light leaves the backdrop untouched.
890            (BlendMode::SoftLight, 0.3, 0.5, 0.3),
891            // The dodge and burn corners, where the ordering of the guards shows.
892            (BlendMode::ColorDodge, 0.0, 1.0, 0.0),
893            (BlendMode::ColorDodge, 0.25, 0.5, 0.5),
894            (BlendMode::ColorBurn, 1.0, 0.0, 1.0),
895            (BlendMode::ColorBurn, 0.5, 0.5, 0.0),
896        ];
897        for &(mode, cb, cs, want) in cases {
898            let got = separable_blend(mode, cb, cs).expect("separable");
899            assert!(
900                (got - want).abs() < 1e-6,
901                "{mode}(backdrop {cb}, source {cs}) gave {got}, want {want}"
902            );
903        }
904    }
905
906    #[test]
907    fn soft_light_is_continuous_where_its_two_branches_meet() {
908        // The branches join at a source of one half and at a backdrop of one
909        // quarter; a transcription error in either shows as a step.
910        for &(cb, cs) in &[(0.25, 0.5), (0.2499, 0.75), (0.5, 0.4999)] {
911            let here = separable_blend(BlendMode::SoftLight, cb, cs).unwrap();
912            let there = separable_blend(BlendMode::SoftLight, cb + 2e-4, cs + 2e-4).unwrap();
913            assert!((here - there).abs() < 1e-3, "step at ({cb}, {cs})");
914        }
915    }
916
917    #[test]
918    fn an_advanced_mode_over_nothing_is_just_the_source() {
919        // Where the backdrop is absent the blend function has nothing to mix
920        // with, so every mode must reduce to the source unchanged.
921        let src = [0.3, 0.0, 0.15, 0.6];
922        for mode in BlendMode::ADVANCED {
923            let out = blend_advanced(*mode, src, [0.0; 4]).expect("advanced");
924            assert!(close(out, src), "{mode} over nothing gave {out:?}");
925        }
926    }
927
928    #[test]
929    fn the_non_separable_modes_take_what_they_are_named_for() {
930        // Each of these is defined as taking some attributes from one side and
931        // the rest from the other, so the check is which side each attribute
932        // came from rather than a value someone recorded.
933        fn lum(c: [f32; 3]) -> f32 {
934            0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
935        }
936        fn sat(c: [f32; 3]) -> f32 {
937            c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
938        }
939
940        // Two requirements on these inputs, and both were found by getting them
941        // wrong. They must differ in luminosity and in saturation, or two of
942        // these four modes look identical — the first pair tried here agreed on
943        // luminosity exactly, by coincidence. And the results must stay inside
944        // zero to one, because the clip that brings an out-of-range color back
945        // reduces its saturation; that is correct behavior and would make the
946        // exact assertions below wrong, so the clip has a test of its own.
947        let cb = [0.15, 0.55, 0.35];
948        let cs = [0.75, 0.5, 0.45];
949        assert!((lum(cb) - lum(cs)).abs() > 0.05);
950        assert!((sat(cb) - sat(cs)).abs() > 0.05);
951
952        let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
953
954        let hue = nonseparable_blend(BlendMode::Hue, cb, cs).unwrap();
955        assert!(close(lum(hue), lum(cb)), "hue kept the wrong luminosity");
956        assert!(close(sat(hue), sat(cb)), "hue kept the wrong saturation");
957
958        let saturation = nonseparable_blend(BlendMode::Saturation, cb, cs).unwrap();
959        assert!(
960            close(lum(saturation), lum(cb)),
961            "saturation moved luminosity"
962        );
963        assert!(
964            close(sat(saturation), sat(cs)),
965            "saturation did not take the source's"
966        );
967
968        let color = nonseparable_blend(BlendMode::Color, cb, cs).unwrap();
969        assert!(close(lum(color), lum(cb)), "color moved luminosity");
970
971        let luminosity = nonseparable_blend(BlendMode::Luminosity, cb, cs).unwrap();
972        assert!(
973            close(lum(luminosity), lum(cs)),
974            "luminosity did not take the source's"
975        );
976        assert!(
977            close(sat(luminosity), sat(cb)),
978            "luminosity moved saturation"
979        );
980    }
981
982    #[test]
983    fn setting_a_luminosity_keeps_every_channel_in_range() {
984        // Shifting a color's luminosity pushes channels outside zero to one,
985        // and clipping each independently would change the hue the operation
986        // exists to preserve. Scaling toward the luminosity is what brings them
987        // back along a line that holds hue fixed -- so this checks the range
988        // and, separately, that the result is still a scaling of the original.
989        for (cb, cs) in [
990            ([0.02, 0.02, 0.9], [0.99, 0.99, 0.99]),
991            ([0.99, 0.5, 0.02], [0.01, 0.01, 0.01]),
992            ([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]),
993            ([1.0, 1.0, 1.0], [0.0, 0.0, 0.0]),
994        ] {
995            for mode in [BlendMode::Color, BlendMode::Luminosity, BlendMode::Hue] {
996                let out = nonseparable_blend(mode, cb, cs).unwrap();
997                for channel in out {
998                    assert!(
999                        (-1e-5..=1.0 + 1e-5).contains(&channel),
1000                        "{mode} on {cb:?} and {cs:?} gave {out:?}"
1001                    );
1002                    assert!(channel.is_finite(), "{mode} produced {out:?}");
1003                }
1004            }
1005        }
1006    }
1007
1008    #[test]
1009    fn a_flat_backdrop_has_no_saturation_to_take() {
1010        // A gray has no hue and no saturation, so a mode asking for either gets
1011        // a gray back. The guard that makes this work is also the one that
1012        // stops a division by zero, which is why it is worth pinning.
1013        let gray = [0.4, 0.4, 0.4];
1014        let colorful = [0.9, 0.2, 0.5];
1015        let hue = nonseparable_blend(BlendMode::Hue, gray, colorful).unwrap();
1016        assert!(
1017            hue.iter().all(|c| (c - hue[0]).abs() < 1e-5),
1018            "hue from a gray backdrop came back colored: {hue:?}"
1019        );
1020        let saturation = nonseparable_blend(BlendMode::Saturation, gray, colorful).unwrap();
1021        assert!(
1022            saturation.iter().all(|c| (c - saturation[0]).abs() < 1e-5),
1023            "saturating a gray produced color from nothing: {saturation:?}"
1024        );
1025    }
1026
1027    #[test]
1028    fn the_two_families_do_not_overlap() {
1029        // Every mode belongs to exactly one family, and the family it claims
1030        // agrees with whether it has factors.
1031        assert_eq!(
1032            BlendMode::PORTER_DUFF.len() + BlendMode::ADVANCED.len(),
1033            BlendMode::ALL.len()
1034        );
1035        for mode in BlendMode::ALL {
1036            assert_eq!(
1037                mode.is_advanced(),
1038                mode.factors().is_none(),
1039                "{mode} disagrees with itself about which family it is in"
1040            );
1041            let has_formula = separable_blend(*mode, 0.5, 0.5).is_some()
1042                || nonseparable_blend(*mode, [0.5; 3], [0.5; 3]).is_some();
1043            assert_eq!(
1044                mode.is_advanced(),
1045                has_formula,
1046                "{mode} has no advanced formula but claims to be advanced"
1047            );
1048            // And never both, since the two families are evaluated differently
1049            // and a mode in both would take whichever path was tried first.
1050            assert!(
1051                !(separable_blend(*mode, 0.5, 0.5).is_some()
1052                    && nonseparable_blend(*mode, [0.5; 3], [0.5; 3]).is_some()),
1053                "{mode} has a formula in both families"
1054            );
1055        }
1056    }
1057
1058    #[test]
1059    fn discriminants_are_upstreams_numbers() {
1060        // ALL is in declaration order, so its index is the discriminant.
1061        for (i, mode) in BlendMode::ALL.iter().enumerate() {
1062            assert_eq!(*mode as usize, i, "{mode} is out of place in ALL");
1063        }
1064        // Spot checks against Impeller's BlendMode (impeller/geometry/color.h)
1065        // and dart:ui's BlendMode.index, which share these numbers.
1066        assert_eq!(BlendMode::SrcOver as u8, 3);
1067        assert_eq!(BlendMode::Modulate as u8, 13);
1068        assert_eq!(BlendMode::Screen as u8, 14);
1069        assert_eq!(BlendMode::Exclusion as u8, 23);
1070        assert_eq!(BlendMode::Multiply as u8, 24);
1071        assert_eq!(BlendMode::Luminosity as u8, 28);
1072        assert_eq!(BlendMode::ALL.len(), 29);
1073    }
1074
1075    #[test]
1076    fn every_mode_has_a_distinct_name() {
1077        let mut names: Vec<&str> = BlendMode::ALL.iter().map(|m| m.name()).collect();
1078        names.sort_unstable();
1079        let count = names.len();
1080        names.dedup();
1081        assert_eq!(names.len(), count, "duplicate blend mode name");
1082    }
1083}