Skip to main content

sim_engine/
color.rs

1use crate::tween::Interpolate;
2
3/// Linear RGBA color with channels in the `0.0..=1.0` range.
4///
5/// Constructors do not clamp so intermediate animation values can overshoot.
6/// Use [`Color::clamp`] before sending untrusted colors to a renderer.
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct Color {
9    r: f32,
10    g: f32,
11    b: f32,
12    a: f32,
13}
14
15impl Color {
16    /// Fully transparent black.
17    pub const TRANSPARENT: Self = Self::rgba(0.0, 0.0, 0.0, 0.0);
18    /// Opaque white.
19    pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0);
20    /// Opaque black.
21    pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0);
22
23    /// Builds an opaque color from floating-point RGB channels.
24    pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
25        Self::rgba(r, g, b, 1.0)
26    }
27
28    /// Builds a color from floating-point RGBA channels.
29    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
30        Self { r, g, b, a }
31    }
32
33    /// Returns the red linear-light channel.
34    pub const fn red(self) -> f32 {
35        self.r
36    }
37
38    /// Returns the green linear-light channel.
39    pub const fn green(self) -> f32 {
40        self.g
41    }
42
43    /// Returns the blue linear-light channel.
44    pub const fn blue(self) -> f32 {
45        self.b
46    }
47
48    /// Returns alpha coverage, where `0.0` is transparent and `1.0` is opaque.
49    pub const fn alpha(self) -> f32 {
50        self.a
51    }
52
53    /// Builds an opaque linear color from `0..=255` sRGB channels.
54    pub fn rgb8(r: u8, g: u8, b: u8) -> Self {
55        Self::rgba8(r, g, b, 255)
56    }
57
58    /// Builds a linear color from `0..=255` sRGB and alpha channels.
59    ///
60    /// RGB channels are converted from sRGB to linear light. Alpha is linear
61    /// coverage and is only normalized to `0.0..=1.0`.
62    pub fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
63        Self::rgba(
64            srgb_channel_to_linear(r as f32 / 255.0),
65            srgb_channel_to_linear(g as f32 / 255.0),
66            srgb_channel_to_linear(b as f32 / 255.0),
67            a as f32 / 255.0,
68        )
69    }
70
71    /// Returns the same RGB color with a replaced alpha channel.
72    pub fn with_alpha(self, alpha: f32) -> Self {
73        Self { a: alpha, ..self }
74    }
75
76    /// Multiplies only the alpha channel by `factor`.
77    pub fn scale_alpha(self, factor: f32) -> Self {
78        Self {
79            a: self.a * factor,
80            ..self
81        }
82    }
83
84    /// Returns true when every channel is finite.
85    pub fn is_finite(self) -> bool {
86        self.r.is_finite() && self.g.is_finite() && self.b.is_finite() && self.a.is_finite()
87    }
88
89    /// Returns true when every channel is finite and lies in `0.0..=1.0`.
90    pub fn is_normalized(self) -> bool {
91        self.is_finite()
92            && [self.r, self.g, self.b, self.a]
93                .into_iter()
94                .all(|channel| (0.0..=1.0).contains(&channel))
95    }
96
97    /// Sanitizes every channel to `0.0..=1.0`.
98    ///
99    /// NaN channels become `0.0`. Infinite values clamp to the nearest bound.
100    pub fn clamp(self) -> Self {
101        Self::rgba(
102            sanitize_channel(self.r),
103            sanitize_channel(self.g),
104            sanitize_channel(self.b),
105            sanitize_channel(self.a),
106        )
107    }
108
109    /// Returns clamped channels in RGBA order for GPU vertex data.
110    pub fn to_array(self) -> [f32; 4] {
111        let color = self.clamp();
112        [color.r, color.g, color.b, color.a]
113    }
114
115    /// Converts to the `wgpu` clear color type.
116    #[cfg(feature = "wgpu")]
117    pub fn to_wgpu(self) -> wgpu::Color {
118        let color = self.clamp();
119        wgpu::Color {
120            r: color.r as f64,
121            g: color.g as f64,
122            b: color.b as f64,
123            a: color.a as f64,
124        }
125    }
126}
127
128fn sanitize_channel(channel: f32) -> f32 {
129    if channel.is_nan() {
130        0.0
131    } else {
132        channel.clamp(0.0, 1.0)
133    }
134}
135
136fn srgb_channel_to_linear(channel: f32) -> f32 {
137    if channel <= 0.04045 {
138        channel / 12.92
139    } else {
140        ((channel + 0.055) / 1.055).powf(2.4)
141    }
142}
143
144impl Interpolate for Color {
145    fn interpolate(self, end: Self, amount: f32) -> Self {
146        Self::rgba(
147            self.r.interpolate(end.r, amount),
148            self.g.interpolate(end.g, amount),
149            self.b.interpolate(end.b, amount),
150            self.a.interpolate(end.a, amount),
151        )
152    }
153
154    fn is_valid_interpolation_value(self) -> bool {
155        self.is_finite()
156    }
157}
158
159/// Default visual palette for Sim;Engine demos and early integrations.
160///
161/// Applications can ignore this and provide their own colors. The palette exists
162/// so examples start from a polished baseline instead of bare grayscale.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub struct Palette {
165    background: Color,
166    surface: Color,
167    grid: Color,
168    axis: Color,
169    primary: Color,
170    secondary: Color,
171    accent: Color,
172    warning: Color,
173}
174
175impl Palette {
176    /// Builds a palette from colors ordered as background, surface, grid, axis,
177    /// primary, secondary, accent, and warning.
178    pub const fn from_colors(colors: [Color; 8]) -> Self {
179        Self {
180            background: colors[0],
181            surface: colors[1],
182            grid: colors[2],
183            axis: colors[3],
184            primary: colors[4],
185            secondary: colors[5],
186            accent: colors[6],
187            warning: colors[7],
188        }
189    }
190
191    /// Returns the main background color.
192    pub const fn background(self) -> Color {
193        self.background
194    }
195    /// Returns the elevated surface color.
196    pub const fn surface(self) -> Color {
197        self.surface
198    }
199    /// Returns the grid-line color.
200    pub const fn grid(self) -> Color {
201        self.grid
202    }
203    /// Returns the axis color.
204    pub const fn axis(self) -> Color {
205        self.axis
206    }
207    /// Returns the primary data color.
208    pub const fn primary(self) -> Color {
209        self.primary
210    }
211    /// Returns the secondary data color.
212    pub const fn secondary(self) -> Color {
213        self.secondary
214    }
215    /// Returns the accent color.
216    pub const fn accent(self) -> Color {
217        self.accent
218    }
219    /// Returns the warning color.
220    pub const fn warning(self) -> Color {
221        self.warning
222    }
223    /// Returns the default Sim;Engine color palette.
224    pub fn sim() -> Self {
225        Self {
226            background: Color::rgb8(12, 14, 18),
227            surface: Color::rgb8(27, 31, 39),
228            grid: Color::rgba8(140, 158, 180, 38),
229            axis: Color::rgba8(214, 224, 238, 100),
230            primary: Color::rgb8(86, 195, 255),
231            secondary: Color::rgb8(128, 228, 167),
232            accent: Color::rgb8(255, 190, 94),
233            warning: Color::rgb8(255, 105, 120),
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::Color;
241
242    #[test]
243    fn clamp_sanitizes_non_finite_channels() {
244        let color = Color::rgba(f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1.5).clamp();
245
246        assert_eq!(color, Color::rgba(0.0, 1.0, 0.0, 1.0));
247    }
248
249    #[test]
250    fn rgb8_converts_srgb_to_linear_light() {
251        let middle_gray = Color::rgb8(128, 128, 128);
252
253        assert!((middle_gray.red() - 0.21586).abs() < 0.0001);
254        assert_eq!(middle_gray.red(), middle_gray.green());
255        assert_eq!(middle_gray.green(), middle_gray.blue());
256    }
257}