Skip to main content

cranpose_render_wgpu/
gpu_stats.rs

1use cranpose_core::NodeId;
2use cranpose_render_common::raster_cache::{
3    LAYER_RASTER_CACHE_KIND_COUNT, LAYER_RASTER_CACHE_KIND_LABELS,
4};
5use cranpose_ui_graphics::Rect;
6
7use crate::{frame_graph::FrameCommandStats, run_geometry::ShapeFill};
8
9/// A diagnostics line: logcat on Android, where nothing reads stderr, and
10/// stderr elsewhere.
11macro_rules! stats_line {
12    ($($arg:tt)*) => {{
13        #[cfg(target_os = "android")]
14        log::info!($($arg)*);
15        #[cfg(not(target_os = "android"))]
16        eprintln!($($arg)*);
17    }};
18}
19
20mod frame_stats;
21pub(crate) use frame_stats::FrameStats;
22
23const TOP_ISOLATED_LAYER_LIMIT: usize = 8;
24
25/// A layer the renderer drew into an offscreen texture of its own.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct IsolatedLayerStat {
28    /// The node of the layer, or `None` when no node owns it.
29    pub node_id: Option<NodeId>,
30    /// The layer's bounds in logical pixels.
31    pub logical_rect: Rect,
32    /// Width of the layer's offscreen texture in device pixels.
33    pub width: u32,
34    /// Height of the layer's offscreen texture in device pixels.
35    pub height: u32,
36}
37
38impl IsolatedLayerStat {
39    fn pixel_area(self) -> u64 {
40        (self.width as u64) * (self.height as u64)
41    }
42}
43
44impl Default for IsolatedLayerStat {
45    fn default() -> Self {
46        Self {
47            node_id: None,
48            logical_rect: Rect {
49                x: 0.0,
50                y: 0.0,
51                width: 0.0,
52                height: 0.0,
53            },
54            width: 0,
55            height: 0,
56        }
57    }
58}
59
60/// The window pixels a frame changes against the frame the renderer's
61/// composition target kept.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63#[expect(
64    clippy::large_enum_variant,
65    reason = "a frame's statistics keep its damage inline; a box would allocate every frame"
66)]
67pub enum FrameDamage {
68    /// The frame drew straight into the presentable image, which keeps no
69    /// earlier frame, or was a screenshot, drawn whole.
70    #[default]
71    Untracked,
72    /// Recent frames changed most of the window, so the frame skipped
73    /// comparing.
74    Skipped,
75    /// The whole window: the target kept no frame to compare with, or the
76    /// frame changes most of it.
77    Full,
78    /// Only the pixels of these rects; none when nothing changes.
79    Part(WindowRects),
80}
81
82/// Up to 32 rects of window pixels that share no pixel, each as
83/// `[x, y, width, height]`.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub struct WindowRects {
86    rects: [[u32; 4]; crate::frame::MAX_DAMAGE_RECTS],
87    len: usize,
88}
89
90impl WindowRects {
91    /// The rects.
92    pub fn rects(&self) -> &[[u32; 4]] {
93        &self.rects[..self.len]
94    }
95
96    /// Whether the pixel at `x`, `y` lies in one of the rects.
97    pub fn contains(&self, x: u32, y: u32) -> bool {
98        self.rects().iter().any(|&[left, top, width, height]| {
99            x >= left && y >= top && x < left + width && y < top + height
100        })
101    }
102
103    /// The pixels of all the rects.
104    pub fn pixels(&self) -> u64 {
105        self.rects()
106            .iter()
107            .map(|&[_, _, width, height]| u64::from(width) * u64::from(height))
108            .sum()
109    }
110
111    /// Adds `rect`, past the rects held: the renderer's damage holds no
112    /// more than four.
113    pub(crate) fn push(&mut self, rect: [u32; 4]) {
114        if let Some(slot) = self.rects.get_mut(self.len) {
115            *slot = rect;
116            self.len += 1;
117        }
118    }
119}
120
121/// The counters of one drawn frame, from `WgpuRenderer::last_frame_stats`. Pixel counts are in
122/// device pixels.
123#[derive(Clone, Copy, Debug, Default, PartialEq)]
124pub struct FrameStatsSnapshot {
125    /// Submissions to the GPU queue during the frame.
126    pub submits: u32,
127    /// Command encoders the frame recorded.
128    pub encoder_count: u32,
129    /// Submissions to the GPU queue, as counted from the recorded commands; equals `submits`.
130    pub submit_count: u32,
131    /// Render passes the frame recorded.
132    pub pass_count: u32,
133    /// Sum of every render pass's first color target area: the tile traffic a
134    /// tiling GPU pays whatever the passes draw.
135    pub pass_pixels: u64,
136    /// Texture regions copied outside any pass, and their texels.
137    pub copy_count: u32,
138    /// Texels of those copies.
139    pub copy_pixels: u64,
140    /// Offscreen textures the frame took from the pool or created.
141    pub offscreen_acquires: u32,
142    /// Of the acquired offscreen textures, those created because the pool held none that fit.
143    pub offscreen_news: u32,
144    /// Bytes of every offscreen texture the frame acquired, new or reused.
145    pub offscreen_total_bytes: u64,
146    /// Bytes of the textures the frame used for one frame only.
147    pub transient_texture_bytes: u64,
148    /// Bytes of the textures kept between frames: the offscreen pool and the layer cache.
149    pub retained_texture_bytes: u64,
150    /// Bytes the frame uploaded to the GPU.
151    pub upload_bytes: u64,
152    /// Buffer writes the frame staged: uploads that reach the GPU as one
153    /// write each, however many draws they carry.
154    pub upload_writes: u32,
155    /// Layers the frame drew into an offscreen texture of their own.
156    pub isolated_layer_renders: u32,
157    /// Pixels of the offscreen textures of those layers.
158    pub isolated_layer_pixels: u64,
159    /// Layers drawn from the layer cache instead of drawn again.
160    pub layer_cache_hits: u32,
161    /// Capture passes that replayed ops not yet on the page.
162    pub capture_fixup_passes: u32,
163    /// Layers drawn anew and stored in the layer cache, because it held no match.
164    pub layer_cache_misses: u32,
165    /// Pixels of the layers drawn from the layer cache.
166    pub layer_cache_hit_pixels: u64,
167    /// Pixels of the layers drawn anew and stored in the layer cache.
168    pub layer_cache_miss_pixels: u64,
169    /// Hits per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
170    pub layer_cache_hits_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
171    /// Stores per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
172    pub layer_cache_misses_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
173    /// Stored pixels per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
174    pub layer_cache_miss_pixels_by_kind: [u64; LAYER_RASTER_CACHE_KIND_COUNT],
175    /// Shadows drawn from a cached blurred texture.
176    pub shadow_shape_cache_hits: u32,
177    /// Shadows blurred anew because the shadow cache held no match.
178    pub shadow_shape_cache_misses: u32,
179    /// Pixels composited from the cached shadow textures.
180    pub shadow_shape_cache_hit_pixels: u64,
181    /// Pixels of the shadow textures blurred anew.
182    pub shadow_shape_cache_miss_pixels: u64,
183    /// Shadows whose source holds more than shapes, such as text, that found no cached texture and
184    /// were blurred anew.
185    pub shadow_text_blur_fallbacks: u32,
186    /// Blur passes the frame encoded, each downsample, horizontal and vertical pass counting one.
187    pub blur_passes: u32,
188    /// Backdrop stages resolved: every stage flushes the page and captures
189    /// once, so the layer pass count is one more than this.
190    pub stages: u32,
191    /// Backdrops whose stage texture the layer cache pinned this frame, so
192    /// later frames replay their composites from it.
193    pub backdrop_admissions: u32,
194    /// Opaque page prefixes copied into the layer cache this frame.
195    pub prefix_admissions: u32,
196    /// Captures averaged into a quarter-size substrate for a shader's wide
197    /// taps.
198    pub substrates: u32,
199    /// Passes that draw at least one resolved composite: a final pass holding
200    /// twelve glass tails counts once, a composite resolved into its own
201    /// texture counts its own pass.
202    pub composite_passes: u32,
203    /// Render effects, such as offsets and runtime shaders, the frame applied to an offscreen
204    /// source.
205    pub effect_applies: u32,
206    /// Pixels shaded by runtime shader composites: what every glass surface
207    /// costs a tiling GPU per frame, each capture that re-shades one included.
208    pub shader_pixels: u64,
209    /// Pixels the blur passes write: every downsample, horizontal and
210    /// vertical pass of a backdrop's blur and of its substrates, within
211    /// the scissor the pass was given.
212    pub blur_pixels: u64,
213    /// Pixels the shape draws rasterize: a band drawn as a mesh counts its
214    /// mesh, everything else its quad. Fill rate is what a scene of rings
215    /// costs a tiling GPU, however few draws it takes.
216    pub shape_fill_pixels: u64,
217    /// `shape_fill_pixels` split by shape kind and brush, in the order of
218    /// `ShapeFill::LABELS`: which records a fill-bound frame pays for.
219    pub shape_fill_pixels_by_class: [u64; ShapeFill::CLASSES],
220    /// Vertices the shape draws run through the vertex stage: six per quad,
221    /// six per band segment. A tiling GPU stores every vertex's varyings
222    /// before it shades a pixel, so this bounds a frame as fill does.
223    pub shape_vertices: u64,
224    /// Batches of shape draws the frame recorded.
225    pub shape_passes: u32,
226    /// Shape draws that took a stand-in while their pipeline compiled: a
227    /// general pipeline, or triangles the CPU laid out.
228    pub shape_pipeline_fallback_draws: u32,
229    /// Image, glyph, shadow and layer draws that took the instant pipeline
230    /// while their own compiled.
231    pub instant_draws: u32,
232    /// Shape draws using a completed specialized pipeline.
233    pub shape_specialized_draws: u32,
234    /// Shape draws laying opaque interiors down in a pass's depth pre-pass.
235    pub shape_interior_draws: u32,
236    /// Render passes that took a depth buffer for their opaque interiors.
237    pub depth_passes: u32,
238    /// Pipelines this process has built, counted since it started rather than
239    /// over the frame. A count that grows while a person is interacting names
240    /// a backend shader compile they waited through.
241    pub pipelines_created: u64,
242    /// Runtime shader draws using a shader's general pipeline while the
243    /// specialization they asked for compiles in the background.
244    pub shader_pipeline_fallback_draws: u32,
245    /// Runtime shader draws using a completed specialized pipeline.
246    pub shader_specialized_draws: u32,
247    /// Effects drawn as their placeholder, or left out, because no pipeline
248    /// they need had compiled yet.
249    pub placeholder_draws: u32,
250    /// Batches of image draws the frame recorded.
251    pub image_passes: u32,
252    /// Batches of text draws the frame recorded.
253    pub text_passes: u32,
254    /// Shape, image, glyph and composite draws recorded this frame. The
255    /// `*_passes` counters above count *batches* or passes, so a single image
256    /// batch reports `image_passes=1` however many images it draws; this
257    /// counts what the driver actually sees. Blur and effect quads are not
258    /// included: they are one draw each and already counted by `blur_passes`
259    /// and `effect_applies`.
260    pub draw_calls: u32,
261    /// The window pixels the frame changes against the frame the
262    /// renderer's composition target kept.
263    pub damage: FrameDamage,
264    /// The window pixels the frame drew again: all of them, or those of the
265    /// damage, over what the frame before left in the rest.
266    pub repainted_pixels: u64,
267    /// The window pixels the frame's image still shows as an earlier frame
268    /// drew them with stand-ins, which the frame did not draw again: no
269    /// pipeline landed since. A frame after the next landing draws them.
270    pub kept_stand_in_pixels: u64,
271    /// Texts drawn from the cache of rasterized text images.
272    pub text_image_cache_hits: u32,
273    /// Texts rasterized into an image because the cache held none.
274    pub text_image_cache_misses: u32,
275    /// Pixels of the text images taken from the cache.
276    pub text_image_cache_hit_pixels: u64,
277    /// Pixels of the text images rasterized.
278    pub text_image_cache_miss_pixels: u64,
279    /// Bytes of the text images rasterized, four per pixel.
280    pub text_image_raster_bytes: u64,
281    /// Glyphs found in the glyph atlas.
282    pub text_glyph_atlas_hits: u32,
283    /// Glyphs rasterized and added to the glyph atlas.
284    pub text_glyph_atlas_misses: u32,
285    /// Pixels of the glyphs added to the glyph atlas.
286    pub text_glyph_atlas_miss_pixels: u64,
287    /// Texts whose glyph runs the frame laid out again: a text drawn as it
288    /// was before takes its run from the cache.
289    pub text_glyph_runs_collected: u32,
290    /// Textures held for reuse at the end of the frame, with the composition target.
291    pub offscreen_pool_size: u32,
292    /// Bytes of the textures counted by `offscreen_pool_size`.
293    pub offscreen_pool_bytes: u64,
294    /// Rasterized text images in the text image cache at the end of the frame.
295    pub text_pool_size: u32,
296    /// Layers in the layer cache at the end of the frame.
297    pub layer_cache_size: u32,
298    /// Bytes of the layer cache's textures at the end of the frame.
299    pub layer_cache_bytes: u64,
300    /// Image textures cached at the end of the frame.
301    pub image_cache_size: u32,
302    /// The largest isolated layers of the frame by pixel area, largest first, in the first
303    /// `top_isolated_layer_count` entries; the rest are `None`.
304    pub top_isolated_layers: [Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT],
305    /// How many entries of `top_isolated_layers` are filled, at most eight.
306    pub top_isolated_layer_count: usize,
307}
308
309impl FrameStatsSnapshot {
310    fn shape_fill_by_class_text(&self) -> String {
311        let mut text = String::new();
312        for (label, pixels) in ShapeFill::LABELS
313            .iter()
314            .zip(self.shape_fill_pixels_by_class)
315        {
316            if pixels > 0 {
317                use std::fmt::Write;
318                let _ = write!(text, " {label}={:.2}MP", pixels as f64 / 1_000_000.0);
319            }
320        }
321        text
322    }
323
324    pub(crate) fn with_command_stats_added(mut self, stats: FrameCommandStats) -> Self {
325        self.submits = self.submits.saturating_add(stats.submit_count);
326        self.encoder_count = self.encoder_count.saturating_add(stats.encoder_count);
327        self.submit_count = self.submit_count.saturating_add(stats.submit_count);
328        self.pass_count = self.pass_count.saturating_add(stats.pass_count);
329        self.pass_pixels = self.pass_pixels.saturating_add(stats.pass_pixels);
330        self.copy_count = self.copy_count.saturating_add(stats.copy_count);
331        self.copy_pixels = self.copy_pixels.saturating_add(stats.copy_pixels);
332        self.transient_texture_bytes = self
333            .transient_texture_bytes
334            .saturating_add(stats.transient_texture_bytes);
335        self.retained_texture_bytes = self
336            .retained_texture_bytes
337            .max(stats.retained_texture_bytes);
338        self.upload_bytes = self.upload_bytes.saturating_add(stats.upload_bytes);
339        self.upload_writes = self.upload_writes.saturating_add(stats.upload_writes);
340        self.offscreen_acquires = self
341            .offscreen_acquires
342            .saturating_add(stats.transient_acquires);
343        self.offscreen_news = self.offscreen_news.saturating_add(stats.transient_news);
344        self
345    }
346
347    /// The largest isolated surface of the frame as `WxH@(x,y)` in device
348    /// pixels and logical origin, or `-`.
349    fn top_isolated_display(&self) -> String {
350        match &self.top_isolated_layers[0] {
351            Some(top) => format!(
352                "{}x{}@({:.0},{:.0})",
353                top.width, top.height, top.logical_rect.x, top.logical_rect.y
354            ),
355            None => "-".to_string(),
356        }
357    }
358
359    /// The largest isolated layers of the frame by pixel area, largest first.
360    pub fn top_isolated_layers(self) -> impl Iterator<Item = IsolatedLayerStat> {
361        self.top_isolated_layers
362            .into_iter()
363            .flatten()
364            .take(self.top_isolated_layer_count)
365    }
366
367    fn layer_cache_hit_rate(self) -> f64 {
368        let total = self.layer_cache_hits + self.layer_cache_misses;
369        if total > 0 {
370            (self.layer_cache_hits as f64 / total as f64) * 100.0
371        } else {
372            0.0
373        }
374    }
375
376    fn miss_pixels_by_kind_display(&self) -> String {
377        by_kind_display(&self.layer_cache_miss_pixels_by_kind, |pixels| {
378            format!("{:.2}MP", pixels as f64 / 1_000_000.0)
379        })
380    }
381
382    fn hits_by_kind_display(&self) -> String {
383        by_kind_display(&self.layer_cache_hits_by_kind, |hits| hits.to_string())
384    }
385
386    fn print(self, frame_count: u64) {
387        let mb = self.offscreen_total_bytes as f64 / (1024.0 * 1024.0);
388        let upload_mb = self.upload_bytes as f64 / (1024.0 * 1024.0);
389        let retained_mb = self.retained_texture_bytes as f64 / (1024.0 * 1024.0);
390        let pool_mb = self.offscreen_pool_bytes as f64 / (1024.0 * 1024.0);
391        let layer_cache_hit_mpx = self.layer_cache_hit_pixels as f64 / 1_000_000.0;
392        let layer_cache_miss_mpx = self.layer_cache_miss_pixels as f64 / 1_000_000.0;
393        let shadow_cache_hit_mpx = self.shadow_shape_cache_hit_pixels as f64 / 1_000_000.0;
394        let shadow_cache_miss_mpx = self.shadow_shape_cache_miss_pixels as f64 / 1_000_000.0;
395        let layer_cache_mb = self.layer_cache_bytes as f64 / (1024.0 * 1024.0);
396        let isolated_layer_mpx = self.isolated_layer_pixels as f64 / 1_000_000.0;
397        stats_line!(
398            "[GPU f#{}] encoders={} submits={} passes={} pass_px={:.2}MP copies={} copy_px={:.2}MP | offscreen: acq={} new={} {:.1}MB pool={}({:.1}MB) retained={:.1}MB | \
399             uploads={:.2}MB writes={} | \
400             isolated_layers={} area={:.2}MP top={} | \
401             layer_cache: hit={} miss={} {:.1}% hit_px={:.2}MP miss_px={:.2}MP size={}({:.1}MB) hit_by_kind={} miss_px_by_kind={} | \
402             shadow_cache: shape_hit={} shape_miss={} hit_px={:.2}MP miss_px={:.2}MP text_blur_fallback={} | \
403             stages={} admit={} blur={} substrate={} composite={} effect={} shader_px={:.2}MP blur_px={:.2}MP | shape={} shape_fill_px={:.2}MP{} shape_verts={} interiors={} depth_passes={} image={} text={} draws={} | \
404             text_img_cache: hit={} miss={} hit_px={:.2}MP miss_px={:.2}MP raster={:.2}MB | \
405             text_glyph_atlas: hit={} miss={} miss_px={:.2}MP runs_collected={} | \
406             caches: text_pool={} img={}",
407            frame_count,
408            self.encoder_count,
409            self.submit_count,
410            self.pass_count,
411            self.pass_pixels as f64 / 1_000_000.0,
412            self.copy_count,
413            self.copy_pixels as f64 / 1_000_000.0,
414            self.offscreen_acquires,
415            self.offscreen_news,
416            mb,
417            self.offscreen_pool_size,
418            pool_mb,
419            retained_mb,
420            upload_mb,
421            self.upload_writes,
422            self.isolated_layer_renders,
423            isolated_layer_mpx,
424            self.top_isolated_display(),
425            self.layer_cache_hits,
426            self.layer_cache_misses,
427            self.layer_cache_hit_rate(),
428            layer_cache_hit_mpx,
429            layer_cache_miss_mpx,
430            self.layer_cache_size,
431            layer_cache_mb,
432            self.hits_by_kind_display(),
433            self.miss_pixels_by_kind_display(),
434            self.shadow_shape_cache_hits,
435            self.shadow_shape_cache_misses,
436            shadow_cache_hit_mpx,
437            shadow_cache_miss_mpx,
438            self.shadow_text_blur_fallbacks,
439            self.stages,
440            self.backdrop_admissions,
441            self.blur_passes,
442            self.substrates,
443            self.composite_passes,
444            self.effect_applies,
445            self.shader_pixels as f64 / 1_000_000.0,
446            self.blur_pixels as f64 / 1_000_000.0,
447            self.shape_passes,
448            self.shape_fill_pixels as f64 / 1_000_000.0,
449            self.shape_fill_by_class_text(),
450            self.shape_vertices,
451            self.shape_interior_draws,
452            self.depth_passes,
453            self.image_passes,
454            self.text_passes,
455            self.draw_calls,
456            self.text_image_cache_hits,
457            self.text_image_cache_misses,
458            self.text_image_cache_hit_pixels as f64 / 1_000_000.0,
459            self.text_image_cache_miss_pixels as f64 / 1_000_000.0,
460            self.text_image_raster_bytes as f64 / (1024.0 * 1024.0),
461            self.text_glyph_atlas_hits,
462            self.text_glyph_atlas_misses,
463            self.text_glyph_atlas_miss_pixels as f64 / 1_000_000.0,
464            self.text_glyph_runs_collected,
465            self.text_pool_size,
466            self.image_cache_size,
467        );
468        for (index, layer) in self.top_isolated_layers().enumerate() {
469            stats_line!(
470                "  [isolated #{index}] node={:?} rect=({:.1},{:.1},{:.1},{:.1}) target={}x{}",
471                layer.node_id,
472                layer.logical_rect.x,
473                layer.logical_rect.y,
474                layer.logical_rect.width,
475                layer.logical_rect.height,
476                layer.width,
477                layer.height,
478            );
479        }
480    }
481}
482
483pub(crate) fn gpu_stats_enabled() -> bool {
484    cranpose_core::DIAGNOSTICS.gpu_stats.flag()
485}
486
487pub(crate) fn print_gpu_memory_report(device: &wgpu::Device, frame_count: u64) {
488    let Some(report) = device.generate_allocator_report() else {
489        return;
490    };
491
492    const MB: f64 = 1024.0 * 1024.0;
493    let mut blocks = String::new();
494    for block in &report.blocks {
495        if !blocks.is_empty() {
496            blocks.push('+');
497        }
498        blocks.push_str(&format!("{:.1}", block.size as f64 / MB));
499    }
500
501    stats_line!(
502        "[GPU-MEM f#{}] reserved={:.1}MB allocated={:.1}MB blocks={}[{}MB] allocations={} | largest={:.6?}",
503        frame_count,
504        report.total_reserved_bytes as f64 / MB,
505        report.total_allocated_bytes as f64 / MB,
506        report.blocks.len(),
507        blocks,
508        report.allocations.len(),
509        report,
510    );
511}
512
513fn shadow_cache_diagnostics_enabled() -> bool {
514    cranpose_core::DIAGNOSTICS.gpu_shadow_cache_diag.flag()
515}
516
517fn by_kind_display<T: Copy + Default + PartialEq>(
518    by_kind: &[T; LAYER_RASTER_CACHE_KIND_COUNT],
519    format: impl Fn(T) -> String,
520) -> String {
521    LAYER_RASTER_CACHE_KIND_LABELS
522        .iter()
523        .zip(by_kind)
524        .filter(|(_, value)| **value != T::default())
525        .map(|(label, value)| format!("{label}={}", format(*value)))
526        .collect::<Vec<_>>()
527        .join(",")
528}
529
530#[cfg(test)]
531#[path = "tests/gpu_stats_tests.rs"]
532mod tests;