use core::{ any::TypeId, convert::TryInto, fmt, marker::PhantomData, ops::{Add, Div}, }; use crate::{ bool_mask::{HasBoolMask, LazySelect}, cast::{ComponentOrder, Packed, UintCast}, color_difference::Wcag21RelativeContrast, convert::FromColorUnclamped, encoding::{FromLinear, IntoLinear, Linear, Srgb}, luma::LumaStandard, num::{Arithmetics, MinMax, PartialCmp, Real}, stimulus::{FromStimulus, Stimulus, StimulusColor}, white_point::D65, Alpha, IntoColor, Xyz, Yxy, }; /// Luminance with an alpha component. See the [`Lumaa` implementation /// in `Alpha`](crate::Alpha#Lumaa). pub type Lumaa = Alpha, T>; /// Luminance. /// /// Luma is a purely gray scale color space, which is included more for /// completeness than anything else, and represents how bright a color is /// perceived to be. It's basically the `Y` component of [CIE /// XYZ](crate::Xyz). The lack of any form of hue representation limits /// the set of operations that can be performed on it. #[derive(Debug, ArrayCast, FromColorUnclamped, WithAlpha)] #[cfg_attr(feature = "serializing", derive(Serialize, Deserialize))] #[palette( palette_internal, luma_standard = "S", component = "T", skip_derives(Xyz, Yxy, Luma) )] #[repr(C)] #[doc(alias = "gray")] #[doc(alias = "grey")] pub struct Luma { /// The lightness of the color. 0.0 is black and 1.0 is white. pub luma: T, /// The kind of RGB standard. sRGB is the default. #[cfg_attr(feature = "serializing", serde(skip))] #[palette(unsafe_zero_sized)] pub standard: PhantomData, } impl Luma { /// Create a luminance color. pub const fn new(luma: T) -> Luma { Luma { luma, standard: PhantomData, } } /// Convert into another component type. pub fn into_format(self) -> Luma where U: FromStimulus, { Luma { luma: U::from_stimulus(self.luma), standard: PhantomData, } } /// Convert from another component type. pub fn from_format(color: Luma) -> Self where T: FromStimulus, { color.into_format() } /// Convert to a `(luma,)` tuple. pub fn into_components(self) -> (T,) { (self.luma,) } /// Convert from a `(luma,)` tuple. pub fn from_components((luma,): (T,)) -> Self { Self::new(luma) } fn reinterpret_as(self) -> Luma where S: LumaStandard, S2: LumaStandard, { Luma { luma: self.luma, standard: PhantomData, } } } impl Luma where T: Stimulus, { /// Return the `luma` value minimum. pub fn min_luma() -> T { T::zero() } /// Return the `luma` value maximum. pub fn max_luma() -> T { T::max_intensity() } } impl Luma { /// Convert to a packed `u16` with with specifiable component order. /// /// ``` /// use palette::{luma, SrgbLuma}; /// /// let integer = SrgbLuma::new(96u8).into_u16::(); /// assert_eq!(0x60FF, integer); /// ``` /// /// It's also possible to use `From` and `Into`, which defaults to the /// `0xAALL` component order: /// /// ``` /// use palette::SrgbLuma; /// /// let integer = u16::from(SrgbLuma::new(96u8)); /// assert_eq!(0xFF60, integer); /// ``` /// /// See [Packed](crate::cast::Packed) for more details. #[inline] pub fn into_u16(self) -> u16 where O: ComponentOrder, u16>, { O::pack(Lumaa::from(self)) } /// Convert from a packed `u16` with specifiable component order. /// /// ``` /// use palette::{luma, SrgbLuma}; /// /// let luma = SrgbLuma::from_u16::(0x60FF); /// assert_eq!(SrgbLuma::new(96u8), luma); /// ``` /// /// It's also possible to use `From` and `Into`, which defaults to the /// `0xAALL` component order: /// /// ``` /// use palette::SrgbLuma; /// /// let luma = SrgbLuma::from(0x60u16); /// assert_eq!(SrgbLuma::new(96u8), luma); /// ``` /// /// See [Packed](crate::cast::Packed) for more details. #[inline] pub fn from_u16(color: u16) -> Self where O: ComponentOrder, u16>, { O::unpack(color).color } } impl Luma where S: LumaStandard, { /// Convert the color to linear luminance. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLuma, LinLuma}; /// /// let linear: LinLuma<_, f32> = SrgbLuma::new(96u8).into_linear(); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn into_linear(self) -> Luma, U> where S::TransferFn: IntoLinear, { Luma::new(S::TransferFn::into_linear(self.luma)) } /// Convert linear luminance to non-linear luminance. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLuma, LinLuma}; /// /// let encoded = SrgbLuma::::from_linear(LinLuma::new(0.95f32)); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn from_linear(color: Luma, U>) -> Luma where S::TransferFn: FromLinear, { Luma::new(S::TransferFn::from_linear(color.luma)) } } impl Luma, T> { /// Convert a linear color to a different encoding. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLuma, LinLuma}; /// /// let encoded: SrgbLuma = LinLuma::new(0.95f32).into_encoding(); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn into_encoding(self) -> Luma where St: LumaStandard, St::TransferFn: FromLinear, { Luma::::from_linear(self) } /// Convert from linear luminance from a different encoding. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLuma, LinLuma}; /// /// let linear = LinLuma::<_, f32>::from_encoding(SrgbLuma::new(96u8)); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn from_encoding(color: Luma) -> Self where St: LumaStandard, St::TransferFn: IntoLinear, { color.into_linear() } } // Safety: // // Luma is a transparent wrapper around its component, which fulfills the // requirements of UintCast. unsafe impl UintCast for Luma { type Uint = u8; } // Safety: // // Luma is a transparent wrapper around its component, which fulfills the // requirements of UintCast. unsafe impl UintCast for Luma { type Uint = u16; } // Safety: // // Luma is a transparent wrapper around its component, which fulfills the // requirements of UintCast. unsafe impl UintCast for Luma { type Uint = u32; } // Safety: // // Luma is a transparent wrapper around its component, which fulfills the // requirements of UintCast. unsafe impl UintCast for Luma { type Uint = u64; } // Safety: // // Luma is a transparent wrapper around its component, which fulfills the // requirements of UintCast. unsafe impl UintCast for Luma { type Uint = u128; } ///[`Lumaa`](crate::luma::Lumaa) implementations. impl Alpha, A> { /// Create a luminance color with transparency. pub const fn new(luma: T, alpha: A) -> Self { Alpha { color: Luma::new(luma), alpha, } } /// Convert into another component type. pub fn into_format(self) -> Alpha, B> where U: FromStimulus, B: FromStimulus, { Alpha { color: self.color.into_format(), alpha: B::from_stimulus(self.alpha), } } /// Convert from another component type. pub fn from_format(color: Alpha, B>) -> Self where T: FromStimulus, A: FromStimulus, { color.into_format() } /// Convert to a `(luma, alpha)` tuple. pub fn into_components(self) -> (T, A) { (self.color.luma, self.alpha) } /// Convert from a `(luma, alpha)` tuple. pub fn from_components((luma, alpha): (T, A)) -> Self { Self::new(luma, alpha) } } impl Lumaa { /// Convert to a packed `u16` with with a specific component order. /// /// ``` /// use palette::{luma, SrgbLumaa}; /// /// let integer = SrgbLumaa::new(96u8, 255).into_u16::(); /// assert_eq!(0xFF60, integer); /// ``` /// /// It's also possible to use `From` and `Into`, which defaults to the /// `0xLLAA` component order: /// /// ``` /// use palette::SrgbLumaa; /// /// let integer = u16::from(SrgbLumaa::new(96u8, 255)); /// assert_eq!(0x60FF, integer); /// ``` /// /// See [Packed](crate::cast::Packed) for more details. #[inline] pub fn into_u16(self) -> u16 where O: ComponentOrder, u16>, { O::pack(self) } /// Convert from a packed `u16` with a specific component order. /// /// ``` /// use palette::{luma, SrgbLumaa}; /// /// let luma = SrgbLumaa::from_u16::(0xFF60); /// assert_eq!(SrgbLumaa::new(96u8, 255), luma); /// ``` /// /// It's also possible to use `From` and `Into`, which defaults to the /// `0xLLAA` component order: /// /// ``` /// use palette::SrgbLumaa; /// /// let luma = SrgbLumaa::from(0x60FF); /// assert_eq!(SrgbLumaa::new(96u8, 255), luma); /// ``` /// /// See [Packed](crate::cast::Packed) for more details. #[inline] pub fn from_u16(color: u16) -> Self where O: ComponentOrder, u16>, { O::unpack(color) } } impl Alpha, A> where S: LumaStandard, { /// Convert the color to linear luminance with transparency. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLumaa, LinLumaa}; /// /// let linear: LinLumaa<_, f32> = SrgbLumaa::new(96u8, 38).into_linear(); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn into_linear(self) -> Alpha, U>, B> where S::TransferFn: IntoLinear, B: FromStimulus, { Alpha { color: self.color.into_linear(), alpha: B::from_stimulus(self.alpha), } } /// Convert linear luminance to non-linear luminance with transparency. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLumaa, LinLumaa}; /// /// let encoded = SrgbLumaa::::from_linear(LinLumaa::new(0.95f32, 0.75)); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn from_linear(color: Alpha, U>, B>) -> Self where S::TransferFn: FromLinear, A: FromStimulus, { Alpha { color: Luma::from_linear(color.color), alpha: A::from_stimulus(color.alpha), } } } impl Alpha, T>, A> { /// Convert a linear color to a different encoding with transparency. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLumaa, LinLumaa}; /// /// let encoded: SrgbLumaa = LinLumaa::new(0.95f32, 0.75).into_encoding(); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn into_encoding(self) -> Alpha, B> where St: LumaStandard, St::TransferFn: FromLinear, B: FromStimulus, { Alpha::, B>::from_linear(self) } /// Convert to linear luminance from a different encoding with transparency. /// /// Some transfer functions allow the component type to be converted at the /// same time. This is usually offered with increased performance, compared /// to using [`into_format`][Luma::into_format]. /// /// ``` /// use palette::{SrgbLumaa, LinLumaa}; /// /// let linear = LinLumaa::<_, f32>::from_encoding(SrgbLumaa::new(96u8, 38)); /// ``` /// /// See the transfer function types in the [`encoding`](crate::encoding) /// module for details and performance characteristics. pub fn from_encoding(color: Alpha, B>) -> Self where St: LumaStandard, St::TransferFn: IntoLinear, A: FromStimulus, { color.into_linear() } } impl_reference_component_methods!(Luma, [luma], standard); impl_struct_of_arrays_methods!(Luma, [luma], standard); impl FromColorUnclamped> for Luma where S1: LumaStandard + 'static, S2: LumaStandard + 'static, S1::TransferFn: FromLinear, S2::TransferFn: IntoLinear, { fn from_color_unclamped(color: Luma) -> Self { if TypeId::of::() == TypeId::of::() { color.reinterpret_as() } else { Self::from_linear(color.into_linear().reinterpret_as()) } } } impl FromColorUnclamped> for Luma where S: LumaStandard, S::TransferFn: FromLinear, { fn from_color_unclamped(color: Xyz) -> Self { Self::from_linear(Luma { luma: color.y, standard: PhantomData, }) } } impl FromColorUnclamped> for Luma where S: LumaStandard, S::TransferFn: FromLinear, { fn from_color_unclamped(color: Yxy) -> Self { Self::from_linear(Luma { luma: color.luma, standard: PhantomData, }) } } impl_tuple_conversion!(Luma as (T)); impl_is_within_bounds! { Luma { luma => [Self::min_luma(), Self::max_luma()] } where T: Stimulus } impl_clamp! { Luma { luma => [Self::min_luma(), Self::max_luma()] } other {standard} where T: Stimulus } impl_mix!(Luma); impl_lighten!(Luma increase {luma => [Self::min_luma(), Self::max_luma()]} other {} phantom: standard where T: Stimulus); impl_premultiply!(Luma {luma} phantom: standard); impl_euclidean_distance!(Luma {luma}); impl StimulusColor for Luma where T: Stimulus {} impl HasBoolMask for Luma where T: HasBoolMask, { type Mask = T::Mask; } impl Default for Luma where T: Stimulus, { fn default() -> Luma { Luma::new(Self::min_luma()) } } impl_color_add!(Luma, [luma], standard); impl_color_sub!(Luma, [luma], standard); impl_color_mul!(Luma, [luma], standard); impl_color_div!(Luma, [luma], standard); impl_array_casts!(Luma, [T; 1]); impl AsRef for Luma { #[inline] fn as_ref(&self) -> &T { &self.luma } } impl AsMut for Luma { #[inline] fn as_mut(&mut self) -> &mut T { &mut self.luma } } impl From for Luma { #[inline] fn from(luma: T) -> Self { Self::new(luma) } } macro_rules! impl_luma_cast_other { ($($other: ty),+) => { $( impl<'a, S> From<&'a $other> for &'a Luma where $other: AsRef>, { #[inline] fn from(luma: &'a $other) -> Self { luma.as_ref() } } impl<'a, S> From<&'a mut $other> for &'a mut Luma where $other: AsMut>, { #[inline] fn from(luma: &'a mut $other) -> Self { luma.as_mut() } } impl AsRef> for $other { #[inline] fn as_ref(&self) -> &Luma { core::slice::from_ref(self).try_into().unwrap() } } impl AsMut> for $other { #[inline] fn as_mut(&mut self) -> &mut Luma { core::slice::from_mut(self).try_into().unwrap() } } impl From> for $other { #[inline] fn from(color: Luma) -> Self { color.luma } } impl<'a, S> From<&'a Luma> for &'a $other { #[inline] fn from(color: &'a Luma) -> Self { color.as_ref() } } impl<'a, S> From<&'a mut Luma> for &'a mut $other { #[inline] fn from(color: &'a mut Luma) -> Self { color.as_mut() } } )+ }; } impl_luma_cast_other!(u8, u16, u32, u64, u128, f32, f64); impl From> for Packed where O: ComponentOrder, P>, Lumaa: From>, { #[inline] fn from(color: Luma) -> Self { Self::from(Lumaa::from(color)) } } impl From> for Packed where O: ComponentOrder, P>, { #[inline] fn from(color: Lumaa) -> Self { Packed::pack(color) } } impl From> for Luma where O: ComponentOrder, P>, { #[inline] fn from(packed: Packed) -> Self { Lumaa::from(packed).color } } impl From> for Lumaa where O: ComponentOrder, P>, { #[inline] fn from(packed: Packed) -> Self { packed.unpack() } } impl From for Luma { #[inline] fn from(color: u16) -> Self { Self::from_u16::(color) } } impl From for Lumaa { #[inline] fn from(color: u16) -> Self { Self::from_u16::(color) } } impl From> for u16 { #[inline] fn from(color: Luma) -> Self { Luma::into_u16::(color) } } impl From> for u16 { #[inline] fn from(color: Lumaa) -> Self { Lumaa::into_u16::(color) } } impl_simd_array_conversion!(Luma, [luma], standard); impl_struct_of_array_traits!(Luma, [luma], standard); impl_copy_clone!(Luma, [luma], standard); impl_eq!(Luma, [luma]); impl fmt::LowerHex for Luma where T: fmt::LowerHex, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let size = f.width().unwrap_or(::core::mem::size_of::() * 2); write!(f, "{:0width$x}", self.luma, width = size) } } impl fmt::UpperHex for Luma where T: fmt::UpperHex, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let size = f.width().unwrap_or(::core::mem::size_of::() * 2); write!(f, "{:0width$X}", self.luma, width = size) } } #[allow(deprecated)] impl crate::RelativeContrast for Luma where T: Real + Arithmetics + PartialCmp, T::Mask: LazySelect, S: LumaStandard, S::TransferFn: IntoLinear, { type Scalar = T; #[inline] fn get_contrast_ratio(self, other: Self) -> T { let luma1 = self.into_linear(); let luma2 = other.into_linear(); crate::contrast_ratio(luma1.luma, luma2.luma) } } impl Wcag21RelativeContrast for Luma where Self: IntoColor, T>>, S: LumaStandard, T: Real + Add + Div + PartialCmp + MinMax, { type Scalar = T; fn relative_luminance(self) -> Luma, Self::Scalar> { self.into_color() } } impl_rand_traits_cartesian!(UniformLuma, Luma {luma} phantom: standard: PhantomData); #[cfg(feature = "bytemuck")] unsafe impl bytemuck::Zeroable for Luma where T: bytemuck::Zeroable {} #[cfg(feature = "bytemuck")] unsafe impl bytemuck::Pod for Luma where T: bytemuck::Pod {} #[cfg(test)] mod test { use crate::encoding::Srgb; use crate::Luma; test_convert_into_from_xyz!(Luma); #[test] fn ranges() { assert_ranges! { Luma; clamped { luma: 0.0 => 1.0 } clamped_min {} unclamped {} } } raw_pixel_conversion_tests!(Luma: luma); #[test] fn lower_hex() { assert_eq!(format!("{:x}", Luma::::new(161)), "a1"); } #[test] fn lower_hex_small_numbers() { assert_eq!(format!("{:x}", Luma::::new(1)), "01"); assert_eq!(format!("{:x}", Luma::::new(1)), "0001"); assert_eq!(format!("{:x}", Luma::::new(1)), "00000001"); assert_eq!( format!("{:x}", Luma::::new(1)), "0000000000000001" ); } #[test] fn lower_hex_custom_width() { assert_eq!(format!("{:03x}", Luma::::new(1)), "001"); assert_eq!(format!("{:03x}", Luma::::new(1)), "001"); assert_eq!(format!("{:03x}", Luma::::new(1)), "001"); assert_eq!(format!("{:03x}", Luma::::new(1)), "001"); } #[test] fn upper_hex() { assert_eq!(format!("{:X}", Luma::::new(161)), "A1"); } #[test] fn upper_hex_small_numbers() { assert_eq!(format!("{:X}", Luma::::new(1)), "01"); assert_eq!(format!("{:X}", Luma::::new(1)), "0001"); assert_eq!(format!("{:X}", Luma::::new(1)), "00000001"); assert_eq!( format!("{:X}", Luma::::new(1)), "0000000000000001" ); } #[test] fn upper_hex_custom_width() { assert_eq!(format!("{:03X}", Luma::::new(1)), "001"); assert_eq!(format!("{:03X}", Luma::::new(1)), "001"); assert_eq!(format!("{:03X}", Luma::::new(1)), "001"); assert_eq!(format!("{:03X}", Luma::::new(1)), "001"); } #[test] fn check_min_max_components() { assert_eq!(Luma::::min_luma(), 0.0); assert_eq!(Luma::::max_luma(), 1.0); } struct_of_arrays_tests!( Luma[luma] phantom: standard, super::Lumaa::new(0.1f32, 0.4), super::Lumaa::new(0.2, 0.5), super::Lumaa::new(0.3, 0.6) ); #[cfg(feature = "serializing")] #[test] fn serialize() { let serialized = ::serde_json::to_string(&Luma::::new(0.3)).unwrap(); assert_eq!(serialized, r#"{"luma":0.3}"#); } #[cfg(feature = "serializing")] #[test] fn deserialize() { let deserialized: Luma = ::serde_json::from_str(r#"{"luma":0.3}"#).unwrap(); assert_eq!(deserialized, Luma::::new(0.3)); } test_uniform_distribution! { Luma { luma: (0.0, 1.0) }, min: Luma::new(0.0f32), max: Luma::new(1.0) } }