Skip to main content

gpui/
scene.rs

1// todo("windows"): remove
2#![cfg_attr(windows, allow(dead_code))]
3
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path,
9    PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation,
10    bounds_tree::BoundsTree,
11};
12use smallvec::SmallVec;
13use std::{
14    collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice, time::Duration,
15};
16
17#[expect(missing_docs)]
18pub type DrawOrder = u32;
19
20/// A boolean stored as a `u32` so that GPU-facing structs contain no
21/// compiler-inserted padding bytes, which would be undefined behavior to
22/// reinterpret as `&[u8]` when writing instance buffers. Guaranteed to be
23/// `0` or `1` by construction; shaders read it as a `u32`/`uint`.
24#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
25#[repr(transparent)]
26pub struct PaddedBool32(u32);
27
28impl From<bool> for PaddedBool32 {
29    fn from(value: bool) -> Self {
30        PaddedBool32(value as u32)
31    }
32}
33
34impl PaddedBool32 {
35    /// The wrapped boolean.
36    pub fn as_bool(self) -> bool {
37        self.0 != 0
38    }
39}
40
41struct Layer {
42    primitives: SmallVec<[Range<usize>; 1]>,
43    bounds: Bounds<ScaledPixels>,
44    max_kind: PrimitiveKind,
45    max_shared_kind: PrimitiveKind,
46}
47
48#[derive(Default)]
49#[expect(missing_docs)]
50pub struct Scene {
51    pub(crate) paint_operations: Vec<PaintOperation>,
52    primitive_bounds: BoundsTree<ScaledPixels>,
53    layer_stack: Vec<usize>,
54    layers: VecDeque<Layer>,
55    pub shadows: Vec<Shadow>,
56    pub quads: Vec<Quad>,
57    pub paths: Vec<PaintedPath>,
58    pub underlines: Vec<Underline>,
59    pub monochrome_sprites: Vec<MonochromeSprite>,
60    pub subpixel_sprites: Vec<SubpixelSprite>,
61    pub polychrome_sprites: Vec<PolychromeSprite>,
62    pub surfaces: Vec<PaintSurface>,
63    animations: Vec<SpriteAnimation>,
64}
65
66#[expect(missing_docs)]
67impl Scene {
68    pub fn clear(&mut self) {
69        self.paint_operations.clear();
70        self.primitive_bounds.clear();
71        self.layer_stack.clear();
72        self.layers.clear();
73        self.paths.clear();
74        self.shadows.clear();
75        self.quads.clear();
76        self.underlines.clear();
77        self.monochrome_sprites.clear();
78        self.subpixel_sprites.clear();
79        self.polychrome_sprites.clear();
80        self.surfaces.clear();
81        self.animations.clear();
82    }
83
84    /// Inserts a sprite that [`Self::advance_animations`] keeps moving. The
85    /// sprite's color is taken as its color before the animation's alpha.
86    pub(crate) fn insert_animated_sprite(
87        &mut self,
88        mut sprite: MonochromeSprite,
89        mut animation: SpriteAnimation,
90    ) {
91        sprite.animation = SpriteAnimationId(self.animations.len() as u32);
92        animation.base_color = sprite.color;
93        if self.try_insert_primitive(sprite.into()) {
94            self.animations.push(animation);
95        }
96    }
97
98    /// How long the window may wait between presents of this scene while only
99    /// its animations need a frame: `None` when nothing in it animates, and
100    /// zero when an animation wants every frame.
101    pub(crate) fn animation_frame_interval(&self) -> Option<Duration> {
102        self.animations
103            .iter()
104            .map(|animation| {
105                animation
106                    .transformation
107                    .min_frame_interval()
108                    .unwrap_or_default()
109            })
110            .min()
111    }
112
113    /// Moves every animated sprite to its pose at `elapsed` time on the app's
114    /// synced animation clock, without the scene being rebuilt.
115    pub(crate) fn advance_animations(&mut self, elapsed: Duration) {
116        for animation in &self.animations {
117            let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else {
118                continue;
119            };
120            let pose = animation.transformation.at(elapsed);
121            sprite.transformation = pose.into_matrix(animation.center, animation.scale_factor);
122            sprite.color = animation.base_color.opacity(pose.alpha_factor());
123        }
124    }
125
126    pub fn len(&self) -> usize {
127        self.paint_operations.len()
128    }
129
130    pub fn push_layer(&mut self) {
131        self.layer_stack.push(self.layers.len());
132        self.layers.push_back(Layer {
133            primitives: SmallVec::new(),
134            bounds: Bounds::default(),
135            max_kind: PrimitiveKind::Shadow,
136            max_shared_kind: PrimitiveKind::Surface,
137        });
138        self.paint_operations.push(PaintOperation::StartLayer);
139    }
140
141    pub fn pop_layer(&mut self) {
142        self.layer_stack.pop();
143        if self.layer_stack.is_empty() {
144            while let Some(layer) = self.layers.pop_front() {
145                self.insert_layer(layer);
146            }
147        }
148        self.paint_operations.push(PaintOperation::EndLayer);
149    }
150
151    fn insert_layer(&mut self, layer: Layer) {
152        if layer.primitives.is_empty() {
153            return;
154        }
155        let order =
156            self.primitive_bounds
157                .insert(layer.bounds, layer.max_kind, layer.max_shared_kind);
158        for index in layer.primitives.into_iter().flatten() {
159            if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] {
160                let primitive = primitive.clone();
161                self.push_primitive(primitive, order);
162            }
163        }
164    }
165
166    pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
167        self.try_insert_primitive(primitive.into());
168    }
169
170    /// Returns whether the primitive was kept, rather than clipped away.
171    fn try_insert_primitive(&mut self, primitive: Primitive) -> bool {
172        let clipped_bounds = primitive.clipped_bounds();
173        if clipped_bounds.is_empty() {
174            return false;
175        }
176
177        let kind = primitive.kind();
178        if let Some(&layer) = self.layer_stack.last()
179            && let Some(layer) = self.layers.get_mut(layer)
180        {
181            layer.bounds = layer.bounds.join(&clipped_bounds);
182            layer.max_kind = layer.max_kind.max(kind);
183            layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind());
184            let index = self.paint_operations.len();
185            match layer.primitives.last_mut() {
186                Some(range) if range.end == index => range.end += 1,
187                _ => layer.primitives.push(index..index + 1),
188            }
189        } else {
190            let order = self
191                .primitive_bounds
192                .insert(clipped_bounds, kind, kind.max_shared_kind());
193            self.push_primitive(primitive.clone(), order);
194        }
195        self.paint_operations
196            .push(PaintOperation::Primitive(primitive));
197        true
198    }
199
200    fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) {
201        match primitive {
202            Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }),
203            Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }),
204            Primitive::Path(mut path) => {
205                path.order = order;
206                self.paths.push(path);
207            }
208            Primitive::Underline(underline) => {
209                self.underlines.push(Underline { order, ..underline })
210            }
211            Primitive::MonochromeSprite(sprite) => self
212                .monochrome_sprites
213                .push(MonochromeSprite { order, ..sprite }),
214            Primitive::SubpixelSprite(sprite) => self
215                .subpixel_sprites
216                .push(SubpixelSprite { order, ..sprite }),
217            Primitive::PolychromeSprite(sprite) => self
218                .polychrome_sprites
219                .push(PolychromeSprite { order, ..sprite }),
220            Primitive::Surface(mut surface) => {
221                surface.order = order;
222                self.surfaces.push(surface);
223            }
224        }
225    }
226
227    pub fn replay(&mut self, range: Range<usize>, prev_scene: &Scene) {
228        for operation in &prev_scene.paint_operations[range] {
229            match operation {
230                PaintOperation::Primitive(primitive) => {
231                    // Animation ids index the scene they were inserted into.
232                    if let Primitive::MonochromeSprite(sprite) = primitive
233                        && let Some(animation) =
234                            prev_scene.animations.get(sprite.animation.0 as usize)
235                    {
236                        self.insert_animated_sprite(*sprite, *animation);
237                    } else {
238                        self.insert_primitive(primitive.clone());
239                    }
240                }
241                PaintOperation::StartLayer => self.push_layer(),
242                PaintOperation::EndLayer => self.pop_layer(),
243            }
244        }
245    }
246
247    pub fn finish(&mut self) {
248        debug_assert!(self.layer_stack.is_empty(), "unbalanced scene layers");
249        let keys = &mut Vec::new();
250        sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0));
251        sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0));
252        self.paths.sort_by_key(|path| path.order);
253        sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0));
254        sort_in_place(&mut self.monochrome_sprites, keys, |sprite| {
255            (sprite.order, sprite.tile.texture_id.index)
256        });
257        sort_in_place(&mut self.subpixel_sprites, keys, |sprite| {
258            (sprite.order, sprite.tile.texture_id.index)
259        });
260        sort_in_place(&mut self.polychrome_sprites, keys, |sprite| {
261            (sprite.order, sprite.tile.texture_id.index)
262        });
263        self.surfaces.sort_by_key(|surface| surface.order);
264
265        // Sorting moved the sprites, so animations learn where theirs ended up.
266        if !self.animations.is_empty() {
267            for (index, sprite) in self.monochrome_sprites.iter().enumerate() {
268                if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) {
269                    animation.sprite_index = index;
270                }
271            }
272        }
273    }
274
275    #[cfg_attr(
276        all(
277            any(target_os = "linux", target_os = "freebsd"),
278            not(any(feature = "x11", feature = "wayland"))
279        ),
280        allow(dead_code)
281    )]
282    pub fn batches(&self) -> impl Iterator<Item = PrimitiveBatch> + '_ {
283        BatchIterator {
284            shadows_start: 0,
285            shadows_iter: self.shadows.iter().peekable(),
286            quads_start: 0,
287            quads_iter: self.quads.iter().peekable(),
288            paths_start: 0,
289            paths_iter: self.paths.iter().peekable(),
290            underlines_start: 0,
291            underlines_iter: self.underlines.iter().peekable(),
292            monochrome_sprites_start: 0,
293            monochrome_sprites_iter: self.monochrome_sprites.iter().peekable(),
294            subpixel_sprites_start: 0,
295            subpixel_sprites_iter: self.subpixel_sprites.iter().peekable(),
296            polychrome_sprites_start: 0,
297            polychrome_sprites_iter: self.polychrome_sprites.iter().peekable(),
298            surfaces_start: 0,
299            surfaces_iter: self.surfaces.iter().peekable(),
300        }
301    }
302}
303
304/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each
305/// primitive into place once. Primitives are large, so a comparison sort that shuffles them
306/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key`
307/// does, because the index is part of what is sorted.
308fn sort_in_place<T: Copy>(
309    primitives: &mut [T],
310    keys: &mut Vec<(u64, u32)>,
311    key: impl Fn(&T) -> (u32, u32),
312) {
313    if primitives.is_sorted_by_key(&key) {
314        return;
315    }
316    keys.clear();
317    keys.extend(primitives.iter().enumerate().map(|(index, primitive)| {
318        let (major, minor) = key(primitive);
319        ((major as u64) << 32 | minor as u64, index as u32)
320    }));
321    keys.sort_unstable();
322
323    // `keys[target].1` is the source index for `target`. Follow each cycle of that
324    // permutation, marking visited slots by pointing them at themselves.
325    for start in 0..primitives.len() {
326        if keys[start].1 as usize == start {
327            continue;
328        }
329        let displaced = primitives[start];
330        let mut target = start;
331        loop {
332            let source = keys[target].1 as usize;
333            keys[target].1 = target as u32;
334            if source == start {
335                primitives[target] = displaced;
336                break;
337            }
338            primitives[target] = primitives[source];
339            target = source;
340        }
341    }
342}
343
344/// The depth step between consecutive quads in a frame with `quad_count` quads.
345pub fn quad_depth_scale(quad_count: usize) -> f32 {
346    let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two();
347    1.0 / denominator as f32
348}
349
350/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer.
351pub fn quad_depth(quad_id: u32, scale: f32) -> f32 {
352    ((quad_id + 1) as f32 * scale).min(1.0)
353}
354
355#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)]
356#[cfg_attr(
357    all(
358        any(target_os = "linux", target_os = "freebsd"),
359        not(any(feature = "x11", feature = "wayland"))
360    ),
361    allow(dead_code)
362)]
363pub(crate) enum PrimitiveKind {
364    Shadow,
365    #[default]
366    Quad,
367    Path,
368    Underline,
369    MonochromeSprite,
370    SubpixelSprite,
371    PolychromeSprite,
372    Surface,
373}
374
375impl PrimitiveKind {
376    /// We guarantee that overlapping primitives are drawn in paint order.
377    /// But, to improve GPU draw batching, the renderer sorts primitives that
378    /// share a draw order by kind, then by atlas texture, and only then in
379    /// paint order. So, a primitive can only share the draw order of the
380    /// topmost primitive it overlaps if that primitive's kind is at most the
381    /// one returned here. Otherwise, it needs a new draw order.
382    fn max_shared_kind(self) -> Self {
383        match self {
384            Self::MonochromeSprite => Self::Underline,
385            Self::SubpixelSprite => Self::MonochromeSprite,
386            Self::PolychromeSprite => Self::SubpixelSprite,
387            kind => kind,
388        }
389    }
390}
391
392pub(crate) enum PaintOperation {
393    Primitive(Primitive),
394    StartLayer,
395    EndLayer,
396}
397
398#[derive(Clone)]
399#[expect(missing_docs)]
400pub enum Primitive {
401    Shadow(Shadow),
402    Quad(Quad),
403    Path(PaintedPath),
404    Underline(Underline),
405    MonochromeSprite(MonochromeSprite),
406    SubpixelSprite(SubpixelSprite),
407    PolychromeSprite(PolychromeSprite),
408    Surface(PaintSurface),
409}
410
411#[expect(missing_docs)]
412impl Primitive {
413    pub(crate) fn kind(&self) -> PrimitiveKind {
414        match self {
415            Primitive::Shadow(_) => PrimitiveKind::Shadow,
416            Primitive::Quad(_) => PrimitiveKind::Quad,
417            Primitive::Path(_) => PrimitiveKind::Path,
418            Primitive::Underline(_) => PrimitiveKind::Underline,
419            Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite,
420            Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite,
421            Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite,
422            Primitive::Surface(_) => PrimitiveKind::Surface,
423        }
424    }
425
426    pub fn bounds(&self) -> &Bounds<ScaledPixels> {
427        match self {
428            Primitive::Shadow(shadow) => &shadow.bounds,
429            Primitive::Quad(quad) => &quad.bounds,
430            Primitive::Path(path) => &path.bounds,
431            Primitive::Underline(underline) => &underline.bounds,
432            Primitive::MonochromeSprite(sprite) => &sprite.bounds,
433            Primitive::SubpixelSprite(sprite) => &sprite.bounds,
434            Primitive::PolychromeSprite(sprite) => &sprite.bounds,
435            Primitive::Surface(surface) => &surface.bounds,
436        }
437    }
438
439    fn transformation(&self) -> TransformationMatrix {
440        match self {
441            Primitive::MonochromeSprite(sprite) => sprite.transformation,
442            Primitive::SubpixelSprite(sprite) => sprite.transformation,
443            _ => TransformationMatrix::unit(),
444        }
445    }
446
447    fn clipped_bounds(&self) -> Bounds<ScaledPixels> {
448        self.transformation()
449            .transform_bounds(*self.bounds())
450            .intersect(&self.content_mask().bounds)
451    }
452
453    pub fn content_mask(&self) -> &ContentMask<ScaledPixels> {
454        match self {
455            Primitive::Shadow(shadow) => &shadow.content_mask,
456            Primitive::Quad(quad) => &quad.content_mask,
457            Primitive::Path(path) => &path.paint.content_mask,
458            Primitive::Underline(underline) => &underline.content_mask,
459            Primitive::MonochromeSprite(sprite) => &sprite.content_mask,
460            Primitive::SubpixelSprite(sprite) => &sprite.content_mask,
461            Primitive::PolychromeSprite(sprite) => &sprite.content_mask,
462            Primitive::Surface(surface) => &surface.content_mask,
463        }
464    }
465}
466
467#[cfg_attr(
468    all(
469        any(target_os = "linux", target_os = "freebsd"),
470        not(any(feature = "x11", feature = "wayland"))
471    ),
472    allow(dead_code)
473)]
474struct BatchIterator<'a> {
475    shadows_start: usize,
476    shadows_iter: Peekable<slice::Iter<'a, Shadow>>,
477    quads_start: usize,
478    quads_iter: Peekable<slice::Iter<'a, Quad>>,
479    paths_start: usize,
480    paths_iter: Peekable<slice::Iter<'a, PaintedPath>>,
481    underlines_start: usize,
482    underlines_iter: Peekable<slice::Iter<'a, Underline>>,
483    monochrome_sprites_start: usize,
484    monochrome_sprites_iter: Peekable<slice::Iter<'a, MonochromeSprite>>,
485    subpixel_sprites_start: usize,
486    subpixel_sprites_iter: Peekable<slice::Iter<'a, SubpixelSprite>>,
487    polychrome_sprites_start: usize,
488    polychrome_sprites_iter: Peekable<slice::Iter<'a, PolychromeSprite>>,
489    surfaces_start: usize,
490    surfaces_iter: Peekable<slice::Iter<'a, PaintSurface>>,
491}
492
493impl<'a> Iterator for BatchIterator<'a> {
494    type Item = PrimitiveBatch;
495
496    fn next(&mut self) -> Option<Self::Item> {
497        let mut orders_and_kinds = [
498            (
499                self.shadows_iter.peek().map(|s| s.order),
500                PrimitiveKind::Shadow,
501            ),
502            (self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad),
503            (
504                self.paths_iter.peek().map(|path| path.order),
505                PrimitiveKind::Path,
506            ),
507            (
508                self.underlines_iter.peek().map(|u| u.order),
509                PrimitiveKind::Underline,
510            ),
511            (
512                self.monochrome_sprites_iter.peek().map(|s| s.order),
513                PrimitiveKind::MonochromeSprite,
514            ),
515            (
516                self.subpixel_sprites_iter.peek().map(|s| s.order),
517                PrimitiveKind::SubpixelSprite,
518            ),
519            (
520                self.polychrome_sprites_iter.peek().map(|s| s.order),
521                PrimitiveKind::PolychromeSprite,
522            ),
523            (
524                self.surfaces_iter.peek().map(|s| s.order),
525                PrimitiveKind::Surface,
526            ),
527        ];
528        orders_and_kinds.sort_by_key(|(order, kind)| (order.unwrap_or(u32::MAX), *kind));
529
530        let first = orders_and_kinds[0];
531        let second = orders_and_kinds[1];
532        let (batch_kind, max_order_and_kind) = if first.0.is_some() {
533            (first.1, (second.0.unwrap_or(u32::MAX), second.1))
534        } else {
535            return None;
536        };
537
538        match batch_kind {
539            PrimitiveKind::Shadow => {
540                let shadows_start = self.shadows_start;
541                let mut shadows_end = shadows_start + 1;
542                self.shadows_iter.next();
543                while self
544                    .shadows_iter
545                    .next_if(|shadow| (shadow.order, batch_kind) < max_order_and_kind)
546                    .is_some()
547                {
548                    shadows_end += 1;
549                }
550                self.shadows_start = shadows_end;
551                Some(PrimitiveBatch::Shadows(shadows_start..shadows_end))
552            }
553            PrimitiveKind::Quad => {
554                let quads_start = self.quads_start;
555                let mut quads_end = quads_start + 1;
556                self.quads_iter.next();
557                while self
558                    .quads_iter
559                    .next_if(|quad| (quad.order, batch_kind) < max_order_and_kind)
560                    .is_some()
561                {
562                    quads_end += 1;
563                }
564                self.quads_start = quads_end;
565                Some(PrimitiveBatch::Quads(quads_start..quads_end))
566            }
567            PrimitiveKind::Path => {
568                let paths_start = self.paths_start;
569                let mut paths_end = paths_start + 1;
570                self.paths_iter.next();
571                while self
572                    .paths_iter
573                    .next_if(|path| (path.order, batch_kind) < max_order_and_kind)
574                    .is_some()
575                {
576                    paths_end += 1;
577                }
578                self.paths_start = paths_end;
579                Some(PrimitiveBatch::Paths(paths_start..paths_end))
580            }
581            PrimitiveKind::Underline => {
582                let underlines_start = self.underlines_start;
583                let mut underlines_end = underlines_start + 1;
584                self.underlines_iter.next();
585                while self
586                    .underlines_iter
587                    .next_if(|underline| (underline.order, batch_kind) < max_order_and_kind)
588                    .is_some()
589                {
590                    underlines_end += 1;
591                }
592                self.underlines_start = underlines_end;
593                Some(PrimitiveBatch::Underlines(underlines_start..underlines_end))
594            }
595            PrimitiveKind::MonochromeSprite => {
596                let texture_id = self.monochrome_sprites_iter.peek().unwrap().tile.texture_id;
597                let sprites_start = self.monochrome_sprites_start;
598                let mut sprites_end = sprites_start + 1;
599                self.monochrome_sprites_iter.next();
600                while self
601                    .monochrome_sprites_iter
602                    .next_if(|sprite| {
603                        (sprite.order, batch_kind) < max_order_and_kind
604                            && sprite.tile.texture_id == texture_id
605                    })
606                    .is_some()
607                {
608                    sprites_end += 1;
609                }
610                self.monochrome_sprites_start = sprites_end;
611                Some(PrimitiveBatch::MonochromeSprites {
612                    texture_id,
613                    range: sprites_start..sprites_end,
614                })
615            }
616            PrimitiveKind::SubpixelSprite => {
617                let texture_id = self.subpixel_sprites_iter.peek().unwrap().tile.texture_id;
618                let sprites_start = self.subpixel_sprites_start;
619                let mut sprites_end = sprites_start + 1;
620                self.subpixel_sprites_iter.next();
621                while self
622                    .subpixel_sprites_iter
623                    .next_if(|sprite| {
624                        (sprite.order, batch_kind) < max_order_and_kind
625                            && sprite.tile.texture_id == texture_id
626                    })
627                    .is_some()
628                {
629                    sprites_end += 1;
630                }
631                self.subpixel_sprites_start = sprites_end;
632                Some(PrimitiveBatch::SubpixelSprites {
633                    texture_id,
634                    range: sprites_start..sprites_end,
635                })
636            }
637            PrimitiveKind::PolychromeSprite => {
638                let texture_id = self.polychrome_sprites_iter.peek().unwrap().tile.texture_id;
639                let sprites_start = self.polychrome_sprites_start;
640                let mut sprites_end = sprites_start + 1;
641                self.polychrome_sprites_iter.next();
642                while self
643                    .polychrome_sprites_iter
644                    .next_if(|sprite| {
645                        (sprite.order, batch_kind) < max_order_and_kind
646                            && sprite.tile.texture_id == texture_id
647                    })
648                    .is_some()
649                {
650                    sprites_end += 1;
651                }
652                self.polychrome_sprites_start = sprites_end;
653                Some(PrimitiveBatch::PolychromeSprites {
654                    texture_id,
655                    range: sprites_start..sprites_end,
656                })
657            }
658            PrimitiveKind::Surface => {
659                let surfaces_start = self.surfaces_start;
660                let mut surfaces_end = surfaces_start + 1;
661                self.surfaces_iter.next();
662                while self
663                    .surfaces_iter
664                    .next_if(|surface| (surface.order, batch_kind) < max_order_and_kind)
665                    .is_some()
666                {
667                    surfaces_end += 1;
668                }
669                self.surfaces_start = surfaces_end;
670                Some(PrimitiveBatch::Surfaces(surfaces_start..surfaces_end))
671            }
672        }
673    }
674}
675
676#[derive(Debug)]
677#[cfg_attr(
678    all(
679        any(target_os = "linux", target_os = "freebsd"),
680        not(any(feature = "x11", feature = "wayland"))
681    ),
682    allow(dead_code)
683)]
684#[allow(missing_docs)]
685pub enum PrimitiveBatch {
686    Shadows(Range<usize>),
687    Quads(Range<usize>),
688    Paths(Range<usize>),
689    Underlines(Range<usize>),
690    MonochromeSprites {
691        texture_id: AtlasTextureId,
692        range: Range<usize>,
693    },
694    #[cfg_attr(target_os = "macos", allow(dead_code))]
695    SubpixelSprites {
696        texture_id: AtlasTextureId,
697        range: Range<usize>,
698    },
699    PolychromeSprites {
700        texture_id: AtlasTextureId,
701        range: Range<usize>,
702    },
703    Surfaces(Range<usize>),
704}
705
706impl PrimitiveBatch {
707    #[expect(missing_docs)]
708    pub fn label(&self) -> String {
709        match self {
710            Self::Shadows(range) => format!("shadows ({})", range.len()),
711            Self::Quads(range) => format!("quads ({})", range.len()),
712            Self::Paths(range) => format!("paths ({})", range.len()),
713            Self::Underlines(range) => format!("underlines ({})", range.len()),
714            Self::MonochromeSprites { texture_id, range } => {
715                format!(
716                    "monochrome sprites ({}) on atlas {}",
717                    range.len(),
718                    texture_id.index
719                )
720            }
721            Self::SubpixelSprites { texture_id, range } => {
722                format!(
723                    "subpixel sprites ({}) on atlas {}",
724                    range.len(),
725                    texture_id.index
726                )
727            }
728            Self::PolychromeSprites { texture_id, range } => {
729                format!(
730                    "polychrome sprites ({}) on atlas {}",
731                    range.len(),
732                    texture_id.index
733                )
734            }
735            Self::Surfaces(range) => format!("surfaces ({})", range.len()),
736        }
737    }
738}
739
740#[derive(Default, Debug, Copy, Clone)]
741#[repr(C)]
742#[expect(missing_docs)]
743pub struct Quad {
744    pub order: DrawOrder,
745    pub border_style: BorderStyle,
746    pub bounds: Bounds<ScaledPixels>,
747    pub content_mask: ContentMask<ScaledPixels>,
748    pub background: Background,
749    pub border_color: Hsla,
750    pub corner_radii: Corners<ScaledPixels>,
751    pub border_widths: Edges<ScaledPixels>,
752}
753
754impl From<Quad> for Primitive {
755    fn from(quad: Quad) -> Self {
756        Primitive::Quad(quad)
757    }
758}
759
760#[derive(Debug, Copy, Clone)]
761#[repr(C)]
762#[expect(missing_docs)]
763pub struct Underline {
764    pub order: DrawOrder,
765    pub pad: u32, // align to 8 bytes
766    pub bounds: Bounds<ScaledPixels>,
767    pub content_mask: ContentMask<ScaledPixels>,
768    pub color: Hsla,
769    pub thickness: ScaledPixels,
770    pub wavy: PaddedBool32,
771}
772
773impl From<Underline> for Primitive {
774    fn from(underline: Underline) -> Self {
775        Primitive::Underline(underline)
776    }
777}
778
779#[derive(Debug, Copy, Clone)]
780#[repr(C)]
781#[expect(missing_docs)]
782pub struct Shadow {
783    pub order: DrawOrder,
784    pub blur_radius: ScaledPixels,
785    pub bounds: Bounds<ScaledPixels>,
786    pub corner_radii: Corners<ScaledPixels>,
787    pub content_mask: ContentMask<ScaledPixels>,
788    pub color: Hsla,
789    pub shape_bounds: Bounds<ScaledPixels>,
790    pub shape_corner_radii: Corners<ScaledPixels>,
791    pub inset: PaddedBool32,
792    pub pad: u32, // align to 8 bytes
793}
794
795impl From<Shadow> for Primitive {
796    fn from(shadow: Shadow) -> Self {
797        Primitive::Shadow(shadow)
798    }
799}
800
801/// The style of a border.
802#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
803#[repr(C)]
804pub enum BorderStyle {
805    /// A solid border.
806    #[default]
807    Solid = 0,
808    /// A dashed border.
809    Dashed = 1,
810}
811
812/// A data type representing a 2 dimensional transformation that can be applied to an element.
813#[derive(Debug, Clone, Copy, PartialEq)]
814#[repr(C)]
815pub struct TransformationMatrix {
816    /// 2x2 matrix containing rotation and scale,
817    /// stored row-major
818    pub rotation_scale: [[f32; 2]; 2],
819    /// translation vector
820    pub translation: [f32; 2],
821}
822
823impl Eq for TransformationMatrix {}
824
825impl TransformationMatrix {
826    /// The unit matrix, has no effect.
827    pub fn unit() -> Self {
828        Self {
829            rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
830            translation: [0.0, 0.0],
831        }
832    }
833
834    /// Move the origin by a given point
835    pub fn translate(self, point: Point<ScaledPixels>) -> Self {
836        self.compose(Self {
837            rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
838            translation: [point.x.0, point.y.0],
839        })
840    }
841
842    /// Clockwise rotation in radians around the origin
843    pub fn rotate(self, angle: Radians) -> Self {
844        self.compose(Self {
845            rotation_scale: [
846                [angle.0.cos(), -angle.0.sin()],
847                [angle.0.sin(), angle.0.cos()],
848            ],
849            translation: [0.0, 0.0],
850        })
851    }
852
853    /// Scale around the origin
854    pub fn scale(self, size: Size<f32>) -> Self {
855        self.compose(Self {
856            rotation_scale: [[size.width, 0.0], [0.0, size.height]],
857            translation: [0.0, 0.0],
858        })
859    }
860
861    /// Perform matrix multiplication with another transformation
862    /// to produce a new transformation that is the result of
863    /// applying both transformations: first, `other`, then `self`.
864    #[inline]
865    pub fn compose(self, other: TransformationMatrix) -> TransformationMatrix {
866        if other == Self::unit() {
867            return self;
868        }
869        // Perform matrix multiplication
870        TransformationMatrix {
871            rotation_scale: [
872                [
873                    self.rotation_scale[0][0] * other.rotation_scale[0][0]
874                        + self.rotation_scale[0][1] * other.rotation_scale[1][0],
875                    self.rotation_scale[0][0] * other.rotation_scale[0][1]
876                        + self.rotation_scale[0][1] * other.rotation_scale[1][1],
877                ],
878                [
879                    self.rotation_scale[1][0] * other.rotation_scale[0][0]
880                        + self.rotation_scale[1][1] * other.rotation_scale[1][0],
881                    self.rotation_scale[1][0] * other.rotation_scale[0][1]
882                        + self.rotation_scale[1][1] * other.rotation_scale[1][1],
883                ],
884            ],
885            translation: [
886                self.translation[0]
887                    + self.rotation_scale[0][0] * other.translation[0]
888                    + self.rotation_scale[0][1] * other.translation[1],
889                self.translation[1]
890                    + self.rotation_scale[1][0] * other.translation[0]
891                    + self.rotation_scale[1][1] * other.translation[1],
892            ],
893        }
894    }
895
896    /// The smallest bounds that contain `bounds` once it is transformed.
897    pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
898        if *self == Self::unit() {
899            return bounds;
900        }
901        let [[xx, xy], [yx, yy]] = self.rotation_scale;
902        let [translate_x, translate_y] = self.translation;
903        let corners = [
904            bounds.origin,
905            bounds.top_right(),
906            bounds.bottom_left(),
907            bounds.bottom_right(),
908        ]
909        .map(|corner| {
910            Point::new(
911                ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
912                ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
913            )
914        });
915        let [first, rest @ ..] = corners;
916        let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
917        let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
918        Bounds::from_corners(top_left, bottom_right)
919    }
920
921    /// Apply transformation to a point, mainly useful for debugging
922    pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
923        let input = [point.x.0, point.y.0];
924        let mut output = self.translation;
925        for (i, output_cell) in output.iter_mut().enumerate() {
926            for (k, input_cell) in input.iter().enumerate() {
927                *output_cell += self.rotation_scale[i][k] * *input_cell;
928            }
929        }
930        Point::new(output[0].into(), output[1].into())
931    }
932}
933
934impl Default for TransformationMatrix {
935    fn default() -> Self {
936        Self::unit()
937    }
938}
939
940#[derive(Copy, Clone, Debug)]
941#[repr(C)]
942#[expect(missing_docs)]
943pub struct MonochromeSprite {
944    pub order: DrawOrder,
945    pub animation: SpriteAnimationId,
946    pub tile: AtlasTile,
947    pub bounds: Bounds<ScaledPixels>,
948    pub content_mask: ContentMask<ScaledPixels>,
949    pub color: Hsla,
950    pub transformation: TransformationMatrix,
951}
952
953/// Refers to an animation of the scene a sprite is inserted into.
954///
955/// A single `u32` so it fits the sprite's existing padding and leaves the
956/// instance layout unchanged on every backend; renderers ignore it.
957#[derive(Copy, Clone, Debug, PartialEq, Eq)]
958#[repr(transparent)]
959pub struct SpriteAnimationId(u32);
960
961impl SpriteAnimationId {
962    /// No animation.
963    pub const NONE: Self = Self(u32::MAX);
964}
965
966impl Default for SpriteAnimationId {
967    fn default() -> Self {
968        Self::NONE
969    }
970}
971
972/// A [`TimedTransformation`] the window applies to a sprite right before
973/// every present, so the scene can be presented again without being redrawn.
974#[derive(Copy, Clone, Debug)]
975pub(crate) struct SpriteAnimation {
976    transformation: TimedTransformation,
977    center: Point<Pixels>,
978    scale_factor: f32,
979    base_color: Hsla,
980    sprite_index: usize,
981}
982
983impl SpriteAnimation {
984    pub(crate) fn new(
985        transformation: TimedTransformation,
986        center: Point<Pixels>,
987        scale_factor: f32,
988    ) -> Self {
989        Self {
990            transformation,
991            center,
992            scale_factor,
993            base_color: Hsla::default(),
994            sprite_index: usize::MAX,
995        }
996    }
997}
998
999impl From<MonochromeSprite> for Primitive {
1000    fn from(sprite: MonochromeSprite) -> Self {
1001        Primitive::MonochromeSprite(sprite)
1002    }
1003}
1004
1005#[derive(Copy, Clone, Debug)]
1006#[repr(C)]
1007#[expect(missing_docs)]
1008pub struct SubpixelSprite {
1009    pub order: DrawOrder,
1010    pub pad: u32, // align to 8 bytes
1011    pub tile: AtlasTile,
1012    pub bounds: Bounds<ScaledPixels>,
1013    pub content_mask: ContentMask<ScaledPixels>,
1014    pub color: Hsla,
1015    pub transformation: TransformationMatrix,
1016}
1017
1018impl From<SubpixelSprite> for Primitive {
1019    fn from(sprite: SubpixelSprite) -> Self {
1020        Primitive::SubpixelSprite(sprite)
1021    }
1022}
1023
1024#[derive(Copy, Clone, Debug)]
1025#[repr(C)]
1026#[expect(missing_docs)]
1027pub struct PolychromeSprite {
1028    pub order: DrawOrder,
1029    pub pad: u32,
1030    pub tile: AtlasTile,
1031    pub grayscale: PaddedBool32,
1032    pub opacity: f32,
1033    pub bounds: Bounds<ScaledPixels>,
1034    pub content_mask: ContentMask<ScaledPixels>,
1035    pub corner_radii: Corners<ScaledPixels>,
1036}
1037
1038impl From<PolychromeSprite> for Primitive {
1039    fn from(sprite: PolychromeSprite) -> Self {
1040        Primitive::PolychromeSprite(sprite)
1041    }
1042}
1043
1044#[derive(Clone, Debug)]
1045#[allow(missing_docs)]
1046pub struct PaintSurface {
1047    pub order: DrawOrder,
1048    pub bounds: Bounds<ScaledPixels>,
1049    pub content_mask: ContentMask<ScaledPixels>,
1050    #[cfg(any(target_os = "macos", target_os = "ios"))]
1051    pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
1052}
1053
1054impl From<PaintSurface> for Primitive {
1055    fn from(surface: PaintSurface) -> Self {
1056        Primitive::Surface(surface)
1057    }
1058}
1059
1060#[derive(Clone, Copy, Debug, PartialEq)]
1061#[repr(C)]
1062#[expect(missing_docs)]
1063pub struct PathCurve {
1064    pub p0: Point<f32>,
1065    pub p1: Point<f32>,
1066    pub a: Point<f32>,
1067    pub b: Point<f32>,
1068    pub sign: f32,
1069    pub pad: u32, // align to 8 bytes
1070}
1071
1072#[derive(Clone, Copy, Debug)]
1073#[repr(C)]
1074#[expect(missing_docs)]
1075pub struct PathPaint {
1076    /// The path's bounds, in device pixels.
1077    pub bounds: Bounds<ScaledPixels>,
1078    pub content_mask: ContentMask<ScaledPixels>,
1079    pub color: Background,
1080    pub even_odd: PaddedBool32,
1081    pub pad: u32, // align to 8 bytes
1082}
1083
1084#[derive(Clone, Copy, Debug, PartialEq)]
1085#[repr(C)]
1086#[expect(missing_docs)]
1087pub struct PathTile {
1088    pub paint: u32,
1089    pub curve_start: u32,
1090    pub curve_count: u32,
1091    pub backdrop: i32,
1092    pub top_left: Point<f32>,
1093    pub bottom_right: Point<f32>,
1094    pub reference: Point<f32>,
1095    pub curves_top_left: Point<f32>,
1096    pub curves_bottom_right: Point<f32>,
1097}
1098
1099#[derive(Clone, Debug)]
1100#[expect(missing_docs)]
1101pub struct PaintedPath {
1102    order: DrawOrder,
1103    bounds: Bounds<ScaledPixels>,
1104    tiles: Rc<PathTiles>,
1105    paint: PathPaint,
1106}
1107
1108#[expect(missing_docs)]
1109impl PaintedPath {
1110    /// Bins `path` into tiles, to be filled with `color` within `content_mask`.
1111    pub fn new(
1112        path: Path,
1113        scale_factor: f32,
1114        content_mask: ContentMask<Pixels>,
1115        color: Background,
1116    ) -> Self {
1117        let content_mask = content_mask.scale(scale_factor);
1118        let mut tiles = path.bin(scale_factor);
1119        tiles.retain_visible(content_mask.bounds);
1120        let paint = PathPaint {
1121            bounds: tiles.bounds(),
1122            content_mask,
1123            color,
1124            even_odd: path.even_odd().into(),
1125            pad: 0,
1126        };
1127        Self {
1128            order: 0,
1129            bounds: tiles.painted_bounds(),
1130            tiles: Rc::new(tiles),
1131            paint,
1132        }
1133    }
1134
1135    pub fn tile_count(&self) -> usize {
1136        self.tiles.tiles().len()
1137    }
1138
1139    pub fn append_to(
1140        &self,
1141        paints: &mut Vec<PathPaint>,
1142        curves: &mut Vec<PathCurve>,
1143        tiles: &mut Vec<PathTile>,
1144    ) {
1145        let paint_index = paints.len() as u32;
1146        let curve_start = curves.len() as u32;
1147        paints.push(self.paint);
1148        curves.extend_from_slice(self.tiles.curves());
1149        tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
1150            paint: paint_index,
1151            curve_start: curve_start + tile.curve_start,
1152            ..*tile
1153        }));
1154    }
1155}
1156
1157impl From<PaintedPath> for Primitive {
1158    fn from(path: PaintedPath) -> Self {
1159        Primitive::Path(path)
1160    }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    use super::*;
1166    use crate::{point, size};
1167
1168    fn square(x: f32) -> Bounds<ScaledPixels> {
1169        Bounds {
1170            origin: point(ScaledPixels(x), ScaledPixels(0.)),
1171            size: size(ScaledPixels(10.), ScaledPixels(10.)),
1172        }
1173    }
1174
1175    fn quad(x: f32) -> Quad {
1176        Quad {
1177            bounds: square(x),
1178            content_mask: ContentMask { bounds: square(x) },
1179            ..Default::default()
1180        }
1181    }
1182
1183    fn underline(x: f32) -> Underline {
1184        Underline {
1185            order: 0,
1186            pad: 0,
1187            bounds: square(x),
1188            content_mask: ContentMask { bounds: square(x) },
1189            color: Hsla::default(),
1190            thickness: ScaledPixels(1.),
1191            wavy: false.into(),
1192        }
1193    }
1194
1195    fn batch_labels(scene: &mut Scene) -> Vec<String> {
1196        scene.finish();
1197        scene.batches().map(|batch| batch.label()).collect()
1198    }
1199
1200    #[test]
1201    fn layers_are_drawn_in_paint_order() {
1202        // A quad painted after a layer goes above it.
1203        let mut scene = Scene::default();
1204        scene.insert_primitive(quad(0.));
1205        scene.push_layer();
1206        scene.insert_primitive(underline(0.));
1207        scene.insert_primitive(underline(5.));
1208        scene.pop_layer();
1209        scene.insert_primitive(quad(5.));
1210        assert_eq!(
1211            batch_labels(&mut scene),
1212            ["quads (1)", "underlines (2)", "quads (1)"]
1213        );
1214
1215        // A layer goes above the layer painted before it.
1216        let mut scene = Scene::default();
1217        scene.push_layer();
1218        scene.insert_primitive(underline(0.));
1219        scene.pop_layer();
1220        scene.push_layer();
1221        scene.insert_primitive(quad(5.));
1222        scene.pop_layer();
1223        assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
1224    }
1225
1226    #[test]
1227    fn nested_layers_are_drawn_above_their_parents() {
1228        // A layer has one draw order, so what it paints after a nested layer
1229        // still goes below that layer.
1230        let mut scene = Scene::default();
1231        scene.push_layer();
1232        scene.insert_primitive(underline(0.));
1233        scene.push_layer();
1234        scene.insert_primitive(quad(5.));
1235        scene.pop_layer();
1236        scene.insert_primitive(underline(5.));
1237        scene.pop_layer();
1238        assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
1239
1240        // The same holds when the nested layer shares its parent's order.
1241        let mut scene = Scene::default();
1242        scene.push_layer();
1243        scene.insert_primitive(quad(0.));
1244        scene.push_layer();
1245        scene.insert_primitive(quad(5.));
1246        scene.pop_layer();
1247        scene.insert_primitive(quad(8.));
1248        scene.pop_layer();
1249        assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
1250        assert_eq!(
1251            scene
1252                .quads
1253                .iter()
1254                .map(|quad| quad.bounds)
1255                .collect::<Vec<_>>(),
1256            [square(0.), square(8.), square(5.)]
1257        );
1258
1259        // A layer goes above the layers nested in the layer before it.
1260        let mut scene = Scene::default();
1261        scene.push_layer();
1262        scene.push_layer();
1263        scene.insert_primitive(underline(0.));
1264        scene.pop_layer();
1265        scene.pop_layer();
1266        scene.push_layer();
1267        scene.insert_primitive(quad(5.));
1268        scene.pop_layer();
1269        assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
1270    }
1271}