chromashift/
linear_rgb.rs1use crate::{ToAlpha, XyzD65, round_dp};
2use core::fmt;
3
4#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct LinearRgb {
12 pub red: f64,
13 pub green: f64,
14 pub blue: f64,
15 pub alpha: f32,
16}
17
18impl LinearRgb {
19 pub fn new(red: f64, green: f64, blue: f64, alpha: f32) -> Self {
20 Self { red, green, blue, alpha: alpha.clamp(0.0, 100.0) }
21 }
22}
23
24impl ToAlpha for LinearRgb {
25 fn to_alpha(&self) -> f32 {
26 self.alpha
27 }
28}
29
30impl fmt::Display for LinearRgb {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 let Self { red, green, blue, alpha } = self;
33 write!(f, "color(srgb-linear {} {}% {}%", round_dp(*red, 2), round_dp(*green, 2), round_dp(*blue, 2))?;
34 if *alpha < 100.0 {
35 write!(f, " / {}", round_dp(*alpha as f64, 2))?;
36 }
37 write!(f, ")")
38 }
39}
40
41impl From<XyzD65> for LinearRgb {
42 fn from(value: XyzD65) -> Self {
43 let XyzD65 { x, y, z, alpha } = value;
44 let x = x / 100.0;
45 let y = y / 100.0;
46 let z = z / 100.0;
47 let red = x * (12831.0 / 3959.0) + y * (-329.0 / 214.0) + z * (-1974.0 / 3959.0);
48 let green = x * (-851781.0 / 878810.0) + y * (1648619.0 / 878810.0) + z * (36519.0 / 878810.0);
49 let blue = x * (705.0 / 12673.0) + y * (-2585.0 / 12673.0) + z * (705.0 / 667.0);
50 LinearRgb::new(red, green, blue, alpha)
51 }
52}
53
54impl From<LinearRgb> for XyzD65 {
55 fn from(value: LinearRgb) -> Self {
56 let LinearRgb { red, green, blue, alpha } = value;
57 let x = red * (506752.0 / 1228815.0) + green * (87881.0 / 245763.0) + blue * (12673.0 / 70218.0);
58 let y = red * (87098.0 / 409605.0) + green * (175762.0 / 245763.0) + blue * (12673.0 / 175545.0);
59 let z = red * (7918.0 / 409605.0) + green * (87881.0 / 737289.0) + blue * (1001167.0 / 1053270.0);
60 XyzD65::new(x * 100.0, y * 100.0, z * 100.0, alpha)
61 }
62}