use super::*;
#[must_use]
pub fn concentric_radius(outer: f32, inset: f32) -> f32 {
if outer >= RADIUS_PILL {
RADIUS_PILL
} else {
(outer - inset).max(2.0)
}
}
pub(crate) const fn srgb_channel_to_linear(channel: u8) -> f32 {
let c: f32 = channel as f32 / 255.0;
if c <= 0.04045 {
return c / 12.92;
}
let x: f32 = (c + 0.055) / 1.055;
let x2: f32 = x * x;
let mut y: f32 = 0.75;
let mut step: usize = 0;
while step < 12 {
let y4: f32 = y * y * y * y;
y = (4.0 * y + x2 / y4) * 0.2;
step += 1;
}
x2 * y
}
#[must_use]
pub const fn relative_luminance_rgb(r: u8, g: u8, b: u8) -> f32 {
0.2126 * srgb_channel_to_linear(r)
+ 0.7152 * srgb_channel_to_linear(g)
+ 0.0722 * srgb_channel_to_linear(b)
}
#[must_use]
pub const fn contrast_ratio_hex(lhs: u32, rhs: u32) -> f32 {
let l1: f32 = relative_luminance_rgb(
((lhs >> 16) & 0xFF) as u8,
((lhs >> 8) & 0xFF) as u8,
(lhs & 0xFF) as u8,
);
let l2: f32 = relative_luminance_rgb(
((rhs >> 16) & 0xFF) as u8,
((rhs >> 8) & 0xFF) as u8,
(rhs & 0xFF) as u8,
);
if l1 >= l2 {
(l1 + 0.05) / (l2 + 0.05)
} else {
(l2 + 0.05) / (l1 + 0.05)
}
}
#[must_use]
pub fn relative_luminance(color: Color) -> f32 {
relative_luminance_rgb(color.get_r(), color.get_g(), color.get_b())
}
#[must_use]
pub fn blend_over(fg: Color, bg: Color) -> Color {
let a: f32 = fg.get_a() as f32 / 255.0;
let inv_a: f32 = 1.0 - a;
let r: u8 = (fg.get_r() as f32 * a + bg.get_r() as f32 * inv_a)
.round()
.clamp(0.0, 255.0) as u8;
let g: u8 = (fg.get_g() as f32 * a + bg.get_g() as f32 * inv_a)
.round()
.clamp(0.0, 255.0) as u8;
let b: u8 = (fg.get_b() as f32 * a + bg.get_b() as f32 * inv_a)
.round()
.clamp(0.0, 255.0) as u8;
Color::rgba(r, g, b, 255)
}
#[must_use]
pub fn contrast_ratio(fg: Color, bg: Color) -> f32 {
let opaque_bg: Color = bg.with_alpha(255);
let l1: f32 = relative_luminance(blend_over(fg, opaque_bg));
let l2: f32 = relative_luminance(opaque_bg);
let (hi, lo): (f32, f32) = if l1 >= l2 { (l1, l2) } else { (l2, l1) };
(hi + 0.05) / (lo + 0.05)
}