1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Implements the system API for the ECS.

use crate::prelude::*;

/// Struct used to run a system function using the world.
pub struct System<Out = ()> {
    /// This should be called once to initialize the system, allowing it to intialize any resources
    /// or components in the world.
    ///
    /// Usually only called once, but this is not guaranteed so the implementation should be
    /// idempotent.
    pub initialize: Box<dyn Send + Sync + Fn(&mut World)>,
    /// This is run every time the system is executed
    pub run: Box<dyn Send + Sync + FnMut(&World) -> SystemResult<Out>>,
    /// A best-effort name for the system, for diagnostic purposes.
    pub name: &'static str,
}

impl<Out> std::fmt::Debug for System<Out> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("System")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl<Out> System<Out> {
    /// Initializes the resources required to run this system inside of the provided [`World`], if
    /// those resources don't already exist.
    ///
    /// This is usually only called once, but this is not guaranteed so the implementation should be
    /// idempotent.
    pub fn initialize(&self, world: &mut World) {
        (self.initialize)(world)
    }

    /// Runs the system's function using the provided [`World`]
    pub fn run(&mut self, world: &World) -> SystemResult<Out> {
        (self.run)(world)
    }

    /// Returns the underlying type name of the system.
    ///
    /// This is not guranteed to be stable or human-readable, but can be used for diagnostics.
    pub fn name(&self) -> &'static str {
        self.name
    }
}

/// Converts a function into a [`System`].
///
/// [`IntoSystem`] is automatically implemented for all functions and closures that:
///
/// - Have 26 or less arguments,
/// - Where every argument implments [`SystemParam`], and
/// - That returns either `()` or [`SystemResult`]
///
/// [`IntoSystem`] is also implemented for functions that take [`&World`][World] as an argument, and
/// return either `()` or [`SystemResult`].
///
/// The most common [`SystemParam`] types that you will use as arguments to a system will be:
///  - [`Res`] and [`ResMut`] parameters to access resources
/// - [`Comp`] and [`CompMut`] parameters to access components
pub trait IntoSystem<Args, Out> {
    /// Convert into a [`System`].
    fn system(self) -> System<Out>;
}

impl<Out> IntoSystem<System<Out>, Out> for System<Out> {
    fn system(self) -> System<Out> {
        self
    }
}

impl<F, Out> IntoSystem<(World, F), Out> for F
where
    F: FnMut(&World) -> Out + Send + Sync + 'static,
{
    fn system(mut self) -> System<Out> {
        System {
            initialize: Box::new(|_| ()),
            run: Box::new(move |world| Ok(self(world))),
            name: std::any::type_name::<F>(),
        }
    }
}
impl<F, Out> IntoSystem<(World, F, SystemResult<Out>), Out> for F
where
    F: FnMut(&World) -> SystemResult<Out> + Send + Sync + 'static,
{
    fn system(self) -> System<Out> {
        System {
            initialize: Box::new(|_| ()),
            run: Box::new(self),
            name: std::any::type_name::<F>(),
        }
    }
}

/// Trait used to implement parameters for [`System`] functions.
///
/// Functions that only take arguments implementing [`SystemParam`] automatically implment
/// [`IntoSystem`].
///
/// Implementing [`SystemParam`] manually can be useful for creating new kinds of parameters you may
/// use in your system funciton arguments. Examples might inlclude event readers and writers or
/// other custom ways to access the data inside a [`World`].
pub trait SystemParam: Sized {
    /// The intermediate state for the parameter, that may be extracted from the world.
    type State;
    /// The type of the parameter, ranging over the lifetime of the intermediate state.
    ///
    /// > **ℹ️ Important:** This type must be the same type as `Self`, other than the fact that it
    /// > may range over the lifetime `'s` instead of a generic lifetime from your `impl`.
    /// >
    /// > If the type is not the same, then system functions will not be able to take it as an
    /// > argument.
    type Param<'s>;
    /// This will be called to give the parameter a chance to initialize it's world storage.
    ///
    /// You can use this chance to init any resources or components you need in the world.
    fn initialize(world: &mut World);
    /// This is called to produce the intermediate state of the system parameter.
    ///
    /// This state will be created immediately before the system is run, and will kept alive until
    /// the system is done running.
    fn get_state(world: &World) -> Self::State;
    /// This is used create an instance of the system parame, possibly borrowed from the
    /// intermediate parameter state.
    #[allow(clippy::needless_lifetimes)] // Explicit lifetimes help clarity in this case
    fn borrow<'s>(state: &'s mut Self::State) -> Self::Param<'s>;
}

