sim_engine/renderer/outcomes.rs
1//! Frame outcomes, timing reports and public rendering errors.
2
3use super::{Duration, Error, SceneBudgetResource, TessellationError, TessellationStats, fmt};
4
5/// Result of attempting to draw a frame.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum RenderStatus {
8 /// Commands were submitted successfully. Surface paths also requested
9 /// presentation; offscreen paths completed their target submission only.
10 Drawn,
11 /// The frame was skipped because the window surface was temporarily unavailable.
12 Skipped(RendererSurfaceStatus),
13}
14
15/// CPU-side durations measured while preparing and submitting one renderer frame.
16///
17/// These values do not measure GPU execution or the monitor scanout timestamp.
18/// FIFO presentation back-pressure normally appears in `surface_acquire` because
19/// `wgpu` blocks frame acquisition when the presentation queue is full.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub struct RendererFrameMetrics {
22 pub(super) tessellation: Duration,
23 pub(super) upload: Duration,
24 pub(super) camera_uniform_upload: Duration,
25 pub(super) surface_acquire: Duration,
26 pub(super) encode_submit_present: Duration,
27 pub(super) total_cpu: Duration,
28 pub(super) geometry_reused: bool,
29 pub(super) geometry_streamed: bool,
30 pub(super) tessellation_stats: TessellationStats,
31 pub(super) preparation: Option<RendererPreparationMetrics>,
32}
33
34/// Non-overlapping CPU preparation stages for a heterogeneous composed frame.
35///
36/// All intervals are on the calling thread before uploads. They do not measure
37/// GPU work or presentation. `None` from [`RendererFrameMetrics::preparation`]
38/// identifies a rendering path which does not expose this detailed breakdown;
39/// it must not be interpreted as zero preparation cost.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41pub struct RendererPreparationMetrics {
42 pub(super) tessellation: Duration,
43 pub(super) geometry_validation: Duration,
44 pub(super) retained_draws: Duration,
45 pub(super) other: Duration,
46}
47
48impl RendererPreparationMetrics {
49 /// CPU generation of streaming ordinary-scene vertices and clip batches.
50 pub const fn tessellation(self) -> Duration {
51 self.tessellation
52 }
53
54 /// CPU numeric/topology validation of streaming and retained 2D geometry.
55 /// Includes bounded exact-proof cache lookups when they replace validation.
56 /// Image/glyph placement validation is included in [`Self::retained_draws`].
57 pub const fn geometry_validation(self) -> Duration {
58 self.geometry_validation
59 }
60
61 /// Retained scene/image/glyph draw preparation excluding ordinary-scene
62 /// numeric validation. Includes placement validation and batch assembly.
63 pub const fn retained_draws(self) -> Duration {
64 self.retained_draws
65 }
66
67 /// Remaining preparation: item preflight, viewport resolution, particles,
68 /// scalar data, bookkeeping, and timing overhead. Excludes uploads/acquire.
69 pub const fn other(self) -> Duration {
70 self.other
71 }
72
73 /// Sum of this breakdown, equal to the report's coarse preparation interval.
74 pub fn total(self) -> Duration {
75 self.tessellation
76 .saturating_add(self.geometry_validation)
77 .saturating_add(self.retained_draws)
78 .saturating_add(self.other)
79 }
80}
81
82impl RendererFrameMetrics {
83 /// Detailed, non-overlapping CPU preparation stages when this path records
84 /// them. The coarse [`Self::tessellation`] interval remains available for
85 /// compatibility and includes all of these stages, not just triangulation.
86 pub const fn preparation(self) -> Option<RendererPreparationMetrics> {
87 self.preparation
88 }
89
90 /// Returns CPU time spent preparing visual work before GPU uploads.
91 ///
92 /// For an ordinary streaming scene this is validation and tessellation.
93 /// A heterogeneous [`FrameComposer`](crate::FrameComposer) frame also
94 /// includes viewport and source validation, particle visibility selection,
95 /// scalar LUT generation, and preparation of retained image/glyph draws.
96 pub fn tessellation(self) -> Duration {
97 self.tessellation
98 }
99
100 /// Returns CPU time spent preparing and enqueueing non-camera per-frame GPU data.
101 ///
102 /// Depending on the rendering path this includes transient vertex or
103 /// instance writes, scalar LUT and pass-uniform uploads, and creation of
104 /// the per-frame bindings needed by image, glyph, scalar, particle, or
105 /// composition passes. The camera-only write remains separately available
106 /// through [`Self::camera_uniform_upload`]. This is CPU preparation/enqueue
107 /// time, not GPU execution time. An ordinary streaming frame can include
108 /// pre-acquire transient buffer
109 /// capacity creation here, so a skipped report may have a non-zero duration
110 /// even though it performed no queue write and reports zero uploaded bytes.
111 pub fn upload(self) -> Duration {
112 self.upload
113 }
114
115 /// Returns CPU time spent updating the small per-frame camera uniform.
116 pub fn camera_uniform_upload(self) -> Duration {
117 self.camera_uniform_upload
118 }
119
120 /// Returns CPU time spent acquiring the next presentation surface texture.
121 ///
122 /// In FIFO modes this includes queue back-pressure and is the closest CPU-side
123 /// approximation to VSync wait exposed by `wgpu`.
124 pub fn surface_acquire(self) -> Duration {
125 self.surface_acquire
126 }
127
128 /// Returns CPU time spent encoding, submitting, and dispatching present.
129 ///
130 /// Present dispatch does not mean the monitor has already scanned out the
131 /// frame; `wgpu` does not expose that timestamp here.
132 pub fn encode_submit_present(self) -> Duration {
133 self.encode_submit_present
134 }
135
136 /// Returns total CPU time inside the profiled render call.
137 pub fn total_cpu(self) -> Duration {
138 self.total_cpu
139 }
140
141 /// Returns whether this frame referenced retained visual geometry.
142 ///
143 /// This includes prepared scenes and retained sprite/glyph batches. It is
144 /// a broad workload-classification hint rather than a statement that the
145 /// frame performed no uploads, and it can be true together with
146 /// [`Self::geometry_streamed`].
147 pub fn geometry_reused(self) -> bool {
148 self.geometry_reused
149 }
150
151 /// Returns whether this frame contained dynamically supplied visual work.
152 ///
153 /// This includes dynamic meshes, particle visibility instances, and scalar
154 /// field passes. It is a broad workload-classification hint rather than an
155 /// allocation or upload guarantee, and it can be true together with
156 /// [`Self::geometry_reused`].
157 pub fn geometry_streamed(self) -> bool {
158 self.geometry_streamed
159 }
160
161 /// Returns command-level tessellation results for this frame.
162 pub fn tessellation_stats(self) -> TessellationStats {
163 self.tessellation_stats
164 }
165}
166
167/// Status and CPU timing breakdown for one renderer frame.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct RenderReport {
170 pub(super) status: RenderStatus,
171 pub(super) metrics: RendererFrameMetrics,
172}
173
174impl RenderReport {
175 /// Returns whether the frame was drawn or skipped by the surface.
176 pub fn status(self) -> RenderStatus {
177 self.status
178 }
179
180 /// Returns CPU-side stage durations for the render call.
181 pub fn metrics(self) -> RendererFrameMetrics {
182 self.metrics
183 }
184}
185
186/// Recoverable or fatal state reported by the presentation surface.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum RendererSurfaceStatus {
189 /// Acquiring the next frame timed out; try again on a later frame.
190 Timeout,
191 /// The surface is occluded or minimized; rendering can be skipped.
192 Occluded,
193 /// The surface configuration is stale; resizing or reconfiguring is needed.
194 Outdated,
195 /// The surface was lost and should be recreated by the host application.
196 Lost,
197 /// `wgpu` reported a validation error while acquiring the frame.
198 Validation,
199}
200
201/// Fatal failure while preparing or submitting one frame.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum RendererFrameError {
204 /// The presentation surface was lost or rejected frame acquisition.
205 Surface(RendererSurfaceStatus),
206 /// Camera, geometry, stroke arithmetic, or dynamic-triangle topology
207 /// cannot be proven portable on the GPU.
208 ///
209 /// This includes nonzero subnormal or excessively large shader sources,
210 /// transform ranges that may overflow under permitted GPU arithmetic, and
211 /// stroke branch decisions that are ambiguous after projection, every
212 /// dynamic triangle requiring partial frustum clipping, and projected
213 /// triangle orientation that may change with legal shader association.
214 /// Compact screen primitives also reject transforms whose boundary-error
215 /// bound exceeds 0.25 physical pixels at the actual destination scale.
216 InvalidGeometryTransform,
217 /// A logical viewport is outside the active surface or render target.
218 InvalidViewport,
219 /// Tessellated geometry exceeds the active device's vertex-buffer limit.
220 GeometryCapacityTooLarge,
221 /// CPU storage for scene tessellation could not be reserved.
222 SceneAllocationFailed {
223 /// Minimum additional bytes requested by the failed reservation.
224 requested_bytes: usize,
225 },
226 /// CPU storage for the camera-visible particle subset could not be reserved.
227 ParticleAllocationFailed {
228 /// Bytes requested for the rejected visible-instance vector.
229 requested_bytes: usize,
230 },
231 /// Actual renderer work exceeded a scene's explicit limit.
232 SceneBudgetExceeded {
233 /// Work category whose post-tessellation limit was exceeded.
234 resource: SceneBudgetResource,
235 /// Configured maximum for the category.
236 limit: usize,
237 /// Actual renderer work observed.
238 actual: usize,
239 },
240}
241
242impl fmt::Display for RendererFrameError {
243 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244 match self {
245 Self::Surface(status) => write!(formatter, "renderer surface failed: {status:?}"),
246 Self::InvalidGeometryTransform => {
247 write!(
248 formatter,
249 "camera, geometry, or dynamic topology is outside the portable GPU envelope"
250 )
251 }
252 Self::InvalidViewport => {
253 write!(
254 formatter,
255 "logical viewport lies outside the active render target"
256 )
257 }
258 Self::GeometryCapacityTooLarge => {
259 write!(formatter, "geometry exceeds the GPU vertex-buffer limit")
260 }
261 Self::SceneAllocationFailed { requested_bytes } => write!(
262 formatter,
263 "could not reserve {requested_bytes} additional bytes for scene tessellation"
264 ),
265 Self::ParticleAllocationFailed { requested_bytes } => write!(
266 formatter,
267 "could not reserve {requested_bytes} bytes for visible particle instances"
268 ),
269 Self::SceneBudgetExceeded {
270 resource,
271 limit,
272 actual,
273 } => write!(
274 formatter,
275 "scene {resource:?} work exceeded its limit {limit} after tessellation: {actual}"
276 ),
277 }
278 }
279}
280
281impl Error for RendererFrameError {}
282
283/// Errors that can happen while creating the `wgpu` renderer.
284#[derive(Debug)]
285pub enum RendererInitError {
286 /// Surface creation failed for the provided window or canvas target.
287 CreateSurface(wgpu::CreateSurfaceError),
288 /// No compatible GPU adapter could be selected.
289 RequestAdapter(wgpu::RequestAdapterError),
290 /// A logical GPU device and queue could not be created.
291 RequestDevice(wgpu::RequestDeviceError),
292 /// The surface did not expose a usable default configuration.
293 NoSurfaceConfig,
294 /// Requested physical dimensions exceed the selected device limit.
295 SurfaceDimensionsTooLarge {
296 /// Rejected physical width.
297 width: u32,
298 /// Rejected physical height.
299 height: u32,
300 /// Device maximum for either dimension.
301 limit: u32,
302 },
303 /// The bounded previous-device quarantine is full.
304 RecoveryLimitReached {
305 /// Configured maximum number of quarantined logical devices.
306 limit: usize,
307 },
308 /// CPU storage for quarantining the previous device could not be reserved.
309 RecoveryAllocationFailed {
310 /// Additional bytes requested for one quarantine entry.
311 requested_bytes: usize,
312 },
313}
314
315impl fmt::Display for RendererInitError {
316 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317 match self {
318 Self::CreateSurface(error) => write!(formatter, "failed to create surface: {error}"),
319 Self::RequestAdapter(error) => write!(formatter, "failed to request adapter: {error}"),
320 Self::RequestDevice(error) => write!(formatter, "failed to request device: {error}"),
321 Self::NoSurfaceConfig => write!(formatter, "surface has no supported default config"),
322 Self::SurfaceDimensionsTooLarge {
323 width,
324 height,
325 limit,
326 } => write!(
327 formatter,
328 "surface dimensions {width}x{height} exceed device limit {limit}"
329 ),
330 Self::RecoveryLimitReached { limit } => write!(
331 formatter,
332 "device recovery limit reached with {limit} quarantined devices"
333 ),
334 Self::RecoveryAllocationFailed { requested_bytes } => write!(
335 formatter,
336 "could not reserve {requested_bytes} bytes for device recovery quarantine"
337 ),
338 }
339 }
340}
341
342impl Error for RendererInitError {}
343
344/// Invalid runtime or initialization configuration for [`WgpuRenderer`](crate::WgpuRenderer).
345#[derive(Debug, Clone, Copy, PartialEq)]
346pub enum RendererConfigurationError {
347 /// Logical-to-physical scale must keep all surface transforms normal and finite.
348 InvalidScaleFactor {
349 /// Rejected physical pixels per logical screen pixel.
350 scale_factor: f64,
351 },
352 /// Previous-device quarantine must remain inside the supported bounded range.
353 InvalidRecoveryLimit {
354 /// Rejected maximum retained-device count.
355 limit: usize,
356 },
357 /// Requested physical dimensions exceed the active device limit.
358 SurfaceDimensionsTooLarge {
359 /// Rejected physical width.
360 width: u32,
361 /// Rejected physical height.
362 height: u32,
363 /// Device maximum for either dimension.
364 limit: u32,
365 },
366}
367
368impl fmt::Display for RendererConfigurationError {
369 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
370 match self {
371 Self::InvalidScaleFactor { scale_factor } => write!(
372 formatter,
373 "renderer scale factor must be finite, representable as f32, and keep every u32 surface transform in the normal f32 range, got {scale_factor}"
374 ),
375 Self::InvalidRecoveryLimit { limit } => write!(
376 formatter,
377 "renderer recovery quarantine must retain between 1 and 8 devices, got {limit}"
378 ),
379 Self::SurfaceDimensionsTooLarge {
380 width,
381 height,
382 limit,
383 } => write!(
384 formatter,
385 "surface dimensions {width}x{height} exceed device limit {limit}"
386 ),
387 }
388 }
389}
390
391impl Error for RendererConfigurationError {}
392
393/// Failure while converting between logical and physical screen coordinates.
394#[derive(Debug, Clone, Copy, PartialEq)]
395pub enum RendererCoordinateError {
396 /// The source position is non-finite or the scaled result cannot be represented as `f32`.
397 NonFiniteConversion,
398}
399
400impl fmt::Display for RendererCoordinateError {
401 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
402 write!(
403 formatter,
404 "screen coordinate conversion produced a non-finite result"
405 )
406 }
407}
408
409impl Error for RendererCoordinateError {}
410
411/// Failure while uploading or restoring immutable prepared-scene geometry.
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
413pub enum PreparedSceneError {
414 /// Tessellated geometry exceeds the active device's vertex-buffer limit.
415 CapacityTooLarge,
416 /// Command sources or derived tessellated vertices are outside the
417 /// portable GPU input envelope.
418 InvalidGeometrySources,
419 /// CPU storage for scene tessellation could not be reserved.
420 AllocationFailed {
421 /// Minimum additional bytes requested by the failed reservation.
422 requested_bytes: usize,
423 },
424 /// Actual prepared-scene work exceeded an explicit scene limit.
425 BudgetExceeded {
426 /// Work category whose post-tessellation limit was exceeded.
427 resource: SceneBudgetResource,
428 /// Configured maximum for the category.
429 limit: usize,
430 /// Actual renderer work observed.
431 actual: usize,
432 },
433}
434
435impl fmt::Display for PreparedSceneError {
436 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
437 match self {
438 Self::CapacityTooLarge => {
439 write!(
440 formatter,
441 "prepared scene exceeds the GPU vertex-buffer limit"
442 )
443 }
444 Self::InvalidGeometrySources => write!(
445 formatter,
446 "prepared scene contains non-portable GPU geometry sources"
447 ),
448 Self::AllocationFailed { requested_bytes } => write!(
449 formatter,
450 "could not reserve {requested_bytes} additional bytes for prepared-scene tessellation"
451 ),
452 Self::BudgetExceeded {
453 resource,
454 limit,
455 actual,
456 } => write!(
457 formatter,
458 "prepared scene {resource:?} work exceeded its limit {limit}: {actual}"
459 ),
460 }
461 }
462}
463
464impl From<TessellationError> for RendererFrameError {
465 fn from(error: TessellationError) -> Self {
466 match error {
467 TessellationError::AllocationFailed { requested_bytes } => {
468 Self::SceneAllocationFailed { requested_bytes }
469 }
470 TessellationError::CapacityTooLarge => Self::GeometryCapacityTooLarge,
471 TessellationError::BudgetExceeded {
472 resource,
473 limit,
474 actual,
475 } => Self::SceneBudgetExceeded {
476 resource,
477 limit,
478 actual,
479 },
480 }
481 }
482}
483
484impl From<TessellationError> for PreparedSceneError {
485 fn from(error: TessellationError) -> Self {
486 match error {
487 TessellationError::AllocationFailed { requested_bytes } => {
488 Self::AllocationFailed { requested_bytes }
489 }
490 TessellationError::CapacityTooLarge => Self::CapacityTooLarge,
491 TessellationError::BudgetExceeded {
492 resource,
493 limit,
494 actual,
495 } => Self::BudgetExceeded {
496 resource,
497 limit,
498 actual,
499 },
500 }
501 }
502}
503
504impl Error for PreparedSceneError {}
505
506/// Failure to draw geometry prepared by [`WgpuRenderer::prepare_scene`](crate::WgpuRenderer::prepare_scene).
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub enum PreparedSceneRenderError {
509 /// The prepared geometry belongs to a different renderer and GPU device.
510 RendererMismatch,
511 /// Frame rendering failed after prepared-scene ownership validation.
512 Frame(RendererFrameError),
513}
514
515impl fmt::Display for PreparedSceneRenderError {
516 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
517 match self {
518 Self::RendererMismatch => {
519 write!(formatter, "prepared scene belongs to a different renderer")
520 }
521 Self::Frame(error) => write!(formatter, "prepared frame failed: {error}"),
522 }
523 }
524}
525
526impl Error for PreparedSceneRenderError {}