cranpose-render-wgpu 0.22.1

GPU renderer for Cranpose scenes through wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Scene structures for GPU rendering

use std::{ops::Range, sync::Arc};

use cranpose_core::NodeId;
pub use cranpose_render_common::graph_scene::{HitRegion, Scene};
use cranpose_render_common::{
    glyph_reach::{InkSpread, glyph_part},
    graph::DrawCommandId,
    layer_shadow::ShadowRRect,
    text_paint::TextPaint,
    text_raster::TextRasterRequest,
};
use cranpose_ui::{TextStyle, text::RenderString};
use cranpose_ui_graphics::{
    BlendMode, Color, ColorFilter, CommandRecording, DrawPrimitive, GraphicsLayer, ImageBitmap,
    ImageSampling, Point, Recorded, Rect, RenderEffect, ShapeRecorder,
};

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct SnapAnchor {
    pub origin: Point,
    pub device_pixel_step: f32,
}

impl SnapAnchor {
    pub(crate) fn rigid(origin: Point) -> Self {
        Self {
            origin,
            device_pixel_step: 1.0,
        }
    }
}

/// The rounded rect of a clip that records drawn in place take coverage
/// from, as a layer clipped to it composites through the same mask: whole,
/// in logical units, even where a rect clip above cuts into it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ClipRounding {
    pub rect: Rect,
    pub radius: f32,
}

/// Edges this close count as one: a clip met through other sums lands a few
/// ulps away from the rect it bounds.
const CLIP_HOLD_SLACK: f32 = 1e-3;

/// Whether `outer` holds `inner` whole, its edges taken within
/// [`CLIP_HOLD_SLACK`].
pub(crate) fn clip_holds(outer: Rect, inner: Rect) -> bool {
    inner.x >= outer.x - CLIP_HOLD_SLACK
        && inner.y >= outer.y - CLIP_HOLD_SLACK
        && inner.x + inner.width <= outer.x + outer.width + CLIP_HOLD_SLACK
        && inner.y + inner.height <= outer.y + outer.height + CLIP_HOLD_SLACK
}

// The bits of a placement's data that the shape shader reads; shape.wgsl
// declares the same.
pub(crate) const PLACEMENT_CANONICALIZE: u32 = 1;
pub(crate) const PLACEMENT_CLIPPED: u32 = 2;
pub(crate) const PLACEMENT_FILTERED: u32 = 4;
pub(crate) const PLACEMENT_PAINTED: u32 = 8;
pub(crate) const PLACEMENT_TURNED: u32 = 16;
const PLACEMENT_ROUNDING_CUT: u32 = 32;

/// Where a recording's record space lands in the scene: the logical
/// offset of its origin, the rigid anchor it snaps with, the clip its
/// records take, and the paint every record takes on the way to the
/// device. One placement per run; the vertex stage reads it as a uniform.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Placement {
    pub offset: Point,
    pub snap_anchor: Option<SnapAnchor>,
    /// The rect nothing outside of is drawn; within a rounding, the part
    /// of its rect that the clips above leave.
    pub clip: Option<Rect>,
    pub rounding: Option<ClipRounding>,
    pub alpha: f32,
    /// Boxed: few layers filter, and inline a filter takes 24 bytes of
    /// every placement against 8.
    pub color_filter: Option<Arc<ColorFilter>>,
}

impl Placement {
    /// Whether the placement paints its records: an alpha or a colour
    /// filter, which may leave an opaque colour translucent.
    pub(crate) fn paints(&self) -> bool {
        self.alpha != 1.0 || self.color_filter.is_some()
    }

    pub(crate) fn at(offset: Point, snap_anchor: Option<SnapAnchor>, clip: Option<Rect>) -> Self {
        Self {
            offset,
            snap_anchor,
            clip,
            rounding: None,
            alpha: 1.0,
            color_filter: None,
        }
    }

