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/// CPU time spent in each phase of `prepare()`, in milliseconds.
142///
143/// `FrameStats::cpu_prepare_ms` is the total. This splits that total across the
144/// main phases so a slow `prepare` can be attributed to a specific one instead
145/// of guessing. The fields sum to roughly `cpu_prepare_ms`; `other_ms` carries
146/// the remainder (timestamp readback, scatter-volume sort, stats assembly, and
147/// other small per-frame work).
148///
149/// All values are wall-clock CPU time on the thread calling `prepare`, measured
150/// with `Instant`. They measure how long it takes to record and submit the work,
151/// not how long the GPU spends running it; use `gpu_frame_ms` for GPU cost.
152#[derive(Debug, Clone, Copy, Default)]
153pub struct PrepareBreakdown {
154 /// Item-type plugin prepare and cull dispatch. Skinning and other vertex
155 /// deformers run here, so a heavy skinned crowd shows up in this field.
156 pub plugin_ms: f32,
157 /// Lighting setup: directional shadow cascade matrices, point-light cube-map
158 /// faces, and light clustering.
159 pub lighting_ms: f32,
160 /// Per-object uniform writes on the non-instanced path. Zero when the scene
161 /// is above the instancing threshold and all meshes batch.
162 pub uniforms_ms: f32,
163 /// Building and uploading instanced batches (grouping items by mesh and
164 /// material, writing instance data).
165 pub instancing_ms: f32,
166 /// Uploading non-mesh geometry: glyphs, point clouds, polylines, decals,
167 /// images, tubes, ribbons, slices, and volumes.
168 pub geometry_ms: f32,
169 /// Recording the shadow depth pass (directional cascades and point-light
170 /// cube-map faces) into the atlas.
171 pub shadow_ms: f32,
172 /// Per-viewport prepare: camera and clip uniforms, grid, overlays, and
173 /// interaction state. Runs once per viewport.
174 pub viewport_ms: f32,
175 /// Remainder of `prepare` not covered by the fields above.
176 pub other_ms: f32,
177}
178
179/// Per-pass split of GPU frame time, measured with `TIMESTAMP_QUERY`.
180///
181/// Each field is the GPU duration of one render pass in milliseconds, captured
182/// with timestamp queries around the pass. A field is `0.0` when that pass did
183/// not run this frame (for example `shadow_ms` when shadows are off or
184/// `oit_ms` when nothing transparent is drawn) or when the backend does not
185/// support `TIMESTAMP_QUERY` (the same condition that leaves
186/// [`FrameStats::gpu_frame_ms`] at `None`).
187///
188/// These passes are submitted in separate command buffers but resolved
189/// together, so the values are comparable. Like `gpu_frame_ms`, they lag one
190/// frame behind due to async readback. The passes measured here do not cover
191/// every GPU pass (decals, scatter, bloom, depth of field, and the final
192/// overlays are not split out), so the fields do not sum to the full frame GPU
193/// time; treat the remainder as those un-instrumented passes plus present.
194#[derive(Debug, Clone, Copy, Default)]
195pub struct GpuBreakdown {
196 /// Main opaque HDR scene pass. This is the same span as
197 /// [`FrameStats::gpu_frame_ms`].
198 pub scene_ms: f32,
199 /// Directional shadow depth pass (all cascades rendered into the atlas).
200 pub shadow_ms: f32,
201 /// Order-independent transparency accumulation pass.
202 pub oit_ms: f32,
203 /// Tone-map and resolve pass that writes the final LDR image.
204 pub post_ms: f32,
205 /// Main-camera GPU cull dispatch: the `cull_instances` + `write_indirect_args`
206 /// compute passes that produce the indirect draw args. `0.0` when GPU culling
207 /// is off or the scene has no instanced batches. Shadow-cascade culls are not
208 /// included here. Useful for checking whether the cull pass costs more than it
209 /// saves on a given scene.
210 pub cull_ms: f32,
211}
212
213/// Per-frame rendering statistics returned by [`crate::ViewportRenderer::prepare`].
214#[derive(Debug, Clone, Copy, Default)]
215pub struct FrameStats {
216 /// Total objects considered for rendering.
217 pub total_objects: u32,
218 /// Objects that passed visibility and frustum tests.
219 pub visible_objects: u32,
220 /// Objects culled by frustum or visibility.
221 pub culled_objects: u32,
222 /// Number of draw calls issued in the main pass.
223 pub draw_calls: u32,
224 /// Number of instanced batches (0 when using per-object path).
225 pub instanced_batches: u32,
226 /// Visible items that miss the instanced fast path and are drawn one at a
227 /// time through the per-object path.
228 ///
229 /// An item is non-instanceable when it uses a styled back-face policy
230 /// (different-colour/tint/pattern) or is two-sided and transparent, uses a
231 /// matcap, has a scalar attribute or parameter visualization, carries a
232 /// position/normal override, has per-instance deform data (skinning), or is
233 /// hit by a compute filter. Each such item costs a uniform write and a bind-group
234 /// build in `prepare`, so a large count here means `prepare` is paying
235 /// per-object cost across much of the scene rather than batching it.
236 pub per_object_items: u32,
237 /// Per-object bind groups actually (re)built this frame.
238 ///
239 /// The per-object path caches bind groups and skips the rebuild when the
240 /// item's textures, attributes, and overrides are unchanged. A value near
241 /// `per_object_items` means the cache is missing most frames (for example
242 /// because items move between slots); a value near zero means the remaining
243 /// per-object cost is the uniform writes, not the bind-group builds.
244 pub per_object_bind_groups_built: u32,
245 /// Instanced batches whose GPU sub-range was re-uploaded this frame.
246 ///
247 /// Non-zero only on cache-miss frames where at least one batch's instance
248 /// data changed. Zero on cache-hit frames and when the per-object path is
249 /// active. Together with `batches_skipped`, this lets callers measure how
250 /// effective the dirty-flagging optimisation is for their scene.
251 pub batches_reuploaded: u32,
252 /// Instanced batches whose GPU sub-range was reused unchanged this frame.
253 ///
254 /// Non-zero only on cache-miss frames where at least one batch compared
255 /// equal to the cached data and its write was skipped. Zero on cache-hit
256 /// frames (no upload attempted at all) and when the per-object path is
257 /// active.
258 pub batches_skipped: u32,
259 /// Total triangles submitted to the GPU.
260 pub triangles_submitted: u64,
261 /// Number of draw calls in the shadow pass.
262 pub shadow_draw_calls: u32,
263 /// CPU time spent in `prepare()`, in milliseconds.
264 pub cpu_prepare_ms: f32,
265 /// Per-phase split of `cpu_prepare_ms`. See [`PrepareBreakdown`].
266 pub prepare_breakdown: PrepareBreakdown,
267 /// CPU time spent encoding the paint pass (draw-call recording) in
268 /// milliseconds, separate from `cpu_prepare_ms`.
269 ///
270 /// Measured around the render/paint encode and latched after it, so
271 /// `last_frame_stats()` reflects the current frame once `render` has run.
272 /// The value carried in the `FrameStats` returned by `prepare()` is the
273 /// previous frame's paint, since paint runs after prepare. For
274 /// multi-viewport rendering this reflects the most recently painted
275 /// viewport, not the sum.
276 pub cpu_paint_ms: f32,
277 /// GPU scene-pass time in milliseconds, if timestamp queries are available.
278 ///
279 /// Measured with `TIMESTAMP_QUERY` around the main scene render pass.
280 /// `None` on backends that do not support `TIMESTAMP_QUERY` (e.g. WebGL).
281 ///
282 /// Note: this value reflects the *previous* frame's GPU cost due to async
283 /// readback. The value lags by one frame and should not be used by the
284 /// adaptation controller across mode transitions.
285 pub gpu_frame_ms: Option<f32>,
286 /// Per-pass split of GPU frame time. See [`GpuBreakdown`].
287 ///
288 /// Populated under the same conditions as `gpu_frame_ms` (requires
289 /// `TIMESTAMP_QUERY`); all fields are `0.0` otherwise. `scene_ms` matches
290 /// `gpu_frame_ms`.
291 pub gpu_breakdown: GpuBreakdown,
292 /// Wall-clock duration since the previous `prepare()` call, in milliseconds.
293 ///
294 /// Approximates the full frame interval. Zero on the first frame.
295 pub total_frame_ms: f32,
296 /// Current internal render scale (1.0 = native resolution).
297 ///
298 /// Reflects the value tracked by the adaptation controller. Values below 1.0
299 /// cause the scene to render into a scaled intermediate texture that is
300 /// bilinearly upscaled to the surface (requires `allow_dynamic_resolution`).
301 pub render_scale: f32,
302 /// True if the last frame exceeded the target frame budget.
303 ///
304 /// Requires `target_fps` to be set in the [`PerformancePolicy`]. Always
305 /// `false` when no target is configured.
306 pub missed_budget: bool,
307 /// Bytes of geometry data uploaded to the GPU since the previous
308 /// `prepare()` call.
309 ///
310 /// Counts full buffer reallocations triggered by
311 /// [`crate::ViewportGpuResources::replace_mesh_data`] and initial uploads
312 /// via `upload_mesh_data` / `upload_mesh`. Uniform buffer writes are not
313 /// counted.
314 pub upload_bytes: u64,
315 /// True when GPU-driven culling is active this frame.
316 ///
317 /// False when the device does not support `INDIRECT_FIRST_INSTANCE` or
318 /// culling has been disabled via `disable_gpu_driven_culling()`.
319 pub gpu_culling_active: bool,
320 /// Number of instances that passed GPU culling and were submitted for drawing.
321 ///
322 /// Populated only when `gpu_culling_active` is true. `None` on the first frame
323 /// or when GPU culling is off. Lags by one frame due to async readback.
324 pub gpu_visible_instances: Option<u32>,
325
326 // --- Per-pass degradation flags ---
327 /// True when the shadow depth pass was skipped this frame.
328 ///
329 /// Set when `allow_shadow_reduction` is true and the previous frame missed
330 /// the target budget. Always false in [`RuntimeMode::Capture`].
331 pub shadows_skipped: bool,
332 /// True when volume raymarch step size was doubled this frame.
333 ///
334 /// Set when `allow_volume_quality_reduction` is true and the previous frame
335 /// missed the target budget. Always false in [`RuntimeMode::Capture`].
336 pub volume_quality_reduced: bool,
337 /// True when SSAO, contact shadows, and bloom were skipped this frame.
338 ///
339 /// Set when `allow_effect_throttling` is true and the previous frame missed
340 /// the target budget. Always false in [`RuntimeMode::Capture`].
341 pub effects_throttled: bool,
342
343 /// Objects that resolved through a LOD group this frame.
344 ///
345 /// Counts `SceneRenderItem`s with a `lod_group` set, plus each individual
346 /// `MeshInstanceItem` instance whose level was selected. Zero when nothing
347 /// uses LOD.
348 pub lod_items_resolved: u32,
349 /// LOD objects whose chosen level changed from the previous frame.
350 ///
351 /// Counts both scene items and individual mesh instances that moved to a
352 /// different level. Only objects with a `pick_id` are tracked across frames,
353 /// so this counts switches among those. A high value relative to
354 /// `lod_items_resolved` suggests thresholds are being crossed often (camera
355 /// motion, or thresholds spaced too tightly for the hysteresis margin).
356 pub lod_switches: u32,
357 /// Objects dropped this frame because they fell below their LOD group's cull
358 /// size. Counts hidden `SceneRenderItem`s plus individual mesh instances that
359 /// were left out of every batch. Zero unless a group sets `cull_below`.
360 pub lod_culled: u32,
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[test]
368 fn test_frame_stats_default_is_zero() {
369 let stats = FrameStats::default();
370 assert_eq!(stats.total_objects, 0);
371 assert_eq!(stats.visible_objects, 0);
372 assert_eq!(stats.culled_objects, 0);
373 assert_eq!(stats.draw_calls, 0);
374 assert_eq!(stats.instanced_batches, 0);
375 assert_eq!(stats.batches_reuploaded, 0);
376 assert_eq!(stats.batches_skipped, 0);
377 assert_eq!(stats.triangles_submitted, 0);
378 assert_eq!(stats.shadow_draw_calls, 0);
379 assert_eq!(stats.cpu_prepare_ms, 0.0);
380 assert!(stats.gpu_frame_ms.is_none());
381 assert_eq!(stats.total_frame_ms, 0.0);
382 assert_eq!(stats.render_scale, 0.0);
383 assert!(!stats.missed_budget);
384 assert_eq!(stats.upload_bytes, 0);
385 assert!(!stats.gpu_culling_active);
386 assert!(stats.gpu_visible_instances.is_none());
387 assert!(!stats.shadows_skipped);
388 assert!(!stats.volume_quality_reduced);
389 assert!(!stats.effects_throttled);
390 }
391
392 #[test]
393 fn test_runtime_mode_default_is_interactive() {
394 assert_eq!(RuntimeMode::default(), RuntimeMode::Interactive);
395 }
396
397 #[test]
398 fn test_performance_policy_default() {
399 let p = PerformancePolicy::default();
400 assert!(p.preset.is_none());
401 assert!(p.target_fps.is_none());
402 assert!(!p.allow_dynamic_resolution);
403 assert!(p.min_render_scale <= p.max_render_scale);
404 assert_eq!(p.max_render_scale, 1.0);
405 }
406}