1use std::{error::Error, fmt, time::Duration};
4
5use sim_engine::LogicalViewport;
6
7use crate::{
8 ExtractionError,
9 commands::CommandBatchError,
10 component::ComponentApprovalError,
11 identity::{WorldFactoryId, WorldGeneration},
12 input::{InputCollectionError, InputEvent},
13 system::{Stage, SystemRunFailure, SystemSetupError},
14 time::{DroppedFixedTime, FixedFramePlan, TimeAdvanceError},
15 transition::{ConvergentTransitionWarning, TransitionRejection},
16 world::WorldBuildError,
17};
18
19pub struct FrameRequest<'a> {
21 elapsed: Duration,
22 events: &'a [InputEvent],
23 viewport: LogicalViewport,
24}
25
26impl<'a> FrameRequest<'a> {
27 pub const fn new(
30 elapsed: Duration,
31 events: &'a [InputEvent],
32 viewport: LogicalViewport,
33 ) -> Self {
34 Self {
35 elapsed,
36 events,
37 viewport,
38 }
39 }
40
41 pub const fn elapsed(&self) -> Duration {
43 self.elapsed
44 }
45
46 pub const fn events(&self) -> &'a [InputEvent] {
51 self.events
52 }
53
54 pub const fn viewport(&self) -> LogicalViewport {
56 self.viewport
57 }
58}
59
60#[derive(Debug)]
62pub enum BeginFrameRejection {
63 FrameIdentityExhausted,
65 Input(InputCollectionError),
67 Time(TimeAdvanceError),
69}
70
71impl fmt::Display for BeginFrameRejection {
72 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 Self::FrameIdentityExhausted => {
75 formatter.write_str("application frame identity space is exhausted")
76 }
77 Self::Input(error) => write!(formatter, "frame input was rejected: {error}"),
78 Self::Time(error) => write!(formatter, "frame time was rejected: {error}"),
79 }
80 }
81}
82
83impl Error for BeginFrameRejection {
84 fn source(&self) -> Option<&(dyn Error + 'static)> {
85 match self {
86 Self::Input(error) => Some(error),
87 Self::Time(error) => Some(error),
88 Self::FrameIdentityExhausted => None,
89 }
90 }
91}
92
93#[derive(Debug)]
95pub enum CandidateFailure {
96 InvalidFactory,
98 GenerationExhausted,
100 Components(ComponentApprovalError),
102 Factory(WorldBuildError),
104 SystemSetup(SystemSetupError),
106 StartupSystem(SystemRunFailure),
108 StartupCommands(CommandBatchError),
110 StartupTransition,
112 Extraction(ExtractionError),
114 RuntimeInvariant,
116}
117
118impl fmt::Display for CandidateFailure {
119 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
120 match self {
121 Self::InvalidFactory => formatter.write_str("World factory handle is not registered"),
122 Self::GenerationExhausted => {
123 formatter.write_str("World generation identity space is exhausted")
124 }
125 Self::Components(error) => write!(formatter, "component registry failed: {error}"),
126 Self::Factory(error) => write!(formatter, "World factory failed: {error}"),
127 Self::SystemSetup(error) => write!(formatter, "System setup failed: {error}"),
128 Self::StartupSystem(error) => write!(formatter, "Startup failed: {error}"),
129 Self::StartupCommands(error) => write!(formatter, "Startup Commands failed: {error}"),
130 Self::StartupTransition => {
131 formatter.write_str("Startup cannot request World replacement in this slice")
132 }
133 Self::Extraction(error) => write!(formatter, "candidate extraction failed: {error}"),
134 Self::RuntimeInvariant => {
135 formatter.write_str("candidate is missing a private runtime Resource")
136 }
137 }
138 }
139}
140
141impl Error for CandidateFailure {
142 fn source(&self) -> Option<&(dyn Error + 'static)> {
143 match self {
144 Self::Components(error) => Some(error),
145 Self::Factory(error) => Some(error),
146 Self::SystemSetup(error) => Some(error),
147 Self::StartupSystem(error) => Some(error),
148 Self::StartupCommands(error) => Some(error),
149 Self::Extraction(error) => Some(error),
150 Self::InvalidFactory
151 | Self::GenerationExhausted
152 | Self::StartupTransition
153 | Self::RuntimeInvariant => None,
154 }
155 }
156}
157
158#[derive(Debug)]
160pub enum RunnerBuildError {
161 InvalidInitialFactory,
163 Input(InputCollectionError),
165 LifecycleTraceAllocation {
167 limit: usize,
169 },
170 MissingApplicationResource {
173 resource: &'static str,
175 stage: Stage,
177 system: &'static str,
179 },
180 ApplicationResourceInvariant,
182 InitialWorld(CandidateFailure),
184}
185
186impl fmt::Display for RunnerBuildError {
187 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
188 match self {
189 Self::InvalidInitialFactory => {
190 formatter.write_str("initial World factory is not registered by this application")
191 }
192 Self::Input(error) => write!(formatter, "input initialization failed: {error}"),
193 Self::LifecycleTraceAllocation { limit } => write!(
194 formatter,
195 "failed to reserve lifecycle trace capacity of {limit} records"
196 ),
197 Self::MissingApplicationResource {
198 resource,
199 stage,
200 system,
201 } => write!(
202 formatter,
203 "{stage:?} System `{system}` requests unregistered Application Resource `{resource}`"
204 ),
205 Self::ApplicationResourceInvariant => formatter
206 .write_str("Application Resource staging failed a private runtime invariant"),
207 Self::InitialWorld(error) => write!(formatter, "initial World failed: {error}"),
208 }
209 }
210}
211
212impl Error for RunnerBuildError {
213 fn source(&self) -> Option<&(dyn Error + 'static)> {
214 match self {
215 Self::Input(error) => Some(error),
216 Self::InitialWorld(error) => Some(error),
217 Self::InvalidInitialFactory
218 | Self::LifecycleTraceAllocation { .. }
219 | Self::MissingApplicationResource { .. }
220 | Self::ApplicationResourceInvariant => None,
221 }
222 }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum LifecycleEvent {
228 WorldEnter,
230 WorldExit,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct LifecycleRecord {
237 pub(super) event: LifecycleEvent,
238 pub(super) generation: WorldGeneration,
239 pub(super) factory: WorldFactoryId,
240}
241
242impl LifecycleRecord {
243 pub const fn event(self) -> LifecycleEvent {
245 self.event
246 }
247
248 pub const fn generation(self) -> WorldGeneration {
250 self.generation
251 }
252
253 pub const fn factory(self) -> WorldFactoryId {
255 self.factory
256 }
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub enum TransitionRequestFailure {
262 InvalidFactory,
264 InvalidIntent,
267}
268
269#[derive(Debug)]
271pub enum FrameTransition {
272 None,
275 Rejected(TransitionRejection),
277 Invalid(TransitionRequestFailure),
279 PreparationFailed {
282 target: WorldFactoryId,
284 error: CandidateFailure,
286 },
287 Committed {
289 old: WorldGeneration,
291 new: WorldGeneration,
293 target: WorldFactoryId,
295 warning: Option<ConvergentTransitionWarning>,
297 },
298}
299
300#[derive(Debug)]
303pub enum FrameFailure {
304 System {
306 stage: Stage,
308 error: SystemRunFailure,
310 },
311 Commands {
313 stage: Stage,
315 error: CommandBatchError,
317 },
318 Time(TimeAdvanceError),
320 Extraction(ExtractionError),
322 RuntimeInvariant,
324}
325
326impl fmt::Display for FrameFailure {
327 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328 match self {
329 Self::System { stage, error } => {
330 write!(formatter, "{stage:?} System failed: {error}")
331 }
332 Self::Commands { stage, error } => {
333 write!(formatter, "{stage:?} Commands failed: {error}")
334 }
335 Self::Time(error) => write!(formatter, "fixed-time cleanup failed: {error}"),
336 Self::Extraction(error) => write!(formatter, "render extraction failed: {error}"),
337 Self::RuntimeInvariant => {
338 formatter.write_str("a private frame runtime invariant was violated")
339 }
340 }
341 }
342}
343
344impl Error for FrameFailure {
345 fn source(&self) -> Option<&(dyn Error + 'static)> {
346 match self {
347 Self::System { error, .. } => Some(error),
348 Self::Commands { error, .. } => Some(error),
349 Self::Time(error) => Some(error),
350 Self::Extraction(error) => Some(error),
351 Self::RuntimeInvariant => None,
352 }
353 }
354}
355
356#[derive(Debug)]
358pub struct LogicFrameReport {
359 pub(super) frame_index: u64,
360 pub(super) timing: FixedFramePlan,
361 pub(super) fixed_ticks_attempted: u32,
362 pub(super) spawned: usize,
363 pub(super) despawned: usize,
364 pub(super) exit_requested: bool,
365 pub(super) transitions_suppressed_by_exit: usize,
366 pub(super) dropped_for_transition: Option<DroppedFixedTime>,
367 pub(super) transition: FrameTransition,
368 pub(super) extracted_generation: Option<WorldGeneration>,
369 pub(super) failure: Option<FrameFailure>,
370}
371
372impl LogicFrameReport {
373 pub const fn frame_index(&self) -> u64 {
375 self.frame_index
376 }
377
378 pub const fn timing(&self) -> FixedFramePlan {
380 self.timing
381 }
382
383 pub const fn fixed_ticks_attempted(&self) -> u32 {
385 self.fixed_ticks_attempted
386 }
387
388 pub const fn spawned(&self) -> usize {
390 self.spawned
391 }
392
393 pub const fn despawned(&self) -> usize {
395 self.despawned
396 }
397
398 pub const fn exit_requested(&self) -> bool {
403 self.exit_requested
404 }
405
406 pub const fn transitions_suppressed_by_exit(&self) -> usize {
408 self.transitions_suppressed_by_exit
409 }
410
411 pub const fn dropped_for_transition(&self) -> Option<DroppedFixedTime> {
413 self.dropped_for_transition
414 }
415
416 pub const fn transition(&self) -> &FrameTransition {
418 &self.transition
419 }
420
421 pub const fn extracted_generation(&self) -> Option<WorldGeneration> {
423 self.extracted_generation
424 }
425
426 pub const fn failure(&self) -> Option<&FrameFailure> {
429 self.failure.as_ref()
430 }
431}
432
433#[derive(Debug)]
435#[expect(
436 clippy::large_enum_variant,
437 reason = "keeping the hot-path frame report inline avoids one allocation per frame"
438)]
439pub enum FrameOutcome {
440 Rejected(BeginFrameRejection),
442 Advanced(LogicFrameReport),
445}