scene.rs

  1use serde::Deserialize;
  2use serde_json::json;
  3use std::{borrow::Cow, sync::Arc};
  4
  5use crate::{
  6    color::Color,
  7    fonts::{FontId, GlyphId},
  8    geometry::{rect::RectF, vector::Vector2F},
  9    json::ToJson,
 10    ImageData,
 11};
 12
 13pub struct Scene {
 14    scale_factor: f32,
 15    stacking_contexts: Vec<StackingContext>,
 16    active_stacking_context_stack: Vec<usize>,
 17}
 18
 19struct StackingContext {
 20    layers: Vec<Layer>,
 21    active_layer_stack: Vec<usize>,
 22}
 23
 24#[derive(Default)]
 25pub struct Layer {
 26    clip_bounds: Option<RectF>,
 27    quads: Vec<Quad>,
 28    underlines: Vec<Quad>,
 29    images: Vec<Image>,
 30    shadows: Vec<Shadow>,
 31    glyphs: Vec<Glyph>,
 32    icons: Vec<Icon>,
 33    paths: Vec<Path>,
 34}
 35
 36#[derive(Default, Debug)]
 37pub struct Quad {
 38    pub bounds: RectF,
 39    pub background: Option<Color>,
 40    pub border: Border,
 41    pub corner_radius: f32,
 42}
 43
 44#[derive(Debug)]
 45pub struct Shadow {
 46    pub bounds: RectF,
 47    pub corner_radius: f32,
 48    pub sigma: f32,
 49    pub color: Color,
 50}
 51
 52#[derive(Debug)]
 53pub struct Glyph {
 54    pub font_id: FontId,
 55    pub font_size: f32,
 56    pub id: GlyphId,
 57    pub origin: Vector2F,
 58    pub color: Color,
 59}
 60
 61pub struct Icon {
 62    pub bounds: RectF,
 63    pub svg: usvg::Tree,
 64    pub path: Cow<'static, str>,
 65    pub color: Color,
 66}
 67
 68#[derive(Clone, Copy, Default, Debug)]
 69pub struct Border {
 70    pub width: f32,
 71    pub color: Color,
 72    pub top: bool,
 73    pub right: bool,
 74    pub bottom: bool,
 75    pub left: bool,
 76}
 77
 78impl<'de> Deserialize<'de> for Border {
 79    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 80    where
 81        D: serde::Deserializer<'de>,
 82    {
 83        #[derive(Deserialize)]
 84        struct BorderData {
 85            pub width: f32,
 86            pub color: Color,
 87            #[serde(default)]
 88            pub top: bool,
 89            #[serde(default)]
 90            pub right: bool,
 91            #[serde(default)]
 92            pub bottom: bool,
 93            #[serde(default)]
 94            pub left: bool,
 95        }
 96
 97        let data = BorderData::deserialize(deserializer)?;
 98        let mut border = Border {
 99            width: data.width,
100            color: data.color,
101            top: data.top,
102            bottom: data.bottom,
103            left: data.left,
104            right: data.right,
105        };
106        if !border.top && !border.bottom && !border.left && !border.right {
107            border.top = true;
108            border.bottom = true;
109            border.left = true;
110            border.right = true;
111        }
112        Ok(border)
113    }
114}
115
116#[derive(Debug)]
117pub struct Path {
118    pub bounds: RectF,
119    pub color: Color,
120    pub vertices: Vec<PathVertex>,
121}
122
123#[derive(Debug)]
124pub struct PathVertex {
125    pub xy_position: Vector2F,
126    pub st_position: Vector2F,
127}
128
129pub struct Image {
130    pub bounds: RectF,
131    pub border: Border,
132    pub corner_radius: f32,
133    pub data: Arc<ImageData>,
134}
135
136impl Scene {
137    pub fn new(scale_factor: f32) -> Self {
138        let stacking_context = StackingContext::new(None);
139        Scene {
140            scale_factor,
141            stacking_contexts: vec![stacking_context],
142            active_stacking_context_stack: vec![0],
143        }
144    }
145
146    pub fn scale_factor(&self) -> f32 {
147        self.scale_factor
148    }
149
150    pub fn layers(&self) -> impl Iterator<Item = &Layer> {
151        self.stacking_contexts.iter().flat_map(|s| &s.layers)
152    }
153
154    pub fn push_stacking_context(&mut self, clip_bounds: Option<RectF>) {
155        self.active_stacking_context_stack
156            .push(self.stacking_contexts.len());
157        self.stacking_contexts
158            .push(StackingContext::new(clip_bounds))
159    }
160
161    pub fn pop_stacking_context(&mut self) {
162        self.active_stacking_context_stack.pop();
163        assert!(!self.active_stacking_context_stack.is_empty());
164    }
165
166    pub fn push_layer(&mut self, clip_bounds: Option<RectF>) {
167        self.active_stacking_context().push_layer(clip_bounds);
168    }
169
170    pub fn pop_layer(&mut self) {
171        self.active_stacking_context().pop_layer();
172    }
173
174    pub fn push_quad(&mut self, quad: Quad) {
175        self.active_layer().push_quad(quad)
176    }
177
178    pub fn push_image(&mut self, image: Image) {
179        self.active_layer().push_image(image)
180    }
181
182    pub fn push_underline(&mut self, underline: Quad) {
183        self.active_layer().push_underline(underline)
184    }
185
186    pub fn push_shadow(&mut self, shadow: Shadow) {
187        self.active_layer().push_shadow(shadow)
188    }
189
190    pub fn push_glyph(&mut self, glyph: Glyph) {
191        self.active_layer().push_glyph(glyph)
192    }
193
194    pub fn push_icon(&mut self, icon: Icon) {
195        self.active_layer().push_icon(icon)
196    }
197
198    pub fn push_path(&mut self, path: Path) {
199        self.active_layer().push_path(path);
200    }
201
202    fn active_stacking_context(&mut self) -> &mut StackingContext {
203        let ix = *self.active_stacking_context_stack.last().unwrap();
204        &mut self.stacking_contexts[ix]
205    }
206
207    fn active_layer(&mut self) -> &mut Layer {
208        self.active_stacking_context().active_layer()
209    }
210}
211
212impl StackingContext {
213    fn new(clip_bounds: Option<RectF>) -> Self {
214        Self {
215            layers: vec![Layer::new(clip_bounds)],
216            active_layer_stack: vec![0],
217        }
218    }
219
220    fn active_layer(&mut self) -> &mut Layer {
221        &mut self.layers[*self.active_layer_stack.last().unwrap()]
222    }
223
224    fn push_layer(&mut self, clip_bounds: Option<RectF>) {
225        let parent_clip_bounds = self.active_layer().clip_bounds();
226        let clip_bounds = clip_bounds
227            .map(|clip_bounds| {
228                clip_bounds
229                    .intersection(parent_clip_bounds.unwrap_or(clip_bounds))
230                    .unwrap_or_else(|| {
231                        if !clip_bounds.is_empty() {
232                            log::warn!("specified clip bounds are disjoint from parent layer");
233                        }
234                        RectF::default()
235                    })
236            })
237            .or(parent_clip_bounds);
238
239        let ix = self.layers.len();
240        self.layers.push(Layer::new(clip_bounds));
241        self.active_layer_stack.push(ix);
242    }
243
244    fn pop_layer(&mut self) {
245        self.active_layer_stack.pop().unwrap();
246        assert!(!self.active_layer_stack.is_empty());
247    }
248}
249
250impl Layer {
251    pub fn new(clip_bounds: Option<RectF>) -> Self {
252        Self {
253            clip_bounds,
254            quads: Vec::new(),
255            underlines: Vec::new(),
256            images: Vec::new(),
257            shadows: Vec::new(),
258            glyphs: Vec::new(),
259            icons: Vec::new(),
260            paths: Vec::new(),
261        }
262    }
263
264    pub fn clip_bounds(&self) -> Option<RectF> {
265        self.clip_bounds
266    }
267
268    fn push_quad(&mut self, quad: Quad) {
269        self.quads.push(quad);
270    }
271
272    pub fn quads(&self) -> &[Quad] {
273        self.quads.as_slice()
274    }
275
276    fn push_underline(&mut self, underline: Quad) {
277        self.underlines.push(underline);
278    }
279
280    pub fn underlines(&self) -> &[Quad] {
281        self.underlines.as_slice()
282    }
283
284    fn push_image(&mut self, image: Image) {
285        self.images.push(image);
286    }
287
288    pub fn images(&self) -> &[Image] {
289        self.images.as_slice()
290    }
291
292    fn push_shadow(&mut self, shadow: Shadow) {
293        self.shadows.push(shadow);
294    }
295
296    pub fn shadows(&self) -> &[Shadow] {
297        self.shadows.as_slice()
298    }
299
300    fn push_glyph(&mut self, glyph: Glyph) {
301        self.glyphs.push(glyph);
302    }
303
304    pub fn glyphs(&self) -> &[Glyph] {
305        self.glyphs.as_slice()
306    }
307
308    pub fn push_icon(&mut self, icon: Icon) {
309        self.icons.push(icon);
310    }
311
312    pub fn icons(&self) -> &[Icon] {
313        self.icons.as_slice()
314    }
315
316    fn push_path(&mut self, path: Path) {
317        if !path.bounds.is_empty() {
318            self.paths.push(path);
319        }
320    }
321
322    pub fn paths(&self) -> &[Path] {
323        self.paths.as_slice()
324    }
325}
326
327impl Border {
328    pub fn new(width: f32, color: Color) -> Self {
329        Self {
330            width,
331            color,
332            top: false,
333            left: false,
334            bottom: false,
335            right: false,
336        }
337    }
338
339    pub fn all(width: f32, color: Color) -> Self {
340        Self {
341            width,
342            color,
343            top: true,
344            left: true,
345            bottom: true,
346            right: true,
347        }
348    }
349
350    pub fn top(width: f32, color: Color) -> Self {
351        let mut border = Self::new(width, color);
352        border.top = true;
353        border
354    }
355
356    pub fn left(width: f32, color: Color) -> Self {
357        let mut border = Self::new(width, color);
358        border.left = true;
359        border
360    }
361
362    pub fn bottom(width: f32, color: Color) -> Self {
363        let mut border = Self::new(width, color);
364        border.bottom = true;
365        border
366    }
367
368    pub fn right(width: f32, color: Color) -> Self {
369        let mut border = Self::new(width, color);
370        border.right = true;
371        border
372    }
373
374    pub fn with_sides(mut self, top: bool, left: bool, bottom: bool, right: bool) -> Self {
375        self.top = top;
376        self.left = left;
377        self.bottom = bottom;
378        self.right = right;
379        self
380    }
381
382    pub fn top_width(&self) -> f32 {
383        if self.top {
384            self.width
385        } else {
386            0.0
387        }
388    }
389
390    pub fn left_width(&self) -> f32 {
391        if self.left {
392            self.width
393        } else {
394            0.0
395        }
396    }
397}
398
399impl ToJson for Border {
400    fn to_json(&self) -> serde_json::Value {
401        let mut value = json!({});
402        if self.top {
403            value["top"] = json!(self.width);
404        }
405        if self.right {
406            value["right"] = json!(self.width);
407        }
408        if self.bottom {
409            value["bottom"] = json!(self.width);
410        }
411        if self.left {
412            value["left"] = json!(self.width);
413        }
414        value
415    }
416}