forked from Real-Serious-Games/Fluent-State-Machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractState.cs
286 lines (253 loc) · 9.34 KB
/
AbstractState.cs
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
using System;
using System.Collections.Generic;
namespace Azur.StateMachine
{
/// <summary>
/// State with a specified handler type.
/// </summary>
public abstract class AbstractState : IState
{
/// <summary>
/// Stack of active child states.
/// </summary>
private readonly Stack<IState> _activeChildren = new();
/// <summary>
/// Dictionary of all children (active and inactive), and their names.
/// </summary>
private readonly IDictionary<string, IState> _children = new Dictionary<string, IState>();
private readonly IList<Condition> _conditions = new List<Condition>();
/// <summary>
/// Dictionary of all actions associated with this state.
/// </summary>
private readonly IDictionary<string, Action<EventArgs>> _events = new Dictionary<string, Action<EventArgs>>();
/// <summary>
/// Action called when we enter the state.
/// </summary>
private Action _onEnter = delegate { };
/// <summary>
/// Action called when we exit the state.
/// </summary>
private Action _onExit = delegate { };
/// <summary>
/// Action called when the state gets updated.
/// </summary>
private Action<float> _onUpdate = delegate { };
/// <summary>
/// Parent state, or null if this is the root level state.
/// </summary>
public IState Parent { get; set; }
/// <summary>
/// Pops the current state from the stack and pushes the specified one on.
/// </summary>
public void ChangeState(string stateName)
{
// Try to find the specified state.
if (!_children.TryGetValue(stateName, out var newState))
{
throw new ApplicationException("Tried to change to state \"" + stateName + "\", but it is not in the list of children.");
}
// Exit and pop the current state
if (_activeChildren.Count > 0)
{
_activeChildren.Pop().Exit();
}
// Activate the new state
_activeChildren.Push(newState);
newState.Enter();
}
/// <summary>
/// Push another state from the existing dictionary of children to the top of the state stack.
/// </summary>
public void PushState(string stateName)
{
// Find the new state and add it
if (!_children.TryGetValue(stateName, out var newState))
{
throw new ApplicationException("Tried to change to state \"" + stateName + "\", but it is not in the list of children.");
}
_activeChildren.Push(newState);
newState.Enter();
}
/// <summary>
/// Remove the current state from the active state stack and activate the state immediately beneath it.
/// </summary>
public void PopState()
{
// Exit and pop the current state
if (_activeChildren.Count > 0)
{
_activeChildren.Pop().Exit();
}
else
{
throw new ApplicationException("PopState called on state with no active children to pop.");
}
}
/// <summary>
/// Update this state and its children with a specified delta time.
/// </summary>
public void Update(float deltaTime)
{
// Only update the child at the end of the tree
if (_activeChildren.Count > 0)
{
_activeChildren.Peek().Update(deltaTime);
return;
}
_onUpdate.Invoke(deltaTime);
for (int i = 0, max = _conditions.Count; i < max; i++)
{
if (_conditions[i].Predicate())
{
_conditions[i].Action();
}
}
}
/// <summary>
/// Triggered when we enter the state.
/// </summary>
public void Enter()
{
_onEnter.Invoke();
}
/// <summary>
/// Triggered when we exit the state.
/// </summary>
public void Exit()
{
_onExit.Invoke();
while (_activeChildren.Count > 0)
{
_activeChildren.Pop().Exit();
}
}
/// <summary>
/// Triggered when and event occurs. Executes the event's action if the
/// current state is at the top of the stack, otherwise triggers it on
/// the next state down.
/// </summary>
/// <param name="name">Name of the event to trigger</param>
public void TriggerEvent(string name)
{
TriggerEvent(name, EventArgs.Empty);
}
/// <summary>
/// Triggered when and event occurs. Executes the event's action if the
/// current state is at the top of the stack, otherwise triggers it on
/// the next state down.
/// </summary>
/// <param name="name">Name of the event to trigger</param>
/// <param name="eventArgs">Arguments to send to the event</param>
public void TriggerEvent(string name, EventArgs eventArgs)
{
// Only update the child at the end of the tree
if (_activeChildren.Count > 0)
{
_activeChildren.Peek().TriggerEvent(name, eventArgs);
return;
}
if (_events.TryGetValue(name, out var myEvent))
{
myEvent(eventArgs);
}
}
/// <summary>
/// Create a new state as a child of the current state.
/// </summary>
public void AddChild(IState newState, string stateName)
{
try
{
_children.Add(stateName, newState);
newState.Parent = this;
}
catch (ArgumentException)
{
throw new ApplicationException("State with name \"" + stateName + "\" already exists in list of children.");
}
}
/// <summary>
/// Create a new state as a child of the current state and automatically derive
/// its name from its handler type.
/// </summary>
public void AddChild(IState newState)
{
AddChild(newState, newState.GetType().Name);
}
/// <summary>
/// Set an action to be called when the state is updated an a specified
/// predicate is true.
/// </summary>
public void SetCondition(Func<bool> predicate, Action action)
{
_conditions.Add(new Condition
{
Predicate = predicate,
Action = action
});
}
/// <summary>
/// Action triggered on entering the state.
/// </summary>
public void SetEnterAction(Action onEnter)
{
_onEnter = onEnter;
}
/// <summary>
/// Action triggered on exiting the state.
/// </summary>
public void SetExitAction(Action onExit)
{
_onExit = onExit;
}
/// <summary>
/// Action which passes the current state object and the delta time since the
/// last update to a function.
/// </summary>
public void SetUpdateAction(Action<float> onUpdate)
{
_onUpdate = onUpdate;
}
/// <summary>
/// Sets an action to be associated with an identifier that can later be used
/// to trigger it.
/// Convenience method that uses default event args intended for events that
/// don't need any arguments.
/// </summary>
public void SetEvent(string identifier, Action<EventArgs> eventTriggeredAction)
{
SetEvent<EventArgs>(identifier, eventTriggeredAction);
}
/// <summary>
/// Sets an action to be associated with an identifier that can later be used
/// to trigger it.
/// </summary>
public void SetEvent<TEvent>(string identifier, Action<TEvent> eventTriggeredAction) where TEvent : EventArgs
{
_events.Add(identifier, args => eventTriggeredAction(CheckEventArgs<TEvent>(identifier, args)));
}
/// <summary>
/// Cast the specified EventArgs to a specified type, throwing a descriptive exception if this fails.
/// </summary>
private static TEvent CheckEventArgs<TEvent>(string identifier, EventArgs args) where TEvent : EventArgs
{
try
{
return (TEvent)args;
}
catch (InvalidCastException ex)
{
throw new ApplicationException("Could not invoke event \"" + identifier + "\" with argument of type " +
args.GetType().Name + ". Expected " + typeof(TEvent).Name, ex);
}
}
/// <summary>
/// Data structure for associating a condition with an action.
/// </summary>
private struct Condition
{
public Func<bool> Predicate;
public Action Action;
}
}
}