From 635e212daaab677340d9ff38ea0e8286c774a480 Mon Sep 17 00:00:00 2001 From: Overlord Date: Sun, 18 Oct 2026 15:27:27 +0200 Subject: [PATCH] Add RGB and interpolation traits. --- src/color/hsl.rs | 14 +++ src/color/hsv.rs | 14 +++ src/color/linear.rs | 22 +++++ src/color/mod.rs | 15 +++ src/color/ops.rs | 13 +++ src/color/rgb.rs | 229 ++++++++++++++++++++++++++++++++++++++++++++ src/color/rgbf.rs | 17 ++++ src/lib.rs | 6 ++ src/smooth/lerp.rs | 5 + src/smooth/mod.rs | 5 + 10 files changed, 340 insertions(+) create mode 100644 src/color/hsl.rs create mode 100644 src/color/hsv.rs create mode 100644 src/color/linear.rs create mode 100644 src/color/ops.rs create mode 100644 src/color/rgb.rs create mode 100644 src/color/rgbf.rs create mode 100644 src/smooth/lerp.rs create mode 100644 src/smooth/mod.rs diff --git a/src/color/hsl.rs b/src/color/hsl.rs new file mode 100644 index 0000000..ff30214 --- /dev/null +++ b/src/color/hsl.rs @@ -0,0 +1,14 @@ +use super::Rgb; + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Hsl { + pub h: f32, + pub s: f32, + pub l: f32, +} + +impl Hsl +{ + pub fn to_rgb(self) -> Rgb { todo!() } +} diff --git a/src/color/hsv.rs b/src/color/hsv.rs new file mode 100644 index 0000000..e309d2d --- /dev/null +++ b/src/color/hsv.rs @@ -0,0 +1,14 @@ +use super::Rgb; + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Hsv { + pub h: f32, + pub s: f32, + pub v: f32, +} + +impl Hsv +{ + pub fn to_rgb(self) -> Rgb { todo!() } +} diff --git a/src/color/linear.rs b/src/color/linear.rs new file mode 100644 index 0000000..e02683e --- /dev/null +++ b/src/color/linear.rs @@ -0,0 +1,22 @@ +use super::Rgb; +use crate::smooth::Lerp; + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct LinearRgb { + pub r: f32, + pub g: f32, + pub b: f32, +} + +impl LinearRgb +{ + pub fn to_rgb(self) -> Rgb { todo!() } + + pub fn luminance(self) -> f32 { todo!() } +} + +impl Lerp for LinearRgb +{ + fn lerp(&self, _to: &Self, _t: f32) -> Self { todo!() } +} diff --git a/src/color/mod.rs b/src/color/mod.rs index 591cf3e..96539df 100644 --- a/src/color/mod.rs +++ b/src/color/mod.rs @@ -1 +1,16 @@ mod transfer; +mod rgb; +mod rgbf; +mod linear; +mod hsv; +mod hsl; +mod ops; + +// + +pub use rgb::Rgb; +pub use rgbf::Rgbf; +pub use linear::LinearRgb; +pub use hsv::Hsv; +pub use hsl::Hsl; +pub use ops::ParseHexError; diff --git a/src/color/ops.rs b/src/color/ops.rs new file mode 100644 index 0000000..d79b516 --- /dev/null +++ b/src/color/ops.rs @@ -0,0 +1,13 @@ +use std::fmt; +use std::error::Error; + +/// The error from parsing an `Rgb` that isn't `#rrggbb` or `#rgb`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParseHexError; + +impl fmt::Display for ParseHexError +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("expected a hex color like #rrggbb or #rgb") } +} + +impl Error for ParseHexError {} diff --git a/src/color/rgb.rs b/src/color/rgb.rs new file mode 100644 index 0000000..73ce5ad --- /dev/null +++ b/src/color/rgb.rs @@ -0,0 +1,229 @@ +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 } diff --git a/src/color/rgbf.rs b/src/color/rgbf.rs new file mode 100644 index 0000000..570d83d --- /dev/null +++ b/src/color/rgbf.rs @@ -0,0 +1,17 @@ +use super::{ Rgb, Hsv, Hsl }; +#[derive(Debug, Clone, Copy, PartialEq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Rgbf { + pub r: f32, + pub g: f32, + pub b: f32, +} + +impl Rgbf +{ + pub fn to_rgb(self) -> Rgb { todo!() } + + pub fn to_hsv(self) -> Hsv { todo!() } + + pub fn to_hsl(self) -> Hsl { todo!() } +} diff --git a/src/lib.rs b/src/lib.rs index 2c53cf0..c970462 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,7 @@ pub mod color; +pub mod smooth; + +// ------ + +pub use color::{ Rgb, Rgbf, LinearRgb, Hsv, Hsl }; +pub use smooth::Lerp; diff --git a/src/smooth/lerp.rs b/src/smooth/lerp.rs new file mode 100644 index 0000000..6ed173a --- /dev/null +++ b/src/smooth/lerp.rs @@ -0,0 +1,5 @@ +// PLACEHOLDER: only the trait; see SPEC ยง10. + +pub trait Lerp { + fn lerp(&self, to: &Self, t: f32) -> Self; +} diff --git a/src/smooth/mod.rs b/src/smooth/mod.rs new file mode 100644 index 0000000..5d5dc8e --- /dev/null +++ b/src/smooth/mod.rs @@ -0,0 +1,5 @@ +mod lerp; + +// ------ + +pub use lerp::Lerp;