pane_ui 0.1.0

A RON-driven, hot-reloadable wgpu UI library with spring animations and consistent scaling
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
use crate::draw::{ClipRect, Color, Rect, Scene, ShaderId, TextAlign, TextDraw};
use crate::textures::{TextureId, TextureInfo};
use crate::widgets::WidgetState;
use serde::Deserialize;
use std::f32::consts::PI;

// ── StyleCtx ──────────────────────────────────────────────────────────────────

/// Style lookup context threaded through draw calls.
///
/// Bundles the [`StyleRegistry`] and texture info so functions that need to
/// look up styles or query texture state do not need two separate arguments.
/// When a function also needs to push draw commands, it receives the `scene`
/// separately — keeping `StyleCtx` cheap to copy.
#[derive(Clone, Copy)]
pub struct StyleCtx<'a> {
    pub registry: &'a StyleRegistry,
    pub tex_registry: &'a dyn TextureInfo,
}

// ── Transition ────────────────────────────────────────────────────────────────

/// Describes a visual transition between two [`WidgetState`]s.
///
/// `t = 0.0` renders `from`; `t = 1.0` renders `to`.  Intermediate values
/// produce a linearly interpolated [`VisualState`].
#[derive(Clone, Copy)]
pub struct Transition {
    pub from: WidgetState,
    pub to: WidgetState,
    /// Interpolation factor in `[0.0, 1.0]`.
    pub t: f32,
}

// ── DrawLabel ─────────────────────────────────────────────────────────────────

/// Optional text label drawn on top of a widget.
#[derive(Clone, Copy)]
pub struct DrawLabel<'a> {
    /// Text to render, or `None` to skip the text pass.
    pub label: Option<&'a str>,
    /// Z depth of the text quad.
    pub z: f32,
    /// Scissor clip rect for the text, or `None` for no clipping.
    pub clip: Option<ClipRect>,
    /// Additional alpha multiplier applied on top of `text_color.a`.
    pub alpha: f32,
}

// ── Shape ─────────────────────────────────────────────────────────────────────

/// The geometric outline used when generating widget vertices.
#[derive(Debug, Clone, Deserialize)]
pub enum Shape {
    /// Axis-aligned rectangle with sharp corners.
    Rectangle,
    /// Rectangle with rounded corners; radius set by [`VisualState::corner_radius`].
    RoundedRectangle,
    /// Rectangle whose corner radius is always half the shorter side (a stadium/pill).
    Pill,
    /// Rectangle whose corner radius is half the shorter side, forming a circle
    /// when `width == height`.
    Circle,
    /// Arbitrary convex polygon defined by vertices in normalized bounding-box
    /// space: `[0.0, 0.0]` = top-left, `[1.0, 1.0]` = bottom-right.
    ///
    /// Vertices are wound clockwise. Triangulated via centroid fan — convex
    /// polygons render correctly; concave shapes may have artefacts.
    ///
    /// Pair with the built-in `"polygon"` shader to avoid the rectangular SDF
    /// clip applied by other shaders.
    Polygon(Vec<[f32; 2]>),
}

// ── VisualState ───────────────────────────────────────────────────────────────