    /// The placement whose records take the coverage of `rounding`.
    pub(crate) fn with_rounding(self, rounding: Option<ClipRounding>) -> Self {
        Self { rounding, ..self }
    }

    /// Whether the clip has rounded corners the records take coverage from.
    pub(crate) fn clip_rounded(&self) -> bool {
        self.clip.is_some() && self.rounding.is_some()
    }

    /// Whether a rect clip above cuts into the rounding: only the draw's
    /// scissor, which a draw under a turn has none of, cuts its records.
    pub(crate) fn rounding_cut(&self) -> bool {
        self.rounding.is_some_and(|rounding| {
            self.clip
                .is_none_or(|clip| !clip_holds(clip, rounding.rect))
        })
    }

    /// The clip in device pixels at `root_scale` as x, y, width and height:
    /// snapped to the device grid when the placement is.
    pub(crate) fn device_clip(&self, root_scale: f32) -> Option<[f32; 4]> {
        self.clip.map(|clip| self.device_rect(clip, root_scale))
    }

    /// The rect the placement's records test in device pixels: a rounded
    /// clip's whole rect, from which the draw's scissor cuts what the clips
    /// above leave, else the clip.
    pub(crate) fn tested_device_clip(&self, root_scale: f32) -> Option<[f32; 4]> {
        let rounding = self.rounding.filter(|_| self.clip_rounded());
        rounding
            .map(|rounding| rounding.rect)
            .or(self.clip)
            .map(|clip| self.device_rect(clip, root_scale))
    }

    /// `rect` in device pixels at `root_scale` as x, y, width and height:
    /// snapped to the device grid when the placement is.
    pub(crate) fn device_rect(&self, rect: Rect, root_scale: f32) -> [f32; 4] {
        let device = crate::geometry::device_rect(rect, root_scale, self.snap_anchor.is_some());
        [device.x, device.y, device.width, device.height]
    }

    pub(crate) fn data_flags(&self) -> u32 {
        let mut flags = 0;
        if self.snap_anchor.is_some() {
            flags |= PLACEMENT_CANONICALIZE;
        }
        if self.paints() {
            flags |= PLACEMENT_PAINTED;
        }
        // A rounded clip's records test its whole rect, and the clips above
        // cut it by the paint's scissor alone, which interiors draw without.
        if self.clip_rounded() && self.rounding_cut() {
            flags |= PLACEMENT_ROUNDING_CUT;
        }
        flags
    }

    /// A placement that paints its records with the layer's alpha and
    /// colour filter; the layer's affine part is identity for anything
    /// drawn direct.
    pub(crate) fn painted(
        offset: Point,
        snap_anchor: Option<SnapAnchor>,
        clip: Option<Rect>,
        layer: &GraphicsLayer,
    ) -> Self {
        Self {
            offset,
            snap_anchor,
            clip,
            rounding: None,
            alpha: layer.alpha.clamp(0.0, 1.0),
            color_filter: layer
                .color_filter
                .as_ref()
                .map(|filter| Arc::new(filter.clone())),
        }
    }

    pub(crate) fn translated_bounds(&self, local: Rect) -> Rect {
        local.translate(self.offset.x, self.offset.y)
    }
}

/// One recording's shapes drawn under one placement: the POD tables the
/// GPU reads, shared with the recorder, and the segment range this run
/// covers. `command` keys the retained GPU copy; a run without one (a
/// layer's loose primitives, a shadow) is copied into the frame arena.
#[derive(Clone)]
pub(crate) struct RunDraw {
    pub recorder: Arc<ShapeRecorder>,
    pub command: Option<DrawCommandId>,
    pub segments: Range<u32>,
    pub records: u32,
    pub placement: Placement,
    /// The scene-space rect the run's records can reach, before snapping.
    pub bounds: Rect,
}

