bevy_ecs/system/input.rs
1use core::ops::{Deref, DerefMut};
2
3use variadics_please::all_tuples;
4
5use crate::{bundle::Bundle, event::Event, prelude::On, system::System};
6
7/// Trait for types that can be used as input to [`System`]s.
8///
9/// Provided implementations are:
10/// - `()`: No input
11/// - [`In<T>`]: For values
12/// - [`InRef<T>`]: For read-only references to values
13/// - [`InMut<T>`]: For mutable references to values
14/// - [`On<E, B>`]: For [`ObserverSystem`]s
15/// - [`StaticSystemInput<I>`]: For arbitrary [`SystemInput`]s in generic contexts
16/// - `Option<I>`: For optional inputs of some [`SystemInput`] `I`
17/// - Tuples of [`SystemInput`]s up to 8 elements
18///
19/// For advanced usecases, you can implement this trait for your own types.
20///
21/// # Examples
22///
23/// ## Tuples of [`SystemInput`]s
24///
25/// ```
26/// use bevy_ecs::prelude::*;
27///
28/// fn add((InMut(a), In(b)): (InMut<usize>, In<usize>)) {
29/// *a += b;
30/// }
31/// # let mut world = World::new();
32/// # let mut add = IntoSystem::into_system(add);
33/// # add.initialize(&mut world);
34/// # let mut a = 12;
35/// # let b = 24;
36/// # add.run((&mut a, b), &mut world);
37/// # assert_eq!(a, 36);
38/// ```
39///
40/// [`ObserverSystem`]: crate::system::ObserverSystem
41pub trait SystemInput: Sized {
42 /// The wrapper input type that is defined as the first argument to [`FunctionSystem`]s.
43 ///
44 /// [`FunctionSystem`]: crate::system::FunctionSystem
45 type Param<'i>: SystemInput;
46 /// The inner input type that is passed to functions that run systems,
47 /// such as [`System::run`].
48 ///
49 /// [`System::run`]: crate::system::System::run
50 type Inner<'i>;
51
52 /// Converts a [`SystemInput::Inner`] into a [`SystemInput::Param`].
53 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_>;
54}
55
56/// Shorthand way to get the [`System::In`] for a [`System`] as a [`SystemInput::Inner`].
57pub type SystemIn<'a, S> = <<S as System>::In as SystemInput>::Inner<'a>;
58
59/// A type that may be constructed from the input of a [`System`].
60/// This is used to allow systems whose first parameter is a `StaticSystemInput<In>`
61/// to take an `In` as input, and can be implemented for user types to allow
62/// similar conversions.
63pub trait FromInput<In: SystemInput>: SystemInput {
64 /// Converts the system input's inner representation into this type's
65 /// inner representation.
66 fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i>;
67}
68
69impl<In: SystemInput> FromInput<In> for In {
70 #[inline]
71 fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i> {
72 inner
73 }
74}
75
76impl<'a, In: SystemInput> FromInput<In> for StaticSystemInput<'a, In> {
77 #[inline]
78 fn from_inner<'i>(inner: In::Inner<'i>) -> Self::Inner<'i> {
79 inner
80 }
81}
82
83/// A [`SystemInput`] type which denotes that a [`System`] receives
84/// an input value of type `T` from its caller.
85///
86/// [`System`]s may take an optional input which they require to be passed to them when they
87/// are being [`run`](System::run). For [`FunctionSystem`]s the input may be marked
88/// with this `In` type, but only the first param of a function may be tagged as an input. This also
89/// means a system can only have one or zero input parameters.
90///
91/// See [`SystemInput`] to learn more about system inputs in general.
92///
93/// # Examples
94///
95/// Here is a simple example of a system that takes a [`usize`] and returns the square of it.
96///
97/// ```
98/// # use bevy_ecs::prelude::*;
99/// #
100/// fn square(In(input): In<usize>) -> usize {
101/// input * input
102/// }
103///
104/// let mut world = World::new();
105/// let mut square_system = IntoSystem::into_system(square);
106/// square_system.initialize(&mut world);
107///
108/// assert_eq!(square_system.run(12, &mut world).unwrap(), 144);
109/// ```
110///
111/// [`SystemParam`]: crate::system::SystemParam
112/// [`FunctionSystem`]: crate::system::FunctionSystem
113#[derive(Debug)]
114pub struct In<T>(pub T);
115
116impl<T: 'static> SystemInput for In<T> {
117 type Param<'i> = In<T>;
118 type Inner<'i> = T;
119
120 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
121 In(this)
122 }
123}
124
125impl<T> Deref for In<T> {
126 type Target = T;
127
128 fn deref(&self) -> &Self::Target {
129 &self.0
130 }
131}
132
133impl<T> DerefMut for In<T> {
134 fn deref_mut(&mut self) -> &mut Self::Target {
135 &mut self.0
136 }
137}
138
139/// A [`SystemInput`] type which denotes that a [`System`] receives
140/// a read-only reference to a value of type `T` from its caller.
141///
142/// This is similar to [`In`] but takes a reference to a value instead of the value itself.
143/// See [`InMut`] for the mutable version.
144///
145/// See [`SystemInput`] to learn more about system inputs in general.
146///
147/// # Examples
148///
149/// Here is a simple example of a system that logs the passed in message.
150///
151/// ```
152/// # use bevy_ecs::prelude::*;
153/// # use std::fmt::Write as _;
154/// #
155/// #[derive(Resource, Default)]
156/// struct Log(String);
157///
158/// fn log(InRef(msg): InRef<str>, mut log: ResMut<Log>) {
159/// writeln!(log.0, "{}", msg).unwrap();
160/// }
161///
162/// let mut world = World::new();
163/// world.init_resource::<Log>();
164/// let mut log_system = IntoSystem::into_system(log);
165/// log_system.initialize(&mut world);
166///
167/// log_system.run("Hello, world!", &mut world);
168/// # assert_eq!(world.get_resource::<Log>().unwrap().0, "Hello, world!\n");
169/// ```
170///
171/// [`SystemParam`]: crate::system::SystemParam
172#[derive(Debug)]
173pub struct InRef<'i, T: ?Sized>(pub &'i T);
174
175impl<T: ?Sized + 'static> SystemInput for InRef<'_, T> {
176 type Param<'i> = InRef<'i, T>;
177 type Inner<'i> = &'i T;
178
179 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
180 InRef(this)
181 }
182}
183
184impl<'i, T: ?Sized> Deref for InRef<'i, T> {
185 type Target = T;
186
187 fn deref(&self) -> &Self::Target {
188 self.0
189 }
190}
191
192/// A [`SystemInput`] type which denotes that a [`System`] receives
193/// a mutable reference to a value of type `T` from its caller.
194///
195/// This is similar to [`In`] but takes a mutable reference to a value instead of the value itself.
196/// See [`InRef`] for the read-only version.
197///
198/// See [`SystemInput`] to learn more about system inputs in general.
199///
200/// # Examples
201///
202/// Here is a simple example of a system that takes a `&mut usize` and squares it.
203///
204/// ```
205/// # use bevy_ecs::prelude::*;
206/// #
207/// fn square(InMut(input): InMut<usize>) {
208/// *input *= *input;
209/// }
210///
211/// let mut world = World::new();
212/// let mut square_system = IntoSystem::into_system(square);
213/// square_system.initialize(&mut world);
214///
215/// let mut value = 12;
216/// square_system.run(&mut value, &mut world);
217/// assert_eq!(value, 144);
218/// ```
219///
220/// [`SystemParam`]: crate::system::SystemParam
221#[derive(Debug)]
222pub struct InMut<'a, T: ?Sized>(pub &'a mut T);
223
224impl<T: ?Sized + 'static> SystemInput for InMut<'_, T> {
225 type Param<'i> = InMut<'i, T>;
226 type Inner<'i> = &'i mut T;
227
228 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
229 InMut(this)
230 }
231}
232
233impl<'i, T: ?Sized> Deref for InMut<'i, T> {
234 type Target = T;
235
236 fn deref(&self) -> &Self::Target {
237 self.0
238 }
239}
240
241impl<'i, T: ?Sized> DerefMut for InMut<'i, T> {
242 fn deref_mut(&mut self) -> &mut Self::Target {
243 self.0
244 }
245}
246
247/// Used for [`ObserverSystem`]s.
248///
249/// [`ObserverSystem`]: crate::system::ObserverSystem
250impl<E: Event, B: Bundle> SystemInput for On<'_, '_, E, B> {
251 // Note: the fact that we must use a shared lifetime here is
252 // a key piece of the complicated safety story documented above
253 // the `&mut E::Trigger<'_>` cast in `observer_system_runner` and in
254 // the `On` implementation.
255 type Param<'i> = On<'i, 'i, E, B>;
256 type Inner<'i> = On<'i, 'i, E, B>;
257
258 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
259 this
260 }
261}
262
263/// A helper for using [`SystemInput`]s in generic contexts.
264///
265/// This type is a [`SystemInput`] adapter which always has
266/// `Self::Param == Self` (ignoring lifetimes for brevity),
267/// no matter the argument [`SystemInput`] (`I`).
268///
269/// This makes it useful for having arbitrary [`SystemInput`]s in
270/// function systems.
271///
272/// See [`SystemInput`] to learn more about system inputs in general.
273pub struct StaticSystemInput<'a, I: SystemInput>(pub I::Inner<'a>);
274
275impl<'a, I: SystemInput> SystemInput for StaticSystemInput<'a, I> {
276 type Param<'i> = StaticSystemInput<'i, I>;
277 type Inner<'i> = I::Inner<'i>;
278
279 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
280 StaticSystemInput(this)
281 }
282}
283
284impl<I: SystemInput> SystemInput for Option<I> {
285 type Param<'i> = Option<I::Param<'i>>;
286 type Inner<'i> = Option<I::Inner<'i>>;
287
288 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
289 this.map(I::wrap)
290 }
291}
292
293macro_rules! impl_system_input_tuple {
294 ($(#[$meta:meta])* $($name:ident),*) => {
295 $(#[$meta])*
296 impl<$($name: SystemInput),*> SystemInput for ($($name,)*) {
297 type Param<'i> = ($($name::Param<'i>,)*);
298 type Inner<'i> = ($($name::Inner<'i>,)*);
299
300 #[expect(
301 clippy::allow_attributes,
302 reason = "This is in a macro; as such, the below lints may not always apply."
303 )]
304 #[allow(
305 non_snake_case,
306 reason = "Certain variable names are provided by the caller, not by us."
307 )]
308 #[allow(
309 clippy::unused_unit,
310 reason = "Zero-length tuples won't have anything to wrap."
311 )]
312 fn wrap(this: Self::Inner<'_>) -> Self::Param<'_> {
313 let ($($name,)*) = this;
314 ($($name::wrap($name),)*)
315 }
316 }
317 };
318}
319
320all_tuples!(
321 #[doc(fake_variadic)]
322 impl_system_input_tuple,
323 0,
324 8,
325 I
326);
327
328#[cfg(test)]
329mod tests {
330 use crate::{
331 system::{assert_is_system, In, InMut, InRef, IntoSystem, StaticSystemInput, System},
332 world::World,
333 };
334
335 #[test]
336 fn two_tuple() {
337 fn by_value((In(a), In(b)): (In<usize>, In<usize>)) -> usize {
338 a + b
339 }
340 fn by_ref((InRef(a), InRef(b)): (InRef<usize>, InRef<usize>)) -> usize {
341 *a + *b
342 }
343 fn by_mut((InMut(a), In(b)): (InMut<usize>, In<usize>)) {
344 *a += b;
345 }
346
347 let mut world = World::new();
348 let mut by_value = IntoSystem::into_system(by_value);
349 let mut by_ref = IntoSystem::into_system(by_ref);
350 let mut by_mut = IntoSystem::into_system(by_mut);
351
352 by_value.initialize(&mut world);
353 by_ref.initialize(&mut world);
354 by_mut.initialize(&mut world);
355
356 let mut a = 12;
357 let b = 24;
358
359 assert_eq!(by_value.run((a, b), &mut world).unwrap(), 36);
360 assert_eq!(by_ref.run((&a, &b), &mut world).unwrap(), 36);
361 by_mut.run((&mut a, b), &mut world).unwrap();
362 assert_eq!(a, 36);
363 }
364
365 #[test]
366 fn compatible_input() {
367 fn takes_usize(In(a): In<usize>) -> usize {
368 a
369 }
370
371 fn takes_static_usize(StaticSystemInput(b): StaticSystemInput<In<usize>>) -> usize {
372 b
373 }
374
375 assert_is_system::<In<usize>, usize, _>(takes_usize);
376 // test if StaticSystemInput is compatible with its inner type
377 assert_is_system::<In<usize>, usize, _>(takes_static_usize);
378 }
379
380 #[test]
381 fn option_input() {
382 fn takes_option_mut(a: Option<InMut<usize>>) -> usize {
383 a.map(|InMut(x)| *x).unwrap_or(0)
384 }
385
386 let mut world = World::new();
387
388 let mut system = IntoSystem::into_system(takes_option_mut);
389 system.initialize(&mut world);
390
391 let mut value = 12;
392 assert_eq!(system.run(Some(&mut value), &mut world).unwrap(), 12);
393 assert_eq!(system.run(None, &mut world).unwrap(), 0);
394 }
395}