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(crate) mod math;
58pub mod porter_duff;
59pub mod rgba;
60pub(crate) mod vec4;
61
62/// Supported blend modes by this crate.
63///
64/// All modes operate in **straight alpha**. See
65/// [`F32x4Rgba::premultiply`](crate::rgba::F32x4Rgba::premultiply) for premultiplied support.
66///
67/// ## Overflow
68///
69/// [`Plus`](BlendMode::Plus) can produce channel values > 1.0. Call
70/// [`clamp()`](crate::rgba::F32x4Rgba::clamp) on the result when using `Plus`.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
72pub enum BlendMode {
73 /// Destination pixels covered by the source pixels are cleared.
74 Clear,
75
76 /// Source pixels are copied to the destination.
77 Source,
78
79 /// Destination pixels are copied to the source.
80 Destination,
81
82 /// Source pixels are copied to the destination, ignoring the alpha channel.
83 #[default]
84 SourceOver,
85
86 /// Destination pixels are copied to the source, ignoring the alpha channel.
87 DestinationOver,
88
89 /// Source pixels are copied to the destination, only where the destination is opaque.
90 SourceIn,
91
92 /// Destination pixels are copied to the source, only where the source is opaque.
93 DestinationIn,
94
95 /// Source pixels are copied to the destination, only where the source is opaque.
96 SourceOut,
97
98 /// Destination pixels are copied to the source, only where the destination is opaque.
99 DestinationOut,
100
101 /// Source pixels are copied to the destination, where both source and destination are opaque.
102 SourceAtop,
103
104 /// Destination pixels are copied to the source, where both source and destination are opaque.
105 DestinationAtop,
106
107 /// Source pixels are blended with the destination using the source's alpha channel.
108 Xor,
109
110 /// Source pixels are added to the destination.
111 ///
112 /// **Note**: can produce channel values > 1.0. Call
113 /// [`clamp()`](crate::rgba::F32x4Rgba::clamp) on the result when clamping is needed.
114 Plus,
115}
116
117impl RgbaBlend for BlendMode {
118 type Channel = f32;
119
120 fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel> {
121 let pd: PorterDuff<f32, fn(f32, f32) -> f32> = match self {
122 Self::Clear => PorterDuff::CLEAR,
123 Self::Source => PorterDuff::SRC,
124 Self::Destination => PorterDuff::DST,
125 Self::SourceOver => PorterDuff::SRC_OVER,
126 Self::DestinationOver => PorterDuff::DST_OVER,
127 Self::SourceIn => PorterDuff::SRC_IN,
128 Self::DestinationIn => PorterDuff::DST_IN,
129 Self::SourceOut => PorterDuff::SRC_OUT,
130 Self::DestinationOut => PorterDuff::DST_OUT,
131 Self::SourceAtop => PorterDuff::SRC_ATOP,
132 Self::DestinationAtop => PorterDuff::DST_ATOP,
133 Self::Xor => PorterDuff::XOR,
134 Self::Plus => PorterDuff::PLUS,
135 };
136 pd.apply(src, dst)
137 }
138}
139
140/// Blends pixel colors using alpha compositing.
141pub trait RgbaBlend {
142 /// What type of channel this blend mode operates on.
143 ///
144 /// **Note**: only `f32` is currently supported via the provided
145 /// [`BlendMode`] / [`PorterDuff`] implementations. `u8` blending is
146 /// available directly on [`U8x4Rgba`](crate::rgba::U8x4Rgba) via
147 /// [`source_over`](crate::rgba::U8x4Rgba::source_over).
148 type Channel: Copy;
149
150 /// Blends two colors together using this blend mode.
151 fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel>;
152
153 /// Blend `src` over `dst` in place, pixel by pixel.
154 ///
155 /// Default impl calls [`apply`](RgbaBlend::apply) in a loop.
156 /// Implementations may override with SIMD or other optimized paths.
157 fn apply_slice(&self, src: &[Rgba<Self::Channel>], dst: &mut [Rgba<Self::Channel>]) {
158 assert_eq!(
159 src.len(),
160 dst.len(),
161 "src and dst slices must have the same length"
162 );
163 for (s, d) in src.iter().zip(dst.iter_mut()) {
164 *d = self.apply(*s, *d);
165 }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use crate::rgba::F32x4Rgba;
173
174 #[test]
175 fn blend_mode_default_is_source_over() {
176 assert_eq!(BlendMode::default(), BlendMode::SourceOver);
177 }
178
179 #[test]
180 fn apply_slice_matches_individual() {
181 let src = [
182 F32x4Rgba::new(1.0, 0.0, 0.0, 0.5),
183 F32x4Rgba::new(0.0, 1.0, 0.0, 1.0),
184 ];
185 let dst = [
186 F32x4Rgba::new(0.0, 0.0, 1.0, 1.0),
187 F32x4Rgba::new(1.0, 0.0, 0.0, 1.0),
188 ];
189
190 let mut batch = dst;
191 BlendMode::SourceOver.apply_slice(&src, &mut batch);
192
193 for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
194 let expected = BlendMode::SourceOver.apply(*s, *d);
195 assert_eq!(batch[i], expected);
196 }
197 }
198
199 #[test]
200 #[should_panic(expected = "must have the same length")]
201 fn apply_slice_panics_on_mismatched_lengths() {
202 let src = [F32x4Rgba::new(0.0, 0.0, 0.0, 0.0)];
203 let mut dst = [F32x4Rgba::new(1.0, 1.0, 1.0, 1.0); 2];
204 BlendMode::SourceOver.apply_slice(&src, &mut dst);
205 }
206
207 #[test]
208 fn blend_mode_hash() {
209 use std::collections::HashSet;
210 let mut set = HashSet::new();
211 set.insert(BlendMode::SourceOver);
212 set.insert(BlendMode::SourceOver);
213 assert_eq!(set.len(), 1);
214 set.insert(BlendMode::Clear);
215 assert_eq!(set.len(), 2);
216 }
217}