alpha-blend 0.3.0

Alpha blending and compositing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Separable blend modes ("mixing functions") from the W3C spec.
//!
//! A [`BlendMode`] decides *how* the source and backdrop colors are mixed. A
//! [`CompositeMode`](crate::CompositeMode) decides *how much* each contributes. The two are
//! orthogonal and are combined by [`Composite`](crate::Composite).
//!
//! All twelve separable modes from [W3C Compositing and Blending Level 1] are implemented. A
//! mode is *separable* when it can be evaluated one channel at a time, which is what lets
//! [`BlendMode::mix`] have the signature it does. The four non-separable modes (`Hue`,
//! `Saturation`, `Color`, `Luminosity`) operate on the whole RGB triple at once and are not
//! implemented.
//!
//! Every mode is generic over [`Channel`], so `u8` gets an exact integer implementation rather
//! than a detour through `f32`.
//!
//! [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending

use crate::channel::Channel;

/// A separable blend mode as defined by the [W3C Compositing and Blending Level 1] spec.
///
/// Each variant is a per-channel mixing function `B(Cb, Cs)` where `Cb` is the backdrop
/// (destination) channel and `Cs` is the source channel. Use [`BlendMode::mix`] to evaluate a
/// single channel, or combine with a [`CompositeMode`](crate::CompositeMode) via
/// [`Composite`](crate::Composite) to blend two full RGBA colors.
///
/// The formulas below are written in normalized `0..=1` terms, matching the spec. See
/// [`Channel`] for how that maps onto `u8`.
///
/// [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BlendMode {
    /// `Cs`
    ///
    /// The source is used unchanged. This is the default, and is what plain Porter-Duff
    /// compositing does.
    #[default]
    Normal,

    /// `Cb * Cs`
    ///
    /// Always results in a color at least as dark as either input. The complement of
    /// [`Screen`](BlendMode::Screen).
    Multiply,

    /// `Cb + Cs - Cb * Cs`
    ///
    /// The complement of multiplying the complements of the backdrop and source; always
    /// results in a color at least as light as either input.
    Screen,

    /// Multiplies or screens the colors, depending on the backdrop.
    ///
    /// Equivalent to `HardLight(Cs, Cb)`:
    ///
    /// ```text
    /// if Cb <= 0.5 { 2 * Cb * Cs }
    /// else { 1 - 2 * (1 - Cb) * (1 - Cs) }
    /// ```
    Overlay,

    /// `min(Cb, Cs)`
    Darken,

    /// `max(Cb, Cs)`
    Lighten,

    /// Brightens the backdrop to reflect the source.
    ///
    /// ```text
    /// if Cb == 0 { 0 }
    /// else if Cs == 1 { 1 }
    /// else { min(1, Cb / (1 - Cs)) }
    /// ```
    ColorDodge,

    /// Darkens the backdrop to reflect the source.
    ///
    /// ```text
    /// if Cb == 1 { 1 }
    /// else if Cs == 0 { 0 }
    /// else { 1 - min(1, (1 - Cb) / Cs) }
    /// ```
    ColorBurn,

    /// Multiplies or screens the colors, depending on the source.
    ///
    /// Equivalent to `Overlay(Cs, Cb)`:
    ///
    /// ```text
    /// if Cs <= 0.5 { Multiply(Cb, 2 * Cs) }
    /// else { Screen(Cb, 2 * Cs - 1) }
    /// ```
    HardLight,

    /// Darkens or lightens the colors, depending on the source.
    ///
    /// A softer [`HardLight`](BlendMode::HardLight); the result of shining a diffused
    /// spotlight on the backdrop.
    ///
    /// ```text
    /// if Cs <= 0.5 { Cb - (1 - 2 * Cs) * Cb * (1 - Cb) }
    /// else { Cb + (2 * Cs - 1) * (D(Cb) - Cb) }
    ///
    /// D(Cb) = ((16 * Cb - 12) * Cb + 4) * Cb   if Cb <= 0.25
    ///         sqrt(Cb)                         otherwise
    /// ```
    SoftLight,

    /// `|Cb - Cs|`
    Difference,

    /// `Cb + Cs - 2 * Cb * Cs`
    ///
    /// Like [`Difference`](BlendMode::Difference), but lower in contrast.
    Exclusion,
}

impl BlendMode {
    /// Every separable blend mode, in spec order.
    ///
    /// Useful for exhaustive tests and for rendering swatches. Because [`BlendMode`] is
    /// `#[non_exhaustive]`, this array may grow in a minor release.
    pub const ALL: [Self; 12] = [
        Self::Normal,
        Self::Multiply,
        Self::Screen,
        Self::Overlay,
        Self::Darken,
        Self::Lighten,
        Self::ColorDodge,
        Self::ColorBurn,
        Self::HardLight,
        Self::SoftLight,
        Self::Difference,
        Self::Exclusion,
    ];

