palette 0.7.7

Convert and manage colors with a focus on correctness, flexibility and ease of use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use core::marker::PhantomData;

use crate::{
    bool_mask::HasBoolMask,
    convert::{ConvertOnce, FromColorUnclamped, Matrix3},
    num::{Arithmetics, Zero},
    stimulus::{FromStimulus, Stimulus, StimulusColor},
    xyz::meta::HasXyzMeta,
    Alpha, Xyz,
};

use super::matrix::{HasLmsMatrix, XyzToLms};

/// Generic LMS with an alpha component. See [`Lmsa` implementation in
/// `Alpha`][crate::Alpha#Lmsa].
pub type Lmsa<M, T> = Alpha<Lms<M, T>, T>;

/// Generic LMS.
///
/// LMS represents the response of the eye's cone cells. L, M and S are for
/// "long", "medium" and "short" wavelengths, roughly corresponding to red,
/// green and blue. Many newer mentions of an LMS representation use the letters
/// R, G and B instead (or sometimes ρ, γ, β), but this library sticks to LMS to
/// differentiate it from [`Rgb`][crate::rgb::Rgb].
///
/// The LMS color space is a model of the physiological response to color
/// stimuli. It has some mathematical shortcomings that [`Xyz`] improves on,
/// such as severe spectral sensitivity overlap between L, M and S. Despite
/// this, LMS has a lot of uses, include chromatic adaptation and emulating
/// different types of color vision deficiency, and it's sometimes part of the
/// conversion process between other color spaces.
///
/// # Creating a Value
///
/// An LMS value is often derived from another color space, through a conversion
/// matrix. Two such matrices are [`VonKries`][super::matrix::VonKries] and
/// [`Bradford`][super::matrix::Bradford], and Palette offers type aliases in the
/// [`lms`][crate::lms] module to make using them a bit more convenient. It's of
/// course also possible to simply use [`Lms::new`], but it may not be as
/// intuitive.
///
/// ```
/// use palette::{
///     lms::{Lms, VonKriesLms, matrix::VonKries},
///     white_point::D65,
///     Srgb, FromColor
/// };
///
/// let von_kries_lms = Lms::<VonKries, f32>::new(0.1, 0.2, 0.3);
/// let von_kries_d65_lms = VonKriesLms::<D65, f32>::new(0.1, 0.2, 0.3);
///
/// // `new` is also `const`:
/// const VON_KRIES_LMS: Lms<VonKries, f32> = Lms::new(0.1, 0.2, 0.3);
///
/// // Von Kries LMS from sRGB:
/// let lms_from_srgb = VonKriesLms::<D65, f32>::from_color(Srgb::new(0.3f32, 0.8, 0.1));
///
/// // It's also possible to convert from (and to) arrays and tuples:
/// let lms_from_array = VonKriesLms::<D65, f32>::from([0.1, 0.2, 0.3]);
/// let lms_from_tuple = VonKriesLms::<D65, f32>::from((0.1, 0.2, 0.3));
/// ```
#[derive(Debug, ArrayCast, FromColorUnclamped, WithAlpha)]
#[cfg_attr(feature = "serializing", derive(Serialize, Deserialize))]
#[palette(palette_internal, component = "T", skip_derives(Lms, Xyz))]
#[repr(C)]
pub struct Lms<M, T> {
    /// Stimulus from long wavelengths, or red, or ρ. The typical range is
    /// between 0.0 and 1.0, but it doesn't have an actual upper bound.
    pub long: T,

    /// Stimulus from medium wavelengths, or green, or γ. The typical range is
    /// between 0.0 and 1.0, but it doesn't have an actual upper bound.
    pub medium: T,

    /// Stimulus from short wavelengths, or blue, or β. The typical range is
    /// between 0.0 and 1.0, but it doesn't have an actual upper bound.
    pub short: T,

    /// Type level meta information, such as reference white, or which matrix
    /// was used when converting from XYZ.
    #[cfg_attr(feature = "serializing", serde(skip))]
    #[palette(unsafe_zero_sized)]
    pub meta: PhantomData<M>,
}

