Skip to main content

three_rs/math/
color_management.rs

1//! Port of `three.js/src/math/ColorManagement.js`.
2//!
3//! Only the singleton surface lives here: the transfer functions themselves
4//! (`SRGBToLinear` / `LinearToSRGB`) are already ported in
5//! [`crate::math::srgb_to_linear`] / [`crate::math::linear_to_srgb`], and
6//! [`Color`] already routes its own `setRGB`/`getRGB` through them, so this
7//! module reuses those rather than duplicating the curves.
8//!
9//! three.js' `ColorManagement` is a mutable module-level singleton. Rust has no
10//! mutable global without synchronisation, so it is a plain value here:
11//! `ColorManagement::default()` is three.js' singleton state (`enabled: true`,
12//! `workingColorSpace: LinearSRGBColorSpace`), and the caller owns it.
13
14use super::color::{linear_to_srgb, srgb_to_linear};
15use super::{Color, Matrix3};
16
17/// `LINEAR_REC709_TO_XYZ`.
18pub fn linear_rec709_to_xyz() -> Matrix3 {
19    *Matrix3::identity().set(
20        0.4123908, 0.3575843, 0.1804808, //
21        0.2126390, 0.7151687, 0.0721923, //
22        0.0193308, 0.1191948, 0.9505322,
23    )
24}
25
26/// `XYZ_TO_LINEAR_REC709`.
27pub fn xyz_to_linear_rec709() -> Matrix3 {
28    *Matrix3::identity().set(
29        3.2409699, -1.5373832, -0.4986108, //
30        -0.9692436, 1.8759675, 0.0415551, //
31        0.0556301, -0.2039770, 1.0569715,
32    )
33}
34
35/// `REC709_PRIMARIES`: chromaticity coordinates `[ rx ry gx gy bx by ]`.
36pub const REC709_PRIMARIES: [f64; 6] = [0.640, 0.330, 0.300, 0.600, 0.150, 0.060];
37
38/// `REC709_LUMINANCE_COEFFICIENTS`.
39pub const REC709_LUMINANCE_COEFFICIENTS: [f64; 3] = [0.2126, 0.7152, 0.0722];
40
41/// The colour spaces `constants.js` names, as far as the port needs them.
42///
43/// three.js spells a colour space as a string constant, and one set of
44/// constants is shared by `ColorManagement`, `Color`'s `set*`/`get*`
45/// methods, `Texture.colorSpace` and `renderer.outputColorSpace`. This enum is
46/// that set, and the one type all four take.
47///
48/// `ColorManagement` defines the two spaces three.js registers by default:
49/// linear sRGB (the working space) and sRGB. Display P3 and the other spaces
50/// in `addons/math/ColorSpaces.js` are not ported, which is why the enum is
51/// `#[non_exhaustive]`. The KTX2 loader reports what a file declares in its
52/// own [`Ktx2ColorSpace`](crate::loaders::Ktx2ColorSpace), which does have P3.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum ColorSpace {
56    /// `NoColorSpace` (`''`): no colour space at all. `ColorManagement`
57    /// converts nothing to or from it, and a texture tagged with it is sampled
58    /// with no transfer function. It is `Texture.colorSpace`'s default.
59    NoColorSpace,
60    /// `SRGBColorSpace` (`'srgb'`): Rec. 709 primaries, sRGB transfer.
61    Srgb,
62    /// `LinearSRGBColorSpace` (`'srgb-linear'`): Rec. 709 primaries, linear
63    /// transfer. `ColorManagement.workingColorSpace`.
64    LinearSrgb,
65}
66
67impl ColorSpace {
68    /// `spaces[ colorSpace ].transfer`, with `NoColorSpace` answering
69    /// `LinearTransfer` as `ColorManagement.getTransfer()` does.
70    pub(crate) fn transfer(self) -> Transfer {
71        match self {
72            ColorSpace::Srgb => Transfer::Srgb,
73            ColorSpace::LinearSrgb | ColorSpace::NoColorSpace => Transfer::Linear,
74        }
75    }
76}
77
78/// The transfer functions `constants.js` names, i.e. `LinearTransfer` and
79/// `SRGBTransfer`.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum Transfer {
82    /// `LinearTransfer`.
83    Linear,
84    /// `SRGBTransfer`.
85    Srgb,
86}
87
88/// `ColorManagement`.
89#[derive(Clone, Copy, Debug, PartialEq)]
90pub struct ColorManagement {
91    /// `ColorManagement.enabled`.
92    pub enabled: bool,
93    /// `ColorManagement.workingColorSpace`.
94    pub working_color_space: ColorSpace,
95}
96
97impl Default for ColorManagement {
98    fn default() -> Self {
99        Self {
100            enabled: true,
101            working_color_space: ColorSpace::LinearSrgb,
102        }
103    }
104}
105
106impl ColorManagement {
107    /// `ColorManagement.convert()`. It is a no-op when either space is
108    /// [`ColorSpace::NoColorSpace`], three.js' falsy `''`.
109    pub fn convert(
110        &self,
111        color: &mut Color,
112        source_color_space: ColorSpace,
113        target_color_space: ColorSpace,
114    ) {
115        if !self.enabled
116            || source_color_space == target_color_space
117            || source_color_space == ColorSpace::NoColorSpace
118            || target_color_space == ColorSpace::NoColorSpace
119        {
120            return;
121        }
122
123        if Self::space_transfer(source_color_space) == Transfer::Srgb {
124            color.r = srgb_to_linear(color.r);
125            color.g = srgb_to_linear(color.g);
126            color.b = srgb_to_linear(color.b);
127        }
128
129        if Self::space_primaries(source_color_space) != Self::space_primaries(target_color_space) {
130            color.apply_matrix3(&Self::space_to_xyz(source_color_space));
131            color.apply_matrix3(&Self::space_from_xyz(target_color_space));
132        }
133
134        if Self::space_transfer(target_color_space) == Transfer::Srgb {
135            color.r = linear_to_srgb(color.r);
136            color.g = linear_to_srgb(color.g);
137            color.b = linear_to_srgb(color.b);
138        }
139    }
140
141    /// `ColorManagement.workingToColorSpace()`.
142    pub fn working_to_color_space(&self, color: &mut Color, target_color_space: ColorSpace) {
143        self.convert(color, self.working_color_space, target_color_space);
144    }
145
146    /// `ColorManagement.colorSpaceToWorking()`.
147    pub fn color_space_to_working(&self, color: &mut Color, source_color_space: ColorSpace) {
148        self.convert(color, source_color_space, self.working_color_space);
149    }
150
151    /// `ColorManagement.getPrimaries()`. Both defined spaces have Rec. 709
152    /// primaries. `NoColorSpace` has none, and three.js' lookup would throw;
153    /// here it answers Rec. 709 too.
154    pub fn get_primaries(&self, color_space: ColorSpace) -> [f64; 6] {
155        Self::space_primaries(color_space)
156    }
157
158    /// `ColorManagement.getTransfer()`: `NoColorSpace` answers
159    /// `LinearTransfer`, as in three.js.
160    pub fn get_transfer(&self, color_space: ColorSpace) -> Transfer {
161        color_space.transfer()
162    }
163
164    /// `ColorManagement.getLuminanceCoefficients()`; `None` means the working
165    /// colour space, as in three.js' default argument.
166    pub fn get_luminance_coefficients(&self, color_space: Option<ColorSpace>) -> [f64; 3] {
167        let _ = color_space.unwrap_or(self.working_color_space);
168        REC709_LUMINANCE_COEFFICIENTS
169    }
170
171    /// `spaces[ colorSpace ].primaries`.
172    fn space_primaries(_color_space: ColorSpace) -> [f64; 6] {
173        REC709_PRIMARIES
174    }
175
176    /// `spaces[ colorSpace ].transfer`.
177    fn space_transfer(color_space: ColorSpace) -> Transfer {
178        color_space.transfer()
179    }
180
181    /// `spaces[ colorSpace ].toXYZ`.
182    fn space_to_xyz(_color_space: ColorSpace) -> Matrix3 {
183        linear_rec709_to_xyz()
184    }
185
186    /// `spaces[ colorSpace ].fromXYZ`.
187    fn space_from_xyz(_color_space: ColorSpace) -> Matrix3 {
188        xyz_to_linear_rec709()
189    }
190}