Skip to main content

viewport_lib/renderer/
stats.rs

1//! Per-frame performance counters for the viewport renderer.
2
3/// Controls the renderer's internal default behavior.
4///
5/// The host application owns playback state, time, and scene content.
6/// `RuntimeMode` tells the renderer what workload to expect so it can adjust
7/// internal defaults (e.g. picking rate) accordingly.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub enum RuntimeMode {
11    /// Prioritize responsiveness and picking accuracy.
12    #[default]
13    Interactive,
14    /// Prioritize steady frame pacing; picking may be throttled.
15    Playback,
16    /// Restore full quality; picking runs at full rate.
17    Paused,
18    /// Full-quality render intended for screenshot or export workflows.
19    ///
20    /// Forces `render_scale` to `max_render_scale` for the duration of the frame
21    /// and suppresses all pass-level degradation regardless of `missed_budget`.
22    /// The adaptation controller is paused; render scale resumes from
23    /// `max_render_scale` on the next non-Capture frame.
24    ///
25    /// Note: blocking until GPU work is complete (for pixel readback) is the
26    /// caller's responsibility. This mode ensures full-quality CPU-side decisions
27    /// only; it does not insert any GPU synchronisation inside the renderer.
28    Capture,
29}
30
31/// A coarse quality tier for [`PerformancePolicy`].
32///
33/// When `PerformancePolicy::preset` is `Some`, the renderer derives render scale
34/// bounds and pass-level degradation flags from the preset instead of the individual
35/// policy fields. The individual fields are still persisted so that switching back
36/// to `None` restores the previous custom configuration.
37///
38/// `target_fps` and `allow_dynamic_resolution` are always taken from the policy
39/// fields regardless of the preset.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub enum QualityPreset {
43    /// Native resolution, all passes enabled, no degradation allowed.
44    ///
45    /// Equivalent to `min_render_scale = 1.0`, `max_render_scale = 1.0`,
46    /// all `allow_*` flags false.
47    High,
48    /// Render scale [0.75, 1.0]; shadow reduction and effect throttling allowed.
49    ///
50    /// Equivalent to `min_render_scale = 0.75`, `max_render_scale = 1.0`,
51    /// `allow_shadow_reduction = true`, `allow_effect_throttling = true`.
52    Medium,
53    /// Render scale [0.5, 0.75]; all degradation paths allowed.
54    ///
55    /// Equivalent to `min_render_scale = 0.5`, `max_render_scale = 0.75`,
56    /// all `allow_*` flags true.
57    Low,
58}
59
60/// Controls what quality reductions the viewport is allowed to apply under load.
61///
62/// Set once via [`crate::ViewportRenderer::set_performance_policy`]. The internal
63/// adaptation controller reads `target_fps` and adjusts render scale within
64/// `[min_render_scale, max_render_scale]` when `allow_dynamic_resolution` is true.
65///
66/// Pass-specific flags (`allow_shadow_reduction`, `allow_volume_quality_reduction`,
67/// `allow_effect_throttling`) gate concrete quality reductions that kick in when
68/// the previous frame missed the target budget, applied in order via a tiered
69/// degradation ladder (render scale first, then shadows, then volumes, then effects).
70///
71/// Set `preset` to a [`QualityPreset`] to configure bounds and flags as a unit.
72#[derive(Debug, Clone, Copy, PartialEq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
74pub struct PerformancePolicy {
75    /// Coarse quality tier. When `Some`, overrides `min_render_scale`,
76    /// `max_render_scale`, and all `allow_*` flags for the duration of the frame.
77    /// Set to `None` to use the individual fields directly.
78    pub preset: Option<QualityPreset>,
79    /// Target frames per second. `None` means uncapped; `missed_budget` is always `false`.
80    pub target_fps: Option<f32>,
81    /// Lower bound for dynamic render scale (e.g. 0.5 = half resolution).
82    ///
83    /// Ignored when `preset` is `Some`; the preset's bounds are used instead.
84    pub min_render_scale: f32,
85    /// Upper bound for dynamic render scale (1.0 = native).
86    ///
87    /// Ignored when `preset` is `Some`; the preset's bounds are used instead.
88    pub max_render_scale: f32,
89    /// Allow the viewport to adjust render scale automatically when budget is exceeded.
90    ///
91    /// When `false`, the internal controller is inactive and render scale can be
92    /// set manually via [`crate::ViewportRenderer::set_render_scale`].
93    ///
94    /// The controller uses `FrameStats::gpu_frame_ms` as the cost signal when GPU
95    /// timestamp queries are available (excludes vsync wait). When GPU timestamps are
96    /// unavailable it falls back to `total_frame_ms`, which reflects wall-clock frame
97    /// duration and correctly fires over-budget at low frame rates.
98    ///
99    /// Works in both the LDR path (`paint_to` / `paint_viewport`) and the HDR
100    /// path (`render` / `render_viewport`). In HDR mode, the scene textures
101    /// (HDR colour, depth, bloom, SSAO, DoF, etc.) are allocated at
102    /// `render_scale * resolution`; the tone-map pass upscales to native
103    /// resolution. `FrameStats::render_scale` reflects the actual scale in both
104    /// modes.
105    pub allow_dynamic_resolution: bool,
106    /// Allow the viewport to skip the shadow pass under load.
107    ///
108    /// When `true` and the previous frame exceeded the target budget, the shadow depth
109    /// pass is skipped entirely. Shadows reappear as soon as the frame is within budget.
110    /// Ignored when `preset` is `Some`.
111    pub allow_shadow_reduction: bool,
112    /// Allow the viewport to reduce volume raymarch quality under load.
113    ///
114    /// When `true` and the previous frame exceeded the target budget, the per-volume
115    /// step size is doubled (half the number of samples), reducing GPU cost at the
116    /// cost of coarser volume appearance. Ignored when `preset` is `Some`.
117    pub allow_volume_quality_reduction: bool,
118    /// Allow the viewport to skip non-essential HDR effect passes under load.
119    ///
120    /// When `true` and the previous frame exceeded the target budget, the SSAO,
121    /// contact shadow, and bloom passes are skipped for that frame.
122    /// Ignored when `preset` is `Some`.
123    pub allow_effect_throttling: bool,
124}
125
126impl Default for PerformancePolicy {
127    fn default() -> Self {
128        Self {
129            preset: None,
130            target_fps: None,
131            min_render_scale: 0.5,
132            max_render_scale: 1.0,
133            allow_dynamic_resolution: false,
134            allow_shadow_reduction: false,
135            allow_volume_quality_reduction: false,
136            allow_effect_throttling: false,
137        }
138    }
139}
140
141/// Per-frame rendering statistics returned by [`crate::ViewportRenderer::prepare`].
142#[derive(Debug, Clone, Copy, Default)]
143pub struct FrameStats {
144    /// Total objects considered for rendering.
145    pub total_objects: u32,
146    /// Objects that passed visibility and frustum tests.
147    pub visible_objects: u32,
148    /// Objects culled by frustum or visibility.
149    pub culled_objects: u32,
150    /// Number of draw calls issued in the main pass.
151    pub draw_calls: u32,
152    /// Number of instanced batches (0 when using per-object path).
153    pub instanced_batches: u32,
154    /// Instanced batches whose GPU sub-range was re-uploaded this frame.
155    ///
156    /// Non-zero only on cache-miss frames where at least one batch's instance
157    /// data changed. Zero on cache-hit frames and when the per-object path is
158    /// active. Together with `batches_skipped`, this lets callers measure how
159    /// effective the dirty-flagging optimisation is for their scene.
160    pub batches_reuploaded: u32,
161    /// Instanced batches whose GPU sub-range was reused unchanged this frame.
162    ///
163    /// Non-zero only on cache-miss frames where at least one batch compared
164    /// equal to the cached data and its write was skipped. Zero on cache-hit
165    /// frames (no upload attempted at all) and when the per-object path is
166    /// active.
167    pub batches_skipped: u32,
168    /// Total triangles submitted to the GPU.
169    pub triangles_submitted: u64,
170    /// Number of draw calls in the shadow pass.
171    pub shadow_draw_calls: u32,
172    /// CPU time spent in `prepare()`, in milliseconds.
173    pub cpu_prepare_ms: f32,
174    /// GPU scene-pass time in milliseconds, if timestamp queries are available.
175    ///
176    /// Measured with `TIMESTAMP_QUERY` around the main scene render pass.
177    /// `None` on backends that do not support `TIMESTAMP_QUERY` (e.g. WebGL).
178    ///
179    /// Note: this value reflects the *previous* frame's GPU cost due to async
180    /// readback. The value lags by one frame and should not be used by the
181    /// adaptation controller across mode transitions.
182    pub gpu_frame_ms: Option<f32>,
183    /// Wall-clock duration since the previous `prepare()` call, in milliseconds.
184    ///
185    /// Approximates the full frame interval. Zero on the first frame.
186    pub total_frame_ms: f32,
187    /// Current internal render scale (1.0 = native resolution).
188    ///
189    /// Reflects the value tracked by the adaptation controller. Values below 1.0
190    /// cause the scene to render into a scaled intermediate texture that is
191    /// bilinearly upscaled to the surface (requires `allow_dynamic_resolution`).
192    pub render_scale: f32,
193    /// True if the last frame exceeded the target frame budget.
194    ///
195    /// Requires `target_fps` to be set in the [`PerformancePolicy`]. Always
196    /// `false` when no target is configured.
197    pub missed_budget: bool,
198    /// Bytes of geometry data uploaded to the GPU since the previous
199    /// `prepare()` call.
200    ///
201    /// Counts full buffer reallocations triggered by
202    /// [`crate::ViewportGpuResources::replace_mesh_data`] and initial uploads
203    /// via `upload_mesh_data` / `upload_mesh`. Uniform buffer writes are not
204    /// counted.
205    pub upload_bytes: u64,
206    /// True when GPU-driven culling is active this frame.
207    ///
208    /// False when the device does not support `INDIRECT_FIRST_INSTANCE` or
209    /// culling has been disabled via `disable_gpu_driven_culling()`.
210    pub gpu_culling_active: bool,
211    /// Number of instances that passed GPU culling and were submitted for drawing.
212    ///
213    /// Populated only when `gpu_culling_active` is true. `None` on the first frame
214    /// or when GPU culling is off. Lags by one frame due to async readback.
215    pub gpu_visible_instances: Option<u32>,
216
217    // --- Per-pass degradation flags ---
218    /// True when the shadow depth pass was skipped this frame.
219    ///
220    /// Set when `allow_shadow_reduction` is true and the previous frame missed
221    /// the target budget. Always false in [`RuntimeMode::Capture`].
222    pub shadows_skipped: bool,
223    /// True when volume raymarch step size was doubled this frame.
224    ///
225    /// Set when `allow_volume_quality_reduction` is true and the previous frame
226    /// missed the target budget. Always false in [`RuntimeMode::Capture`].
227    pub volume_quality_reduced: bool,
228    /// True when SSAO, contact shadows, and bloom were skipped this frame.
229    ///
230    /// Set when `allow_effect_throttling` is true and the previous frame missed
231    /// the target budget. Always false in [`RuntimeMode::Capture`].
232    pub effects_throttled: bool,
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    #[test]
240    fn test_frame_stats_default_is_zero() {
241        let stats = FrameStats::default();
242        assert_eq!(stats.total_objects, 0);
243        assert_eq!(stats.visible_objects, 0);
244        assert_eq!(stats.culled_objects, 0);
245        assert_eq!(stats.draw_calls, 0);
246        assert_eq!(stats.instanced_batches, 0);
247        assert_eq!(stats.batches_reuploaded, 0);
248        assert_eq!(stats.batches_skipped, 0);
249        assert_eq!(stats.triangles_submitted, 0);
250        assert_eq!(stats.shadow_draw_calls, 0);
251        assert_eq!(stats.cpu_prepare_ms, 0.0);
252        assert!(stats.gpu_frame_ms.is_none());
253        assert_eq!(stats.total_frame_ms, 0.0);
254        assert_eq!(stats.render_scale, 0.0);
255        assert!(!stats.missed_budget);
256        assert_eq!(stats.upload_bytes, 0);
257        assert!(!stats.gpu_culling_active);
258        assert!(stats.gpu_visible_instances.is_none());
259        assert!(!stats.shadows_skipped);
260        assert!(!stats.volume_quality_reduced);
261        assert!(!stats.effects_throttled);
262    }
263
264    #[test]
265    fn test_runtime_mode_default_is_interactive() {
266        assert_eq!(RuntimeMode::default(), RuntimeMode::Interactive);
267    }
268
269    #[test]
270    fn test_performance_policy_default() {
271        let p = PerformancePolicy::default();
272        assert!(p.preset.is_none());
273        assert!(p.target_fps.is_none());
274        assert!(!p.allow_dynamic_resolution);
275        assert!(p.min_render_scale <= p.max_render_scale);
276        assert_eq!(p.max_render_scale, 1.0);
277    }
278}