teksilo-canvas 0.9.0

Canvas and geometry layer for Teksilo — RenderFrame, Path, Paint and the TextBackend trait.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use std::borrow::Cow;

use crate::geometry::{Rect, Transform2D};
use crate::paint::{FillRule, StrokeSpace, StrokeStyle};

/// The complete render output for one frame. This is the boundary between
/// platform-independent widget code and GPU-specific rendering code.
#[derive(Debug, Clone, Default)]
pub struct RenderFrame {
    pub glyphs: Vec<GlyphQuad>,
    pub images: Vec<ImageQuad>,
    pub decorations: Vec<DecorationRect>,
    /// Transform-invariant ("cosmetic" / hairline) lines. Unlike
    /// `decorations`, the width here is NOT baked into geometry — the
    /// renderer applies a constant device-pixel thickness regardless of the
    /// active transform. See [`DrawCommand::CosmeticLine`].
    pub cosmetic_lines: Vec<CosmeticLine>,
    pub shapes: Vec<ShapeQuad>,
    pub shadows: Vec<ShadowQuad>,
    pub rasterized: Vec<RasterizedQuad>,
    pub paths: Vec<PathEntry>,
    /// Animated quads (procedural or sprite-atlas kinds). Emitted by
    /// widgets that opt into the shader-driven animation pipeline via
    /// `ctx.animated_quad()`. The fragment shader samples per-slot
    /// state from a renderer-side uniform buffer updated each frame by
    /// the widget tree — the widget's own `paint()` runs only when
    /// layout changes, not once per animation frame.
    pub animated_quads: Vec<AnimatedQuadDraw>,
    /// Per-slot `AnimParams`, indexed by the `slot` field of each
    /// `AnimatedQuadDraw`. Recomputed by the widget tree every frame
    /// (phase advanced, colors resolved against the current theme)
    /// and uploaded to the renderer's uniform buffer at the top of
    /// `Renderer::render`. Slots whose widget is dormant / offscreen /
    /// in an inactive window keep their last-written values — the
    /// fragment shader still renders, just with stale phase for one
    /// frame until the next tick resumes.
    pub anim_params: Vec<AnimParams>,
    pub draw_order: Vec<DrawCommand>,
    /// Images that need GPU registration before rendering this frame.
    pub pending_images: Vec<PendingImage>,
    /// Opaque [`TextLayout::layout_key`](crate::text_backend::TextLayout::layout_key)
    /// values for every `draw_text*` call that produced glyphs in this
    /// frame. When a widget's `cached_paint` is reused without re-running
    /// `paint()`, the renderer calls `TextBackend::touch_layout(key)` for
    /// each stored key so the backend can refresh the underlying glyph
    /// cache timestamps and avoid evicting still-visible glyphs.
    pub layout_keys: Vec<u64>,
}

