bevy_ecs/system/
exclusive_system_param.rs

1use crate::{
2    prelude::{FromWorld, QueryState},
3    query::{QueryData, QueryFilter},
4    system::{Local, SystemMeta, SystemParam, SystemState},
5    world::World,
6};
7use bevy_utils::all_tuples;
8use bevy_utils::synccell::SyncCell;
9use std::marker::PhantomData;
10
11/// A parameter that can be used in an exclusive system (a system with an `&mut World` parameter).
12/// Any parameters implementing this trait must come after the `&mut World` parameter.
13#[diagnostic::on_unimplemented(
14    message = "`{Self}` can not be used as a parameter for an exclusive system",
15    label = "invalid system parameter"
16)]
17pub trait ExclusiveSystemParam: Sized {
18    /// Used to store data which persists across invocations of a system.
19    type State: Send + Sync + 'static;
20    /// The item type returned when constructing this system param.
21    /// See [`SystemParam::Item`].
22    type Item<'s>: ExclusiveSystemParam<State = Self::State>;
23
24    /// Creates a new instance of this param's [`State`](Self::State).
25    fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self::State;
26
27    /// Creates a parameter to be passed into an [`ExclusiveSystemParamFunction`].
28    ///
29    /// [`ExclusiveSystemParamFunction`]: super::ExclusiveSystemParamFunction
30    fn get_param<'s>(state: &'s mut Self::State, system_meta: &SystemMeta) -> Self::Item<'s>;
31}
32
33/// Shorthand way of accessing the associated type [`ExclusiveSystemParam::Item`]
34/// for a given [`ExclusiveSystemParam`].
35pub type ExclusiveSystemParamItem<'s, P> = <P as ExclusiveSystemParam>::Item<'s>;
36
37impl<'a, D: QueryData + 'static, F: QueryFilter + 'static> ExclusiveSystemParam
38    for &'a mut QueryState<D, F>
39{
40    type State = QueryState<D, F>;
41    type Item<'s> = &'s mut QueryState<D, F>;
42
43    fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
44        QueryState::new(world)
45    }
46
47    fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
48        state
49    }
50}
51
52impl<'a, P: SystemParam + 'static> ExclusiveSystemParam for &'a mut SystemState<P> {
53    type State = SystemState<P>;
54    type Item<'s> = &'s mut SystemState<P>;
55
56    fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
57        SystemState::new(world)
58    }
59
60    fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
61        state
62    }
63}
64
65impl<'_s, T: FromWorld + Send + 'static> ExclusiveSystemParam for Local<'_s, T> {
66    type State = SyncCell<T>;
67    type Item<'s> = Local<'s, T>;
68
69    fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
70        SyncCell::new(T::from_world(world))
71    }
72
73    fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
74        Local(state.get())
75    }
76}
77
78impl<S: ?Sized> ExclusiveSystemParam for PhantomData<S> {
79    type State = ();
80    type Item<'s> = PhantomData<S>;
81
82    fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {}
83
84    fn get_param<'s>(_state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
85        PhantomData
86    }
87}
88
89macro_rules! impl_exclusive_system_param_tuple {
90    ($($param: ident),*) => {
91        #[allow(unused_variables)]
92        #[allow(non_snake_case)]
93        impl<$($param: ExclusiveSystemParam),*> ExclusiveSystemParam for ($($param,)*) {
94            type State = ($($param::State,)*);
95            type Item<'s> = ($($param::Item<'s>,)*);
96
97            #[inline]
98            fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
99                (($($param::init(_world, _system_meta),)*))
100            }
101
102            #[inline]
103            #[allow(clippy::unused_unit)]
104            fn get_param<'s>(
105                state: &'s mut Self::State,
106                system_meta: &SystemMeta,
107            ) -> Self::Item<'s> {
108
109                let ($($param,)*) = state;
110                ($($param::get_param($param, system_meta),)*)
111            }
112        }
113    };
114}
115
116all_tuples!(impl_exclusive_system_param_tuple, 0, 16, P);
117
118#[cfg(test)]
119mod tests {
120    use crate as bevy_ecs;
121    use crate::schedule::Schedule;
122    use crate::system::Local;
123    use crate::world::World;
124    use bevy_ecs_macros::Resource;
125    use std::marker::PhantomData;
126
127    #[test]
128    fn test_exclusive_system_params() {
129        #[derive(Resource, Default)]
130        struct Res {
131            test_value: u32,
132        }
133
134        fn my_system(world: &mut World, mut local: Local<u32>, _phantom: PhantomData<Vec<u32>>) {
135            assert_eq!(world.resource::<Res>().test_value, *local);
136            *local += 1;
137            world.resource_mut::<Res>().test_value += 1;
138        }
139
140        let mut schedule = Schedule::default();
141        schedule.add_systems(my_system);
142
143        let mut world = World::default();
144        world.init_resource::<Res>();
145
146        schedule.run(&mut world);
147        schedule.run(&mut world);
148
149        assert_eq!(2, world.get_resource::<Res>().unwrap().test_value);
150    }
151}