uzor-render-hub 1.2.1

uzor-render-hub: unified rendering backend hub — auto-detects GPU, instantiates the right backend (vello-gpu / vello-hybrid / wgpu-instanced / vello-cpu / tiny-skia), submits frames, collects metrics.
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
//! Per-window persistent render state.
//!
//! [`WindowRenderState`] is a **flat struct** that holds all initialized
//! renderer slots plus a [`SurfaceMode`] (GPU swapchain or CPU software
//! buffer).  The active backend is a runtime field — switching backends is
//! done by updating `state.active` through [`RenderHub::set_active`] rather
//! than by recreating the entire state.
//!
//! # Design rationale
//!
//! The old `WindowRenderState` was a 5-variant enum where each variant owned
//! exactly one renderer.  The flat struct replaces this with five `Option<>`
//! slots so multiple renderers can be initialized at the same time, enabling
//! live backend switching without a re-init cycle.
//!
//! ## Send + Sync story
//!
//! `WindowRenderState` is `Send` because:
//! - All wgpu types (`RenderSurface`, devices, queues) are `Send`.
//! - `vello::Renderer`, `vello_hybrid::Renderer`, `InstancedRenderer` are
//!   `Send`.
//! - CPU contexts (`VelloCpuRenderContext`, `TinySkiaCpuRenderContext`) are
//!   `Send`.
//!
//! `WindowRenderState` is **not** `Sync` — it contains interior-mutable GPU
//! state that is not safe to share across threads.  This is fine; the runtime
//! always drives one window from one thread.

use uzor_render_tiny_skia::TinySkiaCpuRenderContext;
use uzor_render_vello_cpu::VelloCpuRenderContext;
use uzor_render_vello_gpu::VelloGpuRenderContext;
use uzor_render_vello_hybrid::VelloHybridRenderContext;
use uzor_render_wgpu_instanced::{InstancedRenderContext, InstancedRenderer};
#[cfg(not(target_arch = "wasm32"))]
use uzor::layout::window::SoftwarePresenter;
use vello::util::{RenderContext as VelloRenderContext, RenderSurface};
use vello::{Renderer as VelloRenderer, Scene};

use crate::backend::RenderBackend;

#[cfg(target_arch = "wasm32")]
use uzor_render_canvas2d::Canvas2dRenderContext;

/// Local alias for vello's GPU device pool.
///
/// vello calls this type `RenderContext`, but that name collides with our
/// public `uzor::render::RenderContext` (the widget draw trait).
pub type GpuDevicePool = VelloRenderContext;

// ── SurfaceMode ───────────────────────────────────────────────────────────────

/// How the window surface is presented.
///
/// All backends that have a GPU adapter available share the same wgpu swapchain
/// — CPU backends upload their pixels via `queue.write_texture` into the same
/// `target_texture`, then the blitter copies to the swapchain (mlc pattern).
///
/// On machines with no GPU the `Software` variant is used instead: only
/// `TinySkia` and `VelloCpu` can run in this mode.  The `Software` variant is
/// not available on `wasm32` (softbuffer is desktop-only).
///
/// On `wasm32` the `Canvas2d` variant is used for DOM canvas rendering.
pub enum SurfaceMode {
    /// wgpu swapchain — used by all backends when a GPU adapter is available.
    ///
    /// CPU backends (VelloCpu, TinySkia) write their pixels via
    /// `queue.write_texture` into `surface.target_texture`, then the blitter
    /// copies the target texture to the swapchain (mlc gpu_submit.rs pattern,
    /// lines 235–258).
    Gpu {
        /// wgpu instance + device pool.
        gpu_pool: GpuDevicePool,
        /// wgpu swapchain bound to the OS window.  `'static` because the window
        /// is kept alive by `WinitWindowProvider` for the entire runtime duration.
        surface: RenderSurface<'static>,
        /// Device index into `gpu_pool.devices`.
        dev_id: usize,
    },
    /// softbuffer software surface — only valid when no GPU is present.
    ///
    /// Only `TinySkia` and `VelloCpu` can render in this mode.
    /// The `presenter` is called once per frame to push the CPU-rasterized
    /// pixel buffer to the OS window.
    #[cfg(not(target_arch = "wasm32"))]
    Software {
        /// Opaque OS window presenter (softbuffer on desktop).
        presenter: Box<dyn SoftwarePresenter>,
        /// Physical width of the software buffer in pixels.
        width: u32,
        /// Physical height of the software buffer in pixels.
        height: u32,
    },
    /// DOM canvas surface (wasm32 only).
    ///
    /// The [`Canvas2dRenderContext`] draws directly into the HTML canvas element.
    /// No GPU swapchain or software buffer is needed — the browser presents the
    /// canvas automatically after each RAF callback.
    #[cfg(target_arch = "wasm32")]
    Canvas2d {
        /// The HTML canvas element being rendered into.
        canvas: web_sys::HtmlCanvasElement,
    },
}

