Skip to main content

model/
color.rs

1#[derive(Debug, Clone, Copy, PartialEq)]
2#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3pub struct Color {
4    pub r: f32,
5    pub g: f32,
6    pub b: f32,
7    pub a: f32,
8}
9
10impl Color {
11    /// Opaque black.
12    pub const BLACK: Self = Self {
13        r: 0.0,
14        g: 0.0,
15        b: 0.0,
16        a: 1.0,
17    };
18    /// Opaque white.
19    pub const WHITE: Self = Self {
20        r: 1.0,
21        g: 1.0,
22        b: 1.0,
23        a: 1.0,
24    };
25
26    /// Create a new color from RGBA components, each in `[0, 1]`.
27    #[inline]
28    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
29        Self { r, g, b, a }
30    }
31
32    /// Create a fully opaque color from RGB.
33    #[inline]
34    pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
35        Self { r, g, b, a: 1.0 }
36    }
37
38    /// Create a color from RGBA.
39    #[inline]
40    pub const fn from_rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
41        Self { r, g, b, a }
42    }
43
44    /// Create a fully opaque color from RGB (alias for [`rgb`](Self::rgb)).
45    #[inline]
46    pub const fn from_rgb(r: f32, g: f32, b: f32) -> Self {
47        Self::rgb(r, g, b)
48    }
49
50    /// Create a fully opaque color from 8-bit RGB components.
51    #[inline]
52    pub const fn from_rgb8(r: u8, g: u8, b: u8) -> Self {
53        Self {
54            r: r as f32 / 255.0,
55            g: g as f32 / 255.0,
56            b: b as f32 / 255.0,
57            a: 1.0,
58        }
59    }
60
61    /// Create a color from 8-bit RGBA components.
62    #[inline]
63    pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
64        Self {
65            r: r as f32 / 255.0,
66            g: g as f32 / 255.0,
67            b: b as f32 / 255.0,
68            a: a as f32 / 255.0,
69        }
70    }
71
72    /// Linearly interpolate between `self` and `other` at parameter `t` in `[0, 1]`.
73    #[inline]
74    pub fn lerp(self, other: Self, t: f32) -> Self {
75        Self {
76            r: self.r + (other.r - self.r) * t,
77            g: self.g + (other.g - self.g) * t,
78            b: self.b + (other.b - self.b) * t,
79            a: self.a + (other.a - self.a) * t,
80        }
81    }
82}