impl RenderFrame {
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Merge another frame into this one, appending all entries
    /// and adjusting draw_order indices.
    pub fn merge(&mut self, other: &RenderFrame) {
        let glyph_offset = self.glyphs.len();
        let image_offset = self.images.len();
        let decoration_offset = self.decorations.len();
        let cosmetic_line_offset = self.cosmetic_lines.len();
        let shape_offset = self.shapes.len();
        let shadow_offset = self.shadows.len();
        let rasterized_offset = self.rasterized.len();
        let path_offset = self.paths.len();
        let animated_offset = self.animated_quads.len();

        self.glyphs.extend_from_slice(&other.glyphs);
        self.images.extend_from_slice(&other.images);
        self.decorations.extend_from_slice(&other.decorations);
        self.cosmetic_lines.extend_from_slice(&other.cosmetic_lines);
        self.shapes.extend_from_slice(&other.shapes);
        self.shadows.extend_from_slice(&other.shadows);
        self.rasterized.extend_from_slice(&other.rasterized);
        self.paths.extend_from_slice(&other.paths);
        self.animated_quads.extend_from_slice(&other.animated_quads);
        // `anim_params` is NOT merged index-wise — the widget tree
        // writes one authoritative slice per frame (indexed by
        // registry slot, which is global across the tree). Cached
        // sub-frames carry empty `anim_params`; the outer tree
        // replaces it wholesale after `render()` is called.
        self.layout_keys.extend_from_slice(&other.layout_keys);
        // Merge pending image registrations (deduped by renderer)
        for pending in &other.pending_images {
            if !self.pending_images.iter().any(|p| p.name == pending.name) {
                self.pending_images.push(pending.clone());
            }
        }

        for cmd in &other.draw_order {
            let shifted = match cmd {
                DrawCommand::Glyph(i) => DrawCommand::Glyph(i + glyph_offset),
                DrawCommand::Image(i) => DrawCommand::Image(i + image_offset),
                DrawCommand::Decoration(i) => DrawCommand::Decoration(i + decoration_offset),
                DrawCommand::CosmeticLine(i) => DrawCommand::CosmeticLine(i + cosmetic_line_offset),
                DrawCommand::Shape(i) => DrawCommand::Shape(i + shape_offset),
                DrawCommand::Shadow(i) => DrawCommand::Shadow(i + shadow_offset),
                DrawCommand::Rasterized(i) => DrawCommand::Rasterized(i + rasterized_offset),
                DrawCommand::Path(i) => DrawCommand::Path(i + path_offset),
                DrawCommand::AnimatedQuad(i) => DrawCommand::AnimatedQuad(i + animated_offset),
                other => other.clone(),
            };
            self.draw_order.push(shifted);
        }
    }
}

impl RenderFrame {
    /// Validate that clip and opacity stacks are balanced in the draw order.
    /// Only runs in debug builds. Panics with a descriptive message if
    /// any push/pop pair is unbalanced.
    pub fn debug_validate_stacks(&self) {
        if !cfg!(debug_assertions) {
            return;
        }
        let mut clip_depth: i32 = 0;
        let mut opacity_depth: i32 = 0;
        let mut blend_depth: i32 = 0;
        let mut transform_depth: i32 = 0;
        let mut blur_depth: i32 = 0;
        for (i, cmd) in self.draw_order.iter().enumerate() {
            match cmd {
                DrawCommand::SetClip(_) => clip_depth += 1,
                DrawCommand::ClearClip => {
                    clip_depth -= 1;
                    debug_assert!(
                        clip_depth >= 0,
                        "RenderFrame: ClearClip without matching SetClip at draw_order[{i}]"
                    );
                }
                DrawCommand::SetOpacity(_) => opacity_depth += 1,
                DrawCommand::RestoreOpacity => {
                    opacity_depth -= 1;
                    debug_assert!(
                        opacity_depth >= 0,
                        "RenderFrame: RestoreOpacity without matching SetOpacity at draw_order[{i}]"
                    );
                }
                DrawCommand::SetBlendMode(_) => blend_depth += 1,
                DrawCommand::RestoreBlendMode => {
                    blend_depth -= 1;
                    debug_assert!(
                        blend_depth >= 0,
                        "RenderFrame: RestoreBlendMode without matching SetBlendMode at draw_order[{i}]"
                    );
                }
                DrawCommand::PushTransform(_) => transform_depth += 1,
                DrawCommand::PopTransform => {
                    transform_depth -= 1;
                    debug_assert!(
                        transform_depth >= 0,
                        "RenderFrame: PopTransform without matching PushTransform at draw_order[{i}]"
                    );
                }
                DrawCommand::BeginBlurredSubtree { .. } => blur_depth += 1,
                DrawCommand::EndBlurredSubtree => {
                    blur_depth -= 1;
                    debug_assert!(
                        blur_depth >= 0,
                        "RenderFrame: EndBlurredSubtree without matching BeginBlurredSubtree at draw_order[{i}]"
                    );
                }
                _ => {}
            }
        }
        debug_assert!(
            clip_depth == 0,
            "RenderFrame: {clip_depth} unmatched SetClip(s) without ClearClip"
        );
        debug_assert!(
            opacity_depth == 0,
            "RenderFrame: {opacity_depth} unmatched SetOpacity(s) without RestoreOpacity"
        );
        debug_assert!(
            blend_depth == 0,
            "RenderFrame: {blend_depth} unmatched SetBlendMode(s) without RestoreBlendMode"
        );
        debug_assert!(
            transform_depth == 0,
            "RenderFrame: {transform_depth} unmatched PushTransform(s) without PopTransform"
        );
        debug_assert!(
            blur_depth == 0,
            "RenderFrame: {blur_depth} unmatched BeginBlurredSubtree(s) without EndBlurredSubtree"
        );
    }
}