impl<M, T> Lms<M, T> {
    /// Create a new LMS color.
    pub const fn new(long: T, medium: T, short: T) -> Self {
        Self {
            long,
            medium,
            short,
            meta: PhantomData,
        }
    }

    /// Convert the LMS components into another number type.
    ///
    /// ```
    /// use palette::{
    ///     lms::VonKriesLms,
    ///     white_point::D65,
    /// };
    ///
    /// let lms_f64: VonKriesLms<D65, f64> = VonKriesLms::new(0.3f32, 0.7, 0.2).into_format();
    /// ```
    pub fn into_format<U>(self) -> Lms<M, U>
    where
        U: FromStimulus<T>,
    {
        Lms {
            long: U::from_stimulus(self.long),
            medium: U::from_stimulus(self.medium),
            short: U::from_stimulus(self.short),
            meta: PhantomData,
        }
    }

    /// Convert the LMS components from another number type.
    ///
    /// ```
    /// use palette::{
    ///     lms::VonKriesLms,
    ///     white_point::D65,
    /// };
    ///
    /// let lms_f64 = VonKriesLms::<D65, f64>::from_format(VonKriesLms::new(0.3f32, 0.7, 0.2));
    /// ```
    pub fn from_format<U>(color: Lms<M, U>) -> Self
    where
        T: FromStimulus<U>,
    {
        color.into_format()
    }

    /// Convert to a `(long, medium, short)` tuple.
    pub fn into_components(self) -> (T, T, T) {
        (self.long, self.medium, self.short)
    }

    /// Convert from a `(long, medium, short)` tuple.
    pub fn from_components((long, medium, short): (T, T, T)) -> Self {
        Self::new(long, medium, short)
    }

    /// Changes the meta type without changing the color value.
    ///
    /// This function doesn't change the numerical values, and thus the stimuli
    /// it represents in an absolute sense. However, the appearance of the color
    /// may not be the same. The effect may be similar to taking a photo with an
    /// incorrect white balance.
    pub fn with_meta<NewM>(self) -> Lms<NewM, T> {
        Lms {
            long: self.long,
            medium: self.medium,
            short: self.short,
            meta: PhantomData,
        }
    }
}

impl<M, T> Lms<M, T>
where
    T: Zero,
{
    /// Return the `short` value minimum.
    pub fn min_short() -> T {
        T::zero()
    }

    /// Return the `medium` value minimum.
    pub fn min_medium() -> T {
        T::zero()
    }

    /// Return the `long` value minimum.
    pub fn min_long() -> T {
        T::zero()
    }
}

impl<M, T> Lms<M, T> {
    /// Produce a conversion matrix from [`Xyz`] to [`Lms`].
    #[inline]
    pub fn matrix_from_xyz() -> Matrix3<Xyz<M::XyzMeta, T>, Self>
    where
        M: HasXyzMeta + HasLmsMatrix,
        M::LmsMatrix: XyzToLms<T>,
    {
        Matrix3::from_array(M::LmsMatrix::xyz_to_lms_matrix())
    }
}

/// <span id="Lmsa"></span>[`Lmsa`][Lmsa] implementations.
impl<S, T, A> Alpha<Lms<S, T>, A> {
    /// Create an LMSA color.
    pub const fn new(red: T, green: T, blue: T, alpha: A) -> Self {
        Alpha {
            color: Lms::new(red, green, blue),
            alpha,
        }
    }

    /// Convert the LMSA components into other number types.
    ///
    /// ```
    /// use palette::{
    ///     lms::VonKriesLmsa,
    ///     white_point::D65,
    /// };
    ///
    /// let lmsa_f64: VonKriesLmsa<D65, f64> = VonKriesLmsa::new(0.3f32, 0.7, 0.2, 0.5).into_format();
    /// ```
    pub fn into_format<U, B>(self) -> Alpha<Lms<S, U>, B>
    where
        U: FromStimulus<T>,
        B: FromStimulus<A>,
    {
        Alpha {
            color: self.color.into_format(),
            alpha: B::from_stimulus(self.alpha),
        }
    }

