Compare commits

..
4 Commits
16 changed files with 610 additions and 0 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = [
"-C", "link-arg=-fuse-ld=mold",
]
+4
View File
@@ -1,10 +1,14 @@
.*
!.git*
!.cargo*
*.md
!README.md
debug/
target/
**/*.rs.bk
*.pdb
*.lock
+38
View File
@@ -0,0 +1,38 @@
[package]
name = "framehue"
version = "0.1.0"
edition = "2024"
description = "Small, dependency-free Rust crate for color conversions (RGB, HSV, HSL, linear sRGB), raw frame sampling and smoothing."
license = "AGPL-3.0-or-later"
publish = false
[features]
serde = ["dep:serde"]
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[profile.dev]
lto = false
opt-level = 0
codegen-units = 256
incremental = true
debug = true
debug-assertions = true
overflow-checks = true
panic = "unwind"
strip = "none"
[profile.dev.package."*"]
opt-level = 2
[profile.release]
lto = "fat"
opt-level = 3
codegen-units = 1
incremental = false
debug = false
debug-assertions = false
overflow-checks = false
panic = "abort"
strip = "symbols"
+27
View File
@@ -0,0 +1,27 @@
use std::{
env, fs,
path::Path
};
/// Writes the sRGB → linear table for every `u8` channel value to `OUT_DIR`,
/// so `color::transfer` can include it as a plain array.
fn main()
{
println!("cargo::rerun-if-changed=NULL");
// `{:?}` prints the shortest literal that parses back to the exact same f32.
let values: Vec<String> = (0..=255u8).map(
|c| format!("{:?}", srgb_to_linear(c as f32 / 255.0))
).collect();
let table = format!("[{}]", values.join(", "));
let out = Path::new(&env::var_os("OUT_DIR").unwrap()).join("srgb_lut.rs");
fs::write(out, table).unwrap();
}
/// A copy of `color::transfer::srgb_to_linear`.
fn srgb_to_linear(c: f32) -> f32
{
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "stable"
components = ["clippy", "rustfmt"]
+16
View File
@@ -0,0 +1,16 @@
use super::{ Rgb, Rgbf };
#[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!() }
pub fn to_rgbf(self) -> Rgbf { todo!() }
}
+24
View File
@@ -0,0 +1,24 @@
use super::{ Rgb, Rgbf };
#[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!() }
pub fn to_rgbf(self) -> Rgbf { todo!() }
}
/// Wraps a hue in degrees into `0..360`.
/// `rem_euclid` rounds tiny negative input up to exactly 360, which is the same angle as 0.
pub(super) fn normalize_hue(h: f32) -> f32
{
let h = h.rem_euclid(360.0);
if h >= 360.0 { 0.0 } else { h }
}
+24
View File
@@ -0,0 +1,24 @@
use super::{ Rgb, Rgbf };
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 to_rgbf(self) -> Rgbf { todo!() }
pub fn luminance(self) -> f32 { todo!() }
}
impl Lerp for LinearRgb
{
fn lerp(&self, _to: &Self, _t: f32) -> Self { todo!() }
}
+16
View File
@@ -0,0 +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;
+13
View File
@@ -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 {}
+229
View File
@@ -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<Self>
{
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<Self, Self::Err> { 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<Rgb> for [u8; 3]
{
fn from(c: Rgb) -> Self { [c.r, c.g, c.b] }
}
impl From<Rgb> for (u8, u8, u8)
{
fn from(c: Rgb) -> Self { (c.r, c.g, c.b) }
}
impl From<Rgb> for Rgbf
{
fn from(c: Rgb) -> Self { c.to_rgbf() }
}
impl From<Rgb> for LinearRgb
{
fn from(c: Rgb) -> Self { c.to_linear() }
}
impl From<Rgb> for Hsv
{
fn from(c: Rgb) -> Self { c.to_hsv() }
}
impl From<Rgb> for Hsl
{
fn from(c: Rgb) -> Self { c.to_hsl() }
}
impl From<Rgbf> for Rgb
{
fn from(c: Rgbf) -> Self { c.to_rgb() }
}
impl From<LinearRgb> for Rgb
{
fn from(c: LinearRgb) -> Self { c.to_rgb() }
}
impl From<Hsv> for Rgb
{
fn from(c: Hsv) -> Self { c.to_rgb() }
}
impl From<Hsl> 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 }
+163
View File
@@ -0,0 +1,163 @@
use std::ops::{ Add, Sub, Mul, Div };
use super::transfer;
use super::rgb::unit_to_u8;
use super::hsv::normalize_hue;
use super::{ Rgb, LinearRgb, Hsv, Hsl };
use crate::smooth::Lerp;
/// An sRGB colour with `f32` channels, nominally in `0..=1`.
/// Still gamma-compressed like `Rgb`; this is the space HSV and HSL are defined in.
/// Blend and average in `LinearRgb` instead.
#[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
{
#[must_use]
pub const fn new(r: f32, g: f32, b: f32) -> Self { Self { r, g, b } }
/// Rounds each channel to a byte, clamping to `0..=1` first.
/// NaN gives 0.
#[must_use]
pub fn to_rgb(self) -> Rgb { Rgb::new(unit_to_u8(self.r), unit_to_u8(self.g), unit_to_u8(self.b)) }
/// Decodes the colour to linear light.
#[must_use]
pub fn to_linear(self) -> LinearRgb
{
LinearRgb {
r: transfer::srgb_to_linear(self.r),
g: transfer::srgb_to_linear(self.g),
b: transfer::srgb_to_linear(self.b),
}
}
/// Clamps each channel to `0..=1`.
#[must_use]
pub const fn clamp(self) -> Self
{
Self::new(self.r.clamp(0.0, 1.0), self.g.clamp(0.0, 1.0), self.b.clamp(0.0, 1.0))
}
#[must_use]
pub fn to_hsv(self) -> Hsv
{
let (h, max, min) = self.hue_max_min();
let s = if max <= f32::EPSILON { 0.0 } else { (max - min) / max };
Hsv { h, s, v: max }
}
#[must_use]
pub fn to_hsl(self) -> Hsl
{
let (h, max, min) = self.hue_max_min();
let delta = max - min;
let l = (max + min) / 2.0;
let s = if delta < f32::EPSILON { 0.0 } else { delta / (max + min).min(2.0 - max - min) };
Hsl { h, s, l }
}
/// The hue in degrees, plus the largest and smallest channel.
/// HSV and HSL share the hue; they only differ in how they turn max and min into the other two values.
fn hue_max_min(self) -> (f32, f32, f32)
{
let Self { r, g, b } = self;
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let delta = max - min;
let h = if delta < f32::EPSILON { 0.0 }
else if max == r { 60.0 * ((g - b) / delta).rem_euclid(6.0) }
else if max == g { 60.0 * ((b - r) / delta + 2.0) }
else { 60.0 * ((r - g) / delta + 4.0) };
(normalize_hue(h), max, min)
}
}
impl Lerp for Rgbf
{
fn lerp(&self, to: &Self, t: f32) -> Self { *self + (*to - *self) * t }
}
//
impl Add for Rgbf
{
type Output = Self;
fn add(self, o: Self) -> Self { Self::new(self.r + o.r, self.g + o.g, self.b + o.b) }
}
impl Sub for Rgbf
{
type Output = Self;
fn sub(self, o: Self) -> Self { Self::new(self.r - o.r, self.g - o.g, self.b - o.b) }
}
impl Mul<f32> for Rgbf
{
type Output = Self;
fn mul(self, k: f32) -> Self { Self::new(self.r * k, self.g * k, self.b * k) }
}
impl Div<f32> for Rgbf
{
type Output = Self;
fn div(self, k: f32) -> Self { Self::new(self.r / k, self.g / k, self.b / k) }
}
//
impl From<[f32; 3]> for Rgbf
{
fn from([r, g, b]: [f32; 3]) -> Self { Rgbf::new(r, g, b) }
}
impl From<Rgbf> for [f32; 3]
{
fn from(c: Rgbf) -> Self { [c.r, c.g, c.b] }
}
impl From<Rgbf> for LinearRgb
{
fn from(c: Rgbf) -> Self { c.to_linear() }
}
impl From<Rgbf> for Hsv
{
fn from(c: Rgbf) -> Self { c.to_hsv() }
}
impl From<Rgbf> for Hsl
{
fn from(c: Rgbf) -> Self { c.to_hsl() }
}
impl From<LinearRgb> for Rgbf
{
fn from(c: LinearRgb) -> Self { c.to_rgbf() }
}
impl From<Hsv> for Rgbf
{
fn from(c: Hsv) -> Self { c.to_rgbf() }
}
impl From<Hsl> for Rgbf
{
fn from(c: Hsl) -> Self { c.to_rgbf() }
}
+31
View File
@@ -0,0 +1,31 @@
/// `srgb_to_linear` of every `u8` channel value, generated by `build.rs`.
static LUT: [f32; 256] = include!(concat!(env!("OUT_DIR"), "/srgb_lut.rs"));
/// Decodes one sRGB-encoded channel to linear light.
///
/// sRGB (IEC 61966-2-1) stores values gamma-compressed, so more of the 0..=255 range
/// goes to dark tones, where the eye is most sensitive. The curve has two pieces:
/// - Near black it is a straight line with slope 1 / 12.92. A pure power curve has slope 0
/// at black, and its inverse an infinite slope, which makes both directions unstable there.
/// - Everywhere else it is a power curve with exponent 2.4. The 0.055 offset shifts it
/// so it meets the line at 0.04045, and overall it behaves like a plain gamma of about 2.2.
pub(super) fn srgb_to_linear(c: f32) -> f32
{
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}
/// Encodes one linear-light channel to sRGB.
///
/// The exact inverse of `srgb_to_linear`: the same line and power curve, solved for the
/// other side. 0.0031308 is the old threshold 0.04045 mapped into linear light (0.04045 / 12.92).
pub(super) fn linear_to_srgb(l: f32) -> f32
{
if l <= 0.0031308 { 12.92 * l } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 }
}
/// Decodes one `u8` sRGB channel to linear light through a lookup table.
pub(super) fn srgb_u8_to_linear(c: u8) -> f32 { LUT[c as usize] }
/// Encodes one linear-light channel to a `u8` sRGB channel.
/// Out-of-range input clamps, and NaN gives 0.
pub(super) fn linear_to_srgb_u8(l: f32) -> u8 { (linear_to_srgb(l).clamp(0.0, 1.0) * 255.0).round() as u8 }
+7
View File
@@ -0,0 +1,7 @@
pub mod color;
pub mod smooth;
// ------
pub use color::{ Rgb, Rgbf, LinearRgb, Hsv, Hsl };
pub use smooth::Lerp;
+5
View File
@@ -0,0 +1,5 @@
// PLACEHOLDER: only the trait; see SPEC §10.
pub trait Lerp {
fn lerp(&self, to: &Self, t: f32) -> Self;
}
+5
View File
@@ -0,0 +1,5 @@
mod lerp;
// ------
pub use lerp::Lerp;