Skip to main content

cranpose_render_wgpu/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4pub use offscreen::{COMPOSITION_BYTES_PER_PIXEL, offscreen_render_target_for_tests};
5pub use render::presentable_root_usages;
6mod ablation;
7mod arc_trig_fill;
8mod capture_hash;
9mod captured_frame;
10mod collect;
11mod cpu_allocation_stats;
12mod depth_gate;
13mod device_error_sentry;
14mod draw_pass;
15mod effect_renderer;
16mod fast_cores;
17mod frame;
18mod geometry;
19mod idle_pool;
20mod layer_cache;
21mod renderer_impl;
22pub use fast_cores::pin_current_thread_to_fast_cores;
23#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
24mod first_screen_glsl;
25mod fixed_pipeline;
26mod frame_graph;
27mod frame_packet;
28mod frontend;
29mod gpu_target;
30mod host_gl;
31#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
32pub use first_screen_glsl::{
33    FirstScreenGlslError, first_screen_stages, list_first_screen_stages, use_first_screen_glsl,
34};
35/// The GLSL templates of the built-in shader modules, which `build.rs` wrote.
36#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
37mod gl_templates {
38    include!(concat!(env!("OUT_DIR"), "/gl_templates.rs"));
39}
40#[cfg(test)]
41#[path = "tests/gles_lowering.rs"]
42mod gles_lowering;
43mod glyph_run;
44mod glyph_run_arena;
45pub(crate) mod gpu_stats;
46mod initial_present;
47#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
48mod inline_present_runtime;
49mod instant_triangles;
50mod lazy_resource;
51mod mesh_fallback;
52mod offscreen;
53mod opaque_prefix;
54mod output_conversion;
55mod pipeline;
56mod pipeline_compiler;
57/// The file in which the driver's compiled pipelines, and a record of the pipelines the first
58/// screen drew with, are kept between launches.
59#[cfg(not(target_arch = "wasm32"))]
60pub mod pipeline_disk_cache;
61mod pipeline_recorder;
62mod pipeline_records;
63#[cfg(not(target_arch = "wasm32"))]
64mod present_handle;
65#[cfg(not(target_arch = "wasm32"))]
66mod present_observer;
67#[cfg(not(target_arch = "wasm32"))]
68mod present_runtime;
69#[cfg(not(target_arch = "wasm32"))]
70mod present_thread;
71mod rc_slice_pool;
72mod record_columns;
73mod render;
74mod rrect_shadow;
75mod run_geometry;
76mod run_store;
77mod scene;
78mod scene_pass;
79mod scissor;
80mod shader_cache;
81mod shaders;
82mod shape_pipelines;
83mod shared_shader;
84mod target_state;
85#[cfg(test)]
86mod test_support;
87#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
88mod test_target;
89mod text_system;
90mod thread_state;
91mod window_packets;
92
93use std::sync::Arc;
94
95pub use captured_frame::CapturedFrame;
96pub use cpu_allocation_stats::DebugCpuAllocationStats;
97use cranpose_render_common::text_fonts::TextFonts;
98use cranpose_ui_graphics::Rect;
99pub use frame_graph::pass_timing::{GpuPassTimingEntry, GpuPassTimingReport};
100pub use frame_packet::PresentTimings;
101use frame_packet::RenderReturns;
102#[doc(hidden)]
103pub use frame_packet::{CancelReason, PresentOutcome};
104use frontend::RendererFrontend;
105pub use gpu_stats::{FrameDamage, FrameStatsSnapshot as RenderStatsSnapshot, WindowRects};
106pub use gpu_target::{GpuTarget, optional_device_features};
107pub use initial_present::{clear_to_background, clear_to_default_background};
108#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
109pub use inline_present_runtime::InlinePresentRuntime;
110use pipeline_compiler::PipelineCompilation;
111#[cfg(not(target_arch = "wasm32"))]
112use present_handle::PresentHandle;
113#[cfg(not(target_arch = "wasm32"))]
114pub use present_observer::PresentObserver;
115#[cfg(not(target_arch = "wasm32"))]
116use present_runtime::PresentRuntimeInit;
117#[cfg(not(target_arch = "wasm32"))]
118pub use present_thread::PresentThread;
119use render::{FrameOutput, FrameSubmit, GpuRenderer, GpuRendererInit};
120pub use render::{
121    frame_clear_color, frames_presented, pipelines_created, pipelines_created_off_frame,
122};
123pub use scene::{HitRegion, Scene};
124pub use shared_shader::{shader_stages_flattened, shader_stages_folded};
125#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
126pub use test_target::TestImages;
127pub use text_system::WgpuTextSystem;
128
129pub(crate) fn rect_to_quad(rect: Rect) -> [[f32; 2]; 4] {
130    [
131        [rect.x, rect.y],
132        [rect.x + rect.width, rect.y],
133        [rect.x, rect.y + rect.height],
134        [rect.x + rect.width, rect.y + rect.height],
135    ]
136}
137
138/// Why a [`WgpuRenderer`] call failed.
139#[derive(Debug)]
140pub enum WgpuRendererError {
141    /// The renderer could not draw, with the reason: no GPU was initialized for synchronous
142    /// rendering, there is no scene graph, or the GPU reported an error.
143    Wgpu(String),
144}
145
146// A renderer that draws on the calling thread, and the executor its frames go
147// through.
148struct SyncPresenter {
149    renderer: GpuRenderer,
150    submit: FrameSubmit,
151}
152
153enum PresentBackend {
154    None,
155    Sync(Box<SyncPresenter>),
156    #[cfg(not(target_arch = "wasm32"))]
157    Threaded(PresentHandle),
158}
159
160impl PresentBackend {
161    // The synchronous renderer, or the error a call that needs one reports.
162    fn sync_mut(&mut self) -> Result<&mut SyncPresenter, WgpuRendererError> {
163        match self {
164            Self::Sync(sync) => Ok(sync),
165            _ => Err(WgpuRendererError::Wgpu(
166                "GPU renderer not initialized for synchronous rendering. Call init_gpu() first."
167                    .to_string(),
168            )),
169        }
170    }
171}
172
173/// What [`WgpuRenderer::publish_frame`] did.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub enum PublishOutcome {
176    /// No scene graph exists; nothing to lower.
177    NoGraph,
178    /// The depth-one slot is occupied (or the renderer is not in threaded
179    /// mode): NO packet was built — backpressure lands before lowering.
180    NoCredit,
181    /// A packet was built and handed to the present runtime.
182    Published,
183}
184
185/// WGPU-based renderer for GPU-accelerated 2D rendering.
186///
187/// This renderer supports:
188/// - GPU-accelerated shape rendering (rectangles, rounded rectangles)
189/// - Gradients (solid, linear, radial)
190/// - GPU text rendering via retained raster image batches
191/// - Cross-platform support (Desktop, Web, Android)
192pub struct WgpuRenderer {
193    frontend: RendererFrontend,
194    backend: PresentBackend,
195    renderer_epoch: u64,
196    surface_epoch: u64,
197    on_device_lost: Option<DeviceLostHandler>,
198}
199
200/// What a host runs when the device it handed a [`WgpuRenderer`] is lost,
201/// after the loss is logged. It may run on any thread.
202pub type DeviceLostHandler = Arc<dyn Fn() + Send + Sync>;
203
204impl WgpuRenderer {
205    /// Create a new WGPU renderer.
206    ///
207    /// * `fonts` – font bytes to load, ordered by priority (first = highest priority).
208    ///   Pass `&[]` to load no fonts; text will not render until fonts are provided.
209    ///
210    /// Call [`init_gpu`][Self::init_gpu] before rendering.
211    pub fn new(fonts: &[&'static [u8]]) -> Self {
212        Self::with_text_system(WgpuTextSystem::from_fonts(fonts))
213    }
214
215    /// Create a renderer over fonts an app already built.
216    pub fn with_text_fonts(fonts: TextFonts) -> Self {
217        Self::with_text_system(WgpuTextSystem::from_text_fonts(fonts))
218    }
219
220    /// Create a renderer that hands the app the fonts of `text_system`.
221    pub fn with_text_system(text_system: WgpuTextSystem) -> Self {
222        Self {
223            frontend: RendererFrontend::new(text_system.fonts().clone()),
224            backend: PresentBackend::None,
225            renderer_epoch: 0,
226            surface_epoch: 0,
227            on_device_lost: None,
228        }
229    }
230
231    /// Runs `handler` when the device of a later `init_gpu` call is lost,
232    /// so the host can open another device and hand it over.
233    pub fn set_device_lost_handler(&mut self, handler: DeviceLostHandler) {
234        self.on_device_lost = Some(handler);
235    }
236
237    fn sync_gpu_renderer(&self) -> Option<&GpuRenderer> {
238        match &self.backend {
239            PresentBackend::Sync(sync) => Some(&sync.renderer),
240            _ => None,
241        }
242    }
243
244    fn retire_live_backend(&mut self) {
245        #[allow(unused_mut, reason = "only native targets change the backend")]
246        let mut backend = std::mem::replace(&mut self.backend, PresentBackend::None);
247        #[cfg(not(target_arch = "wasm32"))]
248        if let PresentBackend::Threaded(handle) = &mut backend {
249            while let Some(returns) = handle.try_drain() {
250                self.frontend.apply_returns(returns);
251            }
252            handle.shutdown();
253        }
254        drop(backend);
255    }
256
257    /// Drops what the renderer holds on its device, for a host whose device
258    /// is gone: the frees then reach the lost device, as a WebGL context
259    /// that is lost ignores them, rather than the device that replaces it.
260    /// [`Self::init_gpu`] gives the renderer a device again.
261    pub fn release_gpu(&mut self) {
262        self.retire_live_backend();
263    }
264
265    /// Initialize GPU resources with a WGPU device and queue.
266    ///
267    /// Replacing a live renderer (Android surface recreation, device loss)
268    /// bumps the renderer epoch, so a packet built against the previous
269    /// renderer is cancelled instead of drawn.
270    pub fn init_gpu(&mut self, target: GpuTarget) {
271        self.install_gpu(target, PipelineCompilation::Background);
272    }
273
274    /// [`init_gpu`][Self::init_gpu], compiling every pipeline where it is
275    /// first needed instead of on the background compiler: no frame draws
276    /// with a stand-in, which a reference frame in a test must not.
277    #[doc(hidden)]
278    pub fn init_gpu_compiling_inline_for_tests(&mut self, target: GpuTarget) {
279        self.install_gpu(target, PipelineCompilation::Inline);
280    }
281
282    fn install_gpu(&mut self, target: GpuTarget, pipeline_compilation: PipelineCompilation) {
283        let init = self.next_gpu_init(target, pipeline_compilation);
284        let submit = FrameSubmit::new(&init);
285        self.backend = PresentBackend::Sync(Box::new(SyncPresenter {
286            renderer: GpuRenderer::new(init),
287            submit,
288        }));
289    }
290
291    /// Retires the live backend and bumps the renderer epoch, then describes
292    /// the renderer that replaces it on `target`.
293    fn next_gpu_init(
294        &mut self,
295        target: GpuTarget,
296        pipeline_compilation: PipelineCompilation,
297    ) -> GpuRendererInit {
298        self.retire_live_backend();
299        self.renderer_epoch = self.renderer_epoch.wrapping_add(1);
300        target.renderer_init(
301            self.renderer_epoch,
302            pipeline_compilation,
303            self.on_device_lost.clone(),
304        )
305    }
306
307    /// [`init_gpu`][Self::init_gpu] for the threaded present runtime
308    /// (Android): the same epoch bump and planner replacement hygiene, but
309    /// instead of constructing a `GpuRenderer` here, everything it needs —
310    /// all owned, all `Send` — crosses to a spawned present thread that
311    /// constructs its own (its `Rc` caches are thread-confined). Frames
312    /// then flow through [`publish_frame`][Self::publish_frame] /
313    /// [`drain_present_returns`][Self::drain_present_returns] under the
314    /// depth-one credit protocol instead of [`render`][Self::render].
315    ///
316    /// * `waker` — wakes the producer's event loop after every returns
317    ///   send (the Android frame waker).
318    /// * `clock` — producer's monotonic nanosecond clock, so present-side
319    ///   [`PresentTimings`] share the producer telemetry's clock domain;
320    ///   `None` leaves timings at zero.
321    /// * `observer` — runs on the present thread around every present to the
322    ///   surface.
323    #[cfg(not(target_arch = "wasm32"))]
324    pub fn init_gpu_threaded(
325        &mut self,
326        target: GpuTarget,
327        waker: Arc<dyn Fn() + Send + Sync>,
328        clock: Option<Arc<dyn Fn() -> i64 + Send + Sync>>,
329        observer: Option<Box<dyn PresentObserver>>,
330    ) -> Result<(), WgpuRendererError> {
331        let init = PresentRuntimeInit {
332            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
333            clock,
334            observer,
335        };
336        let handle = PresentHandle::spawn(init, waker).map_err(WgpuRendererError::Wgpu)?;
337        self.backend = PresentBackend::Threaded(handle);
338        Ok(())
339    }
340
341    #[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
342    #[doc(hidden)]
343    pub fn init_gpu_inline_for_tests(&mut self, target: GpuTarget) -> InlinePresentRuntime {
344        let init = PresentRuntimeInit {
345            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
346            clock: None,
347            observer: None,
348        };
349        let (handle, state, msg_rx) = PresentHandle::new_inline(init, Arc::new(|| {}));
350        self.backend = PresentBackend::Threaded(handle);
351        InlinePresentRuntime::new(state, msg_rx)
352    }
353
354    /// Record that the surface was reconfigured (resize, format change,
355    /// swapchain recreation): bumps the surface epoch stamped into every
356    /// subsequent packet, so a packet built against the previous
357    /// configuration is cancelled by the present stage instead of drawn.
358    pub fn note_surface_reconfigured(&mut self) {
359        self.surface_epoch = self.surface_epoch.wrapping_add(1);
360    }
361
362    /// Clears each frame to nothing instead of the framework's background,
363    /// for a window whose surface composites with the desktop behind it. A
364    /// renderer starts opaque; `false` puts the background back. Takes
365    /// effect from the next frame, on either present backend.
366    pub fn set_transparent_background(&mut self, transparent: bool) {
367        self.frontend.transparent_background = transparent;
368    }
369
370    /// The scale from logical to device pixels the renderer draws the root with, as last set
371    /// by `Renderer::set_root_scale`. It starts at `1.0`.
372    pub fn root_scale(&self) -> f32 {
373        self.frontend.root_scale
374    }
375
376    /// Render the scene to a texture view.
377    ///
378    /// Producer first, present second: the frontend collects the frame into
379    /// a `frame_packet::FramePacket` (root and dev overlay alike), the GPU
380    /// renderer consumes it, and the present stage's returns fold back into
381    /// the frontend afterwards.
382    pub fn render(
383        &mut self,
384        texture: &wgpu::Texture,
385        view: &wgpu::TextureView,
386        width: u32,
387        height: u32,
388    ) -> Result<(), WgpuRendererError> {
389        self.render_frame(texture, view, width, height, frame::ImageContent::Untracked)
390    }
391
392    /// Renders the frame into a surface's presentable image `frame`, through
393    /// `view`. When the image carries the composition format and the capture
394    /// usages, the scene renders into it directly and no output conversion
395    /// pass runs. When the surface hands the image back with the frame it
396    /// last presented (`wgpu::Surface::keep_presented_images`), the frame
397    /// draws only what changed since that frame. When the surface hands its
398    /// images out cleared, as a WebGPU canvas does, and the frames change a
399    /// small part of a window drawn over more than twice, the renderer keeps
400    /// the frame in a texture of its own, draws only what changed there and
401    /// copies it into the image; see [`release_kept_copy`](Self::release_kept_copy).
402    pub fn render_surface_texture(
403        &mut self,
404        frame: &wgpu::SurfaceTexture,
405        view: &wgpu::TextureView,
406        width: u32,
407        height: u32,
408    ) -> Result<(), WgpuRendererError> {
409        let image = frame::ImageContent::of(frame);
410        self.render_frame(&frame.texture, view, width, height, image)
411    }
412
413    /// Clears `view` to the color a frame clears to before it draws. `view`
414    /// is the image of a surface that just took a frame through
415    /// [`render_surface_texture`](Self::render_surface_texture). The
416    /// renderer drops its copy of that frame, so the next frame draws whole.
417    /// A web page hides so a first frame that left out the draws of
418    /// pipelines still compiling in the browser.
419    #[cfg(target_arch = "wasm32")]
420    pub fn hide_drawn_frame(&mut self, view: &wgpu::TextureView) {
421        let Some(gpu_renderer) = self.sync_gpu_renderer() else {
422            return;
423        };
424        clear_to_background(
425            &gpu_renderer.device,
426            &gpu_renderer.queue,
427            view,
428            frame_clear_color(self.frontend.transparent_background),
429        );
430        self.release_kept_copy();
431    }
432
433    /// Presents a surface image this renderer drew with
434    /// [`render_surface_texture`](Self::render_surface_texture), on the queue
435    /// that recorded it.
436    ///
437    /// Before [`init_gpu`](Self::init_gpu) there is no queue, and the image is
438    /// released without being shown.
439    pub fn present(&self, frame: wgpu::SurfaceTexture) {
440        match self.sync_gpu_renderer() {
441            Some(gpu_renderer) => gpu_renderer.queue.present(frame),
442            None => log::debug!("surface image released: the renderer has no GPU queue"),
443        }
444    }
445
446    /// Draws a swapchain image the way the present runtime does on a surface
447    /// that keeps presented images: `index` is its place in a swapchain of
448    /// `images` and `kept` says it holds the frame drawn into it last.
449    #[doc(hidden)]
450    pub fn render_swapchain_image_for_tests(
451        &mut self,
452        texture: &wgpu::Texture,
453        view: &wgpu::TextureView,
454        index: u32,
455        images: u32,
456        kept: bool,
457    ) -> Result<(), WgpuRendererError> {
458        self.render_frame(
459            texture,
460            view,
461            texture.width(),
462            texture.height(),
463            frame::ImageContent::Numbered(frame::PresentedImage {
464                index,
465                kept,
466                images,
467            }),
468        )
469    }
470
471    /// Draws an image the way a surface that hands out its images cleared,
472    /// as a WebGPU canvas does, has it drawn.
473    #[doc(hidden)]
474    pub fn render_cleared_image_for_tests(
475        &mut self,
476        texture: &wgpu::Texture,
477        view: &wgpu::TextureView,
478    ) -> Result<(), WgpuRendererError> {
479        self.render_frame(
480            texture,
481            view,
482            texture.width(),
483            texture.height(),
484            frame::ImageContent::Cleared,
485        )
486    }
487
488    /// Lets go of the texture that keeps the last frame for a surface whose
489    /// images come cleared (see
490    /// [`render_surface_texture`](Self::render_surface_texture)), a window of
491    /// memory. A runtime calls it once its app holds still; the next frame
492    /// draws whole.
493    pub fn release_kept_copy(&mut self) {
494        if let PresentBackend::Sync(sync) = &mut self.backend {
495            sync.renderer.release_kept_copy();
496            self.frontend.forget_held();
497        }
498    }
499
500    fn render_frame(
501        &mut self,
502        texture: &wgpu::Texture,
503        view: &wgpu::TextureView,
504        width: u32,
505        height: u32,
506        image: frame::ImageContent,
507    ) -> Result<(), WgpuRendererError> {
508        self.frontend.landings = self.landings();
509        let SyncPresenter {
510            renderer: gpu_renderer,
511            submit,
512        } = self.backend.sync_mut()?;
513        let epochs = (self.renderer_epoch, self.surface_epoch);
514        let output = FrameOutput::display(texture, view, image);
515        let draw = |packet, returns: &mut RenderReturns| {
516            gpu_renderer.render(submit, (width, height), packet, epochs.1, returns, output)
517        };
518        self.frontend
519            .draw_window((width, height), epochs, image, draw)
520            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?
521            .map_err(WgpuRendererError::Wgpu)
522    }
523
524    /// Whether the surface already shows the current scene at `width` by
525    /// `height` device pixels: the frame drawn last into a surface that keeps
526    /// its presented images, with nothing changed since. A platform asks
527    /// before it takes the surface's next image, and when the surface shows
528    /// the scene it takes no image, draws nothing and presents nothing.
529    /// Otherwise the frame drawn next starts from the scene this collected.
530    pub fn shows_scene(&mut self, width: u32, height: u32) -> bool {
531        self.frontend.landings = self.landings();
532        let PresentBackend::Sync(sync) = &mut self.backend else {
533            return false;
534        };
535        let Some(packet) =
536            self.frontend
537                .take_packet(width, height, self.renderer_epoch, self.surface_epoch)
538        else {
539            return false;
540        };
541        let shown = sync.renderer.shows(&packet, (width, height));
542        if shown {
543            self.frontend.recycle(packet);
544        } else {
545            self.frontend.keep_packet(packet);
546        }
547        shown
548    }
549
550    /// Render the current scene into an RGBA pixel buffer for robot tests.
551    ///
552    /// Uses the renderer's configured root scale.
553    pub fn capture_frame(
554        &mut self,
555        width: u32,
556        height: u32,
557    ) -> Result<CapturedFrame, WgpuRendererError> {
558        self.capture_frame_with_scale(width, height, self.frontend.root_scale)
559    }
560
561    /// Builds every pipeline the pipeline cache file records on the
562    /// background compiler, and returns whether they were all built before
563    /// `timeout`, or before `stop` said to stop. An app runs it after an
564    /// update, before its next launch, so that launch finds them compiled;
565    /// the renderer writes the file when it is dropped, and drops the builds
566    /// not started. It draws nothing, and needs a renderer initialized for
567    /// synchronous rendering.
568    #[cfg(not(target_arch = "wasm32"))]
569    pub fn prepare_recorded_pipelines(
570        &mut self,
571        timeout: std::time::Duration,
572        stop: &dyn Fn() -> bool,
573    ) -> bool {
574        let PresentBackend::Sync(sync) = &mut self.backend else {
575            return false;
576        };
577        let gpu_renderer = &mut sync.renderer;
578        let deadline = web_time::Instant::now() + timeout;
579        let mut compiling = gpu_renderer.prepare_recorded();
580        while compiling {
581            if web_time::Instant::now() >= deadline || stop() {
582                return false;
583            }
584            std::thread::sleep(std::time::Duration::from_millis(10));
585            compiling = gpu_renderer.pipelines.compiling();
586        }
587        true
588    }
589
590    /// Render the current scene into an RGBA pixel buffer with an explicit scale.
591    ///
592    /// `width` and `height` are in device pixels and `root_scale` is the scale from logical to
593    /// device pixels. Needs a renderer initialized for synchronous rendering.
594    pub fn capture_frame_with_scale(
595        &mut self,
596        width: u32,
597        height: u32,
598        root_scale: f32,
599    ) -> Result<CapturedFrame, WgpuRendererError> {
600        let SyncPresenter {
601            renderer: gpu_renderer,
602            submit,
603        } = self.backend.sync_mut()?;
604        let packet = self
605            .frontend
606            .build_frame_packet_with_scale(
607                (width, height, root_scale),
608                self.renderer_epoch,
609                self.surface_epoch,
610                frontend::PacketFor::Capture,
611            )
612            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
613        let mut returns = RenderReturns::default();
614        let result = gpu_renderer.render_to_rgba_pixels(
615            submit,
616            (width, height),
617            packet,
618            self.surface_epoch,
619            &mut returns,
620        );
621        self.frontend.apply_returns(returns);
622        let pixels = result.map_err(WgpuRendererError::Wgpu)?;
623        Ok(CapturedFrame {
624            width,
625            height,
626            pixels,
627            stats: gpu_renderer.last_frame_stats(),
628        })
629    }
630
631    /// Threaded mode: whether the present thread takes a packet now. Two
632    /// packets go in flight at most.
633    /// The Android loop checks this BEFORE `shell.update()` so
634    /// backpressure lands before the expensive update/lowering work.
635    /// Always `true` on the sync path, which has no slot to fill.
636    #[cfg(not(target_arch = "wasm32"))]
637    pub fn has_frame_credit(&self) -> bool {
638        match &self.backend {
639            PresentBackend::Threaded(handle) => handle.has_credit(),
640            PresentBackend::Sync(_) | PresentBackend::None => true,
641        }
642    }
643
644    /// Threaded mode: whether the present thread has handed back a frame
645    /// that [`drain_present_returns`][Self::drain_present_returns] has not
646    /// folded back yet, so draining it would free a publish credit. A loop
647    /// out of credit can work on other things until this turns true.
648    /// Always `false` outside threaded mode.
649    #[cfg(not(target_arch = "wasm32"))]
650    pub fn frame_credit_returned(&self) -> bool {
651        match &self.backend {
652            PresentBackend::Threaded(handle) => handle.has_undrained_return(),
653            PresentBackend::Sync(_) | PresentBackend::None => false,
654        }
655    }
656
657    /// Threaded mode: lower the current scene into a packet and hand it to
658    /// the present runtime. Credit is checked FIRST — a `NoCredit` return
659    /// means no packet was built at all (`frame_sequence` does not
660    /// advance). Returns `NoCredit` (with an error log) when the renderer
661    /// is not in threaded mode.
662    #[cfg(not(target_arch = "wasm32"))]
663    pub fn publish_frame(&mut self, width: u32, height: u32) -> PublishOutcome {
664        self.frontend.landings = self.landings();
665        let PresentBackend::Threaded(handle) = &mut self.backend else {
666            log::error!("publish_frame called without a threaded present runtime");
667            return PublishOutcome::NoCredit;
668        };
669        if !handle.has_credit() {
670            return PublishOutcome::NoCredit;
671        }
672        let Some(packet) = self.frontend.build_frame_packet(
673            width,
674            height,
675            self.renderer_epoch,
676            self.surface_epoch,
677        ) else {
678            return PublishOutcome::NoGraph;
679        };
680        match handle.publish(packet) {
681            Ok(()) => PublishOutcome::Published,
682            Err(packet) => {
683                let mut returns = RenderReturns::default();
684                GpuRenderer::cancel_packet(*packet, CancelReason::SurfaceUnavailable, &mut returns);
685                self.frontend.apply_returns(returns);
686                log::error!("present runtime unavailable; frame recovered, not published");
687                PublishOutcome::NoCredit
688            }
689        }
690    }
691
692    /// Threaded mode: fold every pending `RenderReturns` back into
693    /// producer state and free the publish credit. Returns how many were
694    /// drained. No-op outside threaded mode.
695    #[cfg(not(target_arch = "wasm32"))]
696    pub fn drain_present_returns(&mut self) -> usize {
697        self.drain_present_returns_with(&mut |_, _, _| {})
698    }
699
700    /// [`drain_present_returns`][Self::drain_present_returns], reporting
701    /// each drained frame's id, outcome and present-thread timings — the
702    /// Android loop feeds its frame telemetry from this.
703    #[cfg(not(target_arch = "wasm32"))]
704    pub fn drain_present_returns_with(
705        &mut self,
706        on_return: &mut dyn FnMut(u64, PresentOutcome, PresentTimings),
707    ) -> usize {
708        let mut drained = 0;
709        loop {
710            let returns = {
711                let PresentBackend::Threaded(handle) = &mut self.backend else {
712                    break;
713                };
714                match handle.try_drain() {
715                    Some(returns) => returns,
716                    None => break,
717                }
718            };
719            drained += 1;
720            let frame_id = returns.frame_id;
721            let outcome = returns.outcome;
722            let timings = returns.timings;
723            self.frontend.apply_returns(returns);
724            on_return(frame_id, outcome, timings);
725        }
726        drained
727    }
728
729    /// The thread this renderer hands its frames to, when it presents on one
730    /// ([`init_gpu_threaded`][Self::init_gpu_threaded]); `None` when it
731    /// draws on the calling thread.
732    #[cfg(not(target_arch = "wasm32"))]
733    pub fn present_thread(&mut self) -> Option<PresentThread<'_>> {
734        let PresentBackend::Threaded(handle) = &mut self.backend else {
735            return None;
736        };
737        Some(PresentThread {
738            handle,
739            surface_epoch: &mut self.surface_epoch,
740        })
741    }
742
743    /// Threaded mode: drain outstanding returns, stop the present thread
744    /// and join it. The renderer returns to the uninitialized state.
745    #[cfg(not(target_arch = "wasm32"))]
746    pub fn shutdown_present_runtime(&mut self) {
747        if matches!(self.backend, PresentBackend::Threaded(_)) {
748            self.retire_live_backend();
749        }
750    }
751
752    /// The OS id of the thread that presents frames, once that thread has
753    /// started, on systems whose scheduler hints name threads by one.
754    /// `None` when frames present on the calling thread.
755    pub fn present_thread_id(&self) -> Option<i32> {
756        match &self.backend {
757            #[cfg(not(target_arch = "wasm32"))]
758            PresentBackend::Threaded(handle) => {
759                let id = handle
760                    .status()
761                    .thread_id
762                    .load(std::sync::atomic::Ordering::Relaxed);
763                (id != 0).then_some(id)
764            }
765            _ => None,
766        }
767    }
768
769    /// The producer's monotone packet sequence: the `frame_id` stamped on
770    /// the most recently lowered packet. After a `Published` outcome this
771    /// is the published frame's id (the Android loop keys its telemetry on
772    /// it); it also proves a `NoCredit` publish never lowered a frame.
773    pub fn last_published_frame_id(&self) -> u64 {
774        self.frontend.frame_sequence
775    }
776
777    /// The counters of the most recent frame the renderer drew, or `None` before it drew one.
778    pub fn last_frame_stats(&self) -> Option<RenderStatsSnapshot> {
779        match &self.backend {
780            PresentBackend::Sync(sync) => sync.renderer.last_frame_stats(),
781            #[cfg(not(target_arch = "wasm32"))]
782            PresentBackend::Threaded(handle) => *handle
783                .status()
784                .last_frame_stats
785                .lock()
786                .unwrap_or_else(std::sync::PoisonError::into_inner),
787            PresentBackend::None => None,
788        }
789    }
790
791    /// Whether the pipeline cache file held an earlier launch's first screen,
792    /// whose pipelines build ahead of this renderer's first frame; `false`
793    /// for a first launch or emptied caches, whose first frame builds its
794    /// pipelines, and for a renderer that does not draw on the calling
795    /// thread.
796    #[cfg(not(target_arch = "wasm32"))]
797    pub fn first_screen_recorded(&self) -> bool {
798        self.sync_gpu_renderer()
799            .is_some_and(GpuRenderer::first_screen_recorded)
800    }
801
802    /// The pipelines this renderer's first screen drew with, encoded for
803    /// [`Self::build_first_screen_pipelines`] in a later launch. `None`
804    /// until the first screen ends, two seconds after the first frame and
805    /// later by every wait for a pipeline, and for a renderer that does not
806    /// draw on the calling thread.
807    pub fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
808        self.sync_gpu_renderer()
809            .and_then(|renderer| renderer.pipelines.first_screen_pipelines())
810    }
811
812    /// Builds now the pipelines one set in `records` names: sets
813    /// [`Self::first_screen_pipelines`] wrote, one after another, each at the
814    /// size its first frame drew. A web page calls this as its renderer
815    /// starts, so the browser compiles them while the page composes its
816    /// first screen. Of the sets drawn on this renderer's backend by a build
817    /// with the same layout of pipeline keys, the one drawn nearest to
818    /// `viewport` pixels builds: a phone's screen and a desktop window's
819    /// draw with different pipelines, and a frame that waits for pipelines
820    /// it does not draw with comes later. A renderer that does not draw on
821    /// the calling thread builds nothing.
822    pub fn build_first_screen_pipelines(&mut self, records: &[u8], viewport: (u32, u32)) {
823        if let PresentBackend::Sync(sync) = &mut self.backend {
824            sync.renderer.build_first_screen(records, viewport);
825        }
826    }
827
828    /// GPU milliseconds by pass label, aggregated since the last `[GPU-PASS]`
829    /// print. Empty unless `CRANPOSE_GPU_PASS_TIMING` armed pass timing on a
830    /// device with [`wgpu::Features::TIMESTAMP_QUERY`].
831    pub fn gpu_pass_timings(&self) -> GpuPassTimingReport {
832        match &self.backend {
833            PresentBackend::Sync(sync) => sync.submit.executor.pass_timing_report(),
834            _ => GpuPassTimingReport::default(),
835        }
836    }
837
838    /// The sizes and capacities of the renderer's CPU-side scene data, scratch buffers and
839    /// caches, for memory diagnostics. The members of a renderer that does not draw on the
840    /// calling thread cover the scene only.
841    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
842        let mut stats = self
843            .sync_gpu_renderer()
844            .map_or_default(GpuRenderer::debug_cpu_allocation_stats);
845        stats.scene_graph_node_count = self.frontend.scene.store().node_count();
846        stats.scene_graph_heap_bytes = self.frontend.scene.store().heap_bytes();
847        stats.scene_hits = self.frontend.scene.hit_storage();
848        stats
849    }
850
851    /// Starts a frame drawn while none has shown whole yet. Such a frame
852    /// builds the pipelines it expects a later frame to need at its end, so
853    /// the browser compiles them behind the frame's own.
854    #[cfg(target_arch = "wasm32")]
855    pub fn begin_first_frame(&self) {
856        if let Some(gpu_renderer) = self.sync_gpu_renderer() {
857            gpu_renderer.pipelines.compiler.begin_first_frame();
858        }
859    }
860
861    /// Tells the renderer that the pipelines the browser compiled in the
862    /// background landed (`wgpu::Device::compile_pipelines_in_background`).
863    /// Earlier frames left out the draws that use them: the next frame drops
864    /// what those frames drew and kept, and draws again what they left out.
865    #[cfg(target_arch = "wasm32")]
866    pub fn background_pipelines_landed(&mut self) {
867        if let PresentBackend::Sync(sync) = &mut self.backend {
868            sync.renderer.background_pipelines_landed();
869        }
870    }
871
872    /// Tells the renderer that the browser compiles the pipelines it creates
873    /// from now on in the background (`wgpu::Device::compile_pipelines_in_background`).
874    /// On WebGPU the first screen draws its shapes with a general pipeline,
875    /// whose one compile stands in for the specialized ones; those it builds
876    /// once this is called, and draws switch to each as it lands. A
877    /// renderer whose target is no browser's builds nothing more for it.
878    pub fn compile_pipelines_in_background(&mut self) {
879        if let PresentBackend::Sync(sync) = &mut self.backend {
880            sync.renderer.pipelines.compile_pipelines_in_background();
881        }
882    }
883
884    /// Return the WGPU device when GPU resources are initialized.
885    /// Sync backend only (desktop/web reconfigure paths); the threaded
886    /// runtime owns its device on the present thread.
887    pub fn try_device(&self) -> Option<&wgpu::Device> {
888        self.sync_gpu_renderer().map(|r| &*r.device)
889    }
890
891    #[doc(hidden)]
892    pub fn try_queue_for_tests(&self) -> Option<&wgpu::Queue> {
893        self.sync_gpu_renderer().map(|r| &*r.queue)
894    }
895
896    #[doc(hidden)]
897    pub fn device_error_count_for_tests(&self) -> u64 {
898        self.sync_gpu_renderer()
899            .map_or(0, GpuRenderer::device_error_count)
900    }
901
902    #[doc(hidden)]
903    pub fn build_frame_packet_for_tests(
904        &mut self,
905        width: u32,
906        height: u32,
907    ) -> Option<HeldFramePacket> {
908        self.frontend.landings = self.landings();
909        self.frontend
910            .build_frame_packet(width, height, self.renderer_epoch, self.surface_epoch)
911            .map(HeldFramePacket)
912    }
913
914    // The renderer's count of pipeline landings, which a window packet built
915    // now culls by.
916    fn landings(&mut self) -> Option<u64> {
917        match &mut self.backend {
918            PresentBackend::Sync(sync) => Some(sync.renderer.pipelines.count_landings()),
919            #[cfg(not(target_arch = "wasm32"))]
920            PresentBackend::Threaded(handle) => {
921                handle.status().landing.get().map(|landing| landing.built())
922            }
923            PresentBackend::None => None,
924        }
925    }
926
927    /// Return a producer-built packet without presenting it, as a target
928    /// that keeps its frames returns a packet whose damage it drew. This
929    /// exercises the bounded scene-storage recycler and the damage back-off
930    /// that normal present returns drive, in offline producer benchmarks.
931    ///
932    /// ```
933    /// use cranpose_render_wgpu::{HeldFramePacket, WgpuRenderer};
934    ///
935    /// fn return_without_presenting(renderer: &mut WgpuRenderer, packet: HeldFramePacket) {
936    ///     renderer.return_held_packet_for_tests(packet);
937    /// }
938    /// ```
939    #[doc(hidden)]
940    pub fn return_held_packet_for_tests(&mut self, packet: HeldFramePacket) {
941        self.frontend
942            .apply_returns(RenderReturns::drawn_in_place(packet.0));
943    }
944
945    #[doc(hidden)]
946    pub fn render_held_packet_for_tests(
947        &mut self,
948        texture: &wgpu::Texture,
949        view: &wgpu::TextureView,
950        width: u32,
951        height: u32,
952        packet: HeldFramePacket,
953    ) -> Result<PresentOutcome, WgpuRendererError> {
954        let SyncPresenter {
955            renderer: gpu_renderer,
956            submit,
957        } = self.backend.sync_mut()?;
958        let mut returns = RenderReturns::default();
959        let result = gpu_renderer.render(
960            submit,
961            (width, height),
962            packet.0,
963            self.surface_epoch,
964            &mut returns,
965            FrameOutput::display(texture, view, frame::ImageContent::Untracked),
966        );
967        let outcome = returns.outcome;
968        self.frontend.apply_returns(returns);
969        result.map_err(WgpuRendererError::Wgpu)?;
970        Ok(outcome)
971    }
972}
973
974#[doc(hidden)]
975pub struct HeldFramePacket(frame_packet::FramePacket);
976
977impl Default for WgpuRenderer {
978    fn default() -> Self {
979        Self::new(&[])
980    }
981}
982
983#[cfg(test)]
984#[path = "tests/wgpu_tests.rs"]
985mod tests;