/// The complete visual description for one interaction state (idle / hovered /
/// pressed / disabled).
///
/// All four states live inside a [`Style`].  [`Style::resolve`] picks the right
/// one; [`push_component`] can interpolate between two states during a
/// transition.
#[derive(Debug, Clone)]
pub struct VisualState {
    /// Geometric outline of the widget quad.
    pub shape: Shape,
    /// Fill colour of the main quad.  Alpha is multiplied by [`Self::opacity`]
    /// before drawing.
    pub color: Color,
    /// Corner radius in grid units; only used by [`Shape::RoundedRectangle`].
    pub corner_radius: f32,
    /// Width of the border ring in grid units.  `0.0` skips the border pass.
    pub border_width: f32,
    /// Colour of the border ring.
    pub border_color: Color,
    /// Colour of the highlight quad drawn over the top half of the widget.
    /// An alpha of `0.0` skips the highlight pass.
    pub highlight_color: Color,
    /// How far the drop shadow is offset (down-right) from the widget, in grid
    /// units.  `0.0` skips the shadow pass.
    pub shadow_size: f32,
    /// Colour of the drop shadow.
    pub shadow_color: Color,
    /// Master opacity multiplier applied to every colour alpha in this state.
    /// `1.0` = fully opaque, `0.0` = fully transparent.  Defaults to `0.0` so
    /// a `VisualState::default()` is invisible until explicitly configured.
    pub opacity: f32,
    /// Uniform scale applied to the widget quad around its centre.
    /// `1.0` = normal size.  Spring physics let this briefly overshoot `1.0`
    /// for a bounce effect.
    pub scale: f32,
    /// Per-state shader override.  `None` falls back to [`Style::shader`].
    pub shader: Option<ShaderId>,
    /// Optional image or GIF drawn on top of the base shader pass.
    pub texture: Option<TextureId>,
    // ── Text formatting ───────────────────────────────────────────────────────
    /// When `false`, the shadow draw is skipped even if `shadow_size > 0`.
    /// Useful for states where a shadow would look wrong (e.g. pressed).
    pub cast_shadow: bool,
    /// Label text colour.  `None` defaults to opaque white.
    pub text_color: Option<Color>,
    /// Label font size in grid units.  `None` auto-sizes to `height * 0.45`
    /// clamped to `[10, 48]`.
    pub font_size: Option<f32>,
    /// Horizontal alignment of the label within the widget bounds.
    pub text_align: TextAlign,
    /// Additional X offset applied to the label position after centering.
    pub text_offset_x: f32,
    /// Additional Y offset applied to the label position after centering.
    pub text_offset_y: f32,
    /// Font family name.  `None` uses the system sans-serif fallback.
    pub font: Option<String>,
    pub bold: bool,
    pub italic: bool,
}

impl Default for VisualState {
    fn default() -> Self {
        Self {
            shape: Shape::Rectangle,
            color: Color::rgba(0.0, 0.0, 0.0, 0.0),
            corner_radius: 0.0,
            border_width: 0.0,
            border_color: Color::rgba(0.0, 0.0, 0.0, 0.0),
            highlight_color: Color::rgba(0.0, 0.0, 0.0, 0.0),
            shadow_size: 0.0,
            shadow_color: Color::rgba(0.0, 0.0, 0.0, 0.0),
            // opacity = 0.0 → invisible until explicitly set.
            opacity: 0.0,
            scale: 1.0,
            shader: None,
            texture: None,
            cast_shadow: true,
            text_color: None,
            font_size: None,
            text_align: TextAlign::Center,
            text_offset_x: 0.0,
            text_offset_y: 0.0,
            font: None,
            bold: false,
            italic: false,
        }
    }
}

impl VisualState {
    /// Linearly interpolate between `self` (`t = 0`) and `other` (`t = 1`).
    ///
    /// Continuous fields (colours, sizes, opacity, scale) are lerped.
    /// Discrete fields (shader, texture, font, flags) snap to `other` — there
    /// is no meaningful halfway point for them.
    pub fn lerp(&self, other: &Self, t: f32) -> Self {
        Self {
            shape: self.shape.clone(), // shapes do not interpolate
            color: lerp_color(self.color, other.color, t),
            corner_radius: lerp_f32(self.corner_radius, other.corner_radius, t),
            border_width: lerp_f32(self.border_width, other.border_width, t),
            border_color: lerp_color(self.border_color, other.border_color, t),
            highlight_color: lerp_color(self.highlight_color, other.highlight_color, t),
            shadow_size: lerp_f32(self.shadow_size, other.shadow_size, t),
            shadow_color: lerp_color(self.shadow_color, other.shadow_color, t),
            opacity: lerp_f32(self.opacity, other.opacity, t),
            scale: lerp_f32(self.scale, other.scale, t),
            // discrete fields — snap to destination
            shader: other.shader,
            texture: other.texture,
            cast_shadow: other.cast_shadow,
            text_color: other.text_color,
            font_size: other.font_size,
            text_align: other.text_align,
            text_offset_x: other.text_offset_x,
            text_offset_y: other.text_offset_y,
            font: other.font.clone(),
            bold: other.bold,
            italic: other.italic,
        }
    }
}

// ── Style ─────────────────────────────────────────────────────────────────────

/// A complete widget style: four [`VisualState`]s (one per interaction state)
/// plus shader defaults.
pub struct Style {
    /// Fallback shader used when [`VisualState::shader`] is `None`.
    pub shader: ShaderId,
    /// The "textured" shader id used for the texture overlay pass.  Always set
    /// to the built-in `textured` shader by the style loader.
    pub textured: ShaderId,
    pub idle: VisualState,
    pub hovered: VisualState,
    pub pressed: VisualState,
    pub disabled: VisualState,
}

