use super::vector4::Vector4;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TRGBA {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
pub type RGBAf = TRGBA;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RGBA8888 {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: f32,
}
pub fn hex_to_rgba8888(hex: &str) -> RGBA8888 {
let hex = hex.trim_start_matches('#');
let (r, g, b, a) = match hex.len() {
3 => (
u8::from_str_radix(&hex[0..1].repeat(2), 16).unwrap(),
u8::from_str_radix(&hex[1..2].repeat(2), 16).unwrap(),
u8::from_str_radix(&hex[2..3].repeat(2), 16).unwrap(),
255u8,
),
6 => (
u8::from_str_radix(&hex[0..2], 16).unwrap(),
u8::from_str_radix(&hex[2..4], 16).unwrap(),
u8::from_str_radix(&hex[4..6], 16).unwrap(),
255u8,
),
8 => (
u8::from_str_radix(&hex[0..2], 16).unwrap(),
u8::from_str_radix(&hex[2..4], 16).unwrap(),
u8::from_str_radix(&hex[4..6], 16).unwrap(),
u8::from_str_radix(&hex[6..8], 16).unwrap(),
),
_ => panic!("Invalid hex format. Expected #RGB, #RRGGBB or #RRGGBBAA."),
};
RGBA8888 {
r,
g,
b,
a: a as f32 / 255.0,
}
}
pub fn rgba_to_unit8_chunk(rgba: RGBA8888) -> Vector4 {
[
rgba.r as f32,
rgba.g as f32,
rgba.b as f32,
(rgba.a * 255.0).round(),
]
}
pub fn rgbaf_to_rgba8888(rgba: RGBAf) -> RGBA8888 {
RGBA8888 {
r: (rgba.r * 255.0).round() as u8,
g: (rgba.g * 255.0).round() as u8,
b: (rgba.b * 255.0).round() as u8,
a: rgba.a,
}
}
pub fn rgbaf_multiply_alpha(color: TRGBA, alpha: f32) -> TRGBA {
TRGBA {
a: color.a * alpha,
..color
}
}
pub fn rgba8888_to_hex(color: RGBA8888) -> String {
let a = (color.a * 255.0).round() as u8;
format!("#{:02x}{:02x}{:02x}{:02x}", color.r, color.g, color.b, a)
}