Skip to main content

alpha_blend/
lib.rs

1//! Alpha blending and compositing in (optionally) zero-dependency Rust.
2//!
3//! All blending operations assume **straight (un-premultiplied) alpha** unless
4//! documented otherwise.  For premultiplied conversions see
5//! [`crate::rgba::F32x4Rgba::premultiply`] and [`crate::rgba::F32x4Rgba::unpremultiply`].
6//!
7//! ## Examples
8//!
9//! The [`RgbaBlend`] trait defines a method for blending two RGBA colors together, and the
10//! [`BlendMode`] enum provides various blending modes based on Porter-Duff coefficients; for
11//! example [`BlendMode::SourceOver`] blends the source color over the destination color using
12//! [`PorterDuff::SRC_OVER`][].
13//!
14//! [`PorterDuff::SRC_OVER`]: `crate::porter_duff::PorterDuff::SRC_OVER`
15//!
16//! ```rust
17//! use alpha_blend::{rgba::F32x4Rgba, BlendMode, RgbaBlend};
18//!
19//! let src = F32x4Rgba { r: 1.0, g: 0.0, b: 0.0, a: 0.5 }; // Semi-transparent red
20//! let dst = F32x4Rgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; // Opaque blue
21//! let blended = BlendMode::SourceOver.apply(src, dst);
22//!
23//! // A mixed color of red and blue with alpha blending
24//! assert_eq!(blended, F32x4Rgba { r: 0.5, g: 0.0, b: 0.5, a: 0.75 });
25//! ```
26//!
27//! ## Features
28//!
29//! By default, this crate is `no_std` compatible, and uses [`libm`] for some math operations.
30//!
31//! Either `std` or `libm` must be enabled.
32//!
33//! ### `bytemuck`
34//!
35//! Enables the `bytemuck` crate for zero-copy conversions between types.
36//!
37//! ### `libm`
38//!
39//! _This feature is enabled by default._
40//!
41//! Uses the `libm` crate for math operations.
42//!
43//! ### `libm-arch`
44//!
45//! _This feature is enabled by default._
46//!
47//! Enables the `arch` feature of `libm`.
48//!
49//! ### `std`
50//!
51//! Uses the standard library for math operations, such as `f32::round`.
52
53#![cfg_attr(not(feature = "std"), no_std)]
54
55use crate::{porter_duff::PorterDuff, rgba::Rgba};
56
57pub mod blend_modes;
58pub(crate) mod math;
59pub mod porter_duff;
60pub mod rgba;
61pub(crate) mod vec4;
62
63/// Supported blend modes by this crate.
64///
65/// All modes operate in **straight alpha**.  See
66/// [`F32x4Rgba::premultiply`](crate::rgba::F32x4Rgba::premultiply) for premultiplied support.
67///
68/// ## Overflow
69///
70/// [`Plus`](BlendMode::Plus) can produce channel values > 1.0.  Call
71/// [`clamp()`](crate::rgba::F32x4Rgba::clamp) on the result when using `Plus`.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
73pub enum BlendMode {
74    /// Destination pixels covered by the source pixels are cleared.
75    Clear,
76
77    /// Source pixels are copied to the destination.
78    Source,
79
80    /// Destination pixels are copied to the source.
81    Destination,
82
83    /// Source pixels are copied to the destination, ignoring the alpha channel.
84    #[default]
85    SourceOver,
86
87    /// Destination pixels are copied to the source, ignoring the alpha channel.
88    DestinationOver,
89
90    /// Source pixels are copied to the destination, only where the destination is opaque.
91    SourceIn,
92
93    /// Destination pixels are copied to the source, only where the source is opaque.
94    DestinationIn,
95
96    /// Source pixels are copied to the destination, only where the source is opaque.
97    SourceOut,
98
99    /// Destination pixels are copied to the source, only where the destination is opaque.
100    DestinationOut,
101
102    /// Source pixels are copied to the destination, where both source and destination are opaque.
103    SourceAtop,
104
105    /// Destination pixels are copied to the source, where both source and destination are opaque.
106    DestinationAtop,
107
108    /// Source pixels are blended with the destination using the source's alpha channel.
109    Xor,
110
111    /// Source pixels are added to the destination.
112    ///
113    /// **Note**: can produce channel values > 1.0.  Call
114    /// [`clamp()`](crate::rgba::F32x4Rgba::clamp) on the result when clamping is needed.
115    Plus,
116}
117
118impl RgbaBlend for BlendMode {
119    type Channel = f32;
120
121    fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel> {
122        let pd: PorterDuff<f32, fn(f32, f32) -> f32> = match self {
123            Self::Clear => PorterDuff::CLEAR,
124            Self::Source => PorterDuff::SRC,
125            Self::Destination => PorterDuff::DST,
126            Self::SourceOver => PorterDuff::SRC_OVER,
127            Self::DestinationOver => PorterDuff::DST_OVER,
128            Self::SourceIn => PorterDuff::SRC_IN,
129            Self::DestinationIn => PorterDuff::DST_IN,
130            Self::SourceOut => PorterDuff::SRC_OUT,
131            Self::DestinationOut => PorterDuff::DST_OUT,
132            Self::SourceAtop => PorterDuff::SRC_ATOP,
133            Self::DestinationAtop => PorterDuff::DST_ATOP,
134            Self::Xor => PorterDuff::XOR,
135            Self::Plus => PorterDuff::PLUS,
136        };
137        pd.apply(src, dst)
138    }
139}
140
141/// Blends pixel colors using alpha compositing.
142pub trait RgbaBlend {
143    /// What type of channel this blend mode operates on.
144    ///
145    /// **Note**: only `f32` is currently supported via the provided
146    /// [`BlendMode`] / [`PorterDuff`] implementations.  `u8` blending is
147    /// available directly on [`U8x4Rgba`](crate::rgba::U8x4Rgba) via
148    /// [`source_over`](crate::rgba::U8x4Rgba::source_over).
149    type Channel: Copy;
150
151    /// Blends two colors together using this blend mode.
152    fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel>;
153
154    /// Blend `src` over `dst` in place, pixel by pixel.
155    ///
156    /// Default impl calls [`apply`](RgbaBlend::apply) in a loop.
157    /// Implementations may override with SIMD or other optimized paths.
158    fn apply_slice(&self, src: &[Rgba<Self::Channel>], dst: &mut [Rgba<Self::Channel>]) {
159        assert_eq!(
160            src.len(),
161            dst.len(),
162            "src and dst slices must have the same length"
163        );
164        for (s, d) in src.iter().zip(dst.iter_mut()) {
165            *d = self.apply(*s, *d);
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use crate::rgba::F32x4Rgba;
174
175    #[test]
176    fn blend_mode_default_is_source_over() {
177        assert_eq!(BlendMode::default(), BlendMode::SourceOver);
178    }
179
180    #[test]
181    fn apply_slice_matches_individual() {
182        let src = [
183            F32x4Rgba::new(1.0, 0.0, 0.0, 0.5),
184            F32x4Rgba::new(0.0, 1.0, 0.0, 1.0),
185        ];
186        let dst = [
187            F32x4Rgba::new(0.0, 0.0, 1.0, 1.0),
188            F32x4Rgba::new(1.0, 0.0, 0.0, 1.0),
189        ];
190
191        let mut batch = dst;
192        BlendMode::SourceOver.apply_slice(&src, &mut batch);
193
194        for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
195            let expected = BlendMode::SourceOver.apply(*s, *d);
196            assert_eq!(batch[i], expected);
197        }
198    }
199
200    #[test]
201    #[should_panic(expected = "must have the same length")]
202    fn apply_slice_panics_on_mismatched_lengths() {
203        let src = [F32x4Rgba::new(0.0, 0.0, 0.0, 0.0)];
204        let mut dst = [F32x4Rgba::new(1.0, 1.0, 1.0, 1.0); 2];
205        BlendMode::SourceOver.apply_slice(&src, &mut dst);
206    }
207
208    #[test]
209    fn blend_mode_hash() {
210        use std::collections::HashSet;
211        let mut set = HashSet::new();
212        set.insert(BlendMode::SourceOver);
213        set.insert(BlendMode::SourceOver);
214        assert_eq!(set.len(), 1);
215        set.insert(BlendMode::Clear);
216        assert_eq!(set.len(), 2);
217    }
218}