impl Style {
    /// Pick the [`VisualState`] for `state`.
    ///
    /// Priority (highest first): disabled → pressed → hovered → idle.
    /// A widget that is simultaneously hovered and pressed renders as pressed.
    pub const fn resolve(&self, state: WidgetState) -> &VisualState {
        if state.disabled {
            &self.disabled
        } else if state.pressed {
            &self.pressed
        } else if state.hovered {
            &self.hovered
        } else {
            &self.idle
        }
    }
}

// ── StyleId ───────────────────────────────────────────────────────────────────

/// Opaque handle to a [`Style`] stored in [`StyleRegistry`].
///
/// Returned by [`StyleRegistry::register`].  The inner index is intentionally
/// `pub(crate)` — external callers cannot forge or inspect IDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StyleId(usize);

impl StyleId {
    pub(crate) const fn new(index: usize) -> Self {
        Self(index)
    }
    pub(crate) const fn index(self) -> usize {
        self.0
    }
}

// ── StyleRegistry ─────────────────────────────────────────────────────────────

/// Stores all loaded [`Style`]s and provides the main draw entry point.
///
/// Styles are registered once at startup (or on hot-reload) and looked up by
/// [`StyleId`] at draw time.
pub struct StyleRegistry {
    styles: Vec<Style>,
}

impl StyleRegistry {
    /// Create an empty registry.
    pub const fn new() -> Self {
        Self { styles: Vec::new() }
    }

    /// Register `style` and return its [`StyleId`].
    pub fn register(&mut self, style: Style) -> StyleId {
        let id = StyleId::new(self.styles.len());
        self.styles.push(style);
        id
    }

    /// Look up a style by id.
    ///
    /// # Panics
    /// Panics if `id` does not belong to this registry.
    pub fn get(&self, id: StyleId) -> &Style {
        &self.styles[id.index()]
    }

    /// Draw `id` at `rect` for the given widget state, optionally rendering a
    /// text label on top.
    ///
    /// This is the simple (non-transitioning) draw path used when no spring
    /// animation is active.  For animated transitions use [`push_component`].
    pub fn draw(
        &self,
        id: StyleId,
        rect: Rect,
        state: WidgetState,
        dl: DrawLabel<'_>,
        scene: &mut Scene,
        tex_registry: &dyn TextureInfo,
    ) {
        let style = self.get(id);
        let vs = style.resolve(state);

        let state_arr = [
            f32::from(u8::from(state.hovered)),
            f32::from(u8::from(state.pressed)),
            f32::from(u8::from(state.disabled)),
            f32::from(u8::from(state.focused)),
        ];
        draw_visual_state(
            scene,
            tex_registry,
            style,
            vs,
            rect,
            dl.z,
            dl.clip,
            state_arr,
        );

        if let Some(text) = dl.label {
            let font_size = vs
                .font_size
                .unwrap_or_else(|| (rect.h * 0.45).clamp(10.0, 48.0));
            let mut color = vs.text_color.unwrap_or(Color::WHITE);
            color.a *= dl.alpha;
            let tx = rect.x + vs.text_offset_x;
            let ty = (rect.h - font_size).mul_add(0.5, rect.y) + vs.text_offset_y;
            scene.push_text(&TextDraw {
                text,
                x: tx,
                y: ty,
                w: rect.w,
                size: font_size,
                color,
                align: vs.text_align,
                font: vs.font.as_deref(),
                bold: vs.bold,
                italic: vs.italic,
                clip: dl.clip,
                z: dl.z,
            });
        }
    }
}

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

// ── push_component ────────────────────────────────────────────────────────────

/// Draw a widget with a spring-animated transition between two [`WidgetState`]s.
///
/// Interpolates the [`VisualState`] and the shader state array between `tr.from`
/// and `tr.to` using `tr.t`, then pushes all draw commands to `scene`.
/// Returns the interpolated `VisualState` so the caller can position a text
/// label without re-resolving.
pub fn push_component(
    scene: &mut Scene,
    ctx: StyleCtx<'_>,
    style_id: StyleId,
    tr: Transition,
    rect: Rect,
    z: f32,
    clip: Option<ClipRect>,
) -> VisualState {
    let style = ctx.registry.get(style_id);
    let vs = style.resolve(tr.from).lerp(style.resolve(tr.to), tr.t);
    let state_arr = [
        lerp_f32(
            f32::from(u8::from(tr.from.hovered)),
            f32::from(u8::from(tr.to.hovered)),
            tr.t,
        ),
        lerp_f32(
            f32::from(u8::from(tr.from.pressed)),
            f32::from(u8::from(tr.to.pressed)),
            tr.t,
        ),
        lerp_f32(
            f32::from(u8::from(tr.from.disabled)),
            f32::from(u8::from(tr.to.disabled)),
            tr.t,
        ),
        lerp_f32(
            f32::from(u8::from(tr.from.focused)),
            f32::from(u8::from(tr.to.focused)),
            tr.t,
        ),
    ];
    draw_visual_state(
        scene,
        ctx.tex_registry,
        style,
        &vs,
        rect,
        z,
        clip,
        state_arr,
    );
    vs
}

