Skip to main content

cranpose_render_wgpu/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4pub(crate) use cranpose_render_common::debug_toggles;
5pub use debug_toggles::{
6    DebugToggle, debug_toggle, debug_toggle_os, set_debug_toggle, set_debug_toggle_os,
7};
8pub use offscreen::COMPOSITION_BYTES_PER_PIXEL;
9pub use render::presentable_root_usages;
10mod ablation;
11mod arc_trig_fill;
12mod capture_hash;
13mod collect;
14mod depth_gate;
15mod draw_pass;
16mod effect_renderer;
17mod fast_cores;
18mod frame;
19mod geometry;
20mod idle_pool;
21mod layer_cache;
22pub use fast_cores::pin_current_thread_to_fast_cores;
23mod fixed_pipeline;
24mod frame_graph;
25mod frame_packet;
26mod frontend;
27mod glass_split;
28/// The GLSL templates of the built-in shader modules, which `build.rs` wrote.
29#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
30mod gl_templates {
31    include!(concat!(env!("OUT_DIR"), "/gl_templates.rs"));
32}
33#[cfg(test)]
34#[path = "tests/gles_lowering.rs"]
35mod gles_lowering;
36mod glyph_run;
37mod glyph_run_arena;
38pub(crate) mod gpu_stats;
39mod initial_present;
40mod lazy_resource;
41mod mesh_fallback;
42mod offscreen;
43mod opaque_prefix;
44mod output_conversion;
45pub(crate) mod pass_timing;
46mod pipeline;
47mod pipeline_compiler;
48/// The file in which the driver's compiled pipelines, and a record of the pipelines the first
49/// screen drew with, are kept between launches.
50#[cfg(not(target_arch = "wasm32"))]
51pub mod pipeline_disk_cache;
52mod pipeline_recorder;
53mod pipeline_records;
54#[cfg(not(target_arch = "wasm32"))]
55mod present_runtime;
56mod record_columns;
57mod render;
58mod rrect_shadow;
59mod run_geometry;
60mod run_store;
61mod scene;
62mod scene_pass;
63mod shader_cache;
64#[cfg(not(target_arch = "wasm32"))]
65mod shader_flatten;
66#[cfg(not(target_arch = "wasm32"))]
67mod shader_fold;
68mod shaders;
69mod shape_pipelines;
70mod shared_shader;
71#[cfg(test)]
72mod test_support;
73mod thread_state;
74
75use std::{rc::Rc, sync::Arc};
76
77use cranpose_core::{MemoryApplier, NodeId};
78use cranpose_render_common::{
79    RenderScene, Renderer,
80    graph::RenderGraph,
81    software_text_raster::{
82        SoftwareTextFontSet, SoftwareTextMeasurer, software_text_font_set_from_fonts_or_default,
83    },
84};
85use cranpose_ui::{LayoutTree, TextMeasurer};
86use cranpose_ui_graphics::{Rect, Size};
87pub use frame_packet::PresentTimings;
88
89/// Platform code the present thread runs around every present to a surface,
90/// for what only the platform can do with its swapchain, such as asking the
91/// display when earlier frames reached the screen.
92#[cfg(not(target_arch = "wasm32"))]
93pub trait PresentObserver: Send {
94    /// Runs just before `surface` presents a frame.
95    fn before_present(&mut self, surface: &wgpu::Surface<'static>);
96    /// Runs just after `surface` presented it.
97    fn after_present(&mut self, surface: &wgpu::Surface<'static>);
98
99    /// Runs before `surface` is configured anew, while its current swapchain
100    /// still stands. Does nothing unless the platform needs it to.
101    fn before_reconfigure(&mut self, _surface: &wgpu::Surface<'static>) {}
102}
103use frame_packet::RenderReturns;
104#[doc(hidden)]
105pub use frame_packet::{CancelReason, PresentOutcome};
106use frontend::{DevOverlayCache, RendererFrontend};
107pub use gpu_stats::FrameStatsSnapshot as RenderStatsSnapshot;
108pub use initial_present::{clear_to_background, clear_to_default_background};
109pub use pass_timing::{GpuPassTimingEntry, GpuPassTimingReport};
110use pipeline_compiler::PipelineCompilation;
111#[cfg(not(target_arch = "wasm32"))]
112use present_runtime::{
113    PresentControl, PresentHandle, PresentMsg, PresentRuntimeInit, PresentState,
114};
115use render::{GpuRenderer, GpuRendererInit};
116pub use render::{
117    frame_clear_color, frames_presented, pipelines_created, pipelines_created_off_frame,
118};
119pub use scene::{HitRegion, Scene};
120pub use shared_shader::{shader_stages_flattened, shader_stages_folded};
121
122/// The optional device features the renderer exploits when the adapter
123/// offers them: pipeline caching (see `pipeline_disk_cache`), the
124/// timestamp queries behind `CRANPOSE_GPU_PASS_TIMING`, and, on a GPU
125/// that shares the host's memory, vertex and uniform buffers the CPU
126/// writes directly, so a frame's uploads need no copy. Every platform's
127/// `request_device` passes this so a profiling toggle never needs a rebuilt
128/// binary; intersecting with the adapter's own features keeps the request
129/// valid on adapters without them.
130pub fn optional_device_features(adapter: &wgpu::Adapter) -> wgpu::Features {
131    let mut wanted = wgpu::Features::PIPELINE_CACHE | wgpu::Features::TIMESTAMP_QUERY;
132    if matches!(
133        adapter.get_info().device_type,
134        wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::Cpu
135    ) {
136        wanted |= wgpu::Features::MAPPABLE_PRIMARY_BUFFERS;
137    }
138    adapter.features() & wanted
139}
140
141#[doc(hidden)]
142pub fn offscreen_render_target_for_tests(
143    device: &wgpu::Device,
144    width: u32,
145    height: u32,
146    label: &str,
147) -> (wgpu::Texture, wgpu::TextureView) {
148    let texture = offscreen::create_2d_texture(
149        device,
150        wgpu::TextureFormat::Rgba8Unorm,
151        width,
152        height,
153        wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
154        Some(label),
155    );
156    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
157    (texture, view)
158}
159
160pub(crate) fn rect_to_quad(rect: Rect) -> [[f32; 2]; 4] {
161    [
162        [rect.x, rect.y],
163        [rect.x + rect.width, rect.y],
164        [rect.x, rect.y + rect.height],
165        [rect.x + rect.width, rect.y + rect.height],
166    ]
167}
168
169/// Why a [`WgpuRenderer`] call failed.
170#[derive(Debug)]
171pub enum WgpuRendererError {
172    /// The renderer could not draw, with the reason: no GPU was initialized for synchronous
173    /// rendering, there is no scene graph, or the GPU reported an error.
174    Wgpu(String),
175}
176
177/// CPU-readable RGBA frame captured from the renderer output.
178#[derive(Debug, Clone)]
179pub struct CapturedFrame {
180    /// Width of the frame in device pixels.
181    pub width: u32,
182    /// Height of the frame in device pixels.
183    pub height: u32,
184    /// The pixels as 8-bit RGBA, row by row from the top left, `width * height * 4` bytes.
185    pub pixels: Vec<u8>,
186}
187
188#[doc(hidden)]
189#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
190pub struct DebugCpuAllocationStats {
191    pub scene_graph_node_count: usize,
192    pub scene_graph_heap_bytes: usize,
193    pub scene_hits_len: usize,
194    pub scene_hits_cap: usize,
195    pub scene_node_index_len: usize,
196    pub scene_node_index_cap: usize,
197    pub text_renderer_pool_len: usize,
198    pub text_renderer_pool_cap: usize,
199    pub image_texture_cache_len: usize,
200    pub image_texture_cache_cap: usize,
201    pub run_arena_staging_bytes: usize,
202    pub run_store_bytes: usize,
203    pub run_store_runs: usize,
204    pub scratch_image_vertices_cap: usize,
205    pub scratch_image_indices_cap: usize,
206    pub scratch_image_cmds_cap: usize,
207    pub scratch_glyph_instances_cap: usize,
208    pub layer_cache_len: usize,
209    pub layer_cache_bytes: u64,
210}
211
212/// The device a renderer draws with and the surface format it presents.
213struct GpuTarget {
214    device: Arc<wgpu::Device>,
215    queue: Arc<wgpu::Queue>,
216    surface_format: wgpu::TextureFormat,
217    adapter_backend: wgpu::Backend,
218    adapter_downlevel: wgpu::DownlevelFlags,
219}
220
221pub(crate) struct TextSystemState {
222    measurer: SoftwareTextMeasurer,
223}
224
225impl TextSystemState {
226    fn from_font_set(fonts: SoftwareTextFontSet) -> Self {
227        Self {
228            measurer: SoftwareTextMeasurer::from_font_set(fonts, 8192),
229        }
230    }
231}
232
233impl pipeline::TextLayoutResolver for TextSystemState {
234    fn layout_text(
235        &mut self,
236        text: &cranpose_ui::text::AnnotatedString,
237        style: &cranpose_ui::text::TextStyle,
238    ) -> cranpose_ui::text_layout_result::TextLayoutResult {
239        if cranpose_ui::has_current_app_context() {
240            cranpose_ui::text::layout_text(text, style)
241        } else {
242            self.measurer.layout(text, style)
243        }
244    }
245}
246
247/// The fonts a [`WgpuRenderer`] measures and draws text with.
248#[derive(Clone)]
249pub struct WgpuTextSystem {
250    software_fonts: SoftwareTextFontSet,
251}
252
253impl WgpuTextSystem {
254    /// Parses `fonts`, font file bytes ordered by priority with the first highest, into a text
255    /// system. Files that do not parse are skipped. When none parses, the text system holds the
256    /// embedded default font if the build has it, and no font otherwise.
257    pub fn from_fonts(fonts: &[&'static [u8]]) -> Self {
258        Self {
259            software_fonts: software_text_font_set_from_fonts_or_default(fonts),
260        }
261    }
262
263    /// Adopt a font set an app already built — the path app-supplied families
264    /// take, where faces were parsed once at startup rather than from static
265    /// byte slices here.
266    pub fn from_font_set(software_fonts: SoftwareTextFontSet) -> Self {
267        Self { software_fonts }
268    }
269
270    pub(crate) fn render_state(&self) -> TextSystemState {
271        TextSystemState::from_font_set(self.software_fonts.clone())
272    }
273
274    pub(crate) fn software_fonts(&self) -> SoftwareTextFontSet {
275        self.software_fonts.clone()
276    }
277}
278
279/// Create an accurate WGPU text measurer for headless tests without launching a window.
280pub fn headless_text_measurer() -> Rc<dyn TextMeasurer> {
281    headless_text_measurer_with_fonts(&[])
282}
283
284/// Create an accurate WGPU text measurer for headless tests with explicit fonts.
285pub fn headless_text_measurer_with_fonts(fonts: &[&'static [u8]]) -> Rc<dyn TextMeasurer> {
286    Rc::new(SoftwareTextMeasurer::from_fonts_or_default(fonts, 8192))
287}
288
289enum PresentBackend {
290    None,
291    Sync(Box<GpuRenderer>),
292    #[cfg(not(target_arch = "wasm32"))]
293    Threaded(PresentHandle),
294}
295
296/// What [`WgpuRenderer::publish_frame`] did.
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub enum PublishOutcome {
299    /// No scene graph exists; nothing to lower.
300    NoGraph,
301    /// The depth-one slot is occupied (or the renderer is not in threaded
302    /// mode): NO packet was built — backpressure lands before lowering.
303    NoCredit,
304    /// A packet was built and handed to the present runtime.
305    Published,
306}
307
308/// WGPU-based renderer for GPU-accelerated 2D rendering.
309///
310/// This renderer supports:
311/// - GPU-accelerated shape rendering (rectangles, rounded rectangles)
312/// - Gradients (solid, linear, radial)
313/// - GPU text rendering via retained raster image batches
314/// - Cross-platform support (Desktop, Web, Android)
315pub struct WgpuRenderer {
316    frontend: RendererFrontend,
317    backend: PresentBackend,
318    renderer_epoch: u64,
319    surface_epoch: u64,
320    on_device_lost: Option<DeviceLostHandler>,
321}
322
323/// What a host runs when the device it handed a [`WgpuRenderer`] is lost,
324/// after the loss is logged. It may run on any thread.
325pub type DeviceLostHandler = Arc<dyn Fn() + Send + Sync>;
326
327impl WgpuRenderer {
328    /// Create a new WGPU renderer.
329    ///
330    /// * `fonts` – font bytes to load, ordered by priority (first = highest priority).
331    ///   Pass `&[]` to load no fonts; text will not render until fonts are provided.
332    ///
333    /// Call [`init_gpu`][Self::init_gpu] before rendering.
334    pub fn new(fonts: &[&'static [u8]]) -> Self {
335        Self::with_text_system(WgpuTextSystem::from_fonts(fonts))
336    }
337
338    /// Create a renderer over an already-parsed font set.
339    ///
340    /// Measurement and rasterization both take clones of this one set, so an
341    /// app-supplied family resolves identically on both sides.
342    pub fn with_font_set(fonts: SoftwareTextFontSet) -> Self {
343        Self::with_text_system(WgpuTextSystem::from_font_set(fonts))
344    }
345
346    /// Create a renderer that measures and draws text with `text_system`.
347    pub fn with_text_system(text_system: WgpuTextSystem) -> Self {
348        Self {
349            frontend: RendererFrontend::new(
350                text_system.render_state(),
351                text_system.software_fonts(),
352            ),
353            backend: PresentBackend::None,
354            renderer_epoch: 0,
355            surface_epoch: 0,
356            on_device_lost: None,
357        }
358    }
359
360    /// Runs `handler` when the device of a later `init_gpu` call is lost,
361    /// so the host can open another device and hand it over.
362    pub fn set_device_lost_handler(&mut self, handler: DeviceLostHandler) {
363        self.on_device_lost = Some(handler);
364    }
365
366    fn sync_gpu_renderer(&self) -> Option<&GpuRenderer> {
367        match &self.backend {
368            PresentBackend::Sync(gpu_renderer) => Some(gpu_renderer.as_ref()),
369            _ => None,
370        }
371    }
372
373    #[cfg(not(target_arch = "wasm32"))]
374    fn present_handle_mut(&mut self) -> Option<&mut PresentHandle> {
375        match &mut self.backend {
376            PresentBackend::Threaded(handle) => Some(handle),
377            _ => None,
378        }
379    }
380
381    fn retire_live_backend(&mut self) {
382        #[allow(unused_mut)]
383        let mut backend = std::mem::replace(&mut self.backend, PresentBackend::None);
384        #[cfg(not(target_arch = "wasm32"))]
385        if let PresentBackend::Threaded(handle) = &mut backend {
386            while let Some(returns) = handle.try_drain() {
387                self.frontend.apply_returns(returns);
388            }
389            handle.shutdown();
390        }
391        drop(backend);
392    }
393
394    /// Drops what the renderer holds on its device, for a host whose device
395    /// is gone: the frees then reach the lost device, as a WebGL context
396    /// that is lost ignores them, rather than the device that replaces it.
397    /// [`Self::init_gpu`] gives the renderer a device again.
398    pub fn release_gpu(&mut self) {
399        self.retire_live_backend();
400    }
401
402    /// Initialize GPU resources with a WGPU device and queue.
403    ///
404    /// Replacing a live renderer (Android surface recreation, device loss)
405    /// bumps the renderer epoch, so a packet built against the previous
406    /// renderer is cancelled instead of drawn.
407    pub fn init_gpu(
408        &mut self,
409        device: Arc<wgpu::Device>,
410        queue: Arc<wgpu::Queue>,
411        surface_format: wgpu::TextureFormat,
412        adapter_backend: wgpu::Backend,
413        adapter_downlevel: wgpu::DownlevelFlags,
414    ) {
415        let target = GpuTarget {
416            device,
417            queue,
418            surface_format,
419            adapter_backend,
420            adapter_downlevel,
421        };
422        self.install_gpu(target, PipelineCompilation::Background);
423    }
424
425    /// [`init_gpu`][Self::init_gpu], compiling every pipeline where it is
426    /// first needed instead of on the background compiler: no frame draws
427    /// with a stand-in, which a reference frame in a test must not.
428    #[doc(hidden)]
429    pub fn init_gpu_compiling_inline_for_tests(
430        &mut self,
431        device: Arc<wgpu::Device>,
432        queue: Arc<wgpu::Queue>,
433        surface_format: wgpu::TextureFormat,
434        adapter_backend: wgpu::Backend,
435        adapter_downlevel: wgpu::DownlevelFlags,
436    ) {
437        let target = GpuTarget {
438            device,
439            queue,
440            surface_format,
441            adapter_backend,
442            adapter_downlevel,
443        };
444        self.install_gpu(target, PipelineCompilation::Inline);
445    }
446
447    fn install_gpu(&mut self, target: GpuTarget, pipeline_compilation: PipelineCompilation) {
448        let init = self.next_gpu_init(target, pipeline_compilation);
449        self.backend = PresentBackend::Sync(Box::new(GpuRenderer::new(init)));
450    }
451
452    /// Retires the live backend and bumps the renderer epoch, then describes
453    /// the renderer that replaces it on `target`.
454    fn next_gpu_init(
455        &mut self,
456        target: GpuTarget,
457        pipeline_compilation: PipelineCompilation,
458    ) -> GpuRendererInit {
459        self.retire_live_backend();
460        self.renderer_epoch = self.renderer_epoch.wrapping_add(1);
461        GpuRendererInit {
462            device: target.device,
463            queue: target.queue,
464            surface_format: target.surface_format,
465            adapter_backend: target.adapter_backend,
466            adapter_downlevel: target.adapter_downlevel,
467            text_fonts: self.frontend.text_fonts.clone(),
468            renderer_epoch: self.renderer_epoch,
469            pipeline_compilation,
470            on_device_lost: self.on_device_lost.clone(),
471        }
472    }
473
474    /// [`init_gpu`][Self::init_gpu] for the threaded present runtime
475    /// (Android): the same epoch bump and planner replacement hygiene, but
476    /// instead of constructing a `GpuRenderer` here, everything it needs —
477    /// all owned, all `Send` — crosses to a spawned present thread that
478    /// constructs its own (its `Rc` caches are thread-confined). Frames
479    /// then flow through [`publish_frame`][Self::publish_frame] /
480    /// [`drain_present_returns`][Self::drain_present_returns] under the
481    /// depth-one credit protocol instead of [`render`][Self::render].
482    ///
483    /// * `waker` — wakes the producer's event loop after every returns
484    ///   send (the Android frame waker).
485    /// * `clock` — producer's monotonic nanosecond clock, so present-side
486    ///   [`PresentTimings`] share the producer telemetry's clock domain;
487    ///   `None` leaves timings at zero.
488    /// * `observer` — runs on the present thread around every present to the
489    ///   surface.
490    #[cfg(not(target_arch = "wasm32"))]
491    #[expect(clippy::too_many_arguments)]
492    pub fn init_gpu_threaded(
493        &mut self,
494        device: Arc<wgpu::Device>,
495        queue: Arc<wgpu::Queue>,
496        surface_format: wgpu::TextureFormat,
497        adapter_backend: wgpu::Backend,
498        adapter_downlevel: wgpu::DownlevelFlags,
499        waker: Arc<dyn Fn() + Send + Sync>,
500        clock: Option<Arc<dyn Fn() -> i64 + Send + Sync>>,
501        observer: Option<Box<dyn PresentObserver>>,
502    ) -> Result<(), WgpuRendererError> {
503        let target = GpuTarget {
504            device,
505            queue,
506            surface_format,
507            adapter_backend,
508            adapter_downlevel,
509        };
510        let init = PresentRuntimeInit {
511            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
512            clock,
513            observer,
514        };
515        let handle = PresentHandle::spawn(init, waker).map_err(WgpuRendererError::Wgpu)?;
516        self.backend = PresentBackend::Threaded(handle);
517        Ok(())
518    }
519
520    #[cfg(not(target_arch = "wasm32"))]
521    #[doc(hidden)]
522    pub fn init_gpu_inline_for_tests(
523        &mut self,
524        device: Arc<wgpu::Device>,
525        queue: Arc<wgpu::Queue>,
526        surface_format: wgpu::TextureFormat,
527        adapter_backend: wgpu::Backend,
528        adapter_downlevel: wgpu::DownlevelFlags,
529    ) -> InlinePresentRuntime {
530        let target = GpuTarget {
531            device,
532            queue,
533            surface_format,
534            adapter_backend,
535            adapter_downlevel,
536        };
537        let init = PresentRuntimeInit {
538            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
539            clock: None,
540            observer: None,
541        };
542        let (handle, state, msg_rx) = PresentHandle::new_inline(init, Arc::new(|| {}));
543        self.backend = PresentBackend::Threaded(handle);
544        InlinePresentRuntime {
545            state,
546            msg_rx,
547            shutdown_seen: false,
548        }
549    }
550
551    /// Record that the surface was reconfigured (resize, format change,
552    /// swapchain recreation): bumps the surface epoch stamped into every
553    /// subsequent packet, so a packet built against the previous
554    /// configuration is cancelled by the present stage instead of drawn.
555    pub fn note_surface_reconfigured(&mut self) {
556        self.surface_epoch = self.surface_epoch.wrapping_add(1);
557    }
558
559    /// Clears each frame to nothing instead of the framework's background,
560    /// for a window whose surface composites with the desktop behind it. A
561    /// renderer starts opaque; `false` puts the background back. Takes
562    /// effect from the next frame, on either present backend.
563    pub fn set_transparent_background(&mut self, transparent: bool) {
564        self.frontend.transparent_background = transparent;
565    }
566
567    /// The scale from logical to device pixels the renderer draws the root with, as last set
568    /// by `Renderer::set_root_scale`. It starts at `1.0`.
569    pub fn root_scale(&self) -> f32 {
570        self.frontend.root_scale
571    }
572
573    /// Render the scene to a texture view.
574    ///
575    /// Producer first, present second: the frontend collects the frame into
576    /// a `frame_packet::FramePacket` (root and dev overlay alike), the GPU
577    /// renderer consumes it, and the present stage's returns fold back into
578    /// the frontend afterwards.
579    pub fn render(
580        &mut self,
581        texture: &wgpu::Texture,
582        view: &wgpu::TextureView,
583        width: u32,
584        height: u32,
585    ) -> Result<(), WgpuRendererError> {
586        self.render_frame(texture, view, width, height)
587    }
588
589    /// Renders the frame into a presentable image. When the image carries the
590    /// composition format and the capture usages, the scene renders into it
591    /// directly and no output conversion pass runs.
592    pub fn render_surface_texture(
593        &mut self,
594        texture: &wgpu::Texture,
595        view: &wgpu::TextureView,
596        width: u32,
597        height: u32,
598    ) -> Result<(), WgpuRendererError> {
599        self.render_frame(texture, view, width, height)
600    }
601
602    /// Presents a surface image this renderer drew with
603    /// [`render_surface_texture`](Self::render_surface_texture), on the queue
604    /// that recorded it.
605    ///
606    /// Before [`init_gpu`](Self::init_gpu) there is no queue, and the image is
607    /// released without being shown.
608    pub fn present(&self, frame: wgpu::SurfaceTexture) {
609        match self.sync_gpu_renderer() {
610            Some(gpu_renderer) => gpu_renderer.queue.present(frame),
611            None => log::debug!("surface image released: the renderer has no GPU queue"),
612        }
613    }
614
615    fn render_frame(
616        &mut self,
617        texture: &wgpu::Texture,
618        view: &wgpu::TextureView,
619        width: u32,
620        height: u32,
621    ) -> Result<(), WgpuRendererError> {
622        let PresentBackend::Sync(gpu_renderer) = &mut self.backend else {
623            return Err(WgpuRendererError::Wgpu(
624                "GPU renderer not initialized for synchronous rendering. Call init_gpu() first."
625                    .to_string(),
626            ));
627        };
628        let packet = self
629            .frontend
630            .build_frame_packet(width, height, self.renderer_epoch, self.surface_epoch)
631            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
632        let mut returns = RenderReturns::default();
633        let result = gpu_renderer.render(
634            texture,
635            view,
636            width,
637            height,
638            packet,
639            self.surface_epoch,
640            &mut returns,
641        );
642        self.frontend.apply_returns(returns);
643        result.map_err(WgpuRendererError::Wgpu)
644    }
645
646    /// Render the current scene into an RGBA pixel buffer for robot tests.
647    ///
648    /// Uses the renderer's configured root scale.
649    pub fn capture_frame(
650        &mut self,
651        width: u32,
652        height: u32,
653    ) -> Result<CapturedFrame, WgpuRendererError> {
654        self.capture_frame_with_scale(width, height, self.frontend.root_scale)
655    }
656
657    /// Builds every pipeline the pipeline cache file records on the
658    /// background compiler, and returns whether they were all built before
659    /// `timeout`, or before `stop` said to stop. An app runs it after an
660    /// update, before its next launch, so that launch finds them compiled;
661    /// the renderer writes the file when it is dropped, and drops the builds
662    /// not started. It draws nothing, and needs a renderer initialized for
663    /// synchronous rendering.
664    #[cfg(not(target_arch = "wasm32"))]
665    pub fn prepare_recorded_pipelines(
666        &mut self,
667        timeout: std::time::Duration,
668        stop: &dyn Fn() -> bool,
669    ) -> bool {
670        let PresentBackend::Sync(gpu_renderer) = &mut self.backend else {
671            return false;
672        };
673        let deadline = web_time::Instant::now() + timeout;
674        let mut compiling = gpu_renderer.prepare_recorded();
675        while compiling {
676            if web_time::Instant::now() >= deadline || stop() {
677                return false;
678            }
679            std::thread::sleep(std::time::Duration::from_millis(10));
680            compiling = gpu_renderer.compiling();
681        }
682        true
683    }
684
685    /// Render the current scene into an RGBA pixel buffer with an explicit scale.
686    ///
687    /// `width` and `height` are in device pixels and `root_scale` is the scale from logical to
688    /// device pixels. Needs a renderer initialized for synchronous rendering.
689    pub fn capture_frame_with_scale(
690        &mut self,
691        width: u32,
692        height: u32,
693        root_scale: f32,
694    ) -> Result<CapturedFrame, WgpuRendererError> {
695        let PresentBackend::Sync(gpu_renderer) = &mut self.backend else {
696            return Err(WgpuRendererError::Wgpu(
697                "GPU renderer not initialized for synchronous rendering. Call init_gpu() first."
698                    .to_string(),
699            ));
700        };
701        let packet = self
702            .frontend
703            .build_frame_packet_with_scale(
704                width,
705                height,
706                root_scale,
707                self.renderer_epoch,
708                self.surface_epoch,
709            )
710            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
711        let mut returns = RenderReturns::default();
712        let result = gpu_renderer.render_to_rgba_pixels(
713            width,
714            height,
715            packet,
716            self.surface_epoch,
717            &mut returns,
718        );
719        self.frontend.apply_returns(returns);
720        let pixels = result.map_err(WgpuRendererError::Wgpu)?;
721        Ok(CapturedFrame {
722            width,
723            height,
724            pixels,
725        })
726    }
727
728    /// Threaded mode: whether the depth-one slot has room for a packet.
729    /// The Android loop checks this BEFORE `shell.update()` so
730    /// backpressure lands before the expensive update/lowering work.
731    /// Always `true` on the sync path, which has no slot to fill.
732    #[cfg(not(target_arch = "wasm32"))]
733    pub fn has_frame_credit(&self) -> bool {
734        match &self.backend {
735            PresentBackend::Threaded(handle) => handle.has_credit(),
736            PresentBackend::Sync(_) | PresentBackend::None => true,
737        }
738    }
739
740    /// Threaded mode: whether the present thread has handed back a frame
741    /// that [`drain_present_returns`][Self::drain_present_returns] has not
742    /// folded back yet, so draining it would free a publish credit. A loop
743    /// out of credit can work on other things until this turns true.
744    /// Always `false` outside threaded mode.
745    #[cfg(not(target_arch = "wasm32"))]
746    pub fn frame_credit_returned(&self) -> bool {
747        match &self.backend {
748            PresentBackend::Threaded(handle) => handle.has_undrained_return(),
749            PresentBackend::Sync(_) | PresentBackend::None => false,
750        }
751    }
752
753    /// Threaded mode: lower the current scene into a packet and hand it to
754    /// the present runtime. Credit is checked FIRST — a `NoCredit` return
755    /// means no packet was built at all (`frame_sequence` does not
756    /// advance). Returns `NoCredit` (with an error log) when the renderer
757    /// is not in threaded mode.
758    #[cfg(not(target_arch = "wasm32"))]
759    pub fn publish_frame(&mut self, width: u32, height: u32) -> PublishOutcome {
760        let PresentBackend::Threaded(handle) = &mut self.backend else {
761            log::error!("publish_frame called without a threaded present runtime");
762            return PublishOutcome::NoCredit;
763        };
764        if !handle.has_credit() {
765            return PublishOutcome::NoCredit;
766        }
767        let Some(packet) = self.frontend.build_frame_packet(
768            width,
769            height,
770            self.renderer_epoch,
771            self.surface_epoch,
772        ) else {
773            return PublishOutcome::NoGraph;
774        };
775        match handle.publish(packet) {
776            Ok(()) => PublishOutcome::Published,
777            Err(packet) => {
778                let mut returns = RenderReturns::default();
779                let _ = GpuRenderer::cancel_packet(
780                    *packet,
781                    CancelReason::SurfaceUnavailable,
782                    &mut returns,
783                );
784                self.frontend.apply_returns(returns);
785                log::error!("present runtime unavailable; frame recovered, not published");
786                PublishOutcome::NoCredit
787            }
788        }
789    }
790
791    /// Threaded mode: fold every pending `RenderReturns` back into
792    /// producer state and free the publish credit. Returns how many were
793    /// drained. No-op outside threaded mode.
794    #[cfg(not(target_arch = "wasm32"))]
795    pub fn drain_present_returns(&mut self) -> usize {
796        self.drain_present_returns_with(&mut |_, _, _| {})
797    }
798
799    /// [`drain_present_returns`][Self::drain_present_returns], reporting
800    /// each drained frame's id, outcome and present-thread timings — the
801    /// Android loop feeds its frame telemetry from this.
802    #[cfg(not(target_arch = "wasm32"))]
803    pub fn drain_present_returns_with(
804        &mut self,
805        on_return: &mut dyn FnMut(u64, PresentOutcome, PresentTimings),
806    ) -> usize {
807        let mut drained = 0;
808        loop {
809            let returns = {
810                let PresentBackend::Threaded(handle) = &mut self.backend else {
811                    break;
812                };
813                match handle.try_drain() {
814                    Some(returns) => returns,
815                    None => break,
816                }
817            };
818            drained += 1;
819            let frame_id = returns.frame_id;
820            let outcome = returns.outcome;
821            let timings = returns.timings;
822            self.frontend.apply_returns(returns);
823            on_return(frame_id, outcome, timings);
824        }
825        drained
826    }
827
828    /// Threaded mode: install a (re)created surface on the present thread.
829    /// Nothing waits for the present thread to set it up: frames published
830    /// afterwards queue behind it, so the caller composes its next frame
831    /// while the surface is configured. The caller must have bumped the
832    /// surface epoch first (`note_surface_reconfigured`
833    /// [Self::note_surface_reconfigured]) when the message invalidates
834    /// in-flight packets; the message carries the current epoch. Returns
835    /// false when the present thread is gone.
836    #[cfg(not(target_arch = "wasm32"))]
837    pub fn present_replace_surface(
838        &mut self,
839        surface: wgpu::Surface<'static>,
840        config: wgpu::SurfaceConfiguration,
841    ) -> bool {
842        let surface_epoch = self.surface_epoch;
843        let Some(handle) = self.present_handle_mut() else {
844            log::error!("present_replace_surface called without a threaded present runtime");
845            return false;
846        };
847        let sent = handle.send_control(PresentControl::ReplaceSurface {
848            surface,
849            config,
850            surface_epoch,
851        });
852        if !sent {
853            log::error!("[present-runtime] replace surface: runtime is gone");
854        }
855        sent
856    }
857
858    /// Threaded mode: reconfigure the present thread's surface (resize)
859    /// and wait for the acknowledgement. Same epoch contract as
860    /// [`present_replace_surface`][Self::present_replace_surface].
861    #[cfg(not(target_arch = "wasm32"))]
862    pub fn present_reconfigure(&mut self, config: wgpu::SurfaceConfiguration) -> bool {
863        let surface_epoch = self.surface_epoch;
864        let Some(handle) = self.present_handle_mut() else {
865            log::error!("present_reconfigure called without a threaded present runtime");
866            return false;
867        };
868        handle.send_control_and_wait(
869            move |ack| PresentControl::Reconfigure {
870                config,
871                surface_epoch,
872                ack,
873            },
874            "reconfigure surface",
875        )
876    }
877
878    /// Threaded mode: drop the present thread's surface (the window died;
879    /// the renderer survives for the next one) and wait for the
880    /// acknowledgement. Bump the epoch first so in-flight packets cancel.
881    #[cfg(not(target_arch = "wasm32"))]
882    pub fn present_drop_surface(&mut self) -> bool {
883        let Some(handle) = self.present_handle_mut() else {
884            log::error!("present_drop_surface called without a threaded present runtime");
885            return false;
886        };
887        handle.send_control_and_wait(|ack| PresentControl::DropSurface { ack }, "drop surface")
888    }
889
890    /// Threaded mode: drain outstanding returns, stop the present thread
891    /// and join it. The renderer returns to the uninitialized state.
892    #[cfg(not(target_arch = "wasm32"))]
893    pub fn shutdown_present_runtime(&mut self) {
894        if matches!(self.backend, PresentBackend::Threaded(_)) {
895            self.retire_live_backend();
896        }
897    }
898
899    #[cfg(not(target_arch = "wasm32"))]
900    #[doc(hidden)]
901    pub fn present_attach_offscreen_for_tests(&mut self, width: u32, height: u32) -> bool {
902        let Some(handle) = self.present_handle_mut() else {
903            return false;
904        };
905        handle.send_control_and_wait(
906            move |ack| PresentControl::AttachOffscreenTargetForTests { width, height, ack },
907            "attach offscreen target",
908        )
909    }
910
911    #[cfg(not(target_arch = "wasm32"))]
912    #[doc(hidden)]
913    pub fn send_attach_offscreen_unacked_for_tests(
914        &mut self,
915        width: u32,
916        height: u32,
917    ) -> Option<std::sync::mpsc::Receiver<()>> {
918        let handle = self.present_handle_mut()?;
919        handle.send_control_unacked(move |ack| PresentControl::AttachOffscreenTargetForTests {
920            width,
921            height,
922            ack,
923        })
924    }
925
926    #[cfg(not(target_arch = "wasm32"))]
927    #[doc(hidden)]
928    pub fn send_reconfigure_unacked_for_tests(
929        &mut self,
930        config: wgpu::SurfaceConfiguration,
931    ) -> Option<std::sync::mpsc::Receiver<()>> {
932        let surface_epoch = self.surface_epoch;
933        let handle = self.present_handle_mut()?;
934        handle.send_control_unacked(move |ack| PresentControl::Reconfigure {
935            config,
936            surface_epoch,
937            ack,
938        })
939    }
940
941    #[cfg(not(target_arch = "wasm32"))]
942    #[doc(hidden)]
943    pub fn send_drop_surface_unacked_for_tests(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
944        let handle = self.present_handle_mut()?;
945        handle.send_control_unacked(|ack| PresentControl::DropSurface { ack })
946    }
947
948    /// The OS id of the thread that presents frames, once that thread has
949    /// started, on systems whose scheduler hints name threads by one.
950    /// `None` when frames present on the calling thread.
951    pub fn present_thread_id(&self) -> Option<i32> {
952        match &self.backend {
953            #[cfg(not(target_arch = "wasm32"))]
954            PresentBackend::Threaded(handle) => {
955                let id = handle
956                    .status()
957                    .thread_id
958                    .load(std::sync::atomic::Ordering::Relaxed);
959                (id != 0).then_some(id)
960            }
961            _ => None,
962        }
963    }
964
965    /// The producer's monotone packet sequence: the `frame_id` stamped on
966    /// the most recently lowered packet. After a `Published` outcome this
967    /// is the published frame's id (the Android loop keys its telemetry on
968    /// it); it also proves a `NoCredit` publish never lowered a frame.
969    pub fn last_published_frame_id(&self) -> u64 {
970        self.frontend.frame_sequence
971    }
972
973    #[cfg(not(target_arch = "wasm32"))]
974    #[doc(hidden)]
975    pub fn present_status_snapshot_for_tests(&self) -> Option<(bool, u64, u64)> {
976        match &self.backend {
977            PresentBackend::Threaded(handle) => {
978                let status = handle.status();
979                Some((
980                    status
981                        .needs_frame_warmup
982                        .load(std::sync::atomic::Ordering::Relaxed),
983                    status
984                        .presented_frames
985                        .load(std::sync::atomic::Ordering::Relaxed),
986                    status
987                        .placeholder_frames
988                        .load(std::sync::atomic::Ordering::Relaxed),
989                ))
990            }
991            _ => None,
992        }
993    }
994
995    /// The counters of the most recent frame the renderer drew, or `None` before it drew one.
996    pub fn last_frame_stats(&self) -> Option<RenderStatsSnapshot> {
997        match &self.backend {
998            PresentBackend::Sync(gpu_renderer) => gpu_renderer.last_frame_stats(),
999            #[cfg(not(target_arch = "wasm32"))]
1000            PresentBackend::Threaded(handle) => *handle
1001                .status()
1002                .last_frame_stats
1003                .lock()
1004                .unwrap_or_else(std::sync::PoisonError::into_inner),
1005            PresentBackend::None => None,
1006        }
1007    }
1008
1009    /// Whether the pipeline cache file held an earlier launch's first screen,
1010    /// whose pipelines build ahead of this renderer's first frame; `false`
1011    /// for a first launch or emptied caches, whose first frame builds its
1012    /// pipelines, and for a renderer that does not draw on the calling
1013    /// thread.
1014    #[cfg(not(target_arch = "wasm32"))]
1015    pub fn first_screen_recorded(&self) -> bool {
1016        self.sync_gpu_renderer()
1017            .is_some_and(GpuRenderer::first_screen_recorded)
1018    }
1019
1020    /// The pipelines this renderer's first screen drew with, encoded for
1021    /// [`Self::build_first_screen_pipelines`] in a later launch. `None`
1022    /// until the first screen ends, two seconds after the first frame and
1023    /// later by every wait for a pipeline, and for a renderer that does not
1024    /// draw on the calling thread.
1025    pub fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
1026        self.sync_gpu_renderer()
1027            .and_then(GpuRenderer::first_screen_pipelines)
1028    }
1029
1030    /// Builds now the pipelines one set in `records` names: sets
1031    /// [`Self::first_screen_pipelines`] wrote, one after another, each at the
1032    /// size its first frame drew. A web page calls this as its renderer
1033    /// starts, so the browser compiles them while the page composes its
1034    /// first screen. Of the sets drawn on this renderer's backend by a build
1035    /// with the same layout of pipeline keys, the one drawn nearest to
1036    /// `viewport` pixels builds: a phone's screen and a desktop window's
1037    /// draw with different pipelines, and a frame that waits for pipelines
1038    /// it does not draw with comes later. A renderer that does not draw on
1039    /// the calling thread builds nothing.
1040    pub fn build_first_screen_pipelines(&mut self, records: &[u8], viewport: (u32, u32)) {
1041        if let PresentBackend::Sync(gpu_renderer) = &mut self.backend {
1042            gpu_renderer.build_first_screen(records, viewport);
1043        }
1044    }
1045
1046    /// GPU milliseconds by pass label, aggregated since the last `[GPU-PASS]`
1047    /// print. Empty unless `CRANPOSE_GPU_PASS_TIMING` armed pass timing on a
1048    /// device with [`wgpu::Features::TIMESTAMP_QUERY`].
1049    pub fn gpu_pass_timings(&self) -> GpuPassTimingReport {
1050        self.sync_gpu_renderer()
1051            .map(GpuRenderer::gpu_pass_timings)
1052            .unwrap_or_default()
1053    }
1054
1055    /// The sizes and capacities of the renderer's CPU-side scene data, scratch buffers and
1056    /// caches, for memory diagnostics. The members of a renderer that does not draw on the
1057    /// calling thread cover the scene only.
1058    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
1059        let mut stats = self
1060            .sync_gpu_renderer()
1061            .map(GpuRenderer::debug_cpu_allocation_stats)
1062            .unwrap_or_default();
1063        stats.scene_graph_node_count = self
1064            .frontend
1065            .scene
1066            .graph
1067            .as_ref()
1068            .map_or(0, RenderGraph::node_count);
1069        stats.scene_graph_heap_bytes = self
1070            .frontend
1071            .scene
1072            .graph
1073            .as_ref()
1074            .map_or(0, RenderGraph::heap_bytes);
1075        stats.scene_hits_len = self.frontend.scene.hits.len();
1076        stats.scene_hits_cap = self.frontend.scene.hits.capacity();
1077        stats.scene_node_index_len = self.frontend.scene.node_index.len();
1078        stats.scene_node_index_cap = self.frontend.scene.node_index.capacity();
1079        stats
1080    }
1081
1082    /// Starts a frame that takes its pipelines from a pipeline discovery:
1083    /// the frame that discovers them, or the one that creates them again
1084    /// while the browser holds them compiled. Such a frame also builds the
1085    /// pipelines it expects a later frame to need, at its end, so the browser
1086    /// compiles them behind the frame's own or holds them with those.
1087    #[cfg(target_arch = "wasm32")]
1088    pub fn begin_discovery_frame(&self) {
1089        if let Some(gpu_renderer) = self.sync_gpu_renderer() {
1090            gpu_renderer.pipeline_compiler().begin_discovery_frame();
1091        }
1092    }
1093
1094    /// Drops what earlier frames drew and kept, once the pipelines the
1095    /// browser compiled in the background landed
1096    /// (`wgpu::Device::compile_pipelines_in_background`): those frames left
1097    /// out the draws that use them.
1098    #[cfg(target_arch = "wasm32")]
1099    pub fn background_pipelines_landed(&mut self) {
1100        if let PresentBackend::Sync(gpu_renderer) = &mut self.backend {
1101            gpu_renderer.background_pipelines_landed();
1102        }
1103    }
1104
1105    /// Tells the renderer that the browser compiles the pipelines it creates
1106    /// from now on in the background (`wgpu::Device::compile_pipelines_in_background`).
1107    /// On WebGPU the first screen draws its shapes with a general pipeline,
1108    /// whose one compile stands in for the specialized ones; those it builds
1109    /// once this is called, and draws switch to each as it lands.
1110    #[cfg(target_arch = "wasm32")]
1111    pub fn compile_pipelines_in_background(&mut self) {
1112        if let PresentBackend::Sync(gpu_renderer) = &mut self.backend {
1113            gpu_renderer.compile_pipelines_in_background();
1114        }
1115    }
1116
1117    /// Return the WGPU device when GPU resources are initialized.
1118    /// Sync backend only (desktop/web reconfigure paths); the threaded
1119    /// runtime owns its device on the present thread.
1120    pub fn try_device(&self) -> Option<&wgpu::Device> {
1121        self.sync_gpu_renderer().map(|r| &*r.device)
1122    }
1123
1124    #[doc(hidden)]
1125    pub fn try_queue_for_tests(&self) -> Option<&wgpu::Queue> {
1126        self.sync_gpu_renderer().map(|r| &*r.queue)
1127    }
1128
1129    #[doc(hidden)]
1130    pub fn device_error_count_for_tests(&self) -> u64 {
1131        self.sync_gpu_renderer()
1132            .map_or(0, GpuRenderer::device_error_count)
1133    }
1134
1135    #[doc(hidden)]
1136    pub fn build_frame_packet_for_tests(
1137        &mut self,
1138        width: u32,
1139        height: u32,
1140    ) -> Option<HeldFramePacket> {
1141        self.frontend
1142            .build_frame_packet(width, height, self.renderer_epoch, self.surface_epoch)
1143            .map(HeldFramePacket)
1144    }
1145
1146    /// Return a producer-built packet without presenting it. This exercises
1147    /// the same bounded scene-storage recycler used by normal present returns
1148    /// in offline producer benchmarks.
1149    ///
1150    /// ```
1151    /// use cranpose_render_wgpu::{HeldFramePacket, WgpuRenderer};
1152    ///
1153    /// fn return_without_presenting(renderer: &mut WgpuRenderer, packet: HeldFramePacket) {
1154    ///     renderer.return_held_packet_for_tests(packet);
1155    /// }
1156    /// ```
1157    #[doc(hidden)]
1158    pub fn return_held_packet_for_tests(&mut self, packet: HeldFramePacket) {
1159        let packet = packet.0;
1160        self.frontend.apply_returns(RenderReturns {
1161            scene: Some(frame_packet::FrameSceneStorage {
1162                root: packet.root,
1163                overlay: packet.overlay,
1164            }),
1165            frame_id: packet.frame_id,
1166            ..RenderReturns::default()
1167        });
1168    }
1169
1170    #[doc(hidden)]
1171    pub fn render_held_packet_for_tests(
1172        &mut self,
1173        texture: &wgpu::Texture,
1174        view: &wgpu::TextureView,
1175        width: u32,
1176        height: u32,
1177        packet: HeldFramePacket,
1178    ) -> Result<PresentOutcome, WgpuRendererError> {
1179        let PresentBackend::Sync(gpu_renderer) = &mut self.backend else {
1180            return Err(WgpuRendererError::Wgpu(
1181                "GPU renderer not initialized for synchronous rendering. Call init_gpu() first."
1182                    .to_string(),
1183            ));
1184        };
1185        let mut returns = RenderReturns::default();
1186        let result = gpu_renderer.render(
1187            texture,
1188            view,
1189            width,
1190            height,
1191            packet.0,
1192            self.surface_epoch,
1193            &mut returns,
1194        );
1195        let outcome = returns.outcome;
1196        self.frontend.apply_returns(returns);
1197        result.map_err(WgpuRendererError::Wgpu)?;
1198        Ok(outcome)
1199    }
1200}
1201
1202#[doc(hidden)]
1203pub struct HeldFramePacket(frame_packet::FramePacket);
1204
1205#[cfg(not(target_arch = "wasm32"))]
1206#[doc(hidden)]
1207pub struct InlinePresentRuntime {
1208    state: PresentState,
1209    msg_rx: std::sync::mpsc::Receiver<PresentMsg>,
1210    shutdown_seen: bool,
1211}
1212
1213#[cfg(not(target_arch = "wasm32"))]
1214impl InlinePresentRuntime {
1215    pub fn pump(&mut self) -> bool {
1216        if self.shutdown_seen {
1217            return false;
1218        }
1219        while let Ok(msg) = self.msg_rx.try_recv() {
1220            if !self.state.run_once(msg) {
1221                self.shutdown_seen = true;
1222                return false;
1223            }
1224        }
1225        self.state.consume_waiting();
1226        true
1227    }
1228
1229    pub fn has_waiting_packet(&self) -> bool {
1230        self.state.has_waiting_packet()
1231    }
1232
1233    pub fn step_one_message(&mut self) -> bool {
1234        if self.shutdown_seen {
1235            return false;
1236        }
1237        match self.msg_rx.try_recv() {
1238            Ok(msg) => {
1239                if !self.state.run_once(msg) {
1240                    self.shutdown_seen = true;
1241                }
1242                true
1243            }
1244            Err(_) => false,
1245        }
1246    }
1247
1248    pub fn consume_waiting(&mut self) {
1249        self.state.consume_waiting();
1250    }
1251}
1252
1253impl Default for WgpuRenderer {
1254    fn default() -> Self {
1255        Self::new(&[])
1256    }
1257}
1258
1259/// Gives `app_context` the measurer its text lays out with, over `fonts`.
1260fn install_text_measurer(app_context: &cranpose_ui::AppContext, fonts: &SoftwareTextFontSet) {
1261    app_context.set_text_measurer(SoftwareTextMeasurer::from_font_set(fonts.clone(), 8192));
1262}
1263
1264impl Renderer for WgpuRenderer {
1265    type Scene = Scene;
1266    type Error = WgpuRendererError;
1267
1268    fn attach_app_context_services(&mut self, app_context: &cranpose_ui::AppContext) {
1269        install_text_measurer(app_context, &self.frontend.text_fonts);
1270        self.frontend.app_context = Some(app_context.downgrade());
1271    }
1272
1273    #[cfg(feature = "installed-fonts")]
1274    fn apply_installed_fonts(&mut self, app_context: &cranpose_ui::AppContext) {
1275        let Some(fonts) = self.frontend.text_fonts.with_installed_faces() else {
1276            return;
1277        };
1278        let attached = self
1279            .frontend
1280            .app_context
1281            .as_ref()
1282            .and_then(std::rc::Weak::upgrade)
1283            .is_some_and(|attached| std::ptr::eq(&*attached, app_context));
1284        if attached {
1285            install_text_measurer(app_context, &fonts);
1286        }
1287        self.frontend.text_state = TextSystemState::from_font_set(fonts.clone());
1288        self.frontend.text_fonts = fonts;
1289    }
1290
1291    fn set_root_scale(&mut self, scale: f32) {
1292        self.frontend.root_scale = scale;
1293    }
1294
1295    fn scene(&self) -> &Self::Scene {
1296        &self.frontend.scene
1297    }
1298
1299    fn scene_mut(&mut self) -> &mut Self::Scene {
1300        &mut self.frontend.scene
1301    }
1302
1303    fn rebuild_scene(
1304        &mut self,
1305        layout_tree: &LayoutTree,
1306        _viewport: Size,
1307    ) -> Result<(), Self::Error> {
1308        self.frontend.scene.clear();
1309        self.frontend.clear_fps_overlay();
1310        pipeline::render_layout_tree(layout_tree.root(), &mut self.frontend.scene);
1311        Ok(())
1312    }
1313
1314    fn rebuild_scene_from_applier(
1315        &mut self,
1316        applier: &mut MemoryApplier,
1317        root: NodeId,
1318        _viewport: Size,
1319    ) -> Result<(), Self::Error> {
1320        self.frontend.clear_fps_overlay();
1321        self.frontend.scene.rebuild_from_applier(applier, root);
1322        Ok(())
1323    }
1324
1325    fn update_scene_from_applier(
1326        &mut self,
1327        applier: &mut MemoryApplier,
1328        root: NodeId,
1329        _viewport: Size,
1330        updates: cranpose_render_common::SceneUpdates<'_>,
1331    ) -> Result<(), Self::Error> {
1332        if updates.is_empty() {
1333            self.frontend.clear_fps_overlay();
1334        }
1335        self.frontend
1336            .scene
1337            .update_from_applier(applier, root, updates, true);
1338        Ok(())
1339    }
1340
1341    fn update_visual_scene_from_applier(
1342        &mut self,
1343        applier: &mut MemoryApplier,
1344        root: NodeId,
1345        _viewport: Size,
1346        updates: cranpose_render_common::SceneUpdates<'_>,
1347    ) -> Result<(), Self::Error> {
1348        if updates.is_empty() {
1349            self.frontend.clear_fps_overlay();
1350        }
1351        self.frontend
1352            .scene
1353            .update_from_applier(applier, root, updates, false);
1354        Ok(())
1355    }
1356
1357    fn draw_dev_overlay(&mut self, text: &str, viewport: Size) {
1358        const DEV_OVERLAY_NODE_ID: NodeId = NodeId::MAX;
1359        let key = cranpose_render_common::dev_overlay::DevOverlayKey::new(text, viewport);
1360        if self.frontend.dev_overlay_graph.is_some()
1361            && self
1362                .frontend
1363                .dev_overlay_cache
1364                .as_ref()
1365                .is_some_and(|cache| {
1366                    cache.text == key.text
1367                        && cache.viewport_width_bits == key.viewport_width_bits
1368                        && cache.viewport_height_bits == key.viewport_height_bits
1369                })
1370        {
1371            return;
1372        }
1373        self.frontend.fps_overlay_graph = Some(
1374            cranpose_render_common::dev_overlay::build_dev_overlay_graph(
1375                text,
1376                viewport,
1377                DEV_OVERLAY_NODE_ID,
1378            ),
1379        );
1380        self.frontend.dev_overlay_cache = Some(DevOverlayCache {
1381            text: key.text,
1382            viewport_width_bits: key.viewport_width_bits,
1383            viewport_height_bits: key.viewport_height_bits,
1384        });
1385        self.frontend.refresh_dev_overlay();
1386    }
1387
1388    fn set_inspector_overlay(&mut self, graph: Option<cranpose_render_common::graph::RenderGraph>) {
1389        self.frontend.inspector_overlay_graph = graph;
1390        self.frontend.refresh_dev_overlay();
1391    }
1392
1393    fn needs_frame_warmup(&self) -> bool {
1394        match &self.backend {
1395            PresentBackend::Sync(gpu_renderer) => gpu_renderer.needs_frame_warmup(),
1396            #[cfg(not(target_arch = "wasm32"))]
1397            PresentBackend::Threaded(handle) => handle
1398                .status()
1399                .needs_frame_warmup
1400                .load(std::sync::atomic::Ordering::Relaxed),
1401            PresentBackend::None => false,
1402        }
1403    }
1404
1405    fn awaits_pipelines(&self) -> bool {
1406        match &self.backend {
1407            PresentBackend::Sync(gpu_renderer) => gpu_renderer.awaits_pipelines(),
1408            #[cfg(not(target_arch = "wasm32"))]
1409            PresentBackend::Threaded(handle) => {
1410                let status = handle.status();
1411                status
1412                    .drew_placeholder
1413                    .load(std::sync::atomic::Ordering::Relaxed)
1414                    && status
1415                        .landing
1416                        .get()
1417                        .is_some_and(|landing| landing.in_flight())
1418            }
1419            PresentBackend::None => false,
1420        }
1421    }
1422}
1423
1424#[cfg(test)]
1425#[path = "tests/wgpu_tests.rs"]
1426mod tests;