impl RunDraw {
    pub(crate) fn of(
        recording: &CommandRecording,
        command: Option<DrawCommandId>,
        segments: Range<u32>,
        placement: Placement,
    ) -> Self {
        let records = recording.shape_count_in(&segments);
        Self::with_bounds_and_records(
            Arc::clone(recording.shape_recorder()),
            command,
            segments,
            records,
            recording.shape_bounds(),
            placement,
        )
    }

    fn with_bounds_and_records(
        recorder: Arc<ShapeRecorder>,
        command: Option<DrawCommandId>,
        segments: Range<u32>,
        records: u32,
        shape_bounds: Option<Rect>,
        placement: Placement,
    ) -> Self {
        let bounds = shape_bounds.map_or(
            Rect {
                x: placement.offset.x,
                y: placement.offset.y,
                width: 0.0,
                height: 0.0,
            },
            |bounds| placement.translated_bounds(bounds),
        );
        Self {
            recorder,
            command,
            segments,
            records,
            placement,
            bounds,
        }
    }

    /// The whole recorder as one run, when it recorded anything.
    pub(crate) fn whole(recorder: Arc<ShapeRecorder>, placement: Placement) -> Option<Self> {
        (!recorder.is_empty()).then(|| {
            let segments = recorder.all_segments();
            let records = recorder.tables().shapes.len() as u32;
            let bounds = recorder.bounds();
            Self::with_bounds_and_records(recorder, None, segments, records, bounds, placement)
        })
    }

    pub(crate) fn tables(&self) -> &cranpose_ui_graphics::RecordTables {
        self.recorder.tables()
    }

    pub(crate) fn segment_records(
        &self,
    ) -> impl Iterator<Item = &cranpose_ui_graphics::RecordSegment> {
        self.tables().segments[self.segments.start as usize..self.segments.end as usize]
            .iter()
            .filter(|segment| segment.lane == cranpose_ui_graphics::RecordLane::Shapes)
    }

    pub(crate) fn record_count(&self) -> u32 {
        self.records
    }
}

/// The primitives a layer pushes one by one, recorded together under the
/// placement they share until one arrives under another placement or
/// something else takes a z between them.
struct LooseRun {
    recorder: ShapeRecorder,
    placement: Placement,
}

/// A text's string as its draws carry it, with what drawing a cached glyph
/// run reads of it and of its style on every frame: the present thread then
/// loads neither for a text whose run it holds.
#[derive(Clone)]
pub(crate) struct DrawnText {
    string: Arc<RenderString>,
    hash: u64,
    empty: bool,
    gradient: bool,
    static_motion: bool,
    spread: InkSpread,
}

impl DrawnText {
    // `string` drawn in `style`, laid out as `layout`.
    pub(crate) fn of_laid_out(
        string: Arc<RenderString>,
        style: &TextStyle,
        layout: &cranpose_text::TextLayout,
    ) -> Self {
        let spread = InkSpread::of_text(style, string.span_styles(), layout);
        Self::of(string, style, spread)
    }

    /// `string` drawn in `style`, its glyphs' ink spread by `spread`.
    pub(crate) fn of(string: Arc<RenderString>, style: &TextStyle, spread: InkSpread) -> Self {
        let paints_gradient = |span: &cranpose_ui::text::SpanStyle| {
            span.brush
                .as_ref()
                .is_some_and(|brush| !matches!(brush, cranpose_ui_graphics::Brush::Solid(_)))
        };
        let gradient = paints_gradient(&style.span_style)
            || string
                .span_styles()
                .iter()
                .any(|span| paints_gradient(&span.item));
        Self {
            hash: string.render_hash(),
            empty: string.is_empty(),
            gradient,
            static_motion: style
                .paragraph_style
                .text_motion
                .unwrap_or(cranpose_ui::text::TextMotion::Static)
                == cranpose_ui::text::TextMotion::Static,
            spread,
            string,
        }
    }

