Skip to main content

sim_logic/ecs/
system.rs

1//! Sequential, per-World System construction and execution.
2
3use std::{error::Error, fmt, marker::PhantomData, sync::Arc};
4
5use bevy_ecs::{
6    component::{Component, Mutable},
7    query::{QueryData, QueryFilter},
8    resource::Resource,
9    system::{BoxedSystem, IntoSystem, IsFunctionSystem, Res, ResMut, SystemParamFunction},
10    world::World,
11};
12
13use crate::{
14    collision::{CircleOverlapEntities, RectangleOverlapEntities},
15    commands::LogicCommands,
16    events::{EventReader, EventRegistry, EventWriter, WorldEvent, event_stage_failure},
17    identity::LogicEntityRef,
18    input::{Action, FixedInput, FrameInput},
19    query::{Query, Single},
20    render::FrameViewport,
21    resources::{AppRes, AppResMut, ApplicationResourceRegistry},
22    time::{FixedTime, FrameTime},
23    visual::{ActiveCamera2d, Transform2d},
24};
25
26mod supported {
27    use crate::{events::EventRegistry, resources::ApplicationResourceRegistry};
28
29    pub trait QueryData {}
30    #[allow(private_interfaces)]
31    pub trait Param {
32        fn register_events(_registry: &mut EventRegistry) {}
33        fn register_application_resources(
34            _registry: &mut ApplicationResourceRegistry,
35            _stage: super::Stage,
36            _system: &'static str,
37        ) {
38        }
39        fn writes_events() -> bool {
40            false
41        }
42        fn uses_application_resources() -> bool {
43            false
44        }
45    }
46    #[allow(private_interfaces)]
47    pub trait Tuple {
48        fn register_events(registry: &mut EventRegistry);
49        fn register_application_resources(
50            registry: &mut ApplicationResourceRegistry,
51            stage: super::Stage,
52            system: &'static str,
53        );
54        fn writes_events() -> bool;
55        fn uses_application_resources() -> bool;
56    }
57}
58
59/// Compile-time marker for the System-parameter tuples accepted by the managed
60/// first-slice scheduler.
61///
62/// Sim;Logic implements this sealed trait for generation-checked
63/// [`crate::query::Query`], [`crate::query::Single`],
64/// [`crate::collision::CircleOverlapEntities`],
65/// [`crate::collision::RectangleOverlapEntities`], `Res`, `ResMut`,
66/// [`crate::resources::AppRes`], [`crate::resources::AppResMut`], its own
67/// read-only frame parameters, and [`LogicCommands`]. Raw Bevy `Query` or
68/// `Single`, raw `Entity`, and parameters with
69/// initialization-time World access, including Bevy `Local<T: FromWorld>`, are
70/// intentionally excluded. Typed event parameters register their channels
71/// automatically when a System is added. Application Resource parameters
72/// register a required type and are forbidden in Startup.
73pub trait SupportedSystemParamTuple: supported::Tuple {}
74
75impl<T: supported::Tuple> SupportedSystemParamTuple for T {}
76
77impl supported::QueryData for () {}
78impl<T: Component> supported::QueryData for &T {}
79impl<T: Component> supported::QueryData for &mut T {}
80impl supported::QueryData for LogicEntityRef {}
81impl<D> supported::QueryData for Option<D> where D: QueryData + supported::QueryData {}
82
83macro_rules! impl_supported_query_tuple {
84    ($($parameter:ident),+) => {
85        impl<$($parameter),+> supported::QueryData for ($($parameter,)+)
86        where
87            $($parameter: QueryData + supported::QueryData,)+
88        {}
89    };
90}
91
92impl_supported_query_tuple!(P0);
93impl_supported_query_tuple!(P0, P1);
94impl_supported_query_tuple!(P0, P1, P2);
95impl_supported_query_tuple!(P0, P1, P2, P3);
96impl_supported_query_tuple!(P0, P1, P2, P3, P4);
97impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5);
98impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6);
99impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7);
100impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8);
101impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9);
102impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
103impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
104impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12);
105impl_supported_query_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13);
106impl_supported_query_tuple!(
107    P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14
108);
109impl_supported_query_tuple!(
110    P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15
111);
112
113impl<D, F> supported::Param for Query<'_, '_, D, F>
114where
115    D: QueryData + supported::QueryData,
116    F: QueryFilter,
117{
118}
119impl<D, F> supported::Param for Single<'_, '_, D, F>
120where
121    D: bevy_ecs::query::IterQueryData + supported::QueryData,
122    F: QueryFilter,
123{
124}
125impl<R: Resource> supported::Param for Res<'_, R> {}
126impl<R: Resource<Mutability = Mutable>> supported::Param for ResMut<'_, R> {}
127impl<R: Resource> supported::Param for Option<Res<'_, R>> {}
128impl<R: Resource<Mutability = Mutable>> supported::Param for Option<ResMut<'_, R>> {}
129#[allow(
130    private_interfaces,
131    reason = "this implementation registers a private resource requirement through a sealed hook"
132)]
133impl<T: Send + Sync + 'static> supported::Param for AppRes<'_, T> {
134    fn register_application_resources(
135        registry: &mut ApplicationResourceRegistry,
136        stage: Stage,
137        system: &'static str,
138    ) {
139        registry.require::<T>(stage, system);
140    }
141
142    fn uses_application_resources() -> bool {
143        true
144    }
145}
146#[allow(
147    private_interfaces,
148    reason = "this implementation registers a private resource requirement through a sealed hook"
149)]
150impl<T: Send + Sync + 'static> supported::Param for AppResMut<'_, T> {
151    fn register_application_resources(
152        registry: &mut ApplicationResourceRegistry,
153        stage: Stage,
154        system: &'static str,
155    ) {
156        registry.require::<T>(stage, system);
157    }
158
159    fn uses_application_resources() -> bool {
160        true
161    }
162}
163impl<A: Action> supported::Param for FrameInput<'_, A> {}
164impl<A: Action> supported::Param for FixedInput<'_, A> {}
165impl<F: QueryFilter> supported::Param for CircleOverlapEntities<'_, '_, F> {}
166impl<F: QueryFilter> supported::Param for RectangleOverlapEntities<'_, '_, F> {}
167impl supported::Param for FrameTime<'_> {}
168impl supported::Param for FixedTime<'_> {}
169impl supported::Param for FrameViewport<'_> {}
170impl supported::Param for LogicCommands<'_> {}
171#[allow(
172    private_interfaces,
173    reason = "this implementation registers events through a sealed private hook"
174)]
175impl<E: WorldEvent> supported::Param for EventWriter<'_, E> {
176    fn register_events(registry: &mut EventRegistry) {
177        registry.register::<E>();
178    }
179
180    fn writes_events() -> bool {
181        true
182    }
183}
184#[allow(
185    private_interfaces,
186    reason = "this implementation registers events through a sealed private hook"
187)]
188impl<E: WorldEvent> supported::Param for EventReader<'_, E> {
189    fn register_events(registry: &mut EventRegistry) {
190        registry.register::<E>();
191    }
192}
193
194#[allow(
195    private_interfaces,
196    reason = "this implementation is hidden with the sealed tuple trait"
197)]
198impl supported::Tuple for () {
199    fn register_events(_registry: &mut EventRegistry) {}
200
201    fn register_application_resources(
202        _registry: &mut ApplicationResourceRegistry,
203        _stage: Stage,
204        _system: &'static str,
205    ) {
206    }
207
208    fn writes_events() -> bool {
209        false
210    }
211
212    fn uses_application_resources() -> bool {
213        false
214    }
215}
216
217macro_rules! impl_supported_param_tuple {
218    ($($parameter:ident),+) => {
219        #[allow(
220            private_interfaces,
221            reason = "this implementation is hidden with the sealed tuple trait"
222        )]
223        impl<$($parameter),+> supported::Tuple for ($($parameter,)+)
224        where
225            $($parameter: supported::Param,)+
226        {
227            fn register_events(registry: &mut EventRegistry) {
228                $(<$parameter as supported::Param>::register_events(registry);)+
229            }
230
231            fn register_application_resources(
232                registry: &mut ApplicationResourceRegistry,
233                stage: Stage,
234                system: &'static str,
235            ) {
236                $(<$parameter as supported::Param>::register_application_resources(
237                    registry,
238                    stage,
239                    system,
240                );)+
241            }
242
243            fn writes_events() -> bool {
244                false $(|| <$parameter as supported::Param>::writes_events())+
245            }
246
247            fn uses_application_resources() -> bool {
248                false $(|| <$parameter as supported::Param>::uses_application_resources())+
249            }
250        }
251    };
252}
253
254impl_supported_param_tuple!(P0);
255impl_supported_param_tuple!(P0, P1);
256impl_supported_param_tuple!(P0, P1, P2);
257impl_supported_param_tuple!(P0, P1, P2, P3);
258impl_supported_param_tuple!(P0, P1, P2, P3, P4);
259impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5);
260impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6);
261impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7);
262impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8);
263impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9);
264impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
265impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
266impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12);
267impl_supported_param_tuple!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13);
268impl_supported_param_tuple!(
269    P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14
270);
271impl_supported_param_tuple!(
272    P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15
273);
274
275pub(crate) fn register_system_events<P: SupportedSystemParamTuple>(registry: &mut EventRegistry) {
276    <P as supported::Tuple>::register_events(registry);
277}
278
279pub(crate) fn register_system_application_resources<P: SupportedSystemParamTuple>(
280    registry: &mut ApplicationResourceRegistry,
281    stage: Stage,
282    system: &'static str,
283) {
284    <P as supported::Tuple>::register_application_resources(registry, stage, system);
285}
286
287/// A user-facing System stage in the first Sim;Logic execution model.
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
289pub enum Stage {
290    /// Runs once while a World candidate is still isolated.
291    Startup,
292    /// Runs zero or more times using the configured fixed step.
293    FixedUpdate,
294    /// Runs once per successful application frame when no fixed-stage
295    /// transition is pending.
296    FrameUpdate,
297}
298
299/// A System cannot participate in Sim;Logic's managed schedule.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub enum SystemSetupError {
302    /// The System owns a Bevy deferred buffer such as `bevy_ecs::Commands`.
303    Deferred {
304        /// Bevy's diagnostic System name.
305        system: String,
306    },
307    /// The System requests exclusive access such as `&mut bevy_ecs::World`.
308    Exclusive {
309        /// Bevy's diagnostic System name.
310        system: String,
311    },
312    /// A System requests write access to interpolation-owned transforms in
313    /// FrameUpdate.
314    FrameTransformWrite {
315        /// Bevy's diagnostic System name.
316        system: String,
317    },
318    /// A System requests write access to the interpolation-owned camera in
319    /// FrameUpdate.
320    FrameCameraWrite {
321        /// Bevy's diagnostic System name.
322        system: String,
323    },
324    /// Startup requested live Application state while its World was provisional.
325    StartupApplicationResourceAccess {
326        /// Bevy's diagnostic System name.
327        system: String,
328    },
329}
330
331impl fmt::Display for SystemSetupError {
332    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
333        match self {
334            Self::Deferred { system } => write!(
335                formatter,
336                "system `{system}` uses a deferred Bevy buffer; use Sim;Logic Commands"
337            ),
338            Self::Exclusive { system } => write!(
339                formatter,
340                "system `{system}` requests exclusive World access, which bypasses Sim;Logic"
341            ),
342            Self::FrameTransformWrite { system } => write!(
343                formatter,
344                "FrameUpdate system `{system}` requests mutable Transform2d access"
345            ),
346            Self::FrameCameraWrite { system } => write!(
347                formatter,
348                "FrameUpdate system `{system}` requests mutable ActiveCamera2d access"
349            ),
350            Self::StartupApplicationResourceAccess { system } => write!(
351                formatter,
352                "Startup system `{system}` requests an Application Resource; candidate Startup is isolated from live Application state"
353            ),
354        }
355    }
356}
357
358impl Error for SystemSetupError {}
359
360/// A typed failure returned while running one managed System.
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct SystemRunFailure {
363    system: String,
364    reason: String,
365}
366
367impl SystemRunFailure {
368    /// Returns Bevy's diagnostic name for the failed System.
369    pub fn system(&self) -> &str {
370        &self.system
371    }
372
373    /// Returns the parameter-validation, execution, or user-returned failure text.
374    pub fn reason(&self) -> &str {
375        &self.reason
376    }
377}
378
379impl fmt::Display for SystemRunFailure {
380    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
381        write!(
382            formatter,
383            "system `{}` could not run: {}",
384            self.system, self.reason
385        )
386    }
387}
388
389impl Error for SystemRunFailure {}
390
391type ManagedSystemOutcome = Result<(), String>;
392type ManagedBoxedSystem = BoxedSystem<(), ManagedSystemOutcome>;
393
394fn completed_system((): ()) -> ManagedSystemOutcome {
395    Ok(())
396}
397
398fn returned_system<E: fmt::Display>(result: Result<(), E>) -> ManagedSystemOutcome {
399    result.map_err(|error| format!("returned an error: {error}"))
400}
401
402trait RecreateSystem: Send + Sync + 'static {
403    fn create(&self) -> ManagedBoxedSystem;
404    fn diagnostic_name(&self) -> &'static str;
405    fn writes_events(&self) -> bool;
406    fn uses_application_resources(&self) -> bool;
407}
408
409struct ClonedSystemFactory<S, FunctionMarker> {
410    template: S,
411    diagnostic_name: &'static str,
412    marker: PhantomData<fn() -> FunctionMarker>,
413}
414
415impl<S, FunctionMarker> RecreateSystem for ClonedSystemFactory<S, FunctionMarker>
416where
417    S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static,
418    S::Param: SupportedSystemParamTuple,
419    FunctionMarker: 'static,
420{
421    fn create(&self) -> ManagedBoxedSystem {
422        let system = IntoSystem::<(), (), (IsFunctionSystem, FunctionMarker)>::into_system(
423            self.template.clone(),
424        );
425        Box::new(IntoSystem::into_system(system.map(completed_system)))
426    }
427
428    fn diagnostic_name(&self) -> &'static str {
429        self.diagnostic_name
430    }
431
432    fn writes_events(&self) -> bool {
433        <S::Param as supported::Tuple>::writes_events()
434    }
435
436    fn uses_application_resources(&self) -> bool {
437        <S::Param as supported::Tuple>::uses_application_resources()
438    }
439}
440
441struct FallibleClonedSystemFactory<S, FunctionMarker, E> {
442    template: S,
443    diagnostic_name: &'static str,
444    marker: PhantomData<fn() -> (FunctionMarker, E)>,
445}
446
447impl<S, FunctionMarker, E> RecreateSystem for FallibleClonedSystemFactory<S, FunctionMarker, E>
448where
449    S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>>
450        + Clone
451        + Send
452        + Sync
453        + 'static,
454    S::Param: SupportedSystemParamTuple,
455    FunctionMarker: 'static,
456    E: fmt::Display + 'static,
457{
458    fn create(&self) -> ManagedBoxedSystem {
459        let system =
460            IntoSystem::<(), Result<(), E>, (IsFunctionSystem, FunctionMarker)>::into_system(
461                self.template.clone(),
462            );
463        Box::new(IntoSystem::into_system(system.map(returned_system::<E>)))
464    }
465
466    fn diagnostic_name(&self) -> &'static str {
467        self.diagnostic_name
468    }
469
470    fn writes_events(&self) -> bool {
471        <S::Param as supported::Tuple>::writes_events()
472    }
473
474    fn uses_application_resources(&self) -> bool {
475        <S::Param as supported::Tuple>::uses_application_resources()
476    }
477}
478
479#[derive(Clone, Default)]
480pub(crate) struct StageFactories {
481    factories: Vec<Arc<dyn RecreateSystem>>,
482}
483
484impl StageFactories {
485    pub(crate) fn first_application_resource_system(&self) -> Option<String> {
486        self.factories
487            .iter()
488            .find(|factory| factory.uses_application_resources())
489            .map(|factory| factory.diagnostic_name().to_owned())
490    }
491
492    pub(crate) fn add<FunctionMarker, S>(&mut self, system: S)
493    where
494        S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static,
495        S::Param: SupportedSystemParamTuple,
496        FunctionMarker: 'static,
497    {
498        self.factories.push(Arc::new(ClonedSystemFactory {
499            template: system,
500            diagnostic_name: std::any::type_name::<S>(),
501            marker: PhantomData,
502        }));
503    }
504
505    pub(crate) fn add_fallible<FunctionMarker, S, E>(&mut self, system: S)
506    where
507        S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>>
508            + Clone
509            + Send
510            + Sync
511            + 'static,
512        S::Param: SupportedSystemParamTuple,
513        FunctionMarker: 'static,
514        E: fmt::Display + 'static,
515    {
516        self.factories.push(Arc::new(FallibleClonedSystemFactory {
517            template: system,
518            diagnostic_name: std::any::type_name::<S>(),
519            marker: PhantomData,
520        }));
521    }
522
523    pub(crate) fn instantiate(
524        &self,
525        world: &mut World,
526        stage: Stage,
527    ) -> Result<SequentialStage, SystemSetupError> {
528        let mut systems = Vec::with_capacity(self.factories.len());
529
530        for factory in &self.factories {
531            let mut system = factory.create();
532            let writes_events = factory.writes_events();
533            let name = system.name().to_string();
534
535            if stage == Stage::Startup && factory.uses_application_resources() {
536                return Err(SystemSetupError::StartupApplicationResourceAccess { system: name });
537            }
538
539            if system.has_deferred() {
540                return Err(SystemSetupError::Deferred { system: name });
541            }
542            if system.is_exclusive() {
543                return Err(SystemSetupError::Exclusive { system: name });
544            }
545
546            let access = system.initialize(world);
547            if stage == Stage::FrameUpdate
548                && world
549                    .component_id::<Transform2d>()
550                    .is_some_and(|component| access.combined_access().has_write(component))
551            {
552                return Err(SystemSetupError::FrameTransformWrite { system: name });
553            }
554            if stage == Stage::FrameUpdate
555                && world
556                    .component_id::<ActiveCamera2d>()
557                    .is_some_and(|component| access.combined_access().has_write(component))
558            {
559                return Err(SystemSetupError::FrameCameraWrite { system: name });
560            }
561
562            systems.push(ManagedSystem {
563                name,
564                system,
565                writes_events,
566            });
567        }
568
569        let writes_events = systems.iter().any(|system| system.writes_events);
570        Ok(SequentialStage {
571            systems,
572            writes_events,
573        })
574    }
575}
576
577pub(crate) struct SequentialStage {
578    systems: Vec<ManagedSystem>,
579    writes_events: bool,
580}
581
582struct ManagedSystem {
583    name: String,
584    system: ManagedBoxedSystem,
585    writes_events: bool,
586}
587
588impl SequentialStage {
589    pub(crate) fn is_empty(&self) -> bool {
590        self.systems.is_empty()
591    }
592
593    pub(crate) const fn writes_events(&self) -> bool {
594        self.writes_events
595    }
596
597    pub(crate) fn run(&mut self, world: &mut World) -> Result<(), SystemRunFailure> {
598        for managed in &mut self.systems {
599            let outcome = managed
600                .system
601                .run_without_applying_deferred((), world)
602                .map_err(|error| SystemRunFailure {
603                    system: managed.name.clone(),
604                    reason: error.to_string(),
605                })?;
606            outcome.map_err(|reason| SystemRunFailure {
607                system: managed.name.clone(),
608                reason,
609            })?;
610            if !managed.writes_events {
611                continue;
612            }
613            match event_stage_failure(world) {
614                Ok(Some(failure)) => {
615                    return Err(SystemRunFailure {
616                        system: managed.name.clone(),
617                        reason: failure.to_string(),
618                    });
619                }
620                Ok(None) => {}
621                Err(()) => {
622                    return Err(SystemRunFailure {
623                        system: managed.name.clone(),
624                        reason: "event failure diagnostics are unavailable".to_owned(),
625                    });
626                }
627            }
628        }
629
630        Ok(())
631    }
632}
633
634#[cfg(test)]
635mod tests {
636    use bevy_ecs::prelude::{ResMut, Resource};
637
638    use super::*;
639
640    #[derive(Resource, Default)]
641    struct Trace(Vec<u8>);
642
643    fn first(mut trace: ResMut<Trace>) {
644        trace.0.push(1);
645    }
646
647    fn second(mut trace: ResMut<Trace>) {
648        trace.0.push(2);
649    }
650
651    fn fallible_first(mut trace: ResMut<Trace>) -> Result<(), &'static str> {
652        trace.0.push(1);
653        Ok(())
654    }
655
656    fn fallible_stop(mut trace: ResMut<Trace>) -> Result<(), &'static str> {
657        trace.0.push(2);
658        Err("deliberate failure")
659    }
660
661    fn fallible_write_transform(
662        mut transforms: Query<&mut Transform2d>,
663    ) -> Result<(), &'static str> {
664        for _transform in &mut transforms {}
665        Ok(())
666    }
667
668    fn write_transform(mut transforms: Query<&mut Transform2d>) {
669        for _transform in &mut transforms {}
670    }
671
672    fn write_single_transform(_transform: Single<&mut Transform2d>) {}
673
674    fn write_camera(mut cameras: Query<&mut ActiveCamera2d>) {
675        for _camera in &mut cameras {}
676    }
677
678    fn write_single_camera(_camera: Single<&mut ActiveCamera2d>) {}
679
680    fn fallible_write_camera(mut cameras: Query<&mut ActiveCamera2d>) -> Result<(), &'static str> {
681        for _camera in &mut cameras {}
682        Ok(())
683    }
684
685    fn read_camera(cameras: Query<&ActiveCamera2d>) {
686        for _camera in &cameras {}
687    }
688
689    #[test]
690    fn executes_in_registration_order() {
691        let mut factories = StageFactories::default();
692        factories.add(first);
693        factories.add(second);
694
695        let mut world = World::new();
696        world.insert_resource(Trace::default());
697        EventRegistry::default().install(&mut world, 1);
698        let stage = factories.instantiate(&mut world, Stage::FixedUpdate);
699        assert!(stage.is_ok());
700        let mut stage = match stage {
701            Ok(stage) => stage,
702            Err(error) => panic!("unexpected setup error: {error}"),
703        };
704
705        assert!(stage.run(&mut world).is_ok());
706        assert_eq!(world.resource::<Trace>().0, [1, 2]);
707    }
708
709    #[test]
710    fn sequential_stage_reports_whether_it_contains_any_systems() {
711        let empty = StageFactories::default();
712        let mut world = World::new();
713        let stage = empty
714            .instantiate(&mut world, Stage::FixedUpdate)
715            .expect("empty stage should instantiate");
716        assert!(stage.is_empty());
717
718        let mut populated = StageFactories::default();
719        populated.add(first);
720        let stage = populated
721            .instantiate(&mut world, Stage::FixedUpdate)
722            .expect("populated stage should instantiate");
723        assert!(!stage.is_empty());
724    }
725
726    #[test]
727    fn fallible_error_stops_later_systems_and_retains_diagnostics() {
728        let mut factories = StageFactories::default();
729        factories.add_fallible(fallible_first);
730        factories.add_fallible(fallible_stop);
731        factories.add(second);
732
733        let mut world = World::new();
734        world.insert_resource(Trace::default());
735        let stage = factories.instantiate(&mut world, Stage::FixedUpdate);
736        assert!(stage.is_ok());
737        let mut stage = match stage {
738            Ok(stage) => stage,
739            Err(error) => panic!("unexpected setup error: {error}"),
740        };
741
742        let error = stage
743            .run(&mut world)
744            .expect_err("second System should fail");
745
746        assert!(
747            error.system().ends_with("fallible_stop"),
748            "unexpected System name: {}",
749            error.system()
750        );
751        assert_eq!(error.reason(), "returned an error: deliberate failure");
752        assert_eq!(world.resource::<Trace>().0, [1, 2]);
753    }
754
755    #[test]
756    fn frame_system_transform_writes_are_rejected_at_setup() {
757        let mut factories = StageFactories::default();
758        factories.add(write_transform);
759        let mut world = World::new();
760
761        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
762
763        assert!(matches!(
764            result,
765            Err(SystemSetupError::FrameTransformWrite { .. })
766        ));
767    }
768
769    #[test]
770    fn fallible_adapter_preserves_frame_transform_access() {
771        let mut factories = StageFactories::default();
772        factories.add_fallible(fallible_write_transform);
773        let mut world = World::new();
774
775        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
776
777        assert!(matches!(
778            result,
779            Err(SystemSetupError::FrameTransformWrite { .. })
780        ));
781    }
782
783    #[test]
784    fn fixed_system_transform_writes_remain_supported() {
785        let mut factories = StageFactories::default();
786        factories.add(write_transform);
787        let mut world = World::new();
788
789        assert!(
790            factories
791                .instantiate(&mut world, Stage::FixedUpdate)
792                .is_ok()
793        );
794    }
795
796    #[test]
797    fn frame_single_transform_writes_are_rejected_at_setup() {
798        let mut factories = StageFactories::default();
799        factories.add(write_single_transform);
800        let mut world = World::new();
801
802        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
803
804        assert!(matches!(
805            result,
806            Err(SystemSetupError::FrameTransformWrite { .. })
807        ));
808    }
809
810    #[test]
811    fn fixed_single_transform_writes_remain_supported() {
812        let mut factories = StageFactories::default();
813        factories.add(write_single_transform);
814        let mut world = World::new();
815
816        assert!(
817            factories
818                .instantiate(&mut world, Stage::FixedUpdate)
819                .is_ok()
820        );
821    }
822
823    #[test]
824    fn frame_system_camera_writes_are_rejected_at_setup() {
825        let mut factories = StageFactories::default();
826        factories.add(write_camera);
827        let mut world = World::new();
828
829        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
830
831        assert!(matches!(
832            result,
833            Err(SystemSetupError::FrameCameraWrite { .. })
834        ));
835    }
836
837    #[test]
838    fn fixed_system_camera_writes_remain_supported() {
839        let mut factories = StageFactories::default();
840        factories.add(write_camera);
841        let mut world = World::new();
842
843        assert!(
844            factories
845                .instantiate(&mut world, Stage::FixedUpdate)
846                .is_ok()
847        );
848    }
849
850    #[test]
851    fn frame_single_camera_writes_are_rejected_at_setup() {
852        let mut factories = StageFactories::default();
853        factories.add(write_single_camera);
854        let mut world = World::new();
855
856        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
857
858        assert!(matches!(
859            result,
860            Err(SystemSetupError::FrameCameraWrite { .. })
861        ));
862    }
863
864    #[test]
865    fn fixed_single_camera_writes_remain_supported() {
866        let mut factories = StageFactories::default();
867        factories.add(write_single_camera);
868        let mut world = World::new();
869
870        assert!(
871            factories
872                .instantiate(&mut world, Stage::FixedUpdate)
873                .is_ok()
874        );
875    }
876
877    #[test]
878    fn fallible_adapter_preserves_frame_camera_access() {
879        let mut factories = StageFactories::default();
880        factories.add_fallible(fallible_write_camera);
881        let mut world = World::new();
882
883        let result = factories.instantiate(&mut world, Stage::FrameUpdate);
884
885        assert!(matches!(
886            result,
887            Err(SystemSetupError::FrameCameraWrite { .. })
888        ));
889    }
890
891    #[test]
892    fn frame_system_camera_reads_remain_supported() {
893        let mut factories = StageFactories::default();
894        factories.add(read_camera);
895        let mut world = World::new();
896
897        assert!(
898            factories
899                .instantiate(&mut world, Stage::FrameUpdate)
900                .is_ok()
901        );
902    }
903}