bevy_color/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![forbid(unsafe_code)]
3#![doc(
4    html_logo_url = "https://bevyengine.org/assets/icon.png",
5    html_favicon_url = "https://bevyengine.org/assets/icon.png"
6)]
7#![no_std]
8
9//! Representations of colors in various color spaces.
10//!
11//! This crate provides a number of color representations, including:
12//!
13//! - [`Srgba`] (standard RGBA, with gamma correction)
14//! - [`LinearRgba`] (linear RGBA, without gamma correction)
15//! - [`Hsla`] (hue, saturation, lightness, alpha)
16//! - [`Hsva`] (hue, saturation, value, alpha)
17//! - [`Hwba`] (hue, whiteness, blackness, alpha)
18//! - [`Laba`] (lightness, a-axis, b-axis, alpha)
19//! - [`Lcha`] (lightness, chroma, hue, alpha)
20//! - [`Oklaba`] (lightness, a-axis, b-axis, alpha)
21//! - [`Oklcha`] (lightness, chroma, hue, alpha)
22//! - [`Xyza`] (x-axis, y-axis, z-axis, alpha)
23//!
24//! Each of these color spaces is represented as a distinct Rust type.
25//!
26//! # Color Space Usage
27//!
28//! Rendering engines typically use linear RGBA colors, which allow for physically accurate
29//! lighting calculations. However, linear RGBA colors are not perceptually uniform, because
30//! both human eyes and computer monitors have non-linear responses to light. "Standard" RGBA
31//! represents an industry-wide compromise designed to encode colors in a way that looks good to
32//! humans in as few bits as possible, but it is not suitable for lighting calculations.
33//!
34//! Most image file formats and scene graph formats use standard RGBA, because graphic design
35//! tools are intended to be used by humans. However, 3D lighting calculations operate in linear
36//! RGBA, so it is important to convert standard colors to linear before sending them to the GPU.
37//! Most Bevy APIs will handle this conversion automatically, but if you are writing a custom
38//! shader, you will need to do this conversion yourself.
39//!
40//! HSL and LCH are "cylindrical" color spaces, which means they represent colors as a combination
41//! of hue, saturation, and lightness (or chroma). These color spaces are useful for working
42//! with colors in an artistic way - for example, when creating gradients or color palettes.
43//! A gradient in HSL space from red to violet will produce a rainbow. The LCH color space is
44//! more perceptually accurate than HSL, but is less intuitive to work with.
45//!
46//! HSV and HWB are very closely related to HSL in their derivation, having identical definitions for
47//! hue. Where HSL uses saturation and lightness, HSV uses a slightly modified definition of saturation,
48//! and an analog of lightness in the form of value. In contrast, HWB instead uses whiteness and blackness
49//! parameters, which can be used to lighten and darken a particular hue respectively.
50//!
51//! Oklab and Oklch are perceptually uniform color spaces that are designed to be used for tasks such
52//! as image processing. They are not as widely used as the other color spaces, but are useful
53//! for tasks such as color correction and image analysis, where it is important to be able
54//! to do things like change color saturation without causing hue shifts.
55//!
56//! XYZ is a foundational space commonly used in the definition of other more modern color
57//! spaces. The space is more formally known as CIE 1931, where the `x` and `z` axes represent
58//! a form of chromaticity, while `y` defines an illuminance level.
59//!
60//! See also the [Wikipedia article on color spaces](https://en.wikipedia.org/wiki/Color_space).
61#![doc = include_str!("../docs/conversion.md")]
62//! <div>
63#![doc = include_str!("../docs/diagrams/model_graph.svg")]
64//! </div>
65//!
66//! # Other Utilities
67//!
68//! The crate also provides a number of color operations, such as blending, color difference,
69//! and color range operations.
70//!
71//! In addition, there is a [`Color`] enum that can represent any of the color
72//! types in this crate. This is useful when you need to store a color in a data structure
73//! that can't be generic over the color type.
74//!
75//! Color types that are either physically or perceptually linear also implement `Add<Self>`, `Sub<Self>`, `Mul<f32>` and `Div<f32>`
76//! allowing you to use them with splines.
77//!
78//! Please note that most often adding or subtracting colors is not what you may want.
79//! Please have a look at other operations like blending, lightening or mixing colors using e.g. [`Mix`] or [`Luminance`] instead.
80//!
81//! # Example
82//!
83//! ```
84//! use bevy_color::{Srgba, Hsla};
85//!
86//! let srgba = Srgba::new(0.5, 0.2, 0.8, 1.0);
87//! let hsla: Hsla = srgba.into();
88//!
89//! println!("Srgba: {:?}", srgba);
90//! println!("Hsla: {:?}", hsla);
91//! ```
92
93#[cfg(feature = "std")]
94extern crate std;
95
96#[cfg(feature = "alloc")]
97extern crate alloc;
98
99mod color;
100pub mod color_difference;
101#[cfg(feature = "alloc")]
102mod color_gradient;
103mod color_ops;
104mod color_range;
105mod hsla;
106mod hsva;
107mod hwba;
108mod laba;
109mod lcha;
110mod linear_rgba;
111mod oklaba;
112mod oklcha;
113pub mod palettes;
114mod srgba;
115#[cfg(test)]
116mod test_colors;
117#[cfg(test)]
118mod testing;
119mod xyza;
120
121/// The color prelude.
122///
123/// This includes the most common types in this crate, re-exported for your convenience.
124pub mod prelude {
125    pub use crate::{
126        color::*, color_ops::*, hsla::*, hsva::*, hwba::*, laba::*, lcha::*, linear_rgba::*,
127        oklaba::*, oklcha::*, srgba::*, xyza::*,
128    };
129}
130
131pub use color::*;
132#[cfg(feature = "alloc")]
133pub use color_gradient::*;
134pub use color_ops::*;
135pub use color_range::*;
136pub use hsla::*;
137pub use hsva::*;
138pub use hwba::*;
139pub use laba::*;
140pub use lcha::*;
141pub use linear_rgba::*;
142pub use oklaba::*;
143pub use oklcha::*;
144pub use srgba::*;
145pub use xyza::*;
146
147/// Describes the traits that a color should implement for consistency.
148#[expect(
149    clippy::allow_attributes,
150    reason = "If the below attribute on `dead_code` is removed, then rustc complains that `StandardColor` is dead code. However, if we `expect` the `dead_code` lint, then rustc complains of an unfulfilled expectation."
151)]
152#[allow(
153    dead_code,
154    reason = "This is an internal marker trait used to ensure that our color types impl the required traits"
155)]
156pub(crate) trait StandardColor
157where
158    Self: core::fmt::Debug,
159    Self: Clone + Copy,
160    Self: PartialEq,
161    Self: Default,
162    Self: From<Color> + Into<Color>,
163    Self: From<Srgba> + Into<Srgba>,
164    Self: From<LinearRgba> + Into<LinearRgba>,
165    Self: From<Hsla> + Into<Hsla>,
166    Self: From<Hsva> + Into<Hsva>,
167    Self: From<Hwba> + Into<Hwba>,
168    Self: From<Laba> + Into<Laba>,
169    Self: From<Lcha> + Into<Lcha>,
170    Self: From<Oklaba> + Into<Oklaba>,
171    Self: From<Oklcha> + Into<Oklcha>,
172    Self: From<Xyza> + Into<Xyza>,
173    Self: Alpha,
174{
175}
176
177macro_rules! impl_componentwise_vector_space {
178    ($ty: ident, [$($element: ident),+]) => {
179        impl core::ops::Add<Self> for $ty {
180            type Output = Self;
181
182            fn add(self, rhs: Self) -> Self::Output {
183                Self::Output {
184                    $($element: self.$element + rhs.$element,)+
185                }
186            }
187        }
188
189        impl core::ops::AddAssign<Self> for $ty {
190            fn add_assign(&mut self, rhs: Self) {
191                *self = *self + rhs;
192            }
193        }
194
195        impl core::ops::Neg for $ty {
196            type Output = Self;
197
198            fn neg(self) -> Self::Output {
199                Self::Output {
200                    $($element: -self.$element,)+
201                }
202            }
203        }
204
205        impl core::ops::Sub<Self> for $ty {
206            type Output = Self;
207
208            fn sub(self, rhs: Self) -> Self::Output {
209                Self::Output {
210                    $($element: self.$element - rhs.$element,)+
211                }
212            }
213        }
214
215        impl core::ops::SubAssign<Self> for $ty {
216            fn sub_assign(&mut self, rhs: Self) {
217                *self = *self - rhs;
218            }
219        }
220
221        impl core::ops::Mul<f32> for $ty {
222            type Output = Self;
223
224            fn mul(self, rhs: f32) -> Self::Output {
225                Self::Output {
226                    $($element: self.$element * rhs,)+
227                }
228            }
229        }
230
231        impl core::ops::Mul<$ty> for f32 {
232            type Output = $ty;
233
234            fn mul(self, rhs: $ty) -> Self::Output {
235                Self::Output {
236                    $($element: self * rhs.$element,)+
237                }
238            }
239        }
240
241        impl core::ops::MulAssign<f32> for $ty {
242            fn mul_assign(&mut self, rhs: f32) {
243                *self = *self * rhs;
244            }
245        }
246
247        impl core::ops::Div<f32> for $ty {
248            type Output = Self;
249
250            fn div(self, rhs: f32) -> Self::Output {
251                Self::Output {
252                    $($element: self.$element / rhs,)+
253                }
254            }
255        }
256
257        impl core::ops::DivAssign<f32> for $ty {
258            fn div_assign(&mut self, rhs: f32) {
259                *self = *self / rhs;
260            }
261        }
262
263        impl bevy_math::VectorSpace for $ty {
264            const ZERO: Self = Self {
265                $($element: 0.0,)+
266            };
267        }
268    };
269}
270
271pub(crate) use impl_componentwise_vector_space;