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