1use rouge_theme::Rgba;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq)]
4pub struct Color {
5 pub r: f32,
6 pub g: f32,
7 pub b: f32,
8 pub a: f32,
9}
10
11impl Color {
12 pub const TRANSPARENT: Color = Color::new(0.0, 0.0, 0.0, 0.0);
13 pub const BLACK: Color = Color::new(0.0, 0.0, 0.0, 1.0);
14 pub const WHITE: Color = Color::new(1.0, 1.0, 1.0, 1.0);
15 pub const RED: Color = Color::new(1.0, 0.0, 0.0, 1.0);
16 pub const GREEN: Color = Color::new(0.0, 1.0, 0.0, 1.0);
17 pub const BLUE: Color = Color::new(0.0, 0.0, 1.0, 1.0);
18
19 pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
20 Color { r, g, b, a }
21 }
22
23 pub const fn rgb(hex: u32) -> Self {
24 Color::from_rgba8((hex >> 16) as u8, (hex >> 8) as u8, hex as u8, 255)
25 }
26
27 pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
28 Color::new(
29 r as f32 / 255.0,
30 g as f32 / 255.0,
31 b as f32 / 255.0,
32 a as f32 / 255.0,
33 )
34 }
35
36 #[expect(clippy::many_single_char_names)]
37 pub fn hsl(h: f32, s: f32, l: f32) -> Self {
38 let h = h.rem_euclid(360.0) / 60.0;
39 let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
40 let x = c * (1.0 - (h % 2.0 - 1.0).abs());
41 let (r, g, b) = match h as u32 {
42 0 => (c, x, 0.0),
43 1 => (x, c, 0.0),
44 2 => (0.0, c, x),
45 3 => (0.0, x, c),
46 4 => (x, 0.0, c),
47 _ => (c, 0.0, x),
48 };
49 let m = l - c / 2.0;
50 Color::new(r + m, g + m, b + m, 1.0)
51 }
52
53 pub const fn with_alpha(self, a: f32) -> Self {
54 Color { a, ..self }
55 }
56
57 pub fn premultiplied(self) -> [f32; 4] {
58 [self.r * self.a, self.g * self.a, self.b * self.a, self.a]
59 }
60
61 pub fn to_array(self) -> [f32; 4] {
62 [self.r, self.g, self.b, self.a]
63 }
64
65 pub fn to_rgba8(self) -> [u8; 4] {
66 self.to_array()
67 .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
68 }
69}
70
71impl From<Rgba> for Color {
72 fn from(value: Rgba) -> Self {
73 Color::from_rgba8(value.r, value.g, value.b, value.a)
74 }
75}