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