Skip to main content

mln_style/
light.rs

1use std::sync::Arc;
2
3use crate::conversion::{Convertible, Error};
4use crate::expression::Functions;
5use crate::property::table::{self, InPlace, OwnerSlot, SetPropertyError, StyleProperty};
6
7crate::properties!(
8    #[expect(non_snake_case, reason = "named like the layers' property sets")]
9    pub mod LightProperties: paint {
10        light_anchor: constant LightAnchorType = LightAnchorType::Viewport,
11        light_position: constant Position = Position::new([1.15_f32, 210.0_f32, 30.0_f32]),
12        light_color: constant Color = Color::white(),
13        light_intensity: constant f32 = 0.5_f32,
14    }
15    use crate::types::LightAnchorType, crate::types::Position, crate::color::Color;
16);
17
18/// The style's light.
19#[derive(Clone, Debug, Default, PartialEq)]
20pub struct Light {
21    pub properties: LightProperties::Transitionable,
22}
23
24impl Light {
25    #[must_use]
26    pub fn new() -> Self {
27        Light::default()
28    }
29
30    /// Sets a property (or `<name>-transition`) from a style JSON value,
31    /// whose expressions parse against `functions`.
32    pub fn set_property(&mut self, name: &str, value: &Convertible<'_>, functions: &Arc<Functions>) -> Option<Error> {
33        set_property(&mut InPlace(self), name, value, functions)
34    }
35
36    #[must_use]
37    pub fn property(&self, name: &str) -> StyleProperty {
38        table::property(self, name)
39    }
40}
41
42fn set_property<O: OwnerSlot<Light>>(
43    owner: &mut O,
44    name: &str,
45    value: &Convertible<'_>,
46    functions: &Arc<Functions>,
47) -> Option<Error> {
48    match table::set_property(owner, name, value, functions) {
49        Ok(()) => None,
50        Err(SetPropertyError::Invalid(error)) => Some(error),
51        Err(SetPropertyError::Unknown) => Some(Error::new("light doesn't support this property")),
52    }
53}
54
55/// Converts the style's `light`, whose expressions parse against `functions`.
56pub fn convert_light(value: &Convertible<'_>, functions: &Arc<Functions>, error: &mut Error) -> Option<Light> {
57    if !value.is_object() {
58        error.message = "light must be an object".to_owned();
59        return None;
60    }
61
62    let mut light = Light::new();
63    for name in table::names::<Light>() {
64        let Some(member) = value.object_member(&name) else {
65            continue;
66        };
67        if let Some(conversion_error) = light.set_property(&name, &member, functions) {
68            *error = conversion_error;
69            return None;
70        }
71    }
72
73    Some(light)
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::color::Color;
80    use crate::property::value::StyleValue as _;
81    use crate::tests::util::parse_json;
82    use crate::types::Position;
83
84    fn convert(json: &str) -> Result<Light, String> {
85        let mut error = Error::default();
86        convert_light(&Convertible::from(&parse_json(json)), &Functions::with_builtins(), &mut error)
87            .ok_or(error.message)
88    }
89
90    #[test]
91    fn a_light_reads_its_properties_and_transitions() {
92        let light = convert(
93            r#"{"color": {"stops": [[14, "blue"], [16, "red"]]}, "intensity": 0.3, "position": [3, 90, 90],
94                "intensity-transition": {"duration": 1000}}"#,
95        )
96        .unwrap();
97        let properties = &light.properties;
98        assert!(properties.light_anchor.value.is_undefined());
99        assert_eq!(Some(&0.3), properties.light_intensity.value.as_constant());
100        assert_eq!(Some(std::time::Duration::from_millis(1000)), properties.light_intensity.options.duration);
101        assert_eq!(None, properties.light_intensity.options.delay);
102        assert!(!properties.light_color.value.as_expression().unwrap().is_zoom_constant());
103        assert_eq!(Some(&Position::new([3.0, 90.0, 90.0])), properties.light_position.value.as_constant());
104
105        let mut light = convert("{}").unwrap();
106        let blue = serde_json::json!("blue");
107        assert!(light.set_property("color", &Convertible::from(&blue), &Functions::with_builtins()).is_none());
108        assert_eq!(Some(&Color::blue()), light.properties.light_color.value.as_constant());
109        let error = light.set_property("colour", &Convertible::from(&blue), &Functions::with_builtins());
110        assert_eq!(Some("light doesn't support this property"), error.as_ref().map(|error| error.message.as_str()));
111    }
112
113    #[test]
114    fn an_invalid_light_is_refused_with_a_reason() {
115        for (json, error) in [
116            ("[]", "light must be an object"),
117            (r#"{"intensity": false}"#, "value must be a number"),
118            (r#"{"intensity": {"stops": [[15, "red"], [17, "blue"]]}}"#, "Expected number but found string instead."),
119            (r#"{"color": 5}"#, "value must be a string"),
120            (r#"{"position": [0, 5]}"#, "value must be an array of 3 numbers"),
121            (r#"{"anchor": "something"}"#, "value must be a valid enumeration value"),
122        ] {
123            assert_eq!(Err(error.to_owned()), convert(json).map(|_| ()), "{json}");
124        }
125    }
126}