/// [`SystemParam`] for getting read access to a resource.
pub struct Res<'a, T: TypedEcsData + FromWorld>(AtomicRef<'a, T>);
impl<'a, T: TypedEcsData + FromWorld> std::ops::Deref for Res<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// [`SystemParam`] for getting mutable access to a resource.
pub struct ResMut<'a, T: TypedEcsData + FromWorld>(AtomicRefMut<'a, T>);
impl<'a, T: TypedEcsData + FromWorld> std::ops::Deref for ResMut<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'a, T: TypedEcsData + FromWorld> std::ops::DerefMut for ResMut<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a, T: TypedEcsData + FromWorld> SystemParam for Res<'a, T> {
    type State = AtomicResource<T>;
    type Param<'p> = Res<'p, T>;

    fn initialize(world: &mut World) {
        world.init_resource::<T>()
    }

    fn get_state(world: &World) -> Self::State {
        world.resource::<T>()
    }

    fn borrow(state: &mut Self::State) -> Self::Param<'_> {
        Res(state.borrow())
    }
}

impl<'a, T: TypedEcsData + FromWorld> SystemParam for ResMut<'a, T> {
    type State = AtomicResource<T>;
    type Param<'p> = ResMut<'p, T>;

    fn initialize(world: &mut World) {
        world.init_resource::<T>();
    }

    fn get_state(world: &World) -> Self::State {
        world.resource::<T>()
    }

    fn borrow(state: &mut Self::State) -> Self::Param<'_> {
        ResMut(state.borrow_mut())
    }
}

/// [`SystemParam`] for getting read access to a [`ComponentStore`].
pub type Comp<'a, T> = AtomicComponentStoreRef<'a, T>;
/// [`SystemParam`] for getting mutable access to a [`ComponentStore`].
pub type CompMut<'a, T> = AtomicComponentStoreRefMut<'a, T>;

impl<'a, T: TypedEcsData> SystemParam for Comp<'a, T> {
    type State = AtomicComponentStore<T>;
    type Param<'p> = Comp<'p, T>;

    fn initialize(world: &mut World) {
        world.components.init::<T>();
    }

    fn get_state(world: &World) -> Self::State {
        world.components.get::<T>()
    }

    fn borrow(state: &mut Self::State) -> Self::Param<'_> {
        state.borrow()
    }
}

impl<'a, T: TypedEcsData> SystemParam for CompMut<'a, T> {
    type State = AtomicComponentStore<T>;
    type Param<'p> = CompMut<'p, T>;

    fn initialize(world: &mut World) {
        world.components.init::<T>();
    }

    fn get_state(world: &World) -> Self::State {
        world.components.get::<T>()
    }

    fn borrow(state: &mut Self::State) -> Self::Param<'_> {
        state.borrow_mut()
    }
}

macro_rules! impl_system {
    ($($args:ident,)*) => {
        #[allow(unused_parens)]
        impl<
            F,
            Out,
            $(
                $args: SystemParam,
            )*
        > IntoSystem<(F, $($args,)*), Out> for F
        where for<'a> F: 'static + Send + Sync +
            FnMut(
                $(
                    <$args as SystemParam>::Param<'a>,
                )*
            ) -> SystemResult<Out> +
            FnMut(
                $(
                    $args,
                )*
            ) -> SystemResult<Out>
        {
            fn system(mut self) -> System<Out> {
                System {
                    name: std::any::type_name::<F>(),
                    initialize: Box::new(|_world| {
                        $(
                            $args::initialize(_world);
                        )*
                    }),
                    run: Box::new(move |_world| {
                        $(
                            #[allow(non_snake_case)]
                            let mut $args = $args::get_state(_world);
                        )*

                        self(
                            $(
                                $args::borrow(&mut $args),
                            )*
                        )
                    })
                }
            }
        }
    };
}

