alpha_blend/lib.rs
1//! Alpha blending and compositing in (optionally) zero-dependency Rust.
2//!
3//! There are three pieces:
4//!
5//! - A [`CompositeMode`] decides **how much** of the source and destination survive. These are
6//! the Porter-Duff operators: [`SourceOver`](CompositeMode::SourceOver),
7//! [`Xor`](CompositeMode::Xor), and so on.
8//! - A [`BlendMode`] decides **how** their colors are mixed. These are the W3C separable blend
9//! modes: [`Multiply`](BlendMode::Multiply), [`Screen`](BlendMode::Screen),
10//! [`SoftLight`](BlendMode::SoftLight), and so on.
11//! - A [`Composite`] pairs the two. Either half can be used on its own, in which case the other
12//! takes its default.
13//!
14//! Everything is generic over [`channel::Channel`], so [`u8`] and [`f32`] pixels go
15//! through the same code at their own precision. There is no separate integer implementation to
16//! drift out of sync with the float one.
17//!
18//! All blending assumes **straight (un-premultiplied) alpha** unless documented otherwise. See
19//! [`rgba::Premultiplied`] for the other convention.
20//!
21//! ## Examples
22//!
23//! ```rust
24//! use alpha_blend::{CompositeMode, RgbaBlend, rgba::F32x4Rgba};
25//!
26//! let src = F32x4Rgba { r: 1.0, g: 0.0, b: 0.0, a: 0.5 }; // Semi-transparent red
27//! let dst = F32x4Rgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; // Opaque blue
28//! let blended = CompositeMode::SourceOver.apply(src, dst);
29//!
30//! // Half red over opaque blue: an even mix, still opaque.
31//! assert_eq!(blended, F32x4Rgba { r: 0.5, g: 0.0, b: 0.5, a: 1.0 });
32//! ```
33//!
34//! The same operation on `u8` pixels, and with a blend mode applied:
35//!
36//! ```rust
37//! use alpha_blend::{BlendMode, Composite, CompositeMode, RgbaBlend, rgba::U8x4Rgba};
38//!
39//! let src = U8x4Rgba::new(255, 128, 0, 128);
40//! let dst = U8x4Rgba::new(0, 64, 255, 255);
41//!
42//! // Plain source-over has a dedicated integer fast path.
43//! assert_eq!(CompositeMode::SourceOver.apply(src, dst), src.source_over(dst));
44//!
45//! // Multiply, composited source-over.
46//! let multiply = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver);
47//! assert_eq!(multiply.apply(src, dst), U8x4Rgba::new(0, 48, 127, 255));
48//! ```
49//!
50//! ## Rounding
51//!
52//! Integer channels round to nearest, once per operation, from a widened intermediate.
53//! `scale(255, 255) == 255`, and compositing an opaque pixel repeatedly is idempotent. See the
54//! [`channel`] module docs for the exact rules and why the usual `>> 8` shift trick is not used.
55//!
56//! ## Features
57//!
58//! By default, this crate is `no_std` compatible, and uses [`libm`] for some math operations.
59//!
60//! Either `std` or `libm` must be enabled.
61//!
62//! ### `bytemuck`
63//!
64//! Enables the `bytemuck` crate for zero-copy conversions between types.
65//!
66//! ### `libm`
67//!
68//! _This feature is enabled by default._
69//!
70//! Uses the `libm` crate for math operations.
71//!
72//! ### `libm-arch`
73//!
74//! _This feature is enabled by default._
75//!
76//! Enables the `arch` feature of `libm`.
77//!
78//! ### `std`
79//!
80//! Uses the standard library for math operations, such as `f32::round`.
81
82#![cfg_attr(not(feature = "std"), no_std)]
83
84use crate::{channel::Channel, rgba::Rgba};
85
86pub mod blend_modes;
87pub mod channel;
88pub mod composite;
89pub(crate) mod math;
90pub mod porter_duff;
91pub mod rgba;
92
93pub use crate::{blend_modes::BlendMode, composite::Composite, porter_duff::CompositeMode};
94
95/// Blends pixel colors using alpha compositing.
96///
97/// Implemented by [`Composite`] and, for convenience, by [`BlendMode`] and [`CompositeMode`]
98/// on their own. Implement it yourself to provide a specialized or vectorized path; overriding
99/// [`RgbaBlend::apply_slice`] is the usual reason to.
100pub trait RgbaBlend<C: Channel> {
101 /// Blends two colors together, returning a straight-alpha result.
102 ///
103 /// For integer channels this includes an unpremultiply, which is lossy. Use
104 /// [`Composite::composite`] instead when the result feeds another composite.
105 fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C>;
106
107 /// Blend `src` over `dst` in place, pixel by pixel.
108 ///
109 /// Default impl calls [`apply`](RgbaBlend::apply) in a loop.
110 /// Implementations may override with SIMD or other optimized paths.
111 ///
112 /// # Panics
113 ///
114 /// If `src` and `dst` have different lengths.
115 fn apply_slice(&self, src: &[Rgba<C>], dst: &mut [Rgba<C>]) {
116 assert_eq!(
117 src.len(),
118 dst.len(),
119 "src and dst slices must have the same length"
120 );
121 for (s, d) in src.iter().zip(dst.iter_mut()) {
122 *d = self.apply(*s, *d);
123 }
124 }
125}