    /// Convert the LMSA components from other number types.
    ///
    /// ```
    /// use palette::{
    ///     lms::VonKriesLmsa,
    ///     white_point::D65,
    /// };
    ///
    /// let lmsa_f64 = VonKriesLmsa::<D65, f64>::from_format(VonKriesLmsa::new(0.3f32, 0.7, 0.2, 0.5));
    /// ```
    pub fn from_format<U, B>(color: Alpha<Lms<S, U>, B>) -> Self
    where
        T: FromStimulus<U>,
        A: FromStimulus<B>,
    {
        color.into_format()
    }

    /// Convert to a `(long, medium, short, alpha)` tuple.
    pub fn into_components(self) -> (T, T, T, A) {
        (
            self.color.long,
            self.color.medium,
            self.color.short,
            self.alpha,
        )
    }

    /// Convert from a `(long, medium, short, alpha)` tuple.
    pub fn from_components((long, medium, short, alpha): (T, T, T, A)) -> Self {
        Self::new(long, medium, short, alpha)
    }

    /// Changes the meta type without changing the color value.
    ///
    /// This function doesn't change the numerical values, and thus the stimuli
    /// it represents in an absolute sense. However, the appearance of the color
    /// may not be the same. The effect may be similar to taking a photo with an
    /// incorrect white balance.
    pub fn with_meta<NewM>(self) -> Alpha<Lms<NewM, T>, A> {
        Alpha {
            color: self.color.with_meta(),
            alpha: self.alpha,
        }
    }
}

impl<M, T> FromColorUnclamped<Lms<M, T>> for Lms<M, T> {
    #[inline]
    fn from_color_unclamped(val: Lms<M, T>) -> Self {
        val
    }
}

impl<M, T> FromColorUnclamped<Xyz<M::XyzMeta, T>> for Lms<M, T>
where
    M: HasLmsMatrix + HasXyzMeta,
    M::LmsMatrix: XyzToLms<T>,
    T: Arithmetics,
{
    #[inline]
    fn from_color_unclamped(val: Xyz<M::XyzMeta, T>) -> Self {
        Self::matrix_from_xyz().convert_once(val)
    }
}

impl<M, T> StimulusColor for Lms<M, T> where T: Stimulus {}

impl<M, T> HasBoolMask for Lms<M, T>
where
    T: HasBoolMask,
{
    type Mask = T::Mask;
}

impl<M, T> Default for Lms<M, T>
where
    T: Default,
{
    fn default() -> Lms<M, T> {
        Lms::new(T::default(), T::default(), T::default())
    }
}

impl<M> From<Lms<M, f32>> for Lms<M, f64> {
    #[inline]
    fn from(color: Lms<M, f32>) -> Self {
        color.into_format()
    }
}

impl<M> From<Lmsa<M, f32>> for Lmsa<M, f64> {
    #[inline]
    fn from(color: Lmsa<M, f32>) -> Self {
        color.into_format()
    }
}

impl<M> From<Lms<M, f64>> for Lms<M, f32> {
    #[inline]
    fn from(color: Lms<M, f64>) -> Self {
        color.into_format()
    }
}

impl<M> From<Lmsa<M, f64>> for Lmsa<M, f32> {
    #[inline]
    fn from(color: Lmsa<M, f64>) -> Self {
        color.into_format()
    }
}

#[cfg(feature = "bytemuck")]
unsafe impl<M, T> bytemuck::Zeroable for Lms<M, T> where T: bytemuck::Zeroable {}

#[cfg(feature = "bytemuck")]
unsafe impl<M: 'static, T> bytemuck::Pod for Lms<M, T> where T: bytemuck::Pod {}

impl_reference_component_methods!(Lms<M>, [long, medium, short], meta);
impl_struct_of_arrays_methods!(Lms<M>, [long, medium, short], meta);

