use std::fmt; use std::str::FromStr; use super::{transfer, ParseHexError}; use super::{ Rgbf, LinearRgb, Hsv, Hsl }; use crate::smooth::Lerp; /// An sRGB color with one byte per channel. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Rgb { pub r: u8, pub g: u8, pub b: u8, } impl Rgb { pub const BLACK: Rgb = Rgb::new(0, 0, 0); pub const WHITE: Rgb = Rgb::new(255, 255, 255); #[must_use] pub const fn new(r: u8, g: u8, b: u8) -> Self { Self { r, g, b } } /// Parses `#rrggbb` or the short form `#rgb`, where each digit is doubled (`#f80` is `#ff8800`). /// The `#` is optional, case doesn't matter, and surrounding whitespace is ignored. #[must_use] pub fn from_hex(s: &str) -> Option { let s = s.trim(); let s = s.strip_prefix('#').unwrap_or(s).as_bytes(); // Each byte as a hex digit (0..=15); anything else, including non-ASCII, gives None. let digit = |b: u8| (b as char).to_digit(16).map(|d| d as u8); match *s { [r1, r0, g1, g0, b1, b0] => Some(Self::new( digit(r1)? * 16 + digit(r0)?, digit(g1)? * 16 + digit(g0)?, digit(b1)? * 16 + digit(b0)?, )), [r, g, b] => Some(Self::new(digit(r)? * 17, digit(g)? * 17, digit(b)? * 17)), _ => None, } } /// The colour as `#RRGGBB`, uppercase. #[must_use] pub fn to_hex(self) -> String { format!("{self:#X}") } /// Each channel divided by 255, sRGB-encoded. #[must_use] pub const fn to_rgbf(self) -> Rgbf { Rgbf { r: self.r as f32 / 255.0, g: self.g as f32 / 255.0, b: self.b as f32 / 255.0 } } /// Decodes the colour to linear light. #[must_use] pub fn to_linear(self) -> LinearRgb { LinearRgb { r: transfer::srgb_u8_to_linear(self.r), g: transfer::srgb_u8_to_linear(self.g), b: transfer::srgb_u8_to_linear(self.b), } } #[must_use] pub fn to_hsv(self) -> Hsv { self.to_rgbf().to_hsv() } #[must_use] pub fn to_hsl(self) -> Hsl { self.to_rgbf().to_hsl() } /// Relative luminance (Rec. 709 primaries), computed in linear light. /// 0 for black, 1 for white. #[must_use] pub fn luminance(self) -> f32 { self.to_linear().luminance() } /// The sum of the per-channel differences, from 0 to 765. #[must_use] pub const fn l1_distance(self, other: Rgb) -> u16 { self.r.abs_diff(other.r) as u16 + self.g.abs_diff(other.g) as u16 + self.b.abs_diff(other.b) as u16 } /// Blends toward `other` in linear light: /// `t = 0` gives `self`, /// `t = 1` gives `other`. /// `t` is clamped to `0..=1`. #[must_use] pub fn mix(self, other: Rgb, t: f32) -> Self { self.to_linear().lerp(&other.to_linear(), t.clamp(0.0, 1.0)).to_rgb() } /// Applies `255 * (c / 255) ^ gamma` per channel. /// Meant as the last step before sending a colour to LEDs, which are linear; /// 2.2 to 2.8 suits WS2812-style strips. #[must_use] pub fn gamma(self, gamma: f32) -> Self { let apply = |c: u8| unit_to_u8((c as f32 / 255.0).powf(gamma)); Self::new(apply(self.r), apply(self.g), apply(self.b)) } /// Scales each channel by the matching channel of `wb` over 255, for LED calibration. /// `wb = WHITE` leaves the colour unchanged. #[must_use] pub const fn white_balance(self, wb: Rgb) -> Self { Self::new(scale(self.r, wb.r), scale(self.g, wb.g), scale(self.b, wb.b)) } } // /// `{:x}` gives `ff8000`, and `{:#x}` gives `#ff8000`. impl fmt::LowerHex for Rgb { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if f.alternate() { f.write_str("#")?; } write!(f, "{:02x}{:02x}{:02x}", self.r, self.g, self.b) } } /// `{:X}` gives `FF8000`, and `{:#X}` gives `#FF8000`. impl fmt::UpperHex for Rgb { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if f.alternate() { f.write_str("#")?; } write!(f, "{:02X}{:02X}{:02X}", self.r, self.g, self.b) } } /// `#RRGGBB`, the same as `Rgb::to_hex`. impl fmt::Display for Rgb { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{self:#X}") } } // impl FromStr for Rgb { type Err = ParseHexError; fn from_str(s: &str) -> Result { Rgb::from_hex(s).ok_or(ParseHexError) } } impl From<[u8; 3]> for Rgb { fn from([r, g, b]: [u8; 3]) -> Self { Rgb::new(r, g, b) } } impl From<(u8, u8, u8)> for Rgb { fn from((r, g, b): (u8, u8, u8)) -> Self { Rgb::new(r, g, b) } } impl From for [u8; 3] { fn from(c: Rgb) -> Self { [c.r, c.g, c.b] } } impl From for (u8, u8, u8) { fn from(c: Rgb) -> Self { (c.r, c.g, c.b) } } impl From for Rgbf { fn from(c: Rgb) -> Self { c.to_rgbf() } } impl From for LinearRgb { fn from(c: Rgb) -> Self { c.to_linear() } } impl From for Hsv { fn from(c: Rgb) -> Self { c.to_hsv() } } impl From for Hsl { fn from(c: Rgb) -> Self { c.to_hsl() } } impl From for Rgb { fn from(c: Rgbf) -> Self { c.to_rgb() } } impl From for Rgb { fn from(c: LinearRgb) -> Self { c.to_rgb() } } impl From for Rgb { fn from(c: Hsv) -> Self { c.to_rgb() } } impl From for Rgb { fn from(c: Hsl) -> Self { c.to_rgb() } } // /// Converts a `0..=1` channel to a byte, rounding and clamping. /// NaN gives 0. pub(super) fn unit_to_u8(f: f32) -> u8 { (f.clamp(0.0, 1.0) * 255.0).round() as u8 } /// `round(c * k / 255)` in integers. const fn scale(c: u8, k: u8) -> u8 { ((c as u16 * k as u16 + 127) / 255) as u8 }