Skip to main content

ssplayer_wgpu/
metrics.rs

1//! What a frame cost: counts that are always available, plus GPU pass time when
2//! the device supports timestamp queries.
3
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6
7/// What one frame of a [`crate::SSScene`] cost.
8///
9/// Counts are exact and always populated. `gpu_pass_time_ns` needs
10/// `Features::TIMESTAMP_QUERY` on the device and lags by a frame or two, so it
11/// is a profiling counter rather than this frame's number.
12#[derive(Clone, Copy, Debug, Default, PartialEq)]
13pub struct SceneStats {
14    /// Players that contributed geometry (hidden and culled ones do not).
15    pub players: u32,
16    /// Primitives in the frame's table — parts, shape fans and effect particles.
17    pub prims: u32,
18    /// Draw calls recorded.
19    pub draw_calls: u32,
20    /// Bytes written to the SoA arena, the primitive table and the mesh stream.
21    pub uploaded_bytes: u64,
22    /// Draw calls that could be folded into the one before them as they stand:
23    /// same pipeline, same texture, and a vertex range that carries straight on.
24    pub mergeable_draws: u32,
25    /// Texture bind-group sets that repeat the previous draw's texture.
26    pub redundant_texture_binds: u32,
27    /// Coverage bitmaps rasterised this frame — one per masking player, and one
28    /// more for each further 24 mask writers in its instance tree, each its own
29    /// render pass. Always zero under the stencil backend, which is the point
30    /// of having the number: it is what the coverage backend costs.
31    pub coverage_layers: u32,
32    /// Players drawn into a layer of their own this frame and folded back at
33    /// their alpha (see [`crate::SSScene::set_group_alpha`]) — each a render pass,
34    /// a target-sized layer, and a composite over the target.
35    pub group_layers: u32,
36    /// GPU time for the last render pass whose timestamps came back, in
37    /// nanoseconds. `None` until one has, or always without the feature.
38    pub gpu_pass_time_ns: Option<u64>,
39}
40
41/// Sentinel for "no measurement yet"; real durations never reach it.
42const NO_TIME: u64 = u64::MAX;
43
44/// GPU-side timing for one render target.
45///
46/// Times the render pass as a whole (`beginning_of_pass` / `end_of_pass`).
47/// Per-draw timing needs `TIMESTAMP_QUERY_INSIDE_PASSES`, which is native-only.
48pub(crate) struct GpuTimer {
49    /// Four slots: two pairs, used on alternate frames. See `resolve`.
50    query_set: wgpu::QuerySet,
51    /// `resolve_query_set` target. Cannot be mapped, hence the copy below.
52    resolve: wgpu::Buffer,
53    /// Mappable copy of `resolve`.
54    readback: wgpu::Buffer,
55    /// Nanoseconds per timestamp tick, from `Queue::get_timestamp_period`.
56    period_ns: f32,
57    /// Written by the map callback, read by `last_ns`.
58    last_ns: Arc<AtomicU64>,
59    /// Raised by the map callback to signal that a new sample arrived.
60    landed: Arc<AtomicBool>,
61    /// Which query pair the next pass writes.
62    pair: usize,
63    /// A pair written by an earlier frame, waiting to be resolved.
64    pending: Option<usize>,
65    /// A resolve was encoded and is waiting to be mapped.
66    resolved: bool,
67    /// A map is in flight; starting a second one on the same buffer is an error.
68    mapping: bool,
69}
70
71impl GpuTimer {
72    /// Build the timing resources, or `None` if the device was not created with
73    /// `Features::TIMESTAMP_QUERY`.
74    pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
75        if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
76            return None;
77        }
78        let query_set = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("SpriteStudio Frame Timer"), ty: wgpu::QueryType::Timestamp, count: 4 });
79        // Two u64 timestamps.
80        const BYTES: u64 = 16;
81        let resolve = device.create_buffer(&wgpu::BufferDescriptor { label: Some("SpriteStudio Timestamp Resolve"), size: BYTES, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
82        let readback = device.create_buffer(&wgpu::BufferDescriptor { label: Some("SpriteStudio Timestamp Readback"), size: BYTES, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
83        Some(Self { query_set, resolve, readback, period_ns: queue.get_timestamp_period(), last_ns: Arc::new(AtomicU64::new(NO_TIME)), landed: Arc::new(AtomicBool::new(false)), pair: 0, pending: None, resolved: false, mapping: false })
84    }
85
86    /// The timestamp writes a host attaches to its render pass descriptor.
87    pub(crate) fn writes(&self) -> wgpu::RenderPassTimestampWrites<'_> {
88        let base = (self.pair * 2) as u32;
89        wgpu::RenderPassTimestampWrites { query_set: &self.query_set, beginning_of_pass_write_index: Some(base), end_of_pass_write_index: Some(base + 1) }
90    }
91
92    /// Copy an **earlier** frame's timestamps somewhere the CPU can reach.
93    ///
94    /// Never this frame's: a pair resolved in the command buffer that wrote it
95    /// reads counters that have not retired. The two pairs alternate, so the
96    /// resolve encoded here reads one the GPU has already finished.
97    pub(crate) fn resolve(&mut self, encoder: &mut wgpu::CommandEncoder) {
98        if !self.mapping
99            && let Some(pair) = self.pending.take()
100        {
101            let base = (pair * 2) as u32;
102            encoder.resolve_query_set(&self.query_set, base..base + 2, &self.resolve, 0);
103            encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.readback, 0, self.readback.size());
104            self.resolved = true;
105        }
106        // Whatever the pass just wrote becomes the next candidate, and the next
107        // pass writes the other pair.
108        self.pending = Some(self.pair);
109        self.pair ^= 1;
110    }
111
112    /// Start reading back whatever the previous frame resolved. Call at the top
113    /// of a frame: at `resolve` time the host has not submitted the encoder yet.
114    pub(crate) fn poll(&mut self) {
115        if !self.resolved || self.mapping {
116            return;
117        }
118        self.resolved = false;
119        self.mapping = true;
120
121        let slot = Arc::clone(&self.last_ns);
122        let landed = Arc::clone(&self.landed);
123        let buffer = self.readback.clone();
124        let period = self.period_ns;
125        self.readback.slice(..).map_async(wgpu::MapMode::Read, move |result| {
126            if result.is_ok() {
127                let view = buffer.slice(..).get_mapped_range().expect("the read map just succeeded, and nothing else views it");
128                let mut ticks = [0u64; 2];
129                bytemuck::cast_slice_mut(&mut ticks).copy_from_slice(&view[..16]);
130                drop(view);
131                buffer.unmap();
132                // A backwards or absent pair means the driver dropped the query.
133                if let Some(delta) = ticks[1].checked_sub(ticks[0]) {
134                    slot.store((delta as f64 * period as f64) as u64, Ordering::Relaxed);
135                }
136            }
137            landed.store(true, Ordering::Release);
138        });
139    }
140
141    /// Clear the way for the next measurement once the in-flight map has landed.
142    pub(crate) fn settle(&mut self) {
143        if self.mapping && self.landed.swap(false, Ordering::Acquire) {
144            self.mapping = false;
145        }
146    }
147
148    pub(crate) fn last_ns(&self) -> Option<u64> {
149        match self.last_ns.load(Ordering::Relaxed) {
150            NO_TIME => None,
151            ns => Some(ns),
152        }
153    }
154}