    /// Evaluates this blend mode's per-channel mixing function `B(Cb, Cs)`.
    ///
    /// `cb` is the backdrop (destination) channel and `cs` is the source channel.
    ///
    /// ```rust
    /// use alpha_blend::BlendMode;
    ///
    /// // Integer and float channels are the same function at different precisions.
    /// assert_eq!(BlendMode::Multiply.mix(128u8, 255u8), 128);
    /// assert_eq!(BlendMode::Multiply.mix(0.5f32, 1.0f32), 0.5);
    /// ```
    #[must_use]
    pub fn mix<C: Channel>(self, cb: C, cs: C) -> C {
        match self {
            Self::Normal => cs,
            Self::Multiply => cb.scale(cs),
            // 1 - (1 - Cb)(1 - Cs), which avoids the subtraction underflowing an integer
            // channel and is exact at both endpoints.
            Self::Screen => cb.complement().scale(cs.complement()).complement(),
            // The spec defines Overlay as HardLight with the operands swapped.
            Self::Overlay => Self::HardLight.mix(cs, cb),
            Self::Darken => cb.min_channel(cs),
            Self::Lighten => cb.max_channel(cs),
            Self::ColorDodge => {
                if cb.is_zero() {
                    C::ZERO
                } else if cs.is_one() {
                    C::ONE
                } else {
                    cb.div_normalized(cs.complement())
                }
            }
            Self::ColorBurn => {
                if cb.is_one() {
                    C::ONE
                } else if cs.is_zero() {
                    C::ZERO
                } else {
                    cb.complement().div_normalized(cs).complement()
                }
            }
            Self::HardLight => {
                if cs <= C::HALF {
                    // 2 * Cs cannot overflow on this side of the branch.
                    Self::Multiply.mix(cb, cs.saturating_add(cs))
                } else {
                    Self::Screen.mix(cb, cs.double_minus_one())
                }
            }
            Self::SoftLight => soft_light(cb, cs),
            Self::Difference => cb.abs_diff(cs),
            // Cb + Cs - 2*Cb*Cs, factored as Cb(1 - Cs) + Cs(1 - Cb). Algebraically identical,
            // but the factored form never exceeds 1 partway through, so no intermediate
            // saturates, and integer channels round once instead of three times.
            Self::Exclusion => C::sum_of_products(cb, cs.complement(), cs, cb.complement()),
        }
    }
}

/// The W3C `SoftLight` mixing function, split out to keep [`BlendMode::mix`] readable.
fn soft_light<C: Channel>(cb: C, cs: C) -> C {
    if cs <= C::HALF {
        // Cb - (1 - 2 * Cs) * Cb * (1 - Cb). 2 * Cs cannot overflow on this side.
        let factor = cs.saturating_add(cs).complement();
        cb.saturating_sub(factor.scale(cb).scale(cb.complement()))
    } else {
        // Cb + (2 * Cs - 1) * (D(Cb) - Cb). D(Cb) >= Cb for all Cb, but integer rounding can
        // make them equal, so the saturating subtraction is doing real work here.
        let d = cb.soft_light_d();
        cb.saturating_add(cs.double_minus_one().scale(d.saturating_sub(cb)))
    }
}

#[cfg(test)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::float_cmp,
    clippy::suboptimal_flops
)]
mod tests {
    use super::*;

    /// Evaluates a blend mode in `f64` straight from the spec text. Independent of the
    /// implementation, including of [`Channel`].
    ///
    /// Deliberately transcribed literally, so `suboptimal_flops` is off: an oracle that has
    /// been algebraically rearranged for speed is no longer an independent check.
    #[allow(clippy::match_same_arms, clippy::suboptimal_flops)]
    fn spec_reference(mode: BlendMode, cb: f64, cs: f64) -> f64 {
        fn screen(cb: f64, cs: f64) -> f64 {
            cb + cs - cb * cs
        }
        fn hard_light(cb: f64, cs: f64) -> f64 {
            if cs <= 0.5 {
                cb * (2.0 * cs)
            } else {
                screen(cb, 2.0 * cs - 1.0)
            }
        }
        match mode {
            BlendMode::Normal => cs,
            BlendMode::Multiply => cb * cs,
            BlendMode::Screen => screen(cb, cs),
            BlendMode::Overlay => hard_light(cs, cb),
            BlendMode::Darken => cb.min(cs),
            BlendMode::Lighten => cb.max(cs),
            BlendMode::ColorDodge => {
                if cb == 0.0 {
                    0.0
                } else if cs == 1.0 {
                    1.0
                } else {
                    (cb / (1.0 - cs)).min(1.0)
                }
            }
            BlendMode::ColorBurn => {
                if cb == 1.0 {
                    1.0
                } else if cs == 0.0 {
                    0.0
                } else {
                    1.0 - ((1.0 - cb) / cs).min(1.0)
                }
            }
            BlendMode::HardLight => hard_light(cb, cs),
            BlendMode::SoftLight => {
                let d = if cb <= 0.25 {
                    ((16.0 * cb - 12.0) * cb + 4.0) * cb
                } else {
                    cb.sqrt()
                };
                if cs <= 0.5 {
                    cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
                } else {
                    cb + (2.0 * cs - 1.0) * (d - cb)
                }
            }
            BlendMode::Difference => (cb - cs).abs(),
            BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,
        }
    }

