-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstate.rs
208 lines (165 loc) · 5.58 KB
/
state.rs
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
use std::{
fmt::{self, Debug, Formatter},
marker::PhantomData,
};
use crate::prelude::*;
use self::sealed::EntityStateSealed;
mod sealed {
use std::{any::TypeId, marker::PhantomData};
use variadics_please::all_tuples;
use super::AnyState;
use crate::prelude::*;
pub trait EntityStateSealed: Sized {
fn matches(state: TypeId) -> bool;
fn remove(entity: Entity, world: &mut World, curr: TypeId) -> Self;
}
impl<T: Clone + Component> EntityStateSealed for T {
fn matches(state: TypeId) -> bool {
state == TypeId::of::<T>()
}
fn remove(entity: Entity, world: &mut World, _: TypeId) -> Self {
world.entity_mut(entity).take::<Self>().unwrap()
}
}
impl<T: EntityState> EntityStateSealed for NotState<T> {
fn matches(state: TypeId) -> bool {
!T::matches(state)
}
fn remove(entity: Entity, world: &mut World, curr: TypeId) -> Self {
let curr = world.components().get_id(curr).unwrap();
world.entity_mut(entity).remove_by_id(curr);
Self(PhantomData)
}
}
macro_rules! impl_entity_state_sealed {
($($T:ident),*) => {
#[allow(unused)]
impl<$($T: EntityState),*> EntityStateSealed for OneOfState<($($T,)*)> {
fn matches(state: TypeId) -> bool {
$($T::matches(state) ||)* false
}
fn remove(entity: Entity, world: &mut World, curr: TypeId) -> Self {
$(
if $T::matches(curr) {
$T::remove(entity, world, curr);
}
)*
Self(PhantomData)
}
}
};
}
all_tuples!(impl_entity_state_sealed, 0, 15, T);
impl EntityStateSealed for AnyState {
fn matches(_: TypeId) -> bool {
true
}
fn remove(entity: Entity, world: &mut World, curr: TypeId) -> Self {
let curr = world.components().get_id(curr).unwrap();
world.entity_mut(entity).remove_by_id(curr);
AnyState(())
}
}
}
/// A state that an entity may be in.
///
/// If you are concerned with performance, consider having your states use sparse set storage if
/// transitions are very frequent.
pub trait EntityState: 'static + Clone + Send + Sync + EntityStateSealed {}
impl<T: Clone + Component> EntityState for T {}
/// State that represents any state other than the given state
pub struct NotState<T>(PhantomData<T>);
impl<T> Clone for NotState<T> {
fn clone(&self) -> Self {
Self(PhantomData)
}
}
impl<T: EntityState> EntityState for NotState<T> {}
/// State that represents any of the states given in a tuple (ex
/// `OneOfState<(Idle, Jump, Attack)>`).
#[derive(Debug)]
pub struct OneOfState<T>(PhantomData<T>);
impl<T> Clone for OneOfState<T> {
fn clone(&self) -> Self {
Self(PhantomData)
}
}
impl<T: 'static + Send + Sync> EntityState for OneOfState<T> where Self: EntityStateSealed {}
/// State that represents any state. Transitions from [`AnyState`] may transition from any other
/// state.
#[derive(Clone, Debug)]
pub struct AnyState(());
impl EntityState for AnyState {}
#[derive(Debug)]
pub(crate) enum OnEvent {
Entity(Box<dyn EntityEvent>),
Command(Box<dyn CommandEvent>),
}
impl OnEvent {
pub(crate) fn trigger(&self, entity: Entity, commands: &mut Commands) {
match self {
OnEvent::Entity(event) => event.trigger(&mut commands.entity(entity)),
OnEvent::Command(event) => event.trigger(commands),
}
}
}
pub(crate) trait EntityEvent: Send + Sync {
fn trigger(&self, entity: &mut EntityCommands);
}
impl Debug for dyn EntityEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Fn(&mut EntityCommands)")
}
}
impl<F: Fn(&mut EntityCommands) + Send + Sync> EntityEvent for F {
fn trigger(&self, entity: &mut EntityCommands) {
self(entity)
}
}
pub(crate) trait CommandEvent: Command + Sync {
fn trigger(&self, commands: &mut Commands);
}
impl Debug for dyn CommandEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Command")
}
}
impl<C: Clone + Command + Sync> CommandEvent for C {
fn trigger(&self, commands: &mut Commands) {
commands.queue(self.clone())
}
}
#[cfg(test)]
mod tests {
use crate::machine::transition;
use super::*;
#[derive(Component, Clone)]
struct StateOne;
#[derive(Component, Clone)]
struct StateTwo;
#[derive(Resource, Clone)]
struct SomeResource;
#[derive(Resource, Clone)]
struct AnotherResource;
#[test]
fn test_triggers() {
let mut app = App::new();
app.add_systems(Update, transition);
let machine = StateMachine::default()
.trans::<StateOne, _>(always, StateTwo)
.on_exit::<StateOne>(|commands| commands.commands().insert_resource(SomeResource))
.on_enter::<StateTwo>(|commands| commands.commands().insert_resource(AnotherResource));
let entity = app.world_mut().spawn((machine, StateOne)).id();
assert!(app.world().get::<StateOne>(entity).is_some());
app.update();
assert!(app.world().get::<StateTwo>(entity).is_some());
assert!(
app.world().contains_resource::<SomeResource>(),
"exit state triggers should run"
);
assert!(
app.world().contains_resource::<AnotherResource>(),
"exit state triggers should run"
);
}
}