// ── Per-frame context — caller-built, hub-consumed ────────────────────────────

/// Backend-specific render context the caller fills each frame.
///
/// `VelloGpu` borrows the vello scene; the others are owned.
pub enum BackendContext<'a> {
    /// GPU-backed vello scene context.
    VelloGpu(VelloGpuRenderContext<'a>),
    /// vello hybrid context.
    VelloHybrid(VelloHybridRenderContext),
    /// Wgpu instanced draw context.
    Instanced(InstancedRenderContext),
    /// vello CPU context.
    VelloCpu(VelloCpuRenderContext),
    /// tiny-skia CPU context.
    TinySkia(TinySkiaCpuRenderContext),
}

impl<'a> BackendContext<'a> {
    /// Build a `VelloGpu` context from a mutable scene reference.
    pub fn vello_gpu(scene: &'a mut Scene, offset_x: f64, offset_y: f64) -> Self {
        Self::VelloGpu(VelloGpuRenderContext::new(scene, offset_x, offset_y))
    }
    /// Build a `VelloHybrid` context.
    pub fn vello_hybrid(dpr: f64) -> Self {
        Self::VelloHybrid(VelloHybridRenderContext::new(dpr))
    }
    /// Build an `Instanced` context.
    pub fn instanced(screen_w: f32, screen_h: f32, offset_x: f32, offset_y: f32) -> Self {
        Self::Instanced(InstancedRenderContext::new(screen_w, screen_h, offset_x, offset_y))
    }
    /// Build a `VelloCpu` context.
    pub fn vello_cpu(dpr: f64) -> Self {
        Self::VelloCpu(VelloCpuRenderContext::new(dpr))
    }
    /// Build a `TinySkia` context with its own pixel buffer.
    pub fn tiny_skia(width: u32, height: u32, dpr: f64) -> Self {
        Self::TinySkia(TinySkiaCpuRenderContext::new(width, height, dpr))
    }
}

// ── WindowRenderState ─────────────────────────────────────────────────────────

/// Flat per-window render state that holds **all** initialized renderer slots.
///
/// At most one renderer per slot is initialized at any time; slots that are not
/// relevant to the current backend remain `None`.
///
/// # Frame lifecycle
///
/// 1. Call [`begin_frame`](Self::begin_frame) once at the start of each frame.
/// 2. Fill the scene / CPU buffer via the backend-specific accessor.
/// 3. Call [`crate::submit_frame`] to present.
///
/// # Live backend switching
///
/// Update `state.active` (via [`RenderHub::set_active`]) before the next frame.
/// The renderer for the new backend must already be initialized (`Some`); if it
/// is not, [`crate::submit_frame`] will emit a warning and skip the frame.
pub struct WindowRenderState {
    // ── Surface ───────────────────────────────────────────────────────────────
    /// How the frame is presented to the OS window.
    pub(crate) surface: SurfaceMode,

    // ── GPU renderer slots ────────────────────────────────────────────────────
    /// vello GPU renderer (initialized when `VelloGpu` is in the pool).
    pub(crate) vello_gpu_renderer: Option<VelloRenderer>,
    /// vello hybrid renderer (lazy-init on first submit; needs texture format).
    pub(crate) vello_hybrid_renderer: Option<vello_hybrid::Renderer>,
    /// Wgpu instanced renderer (lazy-init on first submit; needs texture format).
    pub(crate) instanced_renderer: Option<InstancedRenderer>,

    // ── CPU renderer slots ────────────────────────────────────────────────────
    /// vello CPU render context.
    pub(crate) vello_cpu_ctx: Option<VelloCpuRenderContext>,
    /// tiny-skia CPU render context.
    pub(crate) tiny_skia_ctx: Option<TinySkiaCpuRenderContext>,