    /// The string of a plain text (see [`TextPaint::plain`]), its facts
    /// taken from the paint its node worked out: a plain text paints no
    /// gradient, in its style or in a span.
    pub(crate) fn plain(string: Arc<RenderString>, paint: &TextPaint) -> Self {
        Self {
            string,
            hash: paint.text_hash,
            empty: paint.text_empty,
            gradient: false,
            static_motion: paint.static_motion,
            spread: paint.spread,
        }
    }

    pub(crate) fn string(&self) -> &Arc<RenderString> {
        &self.string
    }

    /// [`RenderString::render_hash`] of the string.
    pub(crate) fn render_hash(&self) -> u64 {
        self.hash
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.empty
    }

    /// Whether the style or a span of the string paints with a gradient
    /// brush.
    pub(crate) fn gradient(&self) -> bool {
        self.gradient
    }

    /// Whether the style's motion is static, so its glyphs stay on whole
    /// pixels.
    pub(crate) fn static_motion(&self) -> bool {
        self.static_motion
    }
}

#[derive(Clone)]
pub(crate) struct TextDraw {
    pub node_id: NodeId,
    pub rect: Rect,
    pub snap_anchor: Option<SnapAnchor>,
    pub text: DrawnText,
    /// The lines and glyphs, from `rect`'s top left corner.
    pub layout: cranpose_text::TextLayout,
    pub color: Color,
    pub text_style: Arc<TextStyle>,
    /// `text_style`'s [`TextStyle::render_hash`], hashed once per text.
    pub style_hash: u64,
    pub font_size: f32,
    pub scale: f32,
    pub clip: Option<Rect>,
}

impl TextDraw {
    // The text laid out in `rect` at `scale` device pixels per logical pixel.
    pub(crate) fn raster_request(&self, rect: Rect, scale: f32) -> TextRasterRequest<'_> {
        TextRasterRequest::new(
            &self.layout,
            self.text.string().as_ref(),
            rect,
            &self.text_style,
            self.color,
            scale,
        )
    }

    // The part of `rect`, where the text draws from its top left corner at
    // `scale` units of `rect` a layout pixel, in which its glyphs and their
    // shadows draw.
    pub(crate) fn glyph_reach(&self, rect: Rect, scale: f32) -> Rect {
        glyph_part(rect, &self.layout, scale, self.text.spread)
    }
}