    #[test]
    fn all_contains_every_variant_once() {
        for (i, a) in BlendMode::ALL.iter().enumerate() {
            for b in &BlendMode::ALL[i + 1..] {
                assert_ne!(a, b, "duplicate in ALL");
            }
        }
    }

    #[test]
    fn default_is_normal() {
        assert_eq!(BlendMode::default(), BlendMode::Normal);
    }

    /// Every mode, every channel type, against the spec written out in `f64`.
    #[test]
    fn f32_matches_spec() {
        for mode in BlendMode::ALL {
            for cb in 0..=64u8 {
                for cs in 0..=64u8 {
                    let (cb, cs) = (f32::from(cb) / 64.0, f32::from(cs) / 64.0);
                    let got = mode.mix(cb, cs);
                    let want = spec_reference(mode, f64::from(cb), f64::from(cs));
                    assert!(
                        (f64::from(got) - want).abs() < 1e-6,
                        "{mode:?}(cb={cb}, cs={cs}): got {got}, want {want}",
                    );
                }
            }
        }
    }

    /// The integer path must land within one LSB of the spec for every one of the 65536
    /// `(cb, cs)` pairs, for all twelve modes.
    #[test]
    fn u8_matches_spec_within_one_lsb() {
        for mode in BlendMode::ALL {
            let mut worst = 0u8;
            for cb in 0..=255u8 {
                for cs in 0..=255u8 {
                    let got = mode.mix(cb, cs);
                    let want = spec_reference(mode, f64::from(cb) / 255.0, f64::from(cs) / 255.0);
                    let want = (want.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
                    let delta = got.abs_diff(want);
                    assert!(
                        delta <= 1,
                        "{mode:?}(cb={cb}, cs={cs}): got {got}, want {want}",
                    );
                    worst = worst.max(delta);
                }
            }
            // Only the three modes that divide or take a square root are allowed to be
            // inexact. If a mode moves out of this set, an exact formula was replaced with an
            // approximate one.
            let may_be_inexact = matches!(
                mode,
                BlendMode::ColorDodge | BlendMode::ColorBurn | BlendMode::SoftLight
            );
            assert!(
                worst == 0 || may_be_inexact,
                "{mode:?} became inexact (worst {worst})",
            );
        }
    }

    /// `Normal` is the identity that makes `Composite` reduce to plain Porter-Duff.
    #[test]
    fn normal_returns_the_source() {
        for cb in 0..=255u8 {
            for cs in 0..=255u8 {
                assert_eq!(BlendMode::Normal.mix(cb, cs), cs);
            }
        }
    }

    /// Multiply and Screen are complements of each other, exactly, at every integer input.
    #[test]
    fn multiply_and_screen_are_complements() {
        for cb in 0..=255u8 {
            for cs in 0..=255u8 {
                let multiply = BlendMode::Multiply.mix(cb, cs);
                let screen = BlendMode::Screen.mix(cb.complement(), cs.complement());
                assert_eq!(multiply, screen.complement(), "cb={cb} cs={cs}");
            }
        }
    }

    /// `Overlay` is `HardLight` with the operands swapped, by definition. Must hold bit for bit.
    #[test]
    fn overlay_is_hard_light_swapped() {
        for cb in 0..=255u8 {
            for cs in 0..=255u8 {
                assert_eq!(
                    BlendMode::Overlay.mix(cb, cs),
                    BlendMode::HardLight.mix(cs, cb),
                    "cb={cb} cs={cs}",
                );
            }
        }
    }

    /// White and black are the fixed points every artist expects.
    #[test]
    fn identity_elements() {
        for cb in 0..=255u8 {
            assert_eq!(BlendMode::Multiply.mix(cb, 255), cb, "multiply by white");
            assert_eq!(BlendMode::Multiply.mix(cb, 0), 0, "multiply by black");
            assert_eq!(BlendMode::Screen.mix(cb, 0), cb, "screen with black");
            assert_eq!(BlendMode::Screen.mix(cb, 255), 255, "screen with white");
            assert_eq!(BlendMode::Difference.mix(cb, 0), cb);
            assert_eq!(BlendMode::Exclusion.mix(cb, 0), cb);
            assert_eq!(BlendMode::Darken.mix(cb, 255), cb);
            assert_eq!(BlendMode::Lighten.mix(cb, 0), cb);
            assert_eq!(
                BlendMode::SoftLight.mix(cb, 127),
                cb,
                "soft light is neutral at 0.5"
            );
        }
    }

    /// Repeatedly multiplying by white must not drift. This is the invariant retroglyph's
    /// `Tint` was hand-rolling its own rounding to preserve.
    #[test]
    fn multiply_by_white_never_drifts() {
        let mut v = 200u8;
        for _ in 0..1000 {
            v = BlendMode::Multiply.mix(v, 255);
        }
        assert_eq!(v, 200);
    }

    #[test]
    fn dodge_and_burn_edge_cases() {
        assert_eq!(BlendMode::ColorDodge.mix(0u8, 128), 0, "Cb == 0 wins");
        assert_eq!(
            BlendMode::ColorDodge.mix(0u8, 255),
            0,
            "Cb == 0 beats Cs == 1"
        );
        assert_eq!(BlendMode::ColorDodge.mix(128u8, 255), 255);
        assert_eq!(BlendMode::ColorDodge.mix(128u8, 128), 255, "saturates");
        assert_eq!(BlendMode::ColorBurn.mix(255u8, 128), 255, "Cb == 1 wins");
        assert_eq!(
            BlendMode::ColorBurn.mix(255u8, 0),
            255,
            "Cb == 1 beats Cs == 0"
        );
        assert_eq!(BlendMode::ColorBurn.mix(128u8, 0), 0);
        // 128/255 is 0.502, not 0.5, so the exact answer is 2/255 rather than 0.
        assert_eq!(BlendMode::ColorBurn.mix(128u8, 128), 2);
    }

    #[test]
    fn hard_light_boundary() {
        // 127 is the last value on the multiply side; 128 is the first on the screen side.
        assert_eq!(BlendMode::HardLight.mix(200u8, 127), 200u8.scale(254));
        assert_eq!(
            BlendMode::HardLight.mix(200u8, 128),
            BlendMode::Screen.mix(200, 1),
        );
    }

    /// Regression: computing `2 * Cs - 1` by doubling first saturates the intermediate at
    /// `ONE` and throws the value away, so every `Cs > 0.5` collapsed to `Screen(Cb, 0)`.
    #[test]
    fn hard_light_upper_half_does_not_saturate_away() {
        assert_eq!(BlendMode::HardLight.mix(0u8, 129), 3);
        assert_eq!(BlendMode::HardLight.mix(0u8, 255), 255);
        assert_eq!(BlendMode::Overlay.mix(129u8, 0), 3);
        for cs in 128..=255u8 {
            assert_eq!(
                BlendMode::HardLight.mix(0, cs),
                cs.double_minus_one(),
                "Screen with a black backdrop is the identity; cs={cs}",
            );
        }
    }

    #[test]
    fn soft_light_is_bounded_by_the_backdrop_direction() {
        // Below 0.5 soft light darkens, above 0.5 it lightens, always.
        for cb in 1..255u8 {
            for cs in 0..=127u8 {
                assert!(BlendMode::SoftLight.mix(cb, cs) <= cb, "cb={cb} cs={cs}");
            }
            for cs in 127..=255u8 {
                assert!(BlendMode::SoftLight.mix(cb, cs) >= cb, "cb={cb} cs={cs}");
            }
        }
    }

    #[test]
    fn saturating_modes_never_wrap() {
        // Exclusion and Difference are the two that subtract; make sure neither underflows.
        for cb in 0..=255u8 {
            for cs in 0..=255u8 {
                let _ = BlendMode::Exclusion.mix(cb, cs);
                let _ = BlendMode::Difference.mix(cb, cs);
            }
        }
        assert_eq!(BlendMode::Exclusion.mix(255u8, 255), 0);
        assert_eq!(BlendMode::Difference.mix(255u8, 255), 0);
        assert_eq!(BlendMode::Difference.mix(0u8, 255), 255);
        // Regression: `Cb + Cs` saturates at ONE before the `2 * Cb * Cs` term is subtracted,
        // so the naive form loses everything above the clamp.
        assert_eq!(BlendMode::Exclusion.mix(4u8, 255), 251);
        assert_eq!(BlendMode::Exclusion.mix(255u8, 4), 251);
    }
}