// ── draw_visual_state ─────────────────────────────────────────────────────────

/// Emit all draw commands for one [`VisualState`] at `rect`.
///
/// Rendering is split into two passes:
///
/// **Pass 1 — base shader**: shadow → fill → border → highlight.  Skipped when
/// the state is texture-only (`vs.shader` is `None` and `vs.texture` is `Some`)
/// to avoid drawing a blank quad underneath the image.
///
/// **Pass 2 — texture overlay**: the image or GIF in `vs.texture` drawn on top
/// via the `style.textured` shader.
///
/// `state` is the `[hovered, pressed, disabled, focused]` float array forwarded
/// to the shader as per-instance data.
pub fn draw_visual_state(
    scene: &mut Scene,
    tex_registry: &dyn TextureInfo,
    style: &Style,
    vs: &VisualState,
    rect: Rect,
    z: f32,
    clip: Option<ClipRect>,
    state: [f32; 4],
) {
    let shader = vs.shader.unwrap_or(style.shader);

    let (x, y, w, h) = (rect.x, rect.y, rect.w, rect.h);
    let cx = w.mul_add(0.5, x);
    let cy = h.mul_add(0.5, y);
    let sw = w * vs.scale;
    let sh = h * vs.scale;
    let sx = sw.mul_add(-0.5, cx);
    let sy = sh.mul_add(-0.5, cy);

    // ── Pass 1: Base shader ───────────────────────────────────────────────────
    // Skip when texture-only: no per-state shader override AND a texture is
    // present.  Drawing an empty base pass would add overdraw for no visual gain.
    let has_base = vs.shader.is_some() || vs.texture.is_none();
    if has_base {
        // 1a. Drop shadow
        if vs.cast_shadow && vs.shadow_size > 0.0 {
            let verts = shape_verts(
                &vs.shape,
                sx + vs.shadow_size,
                sy + vs.shadow_size,
                sw,
                sh,
                vs.corner_radius,
            );
            let mut col = vs.shadow_color;
            col.a *= vs.opacity;
            scene.push_widget(
                verts,
                shader,
                col,
                z - 0.1,
                clip,
                vs.corner_radius,
                vs.border_width,
                state,
            );
        }

        // 1b. Main fill
        let verts = shape_verts(&vs.shape, sx, sy, sw, sh, vs.corner_radius);
        let mut col = vs.color;
        col.a *= vs.opacity;
        scene.push_widget(
            verts,
            shader,
            col,
            z,
            clip,
            vs.corner_radius,
            vs.border_width,
            state,
        );

        // 1c. Border ring
        if vs.border_width > 0.0 {
            let verts = border_verts(&vs.shape, sx, sy, sw, sh, vs.corner_radius, vs.border_width);
            let mut col = vs.border_color;
            col.a *= vs.opacity;
            scene.push_widget(
                verts,
                shader,
                col,
                z + 0.01,
                clip,
                vs.corner_radius,
                vs.border_width,
                state,
            );
        }

        // 1d. Highlight — top half of the shape, tinted
        if vs.highlight_color.a > 0.0 {
            let verts = shape_verts(&vs.shape, sx, sy, sw, sh * 0.5, vs.corner_radius);
            let mut col = vs.highlight_color;
            col.a *= vs.opacity;
            scene.push_widget(
                verts,
                shader,
                col,
                z + 0.02,
                clip,
                vs.corner_radius,
                vs.border_width,
                state,
            );
        }
    }

    // ── Pass 2: Texture overlay ───────────────────────────────────────────────
    if let Some(tex) = vs.texture
        && !tex_registry.is_hidden(tex)
    {
        let uv = tex_registry.current_uv_rect(tex);
        scene.push_image_uv(
            Rect::new(sx, sy, sw, sh),
            style.textured,
            tex,
            z + 0.03,
            clip,
            Some(uv),
        );
    }
}

// ── Shape Geometry ────────────────────────────────────────────────────────────