/// A positioned glyph to render as a textured rectangle from the glyph atlas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GlyphQuad {
    /// Screen position and size: [x, y, width, height] in logical pixels.
    pub screen: [f32; 4],
    /// Atlas position and size: [x, y, width, height] in atlas texture coordinates.
    pub atlas: [f32; 4],
    /// Glyph color: [r, g, b, a]. For monochrome glyphs this is the text
    /// tint. For color emoji it is `[1, 1, 1, 1]` — the atlas region
    /// already holds the pre-multiplied RGBA bitmap, so the renderer
    /// samples `texture.rgb` directly.
    pub color: [f32; 4],
    /// `true` if the atlas region holds a pre-multiplied RGBA color
    /// bitmap (color emoji via COLR/CBDT/sbix). When set, the renderer
    /// must sample `texture.rgb` instead of using the texture as an
    /// alpha mask.
    pub is_color: bool,
}

/// An image quad to render as a textured rectangle.
#[derive(Debug, Clone, PartialEq)]
pub struct ImageQuad {
    /// Screen position and size: [x, y, width, height] in logical pixels.
    pub screen: [f32; 4],
    /// Resource name of the image.
    pub name: String,
    /// When `Some(color)`, the image is rendered as an alpha mask tinted
    /// with this color (shader flag=0). When `None`, the image is rendered
    /// in full color (shader flag=1, existing behavior).
    pub tint: Option<[f32; 4]>,
}

/// An image that needs to be registered (uploaded to GPU) before rendering.
/// Widgets emit these during paint for embedded raster resources.
#[derive(Debug, Clone)]
pub struct PendingImage {
    /// Resource name to register under.
    pub name: String,
    /// Image width in pixels.
    pub width: u32,
    /// Image height in pixels.
    pub height: u32,
    /// RGBA pixel data. Uses `Cow` for zero-copy with compile-time data.
    pub pixels: Cow<'static, [u8]>,
}

/// A colored rectangle for decorations (selections, cursors, underlines, borders, etc.).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecorationRect {
    /// Position and size: [x, y, width, height] in logical pixels.
    pub rect: [f32; 4],
    /// Color: [r, g, b, a].
    pub color: [f32; 4],
    /// What kind of decoration this is.
    pub kind: DecorationKind,
}

/// The kind of decoration a DecorationRect represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecorationKind {
    WidgetBackground,
    Selection,
    Cursor,
    Underline,
    Overline,
    Strikeout,
    FocusRing,
    DropIndicator,
    TableBorder,
    TableCellBackground,
    BlockBackground,
    TextBackground,
    CellSelection,
}

/// A transform-invariant ("cosmetic" / hairline) line. The endpoints are in
/// logical pixels and follow the active transform; `width` is in logical
/// pixels but applied as a constant device thickness (× scale_factor), NOT
/// scaled by the transform's zoom. Emitted by
/// [`Canvas::draw_line`](crate::Canvas::draw_line) /
/// [`Canvas::stroke_rect`](crate::Canvas::stroke_rect) when the stroke is
/// [`StrokeSpace::Device`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CosmeticLine {
    /// Start point [x, y] in logical pixels.
    pub from: [f32; 2],
    /// End point [x, y] in logical pixels.
    pub to: [f32; 2],
    /// Stroke thickness in logical pixels, held transform-invariant.
    pub width: f32,
    /// Color: [r, g, b, a].
    pub color: [f32; 4],
}