#[derive(Clone)]
pub(crate) struct ImageDraw {
    pub rect: Rect,
    pub quad: [[f32; 2]; 4],
    pub snap_anchor: Option<SnapAnchor>,
    pub image: ImageBitmap,
    pub alpha: f32,
    pub color_filter: Option<ColorFilter>,
    pub sampling: ImageSampling,
    pub clip: Option<Rect>,
    /// The rounded clip the image takes in place.
    pub rounding: Option<ClipRounding>,
    pub blend_mode: BlendMode,
    pub src_rect: Option<Rect>,
    pub motion_context_animated: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum DrawOpKind {
    Run(usize),
    Image(usize),
    Text(usize),
    Shadow(usize),
    RRectShadow(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct DrawOp {
    pub z_index: usize,
    pub kind: DrawOpKind,
}

/// A shadow's casters: the shapes as one run in the shadow's own space,
/// the cutouts taken after the blur as another under the same placement,
/// and the texts. The shapes' blend modes ride in the records.
#[derive(Clone)]
pub(crate) struct ShadowDraw {
    pub shapes: Option<RunDraw>,
    pub post_blur_cutouts: Option<RunDraw>,
    pub texts: Vec<TextDraw>,
    pub blur_radius: f32,
    pub clip: Option<Rect>,
    pub rounded_clip: Option<LayerRoundedClip>,
    pub z_index: usize,
}

impl ShadowDraw {
    pub(crate) fn requires_surface(&self) -> bool {
        self.blur_radius > 0.0
            || self.post_blur_cutouts.is_some()
            || self.shapes.as_ref().is_some_and(|shapes| {
                shapes
                    .segment_records()
                    .any(|segment| segment.blend == BlendMode::DstOut)
            })
    }
}

/// One pass of a layer's elevation shadow, drawn straight into the pass:
/// Skia's round rect shadow in the scene's logical space, its color, the
/// clip it is cut to and the rigid anchor it snaps with.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct RRectShadowDraw {
    pub shadow: ShadowRRect,
    pub color: Color,
    pub clip: Option<Rect>,
    pub snap_anchor: Option<SnapAnchor>,
}

#[derive(Clone)]
pub(crate) struct EffectLayer {
    pub rect: Rect,
    pub clip: Option<Rect>,
    pub snap_anchor: Option<SnapAnchor>,
    pub effect: Option<RenderEffect>,
    pub blend_mode: BlendMode,
    pub composite_alpha: f32,
    pub z_start: usize,
    pub z_end: usize,
}

/// A rounded clip in a scene's logical space, applied as a mask when the
/// clipped content is composited from a texture.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LayerRoundedClip {
    pub(crate) rect: Rect,
    pub(crate) radii: [f32; 4],
}

#[derive(Clone)]
pub(crate) struct BackdropLayer {
    pub node_id: Option<NodeId>,
    pub alpha: f32,
    pub rect: Rect,
    /// What the layer paints within: the clips above it and its own.
    pub clip: Option<Rect>,
    /// What its effect may read: the clip the layer is drawn in, the way a
    /// list's edge bounds what lies beneath a control inside it. The layer's
    /// own clip bounds its paint alone, so a control still reads past its
    /// own edge.
    pub reach: Option<Rect>,
    pub rounded_clip: Option<LayerRoundedClip>,
    pub snap_anchor: Option<SnapAnchor>,
    pub effect: RenderEffect,
    pub z_index: usize,
}

pub(crate) struct CompositorScene {
    pub runs: Vec<RunDraw>,
    loose: LooseRun,
    pub images: Vec<ImageDraw>,
    pub texts: Vec<TextDraw>,
    pub shadow_draws: Vec<ShadowDraw>,
    shadow_recorders: Vec<Arc<ShapeRecorder>>,
    pub rrect_shadows: Vec<RRectShadowDraw>,
    pub draw_ops: Vec<DrawOp>,
    pub effect_layers: Vec<EffectLayer>,
    pub backdrop_layers: Vec<BackdropLayer>,
    pub next_z: usize,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct SceneCapacityHint {
    pub runs: usize,
    pub images: usize,
    pub texts: usize,
    pub shadow_draws: usize,
    pub rrect_shadows: usize,
    pub draw_ops: usize,
    pub effect_layers: usize,
    pub backdrop_layers: usize,
}

const SCENE_BUFFER_POOL_LIMIT: usize = 4;

pub(crate) struct SceneBuffers {
    runs: Vec<RunDraw>,
    loose: ShapeRecorder,
    images: Vec<ImageDraw>,
    texts: Vec<TextDraw>,
    shadow_draws: Vec<ShadowDraw>,
    shadow_recorders: Vec<Arc<ShapeRecorder>>,
    rrect_shadows: Vec<RRectShadowDraw>,
    draw_ops: Vec<DrawOp>,
    effect_layers: Vec<EffectLayer>,
    backdrop_layers: Vec<BackdropLayer>,
}

impl Drop for CompositorScene {
    fn drop(&mut self) {
        crate::thread_state::try_with(|state| {
            let Ok(mut pool) = state.scene_buffer_pool.try_borrow_mut() else {
                return;
            };
            if pool.len() >= SCENE_BUFFER_POOL_LIMIT {
                pool.remove(0);
            }
            self.clear();
            pool.push(SceneBuffers {
                runs: std::mem::take(&mut self.runs),
                loose: std::mem::take(&mut self.loose.recorder),
                images: std::mem::take(&mut self.images),
                texts: std::mem::take(&mut self.texts),
                shadow_draws: std::mem::take(&mut self.shadow_draws),
                shadow_recorders: std::mem::take(&mut self.shadow_recorders),
                rrect_shadows: std::mem::take(&mut self.rrect_shadows),
                draw_ops: std::mem::take(&mut self.draw_ops),
                effect_layers: std::mem::take(&mut self.effect_layers),
                backdrop_layers: std::mem::take(&mut self.backdrop_layers),
            });
        });
    }
}

impl CompositorScene {
    pub(crate) fn new() -> Self {
        Self::with_capacity(SceneCapacityHint::default())
    }