/// Number of arc segments per corner for a given radius.
///
/// Scales with radius so small corners stay cheap and large corners stay smooth
/// up to 4K.  Capped at 256 to bound vertex count.
fn corner_segments(radius: f32) -> u32 {
    ((radius * 8.0) as u32).clamp(8, 256)
}

/// Generate the triangle vertices for `shape` at the given bounds.
fn shape_verts(shape: &Shape, x: f32, y: f32, w: f32, h: f32, radius: f32) -> Vec<[f32; 2]> {
    match shape {
        Shape::Rectangle => rect_verts(x, y, w, h),
        Shape::RoundedRectangle => rounded_rect_verts(x, y, w, h, radius.min(w / 2.0).min(h / 2.0)),
        Shape::Pill => rounded_rect_verts(x, y, w, h, (h / 2.0).min(w / 2.0)),
        Shape::Circle => rounded_rect_verts(x, y, w, h, (w / 2.0).min(h / 2.0)),
        Shape::Polygon(rel_verts) => {
            let abs: Vec<[f32; 2]> = rel_verts
                .iter()
                .map(|v| [v[0].mul_add(w, x), v[1].mul_add(h, y)])
                .collect();
            centroid_fan(&abs)
        }
    }
}

/// Triangulate a convex polygon via a centroid fan.
///
/// Computes the centroid, then emits one triangle per consecutive edge
/// `(centroid, verts[i], verts[i+1])`.  Works correctly for convex polygons;
/// concave polygons may have missing or overlapping triangles.
fn centroid_fan(verts: &[[f32; 2]]) -> Vec<[f32; 2]> {
    if verts.len() < 3 {
        return vec![];
    }
    let n = verts.len() as f32;
    let cx = verts.iter().map(|v| v[0]).sum::<f32>() / n;
    let cy = verts.iter().map(|v| v[1]).sum::<f32>() / n;
    let centroid = [cx, cy];
    let count = verts.len();
    let mut out = Vec::with_capacity(count * 3);
    for i in 0..count {
        let next = (i + 1) % count;
        out.push(centroid);
        out.push(verts[i]);
        out.push(verts[next]);
    }
    out
}

/// Two-triangle rectangle.
fn rect_verts(x: f32, y: f32, w: f32, h: f32) -> Vec<[f32; 2]> {
    vec![
        [x, y],
        [x + w, y],
        [x, y + h],
        [x + w, y],
        [x + w, y + h],
        [x, y + h],
    ]
}

/// Rounded rectangle built from a centre quad, 4 edge quads, and 4 corner fans.
pub fn rounded_rect_verts(x: f32, y: f32, w: f32, h: f32, r: f32) -> Vec<[f32; 2]> {
    let mut v = Vec::new();
    let segs = corner_segments(r);

    // Arc centres at each corner
    let tl = [x + r, y + r];
    let tr = [x + w - r, y + r];
    let br = [x + w - r, y + h - r];
    let bl = [x + r, y + h - r];

    // Centre fill + 4 edge quads
    push_rect(&mut v, x + r, y + r, r.mul_add(-2.0, w), r.mul_add(-2.0, h)); // centre
    push_rect(&mut v, x + r, y, r.mul_add(-2.0, w), r); // top
    push_rect(&mut v, x + r, y + h - r, r.mul_add(-2.0, w), r); // bottom
    push_rect(&mut v, x, y + r, r, r.mul_add(-2.0, h)); // left
    push_rect(&mut v, x + w - r, y + r, r, r.mul_add(-2.0, h)); // right

    // 4 corner fans
    push_corner_fan(&mut v, tl, r, PI, PI * 1.5, segs); // top-left
    push_corner_fan(&mut v, tr, r, PI * 1.5, PI * 2.0, segs); // top-right
    push_corner_fan(&mut v, br, r, 0.0, PI * 0.5, segs); // bottom-right
    push_corner_fan(&mut v, bl, r, PI * 0.5, PI, segs); // bottom-left

    v
}

/// Push a two-triangle rectangle into `v`.
fn push_rect(v: &mut Vec<[f32; 2]>, x: f32, y: f32, w: f32, h: f32) {
    v.extend_from_slice(&[
        [x, y],
        [x + w, y],
        [x, y + h],
        [x + w, y],
        [x + w, y + h],
        [x, y + h],
    ]);
}

