use core::fmt;
use core::fmt::Write as _;
use core::time::Duration;
use std::cell::RefCell;
use std::collections::VecDeque;
use glam::Vec2;
use crate::budget::BudgetStats;
use crate::draw_list::DrawList;
use crate::hud::Anchor;
use crate::style::{Declaration, Sides};
use crate::text::{FontAtlas, LINE_HEIGHT};
use crate::tree::{Align, AvailableSpace, Length, LengthAuto, NodeKey, Ui};
use crate::widget::{NATURAL_FONT_SIZE, PointerInput};
mod reflected;
pub use reflected::{REFLECTED_DECIMALS, ReflectedSection};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DebugRow {
pub label: String,
pub value: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DebugGraph {
pub label: String,
pub bars: Vec<f32>,
}
#[derive(Debug, Clone, Default)]
pub struct DebugSection {
title: String,
rows: Vec<DebugRow>,
used: usize,
graphs: Vec<DebugGraph>,
graphs_used: usize,
}
impl DebugSection {
#[must_use]
pub fn new(title: impl AsRef<str>) -> Self {
let mut section = Self::default();
section.set_title(title.as_ref());
section
}
pub fn set_title(&mut self, title: &str) {
self.title.clear();
self.title.push_str(title);
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
pub fn row(&mut self, label: &str, value: fmt::Arguments<'_>) {
if self.used == self.rows.len() {
self.rows.push(DebugRow::default());
}
let row = &mut self.rows[self.used];
row.label.clear();
row.label.push_str(label);
row.value.clear();
let _ = row.value.write_fmt(value);
self.used += 1;
}
pub fn row_str(&mut self, label: &str, value: &str) {
self.row(label, format_args!("{value}"));
}
#[must_use]
pub fn rows(&self) -> &[DebugRow] {
&self.rows[..self.used]
}
pub fn graph(&mut self, label: &str, samples: impl IntoIterator<Item = f32>, scale: f32) {
if self.graphs_used == self.graphs.len() {
self.graphs.push(DebugGraph::default());
}
let graph = &mut self.graphs[self.graphs_used];
graph.label.clear();
graph.label.push_str(label);
graph.bars.clear();
graph.bars.extend(samples.into_iter().map(|sample| {
if scale > 0.0 {
(sample / scale).clamp(0.0, 1.0)
} else {
0.0
}
}));
self.graphs_used += 1;
}
#[must_use]
pub fn graphs(&self) -> &[DebugGraph] {
&self.graphs[..self.graphs_used]
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.used == 0 && self.graphs_used == 0
}
pub fn clear(&mut self) {
self.title.clear();
self.used = 0;
self.graphs_used = 0;
}
}
pub trait DebugModule {
fn debug_section(&self, out: &mut DebugSection);
}
pub const DEFAULT_FRAME_WINDOW: usize = 120;
#[derive(Debug, Clone)]
pub struct FrameStats {
window: usize,
samples: VecDeque<Duration>,
total: Duration,
}
impl Default for FrameStats {
fn default() -> Self {
Self::new()
}
}
impl FrameStats {
#[must_use]
pub fn new() -> Self {
Self::with_window(DEFAULT_FRAME_WINDOW)
}
#[must_use]
pub fn with_window(window: usize) -> Self {
let window = window.max(1);
Self {
window,
samples: VecDeque::with_capacity(window),
total: Duration::ZERO,
}
}
pub fn record(&mut self, dt: Duration) {
if dt.is_zero() {
return;
}
if self.samples.len() == self.window
&& let Some(oldest) = self.samples.pop_front()
{
self.total -= oldest;
}
self.samples.push_back(dt);
self.total += dt;
}
#[must_use]
pub fn len(&self) -> usize {
self.samples.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.samples.is_empty()
}
#[must_use]
pub const fn window(&self) -> usize {
self.window
}
#[must_use]
pub const fn total(&self) -> Duration {
self.total
}
#[must_use]
pub fn mean(&self) -> Duration {
let count = u32::try_from(self.samples.len()).unwrap_or(u32::MAX);
if count == 0 {
Duration::ZERO
} else {
self.total / count
}
}
#[must_use]
pub fn fps(&self) -> f64 {
let seconds = self.total.as_secs_f64();
if self.samples.is_empty() || seconds <= 0.0 {
0.0
} else {
self.samples.len() as f64 / seconds
}
}
#[must_use]
pub fn last(&self) -> Option<Duration> {
self.samples.back().copied()
}
#[must_use]
pub fn best(&self) -> Option<Duration> {
self.samples.iter().min().copied()
}
#[must_use]
pub fn worst(&self) -> Option<Duration> {
self.samples.iter().max().copied()
}
pub fn clear(&mut self) {
self.samples.clear();
self.total = Duration::ZERO;
}
}
fn millis(duration: Duration) -> f64 {
duration.as_secs_f64() * 1_000.0
}
impl DebugModule for FrameStats {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title("frame");
out.row("fps", format_args!("{:.1}", self.fps()));
out.row("avg", format_args!("{:.2} ms", millis(self.mean())));
out.row(
"last",
format_args!("{:.2} ms", millis(self.last().unwrap_or_default())),
);
out.row(
"best",
format_args!("{:.2} ms", millis(self.best().unwrap_or_default())),
);
out.row(
"worst",
format_args!("{:.2} ms", millis(self.worst().unwrap_or_default())),
);
out.row("window", format_args!("{}/{}", self.len(), self.window()));
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DebugStyle {
pub bg: [f32; 4],
pub title: [f32; 4],
pub label: [f32; 4],
pub value: [f32; 4],
pub graph: [f32; 4],
pub font_size: f32,
pub padding: f32,
pub column_gap: f32,
pub section_gap: f32,
}
impl Default for DebugStyle {
fn default() -> Self {
Self {
bg: [0.04, 0.04, 0.07, 0.82],
title: [0.45, 0.85, 1.0, 1.0],
label: [0.72, 0.72, 0.78, 1.0],
value: [1.0, 1.0, 1.0, 1.0],
graph: [0.45, 0.85, 1.0, 0.9],
font_size: NATURAL_FONT_SIZE,
padding: 6.0,
column_gap: 10.0,
section_gap: 6.0,
}
}
}
#[derive(Debug, Clone)]
pub struct DebugPanel {
visible: bool,
pub anchor: Anchor,
pub offset: Vec2,
pub style: DebugStyle,
sections: Vec<DebugSection>,
used: usize,
}
impl Default for DebugPanel {
fn default() -> Self {
Self::new()
}
}
impl DebugPanel {
#[must_use]
pub fn new() -> Self {
Self {
visible: false,
anchor: Anchor::TopRight,
offset: Vec2::splat(8.0),
style: DebugStyle::default(),
sections: Vec::new(),
used: 0,
}
}
#[must_use]
pub const fn is_visible(&self) -> bool {
self.visible
}
pub const fn set_visible(&mut self, visible: bool) {
self.visible = visible;
if !visible {
self.used = 0;
}
}
pub const fn toggle(&mut self) {
self.set_visible(!self.visible);
}
pub const fn begin_frame(&mut self) {
self.used = 0;
}
pub fn add(&mut self, module: &dyn DebugModule) {
if !self.visible {
return;
}
if self.used == self.sections.len() {
self.sections.push(DebugSection::default());
}
let section = &mut self.sections[self.used];
section.clear();
module.debug_section(section);
self.used += 1;
}
#[must_use]
pub fn sections(&self) -> &[DebugSection] {
&self.sections[..self.used]
}
#[must_use]
pub fn size(&self, atlas: &FontAtlas) -> Vec2 {
self.laid_out(atlas, |ui, panel| {
let (min, max) = ui.rect(panel).expect("laid out this frame");
max - min
})
.unwrap_or(Vec2::ZERO)
}
pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
self.laid_out(atlas, |ui, panel| {
let (min, max) = ui.rect(panel).expect("laid out this frame");
let origin = self.anchor.position(screen_size, self.offset, max - min);
ui.layout(origin, AvailableSpace::MAX_CONTENT, atlas);
ui.emit(dl);
});
}
fn laid_out<R>(
&self,
atlas: &FontAtlas,
read: impl FnOnce(&mut Ui, NodeKey) -> R,
) -> Option<R> {
if self.sections().is_empty() {
return None;
}
DEBUG_TREE.with(|tree| {
let mut ui = tree.borrow_mut();
ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
let panel = self.build(&mut ui, atlas);
ui.layout(Vec2::ZERO, AvailableSpace::MAX_CONTENT, atlas);
Some(read(&mut ui, panel))
})
}
fn build(&self, ui: &mut Ui, atlas: &FontAtlas) -> NodeKey {
use Declaration as D;
let style = &self.style;
let scale = style.font_size / NATURAL_FONT_SIZE;
let mut label_width = 0.0f32;
for section in self.sections() {
let rows = section.rows().iter().map(|row| &row.label);
let graphs = section.graphs().iter().map(|graph| &graph.label);
for label in rows.chain(graphs) {
label_width = label_width.max(atlas.text_width(label, scale));
}
}
let panel = [
D::Padding(Sides::All, Length::Px(style.padding)),
D::RowGap(Length::Px(style.section_gap)),
D::Background(style.bg),
D::FontSize(style.font_size),
];
let title = [D::Color(style.title)];
let label = [
D::Color(style.label),
D::MinWidth(LengthAuto::Px(label_width + style.column_gap)),
];
let value = [D::Color(style.value)];
let graph_height = GRAPH_HEIGHT * scale;
let graph = [
D::Height(LengthAuto::Px(graph_height)),
D::AlignItems(Some(Align::FlexEnd)),
];
ui.block("debug-panel", &panel, |ui| {
for (index, section) in self.sections().iter().enumerate() {
ui.block_keyed(index, ".debug-section", &[], |ui| {
ui.span(".debug-title", section.title(), &title);
for (row_index, row) in section.rows().iter().enumerate() {
ui.block_keyed(row_index, ".debug-row", &[], |ui| {
ui.span(".debug-label", row.label.as_str(), &label);
ui.span(".debug-value", row.value.as_str(), &value);
});
}
for (graph_index, plotted) in section.graphs().iter().enumerate() {
let key = (section.rows().len(), graph_index);
ui.block_keyed(key, ".debug-row", &[], |ui| {
ui.span(".debug-label", plotted.label.as_str(), &label);
ui.block(".debug-graph", &graph, |ui| {
for (bar_index, bar) in plotted.bars.iter().enumerate() {
let height = (bar * graph_height).max(MIN_BAR_HEIGHT);
let bar = [
D::Width(LengthAuto::Px(GRAPH_BAR_WIDTH * scale)),
D::Height(LengthAuto::Px(height)),
D::Background(style.graph),
];
ui.block_keyed(bar_index, ".debug-bar", &bar, |_| {});
}
});
});
}
});
}
})
.key
}
}
thread_local! {
static DEBUG_TREE: RefCell<Ui> = RefCell::new(Ui::new());
}
const OFF_SCREEN: Vec2 = Vec2::splat(-1.0);
pub const GRAPH_HEIGHT: f32 = LINE_HEIGHT;
pub const GRAPH_BAR_WIDTH: f32 = 2.0;
pub const MIN_BAR_HEIGHT: f32 = 1.0;
#[derive(Debug, Clone, Default)]
pub struct DebugOverlay {
pub panel: DebugPanel,
pub frame: FrameStats,
pub budget: BudgetStats,
}
impl DebugOverlay {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_visible(visible: bool) -> Self {
let mut overlay = Self::new();
overlay.panel.set_visible(visible);
overlay
}
#[must_use]
pub const fn is_visible(&self) -> bool {
self.panel.is_visible()
}
pub const fn set_visible(&mut self, visible: bool) {
self.panel.set_visible(visible);
}
pub const fn toggle(&mut self) {
self.panel.toggle();
}
pub fn record(&mut self, dt: Duration) {
self.frame.record(dt);
}
pub fn begin_frame(&mut self) {
self.panel.begin_frame();
self.panel.add(&self.frame);
if self.budget.has_samples() {
self.panel.add(&self.budget);
}
}
pub fn add(&mut self, module: &dyn DebugModule) {
self.panel.add(module);
}
pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
self.panel.render(dl, screen_size, atlas);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::draw_list::DrawCommand;
fn ms(millis: u64) -> Duration {
Duration::from_millis(millis)
}
fn screen() -> Vec2 {
Vec2::new(1280.0, 720.0)
}
fn texts(dl: &DrawList) -> Vec<String> {
dl.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { text, .. } => Some(text.clone()),
_ => None,
})
.collect()
}
struct Fake {
title: &'static str,
rows: &'static [(&'static str, &'static str)],
}
impl DebugModule for Fake {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title(self.title);
for (label, value) in self.rows {
out.row_str(label, value);
}
}
}
fn shown() -> DebugPanel {
let mut panel = DebugPanel::new();
panel.set_visible(true);
panel.begin_frame();
panel
}
#[test]
fn fps_is_frames_over_elapsed_not_the_mean_of_instantaneous_rates() {
let mut stats = FrameStats::new();
stats.record(ms(10));
stats.record(ms(30));
assert_eq!(stats.len(), 2);
assert_eq!(stats.total(), ms(40));
assert_eq!(stats.mean(), ms(20));
assert!(
(stats.fps() - 50.0).abs() < 1e-9,
"expected 50 fps, got {}",
stats.fps()
);
assert_eq!(stats.best(), Some(ms(10)));
assert_eq!(stats.worst(), Some(ms(30)));
assert_eq!(stats.last(), Some(ms(30)));
}
#[test]
fn a_steady_sequence_reports_its_own_rate() {
let mut stats = FrameStats::new();
let step = Duration::from_nanos(15_625_000); for _ in 0..16 {
stats.record(step);
}
assert_eq!(stats.mean(), step);
assert!((stats.fps() - 64.0).abs() < 1e-9, "got {}", stats.fps());
assert_eq!(stats.best(), Some(step));
assert_eq!(stats.worst(), Some(step));
}
#[test]
fn the_first_frames_zero_delta_is_not_a_sample_and_fps_is_not_infinite() {
let mut stats = FrameStats::new();
stats.record(Duration::ZERO);
assert!(stats.is_empty(), "a zero-length interval is not a frame");
assert_eq!(stats.fps(), 0.0);
assert!(stats.fps().is_finite());
assert_eq!(stats.mean(), Duration::ZERO);
assert_eq!(stats.last(), None);
let mut section = DebugSection::default();
stats.debug_section(&mut section);
for row in section.rows() {
assert!(
!row.value.contains("inf") && !row.value.contains("NaN"),
"{}: {}",
row.label,
row.value
);
}
}
#[test]
fn a_stall_shows_in_the_worst_frame_and_moves_the_average() {
let mut stats = FrameStats::new();
for _ in 0..60 {
stats.record(ms(16));
}
let smooth = stats.mean();
stats.record(ms(500));
assert_eq!(stats.worst(), Some(ms(500)));
assert_eq!(stats.best(), Some(ms(16)));
assert_eq!(stats.last(), Some(ms(500)));
assert_eq!(stats.total(), ms(1460));
assert_eq!(stats.mean(), ms(1460) / 61);
assert!(
stats.mean() > smooth,
"the stall must move the average: {smooth:?} → {:?}",
stats.mean()
);
assert!(
(stats.fps() - 61.0 / 1.46).abs() < 1e-9,
"got {}",
stats.fps()
);
}
#[test]
fn the_window_evicts_and_the_running_total_matches_the_samples() {
let mut stats = FrameStats::with_window(4);
stats.record(ms(500));
for _ in 0..4 {
stats.record(ms(10));
}
assert_eq!(stats.len(), 4, "the window holds four");
assert_eq!(stats.total(), ms(40), "the stall has scrolled off");
assert_eq!(stats.worst(), Some(ms(10)));
assert!((stats.fps() - 100.0).abs() < 1e-9, "got {}", stats.fps());
}
#[test]
fn a_zero_window_is_clamped_to_one_frame() {
let mut stats = FrameStats::with_window(0);
assert_eq!(stats.window(), 1);
stats.record(ms(10));
stats.record(ms(20));
assert_eq!(stats.len(), 1);
assert_eq!(stats.total(), ms(20));
}
#[test]
fn a_panel_with_only_the_frame_module_draws_the_frame_numbers() {
let atlas = FontAtlas::built_in();
let mut overlay = DebugOverlay::with_visible(true);
overlay.record(ms(20));
overlay.record(ms(20));
overlay.begin_frame();
let mut dl = DrawList::new();
overlay.render(&mut dl, screen(), &atlas);
let drawn = texts(&dl);
assert_eq!(
drawn.first().map(String::as_str),
Some("frame"),
"the section heading: {drawn:?}"
);
assert!(drawn.iter().any(|t| t == "fps"), "{drawn:?}");
assert!(
drawn.iter().any(|t| t == "50.0"),
"two 20 ms frames is 50 fps: {drawn:?}"
);
assert!(
drawn.iter().any(|t| t == "20.00 ms"),
"the mean must be drawn: {drawn:?}"
);
assert!(
dl.commands()
.iter()
.any(|c| matches!(c, DrawCommand::Rect { .. })),
"the panel draws its own background"
);
assert_eq!(overlay.panel.sections().len(), 1, "no network module");
}
#[test]
fn the_budget_section_appears_once_it_has_a_sample_and_carries_its_numbers() {
use crate::budget::MIN_PERCENTILE_SAMPLES;
let atlas = FontAtlas::built_in();
let mut overlay = DebugOverlay::with_visible(true);
overlay.record(ms(16));
overlay.begin_frame();
assert_eq!(
overlay
.panel
.sections()
.iter()
.map(DebugSection::title)
.collect::<Vec<_>>(),
["frame"],
"a run with no trace and no GPU timers has no budget to report"
);
for frame in 0..MIN_PERCENTILE_SAMPLES as u64 {
overlay.budget.record_cpu(ms(4));
overlay.budget.record_gpu(frame, ms(11));
}
overlay.begin_frame();
let mut dl = DrawList::new();
overlay.render(&mut dl, screen(), &atlas);
let drawn = texts(&dl);
let start = drawn
.iter()
.position(|text| text == "budget")
.unwrap_or_else(|| panic!("no budget section: {drawn:?}"));
assert_eq!(
&drawn[start..],
[
"budget",
"cpu p50/p95",
"4.00 / 4.00 ms",
"gpu elapsed p50/p95",
"11.00 / 11.00 ms",
"bound",
"gpu",
"gpu frame",
"19",
],
);
}
#[test]
fn two_modules_render_both_sections_in_the_order_added() {
let atlas = FontAtlas::built_in();
let first = Fake {
title: "alpha",
rows: &[("a1", "one"), ("a2", "two")],
};
let second = Fake {
title: "beta",
rows: &[("b1", "three")],
};
let mut panel = shown();
panel.add(&first);
panel.add(&second);
assert_eq!(
panel
.sections()
.iter()
.map(DebugSection::title)
.collect::<Vec<_>>(),
["alpha", "beta"],
);
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
assert_eq!(
texts(&dl),
["alpha", "a1", "one", "a2", "two", "beta", "b1", "three"],
"titles and rows, in order",
);
let mut swapped = shown();
swapped.add(&second);
swapped.add(&first);
let mut other = DrawList::new();
swapped.render(&mut other, screen(), &atlas);
assert_eq!(
texts(&other),
["beta", "b1", "three", "alpha", "a1", "one", "a2", "two"],
);
}
#[test]
fn a_frame_with_fewer_modules_does_not_render_the_previous_frames() {
let atlas = FontAtlas::built_in();
let first = Fake {
title: "alpha",
rows: &[("a1", "one")],
};
let second = Fake {
title: "beta",
rows: &[("b1", "two")],
};
let mut panel = shown();
panel.add(&first);
panel.add(&second);
assert_eq!(panel.sections().len(), 2);
panel.begin_frame();
panel.add(&first);
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
let drawn = texts(&dl);
assert_eq!(panel.sections().len(), 1);
assert!(
!drawn.iter().any(|t| t == "beta"),
"the dropped module is gone: {drawn:?}"
);
}
#[test]
fn a_panel_with_no_sections_at_all_draws_nothing() {
let atlas = FontAtlas::built_in();
let panel = shown();
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
assert!(dl.is_empty(), "{:?}", dl.commands());
assert_eq!(panel.size(&atlas), Vec2::ZERO);
}
#[test]
fn toggling_the_panel_changes_the_draw_list() {
let atlas = FontAtlas::built_in();
let module = Fake {
title: "alpha",
rows: &[("a1", "one")],
};
let mut panel = DebugPanel::new();
let draw = |panel: &mut DebugPanel| {
panel.begin_frame();
panel.add(&module);
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
dl
};
let off = draw(&mut panel);
assert!(off.is_empty(), "hidden: {:?}", off.commands());
assert!(panel.sections().is_empty(), "hidden panels gather nothing");
panel.toggle();
let on = draw(&mut panel);
assert!(texts(&on).iter().any(|t| t == "alpha"), "{:?}", texts(&on));
panel.toggle();
let off_again = draw(&mut panel);
assert!(off_again.is_empty(), "{:?}", off_again.commands());
}
#[test]
fn hiding_forgets_the_sections_it_had() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Fake {
title: "alpha",
rows: &[("a1", "one")],
});
assert_eq!(panel.sections().len(), 1);
panel.set_visible(false);
panel.set_visible(true);
assert!(panel.sections().is_empty());
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
assert!(dl.is_empty(), "{:?}", dl.commands());
}
#[test]
fn the_panel_follows_the_screen_across_a_resize() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Fake {
title: "alpha",
rows: &[("a1", "one")],
});
let size = panel.size(&atlas);
let bounds = |screen: Vec2| {
let mut dl = DrawList::new();
panel.render(&mut dl, screen, &atlas);
match dl.commands().first() {
Some(DrawCommand::Rect { min, max, .. }) => (*min, *max),
other => panic!("expected the panel background, got {other:?}"),
}
};
for screen in [Vec2::new(1280.0, 720.0), Vec2::new(640.0, 360.0)] {
let (min, max) = bounds(screen);
assert_eq!(max - min, size, "the panel is the same size either way");
assert_eq!(
max,
Vec2::new(screen.x - panel.offset.x, min.y + size.y),
"the right edge stays {}px in from the right of {screen:?}",
panel.offset.x,
);
assert!(
min.x >= 0.0 && max.x <= screen.x,
"off-screen: {min:?}..{max:?}"
);
}
assert_ne!(
bounds(Vec2::new(1280.0, 720.0)).0,
bounds(Vec2::new(640.0, 360.0)).0
);
}
#[test]
fn a_resize_does_not_reset_the_frame_window() {
let mut overlay = DebugOverlay::with_visible(true);
for _ in 0..10 {
overlay.record(ms(16));
}
overlay.record(ms(120)); assert_eq!(overlay.frame.len(), 11);
assert_eq!(overlay.frame.worst(), Some(ms(120)));
assert_eq!(overlay.frame.best(), Some(ms(16)));
}
#[test]
fn the_value_column_starts_past_the_longest_label() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Fake {
title: "x",
rows: &[("short", "1"), ("a-much-longer-label", "2")],
});
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
let scale = panel.style.font_size / NATURAL_FONT_SIZE;
let widest = atlas.text_width("a-much-longer-label", scale);
let mut label_x = None;
let mut checked = 0;
for command in dl.commands() {
if let DrawCommand::Text { pos, text, .. } = command {
match text.as_str() {
"short" | "a-much-longer-label" => label_x = Some(pos.x),
"1" | "2" => {
let start = label_x.expect("a label precedes its value");
assert!(
pos.x >= start + widest,
"value at {} overlaps a {widest}px label at {start}",
pos.x,
);
checked += 1;
}
_ => {}
}
}
}
assert_eq!(
checked,
2,
"both rows' values must have been placed and checked, in {:?}",
dl.commands()
);
}
#[test]
fn a_section_reuses_its_row_allocations() {
let mut section = DebugSection::new("frame");
section.row("fps", format_args!("{:.1}", 59.94));
section.row("avg", format_args!("{:.2} ms", 16.68));
assert_eq!(section.rows().len(), 2);
assert_eq!(section.rows()[0].value, "59.9");
assert_eq!(section.rows.len(), 2, "two row slots exist");
section.clear();
assert!(section.is_empty(), "no live rows");
assert_eq!(section.title(), "");
assert_eq!(
section.rows.len(),
2,
"clear keeps the slots — that is the whole point of it",
);
section.row("fps", format_args!("{:.1}", 30.0));
assert_eq!(section.rows().len(), 1, "one live row");
assert_eq!(section.rows()[0].value, "30.0");
assert_eq!(section.rows.len(), 2, "and the second slot is still there");
}
fn arithmetic_render(
panel: &DebugPanel,
dl: &mut DrawList,
screen_size: Vec2,
atlas: &FontAtlas,
) {
use crate::text::LINE_HEIGHT;
let sections = panel.sections();
if sections.is_empty() {
return;
}
let style = &panel.style;
let scale = style.font_size / NATURAL_FONT_SIZE;
let line_height = LINE_HEIGHT * scale;
let mut label_width = 0.0f32;
let mut value_width = 0.0f32;
let mut title_width = 0.0f32;
let mut lines = 0.0f32;
for section in sections {
title_width = title_width.max(atlas.text_width(section.title(), scale));
lines += 1.0;
for row in section.rows() {
label_width = label_width.max(atlas.text_width(&row.label, scale));
value_width = value_width.max(atlas.text_width(&row.value, scale));
lines += 1.0;
}
}
let value_column = label_width + style.column_gap;
let content_width = title_width.max(value_column + value_width);
let gaps = (sections.len() - 1) as f32 * style.section_gap;
let content_height = lines * line_height + gaps;
let size = Vec2::new(content_width, content_height) + Vec2::splat(style.padding * 2.0);
let origin = panel.anchor.position(screen_size, panel.offset, size);
dl.rect(origin, origin + size, style.bg);
let mut cursor = origin + Vec2::splat(style.padding);
for section in sections {
dl.text(cursor, section.title(), style.title, style.font_size);
cursor.y += line_height;
for row in section.rows() {
dl.text(cursor, row.label.as_str(), style.label, style.font_size);
dl.text(
Vec2::new(cursor.x + value_column, cursor.y),
row.value.as_str(),
style.value,
style.font_size,
);
cursor.y += line_height;
}
cursor.y += style.section_gap;
}
}
fn rendering(dl: &DrawList) -> Vec<String> {
dl.commands()
.iter()
.zip(dl.clips())
.map(|(command, clip)| format!("{command:?} under {clip:?}"))
.collect()
}
#[test]
fn the_tree_draws_the_panel_exactly_where_the_arithmetic_did() {
let atlas = FontAtlas::built_in();
let modules = [
Fake {
title: "frame",
rows: &[("fps", "59.9"), ("avg", "16.68 ms"), ("window", "120/120")],
},
Fake {
title: "budget",
rows: &[("cpu p50/p95", "4.00 / 4.00 ms"), ("bound", "gpu")],
},
Fake {
title: "a-much-longer-section-title",
rows: &[("", ""), ("x", "1")],
},
];
for anchor in [
Anchor::TopLeft,
Anchor::TopRight,
Anchor::BottomLeft,
Anchor::BottomRight,
Anchor::Center,
] {
for count in 1..=modules.len() {
let mut panel = shown();
panel.anchor = anchor;
for module in &modules[..count] {
panel.add(module);
}
for screen in [
Vec2::new(960.0, 720.0),
Vec2::new(800.0, 600.0),
Vec2::new(1920.0, 1080.0),
Vec2::new(1440.0, 400.0),
Vec2::new(600.0, 900.0),
] {
let mut tree = DrawList::new();
panel.render(&mut tree, screen, &atlas);
let mut arithmetic = DrawList::new();
arithmetic_render(&panel, &mut arithmetic, screen, &atlas);
assert_eq!(
rendering(&tree),
rendering(&arithmetic),
"{anchor:?}, {count} sections, {screen:?}",
);
assert!(
!tree.is_empty(),
"the panel drew nothing, so this proves nothing",
);
}
}
}
}
#[test]
fn the_trees_panel_is_the_size_the_arithmetic_measured() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Fake {
title: "frame",
rows: &[("fps", "59.9"), ("a-much-longer-label", "16.68 ms")],
});
panel.add(&Fake {
title: "budget",
rows: &[("bound", "gpu")],
});
let mut arithmetic = DrawList::new();
arithmetic_render(&panel, &mut arithmetic, Vec2::ZERO, &atlas);
let measured = match arithmetic.commands().first() {
Some(DrawCommand::Rect { min, max, .. }) => *max - *min,
other => panic!("expected the panel background, got {other:?}"),
};
assert_eq!(panel.size(&atlas), measured);
assert_ne!(measured, Vec2::ZERO, "a zero panel proves nothing");
}
struct Plot {
samples: &'static [f32],
scale: f32,
}
impl DebugModule for Plot {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title("net");
out.row_str("rtt", "12.0 ms");
out.graph("rtt graph", self.samples.iter().copied(), self.scale);
}
}
fn bars(dl: &DrawList, colour: [f32; 4]) -> Vec<(Vec2, Vec2)> {
dl.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Rect { min, max, color } if *color == colour => Some((*min, *max)),
_ => None,
})
.collect()
}
#[test]
fn a_graph_draws_a_bar_per_sample_scaled_to_its_height() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Plot {
samples: &[0.0, 5.0, 10.0, 40.0],
scale: 20.0,
});
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
let drawn = bars(&dl, panel.style.graph);
let heights: Vec<f32> = drawn.iter().map(|(min, max)| max.y - min.y).collect();
assert_eq!(
heights,
[
MIN_BAR_HEIGHT,
GRAPH_HEIGHT / 4.0,
GRAPH_HEIGHT / 2.0,
GRAPH_HEIGHT
],
"0 is the baseline tick, 5 and 10 of 20 a quarter and a half, 40 clamped full",
);
for (min, max) in &drawn {
assert_eq!(max.x - min.x, GRAPH_BAR_WIDTH);
assert_eq!(max.y, drawn[0].1.y, "every bar stands on one baseline");
}
for pair in drawn.windows(2) {
assert_eq!(pair[1].0.x, pair[0].1.x, "oldest first, side by side");
}
assert!(
texts(&dl).iter().any(|text| text == "rtt graph"),
"the graph's label is drawn: {:?}",
texts(&dl)
);
}
#[test]
fn a_graph_with_no_scale_draws_its_bars_empty() {
let mut section = DebugSection::new("net");
section.graph("rtt graph", [3.0, f32::MAX], 0.0);
assert_eq!(section.graphs()[0].bars, [0.0, 0.0]);
}
#[test]
fn a_graph_label_counts_toward_the_value_column() {
let atlas = FontAtlas::built_in();
let mut panel = shown();
panel.add(&Plot {
samples: &[1.0],
scale: 1.0,
});
let mut dl = DrawList::new();
panel.render(&mut dl, screen(), &atlas);
let scale = panel.style.font_size / NATURAL_FONT_SIZE;
let widest = atlas.text_width("rtt graph", scale);
let label_x = dl
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Text { pos, text, .. } if text == "rtt" => Some(pos.x),
_ => None,
})
.expect("the row's label is drawn");
let value_x = dl
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Text { pos, text, .. } if text == "12.0 ms" => Some(pos.x),
_ => None,
})
.expect("the row's value is drawn");
assert!(
value_x >= label_x + widest,
"the value at {value_x} sits under the {widest}px graph label at {label_x}",
);
let (bar_min, _) = bars(&dl, panel.style.graph)[0];
assert_eq!(bar_min.x, value_x, "the bars start in the value column");
}
#[test]
fn clearing_a_section_drops_its_graphs() {
let mut section = DebugSection::new("net");
section.graph("a", [1.0], 1.0);
assert!(!section.is_empty(), "a graph alone is something to draw");
section.clear();
assert!(section.graphs().is_empty());
assert!(section.is_empty());
section.graph("b", [0.5, 0.25], 1.0);
assert_eq!(
section.graphs(),
[DebugGraph {
label: "b".to_owned(),
bars: vec![0.5, 0.25],
}]
);
}
#[test]
fn the_overlay_starts_hidden_unless_asked() {
assert!(!DebugOverlay::new().is_visible());
assert!(DebugOverlay::with_visible(true).is_visible());
let mut overlay = DebugOverlay::with_visible(true);
overlay.toggle();
assert!(!overlay.is_visible());
overlay.set_visible(true);
assert!(overlay.is_visible());
}
#[test]
fn debug_format_covers_the_public_types() {
let overlay = DebugOverlay::with_visible(true);
let text = format!("{overlay:?}");
assert!(text.contains("panel"), "{text}");
assert!(text.contains("visible"), "{text}");
assert_eq!(
format!("{:?}", DebugRow::default()),
"DebugRow { label: \"\", value: \"\" }"
);
}
}