alpha-blend 0.3.0

Alpha blending and compositing
Documentation
//! Compositing operators built from Porter-Duff coefficients.
//!
//! A [`CompositeMode`] decides *how much* the source and destination contribute to the result.
//! A [`BlendMode`](crate::BlendMode) decides *how* their colors are mixed. The two are
//! orthogonal and are combined by [`Composite`](crate::Composite).
//!
//! Each operator is a pair of coefficients `(Fa, Fb)` chosen from
//! `{0, 1, as, ab, 1 - as, 1 - ab}`, applied as:
//!
//! ```text
//! co = as * Fa * Cs + ab * Fb * Cb      (premultiplied)
//! ao = as * Fa + ab * Fb
//! ```
//!
//! See [Alpha compositing] for the derivation.
//!
//! [Alpha compositing]: https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending

use crate::channel::Channel;

/// A Porter-Duff coefficient pair.
///
/// Returned by [`CompositeMode::coefficients`]. `src` is `Fa` and `dst` is `Fb`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Coefficients<C> {
    /// The source coefficient, `Fa`.
    pub src: C,

    /// The destination coefficient, `Fb`.
    pub dst: C,
}

/// How much the source and destination each contribute to a composite.
///
/// All operators assume **straight alpha** inputs. See [`Composite`](crate::Composite) to
/// combine one of these with a [`BlendMode`](crate::BlendMode), or use a `CompositeMode`
/// directly as an [`RgbaBlend`](crate::RgbaBlend) to composite with
/// [`BlendMode::Normal`](crate::BlendMode::Normal).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CompositeMode {
    /// Neither the source nor the destination is used; the result is transparent.
    Clear,

    /// Source pixels replace the destination.
    Source,

    /// Destination pixels are kept and the source is discarded.
    Destination,

    /// Source pixels are placed over the destination.
    #[default]
    SourceOver,

    /// Destination pixels are placed over the source.
    DestinationOver,

    /// Source pixels are kept only where the destination is opaque.
    SourceIn,

    /// Destination pixels are kept only where the source is opaque.
    DestinationIn,

    /// Source pixels are kept only where the destination is transparent.
    SourceOut,

    /// Destination pixels are kept only where the source is transparent.
    DestinationOut,

    /// Source pixels are placed over the destination, clipped to the destination's shape.
    SourceAtop,

    /// Destination pixels are placed over the source, clipped to the source's shape.
    DestinationAtop,

    /// Only the non-overlapping regions of the source and destination are kept.
    Xor,

    /// Source and destination are added together.
    ///
    /// Saturates at [`Channel::ONE`] rather than overflowing. Before 0.3.0 the `f32` path could
    /// return channels above `1.0` and required a manual
    /// [`clamp`](crate::rgba::F32x4Rgba::clamp).
    Plus,
}

impl CompositeMode {
    /// Every compositing operator, in Porter-Duff order.
    ///
    /// Because [`CompositeMode`] is `#[non_exhaustive]`, this array may grow in a minor
    /// release.
    pub const ALL: [Self; 13] = [
        Self::Clear,
        Self::Source,
        Self::Destination,
        Self::SourceOver,
        Self::DestinationOver,
        Self::SourceIn,
        Self::DestinationIn,
        Self::SourceOut,
        Self::DestinationOut,
        Self::SourceAtop,
        Self::DestinationAtop,
        Self::Xor,
        Self::Plus,
    ];

