pub fn srgb_to_linear(c: f32) -> f32 {
if c <= 0.040_45 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
pub fn linear_to_srgb(c: f32) -> f32 {
if c <= 0.003_130_8 {
12.92 * c
} else {
1.055 * c.powf(1.0 / 2.4) - 0.055
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ColourSpace {
Srgb,
Linear,
}
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Colour([f32; 4]);
impl Colour {
pub const WHITE: Colour = Colour([1.0, 1.0, 1.0, 1.0]);
pub const BLACK: Colour = Colour([0.0, 0.0, 0.0, 1.0]);
pub const TRANSPARENT: Colour = Colour([0.0, 0.0, 0.0, 0.0]);
pub const fn linear(r: f32, g: f32, b: f32, a: f32) -> Self {
Colour([r, g, b, a])
}
pub const fn linear_rgb(r: f32, g: f32, b: f32) -> Self {
Colour([r, g, b, 1.0])
}
pub fn srgb(r: f32, g: f32, b: f32, a: f32) -> Self {
Colour([srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a])
}
pub fn srgb_rgb(r: f32, g: f32, b: f32) -> Self {
Self::srgb(r, g, b, 1.0)
}
pub fn srgb_u8(r: u8, g: u8, b: u8, a: u8) -> Self {
Self::srgb(
r as f32 / 255.0,
g as f32 / 255.0,
b as f32 / 255.0,
a as f32 / 255.0,
)
}
pub fn rgb(r: u8, g: u8, b: u8) -> Self {
Self::srgb_u8(r, g, b, 255)
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
Self::srgb_u8(r, g, b, a)
}
pub fn hex(s: &str) -> Result<Self, ColourParseError> {
let h = s.strip_prefix('#').unwrap_or(s);
let expanded: String;
let h = if h.len() == 3 {
expanded = h.chars().flat_map(|c| [c, c]).collect();
expanded.as_str()
} else {
h
};
let byte = |i: usize| -> Result<u8, ColourParseError> {
u8::from_str_radix(&h[i..i + 2], 16).map_err(|_| ColourParseError::BadDigit)
};
match h.len() {
6 => Ok(Self::rgb(byte(0)?, byte(2)?, byte(4)?)),
8 => Ok(Self::rgba(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
_ => Err(ColourParseError::BadLength),
}
}
pub fn hsl(h: f32, s: f32, l: f32) -> Self {
let (r, g, b) = hsl_to_rgb(h, s, l);
Self::srgb_rgb(r, g, b)
}
pub fn hsv(h: f32, s: f32, v: f32) -> Self {
let (r, g, b) = hsv_to_rgb(h, s, v);
Self::srgb_rgb(r, g, b)
}
pub fn with_alpha(self, a: f32) -> Self {
Colour([self.0[0], self.0[1], self.0[2], a])
}
pub const fn to_linear_rgba(self) -> [f32; 4] {
self.0
}
pub const fn to_linear_rgb(self) -> [f32; 3] {
[self.0[0], self.0[1], self.0[2]]
}
pub const fn alpha(self) -> f32 {
self.0[3]
}
pub fn is_finite(self) -> bool {
self.0.iter().all(|c| c.is_finite())
}
pub fn to_srgb_u8(self) -> [u8; 4] {
let enc = |c: f32| (linear_to_srgb(c).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
[
enc(self.0[0]),
enc(self.0[1]),
enc(self.0[2]),
(self.0[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
]
}
}
impl From<[f32; 4]> for Colour {
fn from(v: [f32; 4]) -> Self {
Colour(v)
}
}
impl From<[f32; 3]> for Colour {
fn from(v: [f32; 3]) -> Self {
Colour([v[0], v[1], v[2], 1.0])
}
}
impl From<[f64; 4]> for Colour {
fn from(v: [f64; 4]) -> Self {
Colour([v[0] as f32, v[1] as f32, v[2] as f32, v[3] as f32])
}
}
impl From<[f64; 3]> for Colour {
fn from(v: [f64; 3]) -> Self {
Colour([v[0] as f32, v[1] as f32, v[2] as f32, 1.0])
}
}
impl From<Colour> for [f32; 4] {
fn from(c: Colour) -> Self {
c.0
}
}
impl From<Colour> for [f32; 3] {
fn from(c: Colour) -> Self {
c.to_linear_rgb()
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ColourParseError {
BadLength,
BadDigit,
}
impl core::fmt::Display for ColourParseError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ColourParseError::BadLength => f.write_str("hex colour must be 3, 6, or 8 hex digits"),
ColourParseError::BadDigit => f.write_str("hex colour contains a non-hex character"),
}
}
}
impl std::error::Error for ColourParseError {}
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
let h = h.rem_euclid(360.0);
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = l - c / 2.0;
let (r, g, b) = hue_sector(h, c, x);
(r + m, g + m, b + m)
}
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) {
let h = h.rem_euclid(360.0);
let c = v * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = v - c;
let (r, g, b) = hue_sector(h, c, x);
(r + m, g + m, b + m)
}
fn hue_sector(h: f32, c: f32, x: f32) -> (f32, f32, f32) {
match h as u32 / 60 {
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),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn linear_passthrough() {
let c = Colour::linear(0.1, 0.2, 0.3, 0.4);
assert_eq!(c.to_linear_rgba(), [0.1, 0.2, 0.3, 0.4]);
}
#[test]
fn srgb_decodes_and_round_trips() {
for (r, g, b) in [(24, 48, 84), (250, 218, 22)] {
let c = Colour::rgb(r, g, b);
assert_eq!(c.to_srgb_u8(), [r, g, b, 255]);
}
}
#[test]
fn hex_forms() {
assert_eq!(Colour::hex("#183054").unwrap(), Colour::rgb(24, 48, 84));
assert_eq!(Colour::hex("183054").unwrap(), Colour::rgb(24, 48, 84));
assert_eq!(Colour::hex("#abc").unwrap(), Colour::rgb(0xaa, 0xbb, 0xcc));
assert_eq!(
Colour::hex("#18305480").unwrap(),
Colour::rgba(24, 48, 84, 0x80)
);
assert_eq!(Colour::hex("#zz").err(), Some(ColourParseError::BadLength));
assert_eq!(
Colour::hex("#gggggg").err(),
Some(ColourParseError::BadDigit)
);
}
#[test]
fn alpha_is_not_decoded() {
let c = Colour::rgba(0, 0, 0, 128);
assert!((c.alpha() - 128.0 / 255.0).abs() < 1e-4);
}
#[test]
fn srgb_is_darker_than_linear_for_same_bytes() {
let s = Colour::srgb_rgb(0.5, 0.5, 0.5).to_linear_rgb();
assert!(s[0] < 0.5 - 0.05);
}
#[test]
fn is_finite_flags_bad_channels() {
assert!(Colour::rgb(24, 48, 84).is_finite());
assert!(Colour::linear(2.5, 0.0, 0.0, 1.0).is_finite());
assert!(!Colour::linear(f32::NAN, 0.0, 0.0, 1.0).is_finite());
assert!(!Colour::linear(0.0, f32::INFINITY, 0.0, 1.0).is_finite());
assert!(Colour::srgb(-0.1, 0.5, 1.2, 1.0).is_finite());
}
#[test]
fn hsl_matches_known_colour() {
let c = Colour::hsl(216.0, 0.56, 0.21).to_srgb_u8();
let expected = [24u8, 48, 84, 255];
for (got, want) in c.iter().zip(expected) {
assert!(
(*got as i32 - want as i32).abs() <= 1,
"{c:?} vs {expected:?}"
);
}
}
}