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
use bevy_ecs::{
    event::{EventReader, EventWriter},
    schedule::{IntoSystemConfigs, IntoSystemSetConfigs, Schedule},
    system::{Commands, IntoSystem, Res, ResMut},
};
use bevy_utils::all_tuples;

use self::sealed::StateSetSealed;

use super::{
    computed_states::ComputedStates, internal_apply_state_transition, last_transition, run_enter,
    run_exit, run_transition, sub_states::SubStates, take_next_state, ApplyStateTransition,
    EnterSchedules, ExitSchedules, NextState, State, StateTransitionEvent, StateTransitionSteps,
    States, TransitionSchedules,
};

mod sealed {
    /// Sealed trait used to prevent external implementations of [`StateSet`](super::StateSet).
    pub trait StateSetSealed {}
}

/// A [`States`] type or tuple of types which implement [`States`].
///
/// This trait is used allow implementors of [`States`], as well
/// as tuples containing exclusively implementors of [`States`], to
/// be used as [`ComputedStates::SourceStates`].
///
/// It is sealed, and auto implemented for all [`States`] types and
/// tuples containing them.
pub trait StateSet: sealed::StateSetSealed {
    /// The total [`DEPENDENCY_DEPTH`](`States::DEPENDENCY_DEPTH`) of all
    /// the states that are part of this [`StateSet`], added together.
    ///
    /// Used to de-duplicate computed state executions and prevent cyclic
    /// computed states.
    const SET_DEPENDENCY_DEPTH: usize;

    /// Sets up the systems needed to compute `T` whenever any `State` in this
    /// `StateSet` is changed.
    fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
        schedule: &mut Schedule,
    );

    /// Sets up the systems needed to compute whether `T` exists whenever any `State` in this
    /// `StateSet` is changed.
    fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
        schedule: &mut Schedule,
    );
}

/// The `InnerStateSet` trait is used to isolate [`ComputedStates`] & [`SubStates`] from
/// needing to wrap all state dependencies in an [`Option<S>`].
///
/// Some [`ComputedStates`]'s might need to exist in different states based on the existence
/// of other states. So we needed the ability to use[`Option<S>`] when appropriate.
///
/// The isolation works because it is implemented for both S & [`Option<S>`], and has the `RawState` associated type
/// that allows it to know what the resource in the world should be. We can then essentially "unwrap" it in our
/// `StateSet` implementation - and the behaviour of that unwrapping will depend on the arguments expected by the
/// the [`ComputedStates`] & [`SubStates]`.
trait InnerStateSet: Sized {
    type RawState: States;

    const DEPENDENCY_DEPTH: usize;

    fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self>;
}

impl<S: States> InnerStateSet for S {
    type RawState = Self;

    const DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;

    fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self> {
        wrapped.map(|v| v.0.clone())
    }
}

impl<S: States> InnerStateSet for Option<S> {
    type RawState = S;

    const DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;

    fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self> {
        Some(wrapped.map(|v| v.0.clone()))
    }
}

impl<S: InnerStateSet> StateSetSealed for S {}

impl<S: InnerStateSet> StateSet for S {
    const SET_DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;

    fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
        schedule: &mut Schedule,
    ) {
        let apply_state_transition =
            |mut parent_changed: EventReader<StateTransitionEvent<S::RawState>>,
             event: EventWriter<StateTransitionEvent<T>>,
             commands: Commands,
             current_state: Option<ResMut<State<T>>>,
             state_set: Option<Res<State<S::RawState>>>| {
                if parent_changed.is_empty() {
                    return;
                }
                parent_changed.clear();

                let new_state =
                    if let Some(state_set) = S::convert_to_usable_state(state_set.as_deref()) {
                        T::compute(state_set)
                    } else {
                        None
                    };

                internal_apply_state_transition(event, commands, current_state, new_state);
            };

        schedule.configure_sets((
            ApplyStateTransition::<T>::default()
                .in_set(StateTransitionSteps::DependentTransitions)
                .after(ApplyStateTransition::<S::RawState>::default()),
            ExitSchedules::<T>::default()
                .in_set(StateTransitionSteps::ExitSchedules)
                .before(ExitSchedules::<S::RawState>::default()),
            TransitionSchedules::<T>::default().in_set(StateTransitionSteps::TransitionSchedules),
            EnterSchedules::<T>::default()
                .in_set(StateTransitionSteps::EnterSchedules)
                .after(EnterSchedules::<S::RawState>::default()),
        ));

        schedule
            .add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
            .add_systems(
                last_transition::<T>
                    .pipe(run_exit::<T>)
                    .in_set(ExitSchedules::<T>::default()),
            )
            .add_systems(
                last_transition::<T>
                    .pipe(run_transition::<T>)
                    .in_set(TransitionSchedules::<T>::default()),
            )
            .add_systems(
                last_transition::<T>
                    .pipe(run_enter::<T>)
                    .in_set(EnterSchedules::<T>::default()),
            );
    }

    fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
        schedule: &mut Schedule,
    ) {
        // | parent changed | next state | already exists | should exist | what happens                     |
        // | -------------- | ---------- | -------------- | ------------ | -------------------------------- |
        // | false          | false      | false          | -            | -                                |
        // | false          | false      | true           | -            | -                                |
        // | false          | true       | false          | false        | -                                |
        // | true           | false      | false          | false        | -                                |
        // | true           | true       | false          | false        | -                                |
        // | true           | false      | true           | false        | Some(current) -> None            |
        // | true           | true       | true           | false        | Some(current) -> None            |
        // | true           | false      | false          | true         | None -> Some(default)            |
        // | true           | true       | false          | true         | None -> Some(next)               |
        // | true           | true       | true           | true         | Some(current) -> Some(next)      |
        // | false          | true       | true           | true         | Some(current) -> Some(next)      |
        // | true           | false      | true           | true         | Some(current) -> Some(current)   |

        let apply_state_transition =
            |mut parent_changed: EventReader<StateTransitionEvent<S::RawState>>,
             event: EventWriter<StateTransitionEvent<T>>,
             commands: Commands,
             current_state_res: Option<ResMut<State<T>>>,
             next_state_res: Option<ResMut<NextState<T>>>,
             state_set: Option<Res<State<S::RawState>>>| {
                let parent_changed = parent_changed.read().last().is_some();
                let next_state = take_next_state(next_state_res);

                if !parent_changed && next_state.is_none() {
                    return;
                }

                let current_state = current_state_res.as_ref().map(|s| s.get()).cloned();

                let initial_state = if parent_changed {
                    if let Some(state_set) = S::convert_to_usable_state(state_set.as_deref()) {
                        T::should_exist(state_set)
                    } else {
                        None
                    }
                } else {
                    current_state.clone()
                };
                let new_state = initial_state.map(|x| next_state.or(current_state).unwrap_or(x));

                internal_apply_state_transition(event, commands, current_state_res, new_state);
            };

        schedule.configure_sets((
            ApplyStateTransition::<T>::default()
                .in_set(StateTransitionSteps::DependentTransitions)
                .after(ApplyStateTransition::<S::RawState>::default()),
            ExitSchedules::<T>::default()
                .in_set(StateTransitionSteps::ExitSchedules)
                .before(ExitSchedules::<S::RawState>::default()),
            TransitionSchedules::<T>::default().in_set(StateTransitionSteps::TransitionSchedules),
            EnterSchedules::<T>::default()
                .in_set(StateTransitionSteps::EnterSchedules)
                .after(EnterSchedules::<S::RawState>::default()),
        ));

        schedule
            .add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
            .add_systems(
                last_transition::<T>
                    .pipe(run_exit::<T>)
                    .in_set(ExitSchedules::<T>::default()),
            )
            .add_systems(
                last_transition::<T>
                    .pipe(run_transition::<T>)
                    .in_set(TransitionSchedules::<T>::default()),
            )
            .add_systems(
                last_transition::<T>
                    .pipe(run_enter::<T>)
                    .in_set(EnterSchedules::<T>::default()),
            );
    }
}

