chromashift/
hsb.rs

1use crate::{Srgb, ToAlpha};
2use core::fmt;
3
4/// An colour represented as Hue, Saturation, and Value expressed in the sRGB colour space.
5/// The components are:
6/// - Hue - a number between 0.0 and 360.0
7/// - Saturation - a number between 0.0 and 100.0
8/// - Value / Brightness - 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 Hsv {
12	pub hue: f32,
13	pub saturation: f32,
14	pub value: f32,
15	pub alpha: f32,
16}
17
18impl Hsv {
19	pub fn new(hue: f32, saturation: f32, value: f32, alpha: f32) -> Self {
20		Self {
21			hue: hue.rem_euclid(360.0),
22			saturation: saturation.clamp(0.0, 100.0),
23			value: value.clamp(0.0, 100.0),
24			alpha: alpha.clamp(0.0, 100.0),
25		}
26	}
27}
28
29impl ToAlpha for Hsv {
30	fn to_alpha(&self) -> f32 {
31		self.alpha
32	}
33}
34
35impl fmt::Display for Hsv {
36	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37		let Self { hue, saturation, value, alpha } = self;
38		write!(f, "hsv({hue} {saturation} {value}")?;
39		if *alpha < 100.0 {
40			write!(f, " / {alpha}")?;
41		}
42		write!(f, ")")
43	}
44}
45
46impl From<Srgb> for Hsv {
47	fn from(value: Srgb) -> Self {
48		let r = value.red as f32 / 255.0;
49		let g = value.green as f32 / 255.0;
50		let b = value.blue as f32 / 255.0;
51		let max = r.max(g).max(b);
52		let min = r.min(g).min(b);
53		let delta = max - min;
54		let v = max;
55		let saturation = if max == 0.0 { 0.0 } else { delta / max };
56		let hue = if delta == 0.0 {
57			0.0
58		} else if max == r {
59			60.0 * (((g - b) / delta) % 6.0)
60		} else if max == g {
61			60.0 * ((b - r) / delta + 2.0)
62		} else {
63			60.0 * ((r - g) / delta + 4.0)
64		};
65		let hue = if hue < 0.0 { hue + 360.0 } else { hue };
66		Hsv::new(hue, saturation * 100.0, v * 100.0, value.alpha)
67	}
68}
69
70impl From<Hsv> for Srgb {
71	fn from(value: Hsv) -> Self {
72		let h = value.hue / 60.0;
73		let s = value.saturation / 100.0;
74		let v = value.value / 100.0;
75		let c = v * s;
76		let x = c * (1.0 - (h % 2.0 - 1.0).abs());
77		let m = v - c;
78		let (r_prime, g_prime, b_prime) = if h < 1.0 {
79			(c, x, 0.0)
80		} else if h < 2.0 {
81			(x, c, 0.0)
82		} else if h < 3.0 {
83			(0.0, c, x)
84		} else if h < 4.0 {
85			(0.0, x, c)
86		} else if h < 5.0 {
87			(x, 0.0, c)
88		} else {
89			(c, 0.0, x)
90		};
91		Srgb::new(
92			((r_prime + m) * 255.0).clamp(0.0, 255.0).round() as u8,
93			((g_prime + m) * 255.0).clamp(0.0, 255.0).round() as u8,
94			((b_prime + m) * 255.0).clamp(0.0, 255.0).round() as u8,
95			value.alpha,
96		)
97	}
98}