summaryrefslogtreecommitdiff
path: root/ecs/src/system/stateful.rs
blob: 5eae1dafd9bc3976f40a8522b1a01f86fa39fa6d (plain)
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
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::panic::{RefUnwindSafe, UnwindSafe};

use seq_macro::seq;

use crate::component::Component;
use crate::lock::Lock;
use crate::system::{
    ComponentRefMut,
    Into as IntoSystem,
    Param,
    ParamWithInputFilter,
    System,
    TypeErased,
};
use crate::tuple::{
    Reduce as TupleReduce,
    Tuple,
    WithAllElemLtStatic as TupleWithAllElemLtStatic,
};
use crate::uid::Uid;
use crate::World;

/// A stateful system.
pub struct Stateful<Func>
{
    func: Func,
    local_components: HashMap<Uid, Lock<Box<dyn Component>>>,
}

macro_rules! impl_system {
    ($c: tt) => {
        seq!(I in 0..$c {
            impl<'world, Func, #(TParam~I,)*> System<'world, fn(&'world (), #(TParam~I,)*)>
                for Stateful<Func>
            where
                Func: Fn(#(TParam~I,)*) + Copy + RefUnwindSafe + UnwindSafe + 'static,
                #(TParam~I: Param<'world>,)*
                #(TParam~I::Input: 'static,)*
                (#(TParam~I::Input,)*): TupleReduce<
                    ParamWithInputFilter,
                    Out: Tuple<InOptions: TupleWithAllElemLtStatic>
                >,
            {
                type Input =
                    <(#(TParam~I::Input,)*) as TupleReduce<ParamWithInputFilter>>::Out;

                fn initialize(mut self, input: Self::Input) -> Self
                {
                    let mut option_input = input.into_in_options();

                    let mut index = 0;

                    #(
                        if TypeId::of::<TParam~I::Input>() !=
                            TypeId::of::<()>()
                        {
                            let input = option_input
                                .get_mut::<Option<TParam~I::Input>>(index)
                                .expect("Input element index out of range")
                                .take()
                                .expect("Input element is already taken");

                            TParam~I::initialize(
                                &mut self,
                                input
                            );

                            #[allow(unused_assignments)]
                            {
                                index += 1;
                            }
                        }
                    )*

                    self
                }

                fn run<'this>(&'this self, world: &'world World)
                where
                    'this: 'world
                {
                    let func = self.func;

                    func(#({
                        TParam~I::new(self, &world)
                    },)*);
                }

                fn into_type_erased(self) -> TypeErased
                {
                    TypeErased {
                        data: Box::new(self),
                        run: Box::new(|data, world| {
                            // SAFETY: The caller of TypeErased::run ensures the lifetime
                            // is correct
                            let data = unsafe { &*std::ptr::from_ref::<dyn Any>(data) };

                            let me = data.downcast_ref::<Self>().unwrap();

                            // SAFETY: The caller of TypeErased::run ensures the lifetime
                            // is correct
                            let world = unsafe { &*std::ptr::from_ref(world) };

                            me.run(world);
                        }),
                    }
                }

                fn get_local_component_mut<LocalComponent: Component>(
                    &self,
                ) -> Option<ComponentRefMut<LocalComponent>>
                {
                    let local_component = self.local_components
                        .get(&LocalComponent::id())?
                        .write_nonblock()
                        .expect("Failed to aquire read-write local component lock");

                    Some(ComponentRefMut::new(local_component))
                }

                fn set_local_component<LocalComponent: Component>(
                    &mut self,
                    local_component: LocalComponent,
                )
                {
                    self.local_components
                        .insert(
                            LocalComponent::id(),
                            Lock::new(Box::new(local_component))
                        );
                }
            }

            impl<Func, #(TParam~I,)*> IntoSystem<fn(#(TParam~I,)*)>
                for Func
            where
                Func: Fn(#(TParam~I,)*) + Copy + 'static,
            {
                type System = Stateful<Func>;

                fn into_system(self) -> Self::System
                {
                    Self::System {
                        func: self,
                        local_components: HashMap::new(),
                    }
                }
            }
        });
    };
}

seq!(C in 1..16 {
    impl_system!(C);
});