/// A shape rendered via SDF (signed distance field) shaders.
#[derive(Debug, Clone, PartialEq)]
pub struct ShapeQuad {
    /// Screen position and size: [x, y, width, height] in logical pixels.
    pub screen: [f32; 4],
    /// Fill color: [r, g, b, a].
    pub color: [f32; 4],
    /// What shape to render.
    pub shape: ShapeKind,
    /// Stroke width (0.0 for filled shapes).
    pub stroke_width: f32,
    /// Whether the stroke width is logical (scales with the view transform) or
    /// device/cosmetic (held constant in device pixels, invariant to zoom). A
    /// cosmetic stroke keeps a hairline border crisp at any scene zoom. Fills
    /// (`stroke_width == 0.0`) ignore this.
    pub stroke_space: StrokeSpace,
    /// Corner radii: [top_left, top_right, bottom_right, bottom_left].
    pub corner_radii: [f32; 4],
    /// Paint type for the shape.
    pub paint_data: PaintData,
}

/// The kind of SDF shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShapeKind {
    RoundedRect,
    Circle,
    Ellipse,
}

/// A CPU-rasterized path result, stored in the shape atlas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RasterizedQuad {
    /// Screen position and size: [x, y, width, height] in logical pixels.
    pub screen: [f32; 4],
    /// Shape atlas position and size: [x, y, width, height] in atlas coordinates.
    pub atlas: [f32; 4],
    /// Tint color: [r, g, b, a].
    pub color: [f32; 4],
}

/// A shadow rendered behind a shape using a separate GPU pipeline with Gaussian blur.
#[derive(Debug, Clone, PartialEq)]
pub struct ShadowQuad {
    /// Shadow bounding box (expanded by blur + spread + offset): [x, y, width, height].
    pub screen: [f32; 4],
    /// Shadow color: [r, g, b, a].
    pub color: [f32; 4],
    /// Corner radii matching the shape: [top_left, top_right, bottom_right, bottom_left].
    pub corner_radii: [f32; 4],
    /// The original shape rect (before offset/spread): [x, y, width, height].
    pub shape_rect: [f32; 4],
    /// Gaussian blur radius.
    pub blur_radius: f32,
    /// Shadow spread amount.
    pub spread: f32,
}

/// A path to be rasterized on the CPU (Tier 3). Stored in the RenderFrame
/// until the renderer rasterizes it into the shape atlas and converts it
/// to a [`RasterizedQuad`].
#[derive(Debug, Clone, PartialEq)]
pub struct PathEntry {
    /// The path commands to rasterize.
    pub path: crate::path::Path,
    /// Fill color: [r, g, b, a].
    pub color: [f32; 4],
    /// Stroke style (width, dash pattern, line cap). A zero width signals
    /// a fill (the rasterizer branches on it).
    pub stroke_style: StrokeStyle,
    /// Fill rule for the fill branch (ignored when stroking).
    pub fill_rule: FillRule,
    /// Bounding rect in logical pixels (computed from path bounds).
    pub bounds: [f32; 4],
    /// Paint type for the fill. Mirrors `ShapeQuad::paint_data` (Tier 2):
    /// `Solid` fills draw through the lean `quad_pipeline` (tinted by
    /// `color`); gradient variants draw through the dedicated
    /// `path_gradient` pipeline, which ignores `color` and instead
    /// samples an analytic gradient using this data.
    ///
    /// Strokes may carry a gradient too (`Canvas::stroke_path_with_paint`): the
    /// gradient pipeline samples the atlas coverage mask, and the mask is the
    /// stroked outline rather than the filled interior — nothing else about the
    /// draw changes. Note the gradient is normalized against `bounds`, which for
    /// a stroke is the outline's *expanded* rect; the canvas re-bases the
    /// gradient's coordinates accordingly, so callers always express them
    /// relative to the path's own bounds.
    pub paint_data: PaintData,
}

/// Paint data for SDF shapes, passed to the GPU shader.
#[derive(Debug, Default, Clone, PartialEq)]
pub enum PaintData {
    #[default]
    Solid,
    LinearGradient {
        start: [f32; 2],
        end: [f32; 2],
        stops: Vec<crate::paint::GradientStop>,
    },
    RadialGradient {
        center: [f32; 2],
        radius: f32,
        stops: Vec<crate::paint::GradientStop>,
    },
    ConicGradient {
        center: [f32; 2],
        start_angle: f32,
        stops: Vec<crate::paint::GradientStop>,
    },
}

