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
9macro_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#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct IsolatedLayerStat {
28 pub node_id: Option<NodeId>,
30 pub logical_rect: Rect,
32 pub width: u32,
34 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#[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 #[default]
71 Untracked,
72 Skipped,
75 Full,
78 Part(WindowRects),
80}
81
82#[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 pub fn rects(&self) -> &[[u32; 4]] {
93 &self.rects[..self.len]
94 }
95
96 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
124pub struct FrameStatsSnapshot {
125 pub submits: u32,
127 pub encoder_count: u32,
129 pub submit_count: u32,
131 pub pass_count: u32,
133 pub pass_pixels: u64,
136 pub copy_count: u32,
138 pub copy_pixels: u64,
140 pub offscreen_acquires: u32,
142 pub offscreen_news: u32,
144 pub offscreen_total_bytes: u64,
146 pub transient_texture_bytes: u64,
148 pub retained_texture_bytes: u64,
150 pub upload_bytes: u64,
152 pub upload_writes: u32,
155 pub isolated_layer_renders: u32,
157 pub isolated_layer_pixels: u64,
159 pub layer_cache_hits: u32,
161 pub capture_fixup_passes: u32,
163 pub layer_cache_misses: u32,
165 pub layer_cache_hit_pixels: u64,
167 pub layer_cache_miss_pixels: u64,
169 pub layer_cache_hits_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
171 pub layer_cache_misses_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
173 pub layer_cache_miss_pixels_by_kind: [u64; LAYER_RASTER_CACHE_KIND_COUNT],
175 pub shadow_shape_cache_hits: u32,
177 pub shadow_shape_cache_misses: u32,
179 pub shadow_shape_cache_hit_pixels: u64,
181 pub shadow_shape_cache_miss_pixels: u64,
183 pub shadow_text_blur_fallbacks: u32,
186 pub blur_passes: u32,
188 pub stages: u32,
191 pub backdrop_admissions: u32,
194 pub prefix_admissions: u32,
196 pub substrates: u32,
199 pub composite_passes: u32,
203 pub effect_applies: u32,
206 pub shader_pixels: u64,
209 pub blur_pixels: u64,
213 pub shape_fill_pixels: u64,
217 pub shape_fill_pixels_by_class: [u64; ShapeFill::CLASSES],
220 pub shape_vertices: u64,
224 pub shape_passes: u32,
226 pub shape_pipeline_fallback_draws: u32,
229 pub instant_draws: u32,
232 pub shape_specialized_draws: u32,
234 pub shape_interior_draws: u32,
236 pub depth_passes: u32,
238 pub pipelines_created: u64,
242 pub shader_pipeline_fallback_draws: u32,
245 pub shader_specialized_draws: u32,
247 pub placeholder_draws: u32,
250 pub image_passes: u32,
252 pub text_passes: u32,
254 pub draw_calls: u32,
261 pub damage: FrameDamage,
264 pub repainted_pixels: u64,
267 pub text_image_cache_hits: u32,
269 pub text_image_cache_misses: u32,
271 pub text_image_cache_hit_pixels: u64,
273 pub text_image_cache_miss_pixels: u64,
275 pub text_image_raster_bytes: u64,
277 pub text_glyph_atlas_hits: u32,
279 pub text_glyph_atlas_misses: u32,
281 pub text_glyph_atlas_miss_pixels: u64,
283 pub text_glyph_runs_collected: u32,
286 pub offscreen_pool_size: u32,
288 pub offscreen_pool_bytes: u64,
290 pub text_pool_size: u32,
292 pub layer_cache_size: u32,
294 pub layer_cache_bytes: u64,
296 pub image_cache_size: u32,
298 pub top_isolated_layers: [Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT],
301 pub top_isolated_layer_count: usize,
303}
304
305impl FrameStatsSnapshot {
306 fn shape_fill_by_class_text(&self) -> String {
307 let mut text = String::new();
308 for (label, pixels) in ShapeFill::LABELS
309 .iter()
310 .zip(self.shape_fill_pixels_by_class)
311 {
312 if pixels > 0 {
313 use std::fmt::Write;
314 let _ = write!(text, " {label}={:.2}MP", pixels as f64 / 1_000_000.0);
315 }
316 }
317 text
318 }
319
320 pub(crate) fn with_command_stats_added(mut self, stats: FrameCommandStats) -> Self {
321 self.submits = self.submits.saturating_add(stats.submit_count);
322 self.encoder_count = self.encoder_count.saturating_add(stats.encoder_count);
323 self.submit_count = self.submit_count.saturating_add(stats.submit_count);
324 self.pass_count = self.pass_count.saturating_add(stats.pass_count);
325 self.pass_pixels = self.pass_pixels.saturating_add(stats.pass_pixels);
326 self.copy_count = self.copy_count.saturating_add(stats.copy_count);
327 self.copy_pixels = self.copy_pixels.saturating_add(stats.copy_pixels);
328 self.transient_texture_bytes = self
329 .transient_texture_bytes
330 .saturating_add(stats.transient_texture_bytes);
331 self.retained_texture_bytes = self
332 .retained_texture_bytes
333 .max(stats.retained_texture_bytes);
334 self.upload_bytes = self.upload_bytes.saturating_add(stats.upload_bytes);
335 self.upload_writes = self.upload_writes.saturating_add(stats.upload_writes);
336 self.offscreen_acquires = self
337 .offscreen_acquires
338 .saturating_add(stats.transient_acquires);
339 self.offscreen_news = self.offscreen_news.saturating_add(stats.transient_news);
340 self
341 }
342
343 fn top_isolated_display(&self) -> String {
346 match &self.top_isolated_layers[0] {
347 Some(top) => format!(
348 "{}x{}@({:.0},{:.0})",
349 top.width, top.height, top.logical_rect.x, top.logical_rect.y
350 ),
351 None => "-".to_string(),
352 }
353 }
354
355 pub fn top_isolated_layers(self) -> impl Iterator<Item = IsolatedLayerStat> {
357 self.top_isolated_layers
358 .into_iter()
359 .flatten()
360 .take(self.top_isolated_layer_count)
361 }
362
363 fn layer_cache_hit_rate(self) -> f64 {
364 let total = self.layer_cache_hits + self.layer_cache_misses;
365 if total > 0 {
366 (self.layer_cache_hits as f64 / total as f64) * 100.0
367 } else {
368 0.0
369 }
370 }
371
372 fn miss_pixels_by_kind_display(&self) -> String {
373 by_kind_display(&self.layer_cache_miss_pixels_by_kind, |pixels| {
374 format!("{:.2}MP", pixels as f64 / 1_000_000.0)
375 })
376 }
377
378 fn hits_by_kind_display(&self) -> String {
379 by_kind_display(&self.layer_cache_hits_by_kind, |hits| hits.to_string())
380 }
381
382 fn print(self, frame_count: u64) {
383 let mb = self.offscreen_total_bytes as f64 / (1024.0 * 1024.0);
384 let upload_mb = self.upload_bytes as f64 / (1024.0 * 1024.0);
385 let retained_mb = self.retained_texture_bytes as f64 / (1024.0 * 1024.0);
386 let pool_mb = self.offscreen_pool_bytes as f64 / (1024.0 * 1024.0);
387 let layer_cache_hit_mpx = self.layer_cache_hit_pixels as f64 / 1_000_000.0;
388 let layer_cache_miss_mpx = self.layer_cache_miss_pixels as f64 / 1_000_000.0;
389 let shadow_cache_hit_mpx = self.shadow_shape_cache_hit_pixels as f64 / 1_000_000.0;
390 let shadow_cache_miss_mpx = self.shadow_shape_cache_miss_pixels as f64 / 1_000_000.0;
391 let layer_cache_mb = self.layer_cache_bytes as f64 / (1024.0 * 1024.0);
392 let isolated_layer_mpx = self.isolated_layer_pixels as f64 / 1_000_000.0;
393 stats_line!(
394 "[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 | \
395 uploads={:.2}MB writes={} | \
396 isolated_layers={} area={:.2}MP top={} | \
397 layer_cache: hit={} miss={} {:.1}% hit_px={:.2}MP miss_px={:.2}MP size={}({:.1}MB) hit_by_kind={} miss_px_by_kind={} | \
398 shadow_cache: shape_hit={} shape_miss={} hit_px={:.2}MP miss_px={:.2}MP text_blur_fallback={} | \
399 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={} | \
400 text_img_cache: hit={} miss={} hit_px={:.2}MP miss_px={:.2}MP raster={:.2}MB | \
401 text_glyph_atlas: hit={} miss={} miss_px={:.2}MP runs_collected={} | \
402 caches: text_pool={} img={}",
403 frame_count,
404 self.encoder_count,
405 self.submit_count,
406 self.pass_count,
407 self.pass_pixels as f64 / 1_000_000.0,
408 self.copy_count,
409 self.copy_pixels as f64 / 1_000_000.0,
410 self.offscreen_acquires,
411 self.offscreen_news,
412 mb,
413 self.offscreen_pool_size,
414 pool_mb,
415 retained_mb,
416 upload_mb,
417 self.upload_writes,
418 self.isolated_layer_renders,
419 isolated_layer_mpx,
420 self.top_isolated_display(),
421 self.layer_cache_hits,
422 self.layer_cache_misses,
423 self.layer_cache_hit_rate(),
424 layer_cache_hit_mpx,
425 layer_cache_miss_mpx,
426 self.layer_cache_size,
427 layer_cache_mb,
428 self.hits_by_kind_display(),
429 self.miss_pixels_by_kind_display(),
430 self.shadow_shape_cache_hits,
431 self.shadow_shape_cache_misses,
432 shadow_cache_hit_mpx,
433 shadow_cache_miss_mpx,
434 self.shadow_text_blur_fallbacks,
435 self.stages,
436 self.backdrop_admissions,
437 self.blur_passes,
438 self.substrates,
439 self.composite_passes,
440 self.effect_applies,
441 self.shader_pixels as f64 / 1_000_000.0,
442 self.blur_pixels as f64 / 1_000_000.0,
443 self.shape_passes,
444 self.shape_fill_pixels as f64 / 1_000_000.0,
445 self.shape_fill_by_class_text(),
446 self.shape_vertices,
447 self.shape_interior_draws,
448 self.depth_passes,
449 self.image_passes,
450 self.text_passes,
451 self.draw_calls,
452 self.text_image_cache_hits,
453 self.text_image_cache_misses,
454 self.text_image_cache_hit_pixels as f64 / 1_000_000.0,
455 self.text_image_cache_miss_pixels as f64 / 1_000_000.0,
456 self.text_image_raster_bytes as f64 / (1024.0 * 1024.0),
457 self.text_glyph_atlas_hits,
458 self.text_glyph_atlas_misses,
459 self.text_glyph_atlas_miss_pixels as f64 / 1_000_000.0,
460 self.text_glyph_runs_collected,
461 self.text_pool_size,
462 self.image_cache_size,
463 );
464 for (index, layer) in self.top_isolated_layers().enumerate() {
465 stats_line!(
466 " [isolated #{index}] node={:?} rect=({:.1},{:.1},{:.1},{:.1}) target={}x{}",
467 layer.node_id,
468 layer.logical_rect.x,
469 layer.logical_rect.y,
470 layer.logical_rect.width,
471 layer.logical_rect.height,
472 layer.width,
473 layer.height,
474 );
475 }
476 }
477}
478
479pub(crate) fn gpu_stats_enabled() -> bool {
480 cranpose_core::DIAGNOSTICS.gpu_stats.flag()
481}
482
483pub(crate) fn print_gpu_memory_report(device: &wgpu::Device, frame_count: u64) {
484 let Some(report) = device.generate_allocator_report() else {
485 return;
486 };
487
488 const MB: f64 = 1024.0 * 1024.0;
489 let mut blocks = String::new();
490 for block in &report.blocks {
491 if !blocks.is_empty() {
492 blocks.push('+');
493 }
494 blocks.push_str(&format!("{:.1}", block.size as f64 / MB));
495 }
496
497 stats_line!(
498 "[GPU-MEM f#{}] reserved={:.1}MB allocated={:.1}MB blocks={}[{}MB] allocations={} | largest={:.6?}",
499 frame_count,
500 report.total_reserved_bytes as f64 / MB,
501 report.total_allocated_bytes as f64 / MB,
502 report.blocks.len(),
503 blocks,
504 report.allocations.len(),
505 report,
506 );
507}
508
509fn shadow_cache_diagnostics_enabled() -> bool {
510 cranpose_core::DIAGNOSTICS.gpu_shadow_cache_diag.flag()
511}
512
513fn by_kind_display<T: Copy + Default + PartialEq>(
514 by_kind: &[T; LAYER_RASTER_CACHE_KIND_COUNT],
515 format: impl Fn(T) -> String,
516) -> String {
517 LAYER_RASTER_CACHE_KIND_LABELS
518 .iter()
519 .zip(by_kind)
520 .filter(|(_, value)| **value != T::default())
521 .map(|(label, value)| format!("{label}={}", format(*value)))
522 .collect::<Vec<_>>()
523 .join(",")
524}
525
526#[cfg(test)]
527#[path = "tests/gpu_stats_tests.rs"]
528mod tests;