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