rouge-render 0.7.0

wgpu renderer, effects and shared GPU surfaces for Rouge
Documentation
use rouge_theme::Rgba;

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const TRANSPARENT: Color = Color::new(0.0, 0.0, 0.0, 0.0);
    pub const BLACK: Color = Color::new(0.0, 0.0, 0.0, 1.0);
    pub const WHITE: Color = Color::new(1.0, 1.0, 1.0, 1.0);
    pub const RED: Color = Color::new(1.0, 0.0, 0.0, 1.0);
    pub const GREEN: Color = Color::new(0.0, 1.0, 0.0, 1.0);
    pub const BLUE: Color = Color::new(0.0, 0.0, 1.0, 1.0);

    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
        Color { r, g, b, a }
    }

    pub const fn rgb(hex: u32) -> Self {
        Color::from_rgba8((hex >> 16) as u8, (hex >> 8) as u8, hex as u8, 255)
    }

    pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
        Color::new(
            r as f32 / 255.0,
            g as f32 / 255.0,
            b as f32 / 255.0,
            a as f32 / 255.0,
        )
    }

    #[expect(clippy::many_single_char_names)]
    pub fn hsl(h: f32, s: f32, l: f32) -> Self {
        let h = h.rem_euclid(360.0) / 60.0;
        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
        let x = c * (1.0 - (h % 2.0 - 1.0).abs());
        let (r, g, b) = match h as u32 {
            0 => (c, x, 0.0),
            1 => (x, c, 0.0),
            2 => (0.0, c, x),
            3 => (0.0, x, c),
            4 => (x, 0.0, c),
            _ => (c, 0.0, x),
        };
        let m = l - c / 2.0;
        Color::new(r + m, g + m, b + m, 1.0)
    }

    pub const fn with_alpha(self, a: f32) -> Self {
        Color { a, ..self }
    }

    #[must_use]
    pub fn over(self, background: Color) -> Color {
        let below = background.a * (1.0 - self.a);
        let a = self.a + below;
        if a <= 0.0 {
            return Color::TRANSPARENT;
        }
        let channel = |top: f32, bottom: f32| (top * self.a + bottom * below) / a;
        Color::new(
            channel(self.r, background.r),
            channel(self.g, background.g),
            channel(self.b, background.b),
            a,
        )
    }

    pub fn premultiplied(self) -> [f32; 4] {
        [self.r * self.a, self.g * self.a, self.b * self.a, self.a]
    }

    pub fn to_array(self) -> [f32; 4] {
        [self.r, self.g, self.b, self.a]
    }

    pub fn to_rgba8(self) -> [u8; 4] {
        self.to_array()
            .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
    }
}

impl From<Color> for Rgba {
    fn from(value: Color) -> Self {
        let [r, g, b, a] = value.to_rgba8();
        Rgba::new(r, g, b, a)
    }
}

impl From<Rgba> for Color {
    fn from(value: Rgba) -> Self {
        Color::from_rgba8(value.r, value.g, value.b, value.a)
    }
}