    // ── Canvas 2D context (wasm32 only) ───────────────────────────────────────
    /// HTML Canvas 2D render context.  Only populated when `active` is
    /// [`RenderBackend::Canvas2d`].
    #[cfg(target_arch = "wasm32")]
    pub(crate) canvas2d_ctx: Option<Canvas2dRenderContext>,

    // ── Shared vello scene ────────────────────────────────────────────────────
    /// Per-frame vello scene, reset each frame.  Shared by GPU and Hybrid.
    pub(crate) scene: Scene,

    // ── VelloHybrid per-frame context ─────────────────────────────────────────
    /// vello-hybrid per-frame render context (rebuilt each frame).
    pub(crate) vello_hybrid_ctx: VelloHybridRenderContext,

    // ── Active backend ────────────────────────────────────────────────────────
    /// Currently active backend (set by `RenderHub::set_active`).
    pub(crate) active: RenderBackend,
}

impl WindowRenderState {
    // ── Constructors ──────────────────────────────────────────────────────────

    /// Build a GPU-mode state with vello GPU renderer initialized.
    pub fn new_gpu(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        renderer: VelloRenderer,
        dev_id: usize,
    ) -> Self {
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: Some(renderer),
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::VelloGpu,
        }
    }

    /// Build a GPU-mode state without a vello GPU renderer.
    ///
    /// Used for `VelloHybrid` and `WgpuInstanced` where the renderer is
    /// lazy-initialized on the first submit.
    pub fn new_gpu_no_vello(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
        active: RenderBackend,
        dpr: f64,
    ) -> Self {
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(dpr),
            active,
        }
    }

    /// Build a CPU-only (tiny-skia) state with a software presenter.
    ///
    /// `presenter` is the [`SoftwarePresenter`] obtained from
    /// [`WindowProvider::create_software_presenter`](uzor::layout::window::WindowProvider::create_software_presenter).
    /// It is called once per frame to blit the CPU-rasterized pixels to the OS window.
    ///
    /// Available on native targets only — use the Canvas 2D path on wasm32.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new_cpu(width: u32, height: u32, presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self {
            surface: SurfaceMode::Software { presenter, width, height },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: Some(TinySkiaCpuRenderContext::new(width, height, 1.0)),
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::TinySkia,
        }
    }

    /// Build a CPU-only (vello-cpu) state with a software presenter.
    ///
    /// `presenter` is the [`SoftwarePresenter`] obtained from
    /// [`WindowProvider::create_software_presenter`](uzor::layout::window::WindowProvider::create_software_presenter).
    /// It is called once per frame to blit the CPU-rasterized pixels to the OS window.
    ///
    /// Available on native targets only — use the Canvas 2D path on wasm32.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new_vello_cpu(dpr: f64, presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self {
            surface: SurfaceMode::Software { presenter, width: 0, height: 0 },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: Some(VelloCpuRenderContext::new(dpr)),
            tiny_skia_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(dpr),
            active: RenderBackend::VelloCpu,
        }
    }

    // (helper above the constructor)
}

/// Recreate `surface.target_texture` with the usage flags CPU
/// backends and the screenshot path require: `COPY_SRC | COPY_DST |
/// RENDER_ATTACHMENT` on top of the vello defaults.
///
/// Same shape as the `add_copy_src_to_target_texture` helper used by
/// the screenshot endpoint — kept here so the swapchain comes up
/// with the right usage from the very first frame, not lazily.
#[cfg(not(target_arch = "wasm32"))]
fn recreate_target_with_cpu_usage(
    surface: &mut RenderSurface<'static>,
    device: &wgpu::Device,
) {
    let old = &surface.target_texture;
    let size = old.size();
    let new_texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("target_texture_cpu_swapchain"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::STORAGE_BINDING
            | wgpu::TextureUsages::TEXTURE_BINDING
            | wgpu::TextureUsages::COPY_SRC
            | wgpu::TextureUsages::COPY_DST
            | wgpu::TextureUsages::RENDER_ATTACHMENT,
        view_formats: &[],
    });
    let new_view = new_texture.create_view(&wgpu::TextureViewDescriptor::default());
    surface.target_texture = new_texture;
    surface.target_view = new_view;
}

