Skip to main content

rustial_engine/layers/
background_layer.rs

1//! Solid background layer, similar to MapLibre's background layer.
2
3use crate::layer::{Layer, LayerId};
4use std::any::Any;
5
6/// A solid background fill used as the map clear colour.
7///
8/// This is the first small step toward a broader MapLibre-style layer
9/// taxonomy: renderers can derive their frame clear colour from the
10/// bottom-most scene stack instead of hard-coding a sky colour.
11#[derive(Debug, Clone)]
12pub struct BackgroundLayer {
13    id: LayerId,
14    name: String,
15    visible: bool,
16    opacity: f32,
17    color: [f32; 4],
18}
19
20impl BackgroundLayer {
21    /// Create a new background layer with the given RGBA colour.
22    pub fn new(name: impl Into<String>, color: [f32; 4]) -> Self {
23        Self {
24            id: LayerId::next(),
25            name: name.into(),
26            visible: true,
27            opacity: 1.0,
28            color,
29        }
30    }
31
32    /// Return the configured RGBA colour.
33    #[inline]
34    pub fn color(&self) -> [f32; 4] {
35        self.color
36    }
37
38    /// Replace the RGBA colour.
39    pub fn set_color(&mut self, color: [f32; 4]) {
40        self.color = color;
41    }
42
43    /// Return the effective clear colour after applying layer opacity.
44    #[inline]
45    pub fn effective_color(&self) -> [f32; 4] {
46        [
47            self.color[0],
48            self.color[1],
49            self.color[2],
50            self.color[3] * self.opacity,
51        ]
52    }
53}
54
55impl Layer for BackgroundLayer {
56    fn id(&self) -> LayerId {
57        self.id
58    }
59
60    fn kind(&self) -> crate::layer::LayerKind {
61        crate::layer::LayerKind::Background
62    }
63
64    fn name(&self) -> &str {
65        &self.name
66    }
67
68    fn visible(&self) -> bool {
69        self.visible
70    }
71
72    fn set_visible(&mut self, visible: bool) {
73        self.visible = visible;
74    }
75
76    fn opacity(&self) -> f32 {
77        self.opacity
78    }
79
80    fn set_opacity(&mut self, opacity: f32) {
81        self.opacity = opacity.clamp(0.0, 1.0);
82    }
83
84    fn as_any(&self) -> &dyn Any {
85        self
86    }
87
88    fn as_any_mut(&mut self) -> &mut dyn Any {
89        self
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::layer::Layer;
97
98    #[test]
99    fn effective_color_applies_opacity() {
100        let mut layer = BackgroundLayer::new("bg", [0.2, 0.3, 0.4, 1.0]);
101        layer.set_opacity(0.5);
102        assert_eq!(layer.effective_color(), [0.2, 0.3, 0.4, 0.5]);
103    }
104
105    #[test]
106    fn kind_is_background() {
107        let layer = BackgroundLayer::new("bg", [0.0, 0.0, 0.0, 1.0]);
108        assert_eq!(layer.kind(), crate::layer::LayerKind::Background);
109    }
110}