Skip to main content

crcbl_frame/
timing.rs

1//! Per-pass GPU timestamps, and the frame-timing report they feed.
2//!
3//! Stage 2 §2.4's last bullet: "GPU timestamp per pass,
4//! exposed as a frame-timing report (feeds the stage 7 profiler HUD)". This is
5//! that, and it is wired into [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute)
6//! rather than bolted on, which is the stated reason (`docs/notes/backends.md`)
7//! for putting timestamp queries in the seam at P0: "a profiler bolted on
8//! afterwards is one that never covers the passes written before it".
9//!
10//! # The report is frames latent, on purpose
11//!
12//! Reading a timestamp the GPU has not written yet is either a stall or a lie.
13//! So the timers keep a ring of query sets — two more than the frames the loop
14//! keeps in flight — and resolve a slot only when it is about to come back
15//! round, by which point the submission that wrote it has certainly completed.
16//! The second spare slot is for [the statistics' reset](#a-statistics-set-is-reset-a-frame-ahead). The report is
17//! therefore about a frame a few frames ago, which is exactly what a profiler
18//! HUD wants and exactly the shape topic 03 §3.6
19//! calls for ("N frames latent").
20//!
21//! No fence, no wait, no `wait_idle`: the latency *is* the synchronisation.
22//!
23//! # Timestamps are the pass's own boundaries, and a copy pass has none
24//!
25//! The seam has no free-standing timestamp: two queries are named by the pass
26//! descriptor itself, as [`PassTimestampWrites`], and the backend takes them
27//! where the pass opens and closes. So the number reported for a pass is the
28//! pass alone, and the barriers the graph inserted around it are attributed to
29//! nothing. That is a narrower number than the one this reported before — the
30//! seam used to bracket each pass from before its barriers to after its close —
31//! and it is the only one every backend can produce, because Metal samples at
32//! stage boundaries and WebGPU only through `timestampWrites`.
33//!
34//! It also means a [`PassKind::Copy`](crate::graph::PassKind) pass is not
35//! timed at all: it opens no scope, so there is no boundary to sample at. Such a
36//! pass gets no query pair and **no row in the report**, rather than a row
37//! reading 0.000 ms that a reader would take for a measurement.
38//!
39//! # How many passes a ring slot holds
40//!
41//! Each slot is sized once, at [`PassTimers::new`], because a query set cannot
42//! grow and resizing one mid-frame would throw away the very submissions the
43//! ring is waiting on. So the capacity is a number the caller has to know before
44//! the first frame — and it is a fact about the renderers, not about the game.
45//! Each renderer carries a `MAX_PASSES`, [`UiRenderer::MAX_PASSES`] among them,
46//! and a caller passes the sum for the renderers its frame runs:
47//! `crcbl_render::MAX_TIMED_PASSES` is that sum for the engine's, and a frame
48//! that draws only a UI passes the UI pass's alone, plus any passes of its own.
49//!
50//! [`UiRenderer::MAX_PASSES`]: crate::ui_pass::UiRenderer::MAX_PASSES
51//!
52//! A frame with more passes than the capacity is timed as far as the capacity
53//! goes and the rest are dropped, with one warning. One, not one per frame: the
54//! condition holds for every frame once it holds for any, and this is a
55//! profiler.
56//!
57//! # Degrading, not breaking
58//!
59//! A device without [`Features::TIMESTAMP_QUERY`] cannot create a timestamp set.
60//! [`PassTimers::new`] reports that as `None`, the graph runs with no timers at
61//! all, and the report is empty. The seam says the same thing about
62//! [`PassTimestampWrites`] — accepted and dropped — because topic 10's browsers
63//! are where this actually happens.
64//!
65//! # What a pass did, when asked
66//!
67//! [`STATISTICS_VAR`] set to `1` makes the timers count each timed pass's work
68//! as well: one [`PassStatisticsWrites`] query per pass, in a statistics set
69//! beside each slot's timestamps, read back with them into
70//! [`PassTiming::statistics`]. Off by default, because a count is a question
71//! for a profiling run, not for every frame. A device without
72//! [`Features::PIPELINE_STATISTICS_QUERY`] reports none, and the timings carry
73//! on without them.
74//!
75//! # A statistics set is reset a frame ahead
76//!
77//! Each frame reads the slot the *next* frame will write, and resets its
78//! statistics set in this frame's command buffer, so a slot's counts are reset
79//! a whole submission before any pass is counted into them. Resetting in the
80//! same command buffer as the passes is what the seam allows, and on AMD's
81//! Windows Vulkan driver (25.10.36 on the RX 7900 XTX, 25.10.42 on the Raphael
82//! iGPU, measured 2026-10-28) it loses counts: the reset lands after some of the
83//! first passes' queries, which then read as never written — up to 27 of
84//! lantern's 90 passes on the iGPU, and none once the reset moved a frame ahead.
85//! The timestamps' reset stays where it was, since no driver here loses them.
86
87use core::fmt::Write as _;
88
89use crcbl_hal::{
90    CommandEncoder, Device, Features, PassStatisticsWrites, PassTimestampWrites,
91    PipelineStatistics, QueryKind, QuerySetDesc, QuerySetHandle,
92};
93use crcbl_ui::debug::{DebugModule, DebugSection};
94
95use crate::graph::{CompiledPass, PassKind};
96
97/// What one pass cost on the GPU.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct PassTiming {
100    /// The pass's label, as it appears in the graph dump and in captures.
101    pub label: String,
102    /// When the pass began, in nanoseconds on the GPU's timestamp clock: where
103    /// a timeline puts it, comparable with every other pass's but not with a
104    /// CPU time.
105    pub begin_nanos: u64,
106    /// Nanoseconds between pass boundaries, including inter-stage scheduling
107    /// gaps. These intervals can overlap on a pipelined GPU.
108    pub gpu_nanos: u64,
109    /// What the GPU counted over the pass, when [`STATISTICS_VAR`] asked for
110    /// it and the device can count.
111    pub statistics: Option<PipelineStatistics>,
112}
113
114/// The variable that makes [`PassTimers`] count each pass's work, with `1`.
115pub const STATISTICS_VAR: &str = "CRCBL_PASS_STATISTICS";
116
117/// Whether [`STATISTICS_VAR`] asks for the counts: `1` and nothing else, as
118/// `CRCBL_VK_SHADER_STATS` reads.
119fn statistics_wanted(value: Option<&str>) -> bool {
120    value.map(str::trim) == Some("1")
121}
122
123/// Whether this process's [`STATISTICS_VAR`] asks [`PassTimers::new`] to count
124/// each pass's work; a device that cannot count still only times them.
125#[must_use]
126pub fn statistics_requested() -> bool {
127    statistics_wanted(std::env::var(STATISTICS_VAR).ok().as_deref())
128}
129
130/// A pass's counts as report columns: each stage the device counted, by a
131/// short name, and nothing for a stage it could not.
132///
133/// What [`FrameTimings::report`] and `crcbl_render::PassStats`' report both
134/// print after a pass's time.
135#[must_use]
136pub fn statistics_columns(statistics: &PipelineStatistics) -> String {
137    let columns = [
138        ("ia-vtx", statistics.input_vertices),
139        ("ia-prim", statistics.input_primitives),
140        ("vs", statistics.vertex_invocations),
141        ("clip", statistics.clipper_invocations),
142        ("clip-out", statistics.clipper_primitives),
143        ("fs", statistics.fragment_invocations),
144        ("cs", statistics.compute_invocations),
145        ("task", statistics.task_invocations),
146        ("mesh", statistics.mesh_invocations),
147        ("mesh-prim", statistics.mesh_primitives),
148    ];
149    let mut out = String::new();
150    for (name, count) in columns {
151        if let Some(count) = count {
152            if !out.is_empty() {
153                out.push(' ');
154            }
155            let _ = write!(out, "{name} {count}");
156        }
157    }
158    out
159}
160
161/// A whole frame's per-pass costs.
162#[derive(Clone, Debug, Default, PartialEq, Eq)]
163pub struct FrameTimings {
164    /// One entry per pass, in execution order.
165    pub passes: Vec<PassTiming>,
166    /// Which frame these came from — a few frames behind the one being
167    /// recorded; see the module docs.
168    pub frame: u64,
169    /// Elapsed interval from the earliest measured pass start to the latest
170    /// measured pass end. Includes gaps/contention, but not untimed work before
171    /// or after those boundaries. `None` means the timestamps were incomplete
172    /// or invalid; it must not be replaced with a sum of overlapping spans.
173    pub elapsed_nanos: Option<u64>,
174}
175
176impl FrameTimings {
177    /// The sum of every pass's elapsed span.
178    ///
179    /// This double-counts overlapping stages and includes scheduling gaps.
180    /// It is neither frame duration nor active GPU time. See `elapsed_nanos`
181    /// for the outer measured interval.
182    #[must_use]
183    pub fn total_nanos(&self) -> u64 {
184        self.passes.iter().map(|pass| pass.gpu_nanos).sum()
185    }
186
187    /// Whether anything was measured at all.
188    #[must_use]
189    pub fn is_empty(&self) -> bool {
190        self.passes.is_empty()
191    }
192
193    /// The report, as text.
194    ///
195    /// The other half of the graph's "explain itself" obligation: the dump says
196    /// what the frame *is* and this says what it *cost*.
197    #[must_use]
198    pub fn report(&self) -> String {
199        if self.passes.is_empty() {
200            return "frame timing: no GPU timestamps (the device has none)\n".to_string();
201        }
202        let mut out = String::new();
203        let total = self.total_nanos();
204        let _ = writeln!(
205            out,
206            "frame timing (frame {}): {} pass(es), {:.3} ms sum of pass spans",
207            self.frame,
208            self.passes.len(),
209            total as f64 / 1.0e6
210        );
211        if let Some(elapsed) = self.elapsed_nanos {
212            let _ = writeln!(
213                out,
214                "  measured GPU elapsed: {:.3} ms",
215                elapsed as f64 / 1.0e6
216            );
217        }
218        for pass in &self.passes {
219            let share = if total == 0 {
220                0.0
221            } else {
222                pass.gpu_nanos as f64 * 100.0 / total as f64
223            };
224            let _ = write!(
225                out,
226                "  {:<24} {:>9.3} ms  {:>5.1}%",
227                pass.label,
228                pass.gpu_nanos as f64 / 1.0e6,
229                share
230            );
231            if let Some(statistics) = &pass.statistics {
232                let _ = write!(out, "  {}", statistics_columns(statistics));
233            }
234            out.push('\n');
235        }
236        out
237    }
238}
239
240/// The renderer's contribution to the debug overlay.
241///
242/// The UI plan's first profiler surface (debug item 1 in `docs/notes/tooling.md`) was "stage 2/3 GPU pass
243/// timestamps"; this is the adapter that puts them there. It lives here, not in
244/// `crcbl-ui`, because the overlay is not allowed to know that a render pass
245/// exists — the module is contributed by the system it reports on. `crcbl-render`
246/// already depends on `crcbl-ui` (it owns the UI pass), so this is the direction
247/// the dependency already runs.
248///
249/// Every row is a number [`PassTimers`] resolved from a timestamp query. No row
250/// is derived from anything else, and there is no CPU number here: this struct
251/// measures the GPU and says so.
252impl DebugModule for FrameTimings {
253    fn debug_section(&self, out: &mut DebugSection) {
254        out.set_title("gpu");
255        if self.passes.is_empty() {
256            // Reached when the device has timers but the ring has not come round
257            // yet — the report is deliberately frames latent. A device with no
258            // timestamps at all has no `PassTimers`, so the caller adds no
259            // section.
260            out.row_str("timings", "pending");
261            return;
262        }
263        for pass in &self.passes {
264            out.row(
265                &pass.label,
266                format_args!("{:.3} ms", pass.gpu_nanos as f64 / 1.0e6),
267            );
268        }
269        out.row(
270            "span sum",
271            format_args!("{:.3} ms", self.total_nanos() as f64 / 1.0e6),
272        );
273        if let Some(elapsed) = self.elapsed_nanos {
274            out.row("elapsed", format_args!("{:.3} ms", elapsed as f64 / 1.0e6));
275        }
276        out.row("frame", format_args!("{}", self.frame));
277    }
278}
279
280#[derive(Debug)]
281struct Slot {
282    set: QuerySetHandle,
283    /// One statistics query per timed pass, when [`STATISTICS_VAR`] asked for
284    /// them; see the module docs.
285    statistics: Option<QuerySetHandle>,
286    /// The labels recorded into this slot, or empty if it has never been used.
287    labels: Vec<String>,
288    /// Which frame number was recorded into it.
289    frame: u64,
290}
291
292/// A ring of timestamp query sets, one per frame in flight plus two; see the
293/// module docs.
294#[derive(Debug)]
295pub struct PassTimers {
296    slots: Vec<Slot>,
297    current: usize,
298    /// Which query pair each pass of the frame being recorded was given, indexed
299    /// by its position in the frame. `None` for a pass that is not timed. Built
300    /// by [`PassTimers::begin_frame`] and read by
301    /// [`PassTimers::pass_writes`] as the graph walks the same list.
302    pairs: Vec<Option<u32>>,
303    capacity: u32,
304    frames: u64,
305    latest: FrameTimings,
306    /// Whether a frame with more passes than [`PassTimers::capacity`] has
307    /// already been reported. The condition holds for every frame once it holds
308    /// for one, and a line per frame forever is a line nobody reads.
309    warned: bool,
310}
311
312impl PassTimers {
313    /// Creates timers for up to `max_passes` passes across `frames_in_flight`
314    /// frames, or `None` if the device has no timestamp queries.
315    ///
316    /// `max_passes` is the sum of the `MAX_PASSES` of the renderers the frame
317    /// runs, plus the caller's own passes — see the module docs. A frame longer than it is timed as far as it goes.
318    ///
319    /// `None` is not an error: the seam is explicit that timestamps degrade
320    /// rather than break, and the caller's answer is to pass `None` to
321    /// [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute) and get
322    /// an empty report.
323    ///
324    /// The passes are counted as well when [`STATISTICS_VAR`] is `1`; see
325    /// [`PassTimers::counting`].
326    #[must_use]
327    pub fn new(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
328        Self::create(device, frames_in_flight, max_passes, statistics_requested())
329    }
330
331    /// [`PassTimers::new`], counting each timed pass's work whatever
332    /// [`STATISTICS_VAR`] says: what a profiler that asks for the counts
333    /// itself creates. On a device without
334    /// [`Features::PIPELINE_STATISTICS_QUERY`] the passes are timed and not
335    /// counted, as under the variable.
336    #[must_use]
337    pub fn counting(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
338        Self::create(device, frames_in_flight, max_passes, true)
339    }
340
341    fn create(
342        device: &dyn Device,
343        frames_in_flight: usize,
344        max_passes: u32,
345        counted: bool,
346    ) -> Option<Self> {
347        if !device.caps().features.contains(Features::TIMESTAMP_QUERY) {
348            crcbl_core::log::debug!(
349                "graph: no TIMESTAMP_QUERY on this device; per-pass timing is off"
350            );
351            return None;
352        }
353        // Two queries per pass, and the query index is a `u32` — so a capacity
354        // above half the range would overflow every `capacity * 2` below and
355        // reset a range shorter than the one it wrote.
356        let Some(query_count) = max_passes.checked_mul(2) else {
357            crcbl_core::log::debug!(
358                "graph: {max_passes} passes needs {} timestamp queries, more than a u32 index \
359                 holds; per-pass timing is off",
360                u64::from(max_passes) * 2
361            );
362            return None;
363        };
364        let counted = counted && {
365            let able = device
366                .caps()
367                .features
368                .contains(Features::PIPELINE_STATISTICS_QUERY);
369            if !able {
370                crcbl_core::log::info!(
371                    "graph: passes were to be counted and this device has no \
372                     PIPELINE_STATISTICS_QUERY; they are timed, not counted"
373                );
374            }
375            able
376        };
377        // Two more than the frames in flight, so the slot after the one being
378        // written is always one whose submission has completed: it is read,
379        // and its statistics reset, a frame before it is reused.
380        let count = frames_in_flight + 2;
381        let mut slots: Vec<Slot> = Vec::with_capacity(count);
382        let refused = |slots: &[Slot], what: &str, index: usize, error: crcbl_hal::HalError| {
383            crcbl_core::log::debug!("graph: {what} set {index} refused ({error}); timing is off");
384            for slot in slots {
385                device.destroy_query_set(slot.set);
386                if let Some(statistics) = slot.statistics {
387                    device.destroy_query_set(statistics);
388                }
389            }
390        };
391        for index in 0..count {
392            let set = match device.create_query_set(&QuerySetDesc {
393                label: Some("graph pass timers"),
394                kind: QueryKind::Timestamp,
395                // Two per pass: one before its barriers, one after it closes.
396                count: query_count,
397            }) {
398                Ok(set) => set,
399                Err(error) => {
400                    refused(&slots, "timestamp", index, error);
401                    return None;
402                }
403            };
404            let statistics = if counted {
405                match device.create_query_set(&QuerySetDesc {
406                    label: Some("graph pass statistics"),
407                    kind: QueryKind::PipelineStatistics,
408                    count: max_passes,
409                }) {
410                    Ok(statistics) => Some(statistics),
411                    Err(error) => {
412                        device.destroy_query_set(set);
413                        refused(&slots, "statistics", index, error);
414                        return None;
415                    }
416                }
417            } else {
418                None
419            };
420            slots.push(Slot {
421                set,
422                statistics,
423                labels: Vec::new(),
424                frame: 0,
425            });
426        }
427        Some(Self {
428            slots,
429            current: 0,
430            pairs: Vec::new(),
431            capacity: max_passes,
432            frames: 0,
433            latest: FrameTimings::default(),
434            warned: false,
435        })
436    }
437
438    /// The most recent frame whose timestamps have actually landed.
439    ///
440    /// Empty until the ring has come round once.
441    #[must_use]
442    pub fn latest(&self) -> &FrameTimings {
443        &self.latest
444    }
445
446    /// How many passes these timers can bracket.
447    #[must_use]
448    pub const fn capacity(&self) -> u32 {
449        self.capacity
450    }
451
452    /// Starts a frame: resolves the slot the next frame reuses, and resets the
453    /// timestamps of the one this frame writes and the statistics of the next.
454    ///
455    /// Called by the graph; a caller never has to.
456    pub(crate) fn begin_frame(
457        &mut self,
458        device: &dyn Device,
459        encoder: &mut dyn CommandEncoder,
460        passes: &[CompiledPass<'_>],
461    ) {
462        self.frames += 1;
463        self.current = (self.current + 1) % self.slots.len();
464        let next = (self.current + 1) % self.slots.len();
465
466        // The next slot is about to come round: whatever was recorded into it
467        // belongs to a frame that has completed, so reading it neither stalls
468        // nor lies. The current slot was read when it was the next.
469        self.resolve(device, next);
470
471        // A copy pass opens no scope, so it has no boundary a backend could
472        // sample at and gets no query pair. Everything below counts *timed*
473        // passes for that reason, including the warning.
474        let timeable = passes
475            .iter()
476            .filter(|pass| pass.kind() != PassKind::Copy)
477            .count();
478        let used = timeable.min(self.capacity as usize);
479        if timeable > used && !self.warned {
480            self.warned = true;
481            crcbl_core::log::warn!(
482                "graph: {timeable} timed passes but timers hold {}; the last {} are untimed (said \
483                 once)",
484                self.capacity,
485                timeable - used
486            );
487        }
488        let slot = &mut self.slots[self.current];
489        slot.labels.clear();
490        self.pairs.clear();
491        for pass in passes {
492            let pair = if pass.kind() == PassKind::Copy {
493                None
494            } else {
495                let next = u32::try_from(slot.labels.len()).unwrap_or(u32::MAX);
496                (next < self.capacity).then(|| {
497                    slot.labels.push(pass.label().to_string());
498                    next
499                })
500            };
501            self.pairs.push(pair);
502        }
503        slot.frame = self.frames;
504        // Vulkan requires a reset before every write; the seam makes callers
505        // always do it so the Vulkan path is never the special case.
506        encoder.reset_query_set(slot.set, 0..self.capacity.saturating_mul(2));
507        // A slot's statistics are reset by the frame before it, see the module
508        // docs; the first frame has no frame before it.
509        let ahead = self.slots[next].statistics;
510        let behind = self.slots[self.current]
511            .statistics
512            .filter(|_| self.frames == 1);
513        for statistics in behind.into_iter().chain(ahead) {
514            encoder.reset_query_set(statistics, 0..self.capacity);
515        }
516    }
517
518    /// The two queries pass `index` of this frame is bracketed by, or `None`
519    /// when it is not timed — a copy pass, or one past the ring's capacity.
520    ///
521    /// **What the graph puts in the pass descriptor.** There is no call to
522    /// record: the backend takes both samples where the pass opens and closes.
523    pub(crate) fn pass_writes(&self, index: usize) -> Option<PassTimestampWrites> {
524        let pair = *self.pairs.get(index)?;
525        pair.map(|pair| PassTimestampWrites {
526            set: self.slots[self.current].set,
527            beginning_of_pass: pair * 2,
528            end_of_pass: pair * 2 + 1,
529        })
530    }
531
532    /// The statistics query pass `index` of this frame is counted into, or
533    /// `None` when passes are not counted or this one is not timed.
534    ///
535    /// The pass's timestamp pair has the same index, so a pass is counted
536    /// exactly when it is timed.
537    pub(crate) fn pass_statistics(&self, index: usize) -> Option<PassStatisticsWrites> {
538        let pair = (*self.pairs.get(index)?)?;
539        let set = self.slots[self.current].statistics?;
540        Some(PassStatisticsWrites { set, query: pair })
541    }
542
543    fn resolve(&mut self, device: &dyn Device, index: usize) {
544        let slot = &self.slots[index];
545        if slot.labels.is_empty() {
546            return;
547        }
548        // Nanoseconds, not ticks: `Device::query_results` converts inside the
549        // backend, where the scale is something the API actually reports.
550        let mut nanos = vec![0u64; slot.labels.len() * 2];
551        if let Err(error) = device.query_results(slot.set, 0, &mut nanos) {
552            crcbl_core::log::debug!(
553                "graph: timestamp read failed ({error}); dropping this frame's timing"
554            );
555            return;
556        }
557        // The counts are extra, so a failed read drops them and keeps the
558        // times.
559        let counts = slot.statistics.and_then(|set| {
560            let mut counts = vec![PipelineStatistics::default(); slot.labels.len()];
561            match device.pipeline_statistics(set, 0, &mut counts) {
562                Ok(()) => Some(counts),
563                Err(error) => {
564                    crcbl_core::log::debug!(
565                        "graph: statistics read failed ({error}); this frame is timed, not \
566                         counted"
567                    );
568                    None
569                }
570            }
571        });
572        let passes = slot
573            .labels
574            .iter()
575            .enumerate()
576            .map(|(index, label)| {
577                // `saturating_sub` rather than an assert: a device whose
578                // timestamps are unsupported writes zeros, and a zero-length
579                // pass is a more useful report than a panic in a profiler.
580                PassTiming {
581                    label: label.clone(),
582                    begin_nanos: nanos[index * 2],
583                    gpu_nanos: nanos[index * 2 + 1].saturating_sub(nanos[index * 2]),
584                    statistics: counts.as_ref().map(|counts| counts[index]),
585                }
586            })
587            .collect();
588        self.latest = FrameTimings {
589            passes,
590            frame: slot.frame,
591            elapsed_nanos: measured_span(&nanos),
592        };
593    }
594
595    /// Releases the query sets. Call after the device is idle.
596    pub fn destroy(&mut self, device: &dyn Device) {
597        for slot in &self.slots {
598            device.destroy_query_set(slot.set);
599            if let Some(statistics) = slot.statistics {
600                device.destroy_query_set(statistics);
601            }
602        }
603        self.slots.clear();
604    }
605}
606
607/// Reject incomplete pairs rather than manufacturing a plausible budget value.
608fn measured_span(nanos: &[u64]) -> Option<u64> {
609    if nanos.is_empty() || !nanos.len().is_multiple_of(2) {
610        return None;
611    }
612    let mut first = u64::MAX;
613    let mut last = 0;
614    for pair in nanos.as_chunks::<2>().0 {
615        let (start, end) = (pair[0], pair[1]);
616        if start == 0 || end < start {
617            return None;
618        }
619        first = first.min(start);
620        last = last.max(end);
621    }
622    Some(last - first)
623}
624
625// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
626#[cfg(all(test, not(target_arch = "wasm32")))]
627mod tests {
628    use super::*;
629
630    #[test]
631    fn overlapping_passes_measure_the_outer_interval_not_their_sum() {
632        assert_eq!(measured_span(&[100, 500, 200, 900]), Some(800));
633        assert_eq!(measured_span(&[100, 200, 400, 700]), Some(600));
634        assert_eq!(measured_span(&[500, 500]), Some(0));
635    }
636
637    #[test]
638    fn a_missing_or_backwards_timestamp_cannot_supply_a_budget() {
639        for values in [
640            &[][..],
641            &[100][..],
642            &[0, 200][..],
643            &[100, 0][..],
644            &[200, 100][..],
645        ] {
646            assert_eq!(measured_span(values), None);
647        }
648        assert_eq!(measured_span(&[100, 200, 0, 400]), None);
649    }
650
651    #[test]
652    fn an_empty_report_says_so_rather_than_printing_nothing() {
653        let timings = FrameTimings::default();
654        assert!(timings.is_empty());
655        assert_eq!(timings.total_nanos(), 0);
656        assert!(timings.report().contains("no GPU timestamps"));
657    }
658
659    #[test]
660    fn the_report_lists_every_pass_with_its_share() {
661        let timings = FrameTimings {
662            elapsed_nanos: None,
663            frame: 42,
664            passes: vec![
665                PassTiming {
666                    label: "forward".to_string(),
667                    begin_nanos: 0,
668                    gpu_nanos: 3_000_000,
669                    statistics: None,
670                },
671                PassTiming {
672                    label: "tonemap".to_string(),
673                    begin_nanos: 0,
674                    gpu_nanos: 1_000_000,
675                    statistics: None,
676                },
677            ],
678        };
679        assert_eq!(timings.total_nanos(), 4_000_000);
680        let report = timings.report();
681        assert!(report.contains("frame 42"), "{report}");
682        assert!(report.contains("forward"), "{report}");
683        assert!(report.contains("tonemap"), "{report}");
684        assert!(report.contains("4.000 ms"), "{report}");
685        assert!(
686            report.contains("75.0%"),
687            "the shares must be there: {report}"
688        );
689        assert!(report.contains("25.0%"), "{report}");
690    }
691
692    /// **The counts follow the time, stage by stage, and a stage the device
693    /// could not count is left out** rather than printed as a zero a reader
694    /// would take for no work.
695    #[test]
696    fn a_counted_pass_reports_the_stages_it_counted() {
697        let statistics = PipelineStatistics {
698            vertex_invocations: Some(3),
699            fragment_invocations: Some(788),
700            task_invocations: Some(0),
701            mesh_invocations: None,
702            ..PipelineStatistics::default()
703        };
704        assert_eq!(statistics_columns(&statistics), "vs 3 fs 788 task 0");
705        assert_eq!(statistics_columns(&PipelineStatistics::default()), "");
706
707        let timings = FrameTimings {
708            elapsed_nanos: None,
709            frame: 3,
710            passes: vec![
711                PassTiming {
712                    label: "depth".to_string(),
713                    begin_nanos: 0,
714                    gpu_nanos: 1_000_000,
715                    statistics: Some(statistics),
716                },
717                PassTiming {
718                    label: "tonemap".to_string(),
719                    begin_nanos: 0,
720                    gpu_nanos: 1_000_000,
721                    statistics: None,
722                },
723            ],
724        };
725        let report = timings.report();
726        let depth = report
727            .lines()
728            .find(|line| line.contains("depth"))
729            .expect("a depth row");
730        assert!(depth.ends_with("  vs 3 fs 788 task 0"), "{report}");
731        let tonemap = report
732            .lines()
733            .find(|line| line.contains("tonemap"))
734            .expect("a tonemap row");
735        assert!(
736            tonemap.ends_with('%'),
737            "an uncounted pass has no columns: {report}"
738        );
739    }
740
741    /// `1` turns the counts on and nothing else does, as
742    /// `CRCBL_VK_SHADER_STATS` reads.
743    #[test]
744    fn only_a_one_asks_for_the_counts() {
745        assert!(statistics_wanted(Some("1")));
746        assert!(statistics_wanted(Some(" 1 ")));
747        for value in [None, Some(""), Some("0"), Some("true"), Some("yes")] {
748            assert!(!statistics_wanted(value), "{value:?}");
749        }
750    }
751
752    /// A frame in which every pass measured zero must not divide by zero.
753    #[test]
754    fn a_zero_length_frame_reports_zero_shares_rather_than_nan() {
755        let timings = FrameTimings {
756            elapsed_nanos: None,
757            frame: 1,
758            passes: vec![PassTiming {
759                label: "clear".to_string(),
760                begin_nanos: 0,
761                gpu_nanos: 0,
762                statistics: None,
763            }],
764        };
765        let report = timings.report();
766        assert!(!report.contains("NaN"), "{report}");
767        assert!(report.contains("0.0%"), "{report}");
768    }
769
770    /// **The numbers on the overlay are the renderer's own.** Every pass the
771    /// timers resolved appears as a row, with the label the graph gave it and
772    /// the milliseconds its own nanoseconds convert to — and the whole thing
773    /// reaches the draw list, not just the section.
774    #[test]
775    fn the_debug_section_carries_the_passes_the_renderer_reported() {
776        use crcbl_ui::debug::{DebugOverlay, DebugRow};
777        use crcbl_ui::draw_list::{DrawCommand, DrawList};
778        use crcbl_ui::text::FontAtlas;
779        use glam::Vec2;
780
781        let timings = FrameTimings {
782            elapsed_nanos: None,
783            frame: 7,
784            passes: vec![
785                PassTiming {
786                    label: "sprites".to_string(),
787                    begin_nanos: 0,
788                    gpu_nanos: 2_500_000,
789                    statistics: None,
790                },
791                PassTiming {
792                    label: "ui".to_string(),
793                    begin_nanos: 0,
794                    gpu_nanos: 250_000,
795                    statistics: None,
796                },
797            ],
798        };
799
800        let mut section = DebugSection::default();
801        timings.debug_section(&mut section);
802        assert_eq!(section.title(), "gpu");
803        let rows: Vec<(&str, &str)> = section
804            .rows()
805            .iter()
806            .map(|DebugRow { label, value }| (label.as_str(), value.as_str()))
807            .collect();
808        assert_eq!(
809            rows,
810            [
811                ("sprites", "2.500 ms"),
812                ("ui", "0.250 ms"),
813                ("span sum", "2.750 ms"),
814                ("frame", "7"),
815            ],
816        );
817
818        // And through the panel: the same strings land in the draw list under
819        // the frame section, in the order the modules were added.
820        let mut overlay = DebugOverlay::with_visible(true);
821        overlay.record(core::time::Duration::from_millis(16));
822        overlay.begin_frame();
823        overlay.add(&timings);
824        let mut dl = DrawList::new();
825        overlay.render(&mut dl, Vec2::new(1280.0, 720.0), &FontAtlas::built_in());
826
827        let drawn: Vec<&str> = dl
828            .commands()
829            .iter()
830            .filter_map(|command| match command {
831                DrawCommand::Text { text, .. } => Some(text.as_str()),
832                _ => None,
833            })
834            .collect();
835        assert_eq!(drawn.first(), Some(&"frame"), "{drawn:?}");
836        let gpu = drawn
837            .iter()
838            .position(|text| *text == "gpu")
839            .expect("the gpu section is drawn");
840        assert_eq!(
841            &drawn[gpu..],
842            [
843                "gpu", "sprites", "2.500 ms", "ui", "0.250 ms", "span sum", "2.750 ms", "frame",
844                "7",
845            ],
846        );
847    }
848
849    /// A device that has timers but has not resolved a frame yet says so rather
850    /// than reporting a 0.000 ms frame that never ran.
851    #[test]
852    fn a_latent_report_renders_as_pending_rather_than_zero() {
853        let mut section = DebugSection::default();
854        FrameTimings::default().debug_section(&mut section);
855        assert_eq!(section.title(), "gpu");
856        assert_eq!(section.rows().len(), 1);
857        assert_eq!(section.rows()[0].value, "pending");
858    }
859
860    /// The device this runs against has no timestamp queries, so the whole
861    /// subsystem must decline rather than fail.
862    #[test]
863    fn a_device_without_timestamps_gets_no_timers_and_no_error() {
864        use crcbl_hal::null::NullInstance;
865        use crcbl_hal::{DeviceDesc, Instance};
866
867        let instance = NullInstance::portable();
868        let adapter = instance.adapters().remove(0);
869        let device = instance
870            .create_device(&DeviceDesc {
871                label: None,
872                adapter: adapter.id,
873                required_features: Features::empty(),
874                optional_features: Features::empty(),
875                compatible_surface: None,
876            })
877            .expect("the null backend always opens");
878        assert!(
879            !device.caps().features.contains(Features::TIMESTAMP_QUERY),
880            "this test is only meaningful against a device that has none"
881        );
882        assert!(
883            PassTimers::new(device.as_ref(), 2, 8).is_none(),
884            "timers must decline rather than fail"
885        );
886    }
887}