    /// Returns this operator's `(Fa, Fb)` coefficients for the given straight alphas.
    ///
    /// ```rust
    /// use alpha_blend::{CompositeMode, porter_duff::Coefficients};
    ///
    /// // SourceOver keeps all of the source and (1 - src_a) of the destination.
    /// let c = CompositeMode::SourceOver.coefficients(128u8, 255u8);
    /// assert_eq!(c, Coefficients { src: 255, dst: 127 });
    /// ```
    #[must_use]
    pub fn coefficients<C: Channel>(self, src_a: C, dst_a: C) -> Coefficients<C> {
        let (src, dst) = match self {
            Self::Clear => (C::ZERO, C::ZERO),
            Self::Source => (C::ONE, C::ZERO),
            Self::Destination => (C::ZERO, C::ONE),
            Self::SourceOver => (C::ONE, src_a.complement()),
            Self::DestinationOver => (dst_a.complement(), C::ONE),
            Self::SourceIn => (dst_a, C::ZERO),
            Self::DestinationIn => (C::ZERO, src_a),
            Self::SourceOut => (dst_a.complement(), C::ZERO),
            Self::DestinationOut => (C::ZERO, src_a.complement()),
            Self::SourceAtop => (dst_a, src_a.complement()),
            Self::DestinationAtop => (dst_a.complement(), src_a),
            Self::Xor => (dst_a.complement(), src_a.complement()),
            Self::Plus => (C::ONE, C::ONE),
        };
        Coefficients { src, dst }
    }
}

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

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

    #[test]
    fn default_is_source_over() {
        assert_eq!(CompositeMode::default(), CompositeMode::SourceOver);
    }

    /// The canonical Porter-Duff table, transcribed independently of the implementation.
    #[test]
    fn coefficients_match_the_porter_duff_table() {
        let (sa, da) = (0.25f32, 0.75f32);
        let cases: &[(CompositeMode, f32, f32)] = &[
            (CompositeMode::Clear, 0.0, 0.0),
            (CompositeMode::Source, 1.0, 0.0),
            (CompositeMode::Destination, 0.0, 1.0),
            (CompositeMode::SourceOver, 1.0, 1.0 - 0.25),
            (CompositeMode::DestinationOver, 1.0 - 0.75, 1.0),
            (CompositeMode::SourceIn, 0.75, 0.0),
            (CompositeMode::DestinationIn, 0.0, 0.25),
            (CompositeMode::SourceOut, 1.0 - 0.75, 0.0),
            (CompositeMode::DestinationOut, 0.0, 1.0 - 0.25),
            (CompositeMode::SourceAtop, 0.75, 1.0 - 0.25),
            (CompositeMode::DestinationAtop, 1.0 - 0.75, 0.25),
            (CompositeMode::Xor, 1.0 - 0.75, 1.0 - 0.25),
            (CompositeMode::Plus, 1.0, 1.0),
        ];
        assert_eq!(cases.len(), CompositeMode::ALL.len(), "table is complete");
        for &(mode, fa, fb) in cases {
            let got = mode.coefficients(sa, da);
            assert_eq!(got.src, fa, "{mode:?} Fa");
            assert_eq!(got.dst, fb, "{mode:?} Fb");
        }
    }

    /// Integer and float coefficients must describe the same operator.
    #[test]
    fn u8_and_f32_coefficients_agree() {
        for mode in CompositeMode::ALL {
            for sa in (0..=255u8).step_by(15) {
                for da in (0..=255u8).step_by(15) {
                    let int = mode.coefficients(sa, da);
                    let flt = mode.coefficients(sa.to_f32(), da.to_f32());
                    assert!((int.src.to_f32() - flt.src).abs() < 1e-6, "{mode:?} Fa");
                    assert!((int.dst.to_f32() - flt.dst).abs() < 1e-6, "{mode:?} Fb");
                }
            }
        }
    }

    /// `Source` and `Destination` are mirror images, as are the `In`/`Out`/`Atop` pairs.
    #[test]
    fn operators_come_in_mirrored_pairs() {
        let (sa, da) = (0.25f32, 0.75f32);
        let pairs = [
            (CompositeMode::Source, CompositeMode::Destination),
            (CompositeMode::SourceOver, CompositeMode::DestinationOver),
            (CompositeMode::SourceIn, CompositeMode::DestinationIn),
            (CompositeMode::SourceOut, CompositeMode::DestinationOut),
            (CompositeMode::SourceAtop, CompositeMode::DestinationAtop),
        ];
        for (a, b) in pairs {
            let forward = a.coefficients(sa, da);
            // Swapping the roles of source and destination swaps the coefficients.
            let mirrored = b.coefficients(da, sa);
            assert_eq!(forward.src, mirrored.dst, "{a:?} vs {b:?}");
            assert_eq!(forward.dst, mirrored.src, "{a:?} vs {b:?}");
        }
    }
}