macro_rules! impl_system_with_empty_return {
    ($($args:ident,)*) => {
        #[allow(unused_parens)]
        impl<
            F,
            $(
                $args: SystemParam,
            )*
        > IntoSystem<(F, $($args,)* ()), ()> for F
        where for<'a> F: 'static + Send + Sync +
            FnMut(
                $(
                    <$args as SystemParam>::Param<'a>,
                )*
            ) +
            FnMut(
                $(
                    $args,
                )*
            )
        {
            fn system(mut self) -> System<()> {
                System {
                    name: std::any::type_name::<F>(),
                    initialize: Box::new(|_world| {
                        $(
                            $args::initialize(_world);
                        )*
                    }),
                    run: Box::new(move |_world| {
                        $(
                            #[allow(non_snake_case)]
                            let mut $args = $args::get_state(_world);
                        )*

                        self(
                            $(
                                $args::borrow(&mut $args),
                            )*
                        );

                        Ok(())
                    })
                }
            }
        }
    };
}

macro_rules! impl_systems {
    // base case
    () => {};
    ($head:ident, $($idents:ident,)*) => {
        // recursive call
        impl_system!($head, $($idents,)*);
        impl_system_with_empty_return!($head, $($idents,)*);
        impl_systems!($($idents,)*);
    }
}

impl_system!();
impl_system_with_empty_return!();
impl_systems!(A, B, C, D, E, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,);

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    #[test]
    fn convert_system() {
        fn tmp(
            _var1: AtomicComponentStoreRef<u32>,
            _var2: AtomicComponentStoreRef<u64>,
            _var3: Res<i32>,
            _var4: ResMut<i64>,
        ) -> SystemResult {
            Ok(())
        }
        // Technically reusing the same type is incorrect and causes a runtime panic.
        // However, there doesn't seem to be a clean way to handle type inequality in generics.
        #[allow(clippy::too_many_arguments)]
        fn tmp2(
            _var7: Comp<i64>,
            _var8: CompMut<i64>,
            _var1: Res<u32>,
            _var2: ResMut<u64>,
            _var3: Res<u32>,
            _var4: ResMut<u64>,
            _var5: Res<u32>,
            _var6: ResMut<u64>,
            _var9: Comp<i64>,
            _var10: CompMut<i64>,
            _var11: Comp<i64>,
            _var12: CompMut<u64>,
        ) -> SystemResult {
            Ok(())
        }
        let _ = tmp.system();
        let _ = tmp2.system();
    }

    #[test]
    fn system_is_send() {
        let x = 6;
        send(
            (move |_var1: Res<u32>| {
                let _y = x;
                Ok(())
            })
            .system(),
        );
        send((|| Ok(())).system());
        send(sys.system());
    }

    fn sys(_var1: Res<u32>) -> SystemResult {
        Ok(())
    }
    fn send<T: Send>(_t: T) {}

    #[test]
    fn manual_system_run() {
        let mut world = World::default();
        world.init_resource::<u32>();
    }

    #[test]
    fn system_replace_resource() {
        #[derive(Default, TypeUlid, Clone, PartialEq, Eq, Debug)]
        #[ulid = "01GNDP03R29SDA1S009KTQF18Y"]
        pub struct A;
        #[derive(Default, TypeUlid, Clone, Debug)]
        #[ulid = "01GNDP0C73TAV0TDKZZB39NQ8C"]
        pub struct B {
            x: u32,
        }
        let mut world = World::default();
        let mut my_system = (|_a: Res<A>, mut b: ResMut<B>| {
            let b2 = B { x: 45 };
            *b = b2;
            Ok(())
        })
        .system();

        assert!(world.resources.try_get::<B>().is_none());
        my_system.initialize(&mut world);

        let res = world.resource::<B>();
        assert_eq!(res.borrow().x, 0);

        my_system.run(&world).unwrap();

        let res = world.resource::<B>();
        assert_eq!(res.borrow().x, 45);

        let res = world.resource::<A>();
        assert_eq!(*res.borrow(), A);
    }
}