Skip to main content

crcbl_ui/
debug.rs

1//! The modular debug overlay: one panel, assembled from sections that the
2//! systems being reported on contribute.
3//!
4//! `docs/plan/ROADMAP.md`'s standing requirement 1 and
5//! `docs/plan/sample/00-samples-overview.md` rule 4 both say the same thing:
6//! **one** panel that every sample switches on, where frame timing and FPS are
7//! always present and every other module appears because the system it reports
8//! on is present, not because the sample asked for it. That is what this module
9//! is, and the debug-item table in `docs/notes/tooling.md` (_What the deleted
10//! 07-ui-debug plan left behind_) lists the modules that land on top of it.
11//!
12//! # The panel does not know what a system is
13//!
14//! [`DebugPanel`] holds [`DebugSection`]s, and a section is a title, a list of
15//! `label: value` rows, and any rolling graphs under them ([`DebugGraph`], a
16//! bar per sample — a network link's round trip, say). Nothing here names a
17//! renderer, a network client or a clock. A system contributes by
18//! implementing [`DebugModule`] — one method, which fills a section it is
19//! handed — and the frame that wants the panel calls [`DebugPanel::add`] once
20//! per system it actually has:
21//!
22//! ```text
23//! overlay.record(frame_clock.render_dt());   // always, even while hidden
24//! overlay.begin_frame();                     // clears, adds the frame section
25//! if let Some(timings) = gpu.timings() { overlay.add(timings); }
26//! overlay.render(&mut draw_list, screen, &atlas);
27//! ```
28//!
29//! A sample with no connection never calls `add` with a network module and gets
30//! a panel without one. That is the whole of the modularity claim, and breakout
31//! and flappy — both `InMemoryTransport` — are the check on it: a panel that
32//! could not render without a network module would be broken, and only a
33//! connectionless sample proves it can.
34//!
35//! # It does nothing while it is off
36//!
37//! [`DebugPanel::add`] returns immediately when the panel is hidden, and
38//! [`DebugPanel::render`] emits no commands, so a system's `debug_section` is
39//! never called and no string is ever built. The only work a hidden overlay does
40//! is [`FrameStats::record`], which is a push and two `Duration` adds — the
41//! window has to stay warm or toggling the panel on would show two seconds of
42//! nothing.
43//!
44//! Visible, the cost is one [`DrawList`] text command per row plus one
45//! background rect, and a rect per graph bar. Section and row strings are
46//! reused across frames; the draw commands are not, because
47//! [`DrawList::text`] takes an owned `String`.
48//!
49//! # The panel is built on the element tree
50//!
51//! [`DebugPanel::size`] and [`DebugPanel::render`] build the same
52//! [`crate::tree`] — a `debug-panel` column, a `.debug-section` per module, a
53//! `.debug-row` per row and a span for each title, label and value — lay it out
54//! on Taffy and read its extent back or emit it. The structure is styled by the
55//! engine's `default.css`; what [`DebugStyle`] holds — the colours, the font
56//! size, the padding and the two gaps — is each panel's own and goes on the
57//! nodes as inline declarations, which is the split [`crate::readout`] already
58//! takes.
59//!
60//! **The value column is measured, not laid out.** Every value in the panel
61//! starts at one column, across sections as well as rows, and flexbox aligns
62//! nothing across two containers — that is a grid. So the widest label is
63//! measured in `atlas` and becomes the labels' `min-width`, which is the
64//! arithmetic the panel did before, moved onto a node.
65
66use core::fmt;
67use core::fmt::Write as _;
68use core::time::Duration;
69use std::cell::RefCell;
70use std::collections::VecDeque;
71
72use glam::Vec2;
73
74use crate::budget::BudgetStats;
75use crate::draw_list::DrawList;
76use crate::hud::Anchor;
77use crate::style::{Declaration, Sides};
78use crate::text::{FontAtlas, LINE_HEIGHT};
79use crate::tree::{Align, AvailableSpace, Length, LengthAuto, NodeKey, Ui};
80use crate::widget::{NATURAL_FONT_SIZE, PointerInput};
81
82mod reflected;
83
84pub use reflected::{REFLECTED_DECIMALS, ReflectedSection};
85
86// ---------------------------------------------------------------------------
87// Sections
88// ---------------------------------------------------------------------------
89
90/// One `label: value` line in a [`DebugSection`].
91#[derive(Debug, Clone, Default, PartialEq, Eq)]
92pub struct DebugRow {
93    /// What the number is.
94    pub label: String,
95    /// The number, already formatted — the panel does no formatting of its own.
96    pub value: String,
97}
98
99/// One rolling graph in a [`DebugSection`]: what it plots, and a bar per
100/// sample, oldest first.
101#[derive(Debug, Clone, Default, PartialEq)]
102pub struct DebugGraph {
103    /// What the bars are.
104    pub label: String,
105    /// Each sample's height as a fraction of the graph's, 0 to 1.
106    pub bars: Vec<f32>,
107}
108
109/// One system's contribution to the panel: a title, its rows, and any graphs
110/// under them.
111///
112/// Rows and graphs are kept in `Vec`s that are reused rather than
113/// reallocated: [`DebugSection::clear`] resets the lengths without dropping
114/// the strings, so a module that writes the same rows every frame allocates
115/// on the first frame only.
116#[derive(Debug, Clone, Default)]
117pub struct DebugSection {
118    title: String,
119    rows: Vec<DebugRow>,
120    /// How many of `rows` are live. The rest are retained allocations.
121    used: usize,
122    graphs: Vec<DebugGraph>,
123    /// How many of `graphs` are live.
124    graphs_used: usize,
125}
126
127impl DebugSection {
128    /// An empty section with the given title.
129    #[must_use]
130    pub fn new(title: impl AsRef<str>) -> Self {
131        let mut section = Self::default();
132        section.set_title(title.as_ref());
133        section
134    }
135
136    /// Sets the heading this section renders under.
137    pub fn set_title(&mut self, title: &str) {
138        self.title.clear();
139        self.title.push_str(title);
140    }
141
142    /// The heading.
143    #[must_use]
144    pub fn title(&self) -> &str {
145        &self.title
146    }
147
148    /// Appends a row, formatting `value` into a string this section already
149    /// owns.
150    ///
151    /// Takes [`fmt::Arguments`] rather than a `String` so the caller writes
152    /// `section.row("fps", format_args!("{fps:.1}"))` and nothing allocates
153    /// after the first frame.
154    pub fn row(&mut self, label: &str, value: fmt::Arguments<'_>) {
155        if self.used == self.rows.len() {
156            self.rows.push(DebugRow::default());
157        }
158        let row = &mut self.rows[self.used];
159        row.label.clear();
160        row.label.push_str(label);
161        row.value.clear();
162        // Writing into a `String` cannot fail; the `Result` is `fmt`'s shape.
163        let _ = row.value.write_fmt(value);
164        self.used += 1;
165    }
166
167    /// Appends a row whose value is already a string.
168    pub fn row_str(&mut self, label: &str, value: &str) {
169        self.row(label, format_args!("{value}"));
170    }
171
172    /// The live rows.
173    #[must_use]
174    pub fn rows(&self) -> &[DebugRow] {
175        &self.rows[..self.used]
176    }
177
178    /// Appends a graph of `samples`, oldest first, drawn under the rows as a
179    /// bar each, full height at `scale` and above. A `scale` that is not
180    /// above zero draws every bar empty rather than dividing by it.
181    ///
182    /// The graph says nothing of its scale; a module that wants it read
183    /// writes it in a row.
184    pub fn graph(&mut self, label: &str, samples: impl IntoIterator<Item = f32>, scale: f32) {
185        if self.graphs_used == self.graphs.len() {
186            self.graphs.push(DebugGraph::default());
187        }
188        let graph = &mut self.graphs[self.graphs_used];
189        graph.label.clear();
190        graph.label.push_str(label);
191        graph.bars.clear();
192        graph.bars.extend(samples.into_iter().map(|sample| {
193            if scale > 0.0 {
194                (sample / scale).clamp(0.0, 1.0)
195            } else {
196                0.0
197            }
198        }));
199        self.graphs_used += 1;
200    }
201
202    /// The live graphs.
203    #[must_use]
204    pub fn graphs(&self) -> &[DebugGraph] {
205        &self.graphs[..self.graphs_used]
206    }
207
208    /// Whether this section has no rows and no graphs.
209    #[must_use]
210    pub const fn is_empty(&self) -> bool {
211        self.used == 0 && self.graphs_used == 0
212    }
213
214    /// Drops the title, the rows and the graphs, keeping their allocations.
215    pub fn clear(&mut self) {
216        self.title.clear();
217        self.used = 0;
218        self.graphs_used = 0;
219    }
220}
221
222/// A system that can describe itself in the debug panel.
223///
224/// The one method is handed a section that has already been cleared, and fills
225/// in a title and rows. Implement it on the thing that owns the numbers — the
226/// renderer's frame timings, a network client's counters — never on the panel.
227pub trait DebugModule {
228    /// Writes this system's title and rows into `out`.
229    fn debug_section(&self, out: &mut DebugSection);
230}
231
232// ---------------------------------------------------------------------------
233// Frame statistics
234// ---------------------------------------------------------------------------
235
236/// How many frames [`FrameStats`] averages over by default.
237///
238/// Two seconds at 60 Hz. Short enough that a change in frame rate shows up
239/// while you are still looking at it, long enough that the number is readable —
240/// an instantaneous FPS at 60 Hz is a blur of four-digit noise.
241pub const DEFAULT_FRAME_WINDOW: usize = 120;
242
243/// A rolling window of frame intervals, and the numbers read off it.
244///
245/// Fed from the frame clock's render delta — the wall-clock time between the
246/// last two `update`s — so every number below traces to one measurement the
247/// engine already takes.
248///
249/// # FPS is the reciprocal of the mean, not the mean of the reciprocals
250///
251/// Given frames of 10 ms and 30 ms, the mean of `1/dt` is `(100 + 33.3)/2 = 67`
252/// FPS, which is faster than either frame. The window actually took 40 ms and
253/// contained 2 frames, so it ran at 50 FPS, which is what
254/// [`FrameStats::fps`] reports: `count / total`. The two agree only when every
255/// frame is the same length, and they disagree in exactly the case a profiler
256/// exists for.
257#[derive(Debug, Clone)]
258pub struct FrameStats {
259    window: usize,
260    samples: VecDeque<Duration>,
261    /// Kept incrementally so [`FrameStats::record`] is O(1); `Duration` addition
262    /// is exact, so this cannot drift away from the sum of `samples`.
263    total: Duration,
264}
265
266impl Default for FrameStats {
267    fn default() -> Self {
268        Self::new()
269    }
270}
271
272impl FrameStats {
273    /// A window of [`DEFAULT_FRAME_WINDOW`] frames.
274    #[must_use]
275    pub fn new() -> Self {
276        Self::with_window(DEFAULT_FRAME_WINDOW)
277    }
278
279    /// A window of `window` frames, clamped to at least one.
280    #[must_use]
281    pub fn with_window(window: usize) -> Self {
282        let window = window.max(1);
283        Self {
284            window,
285            samples: VecDeque::with_capacity(window),
286            total: Duration::ZERO,
287        }
288    }
289
290    /// Records one frame interval, evicting the oldest when the window is full.
291    ///
292    /// A zero-length interval is **not** a frame and is dropped.
293    /// [`FrameClock::update`] reports `Duration::ZERO` twice: on the very first
294    /// update, which has no previous timestamp to subtract, and on any update
295    /// whose timestamp went backwards. Neither is a frame that took no time, and
296    /// keeping them would report a frame rate that never happened.
297    ///
298    /// [`FrameClock::update`]: https://docs.rs/crcbl-core
299    pub fn record(&mut self, dt: Duration) {
300        if dt.is_zero() {
301            return;
302        }
303        if self.samples.len() == self.window
304            && let Some(oldest) = self.samples.pop_front()
305        {
306            self.total -= oldest;
307        }
308        self.samples.push_back(dt);
309        self.total += dt;
310    }
311
312    /// How many frames are in the window.
313    #[must_use]
314    pub fn len(&self) -> usize {
315        self.samples.len()
316    }
317
318    /// Whether no frame has been recorded yet.
319    #[must_use]
320    pub fn is_empty(&self) -> bool {
321        self.samples.is_empty()
322    }
323
324    /// The window's capacity in frames.
325    #[must_use]
326    pub const fn window(&self) -> usize {
327        self.window
328    }
329
330    /// The wall-clock time the window covers.
331    #[must_use]
332    pub const fn total(&self) -> Duration {
333        self.total
334    }
335
336    /// The mean frame interval, or zero while the window is empty.
337    #[must_use]
338    pub fn mean(&self) -> Duration {
339        let count = u32::try_from(self.samples.len()).unwrap_or(u32::MAX);
340        if count == 0 {
341            Duration::ZERO
342        } else {
343            self.total / count
344        }
345    }
346
347    /// Frames per second over the window: frames divided by the time they took.
348    ///
349    /// Zero while the window is empty, and zero if the window somehow covers no
350    /// time at all — an infinite frame rate is not a more honest answer.
351    #[must_use]
352    pub fn fps(&self) -> f64 {
353        let seconds = self.total.as_secs_f64();
354        if self.samples.is_empty() || seconds <= 0.0 {
355            0.0
356        } else {
357            self.samples.len() as f64 / seconds
358        }
359    }
360
361    /// The most recent frame interval.
362    #[must_use]
363    pub fn last(&self) -> Option<Duration> {
364        self.samples.back().copied()
365    }
366
367    /// The shortest frame in the window.
368    #[must_use]
369    pub fn best(&self) -> Option<Duration> {
370        self.samples.iter().min().copied()
371    }
372
373    /// The longest frame in the window — the stall, if there was one.
374    #[must_use]
375    pub fn worst(&self) -> Option<Duration> {
376        self.samples.iter().max().copied()
377    }
378
379    /// Forgets every sample.
380    pub fn clear(&mut self) {
381        self.samples.clear();
382        self.total = Duration::ZERO;
383    }
384}
385
386/// Milliseconds, for display.
387fn millis(duration: Duration) -> f64 {
388    duration.as_secs_f64() * 1_000.0
389}
390
391impl DebugModule for FrameStats {
392    fn debug_section(&self, out: &mut DebugSection) {
393        out.set_title("frame");
394        out.row("fps", format_args!("{:.1}", self.fps()));
395        out.row("avg", format_args!("{:.2} ms", millis(self.mean())));
396        out.row(
397            "last",
398            format_args!("{:.2} ms", millis(self.last().unwrap_or_default())),
399        );
400        out.row(
401            "best",
402            format_args!("{:.2} ms", millis(self.best().unwrap_or_default())),
403        );
404        out.row(
405            "worst",
406            format_args!("{:.2} ms", millis(self.worst().unwrap_or_default())),
407        );
408        out.row("window", format_args!("{}/{}", self.len(), self.window()));
409    }
410}
411
412// ---------------------------------------------------------------------------
413// Panel
414// ---------------------------------------------------------------------------
415
416/// Colours and spacing for the debug panel.
417///
418/// Separate from [`Style`](crate::widget::Style), which is the *widget* theme: a
419/// game restyling its buttons must not restyle the profiler out of legibility.
420#[derive(Debug, Clone, Copy, PartialEq)]
421pub struct DebugStyle {
422    /// Backing rectangle behind the whole panel.
423    pub bg: [f32; 4],
424    /// Section headings.
425    pub title: [f32; 4],
426    /// Row labels.
427    pub label: [f32; 4],
428    /// Row values.
429    pub value: [f32; 4],
430    /// A graph's bars.
431    pub graph: [f32; 4],
432    /// Text size in pixels.
433    pub font_size: f32,
434    /// Space between the backing rect and the text.
435    pub padding: f32,
436    /// Space between the label column and the value column.
437    pub column_gap: f32,
438    /// Space between one section and the next.
439    pub section_gap: f32,
440}
441
442impl Default for DebugStyle {
443    fn default() -> Self {
444        Self {
445            bg: [0.04, 0.04, 0.07, 0.82],
446            title: [0.45, 0.85, 1.0, 1.0],
447            label: [0.72, 0.72, 0.78, 1.0],
448            value: [1.0, 1.0, 1.0, 1.0],
449            graph: [0.45, 0.85, 1.0, 0.9],
450            font_size: NATURAL_FONT_SIZE,
451            padding: 6.0,
452            column_gap: 10.0,
453            section_gap: 6.0,
454        }
455    }
456}
457
458/// The overlay's panel: whatever sections were added this frame, stacked.
459///
460/// Hidden by default. See the [module docs](self) for the frame shape and for
461/// why nothing happens while it is hidden.
462#[derive(Debug, Clone)]
463pub struct DebugPanel {
464    visible: bool,
465    /// Which corner it is pinned to. Top-right by default, because both existing
466    /// samples put their game HUD at the top left.
467    pub anchor: Anchor,
468    /// Inset from that corner, in pixels.
469    pub offset: Vec2,
470    /// Colours and spacing.
471    pub style: DebugStyle,
472    sections: Vec<DebugSection>,
473    /// How many of `sections` were filled this frame; the rest are retained
474    /// allocations from a frame that had more modules.
475    used: usize,
476}
477
478impl Default for DebugPanel {
479    fn default() -> Self {
480        Self::new()
481    }
482}
483
484impl DebugPanel {
485    /// A hidden panel with no sections.
486    #[must_use]
487    pub fn new() -> Self {
488        Self {
489            visible: false,
490            anchor: Anchor::TopRight,
491            offset: Vec2::splat(8.0),
492            style: DebugStyle::default(),
493            sections: Vec::new(),
494            used: 0,
495        }
496    }
497
498    /// Whether the panel draws anything.
499    #[must_use]
500    pub const fn is_visible(&self) -> bool {
501        self.visible
502    }
503
504    /// Shows or hides the panel.
505    ///
506    /// Hiding drops the sections gathered this frame, so a hidden panel cannot
507    /// render stale numbers if it is shown again without a `begin_frame`.
508    pub const fn set_visible(&mut self, visible: bool) {
509        self.visible = visible;
510        if !visible {
511            self.used = 0;
512        }
513    }
514
515    /// Flips [`DebugPanel::is_visible`]. What the toggle key calls.
516    pub const fn toggle(&mut self) {
517        self.set_visible(!self.visible);
518    }
519
520    /// Starts a frame: forgets the sections the last one gathered.
521    pub const fn begin_frame(&mut self) {
522        self.used = 0;
523    }
524
525    /// Adds one system's section, in the order added.
526    ///
527    /// A no-op while the panel is hidden — `module`'s `debug_section` is not
528    /// called at all, so a system pays nothing for a panel nobody is looking at.
529    pub fn add(&mut self, module: &dyn DebugModule) {
530        if !self.visible {
531            return;
532        }
533        if self.used == self.sections.len() {
534            self.sections.push(DebugSection::default());
535        }
536        let section = &mut self.sections[self.used];
537        section.clear();
538        module.debug_section(section);
539        self.used += 1;
540    }
541
542    /// The sections gathered this frame, in the order they were added.
543    #[must_use]
544    pub fn sections(&self) -> &[DebugSection] {
545        &self.sections[..self.used]
546    }
547
548    /// The panel's full extent including its padding, or zero if it would draw
549    /// nothing.
550    #[must_use]
551    pub fn size(&self, atlas: &FontAtlas) -> Vec2 {
552        self.laid_out(atlas, |ui, panel| {
553            let (min, max) = ui.rect(panel).expect("laid out this frame");
554            max - min
555        })
556        .unwrap_or(Vec2::ZERO)
557    }
558
559    /// Draws the panel into `dl`.
560    ///
561    /// Emits nothing at all when the panel is hidden or has no sections —
562    /// including no background rect, so an overlay with nothing to say is
563    /// invisible rather than an empty box.
564    pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
565        self.laid_out(atlas, |ui, panel| {
566            let (min, max) = ui.rect(panel).expect("laid out this frame");
567            // The anchor is an inset, so where the panel starts depends on how
568            // big it came out: measured at the origin above, then placed. The
569            // second call lays out nothing new — every measurement, every
570            // resolved style and Taffy's whole cache are the first call's — it
571            // only moves the roots, which is what `Ui::layout`'s `origin` does.
572            let origin = self.anchor.position(screen_size, self.offset, max - min);
573            ui.layout(origin, AvailableSpace::MAX_CONTENT, atlas);
574            ui.emit(dl);
575        });
576    }
577
578    /// Builds the panel with [`DebugPanel::build`], lays it out at the origin
579    /// in the calling thread's one debug tree, and hands the tree to `read`.
580    ///
581    /// `None` — and **no tree touched at all** — when the panel has nothing to
582    /// draw, which is every frame it is hidden: [`DebugPanel::add`] refuses to
583    /// gather while hidden and [`DebugPanel::set_visible`] drops whatever was
584    /// gathered, so a hidden panel has no sections by construction.
585    ///
586    /// One tree per thread, rebuilt by every call, for [`crate::menu`]'s
587    /// reason: the panel is measured and drawn separately every frame with the
588    /// same selectors, so a kept tree resolves each node's style from its own
589    /// last resolve and lays out from Taffy's cache instead of from nothing. It
590    /// holds no state a call can see — the pointer it begins with is off every
591    /// rectangle, so no rule's `:hover` applies.
592    fn laid_out<R>(
593        &self,
594        atlas: &FontAtlas,
595        read: impl FnOnce(&mut Ui, NodeKey) -> R,
596    ) -> Option<R> {
597        if self.sections().is_empty() {
598            return None;
599        }
600        DEBUG_TREE.with(|tree| {
601            let mut ui = tree.borrow_mut();
602            ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
603            let panel = self.build(&mut ui, atlas);
604            ui.layout(Vec2::ZERO, AvailableSpace::MAX_CONTENT, atlas);
605            Some(read(&mut ui, panel))
606        })
607    }
608
609    /// Builds this panel into `ui`: the column, a section per module, a row per
610    /// reading, and a span for every string. Returns the panel's own node.
611    ///
612    /// Every colour, the font size, the padding and the two gaps are
613    /// [`DebugStyle`]'s and go on inline; the rest of the look is
614    /// `default.css`'s. The labels' `min-width` is the widest label in the
615    /// **whole** panel — see the module docs.
616    fn build(&self, ui: &mut Ui, atlas: &FontAtlas) -> NodeKey {
617        use Declaration as D;
618        let style = &self.style;
619        let scale = style.font_size / NATURAL_FONT_SIZE;
620        let mut label_width = 0.0f32;
621        for section in self.sections() {
622            let rows = section.rows().iter().map(|row| &row.label);
623            let graphs = section.graphs().iter().map(|graph| &graph.label);
624            for label in rows.chain(graphs) {
625                label_width = label_width.max(atlas.text_width(label, scale));
626            }
627        }
628
629        let panel = [
630            D::Padding(Sides::All, Length::Px(style.padding)),
631            D::RowGap(Length::Px(style.section_gap)),
632            D::Background(style.bg),
633            D::FontSize(style.font_size),
634        ];
635        let title = [D::Color(style.title)];
636        let label = [
637            D::Color(style.label),
638            D::MinWidth(LengthAuto::Px(label_width + style.column_gap)),
639        ];
640        let value = [D::Color(style.value)];
641        let graph_height = GRAPH_HEIGHT * scale;
642        let graph = [
643            D::Height(LengthAuto::Px(graph_height)),
644            D::AlignItems(Some(Align::FlexEnd)),
645        ];
646
647        ui.block("debug-panel", &panel, |ui| {
648            for (index, section) in self.sections().iter().enumerate() {
649                ui.block_keyed(index, ".debug-section", &[], |ui| {
650                    ui.span(".debug-title", section.title(), &title);
651                    for (row_index, row) in section.rows().iter().enumerate() {
652                        ui.block_keyed(row_index, ".debug-row", &[], |ui| {
653                            ui.span(".debug-label", row.label.as_str(), &label);
654                            ui.span(".debug-value", row.value.as_str(), &value);
655                        });
656                    }
657                    for (graph_index, plotted) in section.graphs().iter().enumerate() {
658                        let key = (section.rows().len(), graph_index);
659                        ui.block_keyed(key, ".debug-row", &[], |ui| {
660                            ui.span(".debug-label", plotted.label.as_str(), &label);
661                            ui.block(".debug-graph", &graph, |ui| {
662                                for (bar_index, bar) in plotted.bars.iter().enumerate() {
663                                    let height = (bar * graph_height).max(MIN_BAR_HEIGHT);
664                                    let bar = [
665                                        D::Width(LengthAuto::Px(GRAPH_BAR_WIDTH * scale)),
666                                        D::Height(LengthAuto::Px(height)),
667                                        D::Background(style.graph),
668                                    ];
669                                    ui.block_keyed(bar_index, ".debug-bar", &bar, |_| {});
670                                }
671                            });
672                        });
673                    }
674                });
675            }
676        })
677        .key
678    }
679}
680
681thread_local! {
682    /// The tree [`DebugPanel::laid_out`] measures and draws panels in; see
683    /// there.
684    static DEBUG_TREE: RefCell<Ui> = RefCell::new(Ui::new());
685}
686
687/// Where [`DebugPanel::laid_out`]'s pointer is: above and left of every
688/// rectangle the panel lays out, which all start at the origin.
689const OFF_SCREEN: Vec2 = Vec2::splat(-1.0);
690
691/// A graph's height at [`NATURAL_FONT_SIZE`]: one line of text, so a graph
692/// takes a row's place in the panel and no more.
693pub const GRAPH_HEIGHT: f32 = LINE_HEIGHT;
694
695/// One bar's width at [`NATURAL_FONT_SIZE`]: narrow enough that a few
696/// seconds of samples fit beside the labels.
697pub const GRAPH_BAR_WIDTH: f32 = 2.0;
698
699/// The least a bar is drawn: an empty sample still shows as a tick on the
700/// baseline, so a graph with nothing to plot is told from no graph at all.
701pub const MIN_BAR_HEIGHT: f32 = 1.0;
702
703// ---------------------------------------------------------------------------
704// Overlay
705// ---------------------------------------------------------------------------
706
707/// The panel plus the one module every frame has: [`FrameStats`].
708///
709/// This is what a sample holds. Frame timing has no precondition and no
710/// configuration — every sample has a frame — so it is wired in here rather than
711/// added by each sample, which is the difference between "switching it on is one
712/// thing" and every sample remembering to add the same module.
713///
714/// Everything else is [`DebugOverlay::add`], called only by a sample that has
715/// the system in question.
716#[derive(Debug, Clone, Default)]
717pub struct DebugOverlay {
718    /// The panel. Public so a sample can move it, restyle it or read its
719    /// sections.
720    pub panel: DebugPanel,
721    /// The rolling frame window, fed by [`DebugOverlay::record`].
722    pub frame: FrameStats,
723    /// CPU against GPU frame time, fed by whatever holds both — the engine's
724    /// loop does, from the trace and the renderer's timers.
725    ///
726    /// Unlike [`DebugOverlay::frame`] this has a precondition, so
727    /// [`DebugOverlay::begin_frame`] adds it only once it has a sample; see
728    /// there.
729    pub budget: BudgetStats,
730}
731
732impl DebugOverlay {
733    /// A hidden overlay.
734    #[must_use]
735    pub fn new() -> Self {
736        Self::default()
737    }
738
739    /// An overlay that starts visible or not.
740    ///
741    /// Samples pass `cfg!(debug_assertions) || options.debug_overlay` — rule 4's
742    /// "on by default in dev builds", with a flag for the other cases.
743    #[must_use]
744    pub fn with_visible(visible: bool) -> Self {
745        let mut overlay = Self::new();
746        overlay.panel.set_visible(visible);
747        overlay
748    }
749
750    /// Whether the panel draws.
751    #[must_use]
752    pub const fn is_visible(&self) -> bool {
753        self.panel.is_visible()
754    }
755
756    /// Shows or hides the panel.
757    pub const fn set_visible(&mut self, visible: bool) {
758        self.panel.set_visible(visible);
759    }
760
761    /// Flips the panel. What a sample's toggle key calls.
762    pub const fn toggle(&mut self) {
763        self.panel.toggle();
764    }
765
766    /// Records one frame interval. Call every frame, hidden or not.
767    pub fn record(&mut self, dt: Duration) {
768        self.frame.record(dt);
769    }
770
771    /// Starts the frame and adds the frame-timing section, plus the budget
772    /// section if there is anything in it.
773    ///
774    /// **The budget row has a precondition and the frame row does not**, which
775    /// is the whole difference between the two. Every sample has a frame
776    /// interval; the CPU half of the budget row exists only in a run whose trace
777    /// is on and the GPU half only on a device with timestamp queries, so a
778    /// sample that has neither would get three rows of `none` forever. That is
779    /// the same rule the panel already applies to a network module: a section
780    /// appears because the system it reports on is there.
781    pub fn begin_frame(&mut self) {
782        self.panel.begin_frame();
783        self.panel.add(&self.frame);
784        if self.budget.has_samples() {
785            self.panel.add(&self.budget);
786        }
787    }
788
789    /// Adds a system's section, after [`DebugOverlay::begin_frame`].
790    pub fn add(&mut self, module: &dyn DebugModule) {
791        self.panel.add(module);
792    }
793
794    /// Draws the panel.
795    pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
796        self.panel.render(dl, screen_size, atlas);
797    }
798}
799
800// ---------------------------------------------------------------------------
801// Tests
802// ---------------------------------------------------------------------------
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807    use crate::draw_list::DrawCommand;
808
809    fn ms(millis: u64) -> Duration {
810        Duration::from_millis(millis)
811    }
812
813    fn screen() -> Vec2 {
814        Vec2::new(1280.0, 720.0)
815    }
816
817    /// Every `Text` command's string, in draw order.
818    fn texts(dl: &DrawList) -> Vec<String> {
819        dl.commands()
820            .iter()
821            .filter_map(|command| match command {
822                DrawCommand::Text { text, .. } => Some(text.clone()),
823                _ => None,
824            })
825            .collect()
826    }
827
828    /// A module that says what it is told to, for testing composition.
829    struct Fake {
830        title: &'static str,
831        rows: &'static [(&'static str, &'static str)],
832    }
833
834    impl DebugModule for Fake {
835        fn debug_section(&self, out: &mut DebugSection) {
836            out.set_title(self.title);
837            for (label, value) in self.rows {
838                out.row_str(label, value);
839            }
840        }
841    }
842
843    fn shown() -> DebugPanel {
844        let mut panel = DebugPanel::new();
845        panel.set_visible(true);
846        panel.begin_frame();
847        panel
848    }
849
850    // -- frame maths --------------------------------------------------------
851
852    /// A known sequence in, known numbers out. 10 + 30 = 40 ms for 2 frames, so
853    /// 50 FPS and a 20 ms mean — *not* the 67 FPS a mean of reciprocals gives.
854    #[test]
855    fn fps_is_frames_over_elapsed_not_the_mean_of_instantaneous_rates() {
856        let mut stats = FrameStats::new();
857        stats.record(ms(10));
858        stats.record(ms(30));
859        assert_eq!(stats.len(), 2);
860        assert_eq!(stats.total(), ms(40));
861        assert_eq!(stats.mean(), ms(20));
862        assert!(
863            (stats.fps() - 50.0).abs() < 1e-9,
864            "expected 50 fps, got {}",
865            stats.fps()
866        );
867        assert_eq!(stats.best(), Some(ms(10)));
868        assert_eq!(stats.worst(), Some(ms(30)));
869        assert_eq!(stats.last(), Some(ms(30)));
870    }
871
872    /// Sixteen frames of exactly 1/64 s: 64 FPS, and every reported number
873    /// agrees because nothing varied.
874    #[test]
875    fn a_steady_sequence_reports_its_own_rate() {
876        let mut stats = FrameStats::new();
877        let step = Duration::from_nanos(15_625_000); // 1/64 s exactly
878        for _ in 0..16 {
879            stats.record(step);
880        }
881        assert_eq!(stats.mean(), step);
882        assert!((stats.fps() - 64.0).abs() < 1e-9, "got {}", stats.fps());
883        assert_eq!(stats.best(), Some(step));
884        assert_eq!(stats.worst(), Some(step));
885    }
886
887    /// **The first frame.** `FrameClock::update` has no previous timestamp on
888    /// its first call and reports `Duration::ZERO`; so does an update whose
889    /// timestamp went backwards. Neither is a frame that took no time, and a
890    /// window holding one would divide by zero.
891    #[test]
892    fn the_first_frames_zero_delta_is_not_a_sample_and_fps_is_not_infinite() {
893        let mut stats = FrameStats::new();
894        stats.record(Duration::ZERO);
895        assert!(stats.is_empty(), "a zero-length interval is not a frame");
896        assert_eq!(stats.fps(), 0.0);
897        assert!(stats.fps().is_finite());
898        assert_eq!(stats.mean(), Duration::ZERO);
899        assert_eq!(stats.last(), None);
900
901        // And the section it renders is finite too, rather than `inf` or `NaN`.
902        let mut section = DebugSection::default();
903        stats.debug_section(&mut section);
904        for row in section.rows() {
905            assert!(
906                !row.value.contains("inf") && !row.value.contains("NaN"),
907                "{}: {}",
908                row.label,
909                row.value
910            );
911        }
912    }
913
914    /// **A long stall.** One 500 ms frame among sixty 16 ms ones must show up as
915    /// the worst frame and must drag the average, or a hitch is invisible.
916    #[test]
917    fn a_stall_shows_in_the_worst_frame_and_moves_the_average() {
918        let mut stats = FrameStats::new();
919        for _ in 0..60 {
920            stats.record(ms(16));
921        }
922        let smooth = stats.mean();
923        stats.record(ms(500));
924        assert_eq!(stats.worst(), Some(ms(500)));
925        assert_eq!(stats.best(), Some(ms(16)));
926        assert_eq!(stats.last(), Some(ms(500)));
927        // 60×16 + 500 = 1460 ms over 61 frames.
928        assert_eq!(stats.total(), ms(1460));
929        assert_eq!(stats.mean(), ms(1460) / 61);
930        assert!(
931            stats.mean() > smooth,
932            "the stall must move the average: {smooth:?} → {:?}",
933            stats.mean()
934        );
935        assert!(
936            (stats.fps() - 61.0 / 1.46).abs() < 1e-9,
937            "got {}",
938            stats.fps()
939        );
940    }
941
942    /// The window evicts, and the total it keeps incrementally stays exactly the
943    /// sum of what is left — so a stall that has scrolled off stops counting.
944    #[test]
945    fn the_window_evicts_and_the_running_total_matches_the_samples() {
946        let mut stats = FrameStats::with_window(4);
947        stats.record(ms(500));
948        for _ in 0..4 {
949            stats.record(ms(10));
950        }
951        assert_eq!(stats.len(), 4, "the window holds four");
952        assert_eq!(stats.total(), ms(40), "the stall has scrolled off");
953        assert_eq!(stats.worst(), Some(ms(10)));
954        assert!((stats.fps() - 100.0).abs() < 1e-9, "got {}", stats.fps());
955    }
956
957    /// A zero window would divide by zero on eviction; it is clamped to one.
958    #[test]
959    fn a_zero_window_is_clamped_to_one_frame() {
960        let mut stats = FrameStats::with_window(0);
961        assert_eq!(stats.window(), 1);
962        stats.record(ms(10));
963        stats.record(ms(20));
964        assert_eq!(stats.len(), 1);
965        assert_eq!(stats.total(), ms(20));
966    }
967
968    // -- modularity ---------------------------------------------------------
969
970    /// **A panel with no module but the frame's renders.** This is breakout and
971    /// flappy's case: no connection, so no network module, and the panel is
972    /// still a panel. Asserting "it did not crash" would pass on a panel that
973    /// drew nothing, so this asserts the frame numbers are actually in the draw
974    /// list.
975    #[test]
976    fn a_panel_with_only_the_frame_module_draws_the_frame_numbers() {
977        let atlas = FontAtlas::built_in();
978        let mut overlay = DebugOverlay::with_visible(true);
979        overlay.record(ms(20));
980        overlay.record(ms(20));
981        overlay.begin_frame();
982
983        let mut dl = DrawList::new();
984        overlay.render(&mut dl, screen(), &atlas);
985
986        let drawn = texts(&dl);
987        assert_eq!(
988            drawn.first().map(String::as_str),
989            Some("frame"),
990            "the section heading: {drawn:?}"
991        );
992        assert!(drawn.iter().any(|t| t == "fps"), "{drawn:?}");
993        assert!(
994            drawn.iter().any(|t| t == "50.0"),
995            "two 20 ms frames is 50 fps: {drawn:?}"
996        );
997        assert!(
998            drawn.iter().any(|t| t == "20.00 ms"),
999            "the mean must be drawn: {drawn:?}"
1000        );
1001        assert!(
1002            dl.commands()
1003                .iter()
1004                .any(|c| matches!(c, DrawCommand::Rect { .. })),
1005            "the panel draws its own background"
1006        );
1007        assert_eq!(overlay.panel.sections().len(), 1, "no network module");
1008    }
1009
1010    /// **The budget row reaches the draw list, and only once it has a sample.**
1011    ///
1012    /// Keyed on the section *title* and then on the labels inside it rather than
1013    /// by searching the whole list for a string: `DebugModule` labels share one
1014    /// namespace across modules and nothing detects a collision, so a search for
1015    /// `cpu` could pick up a row a future module adds. The title `budget` is this
1016    /// module's, and the walk below starts from it.
1017    #[test]
1018    fn the_budget_section_appears_once_it_has_a_sample_and_carries_its_numbers() {
1019        use crate::budget::MIN_PERCENTILE_SAMPLES;
1020
1021        let atlas = FontAtlas::built_in();
1022        let mut overlay = DebugOverlay::with_visible(true);
1023        overlay.record(ms(16));
1024
1025        // Nothing recorded: the frame section and nothing else.
1026        overlay.begin_frame();
1027        assert_eq!(
1028            overlay
1029                .panel
1030                .sections()
1031                .iter()
1032                .map(DebugSection::title)
1033                .collect::<Vec<_>>(),
1034            ["frame"],
1035            "a run with no trace and no GPU timers has no budget to report"
1036        );
1037
1038        for frame in 0..MIN_PERCENTILE_SAMPLES as u64 {
1039            overlay.budget.record_cpu(ms(4));
1040            overlay.budget.record_gpu(frame, ms(11));
1041        }
1042        overlay.begin_frame();
1043        let mut dl = DrawList::new();
1044        overlay.render(&mut dl, screen(), &atlas);
1045
1046        let drawn = texts(&dl);
1047        let start = drawn
1048            .iter()
1049            .position(|text| text == "budget")
1050            .unwrap_or_else(|| panic!("no budget section: {drawn:?}"));
1051        assert_eq!(
1052            &drawn[start..],
1053            [
1054                "budget",
1055                "cpu p50/p95",
1056                "4.00 / 4.00 ms",
1057                "gpu elapsed p50/p95",
1058                "11.00 / 11.00 ms",
1059                "bound",
1060                "gpu",
1061                "gpu frame",
1062                "19",
1063            ],
1064        );
1065    }
1066
1067    /// Two modules render as two sections, in the order they were added, with
1068    /// every row of each.
1069    #[test]
1070    fn two_modules_render_both_sections_in_the_order_added() {
1071        let atlas = FontAtlas::built_in();
1072        let first = Fake {
1073            title: "alpha",
1074            rows: &[("a1", "one"), ("a2", "two")],
1075        };
1076        let second = Fake {
1077            title: "beta",
1078            rows: &[("b1", "three")],
1079        };
1080
1081        let mut panel = shown();
1082        panel.add(&first);
1083        panel.add(&second);
1084
1085        assert_eq!(
1086            panel
1087                .sections()
1088                .iter()
1089                .map(DebugSection::title)
1090                .collect::<Vec<_>>(),
1091            ["alpha", "beta"],
1092        );
1093
1094        let mut dl = DrawList::new();
1095        panel.render(&mut dl, screen(), &atlas);
1096        assert_eq!(
1097            texts(&dl),
1098            ["alpha", "a1", "one", "a2", "two", "beta", "b1", "three"],
1099            "titles and rows, in order",
1100        );
1101
1102        // And the reverse order is genuinely a different draw list.
1103        let mut swapped = shown();
1104        swapped.add(&second);
1105        swapped.add(&first);
1106        let mut other = DrawList::new();
1107        swapped.render(&mut other, screen(), &atlas);
1108        assert_eq!(
1109            texts(&other),
1110            ["beta", "b1", "three", "alpha", "a1", "one", "a2", "two"],
1111        );
1112    }
1113
1114    /// The section count follows the modules added, so a frame with fewer
1115    /// modules than the last does not render the leftovers.
1116    #[test]
1117    fn a_frame_with_fewer_modules_does_not_render_the_previous_frames() {
1118        let atlas = FontAtlas::built_in();
1119        let first = Fake {
1120            title: "alpha",
1121            rows: &[("a1", "one")],
1122        };
1123        let second = Fake {
1124            title: "beta",
1125            rows: &[("b1", "two")],
1126        };
1127
1128        let mut panel = shown();
1129        panel.add(&first);
1130        panel.add(&second);
1131        assert_eq!(panel.sections().len(), 2);
1132
1133        panel.begin_frame();
1134        panel.add(&first);
1135        let mut dl = DrawList::new();
1136        panel.render(&mut dl, screen(), &atlas);
1137        let drawn = texts(&dl);
1138        assert_eq!(panel.sections().len(), 1);
1139        assert!(
1140            !drawn.iter().any(|t| t == "beta"),
1141            "the dropped module is gone: {drawn:?}"
1142        );
1143    }
1144
1145    /// A panel that gathered nothing draws nothing — not an empty box.
1146    #[test]
1147    fn a_panel_with_no_sections_at_all_draws_nothing() {
1148        let atlas = FontAtlas::built_in();
1149        let panel = shown();
1150        let mut dl = DrawList::new();
1151        panel.render(&mut dl, screen(), &atlas);
1152        assert!(dl.is_empty(), "{:?}", dl.commands());
1153        assert_eq!(panel.size(&atlas), Vec2::ZERO);
1154    }
1155
1156    // -- the toggle ---------------------------------------------------------
1157
1158    /// **Toggling changes what is drawn.** Asserted on the draw list, not on
1159    /// `is_visible`: a toggle that flipped a bool nothing read would pass a
1160    /// bool assertion and fail the user.
1161    #[test]
1162    fn toggling_the_panel_changes_the_draw_list() {
1163        let atlas = FontAtlas::built_in();
1164        let module = Fake {
1165            title: "alpha",
1166            rows: &[("a1", "one")],
1167        };
1168        let mut panel = DebugPanel::new();
1169
1170        let draw = |panel: &mut DebugPanel| {
1171            panel.begin_frame();
1172            panel.add(&module);
1173            let mut dl = DrawList::new();
1174            panel.render(&mut dl, screen(), &atlas);
1175            dl
1176        };
1177
1178        // Off: no commands, and the module was never even asked.
1179        let off = draw(&mut panel);
1180        assert!(off.is_empty(), "hidden: {:?}", off.commands());
1181        assert!(panel.sections().is_empty(), "hidden panels gather nothing");
1182
1183        // On: the module's rows.
1184        panel.toggle();
1185        let on = draw(&mut panel);
1186        assert!(texts(&on).iter().any(|t| t == "alpha"), "{:?}", texts(&on));
1187
1188        // Off again: back to nothing.
1189        panel.toggle();
1190        let off_again = draw(&mut panel);
1191        assert!(off_again.is_empty(), "{:?}", off_again.commands());
1192    }
1193
1194    /// Hiding drops what was gathered, so showing again without a `begin_frame`
1195    /// cannot render the numbers from whenever it was last visible.
1196    #[test]
1197    fn hiding_forgets_the_sections_it_had() {
1198        let atlas = FontAtlas::built_in();
1199        let mut panel = shown();
1200        panel.add(&Fake {
1201            title: "alpha",
1202            rows: &[("a1", "one")],
1203        });
1204        assert_eq!(panel.sections().len(), 1);
1205
1206        panel.set_visible(false);
1207        panel.set_visible(true);
1208        assert!(panel.sections().is_empty());
1209        let mut dl = DrawList::new();
1210        panel.render(&mut dl, screen(), &atlas);
1211        assert!(dl.is_empty(), "{:?}", dl.commands());
1212    }
1213
1214    // -- layout -------------------------------------------------------------
1215
1216    /// **A resize.** The panel is anchored, so its rectangle has to follow the
1217    /// screen; a top-right panel that kept its old x runs off a narrowed window.
1218    #[test]
1219    fn the_panel_follows_the_screen_across_a_resize() {
1220        let atlas = FontAtlas::built_in();
1221        let mut panel = shown();
1222        panel.add(&Fake {
1223            title: "alpha",
1224            rows: &[("a1", "one")],
1225        });
1226        let size = panel.size(&atlas);
1227
1228        let bounds = |screen: Vec2| {
1229            let mut dl = DrawList::new();
1230            panel.render(&mut dl, screen, &atlas);
1231            match dl.commands().first() {
1232                Some(DrawCommand::Rect { min, max, .. }) => (*min, *max),
1233                other => panic!("expected the panel background, got {other:?}"),
1234            }
1235        };
1236
1237        for screen in [Vec2::new(1280.0, 720.0), Vec2::new(640.0, 360.0)] {
1238            let (min, max) = bounds(screen);
1239            assert_eq!(max - min, size, "the panel is the same size either way");
1240            assert_eq!(
1241                max,
1242                Vec2::new(screen.x - panel.offset.x, min.y + size.y),
1243                "the right edge stays {}px in from the right of {screen:?}",
1244                panel.offset.x,
1245            );
1246            assert!(
1247                min.x >= 0.0 && max.x <= screen.x,
1248                "off-screen: {min:?}..{max:?}"
1249            );
1250        }
1251
1252        // The two screens really are different positions — otherwise the
1253        // assertions above would hold for a panel pinned to a constant.
1254        assert_ne!(
1255            bounds(Vec2::new(1280.0, 720.0)).0,
1256            bounds(Vec2::new(640.0, 360.0)).0
1257        );
1258    }
1259
1260    /// A resize does not touch the frame window: the long frame a resize costs
1261    /// is a sample like any other, not a reason to forget the last two seconds.
1262    #[test]
1263    fn a_resize_does_not_reset_the_frame_window() {
1264        let mut overlay = DebugOverlay::with_visible(true);
1265        for _ in 0..10 {
1266            overlay.record(ms(16));
1267        }
1268        overlay.record(ms(120)); // the frame the swapchain was rebuilt on
1269        assert_eq!(overlay.frame.len(), 11);
1270        assert_eq!(overlay.frame.worst(), Some(ms(120)));
1271        assert_eq!(overlay.frame.best(), Some(ms(16)));
1272    }
1273
1274    /// The value column clears the longest label, so nothing overlaps.
1275    #[test]
1276    fn the_value_column_starts_past_the_longest_label() {
1277        let atlas = FontAtlas::built_in();
1278        let mut panel = shown();
1279        panel.add(&Fake {
1280            title: "x",
1281            rows: &[("short", "1"), ("a-much-longer-label", "2")],
1282        });
1283        let mut dl = DrawList::new();
1284        panel.render(&mut dl, screen(), &atlas);
1285
1286        let scale = panel.style.font_size / NATURAL_FONT_SIZE;
1287        let widest = atlas.text_width("a-much-longer-label", scale);
1288        let mut label_x = None;
1289        // The loop below only asserts inside its match arms, so a render that
1290        // emitted no text — or one whose labels stopped being these literals —
1291        // would run the body zero times and pass. The count is what makes the
1292        // arms load-bearing.
1293        let mut checked = 0;
1294        for command in dl.commands() {
1295            if let DrawCommand::Text { pos, text, .. } = command {
1296                match text.as_str() {
1297                    "short" | "a-much-longer-label" => label_x = Some(pos.x),
1298                    "1" | "2" => {
1299                        let start = label_x.expect("a label precedes its value");
1300                        assert!(
1301                            pos.x >= start + widest,
1302                            "value at {} overlaps a {widest}px label at {start}",
1303                            pos.x,
1304                        );
1305                        checked += 1;
1306                    }
1307                    _ => {}
1308                }
1309            }
1310        }
1311        assert_eq!(
1312            checked,
1313            2,
1314            "both rows' values must have been placed and checked, in {:?}",
1315            dl.commands()
1316        );
1317    }
1318
1319    /// Rows and titles are reused across frames rather than reallocated.
1320    #[test]
1321    fn a_section_reuses_its_row_allocations() {
1322        let mut section = DebugSection::new("frame");
1323        section.row("fps", format_args!("{:.1}", 59.94));
1324        section.row("avg", format_args!("{:.2} ms", 16.68));
1325        assert_eq!(section.rows().len(), 2);
1326        assert_eq!(section.rows()[0].value, "59.9");
1327        // The backing `Vec`'s *length*, not its capacity: capacity is 4 from the
1328        // first push either way, so a version of `clear` that threw the rows
1329        // away would compare equal and this test would check nothing.
1330        assert_eq!(section.rows.len(), 2, "two row slots exist");
1331
1332        section.clear();
1333        assert!(section.is_empty(), "no live rows");
1334        assert_eq!(section.title(), "");
1335        assert_eq!(
1336            section.rows.len(),
1337            2,
1338            "clear keeps the slots — that is the whole point of it",
1339        );
1340
1341        section.row("fps", format_args!("{:.1}", 30.0));
1342        assert_eq!(section.rows().len(), 1, "one live row");
1343        assert_eq!(section.rows()[0].value, "30.0");
1344        assert_eq!(section.rows.len(), 2, "and the second slot is still there");
1345    }
1346
1347    /// The arithmetic `render` was before the element tree laid it out,
1348    /// verbatim: the oracle the tree's output is held to.
1349    fn arithmetic_render(
1350        panel: &DebugPanel,
1351        dl: &mut DrawList,
1352        screen_size: Vec2,
1353        atlas: &FontAtlas,
1354    ) {
1355        use crate::text::LINE_HEIGHT;
1356
1357        let sections = panel.sections();
1358        if sections.is_empty() {
1359            return;
1360        }
1361        let style = &panel.style;
1362        let scale = style.font_size / NATURAL_FONT_SIZE;
1363        let line_height = LINE_HEIGHT * scale;
1364
1365        let mut label_width = 0.0f32;
1366        let mut value_width = 0.0f32;
1367        let mut title_width = 0.0f32;
1368        let mut lines = 0.0f32;
1369        for section in sections {
1370            title_width = title_width.max(atlas.text_width(section.title(), scale));
1371            lines += 1.0;
1372            for row in section.rows() {
1373                label_width = label_width.max(atlas.text_width(&row.label, scale));
1374                value_width = value_width.max(atlas.text_width(&row.value, scale));
1375                lines += 1.0;
1376            }
1377        }
1378        let value_column = label_width + style.column_gap;
1379        let content_width = title_width.max(value_column + value_width);
1380        let gaps = (sections.len() - 1) as f32 * style.section_gap;
1381        let content_height = lines * line_height + gaps;
1382        let size = Vec2::new(content_width, content_height) + Vec2::splat(style.padding * 2.0);
1383
1384        let origin = panel.anchor.position(screen_size, panel.offset, size);
1385        dl.rect(origin, origin + size, style.bg);
1386        let mut cursor = origin + Vec2::splat(style.padding);
1387        for section in sections {
1388            dl.text(cursor, section.title(), style.title, style.font_size);
1389            cursor.y += line_height;
1390            for row in section.rows() {
1391                dl.text(cursor, row.label.as_str(), style.label, style.font_size);
1392                dl.text(
1393                    Vec2::new(cursor.x + value_column, cursor.y),
1394                    row.value.as_str(),
1395                    style.value,
1396                    style.font_size,
1397                );
1398                cursor.y += line_height;
1399            }
1400            cursor.y += style.section_gap;
1401        }
1402    }
1403
1404    /// Every command and the clip it was pushed under, with every float printed
1405    /// to round-trip precision — so two renderings are equal exactly when every
1406    /// float is the same value.
1407    fn rendering(dl: &DrawList) -> Vec<String> {
1408        dl.commands()
1409            .iter()
1410            .zip(dl.clips())
1411            .map(|(command, clip)| format!("{command:?} under {clip:?}"))
1412            .collect()
1413    }
1414
1415    /// **The tree draws exactly the commands the arithmetic did**, float for
1416    /// float, at every anchor, on every extent the repository's "it is on
1417    /// screen" tests use, and for panels from one section to several — which is
1418    /// what says every sample's overlay golden is the picture it was.
1419    ///
1420    /// Every length involved is a whole number (`LINE_HEIGHT` is 16,
1421    /// `GLYPH_ADVANCE` is 10, the style's padding and gaps are integers), so
1422    /// Taffy's whole-pixel rounding has nothing to move; a style whose font
1423    /// size was not a multiple of `NATURAL_FONT_SIZE` would be the case where
1424    /// the two part company, and nothing ships one.
1425    #[test]
1426    fn the_tree_draws_the_panel_exactly_where_the_arithmetic_did() {
1427        let atlas = FontAtlas::built_in();
1428        let modules = [
1429            Fake {
1430                title: "frame",
1431                rows: &[("fps", "59.9"), ("avg", "16.68 ms"), ("window", "120/120")],
1432            },
1433            Fake {
1434                title: "budget",
1435                rows: &[("cpu p50/p95", "4.00 / 4.00 ms"), ("bound", "gpu")],
1436            },
1437            Fake {
1438                title: "a-much-longer-section-title",
1439                rows: &[("", ""), ("x", "1")],
1440            },
1441        ];
1442        for anchor in [
1443            Anchor::TopLeft,
1444            Anchor::TopRight,
1445            Anchor::BottomLeft,
1446            Anchor::BottomRight,
1447            Anchor::Center,
1448        ] {
1449            for count in 1..=modules.len() {
1450                let mut panel = shown();
1451                panel.anchor = anchor;
1452                for module in &modules[..count] {
1453                    panel.add(module);
1454                }
1455                for screen in [
1456                    Vec2::new(960.0, 720.0),
1457                    Vec2::new(800.0, 600.0),
1458                    Vec2::new(1920.0, 1080.0),
1459                    Vec2::new(1440.0, 400.0),
1460                    Vec2::new(600.0, 900.0),
1461                ] {
1462                    let mut tree = DrawList::new();
1463                    panel.render(&mut tree, screen, &atlas);
1464                    let mut arithmetic = DrawList::new();
1465                    arithmetic_render(&panel, &mut arithmetic, screen, &atlas);
1466                    assert_eq!(
1467                        rendering(&tree),
1468                        rendering(&arithmetic),
1469                        "{anchor:?}, {count} sections, {screen:?}",
1470                    );
1471                    assert!(
1472                        !tree.is_empty(),
1473                        "the panel drew nothing, so this proves nothing",
1474                    );
1475                }
1476            }
1477        }
1478    }
1479
1480    /// The tree's extent is the extent the arithmetic measured, which is what a
1481    /// page stacking something under the panel offsets by.
1482    #[test]
1483    fn the_trees_panel_is_the_size_the_arithmetic_measured() {
1484        let atlas = FontAtlas::built_in();
1485        let mut panel = shown();
1486        panel.add(&Fake {
1487            title: "frame",
1488            rows: &[("fps", "59.9"), ("a-much-longer-label", "16.68 ms")],
1489        });
1490        panel.add(&Fake {
1491            title: "budget",
1492            rows: &[("bound", "gpu")],
1493        });
1494
1495        let mut arithmetic = DrawList::new();
1496        arithmetic_render(&panel, &mut arithmetic, Vec2::ZERO, &atlas);
1497        let measured = match arithmetic.commands().first() {
1498            Some(DrawCommand::Rect { min, max, .. }) => *max - *min,
1499            other => panic!("expected the panel background, got {other:?}"),
1500        };
1501        assert_eq!(panel.size(&atlas), measured);
1502        assert_ne!(measured, Vec2::ZERO, "a zero panel proves nothing");
1503    }
1504
1505    // -- graphs -------------------------------------------------------------
1506
1507    /// A module that plots what it is told to.
1508    struct Plot {
1509        samples: &'static [f32],
1510        scale: f32,
1511    }
1512
1513    impl DebugModule for Plot {
1514        fn debug_section(&self, out: &mut DebugSection) {
1515            out.set_title("net");
1516            out.row_str("rtt", "12.0 ms");
1517            out.graph("rtt graph", self.samples.iter().copied(), self.scale);
1518        }
1519    }
1520
1521    /// Every rect drawn in the graph colour: the bars, in draw order.
1522    fn bars(dl: &DrawList, colour: [f32; 4]) -> Vec<(Vec2, Vec2)> {
1523        dl.commands()
1524            .iter()
1525            .filter_map(|command| match command {
1526                DrawCommand::Rect { min, max, color } if *color == colour => Some((*min, *max)),
1527                _ => None,
1528            })
1529            .collect()
1530    }
1531
1532    /// **A graph draws a bar per sample**, oldest first and left to right,
1533    /// each as tall as its sample over the scale, clamped to the graph, never
1534    /// less than the baseline tick, and all standing on one baseline.
1535    #[test]
1536    fn a_graph_draws_a_bar_per_sample_scaled_to_its_height() {
1537        let atlas = FontAtlas::built_in();
1538        let mut panel = shown();
1539        panel.add(&Plot {
1540            samples: &[0.0, 5.0, 10.0, 40.0],
1541            scale: 20.0,
1542        });
1543        let mut dl = DrawList::new();
1544        panel.render(&mut dl, screen(), &atlas);
1545
1546        let drawn = bars(&dl, panel.style.graph);
1547        let heights: Vec<f32> = drawn.iter().map(|(min, max)| max.y - min.y).collect();
1548        assert_eq!(
1549            heights,
1550            [
1551                MIN_BAR_HEIGHT,
1552                GRAPH_HEIGHT / 4.0,
1553                GRAPH_HEIGHT / 2.0,
1554                GRAPH_HEIGHT
1555            ],
1556            "0 is the baseline tick, 5 and 10 of 20 a quarter and a half, 40 clamped full",
1557        );
1558        for (min, max) in &drawn {
1559            assert_eq!(max.x - min.x, GRAPH_BAR_WIDTH);
1560            assert_eq!(max.y, drawn[0].1.y, "every bar stands on one baseline");
1561        }
1562        for pair in drawn.windows(2) {
1563            assert_eq!(pair[1].0.x, pair[0].1.x, "oldest first, side by side");
1564        }
1565        assert!(
1566            texts(&dl).iter().any(|text| text == "rtt graph"),
1567            "the graph's label is drawn: {:?}",
1568            texts(&dl)
1569        );
1570    }
1571
1572    /// A scale of zero — a graph of nothing yet measured — draws every bar
1573    /// as the baseline tick rather than dividing by it.
1574    #[test]
1575    fn a_graph_with_no_scale_draws_its_bars_empty() {
1576        let mut section = DebugSection::new("net");
1577        section.graph("rtt graph", [3.0, f32::MAX], 0.0);
1578        assert_eq!(section.graphs()[0].bars, [0.0, 0.0]);
1579    }
1580
1581    /// The graph's bars start in the value column, past every label, its own
1582    /// included: a long graph label pushes the values of the rows above it
1583    /// along.
1584    #[test]
1585    fn a_graph_label_counts_toward_the_value_column() {
1586        let atlas = FontAtlas::built_in();
1587        let mut panel = shown();
1588        panel.add(&Plot {
1589            samples: &[1.0],
1590            scale: 1.0,
1591        });
1592        let mut dl = DrawList::new();
1593        panel.render(&mut dl, screen(), &atlas);
1594        let scale = panel.style.font_size / NATURAL_FONT_SIZE;
1595        let widest = atlas.text_width("rtt graph", scale);
1596        let label_x = dl
1597            .commands()
1598            .iter()
1599            .find_map(|command| match command {
1600                DrawCommand::Text { pos, text, .. } if text == "rtt" => Some(pos.x),
1601                _ => None,
1602            })
1603            .expect("the row's label is drawn");
1604        let value_x = dl
1605            .commands()
1606            .iter()
1607            .find_map(|command| match command {
1608                DrawCommand::Text { pos, text, .. } if text == "12.0 ms" => Some(pos.x),
1609                _ => None,
1610            })
1611            .expect("the row's value is drawn");
1612        assert!(
1613            value_x >= label_x + widest,
1614            "the value at {value_x} sits under the {widest}px graph label at {label_x}",
1615        );
1616        let (bar_min, _) = bars(&dl, panel.style.graph)[0];
1617        assert_eq!(bar_min.x, value_x, "the bars start in the value column");
1618    }
1619
1620    /// Clearing a section drops its graphs with its rows, so a frame that
1621    /// plots nothing draws no bars from the last.
1622    #[test]
1623    fn clearing_a_section_drops_its_graphs() {
1624        let mut section = DebugSection::new("net");
1625        section.graph("a", [1.0], 1.0);
1626        assert!(!section.is_empty(), "a graph alone is something to draw");
1627        section.clear();
1628        assert!(section.graphs().is_empty());
1629        assert!(section.is_empty());
1630        section.graph("b", [0.5, 0.25], 1.0);
1631        assert_eq!(
1632            section.graphs(),
1633            [DebugGraph {
1634                label: "b".to_owned(),
1635                bars: vec![0.5, 0.25],
1636            }]
1637        );
1638    }
1639
1640    #[test]
1641    fn the_overlay_starts_hidden_unless_asked() {
1642        assert!(!DebugOverlay::new().is_visible());
1643        assert!(DebugOverlay::with_visible(true).is_visible());
1644        let mut overlay = DebugOverlay::with_visible(true);
1645        overlay.toggle();
1646        assert!(!overlay.is_visible());
1647        overlay.set_visible(true);
1648        assert!(overlay.is_visible());
1649    }
1650
1651    #[test]
1652    fn debug_format_covers_the_public_types() {
1653        let overlay = DebugOverlay::with_visible(true);
1654        let text = format!("{overlay:?}");
1655        assert!(text.contains("panel"), "{text}");
1656        assert!(text.contains("visible"), "{text}");
1657        assert_eq!(
1658            format!("{:?}", DebugRow::default()),
1659            "DebugRow { label: \"\", value: \"\" }"
1660        );
1661    }
1662}