/// Push `segs` triangles forming a pie-slice fan from `start` to `end` radians.
fn push_corner_fan(
    v: &mut Vec<[f32; 2]>,
    center: [f32; 2],
    r: f32,
    start: f32,
    end: f32,
    segs: u32,
) {
    let [cx, cy] = center;
    for i in 0..segs {
        let t0 = i as f32 / segs as f32;
        let t1 = (i + 1) as f32 / segs as f32;
        let a0 = (end - start).mul_add(t0, start);
        let a1 = (end - start).mul_add(t1, start);
        v.push([cx, cy]);
        v.push([r.mul_add(a0.cos(), cx), r.mul_add(a0.sin(), cy)]);
        v.push([r.mul_add(a1.cos(), cx), r.mul_add(a1.sin(), cy)]);
    }
}

// ── Border Geometry ───────────────────────────────────────────────────────────

/// Generate a border ring as triangles between outer and inner perimeters.
///
/// Samples `segs_per_corner * 4` evenly-spaced points around both the outer
/// shape and a uniformly inset copy, then stitches adjacent point pairs into
/// quads.  Handles rounded corners and extreme border widths (inner radius
/// clamps to zero).
fn border_verts(
    shape: &Shape,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    radius: f32,
    bw: f32,
) -> Vec<[f32; 2]> {
    let segs_per_corner = corner_segments(radius.min(w / 2.0).min(h / 2.0));
    // segments is always a multiple of 4 (segs_per_corner * 4), so
    // perimeter_points always receives a count it can evenly distribute across
    // the four corners without rounding loss.
    let segments = (segs_per_corner * 4) as usize;

    let outer_r = match shape {
        Shape::Rectangle => 0.0,
        Shape::RoundedRectangle => radius.min(w / 2.0).min(h / 2.0),
        Shape::Pill => (h / 2.0).min(w / 2.0),
        Shape::Circle => (w / 2.0).min(h / 2.0),
        // Polygon borders are not yet supported; skip by returning empty geometry.
        Shape::Polygon(_) => return vec![],
    };
    let inner_r = (outer_r - bw).max(0.0);

    let outer_pts = perimeter_points(x, y, w, h, outer_r, segments);
    let inner_pts = perimeter_points(
        x + bw,
        y + bw,
        bw.mul_add(-2.0, w),
        bw.mul_add(-2.0, h),
        inner_r,
        segments,
    );

    let mut v = Vec::new();
    let n = outer_pts.len();
    for i in 0..n {
        let next = (i + 1) % n;
        let (o0, o1) = (outer_pts[i], outer_pts[next]);
        let (i0, i1) = (inner_pts[i], inner_pts[next]);
        // Two triangles forming a quad strip between outer and inner edges
        v.push(o0);
        v.push(o1);
        v.push(i0);
        v.push(o1);
        v.push(i1);
        v.push(i0);
    }
    v
}

/// Sample `segments` evenly-spaced points around a rounded-rectangle perimeter.
///
/// `segments` must be a multiple of 4; each quarter is distributed across one
/// corner arc.  Points are emitted in counter-clockwise order starting from the
/// top-right corner.
fn perimeter_points(x: f32, y: f32, w: f32, h: f32, r: f32, segments: usize) -> Vec<[f32; 2]> {
    let r = r.min(w / 2.0).min(h / 2.0).max(0.0);
    let mut pts = Vec::new();

    // Corner arc centres with their angular ranges
    let corners = [
        (x + w - r, y + r, PI * 1.5, PI * 2.0), // top-right
        (x + w - r, y + h - r, 0.0, PI * 0.5),  // bottom-right
        (x + r, y + h - r, PI * 0.5, PI),       // bottom-left
        (x + r, y + r, PI, PI * 1.5),           // top-left
    ];

    let segs_per_corner = (segments / 4).max(2);
    for (cx, cy, start, end) in corners {
        for i in 0..segs_per_corner {
            let t = i as f32 / segs_per_corner as f32;
            let a = (end - start).mul_add(t, start);
            pts.push([cx + r * a.cos(), cy + r * a.sin()]);
        }
    }

    pts
}

// ── Interpolation Helpers ─────────────────────────────────────────────────────

/// Linearly interpolate between two `f32` values.
fn lerp_f32(a: f32, b: f32, t: f32) -> f32 {
    (b - a).mul_add(t, a)
}

/// Linearly interpolate between two [`Color`] values, component-wise.
fn lerp_color(a: Color, b: Color, t: f32) -> Color {
    Color::rgba(
        lerp_f32(a.r, b.r, t),
        lerp_f32(a.g, b.g, t),
        lerp_f32(a.b, b.b, t),
        lerp_f32(a.a, b.a, t),
    )
}