Skip to main content

chromashift/
hwb.rs

1use crate::{Alpha, Hsl, Hsv, Number, Srgb, ToAlpha};
2use core::fmt;
3
4/// An colour represented as Hue, Whiteness, and Blackness expressed in the sRGB colour space.
5/// The components are:
6/// - Hue - a number between 0.0 and 360.0
7/// - Whiteness - a number between 0.0 and 100.0
8/// - Blackness - a number between 0.0 and 100.0
9/// - Alpha - a number between 0.0 and 100.0
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct Hwb {
12	pub hue: f64,
13	pub whiteness: f64,
14	pub blackness: f64,
15	pub alpha: f32,
16}
17
18impl Hwb {
19	pub fn new(hue: f64, whiteness: f64, blackness: f64, alpha: f32) -> Self {
20		Self { hue: hue.rem_euclid(360.0), whiteness, blackness, alpha: alpha.clamp(0.0, 100.0) }
21	}
22}
23
24impl ToAlpha for Hwb {
25	fn to_alpha(&self) -> f32 {
26		self.alpha
27	}
28}
29
30impl fmt::Display for Hwb {
31	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32		let Self { hue, whiteness, blackness, alpha } = *self;
33		write!(f, "hwb({} {}% {}%{})", Number(hue), Number(whiteness), Number(blackness), Alpha(alpha))
34	}
35}
36
37impl From<Hsv> for Hwb {
38	fn from(value: Hsv) -> Self {
39		let Hsv { hue, saturation, value, alpha } = value;
40		let s = saturation as f64 / 100.0;
41		let v = value as f64 / 100.0;
42		let whiteness = (1.0 - s) * v;
43		let blackness = 1.0 - v;
44		Hwb::new(hue as f64, whiteness * 100.0, blackness * 100.0, alpha)
45	}
46}
47
48impl From<Hwb> for Hsv {
49	fn from(value: Hwb) -> Self {
50		let Hwb { hue, whiteness, blackness, alpha } = value;
51		let w = whiteness / 100.0;
52		let b = blackness / 100.0;
53		let sum = w + b;
54		let (s, v) = if sum >= 1.0 {
55			(0.0, w / sum)
56		} else {
57			let v = 1.0 - b;
58			let s = if v == 0.0 { 0.0 } else { 1.0 - w / v };
59			(s, v)
60		};
61		Hsv::new(hue as f32, (s * 100.0) as f32, (v * 100.0) as f32, alpha)
62	}
63}
64
65impl From<Srgb> for Hwb {
66	fn from(value: Srgb) -> Self {
67		let Srgb { red, green, blue, alpha } = value;
68		let whiteness = red.min(green).min(blue);
69		let blackness = 1.0 - red.max(green).max(blue);
70		Hwb::new(value.hue(), whiteness * 100.0, blackness * 100.0, alpha)
71	}
72}
73
74impl From<Hwb> for Srgb {
75	fn from(value: Hwb) -> Self {
76		let Hwb { hue, whiteness, blackness, alpha } = value;
77		let (w, b) = (whiteness / 100.0, blackness / 100.0);
78		if w + b >= 1.0 {
79			let gray = w / (w + b);
80			return Srgb::new(gray, gray, gray, alpha);
81		}
82		let Srgb { red, green, blue, .. } = Hsl::new(hue, 100.0, 50.0, alpha).into();
83		let scale = 1.0 - w - b;
84		Srgb::new(red * scale + w, green * scale + w, blue * scale + w, alpha)
85	}
86}