impl WindowRenderState {
    /// Build a GPU-mode state for tiny-skia (CPU rasteriser, GPU
    /// swapchain).  Each frame the tiny-skia pixmap is uploaded to
    /// `surface.target_texture` via `queue.write_texture` and blitted
    /// to the swapchain — same path mlc uses.
    pub fn new_tiny_skia_gpu(
        gpu_pool: GpuDevicePool,
        mut surface: RenderSurface<'static>,
        dev_id: usize,
    ) -> Self {
        let (w, h) = (surface.config.width.max(1), surface.config.height.max(1));
        // Vello creates `target_texture` with TEXTURE_BINDING | STORAGE_BINDING
        // only; CPU upload needs COPY_DST and the screenshot path needs
        // COPY_SRC.  Recreate the texture with the right usage flags
        // BEFORE handing the surface to the new state.
        recreate_target_with_cpu_usage(&mut surface, &gpu_pool.devices[dev_id].device);
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: Some(TinySkiaCpuRenderContext::new(w, h, 1.0)),
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::TinySkia,
        }
    }

    /// Build a GPU-mode state for vello-cpu (CPU rasteriser, GPU
    /// swapchain).  Mirror of `new_tiny_skia_gpu`.
    pub fn new_vello_cpu_gpu(
        gpu_pool: GpuDevicePool,
        mut surface: RenderSurface<'static>,
        dev_id: usize,
        dpr: f64,
    ) -> Self {
        recreate_target_with_cpu_usage(&mut surface, &gpu_pool.devices[dev_id].device);
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: Some(VelloCpuRenderContext::new(dpr)),
            tiny_skia_ctx: None,
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(dpr),
            active: RenderBackend::VelloCpu,
        }
    }

    /// Build a GPU-mode state for vello-hybrid (renderer lazy-init).
    pub fn new_vello_hybrid(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
        dpr: f64,
    ) -> Self {
        Self::new_gpu_no_vello(gpu_pool, surface, dev_id, RenderBackend::VelloHybrid, dpr)
    }

    /// Build a GPU-mode state for wgpu-instanced (renderer lazy-init).
    pub fn new_wgpu_instanced(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
    ) -> Self {
        Self::new_gpu_no_vello(gpu_pool, surface, dev_id, RenderBackend::InstancedWgpu, 1.0)
    }

    /// Build a Canvas 2D state for DOM canvas rendering (wasm32 only).
    ///
    /// The `canvas` element is the HTML canvas being rendered into.
    /// The `ctx` is a [`Canvas2dRenderContext`] wrapping the
    /// `CanvasRenderingContext2d` obtained from `canvas.getContext("2d")`.
    #[cfg(target_arch = "wasm32")]
    pub fn new_canvas2d(
        canvas: web_sys::HtmlCanvasElement,
        ctx: Canvas2dRenderContext,
    ) -> Self {
        Self {
            surface: SurfaceMode::Canvas2d { canvas },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            canvas2d_ctx: Some(ctx),
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::Canvas2d,
        }
    }

    // ── Accessors ─────────────────────────────────────────────────────────────

    /// The active [`RenderBackend`] for this window.
    pub fn backend(&self) -> RenderBackend {
        self.active
    }

    /// Borrow the wgpu device + queue + render surface tuple, if this
    /// window is GPU-backed.  Returns `None` for software-presented
    /// windows (TinySkia / VelloCpu in headless GPU mode) and on web.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn gpu_handles(&self) -> Option<(&wgpu::Device, &wgpu::Queue, &vello::util::RenderSurface<'static>)> {
        match &self.surface {
            SurfaceMode::Gpu { gpu_pool, surface, dev_id } => {
                let dh = gpu_pool.devices.get(*dev_id)?;
                Some((&dh.device, &dh.queue, surface))
            }
            #[cfg(not(target_arch = "wasm32"))]
            SurfaceMode::Software { .. } => None,
            #[cfg(target_arch = "wasm32")]
            SurfaceMode::Canvas2d { .. } => None,
        }
    }

    /// Mutable variant of [`gpu_handles`] — returns the surface as
    /// `&mut` so callers can patch its texture (e.g. add COPY_SRC for
    /// screenshots).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn gpu_handles_mut(
        &mut self,
    ) -> Option<(&wgpu::Device, &wgpu::Queue, &mut vello::util::RenderSurface<'static>)> {
        match &mut self.surface {
            SurfaceMode::Gpu { gpu_pool, surface, dev_id } => {
                let dh = gpu_pool.devices.get(*dev_id)?;
                Some((&dh.device, &dh.queue, surface))
            }
            #[cfg(not(target_arch = "wasm32"))]
            SurfaceMode::Software { .. } => None,
            #[cfg(target_arch = "wasm32")]
            SurfaceMode::Canvas2d { .. } => None,
        }
    }

    /// Set the active backend (live switching).
    ///
    /// Calls [`ensure_backend_slot`] internally so the matching
    /// renderer / context is ready before the next frame.
    pub fn set_active(&mut self, backend: RenderBackend) {
        self.active = backend;
        self.ensure_backend_slot(backend);
    }

    /// Lazily create whatever renderer / CPU context the given
    /// backend needs.  No-op if the slot is already populated or if
    /// the backend's slot is created on first submit anyway
    /// (`VelloHybrid`, `InstancedWgpu`).  Used after live backend
    /// switching to wake up a previously-cold path on this window.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn ensure_backend_slot(&mut self, backend: RenderBackend) {
        match backend {
            RenderBackend::VelloGpu => {
                if self.vello_gpu_renderer.is_none() {
                    if let Some((device, _, _)) = self.gpu_handles() {
                        match vello::Renderer::new(
                            device,
                            vello::RendererOptions {
                                use_cpu: false,
                                antialiasing_support: vello::AaSupport::all(),
                                num_init_threads: std::num::NonZeroUsize::new(1),
                                pipeline_cache: None,
                            },
                        ) {
                            Ok(r) => self.vello_gpu_renderer = Some(r),
                            Err(e) => eprintln!("[render-hub] VelloGpu renderer init failed: {e}"),
                        }
                    }
                }
            }
            RenderBackend::VelloCpu => {
                if self.vello_cpu_ctx.is_none() {
                    self.vello_cpu_ctx = Some(VelloCpuRenderContext::new(1.0));
                }
            }
            RenderBackend::TinySkia => {
                if self.tiny_skia_ctx.is_none() {
                    let (w, h) = self.gpu_handles()
                        .map(|(_, _, s)| (s.config.width.max(1), s.config.height.max(1)))
                        .unwrap_or((1, 1));
                    self.tiny_skia_ctx = Some(TinySkiaCpuRenderContext::new(w, h, 1.0));
                }
            }
            // Lazy on first submit.
            RenderBackend::VelloHybrid | RenderBackend::InstancedWgpu => {}
            #[cfg(target_arch = "wasm32")]
            RenderBackend::Canvas2d => {}
            #[cfg(not(target_arch = "wasm32"))]
            RenderBackend::Canvas2d => {}
        }
    }

    /// Mutable reference to the vello `Scene` (used by VelloGpu / VelloHybrid).
    pub fn scene_mut(&mut self) -> Option<&mut Scene> {
        match self.active {
            RenderBackend::VelloGpu | RenderBackend::VelloHybrid => Some(&mut self.scene),
            _ => None,
        }
    }

    /// Shared reference to the vello `Scene`.
    pub fn scene(&self) -> Option<&Scene> {
        match self.active {
            RenderBackend::VelloGpu | RenderBackend::VelloHybrid => Some(&self.scene),
            _ => None,
        }
    }

    /// Mutable reference to the tiny-skia CPU context.
    pub fn cpu_ctx_mut(&mut self) -> Option<&mut TinySkiaCpuRenderContext> {
        self.tiny_skia_ctx.as_mut()
    }

    /// Shared reference to the tiny-skia CPU context.
    pub fn cpu_ctx(&self) -> Option<&TinySkiaCpuRenderContext> {
        self.tiny_skia_ctx.as_ref()
    }

    /// Mutable reference to the vello-cpu context.
    pub fn vello_cpu_ctx_mut(&mut self) -> Option<&mut VelloCpuRenderContext> {
        self.vello_cpu_ctx.as_mut()
    }

    /// Shared reference to the vello-cpu context.
    pub fn vello_cpu_ctx(&self) -> Option<&VelloCpuRenderContext> {
        self.vello_cpu_ctx.as_ref()
    }

    /// Mutable reference to the vello-hybrid per-frame context.
    pub fn vello_hybrid_ctx_mut(&mut self) -> Option<&mut VelloHybridRenderContext> {
        if matches!(self.active, RenderBackend::VelloHybrid) {
            Some(&mut self.vello_hybrid_ctx)
        } else {
            None
        }
    }

    /// Mutable reference to the Canvas 2D render context (wasm32 only).
    ///
    /// Returns `Some` only when `active` is [`RenderBackend::Canvas2d`] and
    /// the context has been initialized.
    #[cfg(target_arch = "wasm32")]
    pub fn canvas2d_ctx_mut(&mut self) -> Option<&mut Canvas2dRenderContext> {
        if matches!(self.active, RenderBackend::Canvas2d) {
            self.canvas2d_ctx.as_mut()
        } else {
            None
        }
    }

    /// Shared reference to the Canvas 2D render context (wasm32 only).
    #[cfg(target_arch = "wasm32")]
    pub fn canvas2d_ctx(&self) -> Option<&Canvas2dRenderContext> {
        if matches!(self.active, RenderBackend::Canvas2d) {
            self.canvas2d_ctx.as_ref()
        } else {
            None
        }
    }

    // ── Unified render-context accessor ──────────────────────────────────────

    /// Call `f` with a `&mut dyn RenderContext` wired to the active backend.
    ///
    /// This is the ergonomic entry point for user code inside `App::ui`.
    /// Widget L3 helpers (e.g. `register_layout_manager_button`) accept
    /// `&mut dyn RenderContext`; pass the argument you receive here directly
    /// to those helpers:
    ///
    /// ```rust,ignore
    /// fn ui(&mut self, layout: &mut LayoutManager<NoPanel>, state: &mut WindowRenderState) {
    ///     state.with_render_context(|render| {
    ///         register_layout_manager_button(layout, render, "btn", rect, &layer, &view, &settings);
    ///     });
    /// }
    /// ```
    ///
    /// Returns `None` only when the active backend is `InstancedWgpu` (which
    /// does not expose a `RenderContext`-compatible draw API) or when the
    /// corresponding context slot is uninitialised.
    /// Like [`with_render_context`] but writes into a caller-supplied
    /// `vello::Scene` rather than the per-window main scene.  Used by the
    /// per-region paint scheduler so each region can build into its own
    /// cached scene and the runtime then composites them.
    ///
    /// VelloGpu / VelloHybrid only — returns `None` on backends that don't
    /// expose a vello-style `Scene` (Canvas2d / TinySkia / VelloCpu).
    pub fn with_scene_render_context<R>(
        &mut self,
        scene: &mut Scene,
        f: impl FnOnce(&mut dyn uzor::render::RenderContext) -> R,
    ) -> Option<R> {
        match self.active {
            RenderBackend::VelloGpu => {
                let mut ctx = VelloGpuRenderContext::new(scene, 0.0, 0.0);
                Some(f(&mut ctx))
            }
            RenderBackend::VelloHybrid => {
                // VelloHybrid uses its own context type backed by vello-hybrid::Scene,
                // not vello::Scene. Per-region caching for hybrid is a future patch;
                // for now fall through and let the caller use with_render_context.
                None
            }
            _ => None,
        }
    }

    /// Append a previously-built region scene into the main per-window
    /// scene.  No-op on non-vello backends.
    pub fn append_region_scene(&mut self, region_scene: &Scene) {
        if matches!(self.active, RenderBackend::VelloGpu | RenderBackend::VelloHybrid) {
            self.scene.append(region_scene, None);
        }
    }

    pub fn with_render_context<R>(
        &mut self,
        f: impl FnOnce(&mut dyn uzor::render::RenderContext) -> R,
    ) -> Option<R> {
        match self.active {
            RenderBackend::VelloGpu => {
                let mut ctx = VelloGpuRenderContext::new(&mut self.scene, 0.0, 0.0);
                Some(f(&mut ctx))
            }
            RenderBackend::VelloHybrid => {
                // Route through the dedicated hybrid context; submit_vello_hybrid
                // reads from the same context. Routing through VelloGpuRenderContext
                // would write to the wrong scene and the swapchain stays blank.
                Some(f(&mut self.vello_hybrid_ctx))
            }
            RenderBackend::VelloCpu => {
                let (w, h) = self.gpu_handles()
                    .map(|(_, _, s)| (s.config.width.max(1), s.config.height.max(1)))
                    .unwrap_or((1, 1));
                self.vello_cpu_ctx.as_mut().map(|c| {
                    c.begin_frame(w, h);
                    f(c)
                })
            }
            RenderBackend::TinySkia => {
                let (w, h) = self.gpu_handles()
                    .map(|(_, _, s)| (s.config.width.max(1), s.config.height.max(1)))
                    .unwrap_or((1, 1));
                self.tiny_skia_ctx.as_mut().map(|c| {
                    if c.width() != w || c.height() != h {
                        c.resize(w, h);
                    }
                    f(c)
                })
            }
            RenderBackend::InstancedWgpu => None,
            #[cfg(target_arch = "wasm32")]
            RenderBackend::Canvas2d => {
                self.canvas2d_ctx.as_mut().map(|c| f(c))
            }
            #[cfg(not(target_arch = "wasm32"))]
            RenderBackend::Canvas2d => None,
        }
    }

    // ── Surface lifecycle ─────────────────────────────────────────────────────

    /// Resize the underlying surface to match the window's new physical size.
    ///
    /// For GPU surfaces this re-creates the wgpu swapchain. For software
    /// surfaces it forwards to `SoftwarePresenter::resize` and updates the
    /// stored `width`/`height`.  Caller is responsible for ensuring no GPU
    /// frame is in flight when this is called.
    pub fn resize_surface(&mut self, width: u32, height: u32) {
        if width == 0 || height == 0 {
            return;
        }
        match &mut self.surface {
            SurfaceMode::Gpu { gpu_pool, surface, dev_id } => {
                gpu_pool.resize_surface(surface, width, height);
                // VelloHybrid renderer caches the target dimensions when it
                // was first created. After a swapchain resize we must drop
                // it so the next submit re-creates it with the new size —
                // otherwise the GPU draws into a stale render target and
                // the swapchain shows blank / stretched content.
                if matches!(self.active, RenderBackend::VelloHybrid) {
                    self.vello_hybrid_renderer = None;
                }
                // Vello always recreates the target with
                // STORAGE_BINDING | TEXTURE_BINDING only on resize.
                // We need COPY_SRC (screenshot) and COPY_DST (live
                // backend swap into a CPU rasteriser) on every
                // GPU-backed surface regardless of which renderer is
                // currently active — the user can flip at runtime.
                let device = &gpu_pool.devices[*dev_id].device;
                recreate_target_with_cpu_usage(surface, device);
            }
            #[cfg(not(target_arch = "wasm32"))]
            SurfaceMode::Software { presenter, width: w, height: h } => {
                presenter.resize(width, height);
                *w = width;
                *h = height;
                // Resize the CPU pixmap / vello-cpu render context so the
                // submit path's `cw == width` check succeeds and present()
                // sends a non-empty frame.
                if let Some(ref mut ts) = self.tiny_skia_ctx {
                    ts.resize(width, height);
                }
                // VelloCpuRenderContext's pixmap is rebuilt on each
                // render_to_pixmap_rgba8 call from the buffer the submit
                // path provides — no explicit resize needed here.
            }
            #[cfg(target_arch = "wasm32")]
            SurfaceMode::Canvas2d { .. } => {
                // The canvas element resize is handled by the DOM layout —
                // nothing to do here.
            }
        }
    }

    // ── Frame lifecycle ───────────────────────────────────────────────────────

    /// Reset per-frame artifacts.  Call at the top of each frame.
    pub fn begin_frame(&mut self) {
        match self.active {
            RenderBackend::VelloGpu => self.scene.reset(),
            RenderBackend::VelloHybrid => {
                // Re-create / reset the hybrid scene with the current swapchain
                // size so the caller can paint into it.  Without this the
                // hybrid scene stays None and the swapchain stays blank.
                if let SurfaceMode::Gpu { ref surface, .. } = self.surface {
                    self.vello_hybrid_ctx
                        .begin_frame(surface.config.width, surface.config.height);
                }
            }
            RenderBackend::VelloCpu
            | RenderBackend::TinySkia
            | RenderBackend::InstancedWgpu => {
                // CPU pixel buffers and instanced commands are rebuilt by caller.
            }
            RenderBackend::Canvas2d => {
                // Canvas 2D draw calls are issued directly via canvas2d_ctx_mut().
                // No per-frame reset needed — the browser auto-clears as needed.
            }
        }
    }
}