    pub(crate) fn with_capacity(hint: SceneCapacityHint) -> Self {
        if let Some(buffers) =
            crate::thread_state::with(|state| state.scene_buffer_pool.borrow_mut().pop())
        {
            return Self {
                runs: buffers.runs,
                loose: LooseRun {
                    recorder: buffers.loose,
                    placement: Placement::at(Point::default(), None, None),
                },
                images: buffers.images,
                texts: buffers.texts,
                shadow_draws: buffers.shadow_draws,
                shadow_recorders: buffers.shadow_recorders,
                rrect_shadows: buffers.rrect_shadows,
                draw_ops: buffers.draw_ops,
                effect_layers: buffers.effect_layers,
                backdrop_layers: buffers.backdrop_layers,
                next_z: 0,
            };
        }
        Self {
            runs: Vec::with_capacity(hint.runs),
            loose: LooseRun {
                recorder: ShapeRecorder::default(),
                placement: Placement::at(Point::default(), None, None),
            },
            images: Vec::with_capacity(hint.images),
            texts: Vec::with_capacity(hint.texts),
            shadow_draws: Vec::with_capacity(hint.shadow_draws),
            shadow_recorders: Vec::new(),
            rrect_shadows: Vec::with_capacity(hint.rrect_shadows),
            draw_ops: Vec::with_capacity(hint.draw_ops),
            effect_layers: Vec::with_capacity(hint.effect_layers),
            backdrop_layers: Vec::with_capacity(hint.backdrop_layers),
            next_z: 0,
        }
    }

    pub(crate) fn capacity_hint(&self) -> SceneCapacityHint {
        SceneCapacityHint {
            runs: self.runs.len(),
            images: self.images.len(),
            texts: self.texts.len(),
            shadow_draws: self.shadow_draws.len(),
            rrect_shadows: self.rrect_shadows.len(),
            draw_ops: self.draw_ops.len(),
            effect_layers: self.effect_layers.len(),
            backdrop_layers: self.backdrop_layers.len(),
        }
    }

    pub(crate) fn clear(&mut self) {
        self.runs.clear();
        self.loose.recorder.clear();
        self.images.clear();
        self.texts.clear();
        let recorder_limit = self.shadow_draws.capacity().saturating_mul(2);
        for shadow in self.shadow_draws.drain(..) {
            for mut run in [shadow.shapes, shadow.post_blur_cutouts]
                .into_iter()
                .flatten()
            {
                if self.shadow_recorders.len() < recorder_limit
                    && let Some(recorder) = Arc::get_mut(&mut run.recorder)
                {
                    recorder.clear();
                    self.shadow_recorders.push(run.recorder);
                }
            }
        }
        self.rrect_shadows.clear();
        self.draw_ops.clear();
        self.effect_layers.clear();
        self.backdrop_layers.clear();
        self.next_z = 0;
    }

    pub(crate) fn next_z(&mut self) -> usize {
        self.flush_loose();
        self.next_z
    }

    pub(crate) fn push_loose(&mut self, primitive: DrawPrimitive, placement: Placement) {
        if !self.loose.recorder.is_empty() && self.loose.placement != placement {
            self.flush_loose();
        }
        self.loose.placement = placement;
        if let Recorded::Other(other) = self.loose.recorder.push_primitive(primitive) {
            unreachable!("only shapes join a loose run, not {other:?}");
        }
    }