/// Compositing blend mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BlendMode {
    #[default]
    Normal,
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
}

/// A draw command referencing an entry in one of the RenderFrame arrays.
/// Commands are recorded in painter's order (back-to-front).
#[derive(Debug, Clone, PartialEq)]
pub enum DrawCommand {
    Glyph(usize),
    Image(usize),
    Decoration(usize),
    /// A transform-invariant cosmetic line — index into
    /// [`RenderFrame::cosmetic_lines`].
    CosmeticLine(usize),
    Shape(usize),
    Shadow(usize),
    Rasterized(usize),
    Path(usize),
    /// Shader-driven animated quad — index into `RenderFrame::animated_quads`.
    /// The per-frame state (phase, frame_index, colors) is NOT in the
    /// vertex data; the renderer looks it up from its uniform buffer
    /// via the `slot` stored in `AnimatedQuadDraw`.
    AnimatedQuad(usize),
    SetClip(Rect),
    ClearClip,
    SetOpacity(f32),
    RestoreOpacity,
    SetBlendMode(BlendMode),
    RestoreBlendMode,
    /// Set the renderer's current transform. **Composes** with the
    /// top of the renderer's transform stack: the new current is
    /// `t.then(stack_top)` — the supplied transform is applied to a
    /// local point *first*, then the stack's outer ancestors compose
    /// outward. For widgets not under any `PushTransform` scope the
    /// stack is `[identity]`, so this behaves as "set absolute" —
    /// backwards compatible.
    SetTransform(Transform2D),
    /// Push a new transform onto the renderer's transform stack.
    /// The new top becomes `t.then(prev_top)` — the deepest (innermost)
    /// `t` applies to a pre-transform local point first, then outer
    /// ancestors compose outward. That becomes the renderer's
    /// `current_transform` until the matching
    /// [`DrawCommand::PopTransform`]. Emitted by the render walker
    /// around a subtree whose root has a `transform_prop` set. See
    /// `WidgetArena::effective_transform` in `teksilo-core` for the
    /// composition mirrored on the arena side (used by hit-testing
    /// and a11y bounds projection).
    PushTransform(Transform2D),
    /// Pop the renderer's transform stack, restoring the previous
    /// top as the new `current_transform`. Must be paired with a
    /// [`DrawCommand::PushTransform`].
    PopTransform,
    /// Begin an offscreen-rendered, blurred subtree. The renderer
    /// allocates an intermediate texture sized to `bounds` (in logical
    /// pixels), redirects subsequent drawing into it, and on the
    /// matching [`DrawCommand::EndBlurredSubtree`] runs a dual-Kawase
    /// blur chain at the requested `radius` and composites the result
    /// back into the parent pass at `bounds`.
    BeginBlurredSubtree {
        bounds: Rect,
        radius: f32,
    },
    /// End an offscreen-rendered, blurred subtree. Must be paired with
    /// a preceding [`DrawCommand::BeginBlurredSubtree`].
    EndBlurredSubtree,
}

/// An animated quad to render with one of the shader-animation pipelines.
/// The fragment shader samples per-slot state from the renderer's uniform
/// buffer (updated each frame by the widget tree's animated-quad
/// registry) — the `slot` field selects which entry to read.
#[derive(Debug, Clone, PartialEq)]
pub struct AnimatedQuadDraw {
    /// Screen-space bounds: [x, y, width, height] in logical pixels.
    pub screen: [f32; 4],
    /// Dense index into the renderer's `AnimParams` uniform array. Owned
    /// and allocated by the widget tree's `AnimatedQuadRegistry`; stable
    /// for the lifetime of one widget mount (freed on rebuild/destroy).
    pub slot: u32,
    /// Which pipeline draws this quad — procedural (sweep, pulse…) or
    /// sprite (texture-atlas frame cycling). Picked once at emit time.
    pub class: AnimatedQuadClass,
}