macro_rules! impl_state_set_sealed_tuples {
    ($(($param: ident, $val: ident, $evt: ident)), *) => {
        impl<$($param: InnerStateSet),*> StateSetSealed for  ($($param,)*) {}

        impl<$($param: InnerStateSet),*> StateSet for  ($($param,)*) {

            const SET_DEPENDENCY_DEPTH : usize = $($param::DEPENDENCY_DEPTH +)* 0;


            fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
                schedule: &mut Schedule,
            ) {
                let apply_state_transition =
                    |($(mut $evt),*,): ($(EventReader<StateTransitionEvent<$param::RawState>>),*,),
                     event: EventWriter<StateTransitionEvent<T>>,
                     commands: Commands,
                     current_state: Option<ResMut<State<T>>>,
                     ($($val),*,): ($(Option<Res<State<$param::RawState>>>),*,)| {
                        if ($($evt.is_empty())&&*) {
                            return;
                        }
                        $($evt.clear();)*

                        let new_state = if let ($(Some($val)),*,) = ($($param::convert_to_usable_state($val.as_deref())),*,) {
                            T::compute(($($val),*, ))
                        } else {
                            None
                        };

                        internal_apply_state_transition(event, commands, current_state, new_state);
                    };

                schedule.configure_sets((
                    ApplyStateTransition::<T>::default()
                        .in_set(StateTransitionSteps::DependentTransitions)
                        $(.after(ApplyStateTransition::<$param::RawState>::default()))*,
                    ExitSchedules::<T>::default()
                        .in_set(StateTransitionSteps::ExitSchedules)
                        $(.before(ExitSchedules::<$param::RawState>::default()))*,
                    TransitionSchedules::<T>::default()
                        .in_set(StateTransitionSteps::TransitionSchedules),
                    EnterSchedules::<T>::default()
                        .in_set(StateTransitionSteps::EnterSchedules)
                        $(.after(EnterSchedules::<$param::RawState>::default()))*,
                ));

                schedule
                    .add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_exit::<T>).in_set(ExitSchedules::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_transition::<T>).in_set(TransitionSchedules::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_enter::<T>).in_set(EnterSchedules::<T>::default()));
            }

            fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
                schedule: &mut Schedule,
            ) {
                let apply_state_transition =
                    |($(mut $evt),*,): ($(EventReader<StateTransitionEvent<$param::RawState>>),*,),
                     event: EventWriter<StateTransitionEvent<T>>,
                     commands: Commands,
                     current_state_res: Option<ResMut<State<T>>>,
                     next_state_res: Option<ResMut<NextState<T>>>,
                     ($($val),*,): ($(Option<Res<State<$param::RawState>>>),*,)| {
                        let parent_changed = ($($evt.read().last().is_some())&&*);
                        let next_state = take_next_state(next_state_res);

                        if !parent_changed && next_state.is_none() {
                            return;
                        }

                        let current_state = current_state_res.as_ref().map(|s| s.get()).cloned();

                        let initial_state = if parent_changed {
                            if let ($(Some($val)),*,) = ($($param::convert_to_usable_state($val.as_deref())),*,) {
                                T::should_exist(($($val),*, ))
                            } else {
                                None
                            }
                        } else {
                            current_state.clone()
                        };
                        let new_state = initial_state.map(|x| next_state.or(current_state).unwrap_or(x));

                        internal_apply_state_transition(event, commands, current_state_res, new_state);
                    };

                schedule.configure_sets((
                    ApplyStateTransition::<T>::default()
                        .in_set(StateTransitionSteps::DependentTransitions)
                        $(.after(ApplyStateTransition::<$param::RawState>::default()))*,
                    ExitSchedules::<T>::default()
                        .in_set(StateTransitionSteps::ExitSchedules)
                        $(.before(ExitSchedules::<$param::RawState>::default()))*,
                    TransitionSchedules::<T>::default()
                        .in_set(StateTransitionSteps::TransitionSchedules),
                    EnterSchedules::<T>::default()
                        .in_set(StateTransitionSteps::EnterSchedules)
                        $(.after(EnterSchedules::<$param::RawState>::default()))*,
                ));

                schedule
                    .add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_exit::<T>).in_set(ExitSchedules::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_transition::<T>).in_set(TransitionSchedules::<T>::default()))
                    .add_systems(last_transition::<T>.pipe(run_enter::<T>).in_set(EnterSchedules::<T>::default()));
            }
        }
    };
}

all_tuples!(impl_state_set_sealed_tuples, 1, 15, S, s, ereader);