    #[inline]
    pub(crate) fn flush_loose(&mut self) {
        if !self.loose.recorder.is_empty() {
            self.push_loose_run();
        }
    }

    #[inline(never)]
    fn push_loose_run(&mut self) {
        let Some(run) = RunDraw::whole(
            Arc::new(std::mem::take(&mut self.loose.recorder)),
            self.loose.placement.clone(),
        ) else {
            return;
        };
        self.push_run_unflushed(run);
    }

    pub(crate) fn push_run(&mut self, run: RunDraw) {
        self.flush_loose();
        self.push_run_unflushed(run);
    }

    fn push_run_unflushed(&mut self, run: RunDraw) {
        let z_index = self.next_z;
        self.next_z += 1;
        let index = self.runs.len();
        self.runs.push(run);
        self.draw_ops.push(DrawOp {
            z_index,
            kind: DrawOpKind::Run(index),
        });
    }

    pub(crate) fn push_image(&mut self, draw: ImageDraw) {
        self.flush_loose();
        let z_index = self.next_z;
        self.next_z += 1;
        let index = self.images.len();
        self.images.push(ImageDraw {
            alpha: draw.alpha.clamp(0.0, 1.0),
            ..draw
        });
        self.draw_ops.push(DrawOp {
            z_index,
            kind: DrawOpKind::Image(index),
        });
    }

    pub(crate) fn push_text(&mut self, draw: TextDraw) {
        self.flush_loose();
        let z_index = self.next_z;
        self.next_z += 1;
        let index = self.texts.len();
        self.texts.push(draw);
        self.draw_ops.push(DrawOp {
            z_index,
            kind: DrawOpKind::Text(index),
        });
    }

    pub(crate) fn take_shadow_recorder(&mut self) -> Arc<ShapeRecorder> {
        self.shadow_recorders.pop().unwrap_or_default()
    }

    pub(crate) fn push_shadow_draw(&mut self, mut draw: ShadowDraw) {
        self.flush_loose();
        let z_index = self.next_z;
        self.next_z += 1;
        let index = self.shadow_draws.len();
        draw.z_index = z_index;
        self.shadow_draws.push(draw);
        self.draw_ops.push(DrawOp {
            z_index,
            kind: DrawOpKind::Shadow(index),
        });
    }

    pub(crate) fn push_rrect_shadow(&mut self, draw: RRectShadowDraw) {
        self.flush_loose();
        let z_index = self.next_z;
        self.next_z += 1;
        let index = self.rrect_shadows.len();
        self.rrect_shadows.push(draw);
        self.draw_ops.push(DrawOp {
            z_index,
            kind: DrawOpKind::RRectShadow(index),
        });
    }

    pub(crate) fn push_effect_layer(&mut self, layer: EffectLayer) {
        self.flush_loose();
        self.effect_layers.push(layer);
    }

    pub(crate) fn push_backdrop_layer(&mut self, mut layer: BackdropLayer) {
        self.flush_loose();
        layer.z_index = self.next_z;
        self.next_z += 1;
        self.backdrop_layers.push(layer);
    }
}

impl Default for CompositorScene {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[path = "tests/scene_tests.rs"]
mod tests;

/// Where a layer's own primitives land: the layer's bounds and local
/// graphics layer, the clip and anchor they inherit, and whether their
/// motion context animates.
#[derive(Clone, Copy)]
pub(crate) struct ContentContext<'a> {
    pub(crate) layer_bounds: Rect,
    pub(crate) local_layer: &'a GraphicsLayer,
    pub(crate) visual_clip: Option<Rect>,
    pub(crate) rounding: Option<ClipRounding>,
    pub(crate) anchor: Option<SnapAnchor>,
    pub(crate) motion_context_animated: bool,
}