impl_is_within_bounds! {
    Lms<M> {
        long => [Self::min_long(), None],
        medium => [Self::min_medium(), None],
        short => [Self::min_short(), None]
    }
    where T: Stimulus
}
impl_clamp! {
    Lms<M> {
        long => [Self::min_long()],
        medium => [Self::min_medium()],
        short => [Self::min_short()]
    }
    other {meta}
    where T: Stimulus
}

impl_mix!(Lms<M>);
impl_premultiply!(Lms<M> {long, medium, short} phantom: meta);
impl_euclidean_distance!(Lms<M> {long, medium, short});

impl_color_add!(Lms<M>, [long, medium, short], meta);
impl_color_sub!(Lms<M>, [long, medium, short], meta);
impl_color_mul!(Lms<M>, [long, medium, short], meta);
impl_color_div!(Lms<M>, [long, medium, short], meta);

impl_tuple_conversion!(Lms<M> as (T, T, T));
impl_array_casts!(Lms<M, T>, [T; 3]);
impl_simd_array_conversion!(Lms<M>, [long, medium, short], meta);
impl_struct_of_array_traits!(Lms<M>, [long, medium, short], meta);

impl_eq!(Lms<M>, [long, medium, short]);
impl_copy_clone!(Lms<M>, [long, medium, short], meta);

impl_rand_traits_cartesian!(UniformLms, Lms<M> {long, medium, short} phantom: meta: PhantomData<M>);

#[cfg(test)]
mod test {
    use crate::{lms::VonKriesLms, white_point::D65};

    #[cfg(feature = "alloc")]
    use super::Lmsa;

    #[cfg(feature = "random")]
    use super::Lms;

    #[cfg(feature = "approx")]
    use crate::{convert::FromColorUnclamped, lms::BradfordLms, Xyz};

    test_convert_into_from_xyz!(VonKriesLms<D65, f32>);
    raw_pixel_conversion_tests!(VonKriesLms<D65>: long, medium, short);
    raw_pixel_conversion_fail_tests!(VonKriesLms<D65>: long, medium, short);

    #[cfg(feature = "approx")]
    #[test]
    fn von_kries_xyz_roundtrip() {
        let xyz = Xyz::new(0.2f32, 0.4, 0.8);
        let lms = VonKriesLms::<D65, _>::from_color_unclamped(xyz);
        assert_relative_eq!(Xyz::from_color_unclamped(lms), xyz);
    }

    #[cfg(feature = "approx")]
    #[test]
    fn bradford_xyz_roundtrip() {
        let xyz = Xyz::new(0.2f32, 0.4, 0.8);
        let lms = BradfordLms::<D65, _>::from_color_unclamped(xyz);
        assert_relative_eq!(Xyz::from_color_unclamped(lms), xyz);
    }

    #[cfg(feature = "serializing")]
    #[test]
    fn serialize() {
        let serialized =
            ::serde_json::to_string(&VonKriesLms::<D65, f32>::new(0.3, 0.8, 0.1)).unwrap();

        assert_eq!(serialized, r#"{"long":0.3,"medium":0.8,"short":0.1}"#);
    }

    #[cfg(feature = "serializing")]
    #[test]
    fn deserialize() {
        let deserialized: VonKriesLms<D65, f32> =
            ::serde_json::from_str(r#"{"long":0.3,"medium":0.8,"short":0.1}"#).unwrap();

        assert_eq!(deserialized, VonKriesLms::<D65, f32>::new(0.3, 0.8, 0.1));
    }

    struct_of_arrays_tests!(
        VonKriesLms<D65>[long, medium, short] phantom: meta,
        Lmsa::new(0.1f32, 0.2, 0.3, 0.4),
        Lmsa::new(0.2, 0.3, 0.4, 0.5),
        Lmsa::new(0.3, 0.4, 0.5, 0.6)
    );

    test_uniform_distribution! {
        VonKriesLms<D65, f32> {
            long: (0.0, 1.0),
            medium: (0.0, 1.0),
            short: (0.0, 1.0)
        },
        min: Lms::new(0.0f32, 0.0, 0.0),
        max: Lms::new(1.0, 1.0, 1.0)
    }
}