/// Which shader pipeline a [`DrawCommand::AnimatedQuad`] is routed to.
/// Chosen by the widget at `Canvas::draw_animated_quad` time based on
/// its `AnimatedQuadKind`; the renderer binds the matching pipeline.
#[derive(Debug, Clone, PartialEq)]
pub enum AnimatedQuadClass {
    /// Fully procedural — no texture binding. IndeterminateSweep,
    /// Pulse, Shimmer, etc.
    Procedural,
    /// Samples a texture atlas. Carries the image name so the renderer
    /// can resolve the bind group (same path registered images use).
    Sprite { image_name: String },
}

/// GPU-visible per-slot state for a shader-driven animated quad.
/// Layout must match the WGSL `AnimParams` struct in
/// `teksilo-render/src/shaders/anim_procedural.wgsl` (and the sprite
/// variant). `repr(C)` with explicit `_pad` fields for `std140`
/// compatibility.
///
/// Lives in `teksilo-canvas` (not `teksilo-core`) because it is the
/// serialized-over-the-wire data type between the tree's animated-quad
/// registry and the renderer, and `RenderFrame` is already the
/// tree→renderer data channel.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub struct AnimParams {
    /// Discriminator — 0 = IndeterminateSweep, 1 = SpriteCycle,
    /// 2 = SpinnerArc, ... Matches the `kind: u32` constant in the
    /// fragment shader switch.
    pub kind: u32,
    /// Continuous phase for procedural kinds (0..1) OR integer frame
    /// index (as f32) for sprite kinds. SpinnerArc: rotation phase
    /// (0..1, one full rotation per period).
    pub phase: f32,
    /// IndeterminateSweep: sweep band width (0..1).
    /// SpinnerArc: arc length as a fraction of the full circle.
    /// Other kinds unused.
    pub sweep_ratio: f32,
    /// Generic per-kind parameter slot. SpinnerArc: stroke thickness
    /// as a fraction of the smaller extent (0..0.5). Other kinds
    /// treat this as padding for std140 alignment.
    pub _pad0: f32,
    /// IndeterminateSweep: track color. Unused for sprite and spinner.
    pub color0: [f32; 4],
    /// IndeterminateSweep: fill color. SpriteCycle: tint (alpha 0 = no
    /// tint). SpinnerArc: arc color.
    pub color1: [f32; 4],
    /// Sprite atlas grid width (cols). Unused for procedural.
    pub atlas_cols: f32,
    /// Sprite atlas grid height (rows). Unused for procedural.
    pub atlas_rows: f32,
    pub _pad1: [f32; 2],
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn merge_frames() {
        let mut a = RenderFrame::new();
        a.shapes.push(ShapeQuad {
            screen: [0.0, 0.0, 10.0, 10.0],
            color: [1.0, 0.0, 0.0, 1.0],
            shape: ShapeKind::RoundedRect,
            stroke_width: 0.0,
            stroke_space: StrokeSpace::Logical,
            corner_radii: [0.0; 4],
            paint_data: PaintData::Solid,
        });
        a.draw_order.push(DrawCommand::Shape(0));

        let mut b = RenderFrame::new();
        b.decorations.push(DecorationRect {
            rect: [0.0, 0.0, 5.0, 5.0],
            color: [0.0, 0.0, 1.0, 1.0],
            kind: DecorationKind::FocusRing,
        });
        b.draw_order.push(DrawCommand::Decoration(0));

        a.merge(&b);
        assert_eq!(a.shapes.len(), 1);
        assert_eq!(a.decorations.len(), 1);
        assert_eq!(a.draw_order.len(), 2);
        assert_eq!(a.draw_order[1], DrawCommand::Decoration(0));
    }

    #[test]
    fn merge_preserves_state_commands() {
        let mut a = RenderFrame::new();
        a.draw_order.push(DrawCommand::SetOpacity(0.5));
        let mut b = RenderFrame::new();
        b.draw_order.push(DrawCommand::RestoreOpacity);
        a.merge(&b);
        assert_eq!(a.draw_order.len(), 2);
        assert_eq!(a.draw_order[0], DrawCommand::SetOpacity(0.5));
        assert_eq!(a.draw_order[1], DrawCommand::RestoreOpacity);
    }
}